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