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