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