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