OSDN Git Service

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