]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/mmap.c
mm/mmap: remove preallocation from do_mas_align_munmap()
[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{
79e4f2ca 490 VMA_ITERATOR(vmi, mm, 0);
1da177e4
LT
491 struct address_space *mapping = NULL;
492
79e4f2ca 493 if (vma_iter_prealloc(&vmi))
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
79e4f2ca 501 vma_iter_store(&vmi, vma);
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
11f9a21a 2332 mas->last = end - 1;
1da177e4
LT
2333 /*
2334 * If we need to split any vma, do it now to save pain later.
2335 *
2336 * Note: mremap's move_vma VM_ACCOUNT handling assumes a partially
2337 * unmapped vm_area_struct will remain in use: so lower split_vma
2338 * places tmp vma above, and higher split_vma places tmp vma below.
2339 */
763ecb03
LH
2340
2341 /* Does it split the first one? */
146425a3 2342 if (start > vma->vm_start) {
659ace58
KM
2343
2344 /*
2345 * Make sure that map_count on return from munmap() will
2346 * not exceed its limit; but let map_count go just above
2347 * its limit temporarily, to help free resources as expected.
2348 */
2349 if (end < vma->vm_end && mm->map_count >= sysctl_max_map_count)
d4af56c5 2350 goto map_count_exceeded;
659ace58 2351
763ecb03
LH
2352 /*
2353 * mas_pause() is not needed since mas->index needs to be set
2354 * differently than vma->vm_end anyways.
2355 */
659ace58 2356 error = __split_vma(mm, vma, start, 0);
1da177e4 2357 if (error)
763ecb03 2358 goto start_split_failed;
11f9a21a 2359
763ecb03
LH
2360 mas_set(mas, start);
2361 vma = mas_walk(mas);
1da177e4
LT
2362 }
2363
763ecb03
LH
2364 prev = mas_prev(mas, 0);
2365 if (unlikely((!prev)))
2366 mas_set(mas, start);
2367
2368 /*
2369 * Detach a range of VMAs from the mm. Using next as a temp variable as
2370 * it is always overwritten.
2371 */
2372 mas_for_each(mas, next, end - 1) {
2373 /* Does it split the end? */
2374 if (next->vm_end > end) {
2375 struct vm_area_struct *split;
2376
2377 error = __split_vma(mm, next, end, 1);
2378 if (error)
2379 goto end_split_failed;
11f9a21a 2380
763ecb03
LH
2381 mas_set(mas, end);
2382 split = mas_prev(mas, 0);
2383 error = munmap_sidetree(split, &mas_detach);
2384 if (error)
2385 goto munmap_sidetree_failed;
11f9a21a 2386
763ecb03
LH
2387 count++;
2388 if (vma == next)
2389 vma = split;
2390 break;
2391 }
2392 error = munmap_sidetree(next, &mas_detach);
1da177e4 2393 if (error)
763ecb03 2394 goto munmap_sidetree_failed;
11f9a21a 2395
763ecb03
LH
2396 count++;
2397#ifdef CONFIG_DEBUG_VM_MAPLE_TREE
2398 BUG_ON(next->vm_start < start);
2399 BUG_ON(next->vm_start > end);
2400#endif
1da177e4 2401 }
1da177e4 2402
763ecb03
LH
2403 if (!next)
2404 next = mas_next(mas, ULONG_MAX);
2405
2376dd7c
AA
2406 if (unlikely(uf)) {
2407 /*
2408 * If userfaultfd_unmap_prep returns an error the vmas
f0953a1b 2409 * will remain split, but userland will get a
2376dd7c
AA
2410 * highly unexpected error anyway. This is no
2411 * different than the case where the first of the two
2412 * __split_vma fails, but we don't undo the first
2413 * split, despite we could. This is unlikely enough
2414 * failure that it's not worth optimizing it for.
2415 */
69dbe6da 2416 error = userfaultfd_unmap_prep(mm, start, end, uf);
11f9a21a 2417
2376dd7c 2418 if (error)
d4af56c5 2419 goto userfaultfd_error;
2376dd7c
AA
2420 }
2421
763ecb03
LH
2422#if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
2423 /* Make sure no VMAs are about to be lost. */
2424 {
2425 MA_STATE(test, &mt_detach, start, end - 1);
2426 struct vm_area_struct *vma_mas, *vma_test;
2427 int test_count = 0;
2428
0378c0a0 2429 mas_set_range(mas, start, end - 1);
763ecb03
LH
2430 rcu_read_lock();
2431 vma_test = mas_find(&test, end - 1);
2432 mas_for_each(mas, vma_mas, end - 1) {
2433 BUG_ON(vma_mas != vma_test);
2434 test_count++;
2435 vma_test = mas_next(&test, end - 1);
2436 }
2437 rcu_read_unlock();
2438 BUG_ON(count != test_count);
763ecb03
LH
2439 }
2440#endif
0378c0a0
LH
2441 /* Point of no return */
2442 mas_set_range(mas, start, end - 1);
2443 if (mas_store_gfp(mas, NULL, GFP_KERNEL))
2444 return -ENOMEM;
2445
763ecb03 2446 mm->map_count -= count;
11f9a21a
LH
2447 /*
2448 * Do not downgrade mmap_lock if we are next to VM_GROWSDOWN or
2449 * VM_GROWSUP VMA. Such VMAs can change their size under
2450 * down_read(mmap_lock) and collide with the VMA we are about to unmap.
2451 */
2452 if (downgrade) {
763ecb03 2453 if (next && (next->vm_flags & VM_GROWSDOWN))
11f9a21a
LH
2454 downgrade = false;
2455 else if (prev && (prev->vm_flags & VM_GROWSUP))
2456 downgrade = false;
2457 else
2458 mmap_write_downgrade(mm);
2459 }
dd2283f2 2460
763ecb03
LH
2461 unmap_region(mm, &mt_detach, vma, prev, next, start, end);
2462 /* Statistics and freeing VMAs */
2463 mas_set(&mas_detach, start);
2464 remove_mt(mm, &mas_detach);
2465 __mt_destroy(&mt_detach);
1da177e4 2466
524e00b3
LH
2467
2468 validate_mm(mm);
dd2283f2 2469 return downgrade ? 1 : 0;
d4af56c5 2470
d4af56c5 2471userfaultfd_error:
763ecb03
LH
2472munmap_sidetree_failed:
2473end_split_failed:
2474 __mt_destroy(&mt_detach);
2475start_split_failed:
2476map_count_exceeded:
d4af56c5 2477 return error;
1da177e4 2478}
1da177e4 2479
11f9a21a
LH
2480/*
2481 * do_mas_munmap() - munmap a given range.
2482 * @mas: The maple state
2483 * @mm: The mm_struct
2484 * @start: The start address to munmap
2485 * @len: The length of the range to munmap
2486 * @uf: The userfaultfd list_head
2487 * @downgrade: set to true if the user wants to attempt to write_downgrade the
8651a137 2488 * mmap_lock
11f9a21a
LH
2489 *
2490 * This function takes a @mas that is either pointing to the previous VMA or set
2491 * to MA_START and sets it up to remove the mapping(s). The @len will be
2492 * aligned and any arch_unmap work will be preformed.
2493 *
2494 * Returns: -EINVAL on failure, 1 on success and unlock, 0 otherwise.
2495 */
2496int do_mas_munmap(struct ma_state *mas, struct mm_struct *mm,
2497 unsigned long start, size_t len, struct list_head *uf,
2498 bool downgrade)
2499{
2500 unsigned long end;
2501 struct vm_area_struct *vma;
2502
2503 if ((offset_in_page(start)) || start > TASK_SIZE || len > TASK_SIZE-start)
2504 return -EINVAL;
2505
2506 end = start + PAGE_ALIGN(len);
2507 if (end == start)
2508 return -EINVAL;
2509
2510 /* arch_unmap() might do unmaps itself. */
2511 arch_unmap(mm, start, end);
2512
2513 /* Find the first overlapping VMA */
2514 vma = mas_find(mas, end - 1);
2515 if (!vma)
2516 return 0;
2517
2518 return do_mas_align_munmap(mas, vma, mm, start, end, uf, downgrade);
2519}
2520
2521/* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
2522 * @mm: The mm_struct
2523 * @start: The start address to munmap
2524 * @len: The length to be munmapped.
2525 * @uf: The userfaultfd list_head
2526 */
dd2283f2
YS
2527int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
2528 struct list_head *uf)
2529{
11f9a21a
LH
2530 MA_STATE(mas, &mm->mm_mt, start, start);
2531
2532 return do_mas_munmap(&mas, mm, start, len, uf, false);
dd2283f2
YS
2533}
2534
e99668a5
LH
2535unsigned long mmap_region(struct file *file, unsigned long addr,
2536 unsigned long len, vm_flags_t vm_flags, unsigned long pgoff,
2537 struct list_head *uf)
2538{
2539 struct mm_struct *mm = current->mm;
2540 struct vm_area_struct *vma = NULL;
2541 struct vm_area_struct *next, *prev, *merge;
2542 pgoff_t pglen = len >> PAGE_SHIFT;
2543 unsigned long charged = 0;
2544 unsigned long end = addr + len;
2545 unsigned long merge_start = addr, merge_end = end;
2546 pgoff_t vm_pgoff;
2547 int error;
2548 MA_STATE(mas, &mm->mm_mt, addr, end - 1);
2549
2550 /* Check against address space limit. */
2551 if (!may_expand_vm(mm, vm_flags, len >> PAGE_SHIFT)) {
2552 unsigned long nr_pages;
2553
2554 /*
2555 * MAP_FIXED may remove pages of mappings that intersects with
2556 * requested mapping. Account for the pages it would unmap.
2557 */
2558 nr_pages = count_vma_pages_range(mm, addr, end);
2559
2560 if (!may_expand_vm(mm, vm_flags,
2561 (len >> PAGE_SHIFT) - nr_pages))
2562 return -ENOMEM;
2563 }
2564
2565 /* Unmap any existing mapping in the area */
11f9a21a 2566 if (do_mas_munmap(&mas, mm, addr, len, uf, false))
e99668a5
LH
2567 return -ENOMEM;
2568
2569 /*
2570 * Private writable mapping: check memory availability
2571 */
2572 if (accountable_mapping(file, vm_flags)) {
2573 charged = len >> PAGE_SHIFT;
2574 if (security_vm_enough_memory_mm(mm, charged))
2575 return -ENOMEM;
2576 vm_flags |= VM_ACCOUNT;
2577 }
2578
2579 next = mas_next(&mas, ULONG_MAX);
2580 prev = mas_prev(&mas, 0);
2581 if (vm_flags & VM_SPECIAL)
2582 goto cannot_expand;
2583
2584 /* Attempt to expand an old mapping */
2585 /* Check next */
2586 if (next && next->vm_start == end && !vma_policy(next) &&
2587 can_vma_merge_before(next, vm_flags, NULL, file, pgoff+pglen,
2588 NULL_VM_UFFD_CTX, NULL)) {
2589 merge_end = next->vm_end;
2590 vma = next;
2591 vm_pgoff = next->vm_pgoff - pglen;
2592 }
2593
2594 /* Check prev */
2595 if (prev && prev->vm_end == addr && !vma_policy(prev) &&
2596 (vma ? can_vma_merge_after(prev, vm_flags, vma->anon_vma, file,
2597 pgoff, vma->vm_userfaultfd_ctx, NULL) :
2598 can_vma_merge_after(prev, vm_flags, NULL, file, pgoff,
2599 NULL_VM_UFFD_CTX, NULL))) {
2600 merge_start = prev->vm_start;
2601 vma = prev;
2602 vm_pgoff = prev->vm_pgoff;
2603 }
2604
2605
2606 /* Actually expand, if possible */
2607 if (vma &&
2608 !vma_expand(&mas, vma, merge_start, merge_end, vm_pgoff, next)) {
2609 khugepaged_enter_vma(vma, vm_flags);
2610 goto expanded;
2611 }
2612
2613 mas.index = addr;
2614 mas.last = end - 1;
2615cannot_expand:
2616 /*
2617 * Determine the object being mapped and call the appropriate
2618 * specific mapper. the address has already been validated, but
2619 * not unmapped, but the maps are removed from the list.
2620 */
2621 vma = vm_area_alloc(mm);
2622 if (!vma) {
2623 error = -ENOMEM;
2624 goto unacct_error;
2625 }
2626
2627 vma->vm_start = addr;
2628 vma->vm_end = end;
2629 vma->vm_flags = vm_flags;
2630 vma->vm_page_prot = vm_get_page_prot(vm_flags);
2631 vma->vm_pgoff = pgoff;
2632
2633 if (file) {
2634 if (vm_flags & VM_SHARED) {
2635 error = mapping_map_writable(file->f_mapping);
2636 if (error)
2637 goto free_vma;
2638 }
2639
2640 vma->vm_file = get_file(file);
2641 error = call_mmap(file, vma);
2642 if (error)
2643 goto unmap_and_free_vma;
2644
a57b7051
LH
2645 /*
2646 * Expansion is handled above, merging is handled below.
2647 * Drivers should not alter the address of the VMA.
e99668a5 2648 */
a57b7051
LH
2649 if (WARN_ON((addr != vma->vm_start))) {
2650 error = -EINVAL;
2651 goto close_and_free_vma;
2652 }
e99668a5
LH
2653 mas_reset(&mas);
2654
2655 /*
2656 * If vm_flags changed after call_mmap(), we should try merge
2657 * vma again as we may succeed this time.
2658 */
2659 if (unlikely(vm_flags != vma->vm_flags && prev)) {
2660 merge = vma_merge(mm, prev, vma->vm_start, vma->vm_end, vma->vm_flags,
2661 NULL, vma->vm_file, vma->vm_pgoff, NULL, NULL_VM_UFFD_CTX, NULL);
2662 if (merge) {
2663 /*
2664 * ->mmap() can change vma->vm_file and fput
2665 * the original file. So fput the vma->vm_file
2666 * here or we would add an extra fput for file
2667 * and cause general protection fault
2668 * ultimately.
2669 */
2670 fput(vma->vm_file);
2671 vm_area_free(vma);
2672 vma = merge;
2673 /* Update vm_flags to pick up the change. */
e99668a5
LH
2674 vm_flags = vma->vm_flags;
2675 goto unmap_writable;
2676 }
2677 }
2678
2679 vm_flags = vma->vm_flags;
2680 } else if (vm_flags & VM_SHARED) {
2681 error = shmem_zero_setup(vma);
2682 if (error)
2683 goto free_vma;
2684 } else {
2685 vma_set_anonymous(vma);
2686 }
2687
b507808e
JG
2688 if (map_deny_write_exec(vma, vma->vm_flags)) {
2689 error = -EACCES;
2690 if (file)
2691 goto close_and_free_vma;
2692 else if (vma->vm_file)
2693 goto unmap_and_free_vma;
2694 else
2695 goto free_vma;
2696 }
2697
e99668a5
LH
2698 /* Allow architectures to sanity-check the vm_flags */
2699 if (!arch_validate_flags(vma->vm_flags)) {
2700 error = -EINVAL;
2701 if (file)
deb0f656 2702 goto close_and_free_vma;
cc674ab3
LZ
2703 else if (vma->vm_file)
2704 goto unmap_and_free_vma;
e99668a5
LH
2705 else
2706 goto free_vma;
2707 }
2708
c5d5546e 2709 if (mas_preallocate(&mas, GFP_KERNEL)) {
e99668a5
LH
2710 error = -ENOMEM;
2711 if (file)
5789151e 2712 goto close_and_free_vma;
cc674ab3
LZ
2713 else if (vma->vm_file)
2714 goto unmap_and_free_vma;
e99668a5
LH
2715 else
2716 goto free_vma;
2717 }
2718
2719 if (vma->vm_file)
2720 i_mmap_lock_write(vma->vm_file->f_mapping);
2721
2722 vma_mas_store(vma, &mas);
e99668a5
LH
2723 mm->map_count++;
2724 if (vma->vm_file) {
2725 if (vma->vm_flags & VM_SHARED)
2726 mapping_allow_writable(vma->vm_file->f_mapping);
2727
2728 flush_dcache_mmap_lock(vma->vm_file->f_mapping);
2729 vma_interval_tree_insert(vma, &vma->vm_file->f_mapping->i_mmap);
2730 flush_dcache_mmap_unlock(vma->vm_file->f_mapping);
2731 i_mmap_unlock_write(vma->vm_file->f_mapping);
2732 }
2733
2734 /*
2735 * vma_merge() calls khugepaged_enter_vma() either, the below
2736 * call covers the non-merge case.
2737 */
2738 khugepaged_enter_vma(vma, vma->vm_flags);
2739
2740 /* Once vma denies write, undo our temporary denial count */
2741unmap_writable:
2742 if (file && vm_flags & VM_SHARED)
2743 mapping_unmap_writable(file->f_mapping);
2744 file = vma->vm_file;
2745expanded:
2746 perf_event_mmap(vma);
2747
2748 vm_stat_account(mm, vm_flags, len >> PAGE_SHIFT);
2749 if (vm_flags & VM_LOCKED) {
2750 if ((vm_flags & VM_SPECIAL) || vma_is_dax(vma) ||
2751 is_vm_hugetlb_page(vma) ||
2752 vma == get_gate_vma(current->mm))
2753 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
2754 else
2755 mm->locked_vm += (len >> PAGE_SHIFT);
2756 }
2757
2758 if (file)
2759 uprobe_mmap(vma);
2760
2761 /*
2762 * New (or expanded) vma always get soft dirty status.
2763 * Otherwise user-space soft-dirty page tracker won't
2764 * be able to distinguish situation when vma area unmapped,
2765 * then new mapped in-place (which must be aimed as
2766 * a completely new data area).
2767 */
2768 vma->vm_flags |= VM_SOFTDIRTY;
2769
2770 vma_set_page_prot(vma);
2771
2772 validate_mm(mm);
2773 return addr;
2774
deb0f656
CL
2775close_and_free_vma:
2776 if (vma->vm_ops && vma->vm_ops->close)
2777 vma->vm_ops->close(vma);
e99668a5
LH
2778unmap_and_free_vma:
2779 fput(vma->vm_file);
2780 vma->vm_file = NULL;
2781
2782 /* Undo any partial mapping done by a device driver. */
763ecb03 2783 unmap_region(mm, mas.tree, vma, prev, next, vma->vm_start, vma->vm_end);
cc674ab3 2784 if (file && (vm_flags & VM_SHARED))
e99668a5
LH
2785 mapping_unmap_writable(file->f_mapping);
2786free_vma:
2787 vm_area_free(vma);
2788unacct_error:
2789 if (charged)
2790 vm_unacct_memory(charged);
2791 validate_mm(mm);
2792 return error;
2793}
2794
dd2283f2 2795static int __vm_munmap(unsigned long start, size_t len, bool downgrade)
1da177e4
LT
2796{
2797 int ret;
bfce281c 2798 struct mm_struct *mm = current->mm;
897ab3e0 2799 LIST_HEAD(uf);
11f9a21a 2800 MA_STATE(mas, &mm->mm_mt, start, start);
1da177e4 2801
d8ed45c5 2802 if (mmap_write_lock_killable(mm))
ae798783
MH
2803 return -EINTR;
2804
11f9a21a 2805 ret = do_mas_munmap(&mas, mm, start, len, &uf, downgrade);
dd2283f2 2806 /*
c1e8d7c6 2807 * Returning 1 indicates mmap_lock is downgraded.
dd2283f2
YS
2808 * But 1 is not legal return value of vm_munmap() and munmap(), reset
2809 * it to 0 before return.
2810 */
2811 if (ret == 1) {
d8ed45c5 2812 mmap_read_unlock(mm);
dd2283f2
YS
2813 ret = 0;
2814 } else
d8ed45c5 2815 mmap_write_unlock(mm);
dd2283f2 2816
897ab3e0 2817 userfaultfd_unmap_complete(mm, &uf);
1da177e4
LT
2818 return ret;
2819}
dd2283f2
YS
2820
2821int vm_munmap(unsigned long start, size_t len)
2822{
2823 return __vm_munmap(start, len, false);
2824}
a46ef99d
LT
2825EXPORT_SYMBOL(vm_munmap);
2826
2827SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
2828{
ce18d171 2829 addr = untagged_addr(addr);
dd2283f2 2830 return __vm_munmap(addr, len, true);
a46ef99d 2831}
1da177e4 2832
c8d78c18
KS
2833
2834/*
2835 * Emulation of deprecated remap_file_pages() syscall.
2836 */
2837SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
2838 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
2839{
2840
2841 struct mm_struct *mm = current->mm;
2842 struct vm_area_struct *vma;
2843 unsigned long populate = 0;
2844 unsigned long ret = -EINVAL;
2845 struct file *file;
2846
ee65728e 2847 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
756a025f 2848 current->comm, current->pid);
c8d78c18
KS
2849
2850 if (prot)
2851 return ret;
2852 start = start & PAGE_MASK;
2853 size = size & PAGE_MASK;
2854
2855 if (start + size <= start)
2856 return ret;
2857
2858 /* Does pgoff wrap? */
2859 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
2860 return ret;
2861
d8ed45c5 2862 if (mmap_write_lock_killable(mm))
dc0ef0df
MH
2863 return -EINTR;
2864
9b593cb2 2865 vma = vma_lookup(mm, start);
c8d78c18
KS
2866
2867 if (!vma || !(vma->vm_flags & VM_SHARED))
2868 goto out;
2869
48f7df32 2870 if (start + size > vma->vm_end) {
763ecb03
LH
2871 VMA_ITERATOR(vmi, mm, vma->vm_end);
2872 struct vm_area_struct *next, *prev = vma;
48f7df32 2873
763ecb03 2874 for_each_vma_range(vmi, next, start + size) {
48f7df32 2875 /* hole between vmas ? */
763ecb03 2876 if (next->vm_start != prev->vm_end)
48f7df32
KS
2877 goto out;
2878
2879 if (next->vm_file != vma->vm_file)
2880 goto out;
2881
2882 if (next->vm_flags != vma->vm_flags)
2883 goto out;
2884
1db43d3f
LH
2885 if (start + size <= next->vm_end)
2886 break;
2887
763ecb03 2888 prev = next;
48f7df32
KS
2889 }
2890
2891 if (!next)
2892 goto out;
c8d78c18
KS
2893 }
2894
2895 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
2896 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
2897 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
2898
2899 flags &= MAP_NONBLOCK;
2900 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
fce000b1 2901 if (vma->vm_flags & VM_LOCKED)
c8d78c18 2902 flags |= MAP_LOCKED;
48f7df32 2903
c8d78c18 2904 file = get_file(vma->vm_file);
45e55300 2905 ret = do_mmap(vma->vm_file, start, size,
897ab3e0 2906 prot, flags, pgoff, &populate, NULL);
c8d78c18
KS
2907 fput(file);
2908out:
d8ed45c5 2909 mmap_write_unlock(mm);
c8d78c18
KS
2910 if (populate)
2911 mm_populate(ret, populate);
2912 if (!IS_ERR_VALUE(ret))
2913 ret = 0;
2914 return ret;
2915}
2916
1da177e4 2917/*
92fed820
LH
2918 * brk_munmap() - Unmap a full or partial vma.
2919 * @vmi: The vma iterator
2e7ce7d3
LH
2920 * @vma: The vma to be modified
2921 * @newbrk: the start of the address to unmap
2922 * @oldbrk: The end of the address to unmap
2923 * @uf: The userfaultfd list_head
2924 *
2925 * Returns: 1 on success.
2926 * unmaps a partial VMA mapping. Does not handle alignment, downgrades lock if
2927 * possible.
1da177e4 2928 */
92fed820 2929static int do_brk_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
2e7ce7d3
LH
2930 unsigned long newbrk, unsigned long oldbrk,
2931 struct list_head *uf)
1da177e4 2932{
2e7ce7d3
LH
2933 struct mm_struct *mm = vma->vm_mm;
2934 int ret;
3a459756 2935
2e7ce7d3 2936 arch_unmap(mm, newbrk, oldbrk);
92fed820 2937 ret = do_mas_align_munmap(&vmi->mas, vma, mm, newbrk, oldbrk, uf, true);
2e7ce7d3
LH
2938 validate_mm_mt(mm);
2939 return ret;
2940}
1da177e4 2941
2e7ce7d3
LH
2942/*
2943 * do_brk_flags() - Increase the brk vma if the flags match.
92fed820 2944 * @vmi: The vma iterator
2e7ce7d3
LH
2945 * @addr: The start address
2946 * @len: The length of the increase
2947 * @vma: The vma,
2948 * @flags: The VMA Flags
2949 *
2950 * Extend the brk VMA from addr to addr + len. If the VMA is NULL or the flags
2951 * do not match then create a new anonymous VMA. Eventually we may be able to
2952 * do some brk-specific accounting here.
2953 */
92fed820 2954static int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *vma,
763ecb03 2955 unsigned long addr, unsigned long len, unsigned long flags)
2e7ce7d3
LH
2956{
2957 struct mm_struct *mm = current->mm;
1da177e4 2958
2e7ce7d3
LH
2959 validate_mm_mt(mm);
2960 /*
2961 * Check against address space limits by the changed size
2962 * Note: This happens *after* clearing old mappings in some code paths.
2963 */
2964 flags |= VM_DATA_DEFAULT_FLAGS | VM_ACCOUNT | mm->def_flags;
84638335 2965 if (!may_expand_vm(mm, flags, len >> PAGE_SHIFT))
1da177e4
LT
2966 return -ENOMEM;
2967
2968 if (mm->map_count > sysctl_max_map_count)
2969 return -ENOMEM;
2970
191c5424 2971 if (security_vm_enough_memory_mm(mm, len >> PAGE_SHIFT))
1da177e4
LT
2972 return -ENOMEM;
2973
1da177e4 2974 /*
2e7ce7d3
LH
2975 * Expand the existing vma if possible; Note that singular lists do not
2976 * occur after forking, so the expand will only happen on new VMAs.
1da177e4 2977 */
6c28ca64
LH
2978 if (vma && vma->vm_end == addr && !vma_policy(vma) &&
2979 can_vma_merge_after(vma, flags, NULL, NULL,
2980 addr >> PAGE_SHIFT, NULL_VM_UFFD_CTX, NULL)) {
92fed820 2981 if (vma_iter_prealloc(vmi))
675eaca1 2982 goto unacct_fail;
28c5609f
LH
2983
2984 vma_adjust_trans_huge(vma, vma->vm_start, addr + len, 0);
2e7ce7d3
LH
2985 if (vma->anon_vma) {
2986 anon_vma_lock_write(vma->anon_vma);
2987 anon_vma_interval_tree_pre_update_vma(vma);
2988 }
2989 vma->vm_end = addr + len;
2990 vma->vm_flags |= VM_SOFTDIRTY;
92fed820 2991 vma_iter_store(vmi, vma);
2e7ce7d3
LH
2992
2993 if (vma->anon_vma) {
2994 anon_vma_interval_tree_post_update_vma(vma);
2995 anon_vma_unlock_write(vma->anon_vma);
2996 }
2997 khugepaged_enter_vma(vma, flags);
2998 goto out;
1da177e4 2999 }
2e7ce7d3
LH
3000
3001 /* create a vma struct for an anonymous mapping */
3002 vma = vm_area_alloc(mm);
3003 if (!vma)
675eaca1 3004 goto unacct_fail;
1da177e4 3005
bfd40eaf 3006 vma_set_anonymous(vma);
1da177e4
LT
3007 vma->vm_start = addr;
3008 vma->vm_end = addr + len;
2e7ce7d3 3009 vma->vm_pgoff = addr >> PAGE_SHIFT;
1da177e4 3010 vma->vm_flags = flags;
3ed75eb8 3011 vma->vm_page_prot = vm_get_page_prot(flags);
92fed820 3012 if (vma_iter_store_gfp(vmi, vma, GFP_KERNEL))
2e7ce7d3 3013 goto mas_store_fail;
d4af56c5 3014
2e7ce7d3 3015 mm->map_count++;
1da177e4 3016out:
3af9e859 3017 perf_event_mmap(vma);
1da177e4 3018 mm->total_vm += len >> PAGE_SHIFT;
84638335 3019 mm->data_vm += len >> PAGE_SHIFT;
128557ff
ML
3020 if (flags & VM_LOCKED)
3021 mm->locked_vm += (len >> PAGE_SHIFT);
d9104d1c 3022 vma->vm_flags |= VM_SOFTDIRTY;
763ecb03 3023 validate_mm(mm);
5d22fc25 3024 return 0;
d4af56c5 3025
2e7ce7d3 3026mas_store_fail:
d4af56c5 3027 vm_area_free(vma);
675eaca1 3028unacct_fail:
2e7ce7d3
LH
3029 vm_unacct_memory(len >> PAGE_SHIFT);
3030 return -ENOMEM;
1da177e4
LT
3031}
3032
bb177a73 3033int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
e4eb1ff6
LT
3034{
3035 struct mm_struct *mm = current->mm;
2e7ce7d3 3036 struct vm_area_struct *vma = NULL;
bb177a73 3037 unsigned long len;
5d22fc25 3038 int ret;
128557ff 3039 bool populate;
897ab3e0 3040 LIST_HEAD(uf);
92fed820 3041 VMA_ITERATOR(vmi, mm, addr);
e4eb1ff6 3042
bb177a73
MH
3043 len = PAGE_ALIGN(request);
3044 if (len < request)
3045 return -ENOMEM;
3046 if (!len)
3047 return 0;
3048
d8ed45c5 3049 if (mmap_write_lock_killable(mm))
2d6c9282
MH
3050 return -EINTR;
3051
2e7ce7d3
LH
3052 /* Until we need other flags, refuse anything except VM_EXEC. */
3053 if ((flags & (~VM_EXEC)) != 0)
3054 return -EINVAL;
3055
3056 ret = check_brk_limits(addr, len);
3057 if (ret)
3058 goto limits_failed;
3059
92fed820 3060 ret = do_mas_munmap(&vmi.mas, mm, addr, len, &uf, 0);
2e7ce7d3
LH
3061 if (ret)
3062 goto munmap_failed;
3063
92fed820
LH
3064 vma = vma_prev(&vmi);
3065 ret = do_brk_flags(&vmi, vma, addr, len, flags);
128557ff 3066 populate = ((mm->def_flags & VM_LOCKED) != 0);
d8ed45c5 3067 mmap_write_unlock(mm);
897ab3e0 3068 userfaultfd_unmap_complete(mm, &uf);
5d22fc25 3069 if (populate && !ret)
128557ff 3070 mm_populate(addr, len);
e4eb1ff6 3071 return ret;
2e7ce7d3
LH
3072
3073munmap_failed:
3074limits_failed:
3075 mmap_write_unlock(mm);
3076 return ret;
e4eb1ff6 3077}
16e72e9b
DV
3078EXPORT_SYMBOL(vm_brk_flags);
3079
3080int vm_brk(unsigned long addr, unsigned long len)
3081{
3082 return vm_brk_flags(addr, len, 0);
3083}
e4eb1ff6 3084EXPORT_SYMBOL(vm_brk);
1da177e4
LT
3085
3086/* Release all mmaps. */
3087void exit_mmap(struct mm_struct *mm)
3088{
d16dfc55 3089 struct mmu_gather tlb;
ba470de4 3090 struct vm_area_struct *vma;
1da177e4 3091 unsigned long nr_accounted = 0;
763ecb03
LH
3092 MA_STATE(mas, &mm->mm_mt, 0, 0);
3093 int count = 0;
1da177e4 3094
d6dd61c8 3095 /* mm's last user has gone, and its about to be pulled down */
cddb8a5c 3096 mmu_notifier_release(mm);
d6dd61c8 3097
bf3980c8 3098 mmap_read_lock(mm);
9480c53e
JF
3099 arch_exit_mmap(mm);
3100
763ecb03 3101 vma = mas_find(&mas, ULONG_MAX);
64591e86
SB
3102 if (!vma) {
3103 /* Can happen if dup_mmap() received an OOM */
bf3980c8 3104 mmap_read_unlock(mm);
9480c53e 3105 return;
64591e86 3106 }
9480c53e 3107
1da177e4 3108 lru_add_drain();
1da177e4 3109 flush_cache_mm(mm);
d8b45053 3110 tlb_gather_mmu_fullmm(&tlb, mm);
901608d9 3111 /* update_hiwater_rss(mm) here? but nobody should be looking */
763ecb03
LH
3112 /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
3113 unmap_vmas(&tlb, &mm->mm_mt, vma, 0, ULONG_MAX);
bf3980c8
SB
3114 mmap_read_unlock(mm);
3115
3116 /*
3117 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
b3541d91 3118 * because the memory has been already freed.
bf3980c8
SB
3119 */
3120 set_bit(MMF_OOM_SKIP, &mm->flags);
3121 mmap_write_lock(mm);
763ecb03
LH
3122 free_pgtables(&tlb, &mm->mm_mt, vma, FIRST_USER_ADDRESS,
3123 USER_PGTABLES_CEILING);
ae8eba8b 3124 tlb_finish_mmu(&tlb);
1da177e4 3125
763ecb03
LH
3126 /*
3127 * Walk the list again, actually closing and freeing it, with preemption
3128 * enabled, without holding any MM locks besides the unreachable
3129 * mmap_write_lock.
3130 */
3131 do {
4f74d2c8
LT
3132 if (vma->vm_flags & VM_ACCOUNT)
3133 nr_accounted += vma_pages(vma);
763ecb03
LH
3134 remove_vma(vma);
3135 count++;
0a3b3c25 3136 cond_resched();
763ecb03
LH
3137 } while ((vma = mas_find(&mas, ULONG_MAX)) != NULL);
3138
3139 BUG_ON(count != mm->map_count);
d4af56c5
LH
3140
3141 trace_exit_mmap(mm);
3142 __mt_destroy(&mm->mm_mt);
64591e86 3143 mmap_write_unlock(mm);
4f74d2c8 3144 vm_unacct_memory(nr_accounted);
1da177e4
LT
3145}
3146
3147/* Insert vm structure into process list sorted by address
3148 * and into the inode's i_mmap tree. If vm_file is non-NULL
c8c06efa 3149 * then i_mmap_rwsem is taken here.
1da177e4 3150 */
6597d783 3151int insert_vm_struct(struct mm_struct *mm, struct vm_area_struct *vma)
1da177e4 3152{
d4af56c5 3153 unsigned long charged = vma_pages(vma);
1da177e4 3154
d4af56c5 3155
d0601a50 3156 if (find_vma_intersection(mm, vma->vm_start, vma->vm_end))
c9d13f5f 3157 return -ENOMEM;
d4af56c5 3158
c9d13f5f 3159 if ((vma->vm_flags & VM_ACCOUNT) &&
d4af56c5 3160 security_vm_enough_memory_mm(mm, charged))
c9d13f5f
CG
3161 return -ENOMEM;
3162
1da177e4
LT
3163 /*
3164 * The vm_pgoff of a purely anonymous vma should be irrelevant
3165 * until its first write fault, when page's anon_vma and index
3166 * are set. But now set the vm_pgoff it will almost certainly
3167 * end up with (unless mremap moves it elsewhere before that
3168 * first wfault), so /proc/pid/maps tells a consistent story.
3169 *
3170 * By setting it to reflect the virtual start address of the
3171 * vma, merges and splits can happen in a seamless way, just
3172 * using the existing file pgoff checks and manipulations.
8332326e 3173 * Similarly in do_mmap and in do_brk_flags.
1da177e4 3174 */
8a9cc3b5 3175 if (vma_is_anonymous(vma)) {
1da177e4
LT
3176 BUG_ON(vma->anon_vma);
3177 vma->vm_pgoff = vma->vm_start >> PAGE_SHIFT;
3178 }
2b144498 3179
763ecb03 3180 if (vma_link(mm, vma)) {
d4af56c5
LH
3181 vm_unacct_memory(charged);
3182 return -ENOMEM;
3183 }
3184
1da177e4
LT
3185 return 0;
3186}
3187
3188/*
3189 * Copy the vma structure to a new location in the same mm,
3190 * prior to moving page table entries, to effect an mremap move.
3191 */
3192struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
38a76013
ML
3193 unsigned long addr, unsigned long len, pgoff_t pgoff,
3194 bool *need_rmap_locks)
1da177e4
LT
3195{
3196 struct vm_area_struct *vma = *vmap;
3197 unsigned long vma_start = vma->vm_start;
3198 struct mm_struct *mm = vma->vm_mm;
3199 struct vm_area_struct *new_vma, *prev;
948f017b 3200 bool faulted_in_anon_vma = true;
1da177e4 3201
d4af56c5 3202 validate_mm_mt(mm);
1da177e4
LT
3203 /*
3204 * If anonymous vma has not yet been faulted, update new pgoff
3205 * to match new location, to increase its chance of merging.
3206 */
ce75799b 3207 if (unlikely(vma_is_anonymous(vma) && !vma->anon_vma)) {
1da177e4 3208 pgoff = addr >> PAGE_SHIFT;
948f017b
AA
3209 faulted_in_anon_vma = false;
3210 }
1da177e4 3211
763ecb03
LH
3212 new_vma = find_vma_prev(mm, addr, &prev);
3213 if (new_vma && new_vma->vm_start < addr + len)
6597d783 3214 return NULL; /* should never get here */
524e00b3 3215
1da177e4 3216 new_vma = vma_merge(mm, prev, addr, addr + len, vma->vm_flags,
19a809af 3217 vma->anon_vma, vma->vm_file, pgoff, vma_policy(vma),
5c26f6ac 3218 vma->vm_userfaultfd_ctx, anon_vma_name(vma));
1da177e4
LT
3219 if (new_vma) {
3220 /*
3221 * Source vma may have been merged into new_vma
3222 */
948f017b
AA
3223 if (unlikely(vma_start >= new_vma->vm_start &&
3224 vma_start < new_vma->vm_end)) {
3225 /*
3226 * The only way we can get a vma_merge with
3227 * self during an mremap is if the vma hasn't
3228 * been faulted in yet and we were allowed to
3229 * reset the dst vma->vm_pgoff to the
3230 * destination address of the mremap to allow
3231 * the merge to happen. mremap must change the
3232 * vm_pgoff linearity between src and dst vmas
3233 * (in turn preventing a vma_merge) to be
3234 * safe. It is only safe to keep the vm_pgoff
3235 * linear if there are no pages mapped yet.
3236 */
81d1b09c 3237 VM_BUG_ON_VMA(faulted_in_anon_vma, new_vma);
38a76013 3238 *vmap = vma = new_vma;
108d6642 3239 }
38a76013 3240 *need_rmap_locks = (new_vma->vm_pgoff <= vma->vm_pgoff);
1da177e4 3241 } else {
3928d4f5 3242 new_vma = vm_area_dup(vma);
e3975891
CG
3243 if (!new_vma)
3244 goto out;
e3975891
CG
3245 new_vma->vm_start = addr;
3246 new_vma->vm_end = addr + len;
3247 new_vma->vm_pgoff = pgoff;
3248 if (vma_dup_policy(vma, new_vma))
3249 goto out_free_vma;
e3975891
CG
3250 if (anon_vma_clone(new_vma, vma))
3251 goto out_free_mempol;
3252 if (new_vma->vm_file)
3253 get_file(new_vma->vm_file);
3254 if (new_vma->vm_ops && new_vma->vm_ops->open)
3255 new_vma->vm_ops->open(new_vma);
763ecb03 3256 if (vma_link(mm, new_vma))
524e00b3 3257 goto out_vma_link;
e3975891 3258 *need_rmap_locks = false;
1da177e4 3259 }
d4af56c5 3260 validate_mm_mt(mm);
1da177e4 3261 return new_vma;
5beb4930 3262
524e00b3
LH
3263out_vma_link:
3264 if (new_vma->vm_ops && new_vma->vm_ops->close)
3265 new_vma->vm_ops->close(new_vma);
92b73996
LH
3266
3267 if (new_vma->vm_file)
3268 fput(new_vma->vm_file);
3269
3270 unlink_anon_vmas(new_vma);
e3975891 3271out_free_mempol:
ef0855d3 3272 mpol_put(vma_policy(new_vma));
e3975891 3273out_free_vma:
3928d4f5 3274 vm_area_free(new_vma);
e3975891 3275out:
d4af56c5 3276 validate_mm_mt(mm);
5beb4930 3277 return NULL;
1da177e4 3278}
119f657c 3279
3280/*
3281 * Return true if the calling process may expand its vm space by the passed
3282 * number of pages
3283 */
84638335 3284bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
119f657c 3285{
84638335
KK
3286 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
3287 return false;
119f657c 3288
d977d56c
KK
3289 if (is_data_mapping(flags) &&
3290 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
f4fcd558
KK
3291 /* Workaround for Valgrind */
3292 if (rlimit(RLIMIT_DATA) == 0 &&
3293 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
3294 return true;
57a7702b
DW
3295
3296 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
3297 current->comm, current->pid,
3298 (mm->data_vm + npages) << PAGE_SHIFT,
3299 rlimit(RLIMIT_DATA),
3300 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
3301
3302 if (!ignore_rlimit_data)
d977d56c
KK
3303 return false;
3304 }
119f657c 3305
84638335
KK
3306 return true;
3307}
3308
3309void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
3310{
7866076b 3311 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
84638335 3312
d977d56c 3313 if (is_exec_mapping(flags))
84638335 3314 mm->exec_vm += npages;
d977d56c 3315 else if (is_stack_mapping(flags))
84638335 3316 mm->stack_vm += npages;
d977d56c 3317 else if (is_data_mapping(flags))
84638335 3318 mm->data_vm += npages;
119f657c 3319}
fa5dc22f 3320
b3ec9f33 3321static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
a62c34bd
AL
3322
3323/*
3324 * Having a close hook prevents vma merging regardless of flags.
3325 */
3326static void special_mapping_close(struct vm_area_struct *vma)
3327{
3328}
3329
3330static const char *special_mapping_name(struct vm_area_struct *vma)
3331{
3332 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
3333}
3334
14d07113 3335static int special_mapping_mremap(struct vm_area_struct *new_vma)
b059a453
DS
3336{
3337 struct vm_special_mapping *sm = new_vma->vm_private_data;
3338
280e87e9
DS
3339 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
3340 return -EFAULT;
3341
b059a453
DS
3342 if (sm->mremap)
3343 return sm->mremap(sm, new_vma);
280e87e9 3344
b059a453
DS
3345 return 0;
3346}
3347
871402e0
DS
3348static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
3349{
3350 /*
3351 * Forbid splitting special mappings - kernel has expectations over
3352 * the number of pages in mapping. Together with VM_DONTEXPAND
3353 * the size of vma should stay the same over the special mapping's
3354 * lifetime.
3355 */
3356 return -EINVAL;
3357}
3358
a62c34bd
AL
3359static const struct vm_operations_struct special_mapping_vmops = {
3360 .close = special_mapping_close,
3361 .fault = special_mapping_fault,
b059a453 3362 .mremap = special_mapping_mremap,
a62c34bd 3363 .name = special_mapping_name,
af34ebeb
DS
3364 /* vDSO code relies that VVAR can't be accessed remotely */
3365 .access = NULL,
871402e0 3366 .may_split = special_mapping_split,
a62c34bd
AL
3367};
3368
3369static const struct vm_operations_struct legacy_special_mapping_vmops = {
3370 .close = special_mapping_close,
3371 .fault = special_mapping_fault,
3372};
fa5dc22f 3373
b3ec9f33 3374static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
fa5dc22f 3375{
11bac800 3376 struct vm_area_struct *vma = vmf->vma;
b1d0e4f5 3377 pgoff_t pgoff;
fa5dc22f
RM
3378 struct page **pages;
3379
f872f540 3380 if (vma->vm_ops == &legacy_special_mapping_vmops) {
a62c34bd 3381 pages = vma->vm_private_data;
f872f540
AL
3382 } else {
3383 struct vm_special_mapping *sm = vma->vm_private_data;
3384
3385 if (sm->fault)
11bac800 3386 return sm->fault(sm, vmf->vma, vmf);
f872f540
AL
3387
3388 pages = sm->pages;
3389 }
a62c34bd 3390
8a9cc3b5 3391 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
b1d0e4f5 3392 pgoff--;
fa5dc22f
RM
3393
3394 if (*pages) {
3395 struct page *page = *pages;
3396 get_page(page);
b1d0e4f5
NP
3397 vmf->page = page;
3398 return 0;
fa5dc22f
RM
3399 }
3400
b1d0e4f5 3401 return VM_FAULT_SIGBUS;
fa5dc22f
RM
3402}
3403
a62c34bd
AL
3404static struct vm_area_struct *__install_special_mapping(
3405 struct mm_struct *mm,
3406 unsigned long addr, unsigned long len,
27f28b97
CG
3407 unsigned long vm_flags, void *priv,
3408 const struct vm_operations_struct *ops)
fa5dc22f 3409{
462e635e 3410 int ret;
fa5dc22f
RM
3411 struct vm_area_struct *vma;
3412
d4af56c5 3413 validate_mm_mt(mm);
490fc053 3414 vma = vm_area_alloc(mm);
fa5dc22f 3415 if (unlikely(vma == NULL))
3935ed6a 3416 return ERR_PTR(-ENOMEM);
fa5dc22f 3417
fa5dc22f
RM
3418 vma->vm_start = addr;
3419 vma->vm_end = addr + len;
3420
d9104d1c 3421 vma->vm_flags = vm_flags | mm->def_flags | VM_DONTEXPAND | VM_SOFTDIRTY;
1fc09228 3422 vma->vm_flags &= VM_LOCKED_CLEAR_MASK;
3ed75eb8 3423 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
fa5dc22f 3424
a62c34bd
AL
3425 vma->vm_ops = ops;
3426 vma->vm_private_data = priv;
fa5dc22f 3427
462e635e
TO
3428 ret = insert_vm_struct(mm, vma);
3429 if (ret)
3430 goto out;
fa5dc22f 3431
84638335 3432 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
fa5dc22f 3433
cdd6c482 3434 perf_event_mmap(vma);
089dd79d 3435
d4af56c5 3436 validate_mm_mt(mm);
3935ed6a 3437 return vma;
462e635e
TO
3438
3439out:
3928d4f5 3440 vm_area_free(vma);
d4af56c5 3441 validate_mm_mt(mm);
3935ed6a
SS
3442 return ERR_PTR(ret);
3443}
3444
2eefd878
DS
3445bool vma_is_special_mapping(const struct vm_area_struct *vma,
3446 const struct vm_special_mapping *sm)
3447{
3448 return vma->vm_private_data == sm &&
3449 (vma->vm_ops == &special_mapping_vmops ||
3450 vma->vm_ops == &legacy_special_mapping_vmops);
3451}
3452
a62c34bd 3453/*
c1e8d7c6 3454 * Called with mm->mmap_lock held for writing.
a62c34bd
AL
3455 * Insert a new vma covering the given region, with the given flags.
3456 * Its pages are supplied by the given array of struct page *.
3457 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
3458 * The region past the last page supplied will always produce SIGBUS.
3459 * The array pointer and the pages it points to are assumed to stay alive
3460 * for as long as this mapping might exist.
3461 */
3462struct vm_area_struct *_install_special_mapping(
3463 struct mm_struct *mm,
3464 unsigned long addr, unsigned long len,
3465 unsigned long vm_flags, const struct vm_special_mapping *spec)
3466{
27f28b97
CG
3467 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
3468 &special_mapping_vmops);
a62c34bd
AL
3469}
3470
3935ed6a
SS
3471int install_special_mapping(struct mm_struct *mm,
3472 unsigned long addr, unsigned long len,
3473 unsigned long vm_flags, struct page **pages)
3474{
a62c34bd 3475 struct vm_area_struct *vma = __install_special_mapping(
27f28b97
CG
3476 mm, addr, len, vm_flags, (void *)pages,
3477 &legacy_special_mapping_vmops);
3935ed6a 3478
14bd5b45 3479 return PTR_ERR_OR_ZERO(vma);
fa5dc22f 3480}
7906d00c
AA
3481
3482static DEFINE_MUTEX(mm_all_locks_mutex);
3483
454ed842 3484static void vm_lock_anon_vma(struct mm_struct *mm, struct anon_vma *anon_vma)
7906d00c 3485{
f808c13f 3486 if (!test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
7906d00c
AA
3487 /*
3488 * The LSB of head.next can't change from under us
3489 * because we hold the mm_all_locks_mutex.
3490 */
da1c55f1 3491 down_write_nest_lock(&anon_vma->root->rwsem, &mm->mmap_lock);
7906d00c
AA
3492 /*
3493 * We can safely modify head.next after taking the
5a505085 3494 * anon_vma->root->rwsem. If some other vma in this mm shares
7906d00c
AA
3495 * the same anon_vma we won't take it again.
3496 *
3497 * No need of atomic instructions here, head.next
3498 * can't change from under us thanks to the
5a505085 3499 * anon_vma->root->rwsem.
7906d00c
AA
3500 */
3501 if (__test_and_set_bit(0, (unsigned long *)
f808c13f 3502 &anon_vma->root->rb_root.rb_root.rb_node))
7906d00c
AA
3503 BUG();
3504 }
3505}
3506
454ed842 3507static void vm_lock_mapping(struct mm_struct *mm, struct address_space *mapping)
7906d00c
AA
3508{
3509 if (!test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3510 /*
3511 * AS_MM_ALL_LOCKS can't change from under us because
3512 * we hold the mm_all_locks_mutex.
3513 *
3514 * Operations on ->flags have to be atomic because
3515 * even if AS_MM_ALL_LOCKS is stable thanks to the
3516 * mm_all_locks_mutex, there may be other cpus
3517 * changing other bitflags in parallel to us.
3518 */
3519 if (test_and_set_bit(AS_MM_ALL_LOCKS, &mapping->flags))
3520 BUG();
da1c55f1 3521 down_write_nest_lock(&mapping->i_mmap_rwsem, &mm->mmap_lock);
7906d00c
AA
3522 }
3523}
3524
3525/*
3526 * This operation locks against the VM for all pte/vma/mm related
3527 * operations that could ever happen on a certain mm. This includes
3528 * vmtruncate, try_to_unmap, and all page faults.
3529 *
c1e8d7c6 3530 * The caller must take the mmap_lock in write mode before calling
7906d00c 3531 * mm_take_all_locks(). The caller isn't allowed to release the
c1e8d7c6 3532 * mmap_lock until mm_drop_all_locks() returns.
7906d00c 3533 *
c1e8d7c6 3534 * mmap_lock in write mode is required in order to block all operations
7906d00c 3535 * that could modify pagetables and free pages without need of
27ba0644 3536 * altering the vma layout. It's also needed in write mode to avoid new
7906d00c
AA
3537 * anon_vmas to be associated with existing vmas.
3538 *
3539 * A single task can't take more than one mm_take_all_locks() in a row
3540 * or it would deadlock.
3541 *
bf181b9f 3542 * The LSB in anon_vma->rb_root.rb_node and the AS_MM_ALL_LOCKS bitflag in
7906d00c
AA
3543 * mapping->flags avoid to take the same lock twice, if more than one
3544 * vma in this mm is backed by the same anon_vma or address_space.
3545 *
88f306b6
KS
3546 * We take locks in following order, accordingly to comment at beginning
3547 * of mm/rmap.c:
3548 * - all hugetlbfs_i_mmap_rwsem_key locks (aka mapping->i_mmap_rwsem for
3549 * hugetlb mapping);
3550 * - all i_mmap_rwsem locks;
3551 * - all anon_vma->rwseml
3552 *
3553 * We can take all locks within these types randomly because the VM code
3554 * doesn't nest them and we protected from parallel mm_take_all_locks() by
3555 * mm_all_locks_mutex.
7906d00c
AA
3556 *
3557 * mm_take_all_locks() and mm_drop_all_locks are expensive operations
3558 * that may have to take thousand of locks.
3559 *
3560 * mm_take_all_locks() can fail if it's interrupted by signals.
3561 */
3562int mm_take_all_locks(struct mm_struct *mm)
3563{
3564 struct vm_area_struct *vma;
5beb4930 3565 struct anon_vma_chain *avc;
763ecb03 3566 MA_STATE(mas, &mm->mm_mt, 0, 0);
7906d00c 3567
325bca1f 3568 mmap_assert_write_locked(mm);
7906d00c
AA
3569
3570 mutex_lock(&mm_all_locks_mutex);
3571
763ecb03 3572 mas_for_each(&mas, vma, ULONG_MAX) {
7906d00c
AA
3573 if (signal_pending(current))
3574 goto out_unlock;
88f306b6
KS
3575 if (vma->vm_file && vma->vm_file->f_mapping &&
3576 is_vm_hugetlb_page(vma))
3577 vm_lock_mapping(mm, vma->vm_file->f_mapping);
3578 }
3579
763ecb03
LH
3580 mas_set(&mas, 0);
3581 mas_for_each(&mas, vma, ULONG_MAX) {
88f306b6
KS
3582 if (signal_pending(current))
3583 goto out_unlock;
3584 if (vma->vm_file && vma->vm_file->f_mapping &&
3585 !is_vm_hugetlb_page(vma))
454ed842 3586 vm_lock_mapping(mm, vma->vm_file->f_mapping);
7906d00c 3587 }
7cd5a02f 3588
763ecb03
LH
3589 mas_set(&mas, 0);
3590 mas_for_each(&mas, vma, ULONG_MAX) {
7cd5a02f
PZ
3591 if (signal_pending(current))
3592 goto out_unlock;
3593 if (vma->anon_vma)
5beb4930
RR
3594 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3595 vm_lock_anon_vma(mm, avc->anon_vma);
7906d00c 3596 }
7cd5a02f 3597
584cff54 3598 return 0;
7906d00c
AA
3599
3600out_unlock:
584cff54
KC
3601 mm_drop_all_locks(mm);
3602 return -EINTR;
7906d00c
AA
3603}
3604
3605static void vm_unlock_anon_vma(struct anon_vma *anon_vma)
3606{
f808c13f 3607 if (test_bit(0, (unsigned long *) &anon_vma->root->rb_root.rb_root.rb_node)) {
7906d00c
AA
3608 /*
3609 * The LSB of head.next can't change to 0 from under
3610 * us because we hold the mm_all_locks_mutex.
3611 *
3612 * We must however clear the bitflag before unlocking
bf181b9f 3613 * the vma so the users using the anon_vma->rb_root will
7906d00c
AA
3614 * never see our bitflag.
3615 *
3616 * No need of atomic instructions here, head.next
3617 * can't change from under us until we release the
5a505085 3618 * anon_vma->root->rwsem.
7906d00c
AA
3619 */
3620 if (!__test_and_clear_bit(0, (unsigned long *)
f808c13f 3621 &anon_vma->root->rb_root.rb_root.rb_node))
7906d00c 3622 BUG();
08b52706 3623 anon_vma_unlock_write(anon_vma);
7906d00c
AA
3624 }
3625}
3626
3627static void vm_unlock_mapping(struct address_space *mapping)
3628{
3629 if (test_bit(AS_MM_ALL_LOCKS, &mapping->flags)) {
3630 /*
3631 * AS_MM_ALL_LOCKS can't change to 0 from under us
3632 * because we hold the mm_all_locks_mutex.
3633 */
83cde9e8 3634 i_mmap_unlock_write(mapping);
7906d00c
AA
3635 if (!test_and_clear_bit(AS_MM_ALL_LOCKS,
3636 &mapping->flags))
3637 BUG();
3638 }
3639}
3640
3641/*
c1e8d7c6 3642 * The mmap_lock cannot be released by the caller until
7906d00c
AA
3643 * mm_drop_all_locks() returns.
3644 */
3645void mm_drop_all_locks(struct mm_struct *mm)
3646{
3647 struct vm_area_struct *vma;
5beb4930 3648 struct anon_vma_chain *avc;
763ecb03 3649 MA_STATE(mas, &mm->mm_mt, 0, 0);
7906d00c 3650
325bca1f 3651 mmap_assert_write_locked(mm);
7906d00c
AA
3652 BUG_ON(!mutex_is_locked(&mm_all_locks_mutex));
3653
763ecb03 3654 mas_for_each(&mas, vma, ULONG_MAX) {
7906d00c 3655 if (vma->anon_vma)
5beb4930
RR
3656 list_for_each_entry(avc, &vma->anon_vma_chain, same_vma)
3657 vm_unlock_anon_vma(avc->anon_vma);
7906d00c
AA
3658 if (vma->vm_file && vma->vm_file->f_mapping)
3659 vm_unlock_mapping(vma->vm_file->f_mapping);
3660 }
3661
3662 mutex_unlock(&mm_all_locks_mutex);
3663}
8feae131
DH
3664
3665/*
3edf41d8 3666 * initialise the percpu counter for VM
8feae131
DH
3667 */
3668void __init mmap_init(void)
3669{
00a62ce9
KM
3670 int ret;
3671
908c7f19 3672 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
00a62ce9 3673 VM_BUG_ON(ret);
8feae131 3674}
c9b1d098
AS
3675
3676/*
3677 * Initialise sysctl_user_reserve_kbytes.
3678 *
3679 * This is intended to prevent a user from starting a single memory hogging
3680 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
3681 * mode.
3682 *
3683 * The default value is min(3% of free memory, 128MB)
3684 * 128MB is enough to recover with sshd/login, bash, and top/kill.
3685 */
1640879a 3686static int init_user_reserve(void)
c9b1d098
AS
3687{
3688 unsigned long free_kbytes;
3689
c41f012a 3690 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
c9b1d098
AS
3691
3692 sysctl_user_reserve_kbytes = min(free_kbytes / 32, 1UL << 17);
3693 return 0;
3694}
a64fb3cd 3695subsys_initcall(init_user_reserve);
4eeab4f5
AS
3696
3697/*
3698 * Initialise sysctl_admin_reserve_kbytes.
3699 *
3700 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
3701 * to log in and kill a memory hogging process.
3702 *
3703 * Systems with more than 256MB will reserve 8MB, enough to recover
3704 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
3705 * only reserve 3% of free pages by default.
3706 */
1640879a 3707static int init_admin_reserve(void)
4eeab4f5
AS
3708{
3709 unsigned long free_kbytes;
3710
c41f012a 3711 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
4eeab4f5
AS
3712
3713 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, 1UL << 13);
3714 return 0;
3715}
a64fb3cd 3716subsys_initcall(init_admin_reserve);
1640879a
AS
3717
3718/*
3719 * Reinititalise user and admin reserves if memory is added or removed.
3720 *
3721 * The default user reserve max is 128MB, and the default max for the
3722 * admin reserve is 8MB. These are usually, but not always, enough to
3723 * enable recovery from a memory hogging process using login/sshd, a shell,
3724 * and tools like top. It may make sense to increase or even disable the
3725 * reserve depending on the existence of swap or variations in the recovery
3726 * tools. So, the admin may have changed them.
3727 *
3728 * If memory is added and the reserves have been eliminated or increased above
3729 * the default max, then we'll trust the admin.
3730 *
3731 * If memory is removed and there isn't enough free memory, then we
3732 * need to reset the reserves.
3733 *
3734 * Otherwise keep the reserve set by the admin.
3735 */
3736static int reserve_mem_notifier(struct notifier_block *nb,
3737 unsigned long action, void *data)
3738{
3739 unsigned long tmp, free_kbytes;
3740
3741 switch (action) {
3742 case MEM_ONLINE:
3743 /* Default max is 128MB. Leave alone if modified by operator. */
3744 tmp = sysctl_user_reserve_kbytes;
3745 if (0 < tmp && tmp < (1UL << 17))
3746 init_user_reserve();
3747
3748 /* Default max is 8MB. Leave alone if modified by operator. */
3749 tmp = sysctl_admin_reserve_kbytes;
3750 if (0 < tmp && tmp < (1UL << 13))
3751 init_admin_reserve();
3752
3753 break;
3754 case MEM_OFFLINE:
c41f012a 3755 free_kbytes = global_zone_page_state(NR_FREE_PAGES) << (PAGE_SHIFT - 10);
1640879a
AS
3756
3757 if (sysctl_user_reserve_kbytes > free_kbytes) {
3758 init_user_reserve();
3759 pr_info("vm.user_reserve_kbytes reset to %lu\n",
3760 sysctl_user_reserve_kbytes);
3761 }
3762
3763 if (sysctl_admin_reserve_kbytes > free_kbytes) {
3764 init_admin_reserve();
3765 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
3766 sysctl_admin_reserve_kbytes);
3767 }
3768 break;
3769 default:
3770 break;
3771 }
3772 return NOTIFY_OK;
3773}
3774
1640879a
AS
3775static int __meminit init_reserve_notifier(void)
3776{
1eeaa4fd 3777 if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
b1de0d13 3778 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
1640879a
AS
3779
3780 return 0;
3781}
a64fb3cd 3782subsys_initcall(init_reserve_notifier);