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