Merge tag 'net-6.16-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net
[linux-2.6-block.git] / mm / mmap.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * mm/mmap.c
4 *
5 * Written by obz.
6 *
046c6884 7 * Address space accounting code <alan@lxorguk.ukuu.org.uk>
1da177e4
LT
8 */
9
b1de0d13
MH
10#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11
e8420a8e 12#include <linux/kernel.h>
1da177e4 13#include <linux/slab.h>
4af3c9cc 14#include <linux/backing-dev.h>
1da177e4 15#include <linux/mm.h>
17fca131 16#include <linux/mm_inline.h>
1da177e4
LT
17#include <linux/shm.h>
18#include <linux/mman.h>
19#include <linux/pagemap.h>
20#include <linux/swap.h>
21#include <linux/syscalls.h>
c59ede7b 22#include <linux/capability.h>
1da177e4
LT
23#include <linux/init.h>
24#include <linux/file.h>
25#include <linux/fs.h>
26#include <linux/personality.h>
27#include <linux/security.h>
28#include <linux/hugetlb.h>
c01d5b30 29#include <linux/shmem_fs.h>
1da177e4 30#include <linux/profile.h>
b95f1b31 31#include <linux/export.h>
1da177e4
LT
32#include <linux/mount.h>
33#include <linux/mempolicy.h>
34#include <linux/rmap.h>
cddb8a5c 35#include <linux/mmu_notifier.h>
82f71ae4 36#include <linux/mmdebug.h>
cdd6c482 37#include <linux/perf_event.h>
120a795d 38#include <linux/audit.h>
b15d00b6 39#include <linux/khugepaged.h>
2b144498 40#include <linux/uprobes.h>
1640879a
AS
41#include <linux/notifier.h>
42#include <linux/memory.h>
b1de0d13 43#include <linux/printk.h>
19a809af 44#include <linux/userfaultfd_k.h>
d977d56c 45#include <linux/moduleparam.h>
62b5f7d0 46#include <linux/pkeys.h>
21292580 47#include <linux/oom.h>
04f5866e 48#include <linux/sched/mm.h>
d7597f59 49#include <linux/ksm.h>
8ec396d0 50#include <linux/memfd.h>
1da177e4 51
7c0f6ba6 52#include <linux/uaccess.h>
1da177e4
LT
53#include <asm/cacheflush.h>
54#include <asm/tlb.h>
d6dd61c8 55#include <asm/mmu_context.h>
1da177e4 56
df529cab
JK
57#define CREATE_TRACE_POINTS
58#include <trace/events/mmap.h>
59
42b77728
JB
60#include "internal.h"
61
3a459756
KK
62#ifndef arch_mmap_check
63#define arch_mmap_check(addr, len, flags) (0)
64#endif
65
d07e2259
DC
66#ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
67const int mmap_rnd_bits_min = CONFIG_ARCH_MMAP_RND_BITS_MIN;
71a5849a 68int mmap_rnd_bits_max __ro_after_init = CONFIG_ARCH_MMAP_RND_BITS_MAX;
d07e2259
DC
69int mmap_rnd_bits __read_mostly = CONFIG_ARCH_MMAP_RND_BITS;
70#endif
71#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
72const int mmap_rnd_compat_bits_min = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MIN;
73const int mmap_rnd_compat_bits_max = CONFIG_ARCH_MMAP_RND_COMPAT_BITS_MAX;
74int mmap_rnd_compat_bits __read_mostly = CONFIG_ARCH_MMAP_RND_COMPAT_BITS;
75#endif
76
f4fcd558 77static bool ignore_rlimit_data;
d977d56c 78core_param(ignore_rlimit_data, ignore_rlimit_data, bool, 0644);
d07e2259 79
64e45507
PF
80/* Update vma->vm_page_prot to reflect vma->vm_flags. */
81void vma_set_page_prot(struct vm_area_struct *vma)
82{
83 unsigned long vm_flags = vma->vm_flags;
6d2329f8 84 pgprot_t vm_page_prot;
64e45507 85
6d2329f8
AA
86 vm_page_prot = vm_pgprot_modify(vma->vm_page_prot, vm_flags);
87 if (vma_wants_writenotify(vma, vm_page_prot)) {
64e45507 88 vm_flags &= ~VM_SHARED;
6d2329f8 89 vm_page_prot = vm_pgprot_modify(vm_page_prot, vm_flags);
64e45507 90 }
c1e8d7c6 91 /* remove_protection_ptes reads vma->vm_page_prot without mmap_lock */
6d2329f8 92 WRITE_ONCE(vma->vm_page_prot, vm_page_prot);
64e45507
PF
93}
94
2e7ce7d3
LH
95/*
96 * check_brk_limits() - Use platform specific check of range & verify mlock
97 * limits.
98 * @addr: The address to check
99 * @len: The size of increase.
100 *
101 * Return: 0 on success.
102 */
103static int check_brk_limits(unsigned long addr, unsigned long len)
104{
105 unsigned long mapped_addr;
106
107 mapped_addr = get_unmapped_area(NULL, addr, len, 0, MAP_FIXED);
108 if (IS_ERR_VALUE(mapped_addr))
109 return mapped_addr;
110
b0cc5e89 111 return mlock_future_ok(current->mm, current->mm->def_flags, len)
3c54a298 112 ? 0 : -EAGAIN;
2e7ce7d3 113}
7d344bab 114
6a6160a7 115SYSCALL_DEFINE1(brk, unsigned long, brk)
1da177e4 116{
9bc8039e 117 unsigned long newbrk, oldbrk, origbrk;
1da177e4 118 struct mm_struct *mm = current->mm;
2e7ce7d3 119 struct vm_area_struct *brkvma, *next = NULL;
a5b4592c 120 unsigned long min_brk;
408579cd 121 bool populate = false;
897ab3e0 122 LIST_HEAD(uf);
92fed820 123 struct vma_iterator vmi;
1da177e4 124
d8ed45c5 125 if (mmap_write_lock_killable(mm))
dc0ef0df 126 return -EINTR;
1da177e4 127
9bc8039e
YS
128 origbrk = mm->brk;
129
a5b4592c 130#ifdef CONFIG_COMPAT_BRK
5520e894
JK
131 /*
132 * CONFIG_COMPAT_BRK can still be overridden by setting
133 * randomize_va_space to 2, which will still cause mm->start_brk
134 * to be arbitrarily shifted
135 */
4471a675 136 if (current->brk_randomized)
5520e894
JK
137 min_brk = mm->start_brk;
138 else
139 min_brk = mm->end_data;
a5b4592c
JK
140#else
141 min_brk = mm->start_brk;
142#endif
143 if (brk < min_brk)
1da177e4 144 goto out;
1e624196
RG
145
146 /*
147 * Check against rlimit here. If this check is done later after the test
148 * of oldbrk with newbrk then it can escape the test and let the data
149 * segment grow beyond its set limit the in case where the limit is
150 * not page aligned -Ram Gupta
151 */
8764b338
CG
152 if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk,
153 mm->end_data, mm->start_data))
1e624196
RG
154 goto out;
155
1da177e4
LT
156 newbrk = PAGE_ALIGN(brk);
157 oldbrk = PAGE_ALIGN(mm->brk);
9bc8039e
YS
158 if (oldbrk == newbrk) {
159 mm->brk = brk;
160 goto success;
161 }
1da177e4 162
408579cd 163 /* Always allow shrinking brk. */
1da177e4 164 if (brk <= mm->brk) {
2e7ce7d3 165 /* Search one past newbrk */
92fed820
LH
166 vma_iter_init(&vmi, mm, newbrk);
167 brkvma = vma_find(&vmi, oldbrk);
f5ad5083 168 if (!brkvma || brkvma->vm_start >= oldbrk)
2e7ce7d3 169 goto out; /* mapping intersects with an existing non-brk vma. */
9bc8039e 170 /*
2e7ce7d3 171 * mm->brk must be protected by write mmap_lock.
63fc66f5
LH
172 * do_vmi_align_munmap() will drop the lock on success, so
173 * update it before calling do_vma_munmap().
9bc8039e
YS
174 */
175 mm->brk = brk;
63fc66f5
LH
176 if (do_vmi_align_munmap(&vmi, brkvma, mm, newbrk, oldbrk, &uf,
177 /* unlock = */ true))
408579cd
LH
178 goto out;
179
180 goto success_unlocked;
1da177e4
LT
181 }
182
2e7ce7d3
LH
183 if (check_brk_limits(oldbrk, newbrk - oldbrk))
184 goto out;
185
186 /*
187 * Only check if the next VMA is within the stack_guard_gap of the
188 * expansion area
189 */
92fed820
LH
190 vma_iter_init(&vmi, mm, oldbrk);
191 next = vma_find(&vmi, newbrk + PAGE_SIZE + stack_guard_gap);
1be7107f 192 if (next && newbrk + PAGE_SIZE > vm_start_gap(next))
1da177e4
LT
193 goto out;
194
92fed820 195 brkvma = vma_prev_limit(&vmi, mm->start_brk);
1da177e4 196 /* Ok, looks good - let it rip. */
92fed820 197 if (do_brk_flags(&vmi, brkvma, oldbrk, newbrk - oldbrk, 0) < 0)
1da177e4 198 goto out;
2e7ce7d3 199
49b1b8d6
LS
200 mm->brk = brk;
201 if (mm->def_flags & VM_LOCKED)
202 populate = true;
a67c8caa 203
49b1b8d6
LS
204success:
205 mmap_write_unlock(mm);
206success_unlocked:
207 userfaultfd_unmap_complete(mm, &uf);
208 if (populate)
209 mm_populate(oldbrk, newbrk - oldbrk);
210 return brk;
a67c8caa 211
49b1b8d6
LS
212out:
213 mm->brk = origbrk;
214 mmap_write_unlock(mm);
215 return origbrk;
1da177e4
LT
216}
217
40401530
AV
218/*
219 * If a hint addr is less than mmap_min_addr change hint to be as
220 * low as possible but still greater than mmap_min_addr
221 */
222static inline unsigned long round_hint_to_min(unsigned long hint)
223{
224 hint &= PAGE_MASK;
225 if (((void *)hint != NULL) &&
226 (hint < mmap_min_addr))
227 return PAGE_ALIGN(mmap_min_addr);
228 return hint;
229}
230
b0cc5e89 231bool mlock_future_ok(struct mm_struct *mm, unsigned long flags,
3c54a298 232 unsigned long bytes)
363ee17f 233{
3c54a298 234 unsigned long locked_pages, limit_pages;
363ee17f 235
3c54a298
LS
236 if (!(flags & VM_LOCKED) || capable(CAP_IPC_LOCK))
237 return true;
238
239 locked_pages = bytes >> PAGE_SHIFT;
240 locked_pages += mm->locked_vm;
241
242 limit_pages = rlimit(RLIMIT_MEMLOCK);
243 limit_pages >>= PAGE_SHIFT;
244
245 return locked_pages <= limit_pages;
363ee17f
DB
246}
247
be83bbf8
LT
248static inline u64 file_mmap_size_max(struct file *file, struct inode *inode)
249{
250 if (S_ISREG(inode->i_mode))
423913ad 251 return MAX_LFS_FILESIZE;
be83bbf8
LT
252
253 if (S_ISBLK(inode->i_mode))
254 return MAX_LFS_FILESIZE;
255
76f34950
IK
256 if (S_ISSOCK(inode->i_mode))
257 return MAX_LFS_FILESIZE;
258
be83bbf8 259 /* Special "we do even unsigned file positions" case */
641bb439 260 if (file->f_op->fop_flags & FOP_UNSIGNED_OFFSET)
be83bbf8
LT
261 return 0;
262
263 /* Yes, random drivers might want more. But I'm tired of buggy drivers */
264 return ULONG_MAX;
265}
266
267static inline bool file_mmap_ok(struct file *file, struct inode *inode,
268 unsigned long pgoff, unsigned long len)
269{
270 u64 maxsize = file_mmap_size_max(file, inode);
271
272 if (maxsize && len > maxsize)
273 return false;
274 maxsize -= len;
275 if (pgoff > maxsize >> PAGE_SHIFT)
276 return false;
277 return true;
278}
279
8ad946eb
LS
280/**
281 * do_mmap() - Perform a userland memory mapping into the current process
282 * address space of length @len with protection bits @prot, mmap flags @flags
283 * (from which VMA flags will be inferred), and any additional VMA flags to
284 * apply @vm_flags. If this is a file-backed mapping then the file is specified
285 * in @file and page offset into the file via @pgoff.
286 *
287 * This function does not perform security checks on the file and assumes, if
288 * @uf is non-NULL, the caller has provided a list head to track unmap events
289 * for userfaultfd @uf.
290 *
291 * It also simply indicates whether memory population is required by setting
292 * @populate, which must be non-NULL, expecting the caller to actually perform
293 * this task itself if appropriate.
294 *
295 * This function will invoke architecture-specific (and if provided and
296 * relevant, file system-specific) logic to determine the most appropriate
297 * unmapped area in which to place the mapping if not MAP_FIXED.
298 *
299 * Callers which require userland mmap() behaviour should invoke vm_mmap(),
300 * which is also exported for module use.
301 *
302 * Those which require this behaviour less security checks, userfaultfd and
303 * populate behaviour, and who handle the mmap write lock themselves, should
304 * call this function.
305 *
306 * Note that the returned address may reside within a merged VMA if an
307 * appropriate merge were to take place, so it doesn't necessarily specify the
308 * start of a VMA, rather only the start of a valid mapped range of length
309 * @len bytes, rounded down to the nearest page size.
310 *
3e4e28c5 311 * The caller must write-lock current->mm->mmap_lock.
8ad946eb
LS
312 *
313 * @file: An optional struct file pointer describing the file which is to be
314 * mapped, if a file-backed mapping.
315 * @addr: If non-zero, hints at (or if @flags has MAP_FIXED set, specifies) the
316 * address at which to perform this mapping. See mmap (2) for details. Must be
317 * page-aligned.
318 * @len: The length of the mapping. Will be page-aligned and must be at least 1
319 * page in size.
320 * @prot: Protection bits describing access required to the mapping. See mmap
321 * (2) for details.
322 * @flags: Flags specifying how the mapping should be performed, see mmap (2)
323 * for details.
324 * @vm_flags: VMA flags which should be set by default, or 0 otherwise.
325 * @pgoff: Page offset into the @file if file-backed, should be 0 otherwise.
326 * @populate: A pointer to a value which will be set to 0 if no population of
327 * the range is required, or the number of bytes to populate if it is. Must be
328 * non-NULL. See mmap (2) for details as to under what circumstances population
329 * of the range occurs.
330 * @uf: An optional pointer to a list head to track userfaultfd unmap events
331 * should unmapping events arise. If provided, it is up to the caller to manage
332 * this.
333 *
334 * Returns: Either an error, or the address at which the requested mapping has
335 * been performed.
1da177e4 336 */
1fcfd8db 337unsigned long do_mmap(struct file *file, unsigned long addr,
1da177e4 338 unsigned long len, unsigned long prot,
592b5fad
YY
339 unsigned long flags, vm_flags_t vm_flags,
340 unsigned long pgoff, unsigned long *populate,
341 struct list_head *uf)
1da177e4 342{
cc71aba3 343 struct mm_struct *mm = current->mm;
62b5f7d0 344 int pkey = 0;
1da177e4 345
41badc15 346 *populate = 0;
bebeb3d6 347
df31155a
LS
348 mmap_assert_write_locked(mm);
349
e37609bb
PK
350 if (!len)
351 return -EINVAL;
352
1da177e4
LT
353 /*
354 * Does the application expect PROT_READ to imply PROT_EXEC?
355 *
356 * (the exception is when the underlying filesystem is noexec
be16dd76 357 * mounted, in which case we don't add PROT_EXEC.)
1da177e4
LT
358 */
359 if ((prot & PROT_READ) && (current->personality & READ_IMPLIES_EXEC))
90f8572b 360 if (!(file && path_noexec(&file->f_path)))
1da177e4
LT
361 prot |= PROT_EXEC;
362
a4ff8e86
MH
363 /* force arch specific MAP_FIXED handling in get_unmapped_area */
364 if (flags & MAP_FIXED_NOREPLACE)
365 flags |= MAP_FIXED;
366
7cd94146
EP
367 if (!(flags & MAP_FIXED))
368 addr = round_hint_to_min(addr);
369
1da177e4
LT
370 /* Careful about overflows.. */
371 len = PAGE_ALIGN(len);
9206de95 372 if (!len)
1da177e4
LT
373 return -ENOMEM;
374
375 /* offset overflow? */
376 if ((pgoff + (len >> PAGE_SHIFT)) < pgoff)
cc71aba3 377 return -EOVERFLOW;
1da177e4
LT
378
379 /* Too many mappings? */
380 if (mm->map_count > sysctl_max_map_count)
381 return -ENOMEM;
382
8be7258a
JX
383 /*
384 * addr is returned from get_unmapped_area,
385 * There are two cases:
386 * 1> MAP_FIXED == false
387 * unallocated memory, no need to check sealing.
388 * 1> MAP_FIXED == true
389 * sealing is checked inside mmap_region when
390 * do_vmi_munmap is called.
391 */
392
62b5f7d0
DH
393 if (prot == PROT_EXEC) {
394 pkey = execute_only_pkey(mm);
395 if (pkey < 0)
396 pkey = 0;
397 }
398
1da177e4
LT
399 /* Do simple checking here so the lower-level routines won't have
400 * to. we assume access permissions have been handled by the open
401 * of the memory object, so we don't do any here.
402 */
5baf8b03 403 vm_flags |= calc_vm_prot_bits(prot, pkey) | calc_vm_flag_bits(file, flags) |
1da177e4
LT
404 mm->def_flags | VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
405
8a0fe564
RE
406 /* Obtain the address to map to. we verify (or select) it and ensure
407 * that it represents a valid section of the address space.
408 */
409 addr = __get_unmapped_area(file, addr, len, pgoff, flags, vm_flags);
410 if (IS_ERR_VALUE(addr))
411 return addr;
412
413 if (flags & MAP_FIXED_NOREPLACE) {
414 if (find_vma_intersection(mm, addr, addr + len))
415 return -EEXIST;
416 }
417
cdf7b341 418 if (flags & MAP_LOCKED)
1da177e4
LT
419 if (!can_do_mlock())
420 return -EPERM;
ba470de4 421
b0cc5e89 422 if (!mlock_future_ok(mm, vm_flags, len))
363ee17f 423 return -EAGAIN;
1da177e4 424
1da177e4 425 if (file) {
077bf22b 426 struct inode *inode = file_inode(file);
1c972597 427 unsigned long flags_mask;
fa00b8ef 428 int err;
1c972597 429
be83bbf8
LT
430 if (!file_mmap_ok(file, inode, pgoff, len))
431 return -EOVERFLOW;
432
210a03c9
CB
433 flags_mask = LEGACY_MAP_MASK;
434 if (file->f_op->fop_flags & FOP_MMAP_SYNC)
435 flags_mask |= MAP_SYNC;
077bf22b 436
1da177e4
LT
437 switch (flags & MAP_TYPE) {
438 case MAP_SHARED:
1c972597
DW
439 /*
440 * Force use of MAP_SHARED_VALIDATE with non-legacy
441 * flags. E.g. MAP_SYNC is dangerous to use with
442 * MAP_SHARED as you don't know which consistency model
443 * you will get. We silently ignore unsupported flags
444 * with MAP_SHARED to preserve backward compatibility.
445 */
446 flags &= LEGACY_MAP_MASK;
e4a9bc58 447 fallthrough;
1c972597
DW
448 case MAP_SHARED_VALIDATE:
449 if (flags & ~flags_mask)
450 return -EOPNOTSUPP;
dc617f29
DW
451 if (prot & PROT_WRITE) {
452 if (!(file->f_mode & FMODE_WRITE))
453 return -EACCES;
454 if (IS_SWAPFILE(file->f_mapping->host))
455 return -ETXTBSY;
456 }
1da177e4
LT
457
458 /*
459 * Make sure we don't allow writing to an append-only
460 * file..
461 */
462 if (IS_APPEND(inode) && (file->f_mode & FMODE_WRITE))
463 return -EACCES;
464
1da177e4
LT
465 vm_flags |= VM_SHARED | VM_MAYSHARE;
466 if (!(file->f_mode & FMODE_WRITE))
467 vm_flags &= ~(VM_MAYWRITE | VM_SHARED);
e4a9bc58 468 fallthrough;
1da177e4
LT
469 case MAP_PRIVATE:
470 if (!(file->f_mode & FMODE_READ))
471 return -EACCES;
90f8572b 472 if (path_noexec(&file->f_path)) {
80c5606c
LT
473 if (vm_flags & VM_EXEC)
474 return -EPERM;
475 vm_flags &= ~VM_MAYEXEC;
476 }
80c5606c 477
c84bf6dd 478 if (!file_has_valid_mmap_hooks(file))
80c5606c 479 return -ENODEV;
b2c56e4f
ON
480 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
481 return -EINVAL;
1da177e4
LT
482 break;
483
484 default:
485 return -EINVAL;
486 }
fa00b8ef
LS
487
488 /*
489 * Check to see if we are violating any seals and update VMA
490 * flags if necessary to avoid future seal violations.
491 */
492 err = memfd_check_seals_mmap(file, &vm_flags);
493 if (err)
494 return (unsigned long)err;
1da177e4
LT
495 } else {
496 switch (flags & MAP_TYPE) {
497 case MAP_SHARED:
b2c56e4f
ON
498 if (vm_flags & (VM_GROWSDOWN|VM_GROWSUP))
499 return -EINVAL;
ce363942
TH
500 /*
501 * Ignore pgoff.
502 */
503 pgoff = 0;
1da177e4
LT
504 vm_flags |= VM_SHARED | VM_MAYSHARE;
505 break;
9651fced
JD
506 case MAP_DROPPABLE:
507 if (VM_DROPPABLE == VM_NONE)
508 return -ENOTSUPP;
509 /*
510 * A locked or stack area makes no sense to be droppable.
511 *
512 * Also, since droppable pages can just go away at any time
513 * it makes no sense to copy them on fork or dump them.
514 *
515 * And don't attempt to combine with hugetlb for now.
516 */
517 if (flags & (MAP_LOCKED | MAP_HUGETLB))
518 return -EINVAL;
519 if (vm_flags & (VM_GROWSDOWN | VM_GROWSUP))
520 return -EINVAL;
521
522 vm_flags |= VM_DROPPABLE;
523
524 /*
525 * If the pages can be dropped, then it doesn't make
526 * sense to reserve them.
527 */
528 vm_flags |= VM_NORESERVE;
529
530 /*
531 * Likewise, they're volatile enough that they
532 * shouldn't survive forks or coredumps.
533 */
534 vm_flags |= VM_WIPEONFORK | VM_DONTDUMP;
535 fallthrough;
1da177e4
LT
536 case MAP_PRIVATE:
537 /*
538 * Set pgoff according to addr for anon_vma.
539 */
540 pgoff = addr >> PAGE_SHIFT;
541 break;
542 default:
543 return -EINVAL;
544 }
545 }
546
c22c0d63
ML
547 /*
548 * Set 'VM_NORESERVE' if we should not account for the
549 * memory use of this mapping.
550 */
551 if (flags & MAP_NORESERVE) {
552 /* We honor MAP_NORESERVE if allowed to overcommit */
553 if (sysctl_overcommit_memory != OVERCOMMIT_NEVER)
554 vm_flags |= VM_NORESERVE;
555
556 /* hugetlb applies strict overcommit unless MAP_NORESERVE */
557 if (file && is_file_hugepages(file))
558 vm_flags |= VM_NORESERVE;
559 }
560
897ab3e0 561 addr = mmap_region(file, addr, len, vm_flags, pgoff, uf);
09a9f1d2
ML
562 if (!IS_ERR_VALUE(addr) &&
563 ((vm_flags & VM_LOCKED) ||
564 (flags & (MAP_POPULATE | MAP_NONBLOCK)) == MAP_POPULATE))
41badc15 565 *populate = len;
bebeb3d6 566 return addr;
0165ab44 567}
6be5ceb0 568
a90f590a
DB
569unsigned long ksys_mmap_pgoff(unsigned long addr, unsigned long len,
570 unsigned long prot, unsigned long flags,
571 unsigned long fd, unsigned long pgoff)
66f0dc48
HD
572{
573 struct file *file = NULL;
1e3ee14b 574 unsigned long retval;
66f0dc48
HD
575
576 if (!(flags & MAP_ANONYMOUS)) {
120a795d 577 audit_mmap_fd(fd, flags);
66f0dc48
HD
578 file = fget(fd);
579 if (!file)
1e3ee14b 580 return -EBADF;
7bba8f0e 581 if (is_file_hugepages(file)) {
af73e4d9 582 len = ALIGN(len, huge_page_size(hstate_file(file)));
7bba8f0e
ZL
583 } else if (unlikely(flags & MAP_HUGETLB)) {
584 retval = -EINVAL;
493af578 585 goto out_fput;
7bba8f0e 586 }
66f0dc48 587 } else if (flags & MAP_HUGETLB) {
c103a4dc 588 struct hstate *hs;
af73e4d9 589
20ac2893 590 hs = hstate_sizelog((flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
091d0d55
LZ
591 if (!hs)
592 return -EINVAL;
593
594 len = ALIGN(len, huge_page_size(hs));
66f0dc48
HD
595 /*
596 * VM_NORESERVE is used because the reservations will be
597 * taken when vm_ops->mmap() is called
66f0dc48 598 */
af73e4d9 599 file = hugetlb_file_setup(HUGETLB_ANON_FILE, len,
42d7395f 600 VM_NORESERVE,
83c1fd76 601 HUGETLB_ANONHUGE_INODE,
42d7395f 602 (flags >> MAP_HUGE_SHIFT) & MAP_HUGE_MASK);
66f0dc48
HD
603 if (IS_ERR(file))
604 return PTR_ERR(file);
605 }
606
9fbeb5ab 607 retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
493af578 608out_fput:
66f0dc48
HD
609 if (file)
610 fput(file);
66f0dc48
HD
611 return retval;
612}
613
a90f590a
DB
614SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
615 unsigned long, prot, unsigned long, flags,
616 unsigned long, fd, unsigned long, pgoff)
617{
618 return ksys_mmap_pgoff(addr, len, prot, flags, fd, pgoff);
619}
620
a4679373
CH
621#ifdef __ARCH_WANT_SYS_OLD_MMAP
622struct mmap_arg_struct {
623 unsigned long addr;
624 unsigned long len;
625 unsigned long prot;
626 unsigned long flags;
627 unsigned long fd;
628 unsigned long offset;
629};
630
631SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
632{
633 struct mmap_arg_struct a;
634
635 if (copy_from_user(&a, arg, sizeof(a)))
636 return -EFAULT;
de1741a1 637 if (offset_in_page(a.offset))
a4679373
CH
638 return -EINVAL;
639
a90f590a
DB
640 return ksys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
641 a.offset >> PAGE_SHIFT);
a4679373
CH
642}
643#endif /* __ARCH_WANT_SYS_OLD_MMAP */
644
df7e1286
MB
645/*
646 * Determine if the allocation needs to ensure that there is no
647 * existing mapping within it's guard gaps, for use as start_gap.
648 */
649static inline unsigned long stack_guard_placement(vm_flags_t vm_flags)
650{
651 if (vm_flags & VM_SHADOW_STACK)
652 return PAGE_SIZE;
653
654 return 0;
655}
656
baceaf1c
JK
657/*
658 * Search for an unmapped address range.
659 *
660 * We are looking for a range that:
661 * - does not intersect with any VMA;
662 * - is contained within the [low_limit, high_limit) interval;
663 * - is at least the desired size.
664 * - satisfies (begin_addr & align_mask) == (align_offset & align_mask)
665 */
666unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info)
667{
df529cab
JK
668 unsigned long addr;
669
baceaf1c 670 if (info->flags & VM_UNMAPPED_AREA_TOPDOWN)
df529cab 671 addr = unmapped_area_topdown(info);
baceaf1c 672 else
df529cab
JK
673 addr = unmapped_area(info);
674
675 trace_vm_unmapped_area(addr, info);
676 return addr;
baceaf1c 677}
f6795053 678
1da177e4
LT
679/* Get an address range which is currently unmapped.
680 * For shmat() with addr=0.
681 *
682 * Ugly calling convention alert:
683 * Return value with the low bits set means error value,
684 * ie
685 * if (ret & ~PAGE_MASK)
686 * error = ret;
687 *
688 * This function "knows" that -ENOMEM has the bits set.
689 */
1da177e4 690unsigned long
4b439e25
CL
691generic_get_unmapped_area(struct file *filp, unsigned long addr,
692 unsigned long len, unsigned long pgoff,
540e00a7 693 unsigned long flags, vm_flags_t vm_flags)
1da177e4
LT
694{
695 struct mm_struct *mm = current->mm;
1be7107f 696 struct vm_area_struct *vma, *prev;
b80fa3cb 697 struct vm_unmapped_area_info info = {};
2cb4de08 698 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1da177e4 699
f6795053 700 if (len > mmap_end - mmap_min_addr)
1da177e4
LT
701 return -ENOMEM;
702
06abdfb4
BH
703 if (flags & MAP_FIXED)
704 return addr;
705
1da177e4
LT
706 if (addr) {
707 addr = PAGE_ALIGN(addr);
1be7107f 708 vma = find_vma_prev(mm, addr, &prev);
f6795053 709 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1be7107f
HD
710 (!vma || addr + len <= vm_start_gap(vma)) &&
711 (!prev || addr >= vm_end_gap(prev)))
1da177e4
LT
712 return addr;
713 }
1da177e4 714
db4fbfb9 715 info.length = len;
4e99b021 716 info.low_limit = mm->mmap_base;
f6795053 717 info.high_limit = mmap_end;
df7e1286 718 info.start_gap = stack_guard_placement(vm_flags);
7f24cbc9
OS
719 if (filp && is_file_hugepages(filp))
720 info.align_mask = huge_page_mask_align(filp);
db4fbfb9 721 return vm_unmapped_area(&info);
1da177e4 722}
4b439e25
CL
723
724#ifndef HAVE_ARCH_UNMAPPED_AREA
725unsigned long
726arch_get_unmapped_area(struct file *filp, unsigned long addr,
727 unsigned long len, unsigned long pgoff,
25d4054c 728 unsigned long flags, vm_flags_t vm_flags)
4b439e25 729{
540e00a7
MB
730 return generic_get_unmapped_area(filp, addr, len, pgoff, flags,
731 vm_flags);
4b439e25 732}
cc71aba3 733#endif
1da177e4 734
1da177e4
LT
735/*
736 * This mmap-allocator allocates new areas top-down from below the
737 * stack's low limit (the base):
738 */
1da177e4 739unsigned long
4b439e25
CL
740generic_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
741 unsigned long len, unsigned long pgoff,
540e00a7 742 unsigned long flags, vm_flags_t vm_flags)
1da177e4 743{
1be7107f 744 struct vm_area_struct *vma, *prev;
1da177e4 745 struct mm_struct *mm = current->mm;
b80fa3cb 746 struct vm_unmapped_area_info info = {};
2cb4de08 747 const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
1da177e4
LT
748
749 /* requested length too big for entire address space */
f6795053 750 if (len > mmap_end - mmap_min_addr)
1da177e4
LT
751 return -ENOMEM;
752
06abdfb4
BH
753 if (flags & MAP_FIXED)
754 return addr;
755
1da177e4
LT
756 /* requesting a specific address */
757 if (addr) {
758 addr = PAGE_ALIGN(addr);
1be7107f 759 vma = find_vma_prev(mm, addr, &prev);
f6795053 760 if (mmap_end - len >= addr && addr >= mmap_min_addr &&
1be7107f
HD
761 (!vma || addr + len <= vm_start_gap(vma)) &&
762 (!prev || addr >= vm_end_gap(prev)))
1da177e4
LT
763 return addr;
764 }
765
db4fbfb9
ML
766 info.flags = VM_UNMAPPED_AREA_TOPDOWN;
767 info.length = len;
6b008640 768 info.low_limit = PAGE_SIZE;
f6795053 769 info.high_limit = arch_get_mmap_base(addr, mm->mmap_base);
df7e1286 770 info.start_gap = stack_guard_placement(vm_flags);
7f24cbc9
OS
771 if (filp && is_file_hugepages(filp))
772 info.align_mask = huge_page_mask_align(filp);
db4fbfb9 773 addr = vm_unmapped_area(&info);
b716ad95 774
1da177e4
LT
775 /*
776 * A failed mmap() very likely causes application failure,
777 * so fall back to the bottom-up function here. This scenario
778 * can happen with large stack limits and large mmap()
779 * allocations.
780 */
de1741a1 781 if (offset_in_page(addr)) {
db4fbfb9
ML
782 VM_BUG_ON(addr != -ENOMEM);
783 info.flags = 0;
784 info.low_limit = TASK_UNMAPPED_BASE;
f6795053 785 info.high_limit = mmap_end;
db4fbfb9
ML
786 addr = vm_unmapped_area(&info);
787 }
1da177e4
LT
788
789 return addr;
790}
4b439e25
CL
791
792#ifndef HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
793unsigned long
794arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
795 unsigned long len, unsigned long pgoff,
25d4054c 796 unsigned long flags, vm_flags_t vm_flags)
96114870 797{
540e00a7
MB
798 return generic_get_unmapped_area_topdown(filp, addr, len, pgoff, flags,
799 vm_flags);
96114870
RE
800}
801#endif
802
803unsigned long mm_get_unmapped_area_vmflags(struct mm_struct *mm, struct file *filp,
804 unsigned long addr, unsigned long len,
805 unsigned long pgoff, unsigned long flags,
806 vm_flags_t vm_flags)
807{
808 if (test_bit(MMF_TOPDOWN, &mm->flags))
25d4054c
MB
809 return arch_get_unmapped_area_topdown(filp, addr, len, pgoff,
810 flags, vm_flags);
811 return arch_get_unmapped_area(filp, addr, len, pgoff, flags, vm_flags);
96114870
RE
812}
813
1da177e4 814unsigned long
8a0fe564
RE
815__get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
816 unsigned long pgoff, unsigned long flags, vm_flags_t vm_flags)
1da177e4 817{
06abdfb4 818 unsigned long (*get_area)(struct file *, unsigned long,
529ce23a
RE
819 unsigned long, unsigned long, unsigned long)
820 = NULL;
06abdfb4 821
9206de95
AV
822 unsigned long error = arch_mmap_check(addr, len, flags);
823 if (error)
824 return error;
825
826 /* Careful about overflows.. */
827 if (len > TASK_SIZE)
828 return -ENOMEM;
829
c01d5b30
HD
830 if (file) {
831 if (file->f_op->get_unmapped_area)
832 get_area = file->f_op->get_unmapped_area;
833 } else if (flags & MAP_SHARED) {
834 /*
835 * mmap_region() will call shmem_zero_setup() to create a file,
836 * so use shmem's get_unmapped_area in case it can be huge.
c01d5b30 837 */
c01d5b30
HD
838 get_area = shmem_get_unmapped_area;
839 }
840
96204e15
RR
841 /* Always treat pgoff as zero for anonymous memory. */
842 if (!file)
843 pgoff = 0;
844
ed48e87c 845 if (get_area) {
529ce23a 846 addr = get_area(file, addr, len, pgoff, flags);
34d7cf63 847 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && !file
249608ee 848 && !addr /* no hint */
d4148aea 849 && IS_ALIGNED(len, PMD_SIZE)) {
ed48e87c
RE
850 /* Ensures that larger anonymous mappings are THP aligned. */
851 addr = thp_get_unmapped_area_vmflags(file, addr, len,
852 pgoff, flags, vm_flags);
853 } else {
8a0fe564
RE
854 addr = mm_get_unmapped_area_vmflags(current->mm, file, addr, len,
855 pgoff, flags, vm_flags);
ed48e87c 856 }
06abdfb4
BH
857 if (IS_ERR_VALUE(addr))
858 return addr;
1da177e4 859
07ab67c8
LT
860 if (addr > TASK_SIZE - len)
861 return -ENOMEM;
de1741a1 862 if (offset_in_page(addr))
07ab67c8 863 return -EINVAL;
06abdfb4 864
9ac4ed4b
AV
865 error = security_mmap_addr(addr);
866 return error ? error : addr;
1da177e4
LT
867}
868
529ce23a
RE
869unsigned long
870mm_get_unmapped_area(struct mm_struct *mm, struct file *file,
871 unsigned long addr, unsigned long len,
872 unsigned long pgoff, unsigned long flags)
873{
874 if (test_bit(MMF_TOPDOWN, &mm->flags))
25d4054c
MB
875 return arch_get_unmapped_area_topdown(file, addr, len, pgoff, flags, 0);
876 return arch_get_unmapped_area(file, addr, len, pgoff, flags, 0);
529ce23a
RE
877}
878EXPORT_SYMBOL(mm_get_unmapped_area);
1da177e4 879
abdba2dd
LH
880/**
881 * find_vma_intersection() - Look up the first VMA which intersects the interval
882 * @mm: The process address space.
883 * @start_addr: The inclusive start user address.
884 * @end_addr: The exclusive end user address.
885 *
886 * Returns: The first VMA within the provided range, %NULL otherwise. Assumes
887 * start_addr < end_addr.
888 */
889struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
890 unsigned long start_addr,
891 unsigned long end_addr)
892{
abdba2dd
LH
893 unsigned long index = start_addr;
894
895 mmap_assert_locked(mm);
7964cf8c 896 return mt_find(&mm->mm_mt, &index, end_addr - 1);
abdba2dd
LH
897}
898EXPORT_SYMBOL(find_vma_intersection);
899
be8432e7
LH
900/**
901 * find_vma() - Find the VMA for a given address, or the next VMA.
902 * @mm: The mm_struct to check
903 * @addr: The address
904 *
905 * Returns: The VMA associated with addr, or the next VMA.
906 * May return %NULL in the case of no VMA at addr or above.
907 */
48aae425 908struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
1da177e4 909{
be8432e7 910 unsigned long index = addr;
1da177e4 911
5b78ed24 912 mmap_assert_locked(mm);
7964cf8c 913 return mt_find(&mm->mm_mt, &index, ULONG_MAX);
1da177e4 914}
1da177e4
LT
915EXPORT_SYMBOL(find_vma);
916
7fdbd37d
LH
917/**
918 * find_vma_prev() - Find the VMA for a given address, or the next vma and
919 * set %pprev to the previous VMA, if any.
920 * @mm: The mm_struct to check
921 * @addr: The address
922 * @pprev: The pointer to set to the previous VMA
923 *
924 * Note that RCU lock is missing here since the external mmap_lock() is used
925 * instead.
926 *
927 * Returns: The VMA associated with @addr, or the next vma.
928 * May return %NULL in the case of no vma at addr or above.
6bd4837d 929 */
1da177e4
LT
930struct vm_area_struct *
931find_vma_prev(struct mm_struct *mm, unsigned long addr,
932 struct vm_area_struct **pprev)
933{
6bd4837d 934 struct vm_area_struct *vma;
d4e6b397 935 VMA_ITERATOR(vmi, mm, addr);
1da177e4 936
d4e6b397
YD
937 vma = vma_iter_load(&vmi);
938 *pprev = vma_prev(&vmi);
7fdbd37d 939 if (!vma)
d4e6b397 940 vma = vma_next(&vmi);
6bd4837d 941 return vma;
1da177e4
LT
942}
943
1be7107f
HD
944/* enforced gap between the expanding stack and other mappings. */
945unsigned long stack_guard_gap = 256UL<<PAGE_SHIFT;
946
947static int __init cmdline_parse_stack_guard_gap(char *p)
948{
949 unsigned long val;
950 char *endptr;
951
952 val = simple_strtoul(p, &endptr, 10);
953 if (!*endptr)
954 stack_guard_gap = val << PAGE_SHIFT;
955
e6d09493 956 return 1;
1be7107f
HD
957}
958__setup("stack_guard_gap=", cmdline_parse_stack_guard_gap);
959
b6a2fea3 960#ifdef CONFIG_STACK_GROWSUP
8d7071af 961int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
b6a2fea3
OW
962{
963 return expand_upwards(vma, address);
964}
965
8d7071af 966struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
b6a2fea3
OW
967{
968 struct vm_area_struct *vma, *prev;
969
970 addr &= PAGE_MASK;
971 vma = find_vma_prev(mm, addr, &prev);
972 if (vma && (vma->vm_start <= addr))
973 return vma;
f440fa1a
LH
974 if (!prev)
975 return NULL;
8d7071af 976 if (expand_stack_locked(prev, addr))
b6a2fea3 977 return NULL;
cea10a19 978 if (prev->vm_flags & VM_LOCKED)
fc05f566 979 populate_vma_page_range(prev, addr, prev->vm_end, NULL);
b6a2fea3
OW
980 return prev;
981}
982#else
8d7071af 983int expand_stack_locked(struct vm_area_struct *vma, unsigned long address)
b6a2fea3
OW
984{
985 return expand_downwards(vma, address);
986}
987
8d7071af 988struct vm_area_struct *find_extend_vma_locked(struct mm_struct *mm, unsigned long addr)
1da177e4 989{
cc71aba3 990 struct vm_area_struct *vma;
1da177e4
LT
991 unsigned long start;
992
993 addr &= PAGE_MASK;
cc71aba3 994 vma = find_vma(mm, addr);
1da177e4
LT
995 if (!vma)
996 return NULL;
997 if (vma->vm_start <= addr)
998 return vma;
1da177e4 999 start = vma->vm_start;
8d7071af 1000 if (expand_stack_locked(vma, addr))
1da177e4 1001 return NULL;
cea10a19 1002 if (vma->vm_flags & VM_LOCKED)
fc05f566 1003 populate_vma_page_range(vma, addr, start, NULL);
1da177e4
LT
1004 return vma;
1005}
1006#endif
1007
69e583ea 1008#if defined(CONFIG_STACK_GROWSUP)
8d7071af 1009
49b1b8d6
LS
1010#define vma_expand_up(vma,addr) expand_upwards(vma, addr)
1011#define vma_expand_down(vma, addr) (-EFAULT)
6935e052 1012
49b1b8d6 1013#else
1da177e4 1014
49b1b8d6
LS
1015#define vma_expand_up(vma,addr) (-EFAULT)
1016#define vma_expand_down(vma, addr) expand_downwards(vma, addr)
d4af56c5 1017
49b1b8d6 1018#endif
1da177e4 1019
11f9a21a 1020/*
49b1b8d6
LS
1021 * expand_stack(): legacy interface for page faulting. Don't use unless
1022 * you have to.
11f9a21a 1023 *
49b1b8d6
LS
1024 * This is called with the mm locked for reading, drops the lock, takes
1025 * the lock for writing, tries to look up a vma again, expands it if
1026 * necessary, and downgrades the lock to reading again.
11f9a21a 1027 *
49b1b8d6
LS
1028 * If no vma is found or it can't be expanded, it returns NULL and has
1029 * dropped the lock.
11f9a21a 1030 */
49b1b8d6 1031struct vm_area_struct *expand_stack(struct mm_struct *mm, unsigned long addr)
11f9a21a 1032{
49b1b8d6 1033 struct vm_area_struct *vma, *prev;
11f9a21a 1034
49b1b8d6
LS
1035 mmap_read_unlock(mm);
1036 if (mmap_write_lock_killable(mm))
1037 return NULL;
11f9a21a 1038
49b1b8d6
LS
1039 vma = find_vma_prev(mm, addr, &prev);
1040 if (vma && vma->vm_start <= addr)
1041 goto success;
11f9a21a 1042
49b1b8d6
LS
1043 if (prev && !vma_expand_up(prev, addr)) {
1044 vma = prev;
1045 goto success;
1046 }
8be7258a 1047
49b1b8d6
LS
1048 if (vma && !vma_expand_down(vma, addr))
1049 goto success;
11f9a21a 1050
49b1b8d6
LS
1051 mmap_write_unlock(mm);
1052 return NULL;
11f9a21a 1053
49b1b8d6
LS
1054success:
1055 mmap_write_downgrade(mm);
1056 return vma;
11f9a21a
LH
1057}
1058
1059/* do_munmap() - Wrapper function for non-maple tree aware do_munmap() calls.
1060 * @mm: The mm_struct
1061 * @start: The start address to munmap
1062 * @len: The length to be munmapped.
1063 * @uf: The userfaultfd list_head
408579cd
LH
1064 *
1065 * Return: 0 on success, error otherwise.
11f9a21a 1066 */
dd2283f2
YS
1067int do_munmap(struct mm_struct *mm, unsigned long start, size_t len,
1068 struct list_head *uf)
1069{
183654ce 1070 VMA_ITERATOR(vmi, mm, start);
11f9a21a 1071
183654ce 1072 return do_vmi_munmap(&vmi, mm, start, len, uf, false);
dd2283f2
YS
1073}
1074
dd2283f2
YS
1075int vm_munmap(unsigned long start, size_t len)
1076{
1077 return __vm_munmap(start, len, false);
1078}
a46ef99d
LT
1079EXPORT_SYMBOL(vm_munmap);
1080
1081SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
1082{
ce18d171 1083 addr = untagged_addr(addr);
dd2283f2 1084 return __vm_munmap(addr, len, true);
a46ef99d 1085}
1da177e4 1086
c8d78c18
KS
1087
1088/*
1089 * Emulation of deprecated remap_file_pages() syscall.
1090 */
1091SYSCALL_DEFINE5(remap_file_pages, unsigned long, start, unsigned long, size,
1092 unsigned long, prot, unsigned long, pgoff, unsigned long, flags)
1093{
1094
1095 struct mm_struct *mm = current->mm;
1096 struct vm_area_struct *vma;
1097 unsigned long populate = 0;
1098 unsigned long ret = -EINVAL;
1099 struct file *file;
58a039e6 1100 vm_flags_t vm_flags;
c8d78c18 1101
ee65728e 1102 pr_warn_once("%s (%d) uses deprecated remap_file_pages() syscall. See Documentation/mm/remap_file_pages.rst.\n",
756a025f 1103 current->comm, current->pid);
c8d78c18
KS
1104
1105 if (prot)
1106 return ret;
1107 start = start & PAGE_MASK;
1108 size = size & PAGE_MASK;
1109
1110 if (start + size <= start)
1111 return ret;
1112
1113 /* Does pgoff wrap? */
1114 if (pgoff + (size >> PAGE_SHIFT) < pgoff)
1115 return ret;
1116
58a039e6 1117 if (mmap_read_lock_killable(mm))
dc0ef0df
MH
1118 return -EINTR;
1119
58a039e6
KS
1120 /*
1121 * Look up VMA under read lock first so we can perform the security
1122 * without holding locks (which can be problematic). We reacquire a
1123 * write lock later and check nothing changed underneath us.
1124 */
9b593cb2 1125 vma = vma_lookup(mm, start);
c8d78c18 1126
58a039e6
KS
1127 if (!vma || !(vma->vm_flags & VM_SHARED)) {
1128 mmap_read_unlock(mm);
1129 return -EINVAL;
1130 }
1131
1132 prot |= vma->vm_flags & VM_READ ? PROT_READ : 0;
1133 prot |= vma->vm_flags & VM_WRITE ? PROT_WRITE : 0;
1134 prot |= vma->vm_flags & VM_EXEC ? PROT_EXEC : 0;
1135
1136 flags &= MAP_NONBLOCK;
1137 flags |= MAP_SHARED | MAP_FIXED | MAP_POPULATE;
1138 if (vma->vm_flags & VM_LOCKED)
1139 flags |= MAP_LOCKED;
1140
1141 /* Save vm_flags used to calculate prot and flags, and recheck later. */
1142 vm_flags = vma->vm_flags;
1143 file = get_file(vma->vm_file);
1144
1145 mmap_read_unlock(mm);
1146
1147 /* Call outside mmap_lock to be consistent with other callers. */
1148 ret = security_mmap_file(file, prot, flags);
1149 if (ret) {
1150 fput(file);
1151 return ret;
1152 }
1153
1154 ret = -EINVAL;
1155
1156 /* OK security check passed, take write lock + let it rip. */
1157 if (mmap_write_lock_killable(mm)) {
1158 fput(file);
1159 return -EINTR;
1160 }
1161
1162 vma = vma_lookup(mm, start);
1163
1164 if (!vma)
1165 goto out;
1166
1167 /* Make sure things didn't change under us. */
1168 if (vma->vm_flags != vm_flags)
1169 goto out;
1170 if (vma->vm_file != file)
c8d78c18
KS
1171 goto out;
1172
48f7df32 1173 if (start + size > vma->vm_end) {
763ecb03
LH
1174 VMA_ITERATOR(vmi, mm, vma->vm_end);
1175 struct vm_area_struct *next, *prev = vma;
48f7df32 1176
763ecb03 1177 for_each_vma_range(vmi, next, start + size) {
48f7df32 1178 /* hole between vmas ? */
763ecb03 1179 if (next->vm_start != prev->vm_end)
48f7df32
KS
1180 goto out;
1181
1182 if (next->vm_file != vma->vm_file)
1183 goto out;
1184
1185 if (next->vm_flags != vma->vm_flags)
1186 goto out;
1187
1db43d3f
LH
1188 if (start + size <= next->vm_end)
1189 break;
1190
763ecb03 1191 prev = next;
48f7df32
KS
1192 }
1193
1194 if (!next)
1195 goto out;
c8d78c18
KS
1196 }
1197
45e55300 1198 ret = do_mmap(vma->vm_file, start, size,
592b5fad 1199 prot, flags, 0, pgoff, &populate, NULL);
c8d78c18 1200out:
d8ed45c5 1201 mmap_write_unlock(mm);
58a039e6 1202 fput(file);
c8d78c18
KS
1203 if (populate)
1204 mm_populate(ret, populate);
1205 if (!IS_ERR_VALUE(ret))
1206 ret = 0;
1207 return ret;
1208}
1209
bb177a73 1210int vm_brk_flags(unsigned long addr, unsigned long request, unsigned long flags)
e4eb1ff6
LT
1211{
1212 struct mm_struct *mm = current->mm;
2e7ce7d3 1213 struct vm_area_struct *vma = NULL;
bb177a73 1214 unsigned long len;
5d22fc25 1215 int ret;
128557ff 1216 bool populate;
897ab3e0 1217 LIST_HEAD(uf);
92fed820 1218 VMA_ITERATOR(vmi, mm, addr);
e4eb1ff6 1219
bb177a73
MH
1220 len = PAGE_ALIGN(request);
1221 if (len < request)
1222 return -ENOMEM;
1223 if (!len)
1224 return 0;
1225
2e7ce7d3
LH
1226 /* Until we need other flags, refuse anything except VM_EXEC. */
1227 if ((flags & (~VM_EXEC)) != 0)
1228 return -EINVAL;
1229
e0f81ab1
SO
1230 if (mmap_write_lock_killable(mm))
1231 return -EINTR;
1232
2e7ce7d3
LH
1233 ret = check_brk_limits(addr, len);
1234 if (ret)
1235 goto limits_failed;
1236
183654ce 1237 ret = do_vmi_munmap(&vmi, mm, addr, len, &uf, 0);
2e7ce7d3
LH
1238 if (ret)
1239 goto munmap_failed;
1240
92fed820
LH
1241 vma = vma_prev(&vmi);
1242 ret = do_brk_flags(&vmi, vma, addr, len, flags);
128557ff 1243 populate = ((mm->def_flags & VM_LOCKED) != 0);
d8ed45c5 1244 mmap_write_unlock(mm);
897ab3e0 1245 userfaultfd_unmap_complete(mm, &uf);
5d22fc25 1246 if (populate && !ret)
128557ff 1247 mm_populate(addr, len);
e4eb1ff6 1248 return ret;
2e7ce7d3
LH
1249
1250munmap_failed:
1251limits_failed:
1252 mmap_write_unlock(mm);
1253 return ret;
e4eb1ff6 1254}
16e72e9b
DV
1255EXPORT_SYMBOL(vm_brk_flags);
1256
1da177e4
LT
1257/* Release all mmaps. */
1258void exit_mmap(struct mm_struct *mm)
1259{
d16dfc55 1260 struct mmu_gather tlb;
ba470de4 1261 struct vm_area_struct *vma;
1da177e4 1262 unsigned long nr_accounted = 0;
d4e6b397 1263 VMA_ITERATOR(vmi, mm, 0);
763ecb03 1264 int count = 0;
1da177e4 1265
d6dd61c8 1266 /* mm's last user has gone, and its about to be pulled down */
cddb8a5c 1267 mmu_notifier_release(mm);
d6dd61c8 1268
bf3980c8 1269 mmap_read_lock(mm);
9480c53e
JF
1270 arch_exit_mmap(mm);
1271
d4e6b397 1272 vma = vma_next(&vmi);
d2406291 1273 if (!vma || unlikely(xa_is_zero(vma))) {
64591e86 1274 /* Can happen if dup_mmap() received an OOM */
bf3980c8 1275 mmap_read_unlock(mm);
d2406291
PZ
1276 mmap_write_lock(mm);
1277 goto destroy;
64591e86 1278 }
9480c53e 1279
1da177e4 1280 flush_cache_mm(mm);
d8b45053 1281 tlb_gather_mmu_fullmm(&tlb, mm);
901608d9 1282 /* update_hiwater_rss(mm) here? but nobody should be looking */
763ecb03 1283 /* Use ULONG_MAX here to ensure all VMAs in the mm are unmapped */
d4e6b397 1284 unmap_vmas(&tlb, &vmi.mas, vma, 0, ULONG_MAX, ULONG_MAX, false);
bf3980c8
SB
1285 mmap_read_unlock(mm);
1286
1287 /*
1288 * Set MMF_OOM_SKIP to hide this task from the oom killer/reaper
b3541d91 1289 * because the memory has been already freed.
bf3980c8
SB
1290 */
1291 set_bit(MMF_OOM_SKIP, &mm->flags);
1292 mmap_write_lock(mm);
3dd44325 1293 mt_clear_in_rcu(&mm->mm_mt);
d4e6b397
YD
1294 vma_iter_set(&vmi, vma->vm_end);
1295 free_pgtables(&tlb, &vmi.mas, vma, FIRST_USER_ADDRESS,
98e51a22 1296 USER_PGTABLES_CEILING, true);
ae8eba8b 1297 tlb_finish_mmu(&tlb);
1da177e4 1298
763ecb03
LH
1299 /*
1300 * Walk the list again, actually closing and freeing it, with preemption
1301 * enabled, without holding any MM locks besides the unreachable
1302 * mmap_write_lock.
1303 */
d4e6b397 1304 vma_iter_set(&vmi, vma->vm_end);
763ecb03 1305 do {
4f74d2c8
LT
1306 if (vma->vm_flags & VM_ACCOUNT)
1307 nr_accounted += vma_pages(vma);
31041385
SB
1308 vma_mark_detached(vma);
1309 remove_vma(vma);
763ecb03 1310 count++;
0a3b3c25 1311 cond_resched();
d4e6b397 1312 vma = vma_next(&vmi);
d2406291 1313 } while (vma && likely(!xa_is_zero(vma)));
763ecb03
LH
1314
1315 BUG_ON(count != mm->map_count);
d4af56c5
LH
1316
1317 trace_exit_mmap(mm);
d2406291 1318destroy:
d4af56c5 1319 __mt_destroy(&mm->mm_mt);
64591e86 1320 mmap_write_unlock(mm);
4f74d2c8 1321 vm_unacct_memory(nr_accounted);
1da177e4
LT
1322}
1323
119f657c 1324/*
1325 * Return true if the calling process may expand its vm space by the passed
1326 * number of pages
1327 */
84638335 1328bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
119f657c 1329{
84638335
KK
1330 if (mm->total_vm + npages > rlimit(RLIMIT_AS) >> PAGE_SHIFT)
1331 return false;
119f657c 1332
d977d56c
KK
1333 if (is_data_mapping(flags) &&
1334 mm->data_vm + npages > rlimit(RLIMIT_DATA) >> PAGE_SHIFT) {
f4fcd558
KK
1335 /* Workaround for Valgrind */
1336 if (rlimit(RLIMIT_DATA) == 0 &&
1337 mm->data_vm + npages <= rlimit_max(RLIMIT_DATA) >> PAGE_SHIFT)
1338 return true;
57a7702b
DW
1339
1340 pr_warn_once("%s (%d): VmData %lu exceed data ulimit %lu. Update limits%s.\n",
1341 current->comm, current->pid,
1342 (mm->data_vm + npages) << PAGE_SHIFT,
1343 rlimit(RLIMIT_DATA),
1344 ignore_rlimit_data ? "" : " or use boot option ignore_rlimit_data");
1345
1346 if (!ignore_rlimit_data)
d977d56c
KK
1347 return false;
1348 }
119f657c 1349
84638335
KK
1350 return true;
1351}
1352
1353void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
1354{
7866076b 1355 WRITE_ONCE(mm->total_vm, READ_ONCE(mm->total_vm)+npages);
84638335 1356
d977d56c 1357 if (is_exec_mapping(flags))
84638335 1358 mm->exec_vm += npages;
d977d56c 1359 else if (is_stack_mapping(flags))
84638335 1360 mm->stack_vm += npages;
d977d56c 1361 else if (is_data_mapping(flags))
84638335 1362 mm->data_vm += npages;
119f657c 1363}
fa5dc22f 1364
b3ec9f33 1365static vm_fault_t special_mapping_fault(struct vm_fault *vmf);
a62c34bd
AL
1366
1367/*
223febc6
ME
1368 * Close hook, called for unmap() and on the old vma for mremap().
1369 *
a62c34bd
AL
1370 * Having a close hook prevents vma merging regardless of flags.
1371 */
1372static void special_mapping_close(struct vm_area_struct *vma)
1373{
223febc6
ME
1374 const struct vm_special_mapping *sm = vma->vm_private_data;
1375
1376 if (sm->close)
1377 sm->close(sm, vma);
a62c34bd
AL
1378}
1379
1380static const char *special_mapping_name(struct vm_area_struct *vma)
1381{
1382 return ((struct vm_special_mapping *)vma->vm_private_data)->name;
1383}
1384
14d07113 1385static int special_mapping_mremap(struct vm_area_struct *new_vma)
b059a453
DS
1386{
1387 struct vm_special_mapping *sm = new_vma->vm_private_data;
1388
280e87e9
DS
1389 if (WARN_ON_ONCE(current->mm != new_vma->vm_mm))
1390 return -EFAULT;
1391
b059a453
DS
1392 if (sm->mremap)
1393 return sm->mremap(sm, new_vma);
280e87e9 1394
b059a453
DS
1395 return 0;
1396}
1397
871402e0
DS
1398static int special_mapping_split(struct vm_area_struct *vma, unsigned long addr)
1399{
1400 /*
1401 * Forbid splitting special mappings - kernel has expectations over
1402 * the number of pages in mapping. Together with VM_DONTEXPAND
1403 * the size of vma should stay the same over the special mapping's
1404 * lifetime.
1405 */
1406 return -EINVAL;
1407}
1408
a62c34bd
AL
1409static const struct vm_operations_struct special_mapping_vmops = {
1410 .close = special_mapping_close,
1411 .fault = special_mapping_fault,
b059a453 1412 .mremap = special_mapping_mremap,
a62c34bd 1413 .name = special_mapping_name,
af34ebeb
DS
1414 /* vDSO code relies that VVAR can't be accessed remotely */
1415 .access = NULL,
871402e0 1416 .may_split = special_mapping_split,
a62c34bd
AL
1417};
1418
b3ec9f33 1419static vm_fault_t special_mapping_fault(struct vm_fault *vmf)
fa5dc22f 1420{
11bac800 1421 struct vm_area_struct *vma = vmf->vma;
b1d0e4f5 1422 pgoff_t pgoff;
fa5dc22f 1423 struct page **pages;
497258df 1424 struct vm_special_mapping *sm = vma->vm_private_data;
fa5dc22f 1425
497258df
LT
1426 if (sm->fault)
1427 return sm->fault(sm, vmf->vma, vmf);
f872f540 1428
497258df 1429 pages = sm->pages;
a62c34bd 1430
8a9cc3b5 1431 for (pgoff = vmf->pgoff; pgoff && *pages; ++pages)
b1d0e4f5 1432 pgoff--;
fa5dc22f
RM
1433
1434 if (*pages) {
1435 struct page *page = *pages;
1436 get_page(page);
b1d0e4f5
NP
1437 vmf->page = page;
1438 return 0;
fa5dc22f
RM
1439 }
1440
b1d0e4f5 1441 return VM_FAULT_SIGBUS;
fa5dc22f
RM
1442}
1443
a62c34bd
AL
1444static struct vm_area_struct *__install_special_mapping(
1445 struct mm_struct *mm,
1446 unsigned long addr, unsigned long len,
27f28b97
CG
1447 unsigned long vm_flags, void *priv,
1448 const struct vm_operations_struct *ops)
fa5dc22f 1449{
462e635e 1450 int ret;
fa5dc22f
RM
1451 struct vm_area_struct *vma;
1452
490fc053 1453 vma = vm_area_alloc(mm);
fa5dc22f 1454 if (unlikely(vma == NULL))
3935ed6a 1455 return ERR_PTR(-ENOMEM);
fa5dc22f 1456
412c6ef9 1457 vma_set_range(vma, addr, addr + len, 0);
e430a95a
SB
1458 vm_flags_init(vma, (vm_flags | mm->def_flags |
1459 VM_DONTEXPAND | VM_SOFTDIRTY) & ~VM_LOCKED_MASK);
3ed75eb8 1460 vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
fa5dc22f 1461
a62c34bd
AL
1462 vma->vm_ops = ops;
1463 vma->vm_private_data = priv;
fa5dc22f 1464
462e635e
TO
1465 ret = insert_vm_struct(mm, vma);
1466 if (ret)
1467 goto out;
fa5dc22f 1468
84638335 1469 vm_stat_account(mm, vma->vm_flags, len >> PAGE_SHIFT);
fa5dc22f 1470
cdd6c482 1471 perf_event_mmap(vma);
089dd79d 1472
3935ed6a 1473 return vma;
462e635e
TO
1474
1475out:
3928d4f5 1476 vm_area_free(vma);
3935ed6a
SS
1477 return ERR_PTR(ret);
1478}
1479
2eefd878
DS
1480bool vma_is_special_mapping(const struct vm_area_struct *vma,
1481 const struct vm_special_mapping *sm)
1482{
1483 return vma->vm_private_data == sm &&
497258df 1484 vma->vm_ops == &special_mapping_vmops;
2eefd878
DS
1485}
1486
a62c34bd 1487/*
c1e8d7c6 1488 * Called with mm->mmap_lock held for writing.
a62c34bd
AL
1489 * Insert a new vma covering the given region, with the given flags.
1490 * Its pages are supplied by the given array of struct page *.
1491 * The array can be shorter than len >> PAGE_SHIFT if it's null-terminated.
1492 * The region past the last page supplied will always produce SIGBUS.
1493 * The array pointer and the pages it points to are assumed to stay alive
1494 * for as long as this mapping might exist.
1495 */
1496struct vm_area_struct *_install_special_mapping(
1497 struct mm_struct *mm,
1498 unsigned long addr, unsigned long len,
1499 unsigned long vm_flags, const struct vm_special_mapping *spec)
1500{
27f28b97
CG
1501 return __install_special_mapping(mm, addr, len, vm_flags, (void *)spec,
1502 &special_mapping_vmops);
a62c34bd
AL
1503}
1504
aacdde72
KY
1505#ifdef CONFIG_SYSCTL
1506#if defined(HAVE_ARCH_PICK_MMAP_LAYOUT) || \
1507 defined(CONFIG_ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT)
1508int sysctl_legacy_va_layout;
1509#endif
1510
1511static const struct ctl_table mmap_table[] = {
1512 {
1513 .procname = "max_map_count",
1514 .data = &sysctl_max_map_count,
1515 .maxlen = sizeof(sysctl_max_map_count),
1516 .mode = 0644,
1517 .proc_handler = proc_dointvec_minmax,
1518 .extra1 = SYSCTL_ZERO,
1519 },
1520#if defined(HAVE_ARCH_PICK_MMAP_LAYOUT) || \
1521 defined(CONFIG_ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT)
1522 {
1523 .procname = "legacy_va_layout",
1524 .data = &sysctl_legacy_va_layout,
1525 .maxlen = sizeof(sysctl_legacy_va_layout),
1526 .mode = 0644,
1527 .proc_handler = proc_dointvec_minmax,
1528 .extra1 = SYSCTL_ZERO,
1529 },
1530#endif
1531#ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
1532 {
1533 .procname = "mmap_rnd_bits",
1534 .data = &mmap_rnd_bits,
1535 .maxlen = sizeof(mmap_rnd_bits),
1536 .mode = 0600,
1537 .proc_handler = proc_dointvec_minmax,
1538 .extra1 = (void *)&mmap_rnd_bits_min,
1539 .extra2 = (void *)&mmap_rnd_bits_max,
1540 },
1541#endif
1542#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
1543 {
1544 .procname = "mmap_rnd_compat_bits",
1545 .data = &mmap_rnd_compat_bits,
1546 .maxlen = sizeof(mmap_rnd_compat_bits),
1547 .mode = 0600,
1548 .proc_handler = proc_dointvec_minmax,
1549 .extra1 = (void *)&mmap_rnd_compat_bits_min,
1550 .extra2 = (void *)&mmap_rnd_compat_bits_max,
1551 },
1552#endif
1553};
1554#endif /* CONFIG_SYSCTL */
1555
8feae131 1556/*
3e43e260 1557 * initialise the percpu counter for VM, initialise VMA state.
8feae131
DH
1558 */
1559void __init mmap_init(void)
1560{
00a62ce9
KM
1561 int ret;
1562
908c7f19 1563 ret = percpu_counter_init(&vm_committed_as, 0, GFP_KERNEL);
00a62ce9 1564 VM_BUG_ON(ret);
aacdde72
KY
1565#ifdef CONFIG_SYSCTL
1566 register_sysctl_init("vm", mmap_table);
1567#endif
3e43e260 1568 vma_state_init();
8feae131 1569}
c9b1d098
AS
1570
1571/*
1572 * Initialise sysctl_user_reserve_kbytes.
1573 *
1574 * This is intended to prevent a user from starting a single memory hogging
1575 * process, such that they cannot recover (kill the hog) in OVERCOMMIT_NEVER
1576 * mode.
1577 *
1578 * The default value is min(3% of free memory, 128MB)
1579 * 128MB is enough to recover with sshd/login, bash, and top/kill.
1580 */
1640879a 1581static int init_user_reserve(void)
c9b1d098
AS
1582{
1583 unsigned long free_kbytes;
1584
b1773e0e 1585 free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
c9b1d098 1586
9c793854 1587 sysctl_user_reserve_kbytes = min(free_kbytes / 32, SZ_128K);
c9b1d098
AS
1588 return 0;
1589}
a64fb3cd 1590subsys_initcall(init_user_reserve);
4eeab4f5
AS
1591
1592/*
1593 * Initialise sysctl_admin_reserve_kbytes.
1594 *
1595 * The purpose of sysctl_admin_reserve_kbytes is to allow the sys admin
1596 * to log in and kill a memory hogging process.
1597 *
1598 * Systems with more than 256MB will reserve 8MB, enough to recover
1599 * with sshd, bash, and top in OVERCOMMIT_GUESS. Smaller systems will
1600 * only reserve 3% of free pages by default.
1601 */
1640879a 1602static int init_admin_reserve(void)
4eeab4f5
AS
1603{
1604 unsigned long free_kbytes;
1605
b1773e0e 1606 free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
4eeab4f5 1607
9c793854 1608 sysctl_admin_reserve_kbytes = min(free_kbytes / 32, SZ_8K);
4eeab4f5
AS
1609 return 0;
1610}
a64fb3cd 1611subsys_initcall(init_admin_reserve);
1640879a
AS
1612
1613/*
1614 * Reinititalise user and admin reserves if memory is added or removed.
1615 *
1616 * The default user reserve max is 128MB, and the default max for the
1617 * admin reserve is 8MB. These are usually, but not always, enough to
1618 * enable recovery from a memory hogging process using login/sshd, a shell,
1619 * and tools like top. It may make sense to increase or even disable the
1620 * reserve depending on the existence of swap or variations in the recovery
1621 * tools. So, the admin may have changed them.
1622 *
1623 * If memory is added and the reserves have been eliminated or increased above
1624 * the default max, then we'll trust the admin.
1625 *
1626 * If memory is removed and there isn't enough free memory, then we
1627 * need to reset the reserves.
1628 *
1629 * Otherwise keep the reserve set by the admin.
1630 */
1631static int reserve_mem_notifier(struct notifier_block *nb,
1632 unsigned long action, void *data)
1633{
1634 unsigned long tmp, free_kbytes;
1635
1636 switch (action) {
1637 case MEM_ONLINE:
1638 /* Default max is 128MB. Leave alone if modified by operator. */
1639 tmp = sysctl_user_reserve_kbytes;
9c793854 1640 if (tmp > 0 && tmp < SZ_128K)
1640879a
AS
1641 init_user_reserve();
1642
1643 /* Default max is 8MB. Leave alone if modified by operator. */
1644 tmp = sysctl_admin_reserve_kbytes;
9c793854 1645 if (tmp > 0 && tmp < SZ_8K)
1640879a
AS
1646 init_admin_reserve();
1647
1648 break;
1649 case MEM_OFFLINE:
b1773e0e 1650 free_kbytes = K(global_zone_page_state(NR_FREE_PAGES));
1640879a
AS
1651
1652 if (sysctl_user_reserve_kbytes > free_kbytes) {
1653 init_user_reserve();
1654 pr_info("vm.user_reserve_kbytes reset to %lu\n",
1655 sysctl_user_reserve_kbytes);
1656 }
1657
1658 if (sysctl_admin_reserve_kbytes > free_kbytes) {
1659 init_admin_reserve();
1660 pr_info("vm.admin_reserve_kbytes reset to %lu\n",
1661 sysctl_admin_reserve_kbytes);
1662 }
1663 break;
1664 default:
1665 break;
1666 }
1667 return NOTIFY_OK;
1668}
1669
1640879a
AS
1670static int __meminit init_reserve_notifier(void)
1671{
1eeaa4fd 1672 if (hotplug_memory_notifier(reserve_mem_notifier, DEFAULT_CALLBACK_PRI))
b1de0d13 1673 pr_err("Failed registering memory add/remove notifier for admin reserve\n");
1640879a
AS
1674
1675 return 0;
1676}
a64fb3cd 1677subsys_initcall(init_reserve_notifier);
d61f0d59 1678
7a571499
LS
1679/*
1680 * Obtain a read lock on mm->mmap_lock, if the specified address is below the
1681 * start of the VMA, the intent is to perform a write, and it is a
1682 * downward-growing stack, then attempt to expand the stack to contain it.
1683 *
1684 * This function is intended only for obtaining an argument page from an ELF
1685 * image, and is almost certainly NOT what you want to use for any other
1686 * purpose.
1687 *
1688 * IMPORTANT - VMA fields are accessed without an mmap lock being held, so the
1689 * VMA referenced must not be linked in any user-visible tree, i.e. it must be a
1690 * new VMA being mapped.
1691 *
1692 * The function assumes that addr is either contained within the VMA or below
1693 * it, and makes no attempt to validate this value beyond that.
1694 *
1695 * Returns true if the read lock was obtained and a stack was perhaps expanded,
1696 * false if the stack expansion failed.
1697 *
1698 * On stack expansion the function temporarily acquires an mmap write lock
1699 * before downgrading it.
1700 */
1701bool mmap_read_lock_maybe_expand(struct mm_struct *mm,
1702 struct vm_area_struct *new_vma,
1703 unsigned long addr, bool write)
1704{
1705 if (!write || addr >= new_vma->vm_start) {
1706 mmap_read_lock(mm);
1707 return true;
1708 }
1709
1710 if (!(new_vma->vm_flags & VM_GROWSDOWN))
1711 return false;
1712
1713 mmap_write_lock(mm);
1714 if (expand_downwards(new_vma, addr)) {
1715 mmap_write_unlock(mm);
1716 return false;
1717 }
1718
1719 mmap_write_downgrade(mm);
1720 return true;
1721}
26a8f577
LS
1722
1723__latent_entropy int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
7a571499 1724{
26a8f577
LS
1725 struct vm_area_struct *mpnt, *tmp;
1726 int retval;
1727 unsigned long charge = 0;
1728 LIST_HEAD(uf);
1729 VMA_ITERATOR(vmi, mm, 0);
1730
1731 if (mmap_write_lock_killable(oldmm))
1732 return -EINTR;
1733 flush_cache_dup_mm(oldmm);
1734 uprobe_dup_mmap(oldmm, mm);
1735 /*
1736 * Not linked in yet - no deadlock potential:
1737 */
1738 mmap_write_lock_nested(mm, SINGLE_DEPTH_NESTING);
1739
1740 /* No ordering required: file already has been exposed. */
1741 dup_mm_exe_file(mm, oldmm);
1742
1743 mm->total_vm = oldmm->total_vm;
1744 mm->data_vm = oldmm->data_vm;
1745 mm->exec_vm = oldmm->exec_vm;
1746 mm->stack_vm = oldmm->stack_vm;
1747
1748 /* Use __mt_dup() to efficiently build an identical maple tree. */
1749 retval = __mt_dup(&oldmm->mm_mt, &mm->mm_mt, GFP_KERNEL);
1750 if (unlikely(retval))
1751 goto out;
1752
1753 mt_clear_in_rcu(vmi.mas.tree);
1754 for_each_vma(vmi, mpnt) {
1755 struct file *file;
1756
1757 vma_start_write(mpnt);
1758 if (mpnt->vm_flags & VM_DONTCOPY) {
1759 retval = vma_iter_clear_gfp(&vmi, mpnt->vm_start,
1760 mpnt->vm_end, GFP_KERNEL);
1761 if (retval)
1762 goto loop_out;
1763
1764 vm_stat_account(mm, mpnt->vm_flags, -vma_pages(mpnt));
1765 continue;
1766 }
1767 charge = 0;
1768 /*
1769 * Don't duplicate many vmas if we've been oom-killed (for
1770 * example)
1771 */
1772 if (fatal_signal_pending(current)) {
1773 retval = -EINTR;
1774 goto loop_out;
1775 }
1776 if (mpnt->vm_flags & VM_ACCOUNT) {
1777 unsigned long len = vma_pages(mpnt);
1778
1779 if (security_vm_enough_memory_mm(oldmm, len)) /* sic */
1780 goto fail_nomem;
1781 charge = len;
1782 }
1783
1784 tmp = vm_area_dup(mpnt);
1785 if (!tmp)
1786 goto fail_nomem;
26a8f577
LS
1787 retval = vma_dup_policy(mpnt, tmp);
1788 if (retval)
1789 goto fail_nomem_policy;
1790 tmp->vm_mm = mm;
1791 retval = dup_userfaultfd(tmp, &uf);
1792 if (retval)
1793 goto fail_nomem_anon_vma_fork;
1794 if (tmp->vm_flags & VM_WIPEONFORK) {
1795 /*
1796 * VM_WIPEONFORK gets a clean slate in the child.
1797 * Don't prepare anon_vma until fault since we don't
1798 * copy page for current vma.
1799 */
1800 tmp->anon_vma = NULL;
1801 } else if (anon_vma_fork(tmp, mpnt))
1802 goto fail_nomem_anon_vma_fork;
1803 vm_flags_clear(tmp, VM_LOCKED_MASK);
1804 /*
1805 * Copy/update hugetlb private vma information.
1806 */
1807 if (is_vm_hugetlb_page(tmp))
1808 hugetlb_dup_vma_private(tmp);
1809
1810 /*
1811 * Link the vma into the MT. After using __mt_dup(), memory
1812 * allocation is not necessary here, so it cannot fail.
1813 */
1814 vma_iter_bulk_store(&vmi, tmp);
1815
1816 mm->map_count++;
1817
1818 if (tmp->vm_ops && tmp->vm_ops->open)
1819 tmp->vm_ops->open(tmp);
1820
1821 file = tmp->vm_file;
1822 if (file) {
1823 struct address_space *mapping = file->f_mapping;
1824
1825 get_file(file);
1826 i_mmap_lock_write(mapping);
1827 if (vma_is_shared_maywrite(tmp))
1828 mapping_allow_writable(mapping);
1829 flush_dcache_mmap_lock(mapping);
1830 /* insert tmp into the share list, just after mpnt */
1831 vma_interval_tree_insert_after(tmp, mpnt,
1832 &mapping->i_mmap);
1833 flush_dcache_mmap_unlock(mapping);
1834 i_mmap_unlock_write(mapping);
1835 }
1836
1837 if (!(tmp->vm_flags & VM_WIPEONFORK))
1838 retval = copy_page_range(tmp, mpnt);
1839
1840 if (retval) {
1841 mpnt = vma_next(&vmi);
1842 goto loop_out;
1843 }
1844 }
1845 /* a new mm has just been created */
1846 retval = arch_dup_mmap(oldmm, mm);
1847loop_out:
1848 vma_iter_free(&vmi);
1849 if (!retval) {
1850 mt_set_in_rcu(vmi.mas.tree);
1851 ksm_fork(mm, oldmm);
1852 khugepaged_fork(mm, oldmm);
1853 } else {
1854
1855 /*
1856 * The entire maple tree has already been duplicated. If the
1857 * mmap duplication fails, mark the failure point with
1858 * XA_ZERO_ENTRY. In exit_mmap(), if this marker is encountered,
1859 * stop releasing VMAs that have not been duplicated after this
1860 * point.
1861 */
1862 if (mpnt) {
1863 mas_set_range(&vmi.mas, mpnt->vm_start, mpnt->vm_end - 1);
1864 mas_store(&vmi.mas, XA_ZERO_ENTRY);
1865 /* Avoid OOM iterating a broken tree */
1866 set_bit(MMF_OOM_SKIP, &mm->flags);
1867 }
1868 /*
1869 * The mm_struct is going to exit, but the locks will be dropped
1870 * first. Set the mm_struct as unstable is advisable as it is
1871 * not fully initialised.
1872 */
1873 set_bit(MMF_UNSTABLE, &mm->flags);
1874 }
1875out:
1876 mmap_write_unlock(mm);
1877 flush_tlb_mm(oldmm);
1878 mmap_write_unlock(oldmm);
1879 if (!retval)
1880 dup_userfaultfd_complete(&uf);
1881 else
1882 dup_userfaultfd_fail(&uf);
1883 return retval;
1884
1885fail_nomem_anon_vma_fork:
1886 mpol_put(vma_policy(tmp));
1887fail_nomem_policy:
1888 vm_area_free(tmp);
1889fail_nomem:
1890 retval = -ENOMEM;
1891 vm_unacct_memory(charge);
1892 goto loop_out;
7a571499 1893}