1 // SPDX-License-Identifier: GPL-2.0-only
3 #include <linux/slab.h>
4 #include <linux/string.h>
5 #include <linux/compiler.h>
6 #include <linux/export.h>
8 #include <linux/sched.h>
9 #include <linux/sched/mm.h>
10 #include <linux/sched/task_stack.h>
11 #include <linux/security.h>
12 #include <linux/swap.h>
13 #include <linux/swapops.h>
14 #include <linux/mman.h>
15 #include <linux/hugetlb.h>
16 #include <linux/vmalloc.h>
17 #include <linux/userfaultfd_k.h>
19 #include <linux/uaccess.h>
24 * kfree_const - conditionally free memory
25 * @x: pointer to the memory
27 * Function calls kfree only if @x is not in .rodata section.
29 void kfree_const(const void *x)
31 if (!is_kernel_rodata((unsigned long)x))
34 EXPORT_SYMBOL(kfree_const);
37 * kstrdup - allocate space for and copy an existing string
38 * @s: the string to duplicate
39 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
41 * Return: newly allocated copy of @s or %NULL in case of error
43 char *kstrdup(const char *s, gfp_t gfp)
52 buf = kmalloc_track_caller(len, gfp);
57 EXPORT_SYMBOL(kstrdup);
60 * kstrdup_const - conditionally duplicate an existing const string
61 * @s: the string to duplicate
62 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
64 * Note: Strings allocated by kstrdup_const should be freed by kfree_const.
66 * Return: source string if it is in .rodata section otherwise
67 * fallback to kstrdup.
69 const char *kstrdup_const(const char *s, gfp_t gfp)
71 if (is_kernel_rodata((unsigned long)s))
74 return kstrdup(s, gfp);
76 EXPORT_SYMBOL(kstrdup_const);
79 * kstrndup - allocate space for and copy an existing string
80 * @s: the string to duplicate
81 * @max: read at most @max chars from @s
82 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
84 * Note: Use kmemdup_nul() instead if the size is known exactly.
86 * Return: newly allocated copy of @s or %NULL in case of error
88 char *kstrndup(const char *s, size_t max, gfp_t gfp)
96 len = strnlen(s, max);
97 buf = kmalloc_track_caller(len+1, gfp);
104 EXPORT_SYMBOL(kstrndup);
107 * kmemdup - duplicate region of memory
109 * @src: memory region to duplicate
110 * @len: memory region length
111 * @gfp: GFP mask to use
113 * Return: newly allocated copy of @src or %NULL in case of error
115 void *kmemdup(const void *src, size_t len, gfp_t gfp)
119 p = kmalloc_track_caller(len, gfp);
124 EXPORT_SYMBOL(kmemdup);
127 * kmemdup_nul - Create a NUL-terminated string from unterminated data
128 * @s: The data to stringify
129 * @len: The size of the data
130 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
132 * Return: newly allocated copy of @s with NUL-termination or %NULL in
135 char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
142 buf = kmalloc_track_caller(len + 1, gfp);
149 EXPORT_SYMBOL(kmemdup_nul);
152 * memdup_user - duplicate memory region from user space
154 * @src: source address in user space
155 * @len: number of bytes to copy
157 * Return: an ERR_PTR() on failure. Result is physically
158 * contiguous, to be freed by kfree().
160 void *memdup_user(const void __user *src, size_t len)
164 p = kmalloc_track_caller(len, GFP_USER | __GFP_NOWARN);
166 return ERR_PTR(-ENOMEM);
168 if (copy_from_user(p, src, len)) {
170 return ERR_PTR(-EFAULT);
175 EXPORT_SYMBOL(memdup_user);
178 * vmemdup_user - duplicate memory region from user space
180 * @src: source address in user space
181 * @len: number of bytes to copy
183 * Return: an ERR_PTR() on failure. Result may be not
184 * physically contiguous. Use kvfree() to free.
186 void *vmemdup_user(const void __user *src, size_t len)
190 p = kvmalloc(len, GFP_USER);
192 return ERR_PTR(-ENOMEM);
194 if (copy_from_user(p, src, len)) {
196 return ERR_PTR(-EFAULT);
201 EXPORT_SYMBOL(vmemdup_user);
204 * strndup_user - duplicate an existing string from user space
205 * @s: The string to duplicate
206 * @n: Maximum number of bytes to copy, including the trailing NUL.
208 * Return: newly allocated copy of @s or an ERR_PTR() in case of error
210 char *strndup_user(const char __user *s, long n)
215 length = strnlen_user(s, n);
218 return ERR_PTR(-EFAULT);
221 return ERR_PTR(-EINVAL);
223 p = memdup_user(s, length);
228 p[length - 1] = '\0';
232 EXPORT_SYMBOL(strndup_user);
235 * memdup_user_nul - duplicate memory region from user space and NUL-terminate
237 * @src: source address in user space
238 * @len: number of bytes to copy
240 * Return: an ERR_PTR() on failure.
242 void *memdup_user_nul(const void __user *src, size_t len)
247 * Always use GFP_KERNEL, since copy_from_user() can sleep and
248 * cause pagefault, which makes it pointless to use GFP_NOFS
251 p = kmalloc_track_caller(len + 1, GFP_KERNEL);
253 return ERR_PTR(-ENOMEM);
255 if (copy_from_user(p, src, len)) {
257 return ERR_PTR(-EFAULT);
263 EXPORT_SYMBOL(memdup_user_nul);
265 void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
266 struct vm_area_struct *prev, struct rb_node *rb_parent)
268 struct vm_area_struct *next;
272 next = prev->vm_next;
277 next = rb_entry(rb_parent,
278 struct vm_area_struct, vm_rb);
287 /* Check if the vma is being used as a stack by this task */
288 int vma_is_stack_for_current(struct vm_area_struct *vma)
290 struct task_struct * __maybe_unused t = current;
292 return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
295 #if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
296 void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
298 mm->mmap_base = TASK_UNMAPPED_BASE;
299 mm->get_unmapped_area = arch_get_unmapped_area;
303 unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
304 unsigned long len, unsigned long prot,
305 unsigned long flag, unsigned long pgoff)
308 struct mm_struct *mm = current->mm;
309 unsigned long populate;
312 ret = security_mmap_file(file, prot, flag);
314 if (down_write_killable(&mm->mmap_sem))
316 ret = do_mmap_pgoff(file, addr, len, prot, flag, pgoff,
318 up_write(&mm->mmap_sem);
319 userfaultfd_unmap_complete(mm, &uf);
321 mm_populate(ret, populate);
326 unsigned long vm_mmap(struct file *file, unsigned long addr,
327 unsigned long len, unsigned long prot,
328 unsigned long flag, unsigned long offset)
330 if (unlikely(offset + PAGE_ALIGN(len) < offset))
332 if (unlikely(offset_in_page(offset)))
335 return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
337 EXPORT_SYMBOL(vm_mmap);
340 * kvmalloc_node - attempt to allocate physically contiguous memory, but upon
341 * failure, fall back to non-contiguous (vmalloc) allocation.
342 * @size: size of the request.
343 * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
344 * @node: numa node to allocate from
346 * Uses kmalloc to get the memory but if the allocation fails then falls back
347 * to the vmalloc allocator. Use kvfree for freeing the memory.
349 * Reclaim modifiers - __GFP_NORETRY and __GFP_NOFAIL are not supported.
350 * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
351 * preferable to the vmalloc fallback, due to visible performance drawbacks.
353 * Please note that any use of gfp flags outside of GFP_KERNEL is careful to not
354 * fall back to vmalloc.
356 * Return: pointer to the allocated memory of %NULL in case of failure
358 void *kvmalloc_node(size_t size, gfp_t flags, int node)
360 gfp_t kmalloc_flags = flags;
364 * vmalloc uses GFP_KERNEL for some internal allocations (e.g page tables)
365 * so the given set of flags has to be compatible.
367 if ((flags & GFP_KERNEL) != GFP_KERNEL)
368 return kmalloc_node(size, flags, node);
371 * We want to attempt a large physically contiguous block first because
372 * it is less likely to fragment multiple larger blocks and therefore
373 * contribute to a long term fragmentation less than vmalloc fallback.
374 * However make sure that larger requests are not too disruptive - no
375 * OOM killer and no allocation failure warnings as we have a fallback.
377 if (size > PAGE_SIZE) {
378 kmalloc_flags |= __GFP_NOWARN;
380 if (!(kmalloc_flags & __GFP_RETRY_MAYFAIL))
381 kmalloc_flags |= __GFP_NORETRY;
384 ret = kmalloc_node(size, kmalloc_flags, node);
387 * It doesn't really make sense to fallback to vmalloc for sub page
390 if (ret || size <= PAGE_SIZE)
393 return __vmalloc_node_flags_caller(size, node, flags,
394 __builtin_return_address(0));
396 EXPORT_SYMBOL(kvmalloc_node);
399 * kvfree() - Free memory.
400 * @addr: Pointer to allocated memory.
402 * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
403 * It is slightly more efficient to use kfree() or vfree() if you are certain
404 * that you know which one to use.
406 * Context: Either preemptible task context or not-NMI interrupt.
408 void kvfree(const void *addr)
410 if (is_vmalloc_addr(addr))
415 EXPORT_SYMBOL(kvfree);
417 static inline void *__page_rmapping(struct page *page)
419 unsigned long mapping;
421 mapping = (unsigned long)page->mapping;
422 mapping &= ~PAGE_MAPPING_FLAGS;
424 return (void *)mapping;
427 /* Neutral page->mapping pointer to address_space or anon_vma or other */
428 void *page_rmapping(struct page *page)
430 page = compound_head(page);
431 return __page_rmapping(page);
435 * Return true if this page is mapped into pagetables.
436 * For compound page it returns true if any subpage of compound page is mapped.
438 bool page_mapped(struct page *page)
442 if (likely(!PageCompound(page)))
443 return atomic_read(&page->_mapcount) >= 0;
444 page = compound_head(page);
445 if (atomic_read(compound_mapcount_ptr(page)) >= 0)
449 for (i = 0; i < (1 << compound_order(page)); i++) {
450 if (atomic_read(&page[i]._mapcount) >= 0)
455 EXPORT_SYMBOL(page_mapped);
457 struct anon_vma *page_anon_vma(struct page *page)
459 unsigned long mapping;
461 page = compound_head(page);
462 mapping = (unsigned long)page->mapping;
463 if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
465 return __page_rmapping(page);
468 struct address_space *page_mapping(struct page *page)
470 struct address_space *mapping;
472 page = compound_head(page);
474 /* This happens if someone calls flush_dcache_page on slab page */
475 if (unlikely(PageSlab(page)))
478 if (unlikely(PageSwapCache(page))) {
481 entry.val = page_private(page);
482 return swap_address_space(entry);
485 mapping = page->mapping;
486 if ((unsigned long)mapping & PAGE_MAPPING_ANON)
489 return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
491 EXPORT_SYMBOL(page_mapping);
494 * For file cache pages, return the address_space, otherwise return NULL
496 struct address_space *page_mapping_file(struct page *page)
498 if (unlikely(PageSwapCache(page)))
500 return page_mapping(page);
503 /* Slow path of page_mapcount() for compound pages */
504 int __page_mapcount(struct page *page)
508 ret = atomic_read(&page->_mapcount) + 1;
510 * For file THP page->_mapcount contains total number of mapping
511 * of the page: no need to look into compound_mapcount.
513 if (!PageAnon(page) && !PageHuge(page))
515 page = compound_head(page);
516 ret += atomic_read(compound_mapcount_ptr(page)) + 1;
517 if (PageDoubleMap(page))
521 EXPORT_SYMBOL_GPL(__page_mapcount);
523 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
524 int sysctl_overcommit_ratio __read_mostly = 50;
525 unsigned long sysctl_overcommit_kbytes __read_mostly;
526 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
527 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
528 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
530 int overcommit_ratio_handler(struct ctl_table *table, int write,
531 void __user *buffer, size_t *lenp,
536 ret = proc_dointvec(table, write, buffer, lenp, ppos);
537 if (ret == 0 && write)
538 sysctl_overcommit_kbytes = 0;
542 int overcommit_kbytes_handler(struct ctl_table *table, int write,
543 void __user *buffer, size_t *lenp,
548 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
549 if (ret == 0 && write)
550 sysctl_overcommit_ratio = 0;
555 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
557 unsigned long vm_commit_limit(void)
559 unsigned long allowed;
561 if (sysctl_overcommit_kbytes)
562 allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
564 allowed = ((totalram_pages() - hugetlb_total_pages())
565 * sysctl_overcommit_ratio / 100);
566 allowed += total_swap_pages;
572 * Make sure vm_committed_as in one cacheline and not cacheline shared with
573 * other variables. It can be updated by several CPUs frequently.
575 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
578 * The global memory commitment made in the system can be a metric
579 * that can be used to drive ballooning decisions when Linux is hosted
580 * as a guest. On Hyper-V, the host implements a policy engine for dynamically
581 * balancing memory across competing virtual machines that are hosted.
582 * Several metrics drive this policy engine including the guest reported
585 unsigned long vm_memory_committed(void)
587 return percpu_counter_read_positive(&vm_committed_as);
589 EXPORT_SYMBOL_GPL(vm_memory_committed);
592 * Check that a process has enough memory to allocate a new virtual
593 * mapping. 0 means there is enough memory for the allocation to
594 * succeed and -ENOMEM implies there is not.
596 * We currently support three overcommit policies, which are set via the
597 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting.rst
599 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
600 * Additional code 2002 Jul 20 by Robert Love.
602 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
604 * Note this is a helper function intended to be used by LSMs which
605 * wish to use this logic.
607 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
611 VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
612 -(s64)vm_committed_as_batch * num_online_cpus(),
613 "memory commitment underflow");
615 vm_acct_memory(pages);
618 * Sometimes we want to use more memory than we have
620 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
623 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
624 if (pages > totalram_pages() + total_swap_pages)
629 allowed = vm_commit_limit();
631 * Reserve some for root
634 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
637 * Don't let a single process grow so big a user can't recover
640 long reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
642 allowed -= min_t(long, mm->total_vm / 32, reserve);
645 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
648 vm_unacct_memory(pages);
654 * get_cmdline() - copy the cmdline value to a buffer.
655 * @task: the task whose cmdline value to copy.
656 * @buffer: the buffer to copy to.
657 * @buflen: the length of the buffer. Larger cmdline values are truncated
660 * Return: the size of the cmdline field copied. Note that the copy does
661 * not guarantee an ending NULL byte.
663 int get_cmdline(struct task_struct *task, char *buffer, int buflen)
667 struct mm_struct *mm = get_task_mm(task);
668 unsigned long arg_start, arg_end, env_start, env_end;
672 goto out_mm; /* Shh! No looking before we're done */
674 spin_lock(&mm->arg_lock);
675 arg_start = mm->arg_start;
676 arg_end = mm->arg_end;
677 env_start = mm->env_start;
678 env_end = mm->env_end;
679 spin_unlock(&mm->arg_lock);
681 len = arg_end - arg_start;
686 res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
689 * If the nul at the end of args has been overwritten, then
690 * assume application is using setproctitle(3).
692 if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
693 len = strnlen(buffer, res);
697 len = env_end - env_start;
698 if (len > buflen - res)
700 res += access_process_vm(task, env_start,
703 res = strnlen(buffer, res);