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