blob: 68575a315dc5adbbd5f1b3c7b80a359e9d8036ef [file] [log] [blame]
Thomas Gleixner457c8992019-05-19 13:08:55 +01001// SPDX-License-Identifier: GPL-2.0-only
Andrew Morton16d69262008-07-25 19:44:36 -07002#include <linux/mm.h>
Matt Mackall30992c92006-01-08 01:01:43 -08003#include <linux/slab.h>
4#include <linux/string.h>
Gideon Israel Dsouza3b321232014-04-07 15:37:26 -07005#include <linux/compiler.h>
Paul Gortmakerb95f1b312011-10-16 02:01:52 -04006#include <linux/export.h>
Davi Arnaut96840aa2006-03-24 03:18:42 -08007#include <linux/err.h>
Adrian Bunk3b8f14b2008-07-26 15:22:28 -07008#include <linux/sched.h>
Ingo Molnar6e84f312017-02-08 18:51:29 +01009#include <linux/sched/mm.h>
Ingo Molnar68db0cf2017-02-08 18:51:37 +010010#include <linux/sched/task_stack.h>
Al Viroeb36c582012-05-30 20:17:35 -040011#include <linux/security.h>
Shaohua Li98003392013-02-22 16:34:35 -080012#include <linux/swap.h>
Shaohua Li33806f02013-02-22 16:34:37 -080013#include <linux/swapops.h>
Jerome Marchand00619bc2013-11-12 15:08:31 -080014#include <linux/mman.h>
15#include <linux/hugetlb.h>
Al Viro39f1f782014-05-06 14:02:53 -040016#include <linux/vmalloc.h>
Mike Rapoport897ab3e2017-02-24 14:58:22 -080017#include <linux/userfaultfd_k.h>
Jerome Marchand00619bc2013-11-12 15:08:31 -080018
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080019#include <linux/uaccess.h>
Matt Mackall30992c92006-01-08 01:01:43 -080020
Namhyung Kim6038def2011-05-24 17:11:22 -070021#include "internal.h"
22
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080023/**
24 * kfree_const - conditionally free memory
25 * @x: pointer to the memory
26 *
27 * Function calls kfree only if @x is not in .rodata section.
28 */
29void kfree_const(const void *x)
30{
31 if (!is_kernel_rodata((unsigned long)x))
32 kfree(x);
33}
34EXPORT_SYMBOL(kfree_const);
35
Matt Mackall30992c92006-01-08 01:01:43 -080036/**
Matt Mackall30992c92006-01-08 01:01:43 -080037 * kstrdup - allocate space for and copy an existing string
Matt Mackall30992c92006-01-08 01:01:43 -080038 * @s: the string to duplicate
39 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
Mike Rapoporta862f682019-03-05 15:48:42 -080040 *
41 * Return: newly allocated copy of @s or %NULL in case of error
Matt Mackall30992c92006-01-08 01:01:43 -080042 */
43char *kstrdup(const char *s, gfp_t gfp)
44{
45 size_t len;
46 char *buf;
47
48 if (!s)
49 return NULL;
50
51 len = strlen(s) + 1;
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -070052 buf = kmalloc_track_caller(len, gfp);
Matt Mackall30992c92006-01-08 01:01:43 -080053 if (buf)
54 memcpy(buf, s, len);
55 return buf;
56}
57EXPORT_SYMBOL(kstrdup);
Davi Arnaut96840aa2006-03-24 03:18:42 -080058
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -070059/**
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080060 * 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
63 *
Mike Rapoporta862f682019-03-05 15:48:42 -080064 * Note: Strings allocated by kstrdup_const should be freed by kfree_const.
65 *
66 * Return: source string if it is in .rodata section otherwise
67 * fallback to kstrdup.
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080068 */
69const char *kstrdup_const(const char *s, gfp_t gfp)
70{
71 if (is_kernel_rodata((unsigned long)s))
72 return s;
73
74 return kstrdup(s, gfp);
75}
76EXPORT_SYMBOL(kstrdup_const);
77
78/**
Jeremy Fitzhardinge1e66df32007-07-17 18:37:02 -070079 * 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
David Howellsf3515742017-07-04 17:25:02 +010083 *
84 * Note: Use kmemdup_nul() instead if the size is known exactly.
Mike Rapoporta862f682019-03-05 15:48:42 -080085 *
86 * Return: newly allocated copy of @s or %NULL in case of error
Jeremy Fitzhardinge1e66df32007-07-17 18:37:02 -070087 */
88char *kstrndup(const char *s, size_t max, gfp_t gfp)
89{
90 size_t len;
91 char *buf;
92
93 if (!s)
94 return NULL;
95
96 len = strnlen(s, max);
97 buf = kmalloc_track_caller(len+1, gfp);
98 if (buf) {
99 memcpy(buf, s, len);
100 buf[len] = '\0';
101 }
102 return buf;
103}
104EXPORT_SYMBOL(kstrndup);
105
106/**
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700107 * kmemdup - duplicate region of memory
108 *
109 * @src: memory region to duplicate
110 * @len: memory region length
111 * @gfp: GFP mask to use
Mike Rapoporta862f682019-03-05 15:48:42 -0800112 *
113 * Return: newly allocated copy of @src or %NULL in case of error
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700114 */
115void *kmemdup(const void *src, size_t len, gfp_t gfp)
116{
117 void *p;
118
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -0700119 p = kmalloc_track_caller(len, gfp);
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700120 if (p)
121 memcpy(p, src, len);
122 return p;
123}
124EXPORT_SYMBOL(kmemdup);
125
Christoph Lameteref2ad802007-07-17 04:03:21 -0700126/**
David Howellsf3515742017-07-04 17:25:02 +0100127 * 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
Mike Rapoporta862f682019-03-05 15:48:42 -0800131 *
132 * Return: newly allocated copy of @s with NUL-termination or %NULL in
133 * case of error
David Howellsf3515742017-07-04 17:25:02 +0100134 */
135char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
136{
137 char *buf;
138
139 if (!s)
140 return NULL;
141
142 buf = kmalloc_track_caller(len + 1, gfp);
143 if (buf) {
144 memcpy(buf, s, len);
145 buf[len] = '\0';
146 }
147 return buf;
148}
149EXPORT_SYMBOL(kmemdup_nul);
150
151/**
Li Zefan610a77e2009-03-31 15:23:16 -0700152 * memdup_user - duplicate memory region from user space
153 *
154 * @src: source address in user space
155 * @len: number of bytes to copy
156 *
Mike Rapoporta862f682019-03-05 15:48:42 -0800157 * Return: an ERR_PTR() on failure. Result is physically
Al Viro50fd2f22018-01-07 13:06:15 -0500158 * contiguous, to be freed by kfree().
Li Zefan610a77e2009-03-31 15:23:16 -0700159 */
160void *memdup_user(const void __user *src, size_t len)
161{
162 void *p;
163
Daniel Vetter6c8fcc02019-02-20 22:20:42 -0800164 p = kmalloc_track_caller(len, GFP_USER | __GFP_NOWARN);
Li Zefan610a77e2009-03-31 15:23:16 -0700165 if (!p)
166 return ERR_PTR(-ENOMEM);
167
168 if (copy_from_user(p, src, len)) {
169 kfree(p);
170 return ERR_PTR(-EFAULT);
171 }
172
173 return p;
174}
175EXPORT_SYMBOL(memdup_user);
176
Al Viro50fd2f22018-01-07 13:06:15 -0500177/**
178 * vmemdup_user - duplicate memory region from user space
179 *
180 * @src: source address in user space
181 * @len: number of bytes to copy
182 *
Mike Rapoporta862f682019-03-05 15:48:42 -0800183 * Return: an ERR_PTR() on failure. Result may be not
Al Viro50fd2f22018-01-07 13:06:15 -0500184 * physically contiguous. Use kvfree() to free.
185 */
186void *vmemdup_user(const void __user *src, size_t len)
187{
188 void *p;
189
190 p = kvmalloc(len, GFP_USER);
191 if (!p)
192 return ERR_PTR(-ENOMEM);
193
194 if (copy_from_user(p, src, len)) {
195 kvfree(p);
196 return ERR_PTR(-EFAULT);
197 }
198
199 return p;
200}
201EXPORT_SYMBOL(vmemdup_user);
202
Mike Rapoportb86181f2018-08-23 17:00:59 -0700203/**
Davi Arnaut96840aa2006-03-24 03:18:42 -0800204 * strndup_user - duplicate an existing string from user space
Davi Arnaut96840aa2006-03-24 03:18:42 -0800205 * @s: The string to duplicate
206 * @n: Maximum number of bytes to copy, including the trailing NUL.
Mike Rapoporta862f682019-03-05 15:48:42 -0800207 *
Andrew Mortone9145522019-04-05 18:39:34 -0700208 * Return: newly allocated copy of @s or an ERR_PTR() in case of error
Davi Arnaut96840aa2006-03-24 03:18:42 -0800209 */
210char *strndup_user(const char __user *s, long n)
211{
212 char *p;
213 long length;
214
215 length = strnlen_user(s, n);
216
217 if (!length)
218 return ERR_PTR(-EFAULT);
219
220 if (length > n)
221 return ERR_PTR(-EINVAL);
222
Julia Lawall90d74042010-08-09 17:18:26 -0700223 p = memdup_user(s, length);
Davi Arnaut96840aa2006-03-24 03:18:42 -0800224
Julia Lawall90d74042010-08-09 17:18:26 -0700225 if (IS_ERR(p))
226 return p;
Davi Arnaut96840aa2006-03-24 03:18:42 -0800227
228 p[length - 1] = '\0';
229
230 return p;
231}
232EXPORT_SYMBOL(strndup_user);
Andrew Morton16d69262008-07-25 19:44:36 -0700233
Al Viroe9d408e12015-12-24 00:06:05 -0500234/**
235 * memdup_user_nul - duplicate memory region from user space and NUL-terminate
236 *
237 * @src: source address in user space
238 * @len: number of bytes to copy
239 *
Mike Rapoporta862f682019-03-05 15:48:42 -0800240 * Return: an ERR_PTR() on failure.
Al Viroe9d408e12015-12-24 00:06:05 -0500241 */
242void *memdup_user_nul(const void __user *src, size_t len)
243{
244 char *p;
245
246 /*
247 * Always use GFP_KERNEL, since copy_from_user() can sleep and
248 * cause pagefault, which makes it pointless to use GFP_NOFS
249 * or GFP_ATOMIC.
250 */
251 p = kmalloc_track_caller(len + 1, GFP_KERNEL);
252 if (!p)
253 return ERR_PTR(-ENOMEM);
254
255 if (copy_from_user(p, src, len)) {
256 kfree(p);
257 return ERR_PTR(-EFAULT);
258 }
259 p[len] = '\0';
260
261 return p;
262}
263EXPORT_SYMBOL(memdup_user_nul);
264
Namhyung Kim6038def2011-05-24 17:11:22 -0700265void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
266 struct vm_area_struct *prev, struct rb_node *rb_parent)
267{
268 struct vm_area_struct *next;
269
270 vma->vm_prev = prev;
271 if (prev) {
272 next = prev->vm_next;
273 prev->vm_next = vma;
274 } else {
275 mm->mmap = vma;
276 if (rb_parent)
277 next = rb_entry(rb_parent,
278 struct vm_area_struct, vm_rb);
279 else
280 next = NULL;
281 }
282 vma->vm_next = next;
283 if (next)
284 next->vm_prev = vma;
285}
286
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700287/* Check if the vma is being used as a stack by this task */
Andy Lutomirskid17af502016-09-30 10:58:58 -0700288int vma_is_stack_for_current(struct vm_area_struct *vma)
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700289{
Andy Lutomirskid17af502016-09-30 10:58:58 -0700290 struct task_struct * __maybe_unused t = current;
291
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700292 return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
293}
294
David Howellsefc1a3b2010-01-15 17:01:35 -0800295#if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
Kees Cook8f2af152018-04-10 16:34:53 -0700296void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
Andrew Morton16d69262008-07-25 19:44:36 -0700297{
298 mm->mmap_base = TASK_UNMAPPED_BASE;
299 mm->get_unmapped_area = arch_get_unmapped_area;
Andrew Morton16d69262008-07-25 19:44:36 -0700300}
301#endif
Rusty Russell912985d2008-08-12 17:52:52 -0500302
Al Viroeb36c582012-05-30 20:17:35 -0400303unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
304 unsigned long len, unsigned long prot,
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700305 unsigned long flag, unsigned long pgoff)
Al Viroeb36c582012-05-30 20:17:35 -0400306{
307 unsigned long ret;
308 struct mm_struct *mm = current->mm;
Michel Lespinasse41badc12013-02-22 16:32:47 -0800309 unsigned long populate;
Mike Rapoport897ab3e2017-02-24 14:58:22 -0800310 LIST_HEAD(uf);
Al Viroeb36c582012-05-30 20:17:35 -0400311
312 ret = security_mmap_file(file, prot, flag);
313 if (!ret) {
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700314 if (down_write_killable(&mm->mmap_sem))
315 return -EINTR;
Michel Lespinassebebeb3d2013-02-22 16:32:37 -0800316 ret = do_mmap_pgoff(file, addr, len, prot, flag, pgoff,
Mike Rapoport897ab3e2017-02-24 14:58:22 -0800317 &populate, &uf);
Al Viroeb36c582012-05-30 20:17:35 -0400318 up_write(&mm->mmap_sem);
Mike Rapoport897ab3e2017-02-24 14:58:22 -0800319 userfaultfd_unmap_complete(mm, &uf);
Michel Lespinasse41badc12013-02-22 16:32:47 -0800320 if (populate)
321 mm_populate(ret, populate);
Al Viroeb36c582012-05-30 20:17:35 -0400322 }
323 return ret;
324}
325
326unsigned long vm_mmap(struct file *file, unsigned long addr,
327 unsigned long len, unsigned long prot,
328 unsigned long flag, unsigned long offset)
329{
330 if (unlikely(offset + PAGE_ALIGN(len) < offset))
331 return -EINVAL;
Alexander Kuleshovea53cde2015-11-05 18:46:46 -0800332 if (unlikely(offset_in_page(offset)))
Al Viroeb36c582012-05-30 20:17:35 -0400333 return -EINVAL;
334
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700335 return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
Al Viroeb36c582012-05-30 20:17:35 -0400336}
337EXPORT_SYMBOL(vm_mmap);
338
Michal Hockoa7c3e902017-05-08 15:57:09 -0700339/**
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
345 *
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.
348 *
Michal Hockocc965a22017-07-12 14:36:52 -0700349 * 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.
Michal Hockoa7c3e902017-05-08 15:57:09 -0700352 *
Michal Hockoce91f6e2018-06-07 17:09:40 -0700353 * Please note that any use of gfp flags outside of GFP_KERNEL is careful to not
354 * fall back to vmalloc.
Mike Rapoporta862f682019-03-05 15:48:42 -0800355 *
356 * Return: pointer to the allocated memory of %NULL in case of failure
Michal Hockoa7c3e902017-05-08 15:57:09 -0700357 */
358void *kvmalloc_node(size_t size, gfp_t flags, int node)
359{
360 gfp_t kmalloc_flags = flags;
361 void *ret;
362
363 /*
364 * vmalloc uses GFP_KERNEL for some internal allocations (e.g page tables)
365 * so the given set of flags has to be compatible.
366 */
Michal Hockoce91f6e2018-06-07 17:09:40 -0700367 if ((flags & GFP_KERNEL) != GFP_KERNEL)
368 return kmalloc_node(size, flags, node);
Michal Hockoa7c3e902017-05-08 15:57:09 -0700369
370 /*
Michal Hocko4f4f2ba2017-06-02 14:46:19 -0700371 * 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.
Michal Hockoa7c3e902017-05-08 15:57:09 -0700376 */
Michal Hocko6c5ab6512017-05-08 15:57:15 -0700377 if (size > PAGE_SIZE) {
378 kmalloc_flags |= __GFP_NOWARN;
379
Michal Hockocc965a22017-07-12 14:36:52 -0700380 if (!(kmalloc_flags & __GFP_RETRY_MAYFAIL))
Michal Hocko6c5ab6512017-05-08 15:57:15 -0700381 kmalloc_flags |= __GFP_NORETRY;
382 }
Michal Hockoa7c3e902017-05-08 15:57:09 -0700383
384 ret = kmalloc_node(size, kmalloc_flags, node);
385
386 /*
387 * It doesn't really make sense to fallback to vmalloc for sub page
388 * requests
389 */
390 if (ret || size <= PAGE_SIZE)
391 return ret;
392
Michal Hocko8594a212017-05-12 15:46:41 -0700393 return __vmalloc_node_flags_caller(size, node, flags,
394 __builtin_return_address(0));
Michal Hockoa7c3e902017-05-08 15:57:09 -0700395}
396EXPORT_SYMBOL(kvmalloc_node);
397
Mike Rapoportff4dc772018-08-23 17:01:02 -0700398/**
Andrew Morton04b8e942018-09-04 15:45:55 -0700399 * kvfree() - Free memory.
400 * @addr: Pointer to allocated memory.
Mike Rapoportff4dc772018-08-23 17:01:02 -0700401 *
Andrew Morton04b8e942018-09-04 15:45:55 -0700402 * 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.
405 *
Andrey Ryabinin52414d32018-10-26 15:07:00 -0700406 * Context: Either preemptible task context or not-NMI interrupt.
Mike Rapoportff4dc772018-08-23 17:01:02 -0700407 */
Al Viro39f1f782014-05-06 14:02:53 -0400408void kvfree(const void *addr)
409{
410 if (is_vmalloc_addr(addr))
411 vfree(addr);
412 else
413 kfree(addr);
414}
415EXPORT_SYMBOL(kvfree);
416
Kirill A. Shutemove39155ea2015-04-15 16:14:53 -0700417static inline void *__page_rmapping(struct page *page)
418{
419 unsigned long mapping;
420
421 mapping = (unsigned long)page->mapping;
422 mapping &= ~PAGE_MAPPING_FLAGS;
423
424 return (void *)mapping;
425}
426
427/* Neutral page->mapping pointer to address_space or anon_vma or other */
428void *page_rmapping(struct page *page)
429{
430 page = compound_head(page);
431 return __page_rmapping(page);
432}
433
Andrew Morton1aa8aea52016-05-19 17:12:00 -0700434/*
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.
437 */
438bool page_mapped(struct page *page)
439{
440 int i;
441
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)
446 return true;
447 if (PageHuge(page))
448 return false;
Jan Stancek8ab88c712019-01-08 15:23:28 -0800449 for (i = 0; i < (1 << compound_order(page)); i++) {
Andrew Morton1aa8aea52016-05-19 17:12:00 -0700450 if (atomic_read(&page[i]._mapcount) >= 0)
451 return true;
452 }
453 return false;
454}
455EXPORT_SYMBOL(page_mapped);
456
Kirill A. Shutemove39155ea2015-04-15 16:14:53 -0700457struct anon_vma *page_anon_vma(struct page *page)
458{
459 unsigned long mapping;
460
461 page = compound_head(page);
462 mapping = (unsigned long)page->mapping;
463 if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
464 return NULL;
465 return __page_rmapping(page);
466}
467
Shaohua Li98003392013-02-22 16:34:35 -0800468struct address_space *page_mapping(struct page *page)
469{
Kirill A. Shutemov1c290f62016-01-15 16:52:07 -0800470 struct address_space *mapping;
471
472 page = compound_head(page);
Shaohua Li98003392013-02-22 16:34:35 -0800473
Mikulas Patocka03e5ac22014-01-14 17:56:40 -0800474 /* This happens if someone calls flush_dcache_page on slab page */
475 if (unlikely(PageSlab(page)))
476 return NULL;
477
Shaohua Li33806f02013-02-22 16:34:37 -0800478 if (unlikely(PageSwapCache(page))) {
479 swp_entry_t entry;
480
481 entry.val = page_private(page);
Kirill A. Shutemove39155ea2015-04-15 16:14:53 -0700482 return swap_address_space(entry);
483 }
484
Kirill A. Shutemov1c290f62016-01-15 16:52:07 -0800485 mapping = page->mapping;
Minchan Kimbda807d2016-07-26 15:23:05 -0700486 if ((unsigned long)mapping & PAGE_MAPPING_ANON)
Kirill A. Shutemove39155ea2015-04-15 16:14:53 -0700487 return NULL;
Minchan Kimbda807d2016-07-26 15:23:05 -0700488
489 return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
Shaohua Li98003392013-02-22 16:34:35 -0800490}
Minchan Kimbda807d2016-07-26 15:23:05 -0700491EXPORT_SYMBOL(page_mapping);
Shaohua Li98003392013-02-22 16:34:35 -0800492
Huang Yingcb9f7532018-04-05 16:24:39 -0700493/*
494 * For file cache pages, return the address_space, otherwise return NULL
495 */
496struct address_space *page_mapping_file(struct page *page)
497{
498 if (unlikely(PageSwapCache(page)))
499 return NULL;
500 return page_mapping(page);
501}
502
Kirill A. Shutemovb20ce5e2016-01-15 16:54:37 -0800503/* Slow path of page_mapcount() for compound pages */
504int __page_mapcount(struct page *page)
505{
506 int ret;
507
508 ret = atomic_read(&page->_mapcount) + 1;
Kirill A. Shutemovdd78fed2016-07-26 15:25:26 -0700509 /*
510 * For file THP page->_mapcount contains total number of mapping
511 * of the page: no need to look into compound_mapcount.
512 */
513 if (!PageAnon(page) && !PageHuge(page))
514 return ret;
Kirill A. Shutemovb20ce5e2016-01-15 16:54:37 -0800515 page = compound_head(page);
516 ret += atomic_read(compound_mapcount_ptr(page)) + 1;
517 if (PageDoubleMap(page))
518 ret--;
519 return ret;
520}
521EXPORT_SYMBOL_GPL(__page_mapcount);
522
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700523int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
524int sysctl_overcommit_ratio __read_mostly = 50;
525unsigned long sysctl_overcommit_kbytes __read_mostly;
526int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
527unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
528unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
529
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800530int overcommit_ratio_handler(struct ctl_table *table, int write,
531 void __user *buffer, size_t *lenp,
532 loff_t *ppos)
533{
534 int ret;
535
536 ret = proc_dointvec(table, write, buffer, lenp, ppos);
537 if (ret == 0 && write)
538 sysctl_overcommit_kbytes = 0;
539 return ret;
540}
541
542int overcommit_kbytes_handler(struct ctl_table *table, int write,
543 void __user *buffer, size_t *lenp,
544 loff_t *ppos)
545{
546 int ret;
547
548 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
549 if (ret == 0 && write)
550 sysctl_overcommit_ratio = 0;
551 return ret;
552}
553
Jerome Marchand00619bc2013-11-12 15:08:31 -0800554/*
555 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
556 */
557unsigned long vm_commit_limit(void)
558{
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800559 unsigned long allowed;
560
561 if (sysctl_overcommit_kbytes)
562 allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
563 else
Arun KSca79b0c2018-12-28 00:34:29 -0800564 allowed = ((totalram_pages() - hugetlb_total_pages())
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800565 * sysctl_overcommit_ratio / 100);
566 allowed += total_swap_pages;
567
568 return allowed;
Jerome Marchand00619bc2013-11-12 15:08:31 -0800569}
570
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700571/*
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.
574 */
575struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
576
577/*
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
583 * memory commitment.
584 */
585unsigned long vm_memory_committed(void)
586{
587 return percpu_counter_read_positive(&vm_committed_as);
588}
589EXPORT_SYMBOL_GPL(vm_memory_committed);
590
591/*
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.
595 *
596 * We currently support three overcommit policies, which are set via the
Mike Rapoportad56b732018-03-21 21:22:47 +0200597 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting.rst
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700598 *
599 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
600 * Additional code 2002 Jul 20 by Robert Love.
601 *
602 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
603 *
604 * Note this is a helper function intended to be used by LSMs which
605 * wish to use this logic.
606 */
607int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
608{
Johannes Weiner8c7829b2019-05-13 17:21:50 -0700609 long allowed;
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700610
611 VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
612 -(s64)vm_committed_as_batch * num_online_cpus(),
613 "memory commitment underflow");
614
615 vm_acct_memory(pages);
616
617 /*
618 * Sometimes we want to use more memory than we have
619 */
620 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
621 return 0;
622
623 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
Johannes Weiner8c7829b2019-05-13 17:21:50 -0700624 if (pages > totalram_pages() + total_swap_pages)
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700625 goto error;
Johannes Weiner8c7829b2019-05-13 17:21:50 -0700626 return 0;
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700627 }
628
629 allowed = vm_commit_limit();
630 /*
631 * Reserve some for root
632 */
633 if (!cap_sys_admin)
634 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
635
636 /*
637 * Don't let a single process grow so big a user can't recover
638 */
639 if (mm) {
Johannes Weiner8c7829b2019-05-13 17:21:50 -0700640 long reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
641
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700642 allowed -= min_t(long, mm->total_vm / 32, reserve);
643 }
644
645 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
646 return 0;
647error:
648 vm_unacct_memory(pages);
649
650 return -ENOMEM;
651}
652
William Robertsa9090252014-02-11 10:11:59 -0800653/**
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
658 * to this length.
Mike Rapoporta862f682019-03-05 15:48:42 -0800659 *
660 * Return: the size of the cmdline field copied. Note that the copy does
William Robertsa9090252014-02-11 10:11:59 -0800661 * not guarantee an ending NULL byte.
662 */
663int get_cmdline(struct task_struct *task, char *buffer, int buflen)
664{
665 int res = 0;
666 unsigned int len;
667 struct mm_struct *mm = get_task_mm(task);
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800668 unsigned long arg_start, arg_end, env_start, env_end;
William Robertsa9090252014-02-11 10:11:59 -0800669 if (!mm)
670 goto out;
671 if (!mm->arg_end)
672 goto out_mm; /* Shh! No looking before we're done */
673
Michal Koutnýbc814262019-05-31 22:30:19 -0700674 spin_lock(&mm->arg_lock);
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800675 arg_start = mm->arg_start;
676 arg_end = mm->arg_end;
677 env_start = mm->env_start;
678 env_end = mm->env_end;
Michal Koutnýbc814262019-05-31 22:30:19 -0700679 spin_unlock(&mm->arg_lock);
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800680
681 len = arg_end - arg_start;
William Robertsa9090252014-02-11 10:11:59 -0800682
683 if (len > buflen)
684 len = buflen;
685
Lorenzo Stoakesf307ab62016-10-13 01:20:20 +0100686 res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
William Robertsa9090252014-02-11 10:11:59 -0800687
688 /*
689 * If the nul at the end of args has been overwritten, then
690 * assume application is using setproctitle(3).
691 */
692 if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
693 len = strnlen(buffer, res);
694 if (len < res) {
695 res = len;
696 } else {
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800697 len = env_end - env_start;
William Robertsa9090252014-02-11 10:11:59 -0800698 if (len > buflen - res)
699 len = buflen - res;
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800700 res += access_process_vm(task, env_start,
Lorenzo Stoakesf307ab62016-10-13 01:20:20 +0100701 buffer+res, len,
702 FOLL_FORCE);
William Robertsa9090252014-02-11 10:11:59 -0800703 res = strnlen(buffer, res);
704 }
705 }
706out_mm:
707 mmput(mm);
708out:
709 return res;
710}