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