blob: 734b2d0e4a498b22abbcefbb0122b5b69eff80fd [file] [log] [blame]
Andrew Morton16d69262008-07-25 19:44:36 -07001#include <linux/mm.h>
Matt Mackall30992c92006-01-08 01:01:43 -08002#include <linux/slab.h>
3#include <linux/string.h>
Gideon Israel Dsouza3b321232014-04-07 15:37:26 -07004#include <linux/compiler.h>
Paul Gortmakerb95f1b312011-10-16 02:01:52 -04005#include <linux/export.h>
Davi Arnaut96840aa2006-03-24 03:18:42 -08006#include <linux/err.h>
Adrian Bunk3b8f14b2008-07-26 15:22:28 -07007#include <linux/sched.h>
Al Viroeb36c582012-05-30 20:17:35 -04008#include <linux/security.h>
Shaohua Li98003392013-02-22 16:34:35 -08009#include <linux/swap.h>
Shaohua Li33806f02013-02-22 16:34:37 -080010#include <linux/swapops.h>
Jerome Marchand00619bc2013-11-12 15:08:31 -080011#include <linux/mman.h>
12#include <linux/hugetlb.h>
Al Viro39f1f782014-05-06 14:02:53 -040013#include <linux/vmalloc.h>
Jason A. Donenfeld46eac532022-05-14 13:59:30 +020014#include <linux/random.h>
Jerome Marchand00619bc2013-11-12 15:08:31 -080015
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080016#include <asm/sections.h>
Davi Arnaut96840aa2006-03-24 03:18:42 -080017#include <asm/uaccess.h>
Matt Mackall30992c92006-01-08 01:01:43 -080018
Namhyung Kim6038def2011-05-24 17:11:22 -070019#include "internal.h"
20
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080021static inline int is_kernel_rodata(unsigned long addr)
22{
23 return addr >= (unsigned long)__start_rodata &&
24 addr < (unsigned long)__end_rodata;
25}
26
27/**
28 * kfree_const - conditionally free memory
29 * @x: pointer to the memory
30 *
31 * Function calls kfree only if @x is not in .rodata section.
32 */
33void kfree_const(const void *x)
34{
35 if (!is_kernel_rodata((unsigned long)x))
36 kfree(x);
37}
38EXPORT_SYMBOL(kfree_const);
39
Matt Mackall30992c92006-01-08 01:01:43 -080040/**
Matt Mackall30992c92006-01-08 01:01:43 -080041 * kstrdup - allocate space for and copy an existing string
Matt Mackall30992c92006-01-08 01:01:43 -080042 * @s: the string to duplicate
43 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
44 */
45char *kstrdup(const char *s, gfp_t gfp)
46{
47 size_t len;
48 char *buf;
49
50 if (!s)
51 return NULL;
52
53 len = strlen(s) + 1;
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -070054 buf = kmalloc_track_caller(len, gfp);
Matt Mackall30992c92006-01-08 01:01:43 -080055 if (buf)
56 memcpy(buf, s, len);
57 return buf;
58}
59EXPORT_SYMBOL(kstrdup);
Davi Arnaut96840aa2006-03-24 03:18:42 -080060
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -070061/**
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080062 * 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
65 *
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.
69 */
70const char *kstrdup_const(const char *s, gfp_t gfp)
71{
72 if (is_kernel_rodata((unsigned long)s))
73 return s;
74
75 return kstrdup(s, gfp);
76}
77EXPORT_SYMBOL(kstrdup_const);
78
79/**
Jeremy Fitzhardinge1e66df32007-07-17 18:37:02 -070080 * 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
David Howells5cab144f2017-07-04 17:25:02 +010084 *
85 * Note: Use kmemdup_nul() instead if the size is known exactly.
Jeremy Fitzhardinge1e66df32007-07-17 18:37:02 -070086 */
87char *kstrndup(const char *s, size_t max, gfp_t gfp)
88{
89 size_t len;
90 char *buf;
91
92 if (!s)
93 return NULL;
94
95 len = strnlen(s, max);
96 buf = kmalloc_track_caller(len+1, gfp);
97 if (buf) {
98 memcpy(buf, s, len);
99 buf[len] = '\0';
100 }
101 return buf;
102}
103EXPORT_SYMBOL(kstrndup);
104
105/**
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700106 * kmemdup - duplicate region of memory
107 *
108 * @src: memory region to duplicate
109 * @len: memory region length
110 * @gfp: GFP mask to use
111 */
112void *kmemdup(const void *src, size_t len, gfp_t gfp)
113{
114 void *p;
115
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -0700116 p = kmalloc_track_caller(len, gfp);
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700117 if (p)
118 memcpy(p, src, len);
119 return p;
120}
121EXPORT_SYMBOL(kmemdup);
122
Christoph Lameteref2ad802007-07-17 04:03:21 -0700123/**
David Howells5cab144f2017-07-04 17:25:02 +0100124 * 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
128 */
129char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
130{
131 char *buf;
132
133 if (!s)
134 return NULL;
135
136 buf = kmalloc_track_caller(len + 1, gfp);
137 if (buf) {
138 memcpy(buf, s, len);
139 buf[len] = '\0';
140 }
141 return buf;
142}
143EXPORT_SYMBOL(kmemdup_nul);
144
145/**
Li Zefan610a77e2009-03-31 15:23:16 -0700146 * memdup_user - duplicate memory region from user space
147 *
148 * @src: source address in user space
149 * @len: number of bytes to copy
150 *
151 * Returns an ERR_PTR() on failure.
152 */
153void *memdup_user(const void __user *src, size_t len)
154{
155 void *p;
156
157 /*
158 * Always use GFP_KERNEL, since copy_from_user() can sleep and
159 * cause pagefault, which makes it pointless to use GFP_NOFS
160 * or GFP_ATOMIC.
161 */
162 p = kmalloc_track_caller(len, GFP_KERNEL);
163 if (!p)
164 return ERR_PTR(-ENOMEM);
165
166 if (copy_from_user(p, src, len)) {
167 kfree(p);
168 return ERR_PTR(-EFAULT);
169 }
170
171 return p;
172}
173EXPORT_SYMBOL(memdup_user);
174
Davi Arnaut96840aa2006-03-24 03:18:42 -0800175/*
176 * strndup_user - duplicate an existing string from user space
Davi Arnaut96840aa2006-03-24 03:18:42 -0800177 * @s: The string to duplicate
178 * @n: Maximum number of bytes to copy, including the trailing NUL.
179 */
180char *strndup_user(const char __user *s, long n)
181{
182 char *p;
183 long length;
184
185 length = strnlen_user(s, n);
186
187 if (!length)
188 return ERR_PTR(-EFAULT);
189
190 if (length > n)
191 return ERR_PTR(-EINVAL);
192
Julia Lawall90d74042010-08-09 17:18:26 -0700193 p = memdup_user(s, length);
Davi Arnaut96840aa2006-03-24 03:18:42 -0800194
Julia Lawall90d74042010-08-09 17:18:26 -0700195 if (IS_ERR(p))
196 return p;
Davi Arnaut96840aa2006-03-24 03:18:42 -0800197
198 p[length - 1] = '\0';
199
200 return p;
201}
202EXPORT_SYMBOL(strndup_user);
Andrew Morton16d69262008-07-25 19:44:36 -0700203
Al Viroe9d408e2015-12-24 00:06:05 -0500204/**
205 * memdup_user_nul - duplicate memory region from user space and NUL-terminate
206 *
207 * @src: source address in user space
208 * @len: number of bytes to copy
209 *
210 * Returns an ERR_PTR() on failure.
211 */
212void *memdup_user_nul(const void __user *src, size_t len)
213{
214 char *p;
215
216 /*
217 * Always use GFP_KERNEL, since copy_from_user() can sleep and
218 * cause pagefault, which makes it pointless to use GFP_NOFS
219 * or GFP_ATOMIC.
220 */
221 p = kmalloc_track_caller(len + 1, GFP_KERNEL);
222 if (!p)
223 return ERR_PTR(-ENOMEM);
224
225 if (copy_from_user(p, src, len)) {
226 kfree(p);
227 return ERR_PTR(-EFAULT);
228 }
229 p[len] = '\0';
230
231 return p;
232}
233EXPORT_SYMBOL(memdup_user_nul);
234
Namhyung Kim6038def2011-05-24 17:11:22 -0700235void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
236 struct vm_area_struct *prev, struct rb_node *rb_parent)
237{
238 struct vm_area_struct *next;
239
240 vma->vm_prev = prev;
241 if (prev) {
242 next = prev->vm_next;
243 prev->vm_next = vma;
244 } else {
245 mm->mmap = vma;
246 if (rb_parent)
247 next = rb_entry(rb_parent,
248 struct vm_area_struct, vm_rb);
249 else
250 next = NULL;
251 }
252 vma->vm_next = next;
253 if (next)
254 next->vm_prev = vma;
255}
256
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700257/* Check if the vma is being used as a stack by this task */
Andy Lutomirskid17af502016-09-30 10:58:58 -0700258int vma_is_stack_for_current(struct vm_area_struct *vma)
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700259{
Andy Lutomirskid17af502016-09-30 10:58:58 -0700260 struct task_struct * __maybe_unused t = current;
261
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700262 return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
263}
264
Jason A. Donenfeld46eac532022-05-14 13:59:30 +0200265/**
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.
270 *
271 * If @start + @range would overflow, @range is capped.
272 *
273 * NOTE: Historical use of randomize_range, which this replaces, presumed that
274 * @start was already page aligned. We now align it regardless.
275 *
276 * Return: A page aligned address within [start, start + range). On error,
277 * @start is returned.
278 */
279unsigned long randomize_page(unsigned long start, unsigned long range)
280{
281 if (!PAGE_ALIGNED(start)) {
282 range -= PAGE_ALIGN(start) - start;
283 start = PAGE_ALIGN(start);
284 }
285
286 if (start > ULONG_MAX - range)
287 range = ULONG_MAX - start;
288
289 range >>= PAGE_SHIFT;
290
291 if (range == 0)
292 return start;
293
294 return start + (get_random_long() % range << PAGE_SHIFT);
295}
296
David Howellsefc1a3b2010-01-15 17:01:35 -0800297#if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
Andrew Morton16d69262008-07-25 19:44:36 -0700298void arch_pick_mmap_layout(struct mm_struct *mm)
299{
300 mm->mmap_base = TASK_UNMAPPED_BASE;
301 mm->get_unmapped_area = arch_get_unmapped_area;
Andrew Morton16d69262008-07-25 19:44:36 -0700302}
303#endif
Rusty Russell912985d2008-08-12 17:52:52 -0500304
Xiao Guangrong45888a02010-08-22 19:08:57 +0800305/*
306 * Like get_user_pages_fast() except its IRQ-safe in that it won't fall
307 * back to the regular GUP.
Lucas De Marchi25985ed2011-03-30 22:57:33 -0300308 * If the architecture not support this function, simply return with no
Xiao Guangrong45888a02010-08-22 19:08:57 +0800309 * page pinned
310 */
Gideon Israel Dsouza3b321232014-04-07 15:37:26 -0700311int __weak __get_user_pages_fast(unsigned long start,
Xiao Guangrong45888a02010-08-22 19:08:57 +0800312 int nr_pages, int write, struct page **pages)
313{
314 return 0;
315}
316EXPORT_SYMBOL_GPL(__get_user_pages_fast);
317
Andy Grover9de100d2009-04-13 14:40:05 -0700318/**
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.
325 *
Andy Grover9de100d2009-04-13 14:40:05 -0700326 * 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.
Nick Piggind2bf6be2009-06-16 15:31:39 -0700329 *
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.
333 *
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.
Andy Grover9de100d2009-04-13 14:40:05 -0700341 */
Gideon Israel Dsouza3b321232014-04-07 15:37:26 -0700342int __weak get_user_pages_fast(unsigned long start,
Rusty Russell912985d2008-08-12 17:52:52 -0500343 int nr_pages, int write, struct page **pages)
344{
Lorenzo Stoakesc1641542016-10-13 01:20:13 +0100345 return get_user_pages_unlocked(start, nr_pages, pages,
346 write ? FOLL_WRITE : 0);
Rusty Russell912985d2008-08-12 17:52:52 -0500347}
348EXPORT_SYMBOL_GPL(get_user_pages_fast);
Eduard - Gabriel Munteanuca2b84c2009-03-23 15:12:24 +0200349
Al Viroeb36c582012-05-30 20:17:35 -0400350unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
351 unsigned long len, unsigned long prot,
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700352 unsigned long flag, unsigned long pgoff)
Al Viroeb36c582012-05-30 20:17:35 -0400353{
354 unsigned long ret;
355 struct mm_struct *mm = current->mm;
Michel Lespinasse41badc12013-02-22 16:32:47 -0800356 unsigned long populate;
Al Viroeb36c582012-05-30 20:17:35 -0400357
358 ret = security_mmap_file(file, prot, flag);
359 if (!ret) {
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700360 if (down_write_killable(&mm->mmap_sem))
361 return -EINTR;
Michel Lespinassebebeb3d2013-02-22 16:32:37 -0800362 ret = do_mmap_pgoff(file, addr, len, prot, flag, pgoff,
363 &populate);
Al Viroeb36c582012-05-30 20:17:35 -0400364 up_write(&mm->mmap_sem);
Michel Lespinasse41badc12013-02-22 16:32:47 -0800365 if (populate)
366 mm_populate(ret, populate);
Al Viroeb36c582012-05-30 20:17:35 -0400367 }
368 return ret;
369}
370
371unsigned long vm_mmap(struct file *file, unsigned long addr,
372 unsigned long len, unsigned long prot,
373 unsigned long flag, unsigned long offset)
374{
375 if (unlikely(offset + PAGE_ALIGN(len) < offset))
376 return -EINVAL;
Alexander Kuleshovea53cde2015-11-05 18:46:46 -0800377 if (unlikely(offset_in_page(offset)))
Al Viroeb36c582012-05-30 20:17:35 -0400378 return -EINVAL;
379
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700380 return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
Al Viroeb36c582012-05-30 20:17:35 -0400381}
382EXPORT_SYMBOL(vm_mmap);
383
Al Viro39f1f782014-05-06 14:02:53 -0400384void kvfree(const void *addr)
385{
386 if (is_vmalloc_addr(addr))
387 vfree(addr);
388 else
389 kfree(addr);
390}
391EXPORT_SYMBOL(kvfree);
392
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700393static inline void *__page_rmapping(struct page *page)
394{
395 unsigned long mapping;
396
397 mapping = (unsigned long)page->mapping;
398 mapping &= ~PAGE_MAPPING_FLAGS;
399
400 return (void *)mapping;
401}
402
403/* Neutral page->mapping pointer to address_space or anon_vma or other */
404void *page_rmapping(struct page *page)
405{
406 page = compound_head(page);
407 return __page_rmapping(page);
408}
409
Andrew Morton1aa8aea2016-05-19 17:12:00 -0700410/*
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.
413 */
414bool page_mapped(struct page *page)
415{
416 int i;
417
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)
422 return true;
423 if (PageHuge(page))
424 return false;
Jan Stancekbe225792019-01-08 15:23:28 -0800425 for (i = 0; i < (1 << compound_order(page)); i++) {
Andrew Morton1aa8aea2016-05-19 17:12:00 -0700426 if (atomic_read(&page[i]._mapcount) >= 0)
427 return true;
428 }
429 return false;
430}
431EXPORT_SYMBOL(page_mapped);
432
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700433struct anon_vma *page_anon_vma(struct page *page)
434{
435 unsigned long mapping;
436
437 page = compound_head(page);
438 mapping = (unsigned long)page->mapping;
439 if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
440 return NULL;
441 return __page_rmapping(page);
442}
443
Shaohua Li98003392013-02-22 16:34:35 -0800444struct address_space *page_mapping(struct page *page)
445{
Kirill A. Shutemov1c290f62016-01-15 16:52:07 -0800446 struct address_space *mapping;
447
448 page = compound_head(page);
Shaohua Li98003392013-02-22 16:34:35 -0800449
Mikulas Patocka03e5ac22014-01-14 17:56:40 -0800450 /* This happens if someone calls flush_dcache_page on slab page */
451 if (unlikely(PageSlab(page)))
452 return NULL;
453
Shaohua Li33806f02013-02-22 16:34:37 -0800454 if (unlikely(PageSwapCache(page))) {
455 swp_entry_t entry;
456
457 entry.val = page_private(page);
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700458 return swap_address_space(entry);
459 }
460
Kirill A. Shutemov1c290f62016-01-15 16:52:07 -0800461 mapping = page->mapping;
Minchan Kimbda807d2016-07-26 15:23:05 -0700462 if ((unsigned long)mapping & PAGE_MAPPING_ANON)
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700463 return NULL;
Minchan Kimbda807d2016-07-26 15:23:05 -0700464
465 return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
Shaohua Li98003392013-02-22 16:34:35 -0800466}
Minchan Kimbda807d2016-07-26 15:23:05 -0700467EXPORT_SYMBOL(page_mapping);
Shaohua Li98003392013-02-22 16:34:35 -0800468
Kirill A. Shutemovb20ce5e2016-01-15 16:54:37 -0800469/* Slow path of page_mapcount() for compound pages */
470int __page_mapcount(struct page *page)
471{
472 int ret;
473
474 ret = atomic_read(&page->_mapcount) + 1;
Kirill A. Shutemovdd78fed2016-07-26 15:25:26 -0700475 /*
476 * For file THP page->_mapcount contains total number of mapping
477 * of the page: no need to look into compound_mapcount.
478 */
479 if (!PageAnon(page) && !PageHuge(page))
480 return ret;
Kirill A. Shutemovb20ce5e2016-01-15 16:54:37 -0800481 page = compound_head(page);
482 ret += atomic_read(compound_mapcount_ptr(page)) + 1;
483 if (PageDoubleMap(page))
484 ret--;
485 return ret;
486}
487EXPORT_SYMBOL_GPL(__page_mapcount);
488
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700489int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
490int sysctl_overcommit_ratio __read_mostly = 50;
491unsigned long sysctl_overcommit_kbytes __read_mostly;
492int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
493unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
494unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
495
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800496int overcommit_ratio_handler(struct ctl_table *table, int write,
497 void __user *buffer, size_t *lenp,
498 loff_t *ppos)
499{
500 int ret;
501
502 ret = proc_dointvec(table, write, buffer, lenp, ppos);
503 if (ret == 0 && write)
504 sysctl_overcommit_kbytes = 0;
505 return ret;
506}
507
508int overcommit_kbytes_handler(struct ctl_table *table, int write,
509 void __user *buffer, size_t *lenp,
510 loff_t *ppos)
511{
512 int ret;
513
514 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
515 if (ret == 0 && write)
516 sysctl_overcommit_ratio = 0;
517 return ret;
518}
519
Jerome Marchand00619bc2013-11-12 15:08:31 -0800520/*
521 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
522 */
523unsigned long vm_commit_limit(void)
524{
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800525 unsigned long allowed;
526
527 if (sysctl_overcommit_kbytes)
528 allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
529 else
530 allowed = ((totalram_pages - hugetlb_total_pages())
531 * sysctl_overcommit_ratio / 100);
532 allowed += total_swap_pages;
533
534 return allowed;
Jerome Marchand00619bc2013-11-12 15:08:31 -0800535}
536
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700537/*
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.
540 */
541struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
542
543/*
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
549 * memory commitment.
550 */
551unsigned long vm_memory_committed(void)
552{
553 return percpu_counter_read_positive(&vm_committed_as);
554}
555EXPORT_SYMBOL_GPL(vm_memory_committed);
556
557/*
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.
561 *
562 * We currently support three overcommit policies, which are set via the
563 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
564 *
565 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
566 * Additional code 2002 Jul 20 by Robert Love.
567 *
568 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
569 *
570 * Note this is a helper function intended to be used by LSMs which
571 * wish to use this logic.
572 */
573int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
574{
575 long free, allowed, reserve;
576
577 VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
578 -(s64)vm_committed_as_batch * num_online_cpus(),
579 "memory commitment underflow");
580
581 vm_acct_memory(pages);
582
583 /*
584 * Sometimes we want to use more memory than we have
585 */
586 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
587 return 0;
588
589 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
590 free = global_page_state(NR_FREE_PAGES);
Mel Gorman11fb9982016-07-28 15:46:20 -0700591 free += global_node_page_state(NR_FILE_PAGES);
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700592
593 /*
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.
598 */
Mel Gorman11fb9982016-07-28 15:46:20 -0700599 free -= global_node_page_state(NR_SHMEM);
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700600
601 free += get_nr_swap_pages();
602
603 /*
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
608 */
609 free += global_page_state(NR_SLAB_RECLAIMABLE);
610
611 /*
Roman Gushchin2309d0a2018-04-10 16:27:47 -0700612 * Part of the kernel memory, which can be released
613 * under memory pressure.
614 */
615 free += global_node_page_state(
616 NR_INDIRECTLY_RECLAIMABLE_BYTES) >> PAGE_SHIFT;
617
618 /*
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700619 * Leave reserved pages. The pages are not for anonymous pages.
620 */
621 if (free <= totalreserve_pages)
622 goto error;
623 else
624 free -= totalreserve_pages;
625
626 /*
627 * Reserve some for root
628 */
629 if (!cap_sys_admin)
630 free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
631
632 if (free > pages)
633 return 0;
634
635 goto error;
636 }
637
638 allowed = vm_commit_limit();
639 /*
640 * Reserve some for root
641 */
642 if (!cap_sys_admin)
643 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
644
645 /*
646 * Don't let a single process grow so big a user can't recover
647 */
648 if (mm) {
649 reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
650 allowed -= min_t(long, mm->total_vm / 32, reserve);
651 }
652
653 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
654 return 0;
655error:
656 vm_unacct_memory(pages);
657
658 return -ENOMEM;
659}
660
William Robertsa9090252014-02-11 10:11:59 -0800661/**
662 * get_cmdline() - copy the cmdline value to a buffer.
663 * @task: the task whose cmdline value to copy.
664 * @buffer: the buffer to copy to.
665 * @buflen: the length of the buffer. Larger cmdline values are truncated
666 * to this length.
667 * Returns the size of the cmdline field copied. Note that the copy does
668 * not guarantee an ending NULL byte.
669 */
670int get_cmdline(struct task_struct *task, char *buffer, int buflen)
671{
672 int res = 0;
673 unsigned int len;
674 struct mm_struct *mm = get_task_mm(task);
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800675 unsigned long arg_start, arg_end, env_start, env_end;
William Robertsa9090252014-02-11 10:11:59 -0800676 if (!mm)
677 goto out;
678 if (!mm->arg_end)
679 goto out_mm; /* Shh! No looking before we're done */
680
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800681 down_read(&mm->mmap_sem);
682 arg_start = mm->arg_start;
683 arg_end = mm->arg_end;
684 env_start = mm->env_start;
685 env_end = mm->env_end;
686 up_read(&mm->mmap_sem);
687
688 len = arg_end - arg_start;
William Robertsa9090252014-02-11 10:11:59 -0800689
690 if (len > buflen)
691 len = buflen;
692
Lorenzo Stoakesf307ab62016-10-13 01:20:20 +0100693 res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
William Robertsa9090252014-02-11 10:11:59 -0800694
695 /*
696 * If the nul at the end of args has been overwritten, then
697 * assume application is using setproctitle(3).
698 */
699 if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
700 len = strnlen(buffer, res);
701 if (len < res) {
702 res = len;
703 } else {
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800704 len = env_end - env_start;
William Robertsa9090252014-02-11 10:11:59 -0800705 if (len > buflen - res)
706 len = buflen - res;
Mateusz Guzika3b609e2016-01-20 15:01:05 -0800707 res += access_process_vm(task, env_start,
Lorenzo Stoakesf307ab62016-10-13 01:20:20 +0100708 buffer+res, len,
709 FOLL_FORCE);
William Robertsa9090252014-02-11 10:11:59 -0800710 res = strnlen(buffer, res);
711 }
712 }
713out_mm:
714 mmput(mm);
715out:
716 return res;
717}