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