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