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