blob: dd9a4fdde0f04f5868936ed32f7b86dda3c92f23 [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>
Daniel Jordan79eb5972019-07-16 16:30:54 -070010#include <linux/sched/signal.h>
Ingo Molnar68db0cf2017-02-08 18:51:37 +010011#include <linux/sched/task_stack.h>
Al Viroeb36c582012-05-30 20:17:35 -040012#include <linux/security.h>
Shaohua Li98003392013-02-22 16:34:35 -080013#include <linux/swap.h>
Shaohua Li33806f02013-02-22 16:34:37 -080014#include <linux/swapops.h>
Jerome Marchand00619bc2013-11-12 15:08:31 -080015#include <linux/mman.h>
16#include <linux/hugetlb.h>
Al Viro39f1f782014-05-06 14:02:53 -040017#include <linux/vmalloc.h>
Mike Rapoport897ab3e2017-02-24 14:58:22 -080018#include <linux/userfaultfd_k.h>
Alexandre Ghiti649775b2019-09-23 15:38:37 -070019#include <linux/elf.h>
Alexandre Ghiti67f39772019-09-23 15:38:47 -070020#include <linux/elf-randomize.h>
21#include <linux/personality.h>
Alexandre Ghiti649775b2019-09-23 15:38:37 -070022#include <linux/random.h>
Alexandre Ghiti67f39772019-09-23 15:38:47 -070023#include <linux/processor.h>
24#include <linux/sizes.h>
25#include <linux/compat.h>
Jerome Marchand00619bc2013-11-12 15:08:31 -080026
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080027#include <linux/uaccess.h>
Matt Mackall30992c92006-01-08 01:01:43 -080028
Namhyung Kim6038def2011-05-24 17:11:22 -070029#include "internal.h"
Oven5b8c9a02023-06-30 10:57:12 +080030#ifndef __GENKSYMS__
Kuan-Ying Leee13e55ea2021-10-05 17:29:04 +080031#include <trace/hooks/syscall_check.h>
Oven5b8c9a02023-06-30 10:57:12 +080032#include <trace/hooks/mm.h>
Kuan-Ying Leee13e55ea2021-10-05 17:29:04 +080033#endif
Namhyung Kim6038def2011-05-24 17:11:22 -070034
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080035/**
36 * kfree_const - conditionally free memory
37 * @x: pointer to the memory
38 *
39 * Function calls kfree only if @x is not in .rodata section.
40 */
41void kfree_const(const void *x)
42{
43 if (!is_kernel_rodata((unsigned long)x))
44 kfree(x);
45}
46EXPORT_SYMBOL(kfree_const);
47
Matt Mackall30992c92006-01-08 01:01:43 -080048/**
Matt Mackall30992c92006-01-08 01:01:43 -080049 * kstrdup - allocate space for and copy an existing string
Matt Mackall30992c92006-01-08 01:01:43 -080050 * @s: the string to duplicate
51 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
Mike Rapoporta862f682019-03-05 15:48:42 -080052 *
53 * Return: newly allocated copy of @s or %NULL in case of error
Matt Mackall30992c92006-01-08 01:01:43 -080054 */
55char *kstrdup(const char *s, gfp_t gfp)
56{
57 size_t len;
58 char *buf;
59
60 if (!s)
61 return NULL;
62
63 len = strlen(s) + 1;
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -070064 buf = kmalloc_track_caller(len, gfp);
Matt Mackall30992c92006-01-08 01:01:43 -080065 if (buf)
66 memcpy(buf, s, len);
67 return buf;
68}
69EXPORT_SYMBOL(kstrdup);
Davi Arnaut96840aa2006-03-24 03:18:42 -080070
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -070071/**
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080072 * kstrdup_const - conditionally duplicate an existing const string
73 * @s: the string to duplicate
74 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
75 *
Bartosz Golaszewski295a1732020-10-15 20:07:39 -070076 * Note: Strings allocated by kstrdup_const should be freed by kfree_const and
77 * must not be passed to krealloc().
Mike Rapoporta862f682019-03-05 15:48:42 -080078 *
79 * Return: source string if it is in .rodata section otherwise
80 * fallback to kstrdup.
Andrzej Hajdaa4bb1e42015-02-13 14:36:24 -080081 */
82const char *kstrdup_const(const char *s, gfp_t gfp)
83{
84 if (is_kernel_rodata((unsigned long)s))
85 return s;
86
87 return kstrdup(s, gfp);
88}
89EXPORT_SYMBOL(kstrdup_const);
90
91/**
Jeremy Fitzhardinge1e66df32007-07-17 18:37:02 -070092 * kstrndup - allocate space for and copy an existing string
93 * @s: the string to duplicate
94 * @max: read at most @max chars from @s
95 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
David Howellsf3515742017-07-04 17:25:02 +010096 *
97 * Note: Use kmemdup_nul() instead if the size is known exactly.
Mike Rapoporta862f682019-03-05 15:48:42 -080098 *
99 * Return: newly allocated copy of @s or %NULL in case of error
Jeremy Fitzhardinge1e66df32007-07-17 18:37:02 -0700100 */
101char *kstrndup(const char *s, size_t max, gfp_t gfp)
102{
103 size_t len;
104 char *buf;
105
106 if (!s)
107 return NULL;
108
109 len = strnlen(s, max);
110 buf = kmalloc_track_caller(len+1, gfp);
111 if (buf) {
112 memcpy(buf, s, len);
113 buf[len] = '\0';
114 }
115 return buf;
116}
117EXPORT_SYMBOL(kstrndup);
118
119/**
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700120 * kmemdup - duplicate region of memory
121 *
122 * @src: memory region to duplicate
123 * @len: memory region length
124 * @gfp: GFP mask to use
Mike Rapoporta862f682019-03-05 15:48:42 -0800125 *
126 * Return: newly allocated copy of @src or %NULL in case of error
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700127 */
128void *kmemdup(const void *src, size_t len, gfp_t gfp)
129{
130 void *p;
131
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -0700132 p = kmalloc_track_caller(len, gfp);
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -0700133 if (p)
134 memcpy(p, src, len);
135 return p;
136}
137EXPORT_SYMBOL(kmemdup);
138
Christoph Lameteref2ad802007-07-17 04:03:21 -0700139/**
David Howellsf3515742017-07-04 17:25:02 +0100140 * kmemdup_nul - Create a NUL-terminated string from unterminated data
141 * @s: The data to stringify
142 * @len: The size of the data
143 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
Mike Rapoporta862f682019-03-05 15:48:42 -0800144 *
145 * Return: newly allocated copy of @s with NUL-termination or %NULL in
146 * case of error
David Howellsf3515742017-07-04 17:25:02 +0100147 */
148char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
149{
150 char *buf;
151
152 if (!s)
153 return NULL;
154
155 buf = kmalloc_track_caller(len + 1, gfp);
156 if (buf) {
157 memcpy(buf, s, len);
158 buf[len] = '\0';
159 }
160 return buf;
161}
162EXPORT_SYMBOL(kmemdup_nul);
163
164/**
Li Zefan610a77e2009-03-31 15:23:16 -0700165 * memdup_user - duplicate memory region from user space
166 *
167 * @src: source address in user space
168 * @len: number of bytes to copy
169 *
Mike Rapoporta862f682019-03-05 15:48:42 -0800170 * Return: an ERR_PTR() on failure. Result is physically
Al Viro50fd2f22018-01-07 13:06:15 -0500171 * contiguous, to be freed by kfree().
Li Zefan610a77e2009-03-31 15:23:16 -0700172 */
173void *memdup_user(const void __user *src, size_t len)
174{
175 void *p;
176
Daniel Vetter6c8fcc02019-02-20 22:20:42 -0800177 p = kmalloc_track_caller(len, GFP_USER | __GFP_NOWARN);
Li Zefan610a77e2009-03-31 15:23:16 -0700178 if (!p)
179 return ERR_PTR(-ENOMEM);
180
181 if (copy_from_user(p, src, len)) {
182 kfree(p);
183 return ERR_PTR(-EFAULT);
184 }
185
186 return p;
187}
188EXPORT_SYMBOL(memdup_user);
189
Al Viro50fd2f22018-01-07 13:06:15 -0500190/**
191 * vmemdup_user - duplicate memory region from user space
192 *
193 * @src: source address in user space
194 * @len: number of bytes to copy
195 *
Mike Rapoporta862f682019-03-05 15:48:42 -0800196 * Return: an ERR_PTR() on failure. Result may be not
Al Viro50fd2f22018-01-07 13:06:15 -0500197 * physically contiguous. Use kvfree() to free.
198 */
199void *vmemdup_user(const void __user *src, size_t len)
200{
201 void *p;
202
203 p = kvmalloc(len, GFP_USER);
204 if (!p)
205 return ERR_PTR(-ENOMEM);
206
207 if (copy_from_user(p, src, len)) {
208 kvfree(p);
209 return ERR_PTR(-EFAULT);
210 }
211
212 return p;
213}
214EXPORT_SYMBOL(vmemdup_user);
215
Mike Rapoportb86181f2018-08-23 17:00:59 -0700216/**
Davi Arnaut96840aa2006-03-24 03:18:42 -0800217 * strndup_user - duplicate an existing string from user space
Davi Arnaut96840aa2006-03-24 03:18:42 -0800218 * @s: The string to duplicate
219 * @n: Maximum number of bytes to copy, including the trailing NUL.
Mike Rapoporta862f682019-03-05 15:48:42 -0800220 *
Andrew Mortone9145522019-04-05 18:39:34 -0700221 * Return: newly allocated copy of @s or an ERR_PTR() in case of error
Davi Arnaut96840aa2006-03-24 03:18:42 -0800222 */
223char *strndup_user(const char __user *s, long n)
224{
225 char *p;
226 long length;
227
228 length = strnlen_user(s, n);
229
230 if (!length)
231 return ERR_PTR(-EFAULT);
232
233 if (length > n)
234 return ERR_PTR(-EINVAL);
235
Julia Lawall90d74042010-08-09 17:18:26 -0700236 p = memdup_user(s, length);
Davi Arnaut96840aa2006-03-24 03:18:42 -0800237
Julia Lawall90d74042010-08-09 17:18:26 -0700238 if (IS_ERR(p))
239 return p;
Davi Arnaut96840aa2006-03-24 03:18:42 -0800240
241 p[length - 1] = '\0';
242
243 return p;
244}
245EXPORT_SYMBOL(strndup_user);
Andrew Morton16d69262008-07-25 19:44:36 -0700246
Al Viroe9d408e2015-12-24 00:06:05 -0500247/**
248 * memdup_user_nul - duplicate memory region from user space and NUL-terminate
249 *
250 * @src: source address in user space
251 * @len: number of bytes to copy
252 *
Mike Rapoporta862f682019-03-05 15:48:42 -0800253 * Return: an ERR_PTR() on failure.
Al Viroe9d408e2015-12-24 00:06:05 -0500254 */
255void *memdup_user_nul(const void __user *src, size_t len)
256{
257 char *p;
258
259 /*
260 * Always use GFP_KERNEL, since copy_from_user() can sleep and
261 * cause pagefault, which makes it pointless to use GFP_NOFS
262 * or GFP_ATOMIC.
263 */
264 p = kmalloc_track_caller(len + 1, GFP_KERNEL);
265 if (!p)
266 return ERR_PTR(-ENOMEM);
267
268 if (copy_from_user(p, src, len)) {
269 kfree(p);
270 return ERR_PTR(-EFAULT);
271 }
272 p[len] = '\0';
273
274 return p;
275}
276EXPORT_SYMBOL(memdup_user_nul);
277
Namhyung Kim6038def2011-05-24 17:11:22 -0700278void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
Wei Yangaba6dfb2019-11-30 17:50:53 -0800279 struct vm_area_struct *prev)
Namhyung Kim6038def2011-05-24 17:11:22 -0700280{
281 struct vm_area_struct *next;
282
283 vma->vm_prev = prev;
284 if (prev) {
285 next = prev->vm_next;
286 prev->vm_next = vma;
287 } else {
Wei Yangaba6dfb2019-11-30 17:50:53 -0800288 next = mm->mmap;
Namhyung Kim6038def2011-05-24 17:11:22 -0700289 mm->mmap = vma;
Namhyung Kim6038def2011-05-24 17:11:22 -0700290 }
291 vma->vm_next = next;
292 if (next)
293 next->vm_prev = vma;
294}
295
Wei Yang1b9fc5b22019-11-30 17:50:49 -0800296void __vma_unlink_list(struct mm_struct *mm, struct vm_area_struct *vma)
297{
298 struct vm_area_struct *prev, *next;
299
300 next = vma->vm_next;
301 prev = vma->vm_prev;
302 if (prev)
303 prev->vm_next = next;
304 else
305 mm->mmap = next;
306 if (next)
307 next->vm_prev = prev;
308}
309
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700310/* Check if the vma is being used as a stack by this task */
Andy Lutomirskid17af502016-09-30 10:58:58 -0700311int vma_is_stack_for_current(struct vm_area_struct *vma)
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700312{
Andy Lutomirskid17af502016-09-30 10:58:58 -0700313 struct task_struct * __maybe_unused t = current;
314
Siddhesh Poyarekarb7643752012-03-21 16:34:04 -0700315 return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
316}
317
Christian König295992f2020-09-14 15:09:33 +0200318/*
319 * Change backing file, only valid to use during initial VMA setup.
320 */
321void vma_set_file(struct vm_area_struct *vma, struct file *file)
322{
323 /* Changing an anonymous vma with this is illegal */
324 get_file(file);
325 swap(vma->vm_file, file);
326 fput(file);
327}
328EXPORT_SYMBOL(vma_set_file);
329
Alexandre Ghiti649775b2019-09-23 15:38:37 -0700330#ifndef STACK_RND_MASK
331#define STACK_RND_MASK (0x7ff >> (PAGE_SHIFT - 12)) /* 8MB of VA */
332#endif
333
334unsigned long randomize_stack_top(unsigned long stack_top)
335{
336 unsigned long random_variable = 0;
337
338 if (current->flags & PF_RANDOMIZE) {
339 random_variable = get_random_long();
340 random_variable &= STACK_RND_MASK;
341 random_variable <<= PAGE_SHIFT;
342 }
343#ifdef CONFIG_STACK_GROWSUP
344 return PAGE_ALIGN(stack_top) + random_variable;
345#else
346 return PAGE_ALIGN(stack_top) - random_variable;
347#endif
348}
349
Jason A. Donenfeld64cb7f02022-05-14 13:59:30 +0200350/**
351 * randomize_page - Generate a random, page aligned address
352 * @start: The smallest acceptable address the caller will take.
353 * @range: The size of the area, starting at @start, within which the
354 * random address must fall.
355 *
356 * If @start + @range would overflow, @range is capped.
357 *
358 * NOTE: Historical use of randomize_range, which this replaces, presumed that
359 * @start was already page aligned. We now align it regardless.
360 *
361 * Return: A page aligned address within [start, start + range). On error,
362 * @start is returned.
363 */
364unsigned long randomize_page(unsigned long start, unsigned long range)
365{
366 if (!PAGE_ALIGNED(start)) {
367 range -= PAGE_ALIGN(start) - start;
368 start = PAGE_ALIGN(start);
369 }
370
371 if (start > ULONG_MAX - range)
372 range = ULONG_MAX - start;
373
374 range >>= PAGE_SHIFT;
375
376 if (range == 0)
377 return start;
378
379 return start + (get_random_long() % range << PAGE_SHIFT);
380}
381
Alexandre Ghiti67f39772019-09-23 15:38:47 -0700382#ifdef CONFIG_ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT
Alexandre Ghitie7142bf2019-09-23 15:38:50 -0700383unsigned long arch_randomize_brk(struct mm_struct *mm)
384{
385 /* Is the current task 32bit ? */
386 if (!IS_ENABLED(CONFIG_64BIT) || is_compat_task())
387 return randomize_page(mm->brk, SZ_32M);
388
389 return randomize_page(mm->brk, SZ_1G);
390}
391
Alexandre Ghiti67f39772019-09-23 15:38:47 -0700392unsigned long arch_mmap_rnd(void)
393{
394 unsigned long rnd;
395
396#ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
397 if (is_compat_task())
398 rnd = get_random_long() & ((1UL << mmap_rnd_compat_bits) - 1);
399 else
400#endif /* CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS */
401 rnd = get_random_long() & ((1UL << mmap_rnd_bits) - 1);
402
403 return rnd << PAGE_SHIFT;
404}
Alexandre Ghiti67f39772019-09-23 15:38:47 -0700405
406static int mmap_is_legacy(struct rlimit *rlim_stack)
407{
408 if (current->personality & ADDR_COMPAT_LAYOUT)
409 return 1;
410
411 if (rlim_stack->rlim_cur == RLIM_INFINITY)
412 return 1;
413
414 return sysctl_legacy_va_layout;
415}
416
417/*
418 * Leave enough space between the mmap area and the stack to honour ulimit in
419 * the face of randomisation.
420 */
421#define MIN_GAP (SZ_128M)
422#define MAX_GAP (STACK_TOP / 6 * 5)
423
424static unsigned long mmap_base(unsigned long rnd, struct rlimit *rlim_stack)
425{
426 unsigned long gap = rlim_stack->rlim_cur;
427 unsigned long pad = stack_guard_gap;
428
429 /* Account for stack randomization if necessary */
430 if (current->flags & PF_RANDOMIZE)
431 pad += (STACK_RND_MASK << PAGE_SHIFT);
432
433 /* Values close to RLIM_INFINITY can overflow. */
434 if (gap + pad > gap)
435 gap += pad;
436
437 if (gap < MIN_GAP)
438 gap = MIN_GAP;
439 else if (gap > MAX_GAP)
440 gap = MAX_GAP;
441
442 return PAGE_ALIGN(STACK_TOP - gap - rnd);
443}
444
445void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
446{
447 unsigned long random_factor = 0UL;
448
449 if (current->flags & PF_RANDOMIZE)
450 random_factor = arch_mmap_rnd();
451
452 if (mmap_is_legacy(rlim_stack)) {
453 mm->mmap_base = TASK_UNMAPPED_BASE + random_factor;
454 mm->get_unmapped_area = arch_get_unmapped_area;
455 } else {
456 mm->mmap_base = mmap_base(random_factor, rlim_stack);
457 mm->get_unmapped_area = arch_get_unmapped_area_topdown;
458 }
459}
460#elif defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
Kees Cook8f2af152018-04-10 16:34:53 -0700461void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
Andrew Morton16d69262008-07-25 19:44:36 -0700462{
463 mm->mmap_base = TASK_UNMAPPED_BASE;
464 mm->get_unmapped_area = arch_get_unmapped_area;
Andrew Morton16d69262008-07-25 19:44:36 -0700465}
466#endif
Rusty Russell912985d2008-08-12 17:52:52 -0500467
Daniel Jordan79eb5972019-07-16 16:30:54 -0700468/**
469 * __account_locked_vm - account locked pages to an mm's locked_vm
470 * @mm: mm to account against
471 * @pages: number of pages to account
472 * @inc: %true if @pages should be considered positive, %false if not
473 * @task: task used to check RLIMIT_MEMLOCK
474 * @bypass_rlim: %true if checking RLIMIT_MEMLOCK should be skipped
475 *
476 * Assumes @task and @mm are valid (i.e. at least one reference on each), and
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -0700477 * that mmap_lock is held as writer.
Daniel Jordan79eb5972019-07-16 16:30:54 -0700478 *
479 * Return:
480 * * 0 on success
481 * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded.
482 */
483int __account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc,
484 struct task_struct *task, bool bypass_rlim)
485{
486 unsigned long locked_vm, limit;
487 int ret = 0;
488
Michel Lespinasse42fc5412020-06-08 21:33:44 -0700489 mmap_assert_write_locked(mm);
Daniel Jordan79eb5972019-07-16 16:30:54 -0700490
491 locked_vm = mm->locked_vm;
492 if (inc) {
493 if (!bypass_rlim) {
494 limit = task_rlimit(task, RLIMIT_MEMLOCK) >> PAGE_SHIFT;
495 if (locked_vm + pages > limit)
496 ret = -ENOMEM;
497 }
498 if (!ret)
499 mm->locked_vm = locked_vm + pages;
500 } else {
501 WARN_ON_ONCE(pages > locked_vm);
502 mm->locked_vm = locked_vm - pages;
503 }
504
505 pr_debug("%s: [%d] caller %ps %c%lu %lu/%lu%s\n", __func__, task->pid,
506 (void *)_RET_IP_, (inc) ? '+' : '-', pages << PAGE_SHIFT,
507 locked_vm << PAGE_SHIFT, task_rlimit(task, RLIMIT_MEMLOCK),
508 ret ? " - exceeded" : "");
509
510 return ret;
511}
512EXPORT_SYMBOL_GPL(__account_locked_vm);
513
514/**
515 * account_locked_vm - account locked pages to an mm's locked_vm
516 * @mm: mm to account against, may be NULL
517 * @pages: number of pages to account
518 * @inc: %true if @pages should be considered positive, %false if not
519 *
520 * Assumes a non-NULL @mm is valid (i.e. at least one reference on it).
521 *
522 * Return:
523 * * 0 on success, or if mm is NULL
524 * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded.
525 */
526int account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc)
527{
528 int ret;
529
530 if (pages == 0 || !mm)
531 return 0;
532
Michel Lespinassed8ed45c2020-06-08 21:33:25 -0700533 mmap_write_lock(mm);
Daniel Jordan79eb5972019-07-16 16:30:54 -0700534 ret = __account_locked_vm(mm, pages, inc, current,
535 capable(CAP_IPC_LOCK));
Michel Lespinassed8ed45c2020-06-08 21:33:25 -0700536 mmap_write_unlock(mm);
Daniel Jordan79eb5972019-07-16 16:30:54 -0700537
538 return ret;
539}
540EXPORT_SYMBOL_GPL(account_locked_vm);
541
Al Viroeb36c582012-05-30 20:17:35 -0400542unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
543 unsigned long len, unsigned long prot,
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700544 unsigned long flag, unsigned long pgoff)
Al Viroeb36c582012-05-30 20:17:35 -0400545{
546 unsigned long ret;
547 struct mm_struct *mm = current->mm;
Michel Lespinasse41badc12013-02-22 16:32:47 -0800548 unsigned long populate;
Mike Rapoport897ab3e2017-02-24 14:58:22 -0800549 LIST_HEAD(uf);
Al Viroeb36c582012-05-30 20:17:35 -0400550
551 ret = security_mmap_file(file, prot, flag);
552 if (!ret) {
Michel Lespinassed8ed45c2020-06-08 21:33:25 -0700553 if (mmap_write_lock_killable(mm))
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700554 return -EINTR;
Peter Collingbourne45e55302020-08-06 23:23:37 -0700555 ret = do_mmap(file, addr, len, prot, flag, pgoff, &populate,
556 &uf);
Michel Lespinassed8ed45c2020-06-08 21:33:25 -0700557 mmap_write_unlock(mm);
Mike Rapoport897ab3e2017-02-24 14:58:22 -0800558 userfaultfd_unmap_complete(mm, &uf);
Michel Lespinasse41badc12013-02-22 16:32:47 -0800559 if (populate)
560 mm_populate(ret, populate);
Al Viroeb36c582012-05-30 20:17:35 -0400561 }
Kuan-Ying Leee13e55ea2021-10-05 17:29:04 +0800562 trace_android_vh_check_mmap_file(file, prot, flag, ret);
Al Viroeb36c582012-05-30 20:17:35 -0400563 return ret;
564}
565
566unsigned long vm_mmap(struct file *file, unsigned long addr,
567 unsigned long len, unsigned long prot,
568 unsigned long flag, unsigned long offset)
569{
570 if (unlikely(offset + PAGE_ALIGN(len) < offset))
571 return -EINVAL;
Alexander Kuleshovea53cde2015-11-05 18:46:46 -0800572 if (unlikely(offset_in_page(offset)))
Al Viroeb36c582012-05-30 20:17:35 -0400573 return -EINVAL;
574
Michal Hocko9fbeb5a2016-05-23 16:25:30 -0700575 return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
Al Viroeb36c582012-05-30 20:17:35 -0400576}
577EXPORT_SYMBOL(vm_mmap);
578
Michal Hockoa7c3e902017-05-08 15:57:09 -0700579/**
580 * kvmalloc_node - attempt to allocate physically contiguous memory, but upon
581 * failure, fall back to non-contiguous (vmalloc) allocation.
582 * @size: size of the request.
583 * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
584 * @node: numa node to allocate from
585 *
586 * Uses kmalloc to get the memory but if the allocation fails then falls back
587 * to the vmalloc allocator. Use kvfree for freeing the memory.
588 *
Michal Hockocc965a22017-07-12 14:36:52 -0700589 * Reclaim modifiers - __GFP_NORETRY and __GFP_NOFAIL are not supported.
590 * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
591 * preferable to the vmalloc fallback, due to visible performance drawbacks.
Michal Hockoa7c3e902017-05-08 15:57:09 -0700592 *
Michal Hockoce91f6e2018-06-07 17:09:40 -0700593 * Please note that any use of gfp flags outside of GFP_KERNEL is careful to not
594 * fall back to vmalloc.
Mike Rapoporta862f682019-03-05 15:48:42 -0800595 *
596 * Return: pointer to the allocated memory of %NULL in case of failure
Michal Hockoa7c3e902017-05-08 15:57:09 -0700597 */
598void *kvmalloc_node(size_t size, gfp_t flags, int node)
599{
600 gfp_t kmalloc_flags = flags;
601 void *ret;
Oven5b8c9a02023-06-30 10:57:12 +0800602 bool use_vmalloc = false;
Michal Hockoa7c3e902017-05-08 15:57:09 -0700603
604 /*
605 * vmalloc uses GFP_KERNEL for some internal allocations (e.g page tables)
606 * so the given set of flags has to be compatible.
607 */
Michal Hockoce91f6e2018-06-07 17:09:40 -0700608 if ((flags & GFP_KERNEL) != GFP_KERNEL)
609 return kmalloc_node(size, flags, node);
Michal Hockoa7c3e902017-05-08 15:57:09 -0700610
Oven5b8c9a02023-06-30 10:57:12 +0800611 trace_android_vh_kvmalloc_node_use_vmalloc(size, &kmalloc_flags, &use_vmalloc);
612 if (use_vmalloc)
613 goto use_vmalloc_node;
Michal Hockoa7c3e902017-05-08 15:57:09 -0700614 /*
Michal Hocko4f4f2ba2017-06-02 14:46:19 -0700615 * We want to attempt a large physically contiguous block first because
616 * it is less likely to fragment multiple larger blocks and therefore
617 * contribute to a long term fragmentation less than vmalloc fallback.
618 * However make sure that larger requests are not too disruptive - no
619 * OOM killer and no allocation failure warnings as we have a fallback.
Michal Hockoa7c3e902017-05-08 15:57:09 -0700620 */
Michal Hocko6c5ab652017-05-08 15:57:15 -0700621 if (size > PAGE_SIZE) {
622 kmalloc_flags |= __GFP_NOWARN;
623
Michal Hockocc965a22017-07-12 14:36:52 -0700624 if (!(kmalloc_flags & __GFP_RETRY_MAYFAIL))
Michal Hocko6c5ab652017-05-08 15:57:15 -0700625 kmalloc_flags |= __GFP_NORETRY;
626 }
Michal Hockoa7c3e902017-05-08 15:57:09 -0700627
628 ret = kmalloc_node(size, kmalloc_flags, node);
629
630 /*
631 * It doesn't really make sense to fallback to vmalloc for sub page
632 * requests
633 */
634 if (ret || size <= PAGE_SIZE)
635 return ret;
636
Linus Torvalds76618092021-07-14 09:45:49 -0700637 /* Don't even allow crazy sizes */
Daniel Borkmann261eff12022-03-04 15:26:32 +0100638 if (unlikely(size > INT_MAX)) {
639 WARN_ON_ONCE(!(flags & __GFP_NOWARN));
Linus Torvalds76618092021-07-14 09:45:49 -0700640 return NULL;
Daniel Borkmann261eff12022-03-04 15:26:32 +0100641 }
Linus Torvalds76618092021-07-14 09:45:49 -0700642
Oven5b8c9a02023-06-30 10:57:12 +0800643use_vmalloc_node:
Christoph Hellwig2b905942020-06-01 21:51:53 -0700644 return __vmalloc_node(size, 1, flags, node,
Michal Hocko8594a212017-05-12 15:46:41 -0700645 __builtin_return_address(0));
Michal Hockoa7c3e902017-05-08 15:57:09 -0700646}
647EXPORT_SYMBOL(kvmalloc_node);
648
Mike Rapoportff4dc772018-08-23 17:01:02 -0700649/**
Andrew Morton04b8e942018-09-04 15:45:55 -0700650 * kvfree() - Free memory.
651 * @addr: Pointer to allocated memory.
Mike Rapoportff4dc772018-08-23 17:01:02 -0700652 *
Andrew Morton04b8e942018-09-04 15:45:55 -0700653 * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
654 * It is slightly more efficient to use kfree() or vfree() if you are certain
655 * that you know which one to use.
656 *
Andrey Ryabinin52414d32018-10-26 15:07:00 -0700657 * Context: Either preemptible task context or not-NMI interrupt.
Mike Rapoportff4dc772018-08-23 17:01:02 -0700658 */
Al Viro39f1f782014-05-06 14:02:53 -0400659void kvfree(const void *addr)
660{
661 if (is_vmalloc_addr(addr))
662 vfree(addr);
663 else
664 kfree(addr);
665}
666EXPORT_SYMBOL(kvfree);
667
Waiman Longd4eaa282020-06-04 16:48:21 -0700668/**
669 * kvfree_sensitive - Free a data object containing sensitive information.
670 * @addr: address of the data object to be freed.
671 * @len: length of the data object.
672 *
673 * Use the special memzero_explicit() function to clear the content of a
674 * kvmalloc'ed object containing sensitive data to make sure that the
675 * compiler won't optimize out the data clearing.
676 */
677void kvfree_sensitive(const void *addr, size_t len)
678{
679 if (likely(!ZERO_OR_NULL_PTR(addr))) {
680 memzero_explicit((void *)addr, len);
681 kvfree(addr);
682 }
683}
684EXPORT_SYMBOL(kvfree_sensitive);
685
Dave Chinnerde2860f2021-08-09 10:10:00 -0700686void *kvrealloc(const void *p, size_t oldsize, size_t newsize, gfp_t flags)
687{
688 void *newp;
689
690 if (oldsize >= newsize)
691 return (void *)p;
692 newp = kvmalloc(newsize, flags);
693 if (!newp)
694 return NULL;
695 memcpy(newp, p, oldsize);
696 kvfree(p);
697 return newp;
698}
699EXPORT_SYMBOL(kvrealloc);
700
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700701static inline void *__page_rmapping(struct page *page)
702{
703 unsigned long mapping;
704
705 mapping = (unsigned long)page->mapping;
706 mapping &= ~PAGE_MAPPING_FLAGS;
707
708 return (void *)mapping;
709}
710
Paolo Bonzinic33904f2022-03-08 04:47:22 -0500711/**
712 * __vmalloc_array - allocate memory for a virtually contiguous array.
713 * @n: number of elements.
714 * @size: element size.
715 * @flags: the type of memory to allocate (see kmalloc).
716 */
717void *__vmalloc_array(size_t n, size_t size, gfp_t flags)
718{
719 size_t bytes;
720
721 if (unlikely(check_mul_overflow(n, size, &bytes)))
722 return NULL;
723 return __vmalloc(bytes, flags);
724}
725EXPORT_SYMBOL(__vmalloc_array);
726
727/**
728 * vmalloc_array - allocate memory for a virtually contiguous array.
729 * @n: number of elements.
730 * @size: element size.
731 */
732void *vmalloc_array(size_t n, size_t size)
733{
734 return __vmalloc_array(n, size, GFP_KERNEL);
735}
736EXPORT_SYMBOL(vmalloc_array);
737
738/**
739 * __vcalloc - allocate and zero memory for a virtually contiguous array.
740 * @n: number of elements.
741 * @size: element size.
742 * @flags: the type of memory to allocate (see kmalloc).
743 */
744void *__vcalloc(size_t n, size_t size, gfp_t flags)
745{
746 return __vmalloc_array(n, size, flags | __GFP_ZERO);
747}
748EXPORT_SYMBOL(__vcalloc);
749
750/**
751 * vcalloc - allocate and zero memory for a virtually contiguous array.
752 * @n: number of elements.
753 * @size: element size.
754 */
755void *vcalloc(size_t n, size_t size)
756{
757 return __vmalloc_array(n, size, GFP_KERNEL | __GFP_ZERO);
758}
759EXPORT_SYMBOL(vcalloc);
760
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700761/* Neutral page->mapping pointer to address_space or anon_vma or other */
762void *page_rmapping(struct page *page)
763{
764 page = compound_head(page);
765 return __page_rmapping(page);
766}
767
Andrew Morton1aa8aea2016-05-19 17:12:00 -0700768/*
769 * Return true if this page is mapped into pagetables.
770 * For compound page it returns true if any subpage of compound page is mapped.
771 */
772bool page_mapped(struct page *page)
773{
774 int i;
775
776 if (likely(!PageCompound(page)))
777 return atomic_read(&page->_mapcount) >= 0;
778 page = compound_head(page);
779 if (atomic_read(compound_mapcount_ptr(page)) >= 0)
780 return true;
781 if (PageHuge(page))
782 return false;
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -0700783 for (i = 0; i < compound_nr(page); i++) {
Andrew Morton1aa8aea2016-05-19 17:12:00 -0700784 if (atomic_read(&page[i]._mapcount) >= 0)
785 return true;
786 }
787 return false;
788}
789EXPORT_SYMBOL(page_mapped);
790
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700791struct anon_vma *page_anon_vma(struct page *page)
792{
793 unsigned long mapping;
794
795 page = compound_head(page);
796 mapping = (unsigned long)page->mapping;
797 if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
798 return NULL;
799 return __page_rmapping(page);
800}
801
Shaohua Li98003392013-02-22 16:34:35 -0800802struct address_space *page_mapping(struct page *page)
803{
Kirill A. Shutemov1c290f62016-01-15 16:52:07 -0800804 struct address_space *mapping;
805
806 page = compound_head(page);
Shaohua Li98003392013-02-22 16:34:35 -0800807
Mikulas Patocka03e5ac22014-01-14 17:56:40 -0800808 /* This happens if someone calls flush_dcache_page on slab page */
809 if (unlikely(PageSlab(page)))
810 return NULL;
811
Shaohua Li33806f02013-02-22 16:34:37 -0800812 if (unlikely(PageSwapCache(page))) {
813 swp_entry_t entry;
814
815 entry.val = page_private(page);
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700816 return swap_address_space(entry);
817 }
818
Kirill A. Shutemov1c290f62016-01-15 16:52:07 -0800819 mapping = page->mapping;
Minchan Kimbda807d2016-07-26 15:23:05 -0700820 if ((unsigned long)mapping & PAGE_MAPPING_ANON)
Kirill A. Shutemove39155e2015-04-15 16:14:53 -0700821 return NULL;
Minchan Kimbda807d2016-07-26 15:23:05 -0700822
823 return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
Shaohua Li98003392013-02-22 16:34:35 -0800824}
Minchan Kimbda807d2016-07-26 15:23:05 -0700825EXPORT_SYMBOL(page_mapping);
Shaohua Li98003392013-02-22 16:34:35 -0800826
Kirill A. Shutemovb20ce5e2016-01-15 16:54:37 -0800827/* Slow path of page_mapcount() for compound pages */
828int __page_mapcount(struct page *page)
829{
830 int ret;
831
832 ret = atomic_read(&page->_mapcount) + 1;
Kirill A. Shutemovdd78fed2016-07-26 15:25:26 -0700833 /*
834 * For file THP page->_mapcount contains total number of mapping
835 * of the page: no need to look into compound_mapcount.
836 */
837 if (!PageAnon(page) && !PageHuge(page))
838 return ret;
Kirill A. Shutemovb20ce5e2016-01-15 16:54:37 -0800839 page = compound_head(page);
840 ret += atomic_read(compound_mapcount_ptr(page)) + 1;
841 if (PageDoubleMap(page))
842 ret--;
843 return ret;
844}
845EXPORT_SYMBOL_GPL(__page_mapcount);
846
Matthew Wilcox (Oracle)79789db2021-07-12 16:32:07 +0100847void copy_huge_page(struct page *dst, struct page *src)
848{
849 unsigned i, nr = compound_nr(src);
850
851 for (i = 0; i < nr; i++) {
852 cond_resched();
853 copy_highpage(nth_page(dst, i), nth_page(src, i));
854 }
855}
856
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700857int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
858int sysctl_overcommit_ratio __read_mostly = 50;
859unsigned long sysctl_overcommit_kbytes __read_mostly;
860int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
861unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
862unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
863
Christoph Hellwig32927392020-04-24 08:43:38 +0200864int overcommit_ratio_handler(struct ctl_table *table, int write, void *buffer,
865 size_t *lenp, loff_t *ppos)
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800866{
867 int ret;
868
869 ret = proc_dointvec(table, write, buffer, lenp, ppos);
870 if (ret == 0 && write)
871 sysctl_overcommit_kbytes = 0;
872 return ret;
873}
874
Feng Tang56f35472020-08-06 23:23:15 -0700875static void sync_overcommit_as(struct work_struct *dummy)
876{
877 percpu_counter_sync(&vm_committed_as);
878}
879
880int overcommit_policy_handler(struct ctl_table *table, int write, void *buffer,
881 size_t *lenp, loff_t *ppos)
882{
883 struct ctl_table t;
Chen Junbcbda812021-09-24 15:44:06 -0700884 int new_policy = -1;
Feng Tang56f35472020-08-06 23:23:15 -0700885 int ret;
886
887 /*
888 * The deviation of sync_overcommit_as could be big with loose policy
889 * like OVERCOMMIT_ALWAYS/OVERCOMMIT_GUESS. When changing policy to
890 * strict OVERCOMMIT_NEVER, we need to reduce the deviation to comply
Bhaskar Chowdhury31454982021-05-04 18:38:35 -0700891 * with the strict "NEVER", and to avoid possible race condition (even
Feng Tang56f35472020-08-06 23:23:15 -0700892 * though user usually won't too frequently do the switching to policy
893 * OVERCOMMIT_NEVER), the switch is done in the following order:
894 * 1. changing the batch
895 * 2. sync percpu count on each CPU
896 * 3. switch the policy
897 */
898 if (write) {
899 t = *table;
900 t.data = &new_policy;
901 ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
Chen Junbcbda812021-09-24 15:44:06 -0700902 if (ret || new_policy == -1)
Feng Tang56f35472020-08-06 23:23:15 -0700903 return ret;
904
905 mm_compute_batch(new_policy);
906 if (new_policy == OVERCOMMIT_NEVER)
907 schedule_on_each_cpu(sync_overcommit_as);
908 sysctl_overcommit_memory = new_policy;
909 } else {
910 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
911 }
912
913 return ret;
914}
915
Christoph Hellwig32927392020-04-24 08:43:38 +0200916int overcommit_kbytes_handler(struct ctl_table *table, int write, void *buffer,
917 size_t *lenp, loff_t *ppos)
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800918{
919 int ret;
920
921 ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
922 if (ret == 0 && write)
923 sysctl_overcommit_ratio = 0;
924 return ret;
925}
926
Jerome Marchand00619bc2013-11-12 15:08:31 -0800927/*
928 * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
929 */
930unsigned long vm_commit_limit(void)
931{
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800932 unsigned long allowed;
933
934 if (sysctl_overcommit_kbytes)
935 allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
936 else
Arun KSca79b0c2018-12-28 00:34:29 -0800937 allowed = ((totalram_pages() - hugetlb_total_pages())
Jerome Marchand49f0ce52014-01-21 15:49:14 -0800938 * sysctl_overcommit_ratio / 100);
939 allowed += total_swap_pages;
940
941 return allowed;
Jerome Marchand00619bc2013-11-12 15:08:31 -0800942}
943
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700944/*
945 * Make sure vm_committed_as in one cacheline and not cacheline shared with
946 * other variables. It can be updated by several CPUs frequently.
947 */
948struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
949
950/*
951 * The global memory commitment made in the system can be a metric
952 * that can be used to drive ballooning decisions when Linux is hosted
953 * as a guest. On Hyper-V, the host implements a policy engine for dynamically
954 * balancing memory across competing virtual machines that are hosted.
955 * Several metrics drive this policy engine including the guest reported
956 * memory commitment.
Feng Tang4e2ee512020-08-06 23:23:07 -0700957 *
958 * The time cost of this is very low for small platforms, and for big
959 * platform like a 2S/36C/72T Skylake server, in worst case where
960 * vm_committed_as's spinlock is under severe contention, the time cost
961 * could be about 30~40 microseconds.
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700962 */
963unsigned long vm_memory_committed(void)
964{
Feng Tang4e2ee512020-08-06 23:23:07 -0700965 return percpu_counter_sum_positive(&vm_committed_as);
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700966}
967EXPORT_SYMBOL_GPL(vm_memory_committed);
968
969/*
970 * Check that a process has enough memory to allocate a new virtual
971 * mapping. 0 means there is enough memory for the allocation to
972 * succeed and -ENOMEM implies there is not.
973 *
974 * We currently support three overcommit policies, which are set via the
Mike Rapoportad56b732018-03-21 21:22:47 +0200975 * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting.rst
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700976 *
977 * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
978 * Additional code 2002 Jul 20 by Robert Love.
979 *
980 * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
981 *
982 * Note this is a helper function intended to be used by LSMs which
983 * wish to use this logic.
984 */
985int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
986{
Johannes Weiner8c7829b2019-05-13 17:21:50 -0700987 long allowed;
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700988
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700989 vm_acct_memory(pages);
990
991 /*
992 * Sometimes we want to use more memory than we have
993 */
994 if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
995 return 0;
996
997 if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
Johannes Weiner8c7829b2019-05-13 17:21:50 -0700998 if (pages > totalram_pages() + total_swap_pages)
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -0700999 goto error;
Johannes Weiner8c7829b2019-05-13 17:21:50 -07001000 return 0;
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -07001001 }
1002
1003 allowed = vm_commit_limit();
1004 /*
1005 * Reserve some for root
1006 */
1007 if (!cap_sys_admin)
1008 allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
1009
1010 /*
1011 * Don't let a single process grow so big a user can't recover
1012 */
1013 if (mm) {
Johannes Weiner8c7829b2019-05-13 17:21:50 -07001014 long reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
1015
Andrey Ryabinin39a1aa82016-03-17 14:18:50 -07001016 allowed -= min_t(long, mm->total_vm / 32, reserve);
1017 }
1018
1019 if (percpu_counter_read_positive(&vm_committed_as) < allowed)
1020 return 0;
1021error:
1022 vm_unacct_memory(pages);
1023
1024 return -ENOMEM;
1025}
1026
William Robertsa9090252014-02-11 10:11:59 -08001027/**
1028 * get_cmdline() - copy the cmdline value to a buffer.
1029 * @task: the task whose cmdline value to copy.
1030 * @buffer: the buffer to copy to.
1031 * @buflen: the length of the buffer. Larger cmdline values are truncated
1032 * to this length.
Mike Rapoporta862f682019-03-05 15:48:42 -08001033 *
1034 * Return: the size of the cmdline field copied. Note that the copy does
William Robertsa9090252014-02-11 10:11:59 -08001035 * not guarantee an ending NULL byte.
1036 */
1037int get_cmdline(struct task_struct *task, char *buffer, int buflen)
1038{
1039 int res = 0;
1040 unsigned int len;
1041 struct mm_struct *mm = get_task_mm(task);
Mateusz Guzika3b609e2016-01-20 15:01:05 -08001042 unsigned long arg_start, arg_end, env_start, env_end;
William Robertsa9090252014-02-11 10:11:59 -08001043 if (!mm)
1044 goto out;
1045 if (!mm->arg_end)
1046 goto out_mm; /* Shh! No looking before we're done */
1047
Michal Koutnýbc814262019-05-31 22:30:19 -07001048 spin_lock(&mm->arg_lock);
Mateusz Guzika3b609e2016-01-20 15:01:05 -08001049 arg_start = mm->arg_start;
1050 arg_end = mm->arg_end;
1051 env_start = mm->env_start;
1052 env_end = mm->env_end;
Michal Koutnýbc814262019-05-31 22:30:19 -07001053 spin_unlock(&mm->arg_lock);
Mateusz Guzika3b609e2016-01-20 15:01:05 -08001054
1055 len = arg_end - arg_start;
William Robertsa9090252014-02-11 10:11:59 -08001056
1057 if (len > buflen)
1058 len = buflen;
1059
Lorenzo Stoakesf307ab62016-10-13 01:20:20 +01001060 res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
William Robertsa9090252014-02-11 10:11:59 -08001061
1062 /*
1063 * If the nul at the end of args has been overwritten, then
1064 * assume application is using setproctitle(3).
1065 */
1066 if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
1067 len = strnlen(buffer, res);
1068 if (len < res) {
1069 res = len;
1070 } else {
Mateusz Guzika3b609e2016-01-20 15:01:05 -08001071 len = env_end - env_start;
William Robertsa9090252014-02-11 10:11:59 -08001072 if (len > buflen - res)
1073 len = buflen - res;
Mateusz Guzika3b609e2016-01-20 15:01:05 -08001074 res += access_process_vm(task, env_start,
Lorenzo Stoakesf307ab62016-10-13 01:20:20 +01001075 buffer+res, len,
1076 FOLL_FORCE);
William Robertsa9090252014-02-11 10:11:59 -08001077 res = strnlen(buffer, res);
1078 }
1079 }
1080out_mm:
1081 mmput(mm);
1082out:
1083 return res;
1084}
Song Liu010c1642019-09-23 15:38:19 -07001085
Catalin Marinas4d1a8a22019-11-27 09:53:44 +00001086int __weak memcmp_pages(struct page *page1, struct page *page2)
Song Liu010c1642019-09-23 15:38:19 -07001087{
1088 char *addr1, *addr2;
1089 int ret;
1090
1091 addr1 = kmap_atomic(page1);
1092 addr2 = kmap_atomic(page2);
1093 ret = memcmp(addr1, addr2, PAGE_SIZE);
1094 kunmap_atomic(addr2);
1095 kunmap_atomic(addr1);
1096 return ret;
1097}
Paul E. McKenney8e7f37f2020-12-07 17:41:02 -08001098
Paul E. McKenney5bb1bb32021-01-07 13:46:11 -08001099#ifdef CONFIG_PRINTK
Paul E. McKenney8e7f37f2020-12-07 17:41:02 -08001100/**
1101 * mem_dump_obj - Print available provenance information
1102 * @object: object for which to find provenance information.
1103 *
1104 * This function uses pr_cont(), so that the caller is expected to have
1105 * printed out whatever preamble is appropriate. The provenance information
1106 * depends on the type of object and on how much debugging is enabled.
1107 * For example, for a slab-cache object, the slab name is printed, and,
1108 * if available, the return address and stack trace from the allocation
Maninder Singhe548eaa2021-03-16 16:07:11 +05301109 * and last free path of that object.
Paul E. McKenney8e7f37f2020-12-07 17:41:02 -08001110 */
1111void mem_dump_obj(void *object)
1112{
Joe Perches25217812021-05-04 18:38:32 -07001113 const char *type;
1114
Paul E. McKenney98f18082020-12-08 16:13:57 -08001115 if (kmem_valid_obj(object)) {
1116 kmem_dump_obj(object);
1117 return;
1118 }
Joe Perches25217812021-05-04 18:38:32 -07001119
Paul E. McKenney98f18082020-12-08 16:13:57 -08001120 if (vmalloc_dump_obj(object))
1121 return;
Joe Perches25217812021-05-04 18:38:32 -07001122
Zqiang0a22f9c2023-09-04 18:08:05 +00001123 if (is_vmalloc_addr(object))
1124 type = "vmalloc memory";
1125 else if (virt_addr_valid(object))
Joe Perches25217812021-05-04 18:38:32 -07001126 type = "non-slab/vmalloc memory";
1127 else if (object == NULL)
1128 type = "NULL pointer";
1129 else if (object == ZERO_SIZE_PTR)
1130 type = "zero-size pointer";
1131 else
1132 type = "non-paged memory";
1133
1134 pr_cont(" %s\n", type);
Paul E. McKenney8e7f37f2020-12-07 17:41:02 -08001135}
Paul E. McKenney0d3dd2c2020-12-07 21:23:36 -08001136EXPORT_SYMBOL_GPL(mem_dump_obj);
Paul E. McKenney5bb1bb32021-01-07 13:46:11 -08001137#endif
David Hildenbrand82840452021-06-30 18:50:14 -07001138
1139/*
1140 * A driver might set a page logically offline -- PageOffline() -- and
1141 * turn the page inaccessible in the hypervisor; after that, access to page
1142 * content can be fatal.
1143 *
1144 * Some special PFN walkers -- i.e., /proc/kcore -- read content of random
1145 * pages after checking PageOffline(); however, these PFN walkers can race
1146 * with drivers that set PageOffline().
1147 *
1148 * page_offline_freeze()/page_offline_thaw() allows for a subsystem to
1149 * synchronize with such drivers, achieving that a page cannot be set
1150 * PageOffline() while frozen.
1151 *
1152 * page_offline_begin()/page_offline_end() is used by drivers that care about
1153 * such races when setting a page PageOffline().
1154 */
1155static DECLARE_RWSEM(page_offline_rwsem);
1156
1157void page_offline_freeze(void)
1158{
1159 down_read(&page_offline_rwsem);
1160}
1161
1162void page_offline_thaw(void)
1163{
1164 up_read(&page_offline_rwsem);
1165}
1166
1167void page_offline_begin(void)
1168{
1169 down_write(&page_offline_rwsem);
1170}
1171EXPORT_SYMBOL(page_offline_begin);
1172
1173void page_offline_end(void)
1174{
1175 up_write(&page_offline_rwsem);
1176}
1177EXPORT_SYMBOL(page_offline_end);