]> asedeno.scripts.mit.edu Git - linux.git/blob - mm/mmap.c
mm/mmap.c: remove a never-triggered warning in __vma_adjust()
[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         brk = untagged_addr(brk);
205
206         if (down_write_killable(&mm->mmap_sem))
207                 return -EINTR;
208
209         origbrk = mm->brk;
210
211 #ifdef CONFIG_COMPAT_BRK
212         /*
213          * CONFIG_COMPAT_BRK can still be overridden by setting
214          * randomize_va_space to 2, which will still cause mm->start_brk
215          * to be arbitrarily shifted
216          */
217         if (current->brk_randomized)
218                 min_brk = mm->start_brk;
219         else
220                 min_brk = mm->end_data;
221 #else
222         min_brk = mm->start_brk;
223 #endif
224         if (brk < min_brk)
225                 goto out;
226
227         /*
228          * Check against rlimit here. If this check is done later after the test
229          * of oldbrk with newbrk then it can escape the test and let the data
230          * segment grow beyond its set limit the in case where the limit is
231          * not page aligned -Ram Gupta
232          */
233         if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
234                               mm->end_data, mm->start_data))
235                 goto out;
236
237         newbrk = PAGE_ALIGN(brk);
238         oldbrk = PAGE_ALIGN(mm->brk);
239         if (oldbrk == newbrk) {
240                 mm->brk = brk;
241                 goto success;
242         }
243
244         /*
245          * Always allow shrinking brk.
246          * __do_munmap() may downgrade mmap_sem to read.
247          */
248         if (brk <= mm->brk) {
249                 int ret;
250
251                 /*
252                  * mm->brk must to be protected by write mmap_sem so update it
253                  * before downgrading mmap_sem. When __do_munmap() fails,
254                  * mm->brk will be restored from origbrk.
255                  */
256                 mm->brk = brk;
257                 ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true);
258                 if (ret < 0) {
259                         mm->brk = origbrk;
260                         goto out;
261                 } else if (ret == 1) {
262                         downgraded = true;
263                 }
264                 goto success;
265         }
266
267         /* Check against existing mmap mappings. */
268         next = find_vma(mm, oldbrk);
269         if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
270                 goto out;
271
272         /* Ok, looks good - let it rip. */
273         if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0)
274                 goto out;
275         mm->brk = brk;
276
277 success:
278         populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
279         if (downgraded)
280                 up_read(&mm->mmap_sem);
281         else
282                 up_write(&mm->mmap_sem);
283         userfaultfd_unmap_complete(mm, &uf);
284         if (populate)
285                 mm_populate(oldbrk, newbrk - oldbrk);
286         return brk;
287
288 out:
289         retval = origbrk;
290         up_write(&mm->mmap_sem);
291         return retval;
292 }
293
294 static inline unsigned long vma_compute_gap(struct vm_area_struct *vma)
295 {
296         unsigned long gap, prev_end;
297
298         /*
299          * Note: in the rare case of a VM_GROWSDOWN above a VM_GROWSUP, we
300          * allow two stack_guard_gaps between them here, and when choosing
301          * an unmapped area; whereas when expanding we only require one.
302          * That's a little inconsistent, but keeps the code here simpler.
303          */
304         gap = vm_start_gap(vma);
305         if (vma->vm_prev) {
306                 prev_end = vm_end_gap(vma->vm_prev);
307                 if (gap > prev_end)
308                         gap -= prev_end;
309                 else
310                         gap = 0;
311         }
312         return gap;
313 }
314
315 #ifdef CONFIG_DEBUG_VM_RB
316 static unsigned long vma_compute_subtree_gap(struct vm_area_struct *vma)
317 {
318         unsigned long max = vma_compute_gap(vma), subtree_gap;
319         if (vma->vm_rb.rb_left) {
320                 subtree_gap = rb_entry(vma->vm_rb.rb_left,
321                                 struct vm_area_struct, vm_rb)->rb_subtree_gap;
322                 if (subtree_gap > max)
323                         max = subtree_gap;
324         }
325         if (vma->vm_rb.rb_right) {
326                 subtree_gap = rb_entry(vma->vm_rb.rb_right,
327                                 struct vm_area_struct, vm_rb)->rb_subtree_gap;
328                 if (subtree_gap > max)
329                         max = subtree_gap;
330         }
331         return max;
332 }
333
334 static int browse_rb(struct mm_struct *mm)
335 {
336         struct rb_root *root = &mm->mm_rb;
337         int i = 0, j, bug = 0;
338         struct rb_node *nd, *pn = NULL;
339         unsigned long prev = 0, pend = 0;
340
341         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
342                 struct vm_area_struct *vma;
343                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
344                 if (vma->vm_start < prev) {
345                         pr_emerg("vm_start %lx < prev %lx\n",
346                                   vma->vm_start, prev);
347                         bug = 1;
348                 }
349                 if (vma->vm_start < pend) {
350                         pr_emerg("vm_start %lx < pend %lx\n",
351                                   vma->vm_start, pend);
352                         bug = 1;
353                 }
354                 if (vma->vm_start > vma->vm_end) {
355                         pr_emerg("vm_start %lx > vm_end %lx\n",
356                                   vma->vm_start, vma->vm_end);
357                         bug = 1;
358                 }
359                 spin_lock(&mm->page_table_lock);
360                 if (vma->rb_subtree_gap != vma_compute_subtree_gap(vma)) {
361                         pr_emerg("free gap %lx, correct %lx\n",
362                                vma->rb_subtree_gap,
363                                vma_compute_subtree_gap(vma));
364                         bug = 1;
365                 }
366                 spin_unlock(&mm->page_table_lock);
367                 i++;
368                 pn = nd;
369                 prev = vma->vm_start;
370                 pend = vma->vm_end;
371         }
372         j = 0;
373         for (nd = pn; nd; nd = rb_prev(nd))
374                 j++;
375         if (i != j) {
376                 pr_emerg("backwards %d, forwards %d\n", j, i);
377                 bug = 1;
378         }
379         return bug ? -1 : i;
380 }
381
382 static void validate_mm_rb(struct rb_root *root, struct vm_area_struct *ignore)
383 {
384         struct rb_node *nd;
385
386         for (nd = rb_first(root); nd; nd = rb_next(nd)) {
387                 struct vm_area_struct *vma;
388                 vma = rb_entry(nd, struct vm_area_struct, vm_rb);
389                 VM_BUG_ON_VMA(vma != ignore &&
390                         vma->rb_subtree_gap != vma_compute_subtree_gap(vma),
391                         vma);
392         }
393 }
394
395 static void validate_mm(struct mm_struct *mm)
396 {
397         int bug = 0;
398         int i = 0;
399         unsigned long highest_address = 0;
400         struct vm_area_struct *vma = mm->mmap;
401
402         while (vma) {
403                 struct anon_vma *anon_vma = vma->anon_vma;
404                 struct anon_vma_chain *avc;
405
406                 if (anon_vma) {
407                         anon_vma_lock_read(anon_vma);
408                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
409                                 anon_vma_interval_tree_verify(avc);
410                         anon_vma_unlock_read(anon_vma);
411                 }
412
413                 highest_address = vm_end_gap(vma);
414                 vma = vma->vm_next;
415                 i++;
416         }
417         if (i != mm->map_count) {
418                 pr_emerg("map_count %d vm_next %d\n", mm->map_count, i);
419                 bug = 1;
420         }
421         if (highest_address != mm->highest_vm_end) {
422                 pr_emerg("mm->highest_vm_end %lx, found %lx\n",
423                           mm->highest_vm_end, highest_address);
424                 bug = 1;
425         }
426         i = browse_rb(mm);
427         if (i != mm->map_count) {
428                 if (i != -1)
429                         pr_emerg("map_count %d rb %d\n", mm->map_count, i);
430                 bug = 1;
431         }
432         VM_BUG_ON_MM(bug, mm);
433 }
434 #else
435 #define validate_mm_rb(root, ignore) do { } while (0)
436 #define validate_mm(mm) do { } while (0)
437 #endif
438
439 RB_DECLARE_CALLBACKS_MAX(static, vma_gap_callbacks,
440                          struct vm_area_struct, vm_rb,
441                          unsigned long, rb_subtree_gap, vma_compute_gap)
442
443 /*
444  * Update augmented rbtree rb_subtree_gap values after vma->vm_start or
445  * vma->vm_prev->vm_end values changed, without modifying the vma's position
446  * in the rbtree.
447  */
448 static void vma_gap_update(struct vm_area_struct *vma)
449 {
450         /*
451          * As it turns out, RB_DECLARE_CALLBACKS_MAX() already created
452          * a callback function that does exactly what we want.
453          */
454         vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
455 }
456
457 static inline void vma_rb_insert(struct vm_area_struct *vma,
458                                  struct rb_root *root)
459 {
460         /* All rb_subtree_gap values must be consistent prior to insertion */
461         validate_mm_rb(root, NULL);
462
463         rb_insert_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
464 }
465
466 static void __vma_rb_erase(struct vm_area_struct *vma, struct rb_root *root)
467 {
468         /*
469          * Note rb_erase_augmented is a fairly large inline function,
470          * so make sure we instantiate it only once with our desired
471          * augmented rbtree callbacks.
472          */
473         rb_erase_augmented(&vma->vm_rb, root, &vma_gap_callbacks);
474 }
475
476 static __always_inline void vma_rb_erase_ignore(struct vm_area_struct *vma,
477                                                 struct rb_root *root,
478                                                 struct vm_area_struct *ignore)
479 {
480         /*
481          * All rb_subtree_gap values must be consistent prior to erase,
482          * with the possible exception of the "next" vma being erased if
483          * next->vm_start was reduced.
484          */
485         validate_mm_rb(root, ignore);
486
487         __vma_rb_erase(vma, root);
488 }
489
490 static __always_inline void vma_rb_erase(struct vm_area_struct *vma,
491                                          struct rb_root *root)
492 {
493         /*
494          * All rb_subtree_gap values must be consistent prior to erase,
495          * with the possible exception of the vma being erased.
496          */
497         validate_mm_rb(root, vma);
498
499         __vma_rb_erase(vma, root);
500 }
501
502 /*
503  * vma has some anon_vma assigned, and is already inserted on that
504  * anon_vma's interval trees.
505  *
506  * Before updating the vma's vm_start / vm_end / vm_pgoff fields, the
507  * vma must be removed from the anon_vma's interval trees using
508  * anon_vma_interval_tree_pre_update_vma().
509  *
510  * After the update, the vma will be reinserted using
511  * anon_vma_interval_tree_post_update_vma().
512  *
513  * The entire update must be protected by exclusive mmap_sem and by
514  * the root anon_vma's mutex.
515  */
516 static inline void
517 anon_vma_interval_tree_pre_update_vma(struct vm_area_struct *vma)
518 {
519         struct anon_vma_chain *avc;
520
521         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
522                 anon_vma_interval_tree_remove(avc, &avc->anon_vma->rb_root);
523 }
524
525 static inline void
526 anon_vma_interval_tree_post_update_vma(struct vm_area_struct *vma)
527 {
528         struct anon_vma_chain *avc;
529
530         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
531                 anon_vma_interval_tree_insert(avc, &avc->anon_vma->rb_root);
532 }
533
534 static int find_vma_links(struct mm_struct *mm, unsigned long addr,
535                 unsigned long end, struct vm_area_struct **pprev,
536                 struct rb_node ***rb_link, struct rb_node **rb_parent)
537 {
538         struct rb_node **__rb_link, *__rb_parent, *rb_prev;
539
540         __rb_link = &mm->mm_rb.rb_node;
541         rb_prev = __rb_parent = NULL;
542
543         while (*__rb_link) {
544                 struct vm_area_struct *vma_tmp;
545
546                 __rb_parent = *__rb_link;
547                 vma_tmp = rb_entry(__rb_parent, struct vm_area_struct, vm_rb);
548
549                 if (vma_tmp->vm_end > addr) {
550                         /* Fail if an existing vma overlaps the area */
551                         if (vma_tmp->vm_start < end)
552                                 return -ENOMEM;
553                         __rb_link = &__rb_parent->rb_left;
554                 } else {
555                         rb_prev = __rb_parent;
556                         __rb_link = &__rb_parent->rb_right;
557                 }
558         }
559
560         *pprev = NULL;
561         if (rb_prev)
562                 *pprev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
563         *rb_link = __rb_link;
564         *rb_parent = __rb_parent;
565         return 0;
566 }
567
568 static unsigned long count_vma_pages_range(struct mm_struct *mm,
569                 unsigned long addr, unsigned long end)
570 {
571         unsigned long nr_pages = 0;
572         struct vm_area_struct *vma;
573
574         /* Find first overlaping mapping */
575         vma = find_vma_intersection(mm, addr, end);
576         if (!vma)
577                 return 0;
578
579         nr_pages = (min(end, vma->vm_end) -
580                 max(addr, vma->vm_start)) >> PAGE_SHIFT;
581
582         /* Iterate over the rest of the overlaps */
583         for (vma = vma->vm_next; vma; vma = vma->vm_next) {
584                 unsigned long overlap_len;
585
586                 if (vma->vm_start > end)
587                         break;
588
589                 overlap_len = min(end, vma->vm_end) - vma->vm_start;
590                 nr_pages += overlap_len >> PAGE_SHIFT;
591         }
592
593         return nr_pages;
594 }
595
596 void __vma_link_rb(struct mm_struct *mm, struct vm_area_struct *vma,
597                 struct rb_node **rb_link, struct rb_node *rb_parent)
598 {
599         /* Update tracking information for the gap following the new vma. */
600         if (vma->vm_next)
601                 vma_gap_update(vma->vm_next);
602         else
603                 mm->highest_vm_end = vm_end_gap(vma);
604
605         /*
606          * vma->vm_prev wasn't known when we followed the rbtree to find the
607          * correct insertion point for that vma. As a result, we could not
608          * update the vma vm_rb parents rb_subtree_gap values on the way down.
609          * So, we first insert the vma with a zero rb_subtree_gap value
610          * (to be consistent with what we did on the way down), and then
611          * immediately update the gap to the correct value. Finally we
612          * rebalance the rbtree after all augmented values have been set.
613          */
614         rb_link_node(&vma->vm_rb, rb_parent, rb_link);
615         vma->rb_subtree_gap = 0;
616         vma_gap_update(vma);
617         vma_rb_insert(vma, &mm->mm_rb);
618 }
619
620 static void __vma_link_file(struct vm_area_struct *vma)
621 {
622         struct file *file;
623
624         file = vma->vm_file;
625         if (file) {
626                 struct address_space *mapping = file->f_mapping;
627
628                 if (vma->vm_flags & VM_DENYWRITE)
629                         atomic_dec(&file_inode(file)->i_writecount);
630                 if (vma->vm_flags & VM_SHARED)
631                         atomic_inc(&mapping->i_mmap_writable);
632
633                 flush_dcache_mmap_lock(mapping);
634                 vma_interval_tree_insert(vma, &mapping->i_mmap);
635                 flush_dcache_mmap_unlock(mapping);
636         }
637 }
638
639 static void
640 __vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
641         struct vm_area_struct *prev, struct rb_node **rb_link,
642         struct rb_node *rb_parent)
643 {
644         __vma_link_list(mm, vma, prev, rb_parent);
645         __vma_link_rb(mm, vma, rb_link, rb_parent);
646 }
647
648 static void vma_link(struct mm_struct *mm, struct vm_area_struct *vma,
649                         struct vm_area_struct *prev, struct rb_node **rb_link,
650                         struct rb_node *rb_parent)
651 {
652         struct address_space *mapping = NULL;
653
654         if (vma->vm_file) {
655                 mapping = vma->vm_file->f_mapping;
656                 i_mmap_lock_write(mapping);
657         }
658
659         __vma_link(mm, vma, prev, rb_link, rb_parent);
660         __vma_link_file(vma);
661
662         if (mapping)
663                 i_mmap_unlock_write(mapping);
664
665         mm->map_count++;
666         validate_mm(mm);
667 }
668
669 /*
670  * Helper for vma_adjust() in the split_vma insert case: insert a vma into the
671  * mm's list and rbtree.  It has already been inserted into the interval tree.
672  */
673 static void __insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
674 {
675         struct vm_area_struct *prev;
676         struct rb_node **rb_link, *rb_parent;
677
678         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
679                            &prev, &rb_link, &rb_parent))
680                 BUG();
681         __vma_link(mm, vma, prev, rb_link, rb_parent);
682         mm->map_count++;
683 }
684
685 static __always_inline void __vma_unlink_common(struct mm_struct *mm,
686                                                 struct vm_area_struct *vma,
687                                                 struct vm_area_struct *prev,
688                                                 bool has_prev,
689                                                 struct vm_area_struct *ignore)
690 {
691         struct vm_area_struct *next;
692
693         vma_rb_erase_ignore(vma, &mm->mm_rb, ignore);
694         next = vma->vm_next;
695         if (has_prev)
696                 prev->vm_next = next;
697         else {
698                 prev = vma->vm_prev;
699                 if (prev)
700                         prev->vm_next = next;
701                 else
702                         mm->mmap = next;
703         }
704         if (next)
705                 next->vm_prev = prev;
706
707         /* Kill the cache */
708         vmacache_invalidate(mm);
709 }
710
711 static inline void __vma_unlink_prev(struct mm_struct *mm,
712                                      struct vm_area_struct *vma,
713                                      struct vm_area_struct *prev)
714 {
715         __vma_unlink_common(mm, vma, prev, true, vma);
716 }
717
718 /*
719  * We cannot adjust vm_start, vm_end, vm_pgoff fields of a vma that
720  * is already present in an i_mmap tree without adjusting the tree.
721  * The following helper function should be used when such adjustments
722  * are necessary.  The "insert" vma (if any) is to be inserted
723  * before we drop the necessary locks.
724  */
725 int __vma_adjust(struct vm_area_struct *vma, unsigned long start,
726         unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert,
727         struct vm_area_struct *expand)
728 {
729         struct mm_struct *mm = vma->vm_mm;
730         struct vm_area_struct *next = vma->vm_next, *orig_vma = vma;
731         struct address_space *mapping = NULL;
732         struct rb_root_cached *root = NULL;
733         struct anon_vma *anon_vma = NULL;
734         struct file *file = vma->vm_file;
735         bool start_changed = false, end_changed = false;
736         long adjust_next = 0;
737         int remove_next = 0;
738
739         if (next && !insert) {
740                 struct vm_area_struct *exporter = NULL, *importer = NULL;
741
742                 if (end >= next->vm_end) {
743                         /*
744                          * vma expands, overlapping all the next, and
745                          * perhaps the one after too (mprotect case 6).
746                          * The only other cases that gets here are
747                          * case 1, case 7 and case 8.
748                          */
749                         if (next == expand) {
750                                 /*
751                                  * The only case where we don't expand "vma"
752                                  * and we expand "next" instead is case 8.
753                                  */
754                                 VM_WARN_ON(end != next->vm_end);
755                                 /*
756                                  * remove_next == 3 means we're
757                                  * removing "vma" and that to do so we
758                                  * swapped "vma" and "next".
759                                  */
760                                 remove_next = 3;
761                                 VM_WARN_ON(file != next->vm_file);
762                                 swap(vma, next);
763                         } else {
764                                 VM_WARN_ON(expand != vma);
765                                 /*
766                                  * case 1, 6, 7, remove_next == 2 is case 6,
767                                  * remove_next == 1 is case 1 or 7.
768                                  */
769                                 remove_next = 1 + (end > next->vm_end);
770                                 VM_WARN_ON(remove_next == 2 &&
771                                            end != next->vm_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         addr = untagged_addr(addr);
1591
1592         if (!(flags & MAP_ANONYMOUS)) {
1593                 audit_mmap_fd(fd, flags);
1594                 file = fget(fd);
1595                 if (!file)
1596                         return -EBADF;
1597                 if (is_file_hugepages(file))
1598                         len = ALIGN(len, huge_page_size(hstate_file(file)));
1599                 retval = -EINVAL;
1600                 if (unlikely(flags & MAP_HUGETLB && !is_file_hugepages(file)))
1601                         goto out_fput;
1602         } else if (flags & MAP_HUGETLB) {
1603                 struct user_struct *user = NULL;
1604                 struct hstate *hs;
1605
1606                 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1607                 if (!hs)
1608                         return -EINVAL;
1609
1610                 len = ALIGN(len, huge_page_size(hs));
1611                 /*
1612                  * VM_NORESERVE is used because the reservations will be
1613                  * taken when vm_ops->mmap() is called
1614                  * A dummy user value is used because we are not locking
1615                  * memory so no accounting is necessary
1616                  */
1617                 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
1618                                 VM_NORESERVE,
1619                                 &user, HUGETLB_ANONHUGE_INODE,
1620                                 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
1621                 if (IS_ERR(file))
1622                         return PTR_ERR(file);
1623         }
1624
1625         flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
1626
1627         retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
1628 out_fput:
1629         if (file)
1630                 fput(file);
1631         return retval;
1632 }
1633
1634 SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
1635                 unsigned long, prot, unsigned long, flags,
1636                 unsigned long, fd, unsigned long, pgoff)
1637 {
1638         return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
1639 }
1640
1641 #ifdef __ARCH_WANT_SYS_OLD_MMAP
1642 struct mmap_arg_struct {
1643         unsigned long addr;
1644         unsigned long len;
1645         unsigned long prot;
1646         unsigned long flags;
1647         unsigned long fd;
1648         unsigned long offset;
1649 };
1650
1651 SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
1652 {
1653         struct mmap_arg_struct a;
1654
1655         if (copy_from_user(&a, arg, sizeof(a)))
1656                 return -EFAULT;
1657         if (offset_in_page(a.offset))
1658                 return -EINVAL;
1659
1660         return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
1661                                a.offset >> PAGE_SHIFT);
1662 }
1663 #endif /* __ARCH_WANT_SYS_OLD_MMAP */
1664
1665 /*
1666  * Some shared mappings will want the pages marked read-only
1667  * to track write events. If so, we'll downgrade vm_page_prot
1668  * to the private version (using protection_map[] without the
1669  * VM_SHARED bit).
1670  */
1671 int vma_wants_writenotify(struct vm_area_struct *vma, pgprot_t vm_page_prot)
1672 {
1673         vm_flags_t vm_flags = vma->vm_flags;
1674         const struct vm_operations_struct *vm_ops = vma->vm_ops;
1675
1676         /* If it was private or non-writable, the write bit is already clear */
1677         if ((vm_flags & (VM_WRITE|VM_SHARED)) != ((VM_WRITE|VM_SHARED)))
1678                 return 0;
1679
1680         /* The backer wishes to know when pages are first written to? */
1681         if (vm_ops && (vm_ops->page_mkwrite || vm_ops->pfn_mkwrite))
1682                 return 1;
1683
1684         /* The open routine did something to the protections that pgprot_modify
1685          * won't preserve? */
1686         if (pgprot_val(vm_page_prot) !=
1687             pgprot_val(vm_pgprot_modify(vm_page_prot, vm_flags)))
1688                 return 0;
1689
1690         /* Do we need to track softdirty? */
1691         if (IS_ENABLED(CONFIG_MEM_SOFT_DIRTY) && !(vm_flags & VM_SOFTDIRTY))
1692                 return 1;
1693
1694         /* Specialty mapping? */
1695         if (vm_flags & VM_PFNMAP)
1696                 return 0;
1697
1698         /* Can the mapping track the dirty pages? */
1699         return vma->vm_file && vma->vm_file->f_mapping &&
1700                 mapping_cap_account_dirty(vma->vm_file->f_mapping);
1701 }
1702
1703 /*
1704  * We account for memory if it's a private writeable mapping,
1705  * not hugepages and VM_NORESERVE wasn't set.
1706  */
1707 static inline int accountable_mapping(struct file *file, vm_flags_t vm_flags)
1708 {
1709         /*
1710          * hugetlb has its own accounting separate from the core VM
1711          * VM_HUGETLB may not be set yet so we cannot check for that flag.
1712          */
1713         if (file && is_file_hugepages(file))
1714                 return 0;
1715
1716         return (vm_flags & (VM_NORESERVE | VM_SHARED | VM_WRITE)) == VM_WRITE;
1717 }
1718
1719 unsigned long mmap_region(struct file *file, unsigned long addr,
1720                 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
1721                 struct list_head *uf)
1722 {
1723         struct mm_struct *mm = current->mm;
1724         struct vm_area_struct *vma, *prev;
1725         int error;
1726         struct rb_node **rb_link, *rb_parent;
1727         unsigned long charged = 0;
1728
1729         /* Check against address space limit. */
1730         if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
1731                 unsigned long nr_pages;
1732
1733                 /*
1734                  * MAP_FIXED may remove pages of mappings that intersects with
1735                  * requested mapping. Account for the pages it would unmap.
1736                  */
1737                 nr_pages = count_vma_pages_range(mm, addr, addr + len);
1738
1739                 if (!may_expand_vm(mm, vm_flags,
1740                                         (len >> PAGE_SHIFT) - nr_pages))
1741                         return -ENOMEM;
1742         }
1743
1744         /* Clear old maps */
1745         while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
1746                               &rb_parent)) {
1747                 if (do_munmap(mm, addr, len, uf))
1748                         return -ENOMEM;
1749         }
1750
1751         /*
1752          * Private writable mapping: check memory availability
1753          */
1754         if (accountable_mapping(file, vm_flags)) {
1755                 charged = len >> PAGE_SHIFT;
1756                 if (security_vm_enough_memory_mm(mm, charged))
1757                         return -ENOMEM;
1758                 vm_flags |= VM_ACCOUNT;
1759         }
1760
1761         /*
1762          * Can we just expand an old mapping?
1763          */
1764         vma = vma_merge(mm, prev, addr, addr + len, vm_flags,
1765                         NULL, file, pgoff, NULL, NULL_VM_UFFD_CTX);
1766         if (vma)
1767                 goto out;
1768
1769         /*
1770          * Determine the object being mapped and call the appropriate
1771          * specific mapper. the address has already been validated, but
1772          * not unmapped, but the maps are removed from the list.
1773          */
1774         vma = vm_area_alloc(mm);
1775         if (!vma) {
1776                 error = -ENOMEM;
1777                 goto unacct_error;
1778         }
1779
1780         vma->vm_start = addr;
1781         vma->vm_end = addr + len;
1782         vma->vm_flags = vm_flags;
1783         vma->vm_page_prot = vm_get_page_prot(vm_flags);
1784         vma->vm_pgoff = pgoff;
1785
1786         if (file) {
1787                 if (vm_flags & VM_DENYWRITE) {
1788                         error = deny_write_access(file);
1789                         if (error)
1790                                 goto free_vma;
1791                 }
1792                 if (vm_flags & VM_SHARED) {
1793                         error = mapping_map_writable(file->f_mapping);
1794                         if (error)
1795                                 goto allow_write_and_free_vma;
1796                 }
1797
1798                 /* ->mmap() can change vma->vm_file, but must guarantee that
1799                  * vma_link() below can deny write-access if VM_DENYWRITE is set
1800                  * and map writably if VM_SHARED is set. This usually means the
1801                  * new file must not have been exposed to user-space, yet.
1802                  */
1803                 vma->vm_file = get_file(file);
1804                 error = call_mmap(file, vma);
1805                 if (error)
1806                         goto unmap_and_free_vma;
1807
1808                 /* Can addr have changed??
1809                  *
1810                  * Answer: Yes, several device drivers can do it in their
1811                  *         f_op->mmap method. -DaveM
1812                  * Bug: If addr is changed, prev, rb_link, rb_parent should
1813                  *      be updated for vma_link()
1814                  */
1815                 WARN_ON_ONCE(addr != vma->vm_start);
1816
1817                 addr = vma->vm_start;
1818                 vm_flags = vma->vm_flags;
1819         } else if (vm_flags & VM_SHARED) {
1820                 error = shmem_zero_setup(vma);
1821                 if (error)
1822                         goto free_vma;
1823         } else {
1824                 vma_set_anonymous(vma);
1825         }
1826
1827         vma_link(mm, vma, prev, rb_link, rb_parent);
1828         /* Once vma denies write, undo our temporary denial count */
1829         if (file) {
1830                 if (vm_flags & VM_SHARED)
1831                         mapping_unmap_writable(file->f_mapping);
1832                 if (vm_flags & VM_DENYWRITE)
1833                         allow_write_access(file);
1834         }
1835         file = vma->vm_file;
1836 out:
1837         perf_event_mmap(vma);
1838
1839         vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
1840         if (vm_flags & VM_LOCKED) {
1841                 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
1842                                         is_vm_hugetlb_page(vma) ||
1843                                         vma == get_gate_vma(current->mm))
1844                         vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
1845                 else
1846                         mm->locked_vm += (len >> PAGE_SHIFT);
1847         }
1848
1849         if (file)
1850                 uprobe_mmap(vma);
1851
1852         /*
1853          * New (or expanded) vma always get soft dirty status.
1854          * Otherwise user-space soft-dirty page tracker won't
1855          * be able to distinguish situation when vma area unmapped,
1856          * then new mapped in-place (which must be aimed as
1857          * a completely new data area).
1858          */
1859         vma->vm_flags |= VM_SOFTDIRTY;
1860
1861         vma_set_page_prot(vma);
1862
1863         return addr;
1864
1865 unmap_and_free_vma:
1866         vma->vm_file = NULL;
1867         fput(file);
1868
1869         /* Undo any partial mapping done by a device driver. */
1870         unmap_region(mm, vma, prev, vma->vm_start, vma->vm_end);
1871         charged = 0;
1872         if (vm_flags & VM_SHARED)
1873                 mapping_unmap_writable(file->f_mapping);
1874 allow_write_and_free_vma:
1875         if (vm_flags & VM_DENYWRITE)
1876                 allow_write_access(file);
1877 free_vma:
1878         vm_area_free(vma);
1879 unacct_error:
1880         if (charged)
1881                 vm_unacct_memory(charged);
1882         return error;
1883 }
1884
1885 unsigned long unmapped_area(struct vm_unmapped_area_info *info)
1886 {
1887         /*
1888          * We implement the search by looking for an rbtree node that
1889          * immediately follows a suitable gap. That is,
1890          * - gap_start = vma->vm_prev->vm_end <= info->high_limit - length;
1891          * - gap_end   = vma->vm_start        >= info->low_limit  + length;
1892          * - gap_end - gap_start >= length
1893          */
1894
1895         struct mm_struct *mm = current->mm;
1896         struct vm_area_struct *vma;
1897         unsigned long length, low_limit, high_limit, gap_start, gap_end;
1898
1899         /* Adjust search length to account for worst case alignment overhead */
1900         length = info->length + info->align_mask;
1901         if (length < info->length)
1902                 return -ENOMEM;
1903
1904         /* Adjust search limits by the desired length */
1905         if (info->high_limit < length)
1906                 return -ENOMEM;
1907         high_limit = info->high_limit - length;
1908
1909         if (info->low_limit > high_limit)
1910                 return -ENOMEM;
1911         low_limit = info->low_limit + length;
1912
1913         /* Check if rbtree root looks promising */
1914         if (RB_EMPTY_ROOT(&mm->mm_rb))
1915                 goto check_highest;
1916         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
1917         if (vma->rb_subtree_gap < length)
1918                 goto check_highest;
1919
1920         while (true) {
1921                 /* Visit left subtree if it looks promising */
1922                 gap_end = vm_start_gap(vma);
1923                 if (gap_end >= low_limit && vma->vm_rb.rb_left) {
1924                         struct vm_area_struct *left =
1925                                 rb_entry(vma->vm_rb.rb_left,
1926                                          struct vm_area_struct, vm_rb);
1927                         if (left->rb_subtree_gap >= length) {
1928                                 vma = left;
1929                                 continue;
1930                         }
1931                 }
1932
1933                 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
1934 check_current:
1935                 /* Check if current node has a suitable gap */
1936                 if (gap_start > high_limit)
1937                         return -ENOMEM;
1938                 if (gap_end >= low_limit &&
1939                     gap_end > gap_start && gap_end - gap_start >= length)
1940                         goto found;
1941
1942                 /* Visit right subtree if it looks promising */
1943                 if (vma->vm_rb.rb_right) {
1944                         struct vm_area_struct *right =
1945                                 rb_entry(vma->vm_rb.rb_right,
1946                                          struct vm_area_struct, vm_rb);
1947                         if (right->rb_subtree_gap >= length) {
1948                                 vma = right;
1949                                 continue;
1950                         }
1951                 }
1952
1953                 /* Go back up the rbtree to find next candidate node */
1954                 while (true) {
1955                         struct rb_node *prev = &vma->vm_rb;
1956                         if (!rb_parent(prev))
1957                                 goto check_highest;
1958                         vma = rb_entry(rb_parent(prev),
1959                                        struct vm_area_struct, vm_rb);
1960                         if (prev == vma->vm_rb.rb_left) {
1961                                 gap_start = vm_end_gap(vma->vm_prev);
1962                                 gap_end = vm_start_gap(vma);
1963                                 goto check_current;
1964                         }
1965                 }
1966         }
1967
1968 check_highest:
1969         /* Check highest gap, which does not precede any rbtree node */
1970         gap_start = mm->highest_vm_end;
1971         gap_end = ULONG_MAX;  /* Only for VM_BUG_ON below */
1972         if (gap_start > high_limit)
1973                 return -ENOMEM;
1974
1975 found:
1976         /* We found a suitable gap. Clip it with the original low_limit. */
1977         if (gap_start < info->low_limit)
1978                 gap_start = info->low_limit;
1979
1980         /* Adjust gap address to the desired alignment */
1981         gap_start += (info->align_offset - gap_start) & info->align_mask;
1982
1983         VM_BUG_ON(gap_start + info->length > info->high_limit);
1984         VM_BUG_ON(gap_start + info->length > gap_end);
1985         return gap_start;
1986 }
1987
1988 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info)
1989 {
1990         struct mm_struct *mm = current->mm;
1991         struct vm_area_struct *vma;
1992         unsigned long length, low_limit, high_limit, gap_start, gap_end;
1993
1994         /* Adjust search length to account for worst case alignment overhead */
1995         length = info->length + info->align_mask;
1996         if (length < info->length)
1997                 return -ENOMEM;
1998
1999         /*
2000          * Adjust search limits by the desired length.
2001          * See implementation comment at top of unmapped_area().
2002          */
2003         gap_end = info->high_limit;
2004         if (gap_end < length)
2005                 return -ENOMEM;
2006         high_limit = gap_end - length;
2007
2008         if (info->low_limit > high_limit)
2009                 return -ENOMEM;
2010         low_limit = info->low_limit + length;
2011
2012         /* Check highest gap, which does not precede any rbtree node */
2013         gap_start = mm->highest_vm_end;
2014         if (gap_start <= high_limit)
2015                 goto found_highest;
2016
2017         /* Check if rbtree root looks promising */
2018         if (RB_EMPTY_ROOT(&mm->mm_rb))
2019                 return -ENOMEM;
2020         vma = rb_entry(mm->mm_rb.rb_node, struct vm_area_struct, vm_rb);
2021         if (vma->rb_subtree_gap < length)
2022                 return -ENOMEM;
2023
2024         while (true) {
2025                 /* Visit right subtree if it looks promising */
2026                 gap_start = vma->vm_prev ? vm_end_gap(vma->vm_prev) : 0;
2027                 if (gap_start <= high_limit && vma->vm_rb.rb_right) {
2028                         struct vm_area_struct *right =
2029                                 rb_entry(vma->vm_rb.rb_right,
2030                                          struct vm_area_struct, vm_rb);
2031                         if (right->rb_subtree_gap >= length) {
2032                                 vma = right;
2033                                 continue;
2034                         }
2035                 }
2036
2037 check_current:
2038                 /* Check if current node has a suitable gap */
2039                 gap_end = vm_start_gap(vma);
2040                 if (gap_end < low_limit)
2041                         return -ENOMEM;
2042                 if (gap_start <= high_limit &&
2043                     gap_end > gap_start && gap_end - gap_start >= length)
2044                         goto found;
2045
2046                 /* Visit left subtree if it looks promising */
2047                 if (vma->vm_rb.rb_left) {
2048                         struct vm_area_struct *left =
2049                                 rb_entry(vma->vm_rb.rb_left,
2050                                          struct vm_area_struct, vm_rb);
2051                         if (left->rb_subtree_gap >= length) {
2052                                 vma = left;
2053                                 continue;
2054                         }
2055                 }
2056
2057                 /* Go back up the rbtree to find next candidate node */
2058                 while (true) {
2059                         struct rb_node *prev = &vma->vm_rb;
2060                         if (!rb_parent(prev))
2061                                 return -ENOMEM;
2062                         vma = rb_entry(rb_parent(prev),
2063                                        struct vm_area_struct, vm_rb);
2064                         if (prev == vma->vm_rb.rb_right) {
2065                                 gap_start = vma->vm_prev ?
2066                                         vm_end_gap(vma->vm_prev) : 0;
2067                                 goto check_current;
2068                         }
2069                 }
2070         }
2071
2072 found:
2073         /* We found a suitable gap. Clip it with the original high_limit. */
2074         if (gap_end > info->high_limit)
2075                 gap_end = info->high_limit;
2076
2077 found_highest:
2078         /* Compute highest gap address at the desired alignment */
2079         gap_end -= info->length;
2080         gap_end -= (gap_end - info->align_offset) & info->align_mask;
2081
2082         VM_BUG_ON(gap_end < info->low_limit);
2083         VM_BUG_ON(gap_end < gap_start);
2084         return gap_end;
2085 }
2086
2087
2088 #ifndef arch_get_mmap_end
2089 #define arch_get_mmap_end(addr) (TASK_SIZE)
2090 #endif
2091
2092 #ifndef arch_get_mmap_base
2093 #define arch_get_mmap_base(addr, base) (base)
2094 #endif
2095
2096 /* Get an address range which is currently unmapped.
2097  * For shmat() with addr=0.
2098  *
2099  * Ugly calling convention alert:
2100  * Return value with the low bits set means error value,
2101  * ie
2102  *      if (ret & ~PAGE_MASK)
2103  *              error = ret;
2104  *
2105  * This function "knows" that -ENOMEM has the bits set.
2106  */
2107 #ifndef HAVE_ARCH_UNMAPPED_AREA
2108 unsigned long
2109 arch_get_unmapped_area(struct file *filp, unsigned long addr,
2110                 unsigned long len, unsigned long pgoff, unsigned long flags)
2111 {
2112         struct mm_struct *mm = current->mm;
2113         struct vm_area_struct *vma, *prev;
2114         struct vm_unmapped_area_info info;
2115         const unsigned long mmap_end = arch_get_mmap_end(addr);
2116
2117         if (len > mmap_end - mmap_min_addr)
2118                 return -ENOMEM;
2119
2120         if (flags & MAP_FIXED)
2121                 return addr;
2122
2123         if (addr) {
2124                 addr = PAGE_ALIGN(addr);
2125                 vma = find_vma_prev(mm, addr, &prev);
2126                 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2127                     (!vma || addr + len <= vm_start_gap(vma)) &&
2128                     (!prev || addr >= vm_end_gap(prev)))
2129                         return addr;
2130         }
2131
2132         info.flags = 0;
2133         info.length = len;
2134         info.low_limit = mm->mmap_base;
2135         info.high_limit = mmap_end;
2136         info.align_mask = 0;
2137         return vm_unmapped_area(&info);
2138 }
2139 #endif
2140
2141 /*
2142  * This mmap-allocator allocates new areas top-down from below the
2143  * stack's low limit (the base):
2144  */
2145 #ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
2146 unsigned long
2147 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
2148                           unsigned long len, unsigned long pgoff,
2149                           unsigned long flags)
2150 {
2151         struct vm_area_struct *vma, *prev;
2152         struct mm_struct *mm = current->mm;
2153         struct vm_unmapped_area_info info;
2154         const unsigned long mmap_end = arch_get_mmap_end(addr);
2155
2156         /* requested length too big for entire address space */
2157         if (len > mmap_end - mmap_min_addr)
2158                 return -ENOMEM;
2159
2160         if (flags & MAP_FIXED)
2161                 return addr;
2162
2163         /* requesting a specific address */
2164         if (addr) {
2165                 addr = PAGE_ALIGN(addr);
2166                 vma = find_vma_prev(mm, addr, &prev);
2167                 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
2168                                 (!vma || addr + len <= vm_start_gap(vma)) &&
2169                                 (!prev || addr >= vm_end_gap(prev)))
2170                         return addr;
2171         }
2172
2173         info.flags = VM_UNMAPPED_AREA_TOPDOWN;
2174         info.length = len;
2175         info.low_limit = max(PAGE_SIZE, mmap_min_addr);
2176         info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
2177         info.align_mask = 0;
2178         addr = vm_unmapped_area(&info);
2179
2180         /*
2181          * A failed mmap() very likely causes application failure,
2182          * so fall back to the bottom-up function here. This scenario
2183          * can happen with large stack limits and large mmap()
2184          * allocations.
2185          */
2186         if (offset_in_page(addr)) {
2187                 VM_BUG_ON(addr != -ENOMEM);
2188                 info.flags = 0;
2189                 info.low_limit = TASK_UNMAPPED_BASE;
2190                 info.high_limit = mmap_end;
2191                 addr = vm_unmapped_area(&info);
2192         }
2193
2194         return addr;
2195 }
2196 #endif
2197
2198 unsigned long
2199 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
2200                 unsigned long pgoff, unsigned long flags)
2201 {
2202         unsigned long (*get_area)(struct file *, unsigned long,
2203                                   unsigned long, unsigned long, unsigned long);
2204
2205         unsigned long error = arch_mmap_check(addr, len, flags);
2206         if (error)
2207                 return error;
2208
2209         /* Careful about overflows.. */
2210         if (len > TASK_SIZE)
2211                 return -ENOMEM;
2212
2213         get_area = current->mm->get_unmapped_area;
2214         if (file) {
2215                 if (file->f_op->get_unmapped_area)
2216                         get_area = file->f_op->get_unmapped_area;
2217         } else if (flags & MAP_SHARED) {
2218                 /*
2219                  * mmap_region() will call shmem_zero_setup() to create a file,
2220                  * so use shmem's get_unmapped_area in case it can be huge.
2221                  * do_mmap_pgoff() will clear pgoff, so match alignment.
2222                  */
2223                 pgoff = 0;
2224                 get_area = shmem_get_unmapped_area;
2225         }
2226
2227         addr = get_area(file, addr, len, pgoff, flags);
2228         if (IS_ERR_VALUE(addr))
2229                 return addr;
2230
2231         if (addr > TASK_SIZE - len)
2232                 return -ENOMEM;
2233         if (offset_in_page(addr))
2234                 return -EINVAL;
2235
2236         error = security_mmap_addr(addr);
2237         return error ? error : addr;
2238 }
2239
2240 EXPORT_SYMBOL(get_unmapped_area);
2241
2242 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
2243 struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
2244 {
2245         struct rb_node *rb_node;
2246         struct vm_area_struct *vma;
2247
2248         /* Check the cache first. */
2249         vma = vmacache_find(mm, addr);
2250         if (likely(vma))
2251                 return vma;
2252
2253         rb_node = mm->mm_rb.rb_node;
2254
2255         while (rb_node) {
2256                 struct vm_area_struct *tmp;
2257
2258                 tmp = rb_entry(rb_node, struct vm_area_struct, vm_rb);
2259
2260                 if (tmp->vm_end > addr) {
2261                         vma = tmp;
2262                         if (tmp->vm_start <= addr)
2263                                 break;
2264                         rb_node = rb_node->rb_left;
2265                 } else
2266                         rb_node = rb_node->rb_right;
2267         }
2268
2269         if (vma)
2270                 vmacache_update(addr, vma);
2271         return vma;
2272 }
2273
2274 EXPORT_SYMBOL(find_vma);
2275
2276 /*
2277  * Same as find_vma, but also return a pointer to the previous VMA in *pprev.
2278  */
2279 struct vm_area_struct *
2280 find_vma_prev(struct mm_struct *mm, unsigned long addr,
2281                         struct vm_area_struct **pprev)
2282 {
2283         struct vm_area_struct *vma;
2284
2285         vma = find_vma(mm, addr);
2286         if (vma) {
2287                 *pprev = vma->vm_prev;
2288         } else {
2289                 struct rb_node *rb_node = rb_last(&mm->mm_rb);
2290
2291                 *pprev = rb_node ? rb_entry(rb_node, struct vm_area_struct, vm_rb) : NULL;
2292         }
2293         return vma;
2294 }
2295
2296 /*
2297  * Verify that the stack growth is acceptable and
2298  * update accounting. This is shared with both the
2299  * grow-up and grow-down cases.
2300  */
2301 static int acct_stack_growth(struct vm_area_struct *vma,
2302                              unsigned long size, unsigned long grow)
2303 {
2304         struct mm_struct *mm = vma->vm_mm;
2305         unsigned long new_start;
2306
2307         /* address space limit tests */
2308         if (!may_expand_vm(mm, vma->vm_flags, grow))
2309                 return -ENOMEM;
2310
2311         /* Stack limit test */
2312         if (size > rlimit(RLIMIT_STACK))
2313                 return -ENOMEM;
2314
2315         /* mlock limit tests */
2316         if (vma->vm_flags & VM_LOCKED) {
2317                 unsigned long locked;
2318                 unsigned long limit;
2319                 locked = mm->locked_vm + grow;
2320                 limit = rlimit(RLIMIT_MEMLOCK);
2321                 limit >>= PAGE_SHIFT;
2322                 if (locked > limit && !capable(CAP_IPC_LOCK))
2323                         return -ENOMEM;
2324         }
2325
2326         /* Check to ensure the stack will not grow into a hugetlb-only region */
2327         new_start = (vma->vm_flags & VM_GROWSUP) ? vma->vm_start :
2328                         vma->vm_end - size;
2329         if (is_hugepage_only_range(vma->vm_mm, new_start, size))
2330                 return -EFAULT;
2331
2332         /*
2333          * Overcommit..  This must be the final test, as it will
2334          * update security statistics.
2335          */
2336         if (security_vm_enough_memory_mm(mm, grow))
2337                 return -ENOMEM;
2338
2339         return 0;
2340 }
2341
2342 #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64)
2343 /*
2344  * PA-RISC uses this for its stack; IA64 for its Register Backing Store.
2345  * vma is the last one with address > vma->vm_end.  Have to extend vma.
2346  */
2347 int expand_upwards(struct vm_area_struct *vma, unsigned long address)
2348 {
2349         struct mm_struct *mm = vma->vm_mm;
2350         struct vm_area_struct *next;
2351         unsigned long gap_addr;
2352         int error = 0;
2353
2354         if (!(vma->vm_flags & VM_GROWSUP))
2355                 return -EFAULT;
2356
2357         /* Guard against exceeding limits of the address space. */
2358         address &= PAGE_MASK;
2359         if (address >= (TASK_SIZE & PAGE_MASK))
2360                 return -ENOMEM;
2361         address += PAGE_SIZE;
2362
2363         /* Enforce stack_guard_gap */
2364         gap_addr = address + stack_guard_gap;
2365
2366         /* Guard against overflow */
2367         if (gap_addr < address || gap_addr > TASK_SIZE)
2368                 gap_addr = TASK_SIZE;
2369
2370         next = vma->vm_next;
2371         if (next && next->vm_start < gap_addr &&
2372                         (next->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2373                 if (!(next->vm_flags & VM_GROWSUP))
2374                         return -ENOMEM;
2375                 /* Check that both stack segments have the same anon_vma? */
2376         }
2377
2378         /* We must make sure the anon_vma is allocated. */
2379         if (unlikely(anon_vma_prepare(vma)))
2380                 return -ENOMEM;
2381
2382         /*
2383          * vma->vm_start/vm_end cannot change under us because the caller
2384          * is required to hold the mmap_sem in read mode.  We need the
2385          * anon_vma lock to serialize against concurrent expand_stacks.
2386          */
2387         anon_vma_lock_write(vma->anon_vma);
2388
2389         /* Somebody else might have raced and expanded it already */
2390         if (address > vma->vm_end) {
2391                 unsigned long size, grow;
2392
2393                 size = address - vma->vm_start;
2394                 grow = (address - vma->vm_end) >> PAGE_SHIFT;
2395
2396                 error = -ENOMEM;
2397                 if (vma->vm_pgoff + (size >> PAGE_SHIFT) >= vma->vm_pgoff) {
2398                         error = acct_stack_growth(vma, size, grow);
2399                         if (!error) {
2400                                 /*
2401                                  * vma_gap_update() doesn't support concurrent
2402                                  * updates, but we only hold a shared mmap_sem
2403                                  * lock here, so we need to protect against
2404                                  * concurrent vma expansions.
2405                                  * anon_vma_lock_write() doesn't help here, as
2406                                  * we don't guarantee that all growable vmas
2407                                  * in a mm share the same root anon vma.
2408                                  * So, we reuse mm->page_table_lock to guard
2409                                  * against concurrent vma expansions.
2410                                  */
2411                                 spin_lock(&mm->page_table_lock);
2412                                 if (vma->vm_flags & VM_LOCKED)
2413                                         mm->locked_vm += grow;
2414                                 vm_stat_account(mm, vma->vm_flags, grow);
2415                                 anon_vma_interval_tree_pre_update_vma(vma);
2416                                 vma->vm_end = address;
2417                                 anon_vma_interval_tree_post_update_vma(vma);
2418                                 if (vma->vm_next)
2419                                         vma_gap_update(vma->vm_next);
2420                                 else
2421                                         mm->highest_vm_end = vm_end_gap(vma);
2422                                 spin_unlock(&mm->page_table_lock);
2423
2424                                 perf_event_mmap(vma);
2425                         }
2426                 }
2427         }
2428         anon_vma_unlock_write(vma->anon_vma);
2429         khugepaged_enter_vma_merge(vma, vma->vm_flags);
2430         validate_mm(mm);
2431         return error;
2432 }
2433 #endif /* CONFIG_STACK_GROWSUP || CONFIG_IA64 */
2434
2435 /*
2436  * vma is the first one with address < vma->vm_start.  Have to extend vma.
2437  */
2438 int expand_downwards(struct vm_area_struct *vma,
2439                                    unsigned long address)
2440 {
2441         struct mm_struct *mm = vma->vm_mm;
2442         struct vm_area_struct *prev;
2443         int error = 0;
2444
2445         address &= PAGE_MASK;
2446         if (address < mmap_min_addr)
2447                 return -EPERM;
2448
2449         /* Enforce stack_guard_gap */
2450         prev = vma->vm_prev;
2451         /* Check that both stack segments have the same anon_vma? */
2452         if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
2453                         (prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
2454                 if (address - prev->vm_end < stack_guard_gap)
2455                         return -ENOMEM;
2456         }
2457
2458         /* We must make sure the anon_vma is allocated. */
2459         if (unlikely(anon_vma_prepare(vma)))
2460                 return -ENOMEM;
2461
2462         /*
2463          * vma->vm_start/vm_end cannot change under us because the caller
2464          * is required to hold the mmap_sem in read mode.  We need the
2465          * anon_vma lock to serialize against concurrent expand_stacks.
2466          */
2467         anon_vma_lock_write(vma->anon_vma);
2468
2469         /* Somebody else might have raced and expanded it already */
2470         if (address < vma->vm_start) {
2471                 unsigned long size, grow;
2472
2473                 size = vma->vm_end - address;
2474                 grow = (vma->vm_start - address) >> PAGE_SHIFT;
2475
2476                 error = -ENOMEM;
2477                 if (grow <= vma->vm_pgoff) {
2478                         error = acct_stack_growth(vma, size, grow);
2479                         if (!error) {
2480                                 /*
2481                                  * vma_gap_update() doesn't support concurrent
2482                                  * updates, but we only hold a shared mmap_sem
2483                                  * lock here, so we need to protect against
2484                                  * concurrent vma expansions.
2485                                  * anon_vma_lock_write() doesn't help here, as
2486                                  * we don't guarantee that all growable vmas
2487                                  * in a mm share the same root anon vma.
2488                                  * So, we reuse mm->page_table_lock to guard
2489                                  * against concurrent vma expansions.
2490                                  */
2491                                 spin_lock(&mm->page_table_lock);
2492                                 if (vma->vm_flags & VM_LOCKED)
2493                                         mm->locked_vm += grow;
2494                                 vm_stat_account(mm, vma->vm_flags, grow);
2495                                 anon_vma_interval_tree_pre_update_vma(vma);
2496                                 vma->vm_start = address;
2497                                 vma->vm_pgoff -= grow;
2498                                 anon_vma_interval_tree_post_update_vma(vma);
2499                                 vma_gap_update(vma);
2500                                 spin_unlock(&mm->page_table_lock);
2501
2502                                 perf_event_mmap(vma);
2503                         }
2504                 }
2505         }
2506         anon_vma_unlock_write(vma->anon_vma);
2507         khugepaged_enter_vma_merge(vma, vma->vm_flags);
2508         validate_mm(mm);
2509         return error;
2510 }
2511
2512 /* enforced gap between the expanding stack and other mappings. */
2513 unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
2514
2515 static int __init cmdline_parse_stack_guard_gap(char *p)
2516 {
2517         unsigned long val;
2518         char *endptr;
2519
2520         val = simple_strtoul(p, &endptr, 10);
2521         if (!*endptr)
2522                 stack_guard_gap = val << PAGE_SHIFT;
2523
2524         return 0;
2525 }
2526 __setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
2527
2528 #ifdef CONFIG_STACK_GROWSUP
2529 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2530 {
2531         return expand_upwards(vma, address);
2532 }
2533
2534 struct vm_area_struct *
2535 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2536 {
2537         struct vm_area_struct *vma, *prev;
2538
2539         addr &= PAGE_MASK;
2540         vma = find_vma_prev(mm, addr, &prev);
2541         if (vma && (vma->vm_start <= addr))
2542                 return vma;
2543         /* don't alter vm_end if the coredump is running */
2544         if (!prev || !mmget_still_valid(mm) || expand_stack(prev, addr))
2545                 return NULL;
2546         if (prev->vm_flags & VM_LOCKED)
2547                 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
2548         return prev;
2549 }
2550 #else
2551 int expand_stack(struct vm_area_struct *vma, unsigned long address)
2552 {
2553         return expand_downwards(vma, address);
2554 }
2555
2556 struct vm_area_struct *
2557 find_extend_vma(struct mm_struct *mm, unsigned long addr)
2558 {
2559         struct vm_area_struct *vma;
2560         unsigned long start;
2561
2562         addr &= PAGE_MASK;
2563         vma = find_vma(mm, addr);
2564         if (!vma)
2565                 return NULL;
2566         if (vma->vm_start <= addr)
2567                 return vma;
2568         if (!(vma->vm_flags & VM_GROWSDOWN))
2569                 return NULL;
2570         /* don't alter vm_start if the coredump is running */
2571         if (!mmget_still_valid(mm))
2572                 return NULL;
2573         start = vma->vm_start;
2574         if (expand_stack(vma, addr))
2575                 return NULL;
2576         if (vma->vm_flags & VM_LOCKED)
2577                 populate_vma_page_range(vma, addr, start, NULL);
2578         return vma;
2579 }
2580 #endif
2581
2582 EXPORT_SYMBOL_GPL(find_extend_vma);
2583
2584 /*
2585  * Ok - we have the memory areas we should free on the vma list,
2586  * so release them, and do the vma updates.
2587  *
2588  * Called with the mm semaphore held.
2589  */
2590 static void remove_vma_list(struct mm_struct *mm, struct vm_area_struct *vma)
2591 {
2592         unsigned long nr_accounted = 0;
2593
2594         /* Update high watermark before we lower total_vm */
2595         update_hiwater_vm(mm);
2596         do {
2597                 long nrpages = vma_pages(vma);
2598
2599                 if (vma->vm_flags & VM_ACCOUNT)
2600                         nr_accounted += nrpages;
2601                 vm_stat_account(mm, vma->vm_flags, -nrpages);
2602                 vma = remove_vma(vma);
2603         } while (vma);
2604         vm_unacct_memory(nr_accounted);
2605         validate_mm(mm);
2606 }
2607
2608 /*
2609  * Get rid of page table information in the indicated region.
2610  *
2611  * Called with the mm semaphore held.
2612  */
2613 static void unmap_region(struct mm_struct *mm,
2614                 struct vm_area_struct *vma, struct vm_area_struct *prev,
2615                 unsigned long start, unsigned long end)
2616 {
2617         struct vm_area_struct *next = prev ? prev->vm_next : mm->mmap;
2618         struct mmu_gather tlb;
2619
2620         lru_add_drain();
2621         tlb_gather_mmu(&tlb, mm, start, end);
2622         update_hiwater_rss(mm);
2623         unmap_vmas(&tlb, vma, start, end);
2624         free_pgtables(&tlb, vma, prev ? prev->vm_end : FIRST_USER_ADDRESS,
2625                                  next ? next->vm_start : USER_PGTABLES_CEILING);
2626         tlb_finish_mmu(&tlb, start, end);
2627 }
2628
2629 /*
2630  * Create a list of vma's touched by the unmap, removing them from the mm's
2631  * vma list as we go..
2632  */
2633 static void
2634 detach_vmas_to_be_unmapped(struct mm_struct *mm, struct vm_area_struct *vma,
2635         struct vm_area_struct *prev, unsigned long end)
2636 {
2637         struct vm_area_struct **insertion_point;
2638         struct vm_area_struct *tail_vma = NULL;
2639
2640         insertion_point = (prev ? &prev->vm_next : &mm->mmap);
2641         vma->vm_prev = NULL;
2642         do {
2643                 vma_rb_erase(vma, &mm->mm_rb);
2644                 mm->map_count--;
2645                 tail_vma = vma;
2646                 vma = vma->vm_next;
2647         } while (vma && vma->vm_start < end);
2648         *insertion_point = vma;
2649         if (vma) {
2650                 vma->vm_prev = prev;
2651                 vma_gap_update(vma);
2652         } else
2653                 mm->highest_vm_end = prev ? vm_end_gap(prev) : 0;
2654         tail_vma->vm_next = NULL;
2655
2656         /* Kill the cache */
2657         vmacache_invalidate(mm);
2658 }
2659
2660 /*
2661  * __split_vma() bypasses sysctl_max_map_count checking.  We use this where it
2662  * has already been checked or doesn't make sense to fail.
2663  */
2664 int __split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2665                 unsigned long addr, int new_below)
2666 {
2667         struct vm_area_struct *new;
2668         int err;
2669
2670         if (vma->vm_ops && vma->vm_ops->split) {
2671                 err = vma->vm_ops->split(vma, addr);
2672                 if (err)
2673                         return err;
2674         }
2675
2676         new = vm_area_dup(vma);
2677         if (!new)
2678                 return -ENOMEM;
2679
2680         if (new_below)
2681                 new->vm_end = addr;
2682         else {
2683                 new->vm_start = addr;
2684                 new->vm_pgoff += ((addr - vma->vm_start) >> PAGE_SHIFT);
2685         }
2686
2687         err = vma_dup_policy(vma, new);
2688         if (err)
2689                 goto out_free_vma;
2690
2691         err = anon_vma_clone(new, vma);
2692         if (err)
2693                 goto out_free_mpol;
2694
2695         if (new->vm_file)
2696                 get_file(new->vm_file);
2697
2698         if (new->vm_ops && new->vm_ops->open)
2699                 new->vm_ops->open(new);
2700
2701         if (new_below)
2702                 err = vma_adjust(vma, addr, vma->vm_end, vma->vm_pgoff +
2703                         ((addr - new->vm_start) >> PAGE_SHIFT), new);
2704         else
2705                 err = vma_adjust(vma, vma->vm_start, addr, vma->vm_pgoff, new);
2706
2707         /* Success. */
2708         if (!err)
2709                 return 0;
2710
2711         /* Clean everything up if vma_adjust failed. */
2712         if (new->vm_ops && new->vm_ops->close)
2713                 new->vm_ops->close(new);
2714         if (new->vm_file)
2715                 fput(new->vm_file);
2716         unlink_anon_vmas(new);
2717  out_free_mpol:
2718         mpol_put(vma_policy(new));
2719  out_free_vma:
2720         vm_area_free(new);
2721         return err;
2722 }
2723
2724 /*
2725  * Split a vma into two pieces at address 'addr', a new vma is allocated
2726  * either for the first part or the tail.
2727  */
2728 int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
2729               unsigned long addr, int new_below)
2730 {
2731         if (mm->map_count >= sysctl_max_map_count)
2732                 return -ENOMEM;
2733
2734         return __split_vma(mm, vma, addr, new_below);
2735 }
2736
2737 /* Munmap is split into 2 main parts -- this part which finds
2738  * what needs doing, and the areas themselves, which do the
2739  * work.  This now handles partial unmappings.
2740  * Jeremy Fitzhardinge <jeremy@goop.org>
2741  */
2742 int __do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2743                 struct list_head *uf, bool downgrade)
2744 {
2745         unsigned long end;
2746         struct vm_area_struct *vma, *prev, *last;
2747
2748         if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2749                 return -EINVAL;
2750
2751         len = PAGE_ALIGN(len);
2752         end = start + len;
2753         if (len == 0)
2754                 return -EINVAL;
2755
2756         /*
2757          * arch_unmap() might do unmaps itself.  It must be called
2758          * and finish any rbtree manipulation before this code
2759          * runs and also starts to manipulate the rbtree.
2760          */
2761         arch_unmap(mm, start, end);
2762
2763         /* Find the first overlapping VMA */
2764         vma = find_vma(mm, start);
2765         if (!vma)
2766                 return 0;
2767         prev = vma->vm_prev;
2768         /* we have  start < vma->vm_end  */
2769
2770         /* if it doesn't overlap, we have nothing.. */
2771         if (vma->vm_start >= end)
2772                 return 0;
2773
2774         /*
2775          * If we need to split any vma, do it now to save pain later.
2776          *
2777          * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2778          * unmapped vm_area_struct will remain in use: so lower split_vma
2779          * places tmp vma above, and higher split_vma places tmp vma below.
2780          */
2781         if (start > vma->vm_start) {
2782                 int error;
2783
2784                 /*
2785                  * Make sure that map_count on return from munmap() will
2786                  * not exceed its limit; but let map_count go just above
2787                  * its limit temporarily, to help free resources as expected.
2788                  */
2789                 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
2790                         return -ENOMEM;
2791
2792                 error = __split_vma(mm, vma, start, 0);
2793                 if (error)
2794                         return error;
2795                 prev = vma;
2796         }
2797
2798         /* Does it split the last one? */
2799         last = find_vma(mm, end);
2800         if (last && end > last->vm_start) {
2801                 int error = __split_vma(mm, last, end, 1);
2802                 if (error)
2803                         return error;
2804         }
2805         vma = prev ? prev->vm_next : mm->mmap;
2806
2807         if (unlikely(uf)) {
2808                 /*
2809                  * If userfaultfd_unmap_prep returns an error the vmas
2810                  * will remain splitted, but userland will get a
2811                  * highly unexpected error anyway. This is no
2812                  * different than the case where the first of the two
2813                  * __split_vma fails, but we don't undo the first
2814                  * split, despite we could. This is unlikely enough
2815                  * failure that it's not worth optimizing it for.
2816                  */
2817                 int error = userfaultfd_unmap_prep(vma, start, end, uf);
2818                 if (error)
2819                         return error;
2820         }
2821
2822         /*
2823          * unlock any mlock()ed ranges before detaching vmas
2824          */
2825         if (mm->locked_vm) {
2826                 struct vm_area_struct *tmp = vma;
2827                 while (tmp && tmp->vm_start < end) {
2828                         if (tmp->vm_flags & VM_LOCKED) {
2829                                 mm->locked_vm -= vma_pages(tmp);
2830                                 munlock_vma_pages_all(tmp);
2831                         }
2832
2833                         tmp = tmp->vm_next;
2834                 }
2835         }
2836
2837         /* Detach vmas from rbtree */
2838         detach_vmas_to_be_unmapped(mm, vma, prev, end);
2839
2840         if (downgrade)
2841                 downgrade_write(&mm->mmap_sem);
2842
2843         unmap_region(mm, vma, prev, start, end);
2844
2845         /* Fix up all other VM information */
2846         remove_vma_list(mm, vma);
2847
2848         return downgrade ? 1 : 0;
2849 }
2850
2851 int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2852               struct list_head *uf)
2853 {
2854         return __do_munmap(mm, start, len, uf, false);
2855 }
2856
2857 static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
2858 {
2859         int ret;
2860         struct mm_struct *mm = current->mm;
2861         LIST_HEAD(uf);
2862
2863         if (down_write_killable(&mm->mmap_sem))
2864                 return -EINTR;
2865
2866         ret = __do_munmap(mm, start, len, &uf, downgrade);
2867         /*
2868          * Returning 1 indicates mmap_sem is downgraded.
2869          * But 1 is not legal return value of vm_munmap() and munmap(), reset
2870          * it to 0 before return.
2871          */
2872         if (ret == 1) {
2873                 up_read(&mm->mmap_sem);
2874                 ret = 0;
2875         } else
2876                 up_write(&mm->mmap_sem);
2877
2878         userfaultfd_unmap_complete(mm, &uf);
2879         return ret;
2880 }
2881
2882 int vm_munmap(unsigned long start, size_t len)
2883 {
2884         return __vm_munmap(start, len, false);
2885 }
2886 EXPORT_SYMBOL(vm_munmap);
2887
2888 SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2889 {
2890         addr = untagged_addr(addr);
2891         profile_munmap(addr);
2892         return __vm_munmap(addr, len, true);
2893 }
2894
2895
2896 /*
2897  * Emulation of deprecated remap_file_pages() syscall.
2898  */
2899 SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2900                 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2901 {
2902
2903         struct mm_struct *mm = current->mm;
2904         struct vm_area_struct *vma;
2905         unsigned long populate = 0;
2906         unsigned long ret = -EINVAL;
2907         struct file *file;
2908
2909         pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/vm/remap_file_pages.rst.\n",
2910                      current->comm, current->pid);
2911
2912         if (prot)
2913                 return ret;
2914         start = start & PAGE_MASK;
2915         size = size & PAGE_MASK;
2916
2917         if (start + size <= start)
2918                 return ret;
2919
2920         /* Does pgoff wrap? */
2921         if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2922                 return ret;
2923
2924         if (down_write_killable(&mm->mmap_sem))
2925                 return -EINTR;
2926
2927         vma = find_vma(mm, start);
2928
2929         if (!vma || !(vma->vm_flags & VM_SHARED))
2930                 goto out;
2931
2932         if (start < vma->vm_start)
2933                 goto out;
2934
2935         if (start + size > vma->vm_end) {
2936                 struct vm_area_struct *next;
2937
2938                 for (next = vma->vm_next; next; next = next->vm_next) {
2939                         /* hole between vmas ? */
2940                         if (next->vm_start != next->vm_prev->vm_end)
2941                                 goto out;
2942
2943                         if (next->vm_file != vma->vm_file)
2944                                 goto out;
2945
2946                         if (next->vm_flags != vma->vm_flags)
2947                                 goto out;
2948
2949                         if (start + size <= next->vm_end)
2950                                 break;
2951                 }
2952
2953                 if (!next)
2954                         goto out;
2955         }
2956
2957         prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2958         prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2959         prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2960
2961         flags &= MAP_NONBLOCK;
2962         flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
2963         if (vma->vm_flags & VM_LOCKED) {
2964                 struct vm_area_struct *tmp;
2965                 flags |= MAP_LOCKED;
2966
2967                 /* drop PG_Mlocked flag for over-mapped range */
2968                 for (tmp = vma; tmp->vm_start >= start + size;
2969                                 tmp = tmp->vm_next) {
2970                         /*
2971                          * Split pmd and munlock page on the border
2972                          * of the range.
2973                          */
2974                         vma_adjust_trans_huge(tmp, start, start + size, 0);
2975
2976                         munlock_vma_pages_range(tmp,
2977                                         max(tmp->vm_start, start),
2978                                         min(tmp->vm_end, start + size));
2979                 }
2980         }
2981
2982         file = get_file(vma->vm_file);
2983         ret = do_mmap_pgoff(vma->vm_file, start, size,
2984                         prot, flags, pgoff, &populate, NULL);
2985         fput(file);
2986 out:
2987         up_write(&mm->mmap_sem);
2988         if (populate)
2989                 mm_populate(ret, populate);
2990         if (!IS_ERR_VALUE(ret))
2991                 ret = 0;
2992         return ret;
2993 }
2994
2995 /*
2996  *  this is really a simplified "do_mmap".  it only handles
2997  *  anonymous maps.  eventually we may be able to do some
2998  *  brk-specific accounting here.
2999  */
3000 static int do_brk_flags(unsigned long addr, unsigned long len, unsigned long flags, struct list_head *uf)
3001 {
3002         struct mm_struct *mm = current->mm;
3003         struct vm_area_struct *vma, *prev;
3004         struct rb_node **rb_link, *rb_parent;
3005         pgoff_t pgoff = addr >> PAGE_SHIFT;
3006         int error;
3007
3008         /* Until we need other flags, refuse anything except VM_EXEC. */
3009         if ((flags & (~VM_EXEC)) != 0)
3010                 return -EINVAL;
3011         flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
3012
3013         error = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
3014         if (offset_in_page(error))
3015                 return error;
3016
3017         error = mlock_future_check(mm, mm->def_flags, len);
3018         if (error)
3019                 return error;
3020
3021         /*
3022          * Clear old maps.  this also does some error checking for us
3023          */
3024         while (find_vma_links(mm, addr, addr + len, &prev, &rb_link,
3025                               &rb_parent)) {
3026                 if (do_munmap(mm, addr, len, uf))
3027                         return -ENOMEM;
3028         }
3029
3030         /* Check against address space limits *after* clearing old maps... */
3031         if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
3032                 return -ENOMEM;
3033
3034         if (mm->map_count > sysctl_max_map_count)
3035                 return -ENOMEM;
3036
3037         if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
3038                 return -ENOMEM;
3039
3040         /* Can we just expand an old private anonymous mapping? */
3041         vma = vma_merge(mm, prev, addr, addr + len, flags,
3042                         NULL, NULL, pgoff, NULL, NULL_VM_UFFD_CTX);
3043         if (vma)
3044                 goto out;
3045
3046         /*
3047          * create a vma struct for an anonymous mapping
3048          */
3049         vma = vm_area_alloc(mm);
3050         if (!vma) {
3051                 vm_unacct_memory(len >> PAGE_SHIFT);
3052                 return -ENOMEM;
3053         }
3054
3055         vma_set_anonymous(vma);
3056         vma->vm_start = addr;
3057         vma->vm_end = addr + len;
3058         vma->vm_pgoff = pgoff;
3059         vma->vm_flags = flags;
3060         vma->vm_page_prot = vm_get_page_prot(flags);
3061         vma_link(mm, vma, prev, rb_link, rb_parent);
3062 out:
3063         perf_event_mmap(vma);
3064         mm->total_vm += len >> PAGE_SHIFT;
3065         mm->data_vm += len >> PAGE_SHIFT;
3066         if (flags & VM_LOCKED)
3067                 mm->locked_vm += (len >> PAGE_SHIFT);
3068         vma->vm_flags |= VM_SOFTDIRTY;
3069         return 0;
3070 }
3071
3072 int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
3073 {
3074         struct mm_struct *mm = current->mm;
3075         unsigned long len;
3076         int ret;
3077         bool populate;
3078         LIST_HEAD(uf);
3079
3080         len = PAGE_ALIGN(request);
3081         if (len < request)
3082                 return -ENOMEM;
3083         if (!len)
3084                 return 0;
3085
3086         if (down_write_killable(&mm->mmap_sem))
3087                 return -EINTR;
3088
3089         ret = do_brk_flags(addr, len, flags, &uf);
3090         populate = ((mm->def_flags & VM_LOCKED) != 0);
3091         up_write(&mm->mmap_sem);
3092         userfaultfd_unmap_complete(mm, &uf);
3093         if (populate && !ret)
3094                 mm_populate(addr, len);
3095         return ret;
3096 }
3097 EXPORT_SYMBOL(vm_brk_flags);
3098
3099 int vm_brk(unsigned long addr, unsigned long len)
3100 {
3101         return vm_brk_flags(addr, len, 0);
3102 }
3103 EXPORT_SYMBOL(vm_brk);
3104
3105 /* Release all mmaps. */
3106 void exit_mmap(struct mm_struct *mm)
3107 {
3108         struct mmu_gather tlb;
3109         struct vm_area_struct *vma;
3110         unsigned long nr_accounted = 0;
3111
3112         /* mm's last user has gone, and its about to be pulled down */
3113         mmu_notifier_release(mm);
3114
3115         if (unlikely(mm_is_oom_victim(mm))) {
3116                 /*
3117                  * Manually reap the mm to free as much memory as possible.
3118                  * Then, as the oom reaper does, set MMF_OOM_SKIP to disregard
3119                  * this mm from further consideration.  Taking mm->mmap_sem for
3120                  * write after setting MMF_OOM_SKIP will guarantee that the oom
3121                  * reaper will not run on this mm again after mmap_sem is
3122                  * dropped.
3123                  *
3124                  * Nothing can be holding mm->mmap_sem here and the above call
3125                  * to mmu_notifier_release(mm) ensures mmu notifier callbacks in
3126                  * __oom_reap_task_mm() will not block.
3127                  *
3128                  * This needs to be done before calling munlock_vma_pages_all(),
3129                  * which clears VM_LOCKED, otherwise the oom reaper cannot
3130                  * reliably test it.
3131                  */
3132                 (void)__oom_reap_task_mm(mm);
3133
3134                 set_bit(MMF_OOM_SKIP, &mm->flags);
3135                 down_write(&mm->mmap_sem);
3136                 up_write(&mm->mmap_sem);
3137         }
3138
3139         if (mm->locked_vm) {
3140                 vma = mm->mmap;
3141                 while (vma) {
3142                         if (vma->vm_flags & VM_LOCKED)
3143                                 munlock_vma_pages_all(vma);
3144                         vma = vma->vm_next;
3145                 }
3146         }
3147
3148         arch_exit_mmap(mm);
3149
3150         vma = mm->mmap;
3151         if (!vma)       /* Can happen if dup_mmap() received an OOM */
3152                 return;
3153
3154         lru_add_drain();
3155         flush_cache_mm(mm);
3156         tlb_gather_mmu(&tlb, mm, 0, -1);
3157         /* update_hiwater_rss(mm) here? but nobody should be looking */
3158         /* Use -1 here to ensure all VMAs in the mm are unmapped */
3159         unmap_vmas(&tlb, vma, 0, -1);
3160         free_pgtables(&tlb, vma, FIRST_USER_ADDRESS, USER_PGTABLES_CEILING);
3161         tlb_finish_mmu(&tlb, 0, -1);
3162
3163         /*
3164          * Walk the list again, actually closing and freeing it,
3165          * with preemption enabled, without holding any MM locks.
3166          */
3167         while (vma) {
3168                 if (vma->vm_flags & VM_ACCOUNT)
3169                         nr_accounted += vma_pages(vma);
3170                 vma = remove_vma(vma);
3171         }
3172         vm_unacct_memory(nr_accounted);
3173 }
3174
3175 /* Insert vm structure into process list sorted by address
3176  * and into the inode's i_mmap tree.  If vm_file is non-NULL
3177  * then i_mmap_rwsem is taken here.
3178  */
3179 int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
3180 {
3181         struct vm_area_struct *prev;
3182         struct rb_node **rb_link, *rb_parent;
3183
3184         if (find_vma_links(mm, vma->vm_start, vma->vm_end,
3185                            &prev, &rb_link, &rb_parent))
3186                 return -ENOMEM;
3187         if ((vma->vm_flags & VM_ACCOUNT) &&
3188              security_vm_enough_memory_mm(mm, vma_pages(vma)))
3189                 return -ENOMEM;
3190
3191         /*
3192          * The vm_pgoff of a purely anonymous vma should be irrelevant
3193          * until its first write fault, when page's anon_vma and index
3194          * are set.  But now set the vm_pgoff it will almost certainly
3195          * end up with (unless mremap moves it elsewhere before that
3196          * first wfault), so /proc/pid/maps tells a consistent story.
3197          *
3198          * By setting it to reflect the virtual start address of the
3199          * vma, merges and splits can happen in a seamless way, just
3200          * using the existing file pgoff checks and manipulations.
3201          * Similarly in do_mmap_pgoff and in do_brk.
3202          */
3203         if (vma_is_anonymous(vma)) {
3204                 BUG_ON(vma->anon_vma);
3205                 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3206         }
3207
3208         vma_link(mm, vma, prev, rb_link, rb_parent);
3209         return 0;
3210 }
3211
3212 /*
3213  * Copy the vma structure to a new location in the same mm,
3214  * prior to moving page table entries, to effect an mremap move.
3215  */
3216 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
3217         unsigned long addr, unsigned long len, pgoff_t pgoff,
3218         bool *need_rmap_locks)
3219 {
3220         struct vm_area_struct *vma = *vmap;
3221         unsigned long vma_start = vma->vm_start;
3222         struct mm_struct *mm = vma->vm_mm;
3223         struct vm_area_struct *new_vma, *prev;
3224         struct rb_node **rb_link, *rb_parent;
3225         bool faulted_in_anon_vma = true;
3226
3227         /*
3228          * If anonymous vma has not yet been faulted, update new pgoff
3229          * to match new location, to increase its chance of merging.
3230          */
3231         if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
3232                 pgoff = addr >> PAGE_SHIFT;
3233                 faulted_in_anon_vma = false;
3234         }
3235
3236         if (find_vma_links(mm, addr, addr + len, &prev, &rb_link, &rb_parent))
3237                 return NULL;    /* should never get here */
3238         new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
3239                             vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
3240                             vma->vm_userfaultfd_ctx);
3241         if (new_vma) {
3242                 /*
3243                  * Source vma may have been merged into new_vma
3244                  */
3245                 if (unlikely(vma_start >= new_vma->vm_start &&
3246                              vma_start < new_vma->vm_end)) {
3247                         /*
3248                          * The only way we can get a vma_merge with
3249                          * self during an mremap is if the vma hasn't
3250                          * been faulted in yet and we were allowed to
3251                          * reset the dst vma->vm_pgoff to the
3252                          * destination address of the mremap to allow
3253                          * the merge to happen. mremap must change the
3254                          * vm_pgoff linearity between src and dst vmas
3255                          * (in turn preventing a vma_merge) to be
3256                          * safe. It is only safe to keep the vm_pgoff
3257                          * linear if there are no pages mapped yet.
3258                          */
3259                         VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
3260                         *vmap = vma = new_vma;
3261                 }
3262                 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
3263         } else {
3264                 new_vma = vm_area_dup(vma);
3265                 if (!new_vma)
3266                         goto out;
3267                 new_vma->vm_start = addr;
3268                 new_vma->vm_end = addr + len;
3269                 new_vma->vm_pgoff = pgoff;
3270                 if (vma_dup_policy(vma, new_vma))
3271                         goto out_free_vma;
3272                 if (anon_vma_clone(new_vma, vma))
3273                         goto out_free_mempol;
3274                 if (new_vma->vm_file)
3275                         get_file(new_vma->vm_file);
3276                 if (new_vma->vm_ops && new_vma->vm_ops->open)
3277                         new_vma->vm_ops->open(new_vma);
3278                 vma_link(mm, new_vma, prev, rb_link, rb_parent);
3279                 *need_rmap_locks = false;
3280         }
3281         return new_vma;
3282
3283 out_free_mempol:
3284         mpol_put(vma_policy(new_vma));
3285 out_free_vma:
3286         vm_area_free(new_vma);
3287 out:
3288         return NULL;
3289 }
3290
3291 /*
3292  * Return true if the calling process may expand its vm space by the passed
3293  * number of pages
3294  */
3295 bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
3296 {
3297         if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3298                 return false;
3299
3300         if (is_data_mapping(flags) &&
3301             mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
3302                 /* Workaround for Valgrind */
3303                 if (rlimit(RLIMIT_DATA) == 0 &&
3304                     mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3305                         return true;
3306
3307                 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3308                              current->comm, current->pid,
3309                              (mm->data_vm + npages) << PAGE_SHIFT,
3310                              rlimit(RLIMIT_DATA),
3311                              ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3312
3313                 if (!ignore_rlimit_data)
3314                         return false;
3315         }
3316
3317         return true;
3318 }
3319
3320 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3321 {
3322         mm->total_vm += npages;
3323
3324         if (is_exec_mapping(flags))
3325                 mm->exec_vm += npages;
3326         else if (is_stack_mapping(flags))
3327                 mm->stack_vm += npages;
3328         else if (is_data_mapping(flags))
3329                 mm->data_vm += npages;
3330 }
3331
3332 static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
3333
3334 /*
3335  * Having a close hook prevents vma merging regardless of flags.
3336  */
3337 static void special_mapping_close(struct vm_area_struct *vma)
3338 {
3339 }
3340
3341 static const char *special_mapping_name(struct vm_area_struct *vma)
3342 {
3343         return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3344 }
3345
3346 static int special_mapping_mremap(struct vm_area_struct *new_vma)
3347 {
3348         struct vm_special_mapping *sm = new_vma->vm_private_data;
3349
3350         if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3351                 return -EFAULT;
3352
3353         if (sm->mremap)
3354                 return sm->mremap(sm, new_vma);
3355
3356         return 0;
3357 }
3358
3359 static const struct vm_operations_struct special_mapping_vmops = {
3360         .close = special_mapping_close,
3361         .fault = special_mapping_fault,
3362         .mremap = special_mapping_mremap,
3363         .name = special_mapping_name,
3364 };
3365
3366 static const struct vm_operations_struct legacy_special_mapping_vmops = {
3367         .close = special_mapping_close,
3368         .fault = special_mapping_fault,
3369 };
3370
3371 static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
3372 {
3373         struct vm_area_struct *vma = vmf->vma;
3374         pgoff_t pgoff;
3375         struct page **pages;
3376
3377         if (vma->vm_ops == &legacy_special_mapping_vmops) {
3378                 pages = vma->vm_private_data;
3379         } else {
3380                 struct vm_special_mapping *sm = vma->vm_private_data;
3381
3382                 if (sm->fault)
3383                         return sm->fault(sm, vmf->vma, vmf);
3384
3385                 pages = sm->pages;
3386         }
3387
3388         for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
3389                 pgoff--;
3390
3391         if (*pages) {
3392                 struct page *page = *pages;
3393                 get_page(page);
3394                 vmf->page = page;
3395                 return 0;
3396         }
3397
3398         return VM_FAULT_SIGBUS;
3399 }
3400
3401 static struct vm_area_struct *__install_special_mapping(
3402         struct mm_struct *mm,
3403         unsigned long addr, unsigned long len,
3404         unsigned long vm_flags, void *priv,
3405         const struct vm_operations_struct *ops)
3406 {
3407         int ret;
3408         struct vm_area_struct *vma;
3409
3410         vma = vm_area_alloc(mm);
3411         if (unlikely(vma == NULL))
3412                 return ERR_PTR(-ENOMEM);
3413
3414         vma->vm_start = addr;
3415         vma->vm_end = addr + len;
3416
3417         vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
3418         vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
3419
3420         vma->vm_ops = ops;
3421         vma->vm_private_data = priv;
3422
3423         ret = insert_vm_struct(mm, vma);
3424         if (ret)
3425                 goto out;
3426
3427         vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
3428
3429         perf_event_mmap(vma);
3430
3431         return vma;
3432
3433 out:
3434         vm_area_free(vma);
3435         return ERR_PTR(ret);
3436 }
3437
3438 bool vma_is_special_mapping(const struct vm_area_struct *vma,
3439         const struct vm_special_mapping *sm)
3440 {
3441         return vma->vm_private_data == sm &&
3442                 (vma->vm_ops == &special_mapping_vmops ||
3443                  vma->vm_ops == &legacy_special_mapping_vmops);
3444 }
3445
3446 /*
3447  * Called with mm->mmap_sem held for writing.
3448  * Insert a new vma covering the given region, with the given flags.
3449  * Its pages are supplied by the given array of struct page *.
3450  * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3451  * The region past the last page supplied will always produce SIGBUS.
3452  * The array pointer and the pages it points to are assumed to stay alive
3453  * for as long as this mapping might exist.
3454  */
3455 struct vm_area_struct *_install_special_mapping(
3456         struct mm_struct *mm,
3457         unsigned long addr, unsigned long len,
3458         unsigned long vm_flags, const struct vm_special_mapping *spec)
3459 {
3460         return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3461                                         &special_mapping_vmops);
3462 }
3463
3464 int install_special_mapping(struct mm_struct *mm,
3465                             unsigned long addr, unsigned long len,
3466                             unsigned long vm_flags, struct page **pages)
3467 {
3468         struct vm_area_struct *vma = __install_special_mapping(
3469                 mm, addr, len, vm_flags, (void *)pages,
3470                 &legacy_special_mapping_vmops);
3471
3472         return PTR_ERR_OR_ZERO(vma);
3473 }
3474
3475 static DEFINE_MUTEX(mm_all_locks_mutex);
3476
3477 static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
3478 {
3479         if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3480                 /*
3481                  * The LSB of head.next can't change from under us
3482                  * because we hold the mm_all_locks_mutex.
3483                  */
3484                 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_sem);
3485                 /*
3486                  * We can safely modify head.next after taking the
3487                  * anon_vma->root->rwsem. If some other vma in this mm shares
3488                  * the same anon_vma we won't take it again.
3489                  *
3490                  * No need of atomic instructions here, head.next
3491                  * can't change from under us thanks to the
3492                  * anon_vma->root->rwsem.
3493                  */
3494                 if (__test_and_set_bit(0, (unsigned long *)
3495                                        &anon_vma->root->rb_root.rb_root.rb_node))
3496                         BUG();
3497         }
3498 }
3499
3500 static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
3501 {
3502         if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3503                 /*
3504                  * AS_MM_ALL_LOCKS can't change from under us because
3505                  * we hold the mm_all_locks_mutex.
3506                  *
3507                  * Operations on ->flags have to be atomic because
3508                  * even if AS_MM_ALL_LOCKS is stable thanks to the
3509                  * mm_all_locks_mutex, there may be other cpus
3510                  * changing other bitflags in parallel to us.
3511                  */
3512                 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3513                         BUG();
3514                 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_sem);
3515         }
3516 }
3517
3518 /*
3519  * This operation locks against the VM for all pte/vma/mm related
3520  * operations that could ever happen on a certain mm. This includes
3521  * vmtruncate, try_to_unmap, and all page faults.
3522  *
3523  * The caller must take the mmap_sem in write mode before calling
3524  * mm_take_all_locks(). The caller isn't allowed to release the
3525  * mmap_sem until mm_drop_all_locks() returns.
3526  *
3527  * mmap_sem in write mode is required in order to block all operations
3528  * that could modify pagetables and free pages without need of
3529  * altering the vma layout. It's also needed in write mode to avoid new
3530  * anon_vmas to be associated with existing vmas.
3531  *
3532  * A single task can't take more than one mm_take_all_locks() in a row
3533  * or it would deadlock.
3534  *
3535  * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
3536  * mapping->flags avoid to take the same lock twice, if more than one
3537  * vma in this mm is backed by the same anon_vma or address_space.
3538  *
3539  * We take locks in following order, accordingly to comment at beginning
3540  * of mm/rmap.c:
3541  *   - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3542  *     hugetlb mapping);
3543  *   - all i_mmap_rwsem locks;
3544  *   - all anon_vma->rwseml
3545  *
3546  * We can take all locks within these types randomly because the VM code
3547  * doesn't nest them and we protected from parallel mm_take_all_locks() by
3548  * mm_all_locks_mutex.
3549  *
3550  * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3551  * that may have to take thousand of locks.
3552  *
3553  * mm_take_all_locks() can fail if it's interrupted by signals.
3554  */
3555 int mm_take_all_locks(struct mm_struct *mm)
3556 {
3557         struct vm_area_struct *vma;
3558         struct anon_vma_chain *avc;
3559
3560         BUG_ON(down_read_trylock(&mm->mmap_sem));
3561
3562         mutex_lock(&mm_all_locks_mutex);
3563
3564         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3565                 if (signal_pending(current))
3566                         goto out_unlock;
3567                 if (vma->vm_file && vma->vm_file->f_mapping &&
3568                                 is_vm_hugetlb_page(vma))
3569                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3570         }
3571
3572         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3573                 if (signal_pending(current))
3574                         goto out_unlock;
3575                 if (vma->vm_file && vma->vm_file->f_mapping &&
3576                                 !is_vm_hugetlb_page(vma))
3577                         vm_lock_mapping(mm, vma->vm_file->f_mapping);
3578         }
3579
3580         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3581                 if (signal_pending(current))
3582                         goto out_unlock;
3583                 if (vma->anon_vma)
3584                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3585                                 vm_lock_anon_vma(mm, avc->anon_vma);
3586         }
3587
3588         return 0;
3589
3590 out_unlock:
3591         mm_drop_all_locks(mm);
3592         return -EINTR;
3593 }
3594
3595 static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3596 {
3597         if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
3598                 /*
3599                  * The LSB of head.next can't change to 0 from under
3600                  * us because we hold the mm_all_locks_mutex.
3601                  *
3602                  * We must however clear the bitflag before unlocking
3603                  * the vma so the users using the anon_vma->rb_root will
3604                  * never see our bitflag.
3605                  *
3606                  * No need of atomic instructions here, head.next
3607                  * can't change from under us until we release the
3608                  * anon_vma->root->rwsem.
3609                  */
3610                 if (!__test_and_clear_bit(0, (unsigned long *)
3611                                           &anon_vma->root->rb_root.rb_root.rb_node))
3612                         BUG();
3613                 anon_vma_unlock_write(anon_vma);
3614         }
3615 }
3616
3617 static void vm_unlock_mapping(struct address_space *mapping)
3618 {
3619         if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3620                 /*
3621                  * AS_MM_ALL_LOCKS can't change to 0 from under us
3622                  * because we hold the mm_all_locks_mutex.
3623                  */
3624                 i_mmap_unlock_write(mapping);
3625                 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3626                                         &mapping->flags))
3627                         BUG();
3628         }
3629 }
3630
3631 /*
3632  * The mmap_sem cannot be released by the caller until
3633  * mm_drop_all_locks() returns.
3634  */
3635 void mm_drop_all_locks(struct mm_struct *mm)
3636 {
3637         struct vm_area_struct *vma;
3638         struct anon_vma_chain *avc;
3639
3640         BUG_ON(down_read_trylock(&mm->mmap_sem));
3641         BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3642
3643         for (vma = mm->mmap; vma; vma = vma->vm_next) {
3644                 if (vma->anon_vma)
3645                         list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3646                                 vm_unlock_anon_vma(avc->anon_vma);
3647                 if (vma->vm_file && vma->vm_file->f_mapping)
3648                         vm_unlock_mapping(vma->vm_file->f_mapping);
3649         }
3650
3651         mutex_unlock(&mm_all_locks_mutex);
3652 }
3653
3654 /*
3655  * initialise the percpu counter for VM
3656  */
3657 void __init mmap_init(void)
3658 {
3659         int ret;
3660
3661         ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
3662         VM_BUG_ON(ret);
3663 }
3664
3665 /*
3666  * Initialise sysctl_user_reserve_kbytes.
3667  *
3668  * This is intended to prevent a user from starting a single memory hogging
3669  * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3670  * mode.
3671  *
3672  * The default value is min(3% of free memory, 128MB)
3673  * 128MB is enough to recover with sshd/login, bash, and top/kill.
3674  */
3675 static int init_user_reserve(void)
3676 {
3677         unsigned long free_kbytes;
3678
3679         free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3680
3681         sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3682         return 0;
3683 }
3684 subsys_initcall(init_user_reserve);
3685
3686 /*
3687  * Initialise sysctl_admin_reserve_kbytes.
3688  *
3689  * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3690  * to log in and kill a memory hogging process.
3691  *
3692  * Systems with more than 256MB will reserve 8MB, enough to recover
3693  * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3694  * only reserve 3% of free pages by default.
3695  */
3696 static int init_admin_reserve(void)
3697 {
3698         unsigned long free_kbytes;
3699
3700         free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3701
3702         sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3703         return 0;
3704 }
3705 subsys_initcall(init_admin_reserve);
3706
3707 /*
3708  * Reinititalise user and admin reserves if memory is added or removed.
3709  *
3710  * The default user reserve max is 128MB, and the default max for the
3711  * admin reserve is 8MB. These are usually, but not always, enough to
3712  * enable recovery from a memory hogging process using login/sshd, a shell,
3713  * and tools like top. It may make sense to increase or even disable the
3714  * reserve depending on the existence of swap or variations in the recovery
3715  * tools. So, the admin may have changed them.
3716  *
3717  * If memory is added and the reserves have been eliminated or increased above
3718  * the default max, then we'll trust the admin.
3719  *
3720  * If memory is removed and there isn't enough free memory, then we
3721  * need to reset the reserves.
3722  *
3723  * Otherwise keep the reserve set by the admin.
3724  */
3725 static int reserve_mem_notifier(struct notifier_block *nb,
3726                              unsigned long action, void *data)
3727 {
3728         unsigned long tmp, free_kbytes;
3729
3730         switch (action) {
3731         case MEM_ONLINE:
3732                 /* Default max is 128MB. Leave alone if modified by operator. */
3733                 tmp = sysctl_user_reserve_kbytes;
3734                 if (0 < tmp && tmp < (1UL << 17))
3735                         init_user_reserve();
3736
3737                 /* Default max is 8MB.  Leave alone if modified by operator. */
3738                 tmp = sysctl_admin_reserve_kbytes;
3739                 if (0 < tmp && tmp < (1UL << 13))
3740                         init_admin_reserve();
3741
3742                 break;
3743         case MEM_OFFLINE:
3744                 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
3745
3746                 if (sysctl_user_reserve_kbytes > free_kbytes) {
3747                         init_user_reserve();
3748                         pr_info("vm.user_reserve_kbytes reset to %lu\n",
3749                                 sysctl_user_reserve_kbytes);
3750                 }
3751
3752                 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3753                         init_admin_reserve();
3754                         pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3755                                 sysctl_admin_reserve_kbytes);
3756                 }
3757                 break;
3758         default:
3759                 break;
3760         }
3761         return NOTIFY_OK;
3762 }
3763
3764 static struct notifier_block reserve_mem_nb = {
3765         .notifier_call = reserve_mem_notifier,
3766 };
3767
3768 static int __meminit init_reserve_notifier(void)
3769 {
3770         if (register_hotmemory_notifier(&reserve_mem_nb))
3771                 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
3772
3773         return 0;
3774 }
3775 subsys_initcall(init_reserve_notifier);