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