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