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