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