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