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