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