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