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/sched/mm.h>
9 #include <linux/security.h>
10 #include <linux/swap.h>
11 #include <linux/swapops.h>
12 #include <linux/mman.h>
13 #include <linux/hugetlb.h>
14 #include <linux/vmalloc.h>
15 #include <linux/userfaultfd_k.h>
17 #include <asm/sections.h>
18 #include <linux/uaccess.h>
22 static inline int is_kernel_rodata(unsigned long addr
)
24 return addr
>= (unsigned long)__start_rodata
&&
25 addr
< (unsigned long)__end_rodata
;
29 * kfree_const - conditionally free memory
30 * @x: pointer to the memory
32 * Function calls kfree only if @x is not in .rodata section.
34 void kfree_const(const void *x
)
36 if (!is_kernel_rodata((unsigned long)x
))
39 EXPORT_SYMBOL(kfree_const
);
42 * kstrdup - allocate space for and copy an existing string
43 * @s: the string to duplicate
44 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
46 char *kstrdup(const char *s
, gfp_t gfp
)
55 buf
= kmalloc_track_caller(len
, gfp
);
60 EXPORT_SYMBOL(kstrdup
);
63 * kstrdup_const - conditionally duplicate an existing const string
64 * @s: the string to duplicate
65 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
67 * Function returns source string if it is in .rodata section otherwise it
68 * fallbacks to kstrdup.
69 * Strings allocated by kstrdup_const should be freed by kfree_const.
71 const char *kstrdup_const(const char *s
, gfp_t gfp
)
73 if (is_kernel_rodata((unsigned long)s
))
76 return kstrdup(s
, gfp
);
78 EXPORT_SYMBOL(kstrdup_const
);
81 * kstrndup - allocate space for and copy an existing string
82 * @s: the string to duplicate
83 * @max: read at most @max chars from @s
84 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
86 char *kstrndup(const char *s
, size_t max
, gfp_t gfp
)
94 len
= strnlen(s
, max
);
95 buf
= kmalloc_track_caller(len
+1, gfp
);
102 EXPORT_SYMBOL(kstrndup
);
105 * kmemdup - duplicate region of memory
107 * @src: memory region to duplicate
108 * @len: memory region length
109 * @gfp: GFP mask to use
111 void *kmemdup(const void *src
, size_t len
, gfp_t gfp
)
115 p
= kmalloc_track_caller(len
, gfp
);
120 EXPORT_SYMBOL(kmemdup
);
123 * memdup_user - duplicate memory region from user space
125 * @src: source address in user space
126 * @len: number of bytes to copy
128 * Returns an ERR_PTR() on failure.
130 void *memdup_user(const void __user
*src
, size_t len
)
135 * Always use GFP_KERNEL, since copy_from_user() can sleep and
136 * cause pagefault, which makes it pointless to use GFP_NOFS
139 p
= kmalloc_track_caller(len
, GFP_KERNEL
);
141 return ERR_PTR(-ENOMEM
);
143 if (copy_from_user(p
, src
, len
)) {
145 return ERR_PTR(-EFAULT
);
150 EXPORT_SYMBOL(memdup_user
);
153 * strndup_user - duplicate an existing string from user space
154 * @s: The string to duplicate
155 * @n: Maximum number of bytes to copy, including the trailing NUL.
157 char *strndup_user(const char __user
*s
, long n
)
162 length
= strnlen_user(s
, n
);
165 return ERR_PTR(-EFAULT
);
168 return ERR_PTR(-EINVAL
);
170 p
= memdup_user(s
, length
);
175 p
[length
- 1] = '\0';
179 EXPORT_SYMBOL(strndup_user
);
182 * memdup_user_nul - duplicate memory region from user space and NUL-terminate
184 * @src: source address in user space
185 * @len: number of bytes to copy
187 * Returns an ERR_PTR() on failure.
189 void *memdup_user_nul(const void __user
*src
, size_t len
)
194 * Always use GFP_KERNEL, since copy_from_user() can sleep and
195 * cause pagefault, which makes it pointless to use GFP_NOFS
198 p
= kmalloc_track_caller(len
+ 1, GFP_KERNEL
);
200 return ERR_PTR(-ENOMEM
);
202 if (copy_from_user(p
, src
, len
)) {
204 return ERR_PTR(-EFAULT
);
210 EXPORT_SYMBOL(memdup_user_nul
);
212 void __vma_link_list(struct mm_struct
*mm
, struct vm_area_struct
*vma
,
213 struct vm_area_struct
*prev
, struct rb_node
*rb_parent
)
215 struct vm_area_struct
*next
;
219 next
= prev
->vm_next
;
224 next
= rb_entry(rb_parent
,
225 struct vm_area_struct
, vm_rb
);
234 /* Check if the vma is being used as a stack by this task */
235 int vma_is_stack_for_current(struct vm_area_struct
*vma
)
237 struct task_struct
* __maybe_unused t
= current
;
239 return (vma
->vm_start
<= KSTK_ESP(t
) && vma
->vm_end
>= KSTK_ESP(t
));
242 #if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
243 void arch_pick_mmap_layout(struct mm_struct
*mm
)
245 mm
->mmap_base
= TASK_UNMAPPED_BASE
;
246 mm
->get_unmapped_area
= arch_get_unmapped_area
;
251 * Like get_user_pages_fast() except its IRQ-safe in that it won't fall
252 * back to the regular GUP.
253 * If the architecture not support this function, simply return with no
256 int __weak
__get_user_pages_fast(unsigned long start
,
257 int nr_pages
, int write
, struct page
**pages
)
261 EXPORT_SYMBOL_GPL(__get_user_pages_fast
);
264 * get_user_pages_fast() - pin user pages in memory
265 * @start: starting user address
266 * @nr_pages: number of pages from start to pin
267 * @write: whether pages will be written to
268 * @pages: array that receives pointers to the pages pinned.
269 * Should be at least nr_pages long.
271 * Returns number of pages pinned. This may be fewer than the number
272 * requested. If nr_pages is 0 or negative, returns 0. If no pages
273 * were pinned, returns -errno.
275 * get_user_pages_fast provides equivalent functionality to get_user_pages,
276 * operating on current and current->mm, with force=0 and vma=NULL. However
277 * unlike get_user_pages, it must be called without mmap_sem held.
279 * get_user_pages_fast may take mmap_sem and page table locks, so no
280 * assumptions can be made about lack of locking. get_user_pages_fast is to be
281 * implemented in a way that is advantageous (vs get_user_pages()) when the
282 * user memory area is already faulted in and present in ptes. However if the
283 * pages have to be faulted in, it may turn out to be slightly slower so
284 * callers need to carefully consider what to use. On many architectures,
285 * get_user_pages_fast simply falls back to get_user_pages.
287 int __weak
get_user_pages_fast(unsigned long start
,
288 int nr_pages
, int write
, struct page
**pages
)
290 return get_user_pages_unlocked(start
, nr_pages
, pages
,
291 write
? FOLL_WRITE
: 0);
293 EXPORT_SYMBOL_GPL(get_user_pages_fast
);
295 unsigned long vm_mmap_pgoff(struct file
*file
, unsigned long addr
,
296 unsigned long len
, unsigned long prot
,
297 unsigned long flag
, unsigned long pgoff
)
300 struct mm_struct
*mm
= current
->mm
;
301 unsigned long populate
;
304 ret
= security_mmap_file(file
, prot
, flag
);
306 if (down_write_killable(&mm
->mmap_sem
))
308 ret
= do_mmap_pgoff(file
, addr
, len
, prot
, flag
, pgoff
,
310 up_write(&mm
->mmap_sem
);
311 userfaultfd_unmap_complete(mm
, &uf
);
313 mm_populate(ret
, populate
);
318 unsigned long vm_mmap(struct file
*file
, unsigned long addr
,
319 unsigned long len
, unsigned long prot
,
320 unsigned long flag
, unsigned long offset
)
322 if (unlikely(offset
+ PAGE_ALIGN(len
) < offset
))
324 if (unlikely(offset_in_page(offset
)))
327 return vm_mmap_pgoff(file
, addr
, len
, prot
, flag
, offset
>> PAGE_SHIFT
);
329 EXPORT_SYMBOL(vm_mmap
);
331 void kvfree(const void *addr
)
333 if (is_vmalloc_addr(addr
))
338 EXPORT_SYMBOL(kvfree
);
340 static inline void *__page_rmapping(struct page
*page
)
342 unsigned long mapping
;
344 mapping
= (unsigned long)page
->mapping
;
345 mapping
&= ~PAGE_MAPPING_FLAGS
;
347 return (void *)mapping
;
350 /* Neutral page->mapping pointer to address_space or anon_vma or other */
351 void *page_rmapping(struct page
*page
)
353 page
= compound_head(page
);
354 return __page_rmapping(page
);
358 * Return true if this page is mapped into pagetables.
359 * For compound page it returns true if any subpage of compound page is mapped.
361 bool page_mapped(struct page
*page
)
365 if (likely(!PageCompound(page
)))
366 return atomic_read(&page
->_mapcount
) >= 0;
367 page
= compound_head(page
);
368 if (atomic_read(compound_mapcount_ptr(page
)) >= 0)
372 for (i
= 0; i
< hpage_nr_pages(page
); i
++) {
373 if (atomic_read(&page
[i
]._mapcount
) >= 0)
378 EXPORT_SYMBOL(page_mapped
);
380 struct anon_vma
*page_anon_vma(struct page
*page
)
382 unsigned long mapping
;
384 page
= compound_head(page
);
385 mapping
= (unsigned long)page
->mapping
;
386 if ((mapping
& PAGE_MAPPING_FLAGS
) != PAGE_MAPPING_ANON
)
388 return __page_rmapping(page
);
391 struct address_space
*page_mapping(struct page
*page
)
393 struct address_space
*mapping
;
395 page
= compound_head(page
);
397 /* This happens if someone calls flush_dcache_page on slab page */
398 if (unlikely(PageSlab(page
)))
401 if (unlikely(PageSwapCache(page
))) {
404 entry
.val
= page_private(page
);
405 return swap_address_space(entry
);
408 mapping
= page
->mapping
;
409 if ((unsigned long)mapping
& PAGE_MAPPING_ANON
)
412 return (void *)((unsigned long)mapping
& ~PAGE_MAPPING_FLAGS
);
414 EXPORT_SYMBOL(page_mapping
);
416 /* Slow path of page_mapcount() for compound pages */
417 int __page_mapcount(struct page
*page
)
421 ret
= atomic_read(&page
->_mapcount
) + 1;
423 * For file THP page->_mapcount contains total number of mapping
424 * of the page: no need to look into compound_mapcount.
426 if (!PageAnon(page
) && !PageHuge(page
))
428 page
= compound_head(page
);
429 ret
+= atomic_read(compound_mapcount_ptr(page
)) + 1;
430 if (PageDoubleMap(page
))
434 EXPORT_SYMBOL_GPL(__page_mapcount
);
436 int sysctl_overcommit_memory __read_mostly
= OVERCOMMIT_GUESS
;
437 int sysctl_overcommit_ratio __read_mostly
= 50;
438 unsigned long sysctl_overcommit_kbytes __read_mostly
;
439 int sysctl_max_map_count __read_mostly
= DEFAULT_MAX_MAP_COUNT
;
440 unsigned long sysctl_user_reserve_kbytes __read_mostly
= 1UL << 17; /* 128MB */
441 unsigned long sysctl_admin_reserve_kbytes __read_mostly
= 1UL << 13; /* 8MB */
443 int overcommit_ratio_handler(struct ctl_table
*table
, int write
,
444 void __user
*buffer
, size_t *lenp
,
449 ret
= proc_dointvec(table
, write
, buffer
, lenp
, ppos
);
450 if (ret
== 0 && write
)
451 sysctl_overcommit_kbytes
= 0;
455 int overcommit_kbytes_handler(struct ctl_table
*table
, int write
,
456 void __user
*buffer
, size_t *lenp
,
461 ret
= proc_doulongvec_minmax(table
, write
, buffer
, lenp
, ppos
);
462 if (ret
== 0 && write
)
463 sysctl_overcommit_ratio
= 0;
468 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
470 unsigned long vm_commit_limit(void)
472 unsigned long allowed
;
474 if (sysctl_overcommit_kbytes
)
475 allowed
= sysctl_overcommit_kbytes
>> (PAGE_SHIFT
- 10);
477 allowed
= ((totalram_pages
- hugetlb_total_pages())
478 * sysctl_overcommit_ratio
/ 100);
479 allowed
+= total_swap_pages
;
485 * Make sure vm_committed_as in one cacheline and not cacheline shared with
486 * other variables. It can be updated by several CPUs frequently.
488 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp
;
491 * The global memory commitment made in the system can be a metric
492 * that can be used to drive ballooning decisions when Linux is hosted
493 * as a guest. On Hyper-V, the host implements a policy engine for dynamically
494 * balancing memory across competing virtual machines that are hosted.
495 * Several metrics drive this policy engine including the guest reported
498 unsigned long vm_memory_committed(void)
500 return percpu_counter_read_positive(&vm_committed_as
);
502 EXPORT_SYMBOL_GPL(vm_memory_committed
);
505 * Check that a process has enough memory to allocate a new virtual
506 * mapping. 0 means there is enough memory for the allocation to
507 * succeed and -ENOMEM implies there is not.
509 * We currently support three overcommit policies, which are set via the
510 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
512 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
513 * Additional code 2002 Jul 20 by Robert Love.
515 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
517 * Note this is a helper function intended to be used by LSMs which
518 * wish to use this logic.
520 int __vm_enough_memory(struct mm_struct
*mm
, long pages
, int cap_sys_admin
)
522 long free
, allowed
, reserve
;
524 VM_WARN_ONCE(percpu_counter_read(&vm_committed_as
) <
525 -(s64
)vm_committed_as_batch
* num_online_cpus(),
526 "memory commitment underflow");
528 vm_acct_memory(pages
);
531 * Sometimes we want to use more memory than we have
533 if (sysctl_overcommit_memory
== OVERCOMMIT_ALWAYS
)
536 if (sysctl_overcommit_memory
== OVERCOMMIT_GUESS
) {
537 free
= global_page_state(NR_FREE_PAGES
);
538 free
+= global_node_page_state(NR_FILE_PAGES
);
541 * shmem pages shouldn't be counted as free in this
542 * case, they can't be purged, only swapped out, and
543 * that won't affect the overall amount of available
544 * memory in the system.
546 free
-= global_node_page_state(NR_SHMEM
);
548 free
+= get_nr_swap_pages();
551 * Any slabs which are created with the
552 * SLAB_RECLAIM_ACCOUNT flag claim to have contents
553 * which are reclaimable, under pressure. The dentry
554 * cache and most inode caches should fall into this
556 free
+= global_page_state(NR_SLAB_RECLAIMABLE
);
559 * Leave reserved pages. The pages are not for anonymous pages.
561 if (free
<= totalreserve_pages
)
564 free
-= totalreserve_pages
;
567 * Reserve some for root
570 free
-= sysctl_admin_reserve_kbytes
>> (PAGE_SHIFT
- 10);
578 allowed
= vm_commit_limit();
580 * Reserve some for root
583 allowed
-= sysctl_admin_reserve_kbytes
>> (PAGE_SHIFT
- 10);
586 * Don't let a single process grow so big a user can't recover
589 reserve
= sysctl_user_reserve_kbytes
>> (PAGE_SHIFT
- 10);
590 allowed
-= min_t(long, mm
->total_vm
/ 32, reserve
);
593 if (percpu_counter_read_positive(&vm_committed_as
) < allowed
)
596 vm_unacct_memory(pages
);
602 * get_cmdline() - copy the cmdline value to a buffer.
603 * @task: the task whose cmdline value to copy.
604 * @buffer: the buffer to copy to.
605 * @buflen: the length of the buffer. Larger cmdline values are truncated
607 * Returns the size of the cmdline field copied. Note that the copy does
608 * not guarantee an ending NULL byte.
610 int get_cmdline(struct task_struct
*task
, char *buffer
, int buflen
)
614 struct mm_struct
*mm
= get_task_mm(task
);
615 unsigned long arg_start
, arg_end
, env_start
, env_end
;
619 goto out_mm
; /* Shh! No looking before we're done */
621 down_read(&mm
->mmap_sem
);
622 arg_start
= mm
->arg_start
;
623 arg_end
= mm
->arg_end
;
624 env_start
= mm
->env_start
;
625 env_end
= mm
->env_end
;
626 up_read(&mm
->mmap_sem
);
628 len
= arg_end
- arg_start
;
633 res
= access_process_vm(task
, arg_start
, buffer
, len
, FOLL_FORCE
);
636 * If the nul at the end of args has been overwritten, then
637 * assume application is using setproctitle(3).
639 if (res
> 0 && buffer
[res
-1] != '\0' && len
< buflen
) {
640 len
= strnlen(buffer
, res
);
644 len
= env_end
- env_start
;
645 if (len
> buflen
- res
)
647 res
+= access_process_vm(task
, env_start
,
650 res
= strnlen(buffer
, res
);