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