2 #include <linux/slab.h>
3 #include <linux/string.h>
4 #include <linux/compiler.h>
5 #include <linux/export.h>
7 #include <linux/sched.h>
8 #include <linux/security.h>
9 #include <linux/swap.h>
10 #include <linux/swapops.h>
11 #include <linux/mman.h>
12 #include <linux/hugetlb.h>
13 #include <linux/vmalloc.h>
14 #include <linux/random.h>
16 #include <asm/sections.h>
17 #include <asm/uaccess.h>
21 static inline int is_kernel_rodata(unsigned long addr)
23 return addr >= (unsigned long)__start_rodata &&
24 addr < (unsigned long)__end_rodata;
28 * kfree_const - conditionally free memory
29 * @x: pointer to the memory
31 * Function calls kfree only if @x is not in .rodata section.
33 void kfree_const(const void *x)
35 if (!is_kernel_rodata((unsigned long)x))
38 EXPORT_SYMBOL(kfree_const);
41 * kstrdup - allocate space for and copy an existing string
42 * @s: the string to duplicate
43 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
45 char *kstrdup(const char *s, gfp_t gfp)
54 buf = kmalloc_track_caller(len, gfp);
59 EXPORT_SYMBOL(kstrdup);
62 * kstrdup_const - conditionally duplicate an existing const string
63 * @s: the string to duplicate
64 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
66 * Function returns source string if it is in .rodata section otherwise it
67 * fallbacks to kstrdup.
68 * Strings allocated by kstrdup_const should be freed by kfree_const.
70 const char *kstrdup_const(const char *s, gfp_t gfp)
72 if (is_kernel_rodata((unsigned long)s))
75 return kstrdup(s, gfp);
77 EXPORT_SYMBOL(kstrdup_const);
80 * kstrndup - allocate space for and copy an existing string
81 * @s: the string to duplicate
82 * @max: read at most @max chars from @s
83 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
85 * Note: Use kmemdup_nul() instead if the size is known exactly.
87 char *kstrndup(const char *s, size_t max, gfp_t gfp)
95 len = strnlen(s, max);
96 buf = kmalloc_track_caller(len+1, gfp);
103 EXPORT_SYMBOL(kstrndup);
106 * kmemdup - duplicate region of memory
108 * @src: memory region to duplicate
109 * @len: memory region length
110 * @gfp: GFP mask to use
112 void *kmemdup(const void *src, size_t len, gfp_t gfp)
116 p = kmalloc_track_caller(len, gfp);
121 EXPORT_SYMBOL(kmemdup);
124 * kmemdup_nul - Create a NUL-terminated string from unterminated data
125 * @s: The data to stringify
126 * @len: The size of the data
127 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
129 char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
136 buf = kmalloc_track_caller(len + 1, gfp);
143 EXPORT_SYMBOL(kmemdup_nul);
146 * memdup_user - duplicate memory region from user space
148 * @src: source address in user space
149 * @len: number of bytes to copy
151 * Returns an ERR_PTR() on failure.
153 void *memdup_user(const void __user *src, size_t len)
158 * Always use GFP_KERNEL, since copy_from_user() can sleep and
159 * cause pagefault, which makes it pointless to use GFP_NOFS
162 p = kmalloc_track_caller(len, GFP_KERNEL);
164 return ERR_PTR(-ENOMEM);
166 if (copy_from_user(p, src, len)) {
168 return ERR_PTR(-EFAULT);
173 EXPORT_SYMBOL(memdup_user);
176 * strndup_user - duplicate an existing string from user space
177 * @s: The string to duplicate
178 * @n: Maximum number of bytes to copy, including the trailing NUL.
180 char *strndup_user(const char __user *s, long n)
185 length = strnlen_user(s, n);
188 return ERR_PTR(-EFAULT);
191 return ERR_PTR(-EINVAL);
193 p = memdup_user(s, length);
198 p[length - 1] = '\0';
202 EXPORT_SYMBOL(strndup_user);
205 * memdup_user_nul - duplicate memory region from user space and NUL-terminate
207 * @src: source address in user space
208 * @len: number of bytes to copy
210 * Returns an ERR_PTR() on failure.
212 void *memdup_user_nul(const void __user *src, size_t len)
217 * Always use GFP_KERNEL, since copy_from_user() can sleep and
218 * cause pagefault, which makes it pointless to use GFP_NOFS
221 p = kmalloc_track_caller(len + 1, GFP_KERNEL);
223 return ERR_PTR(-ENOMEM);
225 if (copy_from_user(p, src, len)) {
227 return ERR_PTR(-EFAULT);
233 EXPORT_SYMBOL(memdup_user_nul);
235 void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
236 struct vm_area_struct *prev, struct rb_node *rb_parent)
238 struct vm_area_struct *next;
242 next = prev->vm_next;
247 next = rb_entry(rb_parent,
248 struct vm_area_struct, vm_rb);
257 /* Check if the vma is being used as a stack by this task */
258 int vma_is_stack_for_current(struct vm_area_struct *vma)
260 struct task_struct * __maybe_unused t = current;
262 return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
266 * randomize_page - Generate a random, page aligned address
267 * @start: The smallest acceptable address the caller will take.
268 * @range: The size of the area, starting at @start, within which the
269 * random address must fall.
271 * If @start + @range would overflow, @range is capped.
273 * NOTE: Historical use of randomize_range, which this replaces, presumed that
274 * @start was already page aligned. We now align it regardless.
276 * Return: A page aligned address within [start, start + range). On error,
277 * @start is returned.
279 unsigned long randomize_page(unsigned long start, unsigned long range)
281 if (!PAGE_ALIGNED(start)) {
282 range -= PAGE_ALIGN(start) - start;
283 start = PAGE_ALIGN(start);
286 if (start > ULONG_MAX - range)
287 range = ULONG_MAX - start;
289 range >>= PAGE_SHIFT;
294 return start + (get_random_long() % range << PAGE_SHIFT);
297 #if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
298 void arch_pick_mmap_layout(struct mm_struct *mm)
300 mm->mmap_base = TASK_UNMAPPED_BASE;
301 mm->get_unmapped_area = arch_get_unmapped_area;
306 * Like get_user_pages_fast() except its IRQ-safe in that it won't fall
307 * back to the regular GUP.
308 * If the architecture not support this function, simply return with no
311 int __weak __get_user_pages_fast(unsigned long start,
312 int nr_pages, int write, struct page **pages)
316 EXPORT_SYMBOL_GPL(__get_user_pages_fast);
319 * get_user_pages_fast() - pin user pages in memory
320 * @start: starting user address
321 * @nr_pages: number of pages from start to pin
322 * @write: whether pages will be written to
323 * @pages: array that receives pointers to the pages pinned.
324 * Should be at least nr_pages long.
326 * Returns number of pages pinned. This may be fewer than the number
327 * requested. If nr_pages is 0 or negative, returns 0. If no pages
328 * were pinned, returns -errno.
330 * get_user_pages_fast provides equivalent functionality to get_user_pages,
331 * operating on current and current->mm, with force=0 and vma=NULL. However
332 * unlike get_user_pages, it must be called without mmap_sem held.
334 * get_user_pages_fast may take mmap_sem and page table locks, so no
335 * assumptions can be made about lack of locking. get_user_pages_fast is to be
336 * implemented in a way that is advantageous (vs get_user_pages()) when the
337 * user memory area is already faulted in and present in ptes. However if the
338 * pages have to be faulted in, it may turn out to be slightly slower so
339 * callers need to carefully consider what to use. On many architectures,
340 * get_user_pages_fast simply falls back to get_user_pages.
342 int __weak get_user_pages_fast(unsigned long start,
343 int nr_pages, int write, struct page **pages)
345 return get_user_pages_unlocked(start, nr_pages, pages,
346 write ? FOLL_WRITE : 0);
348 EXPORT_SYMBOL_GPL(get_user_pages_fast);
350 unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
351 unsigned long len, unsigned long prot,
352 unsigned long flag, unsigned long pgoff)
355 struct mm_struct *mm = current->mm;
356 unsigned long populate;
358 ret = security_mmap_file(file, prot, flag);
360 if (down_write_killable(&mm->mmap_sem))
362 ret = do_mmap_pgoff(file, addr, len, prot, flag, pgoff,
364 up_write(&mm->mmap_sem);
366 mm_populate(ret, populate);
371 unsigned long vm_mmap(struct file *file, unsigned long addr,
372 unsigned long len, unsigned long prot,
373 unsigned long flag, unsigned long offset)
375 if (unlikely(offset + PAGE_ALIGN(len) < offset))
377 if (unlikely(offset_in_page(offset)))
380 return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
382 EXPORT_SYMBOL(vm_mmap);
384 void kvfree(const void *addr)
386 if (is_vmalloc_addr(addr))
391 EXPORT_SYMBOL(kvfree);
393 static inline void *__page_rmapping(struct page *page)
395 unsigned long mapping;
397 mapping = (unsigned long)page->mapping;
398 mapping &= ~PAGE_MAPPING_FLAGS;
400 return (void *)mapping;
403 /* Neutral page->mapping pointer to address_space or anon_vma or other */
404 void *page_rmapping(struct page *page)
406 page = compound_head(page);
407 return __page_rmapping(page);
411 * Return true if this page is mapped into pagetables.
412 * For compound page it returns true if any subpage of compound page is mapped.
414 bool page_mapped(struct page *page)
418 if (likely(!PageCompound(page)))
419 return atomic_read(&page->_mapcount) >= 0;
420 page = compound_head(page);
421 if (atomic_read(compound_mapcount_ptr(page)) >= 0)
425 for (i = 0; i < (1 << compound_order(page)); i++) {
426 if (atomic_read(&page[i]._mapcount) >= 0)
431 EXPORT_SYMBOL(page_mapped);
433 struct anon_vma *page_anon_vma(struct page *page)
435 unsigned long mapping;
437 page = compound_head(page);
438 mapping = (unsigned long)page->mapping;
439 if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
441 return __page_rmapping(page);
444 struct address_space *page_mapping(struct page *page)
446 struct address_space *mapping;
448 page = compound_head(page);
450 /* This happens if someone calls flush_dcache_page on slab page */
451 if (unlikely(PageSlab(page)))
454 if (unlikely(PageSwapCache(page))) {
457 entry.val = page_private(page);
458 return swap_address_space(entry);
461 mapping = page->mapping;
462 if ((unsigned long)mapping & PAGE_MAPPING_ANON)
465 return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
467 EXPORT_SYMBOL(page_mapping);
469 /* Slow path of page_mapcount() for compound pages */
470 int __page_mapcount(struct page *page)
474 ret = atomic_read(&page->_mapcount) + 1;
476 * For file THP page->_mapcount contains total number of mapping
477 * of the page: no need to look into compound_mapcount.
479 if (!PageAnon(page) && !PageHuge(page))
481 page = compound_head(page);
482 ret += atomic_read(compound_mapcount_ptr(page)) + 1;
483 if (PageDoubleMap(page))
487 EXPORT_SYMBOL_GPL(__page_mapcount);
489 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
490 int sysctl_overcommit_ratio __read_mostly = 50;
491 unsigned long sysctl_overcommit_kbytes __read_mostly;
492 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
493 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
494 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
496 int overcommit_ratio_handler(struct ctl_table *table, int write,
497 void __user *buffer, size_t *lenp,
502 ret = proc_dointvec(table, write, buffer, lenp, ppos);
503 if (ret == 0 && write)
504 sysctl_overcommit_kbytes = 0;
508 int overcommit_kbytes_handler(struct ctl_table *table, int write,
509 void __user *buffer, size_t *lenp,
514 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
515 if (ret == 0 && write)
516 sysctl_overcommit_ratio = 0;
521 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
523 unsigned long vm_commit_limit(void)
525 unsigned long allowed;
527 if (sysctl_overcommit_kbytes)
528 allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
530 allowed = ((totalram_pages - hugetlb_total_pages())
531 * sysctl_overcommit_ratio / 100);
532 allowed += total_swap_pages;
538 * Make sure vm_committed_as in one cacheline and not cacheline shared with
539 * other variables. It can be updated by several CPUs frequently.
541 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
544 * The global memory commitment made in the system can be a metric
545 * that can be used to drive ballooning decisions when Linux is hosted
546 * as a guest. On Hyper-V, the host implements a policy engine for dynamically
547 * balancing memory across competing virtual machines that are hosted.
548 * Several metrics drive this policy engine including the guest reported
551 unsigned long vm_memory_committed(void)
553 return percpu_counter_read_positive(&vm_committed_as);
555 EXPORT_SYMBOL_GPL(vm_memory_committed);
558 * Check that a process has enough memory to allocate a new virtual
559 * mapping. 0 means there is enough memory for the allocation to
560 * succeed and -ENOMEM implies there is not.
562 * We currently support three overcommit policies, which are set via the
563 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
565 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
566 * Additional code 2002 Jul 20 by Robert Love.
568 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
570 * Note this is a helper function intended to be used by LSMs which
571 * wish to use this logic.
573 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
575 long free, allowed, reserve;
577 VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
578 -(s64)vm_committed_as_batch * num_online_cpus(),
579 "memory commitment underflow");
581 vm_acct_memory(pages);
584 * Sometimes we want to use more memory than we have
586 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
589 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
590 free = global_page_state(NR_FREE_PAGES);
591 free += global_node_page_state(NR_FILE_PAGES);
594 * shmem pages shouldn't be counted as free in this
595 * case, they can't be purged, only swapped out, and
596 * that won't affect the overall amount of available
597 * memory in the system.
599 free -= global_node_page_state(NR_SHMEM);
601 free += get_nr_swap_pages();
604 * Any slabs which are created with the
605 * SLAB_RECLAIM_ACCOUNT flag claim to have contents
606 * which are reclaimable, under pressure. The dentry
607 * cache and most inode caches should fall into this
609 free += global_page_state(NR_SLAB_RECLAIMABLE);
612 * Leave reserved pages. The pages are not for anonymous pages.
614 if (free <= totalreserve_pages)
617 free -= totalreserve_pages;
620 * Reserve some for root
623 free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
631 allowed = vm_commit_limit();
633 * Reserve some for root
636 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
639 * Don't let a single process grow so big a user can't recover
642 reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
643 allowed -= min_t(long, mm->total_vm / 32, reserve);
646 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
649 vm_unacct_memory(pages);
655 * get_cmdline() - copy the cmdline value to a buffer.
656 * @task: the task whose cmdline value to copy.
657 * @buffer: the buffer to copy to.
658 * @buflen: the length of the buffer. Larger cmdline values are truncated
660 * Returns 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 down_read(&mm->mmap_sem);
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 up_read(&mm->mmap_sem);
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);