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