util.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. #include <linux/mm.h>
  3. #include <linux/slab.h>
  4. #include <linux/string.h>
  5. #include <linux/compiler.h>
  6. #include <linux/export.h>
  7. #include <linux/err.h>
  8. #include <linux/sched.h>
  9. #include <linux/sched/mm.h>
  10. #include <linux/sched/signal.h>
  11. #include <linux/sched/task_stack.h>
  12. #include <linux/security.h>
  13. #include <linux/swap.h>
  14. #include <linux/swapops.h>
  15. #include <linux/mman.h>
  16. #include <linux/hugetlb.h>
  17. #include <linux/vmalloc.h>
  18. #include <linux/userfaultfd_k.h>
  19. #include <linux/elf.h>
  20. #include <linux/elf-randomize.h>
  21. #include <linux/personality.h>
  22. #include <linux/random.h>
  23. #include <linux/processor.h>
  24. #include <linux/sizes.h>
  25. #include <linux/compat.h>
  26. #include <linux/uaccess.h>
  27. #include <kunit/visibility.h>
  28. #include "internal.h"
  29. #include "swap.h"
  30. /**
  31. * kfree_const - conditionally free memory
  32. * @x: pointer to the memory
  33. *
  34. * Function calls kfree only if @x is not in .rodata section.
  35. */
  36. void kfree_const(const void *x)
  37. {
  38. if (!is_kernel_rodata((unsigned long)x))
  39. kfree(x);
  40. }
  41. EXPORT_SYMBOL(kfree_const);
  42. /**
  43. * kstrdup - allocate space for and copy an existing string
  44. * @s: the string to duplicate
  45. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  46. *
  47. * Return: newly allocated copy of @s or %NULL in case of error
  48. */
  49. noinline
  50. char *kstrdup(const char *s, gfp_t gfp)
  51. {
  52. size_t len;
  53. char *buf;
  54. if (!s)
  55. return NULL;
  56. len = strlen(s) + 1;
  57. buf = kmalloc_track_caller(len, gfp);
  58. if (buf)
  59. memcpy(buf, s, len);
  60. return buf;
  61. }
  62. EXPORT_SYMBOL(kstrdup);
  63. /**
  64. * kstrdup_const - conditionally duplicate an existing const string
  65. * @s: the string to duplicate
  66. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  67. *
  68. * Note: Strings allocated by kstrdup_const should be freed by kfree_const and
  69. * must not be passed to krealloc().
  70. *
  71. * Return: source string if it is in .rodata section otherwise
  72. * fallback to kstrdup.
  73. */
  74. const char *kstrdup_const(const char *s, gfp_t gfp)
  75. {
  76. if (is_kernel_rodata((unsigned long)s))
  77. return s;
  78. return kstrdup(s, gfp);
  79. }
  80. EXPORT_SYMBOL(kstrdup_const);
  81. /**
  82. * kstrndup - allocate space for and copy an existing string
  83. * @s: the string to duplicate
  84. * @max: read at most @max chars from @s
  85. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  86. *
  87. * Note: Use kmemdup_nul() instead if the size is known exactly.
  88. *
  89. * Return: newly allocated copy of @s or %NULL in case of error
  90. */
  91. char *kstrndup(const char *s, size_t max, gfp_t gfp)
  92. {
  93. size_t len;
  94. char *buf;
  95. if (!s)
  96. return NULL;
  97. len = strnlen(s, max);
  98. buf = kmalloc_track_caller(len+1, gfp);
  99. if (buf) {
  100. memcpy(buf, s, len);
  101. buf[len] = '\0';
  102. }
  103. return buf;
  104. }
  105. EXPORT_SYMBOL(kstrndup);
  106. /**
  107. * kmemdup - duplicate region of memory
  108. *
  109. * @src: memory region to duplicate
  110. * @len: memory region length
  111. * @gfp: GFP mask to use
  112. *
  113. * Return: newly allocated copy of @src or %NULL in case of error,
  114. * result is physically contiguous. Use kfree() to free.
  115. */
  116. void *kmemdup_noprof(const void *src, size_t len, gfp_t gfp)
  117. {
  118. void *p;
  119. p = kmalloc_node_track_caller_noprof(len, gfp, NUMA_NO_NODE, _RET_IP_);
  120. if (p)
  121. memcpy(p, src, len);
  122. return p;
  123. }
  124. EXPORT_SYMBOL(kmemdup_noprof);
  125. /**
  126. * kmemdup_array - duplicate a given array.
  127. *
  128. * @src: array to duplicate.
  129. * @count: number of elements to duplicate from array.
  130. * @element_size: size of each element of array.
  131. * @gfp: GFP mask to use.
  132. *
  133. * Return: duplicated array of @src or %NULL in case of error,
  134. * result is physically contiguous. Use kfree() to free.
  135. */
  136. void *kmemdup_array(const void *src, size_t count, size_t element_size, gfp_t gfp)
  137. {
  138. return kmemdup(src, size_mul(element_size, count), gfp);
  139. }
  140. EXPORT_SYMBOL(kmemdup_array);
  141. /**
  142. * kvmemdup - duplicate region of memory
  143. *
  144. * @src: memory region to duplicate
  145. * @len: memory region length
  146. * @gfp: GFP mask to use
  147. *
  148. * Return: newly allocated copy of @src or %NULL in case of error,
  149. * result may be not physically contiguous. Use kvfree() to free.
  150. */
  151. void *kvmemdup(const void *src, size_t len, gfp_t gfp)
  152. {
  153. void *p;
  154. p = kvmalloc(len, gfp);
  155. if (p)
  156. memcpy(p, src, len);
  157. return p;
  158. }
  159. EXPORT_SYMBOL(kvmemdup);
  160. /**
  161. * kmemdup_nul - Create a NUL-terminated string from unterminated data
  162. * @s: The data to stringify
  163. * @len: The size of the data
  164. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  165. *
  166. * Return: newly allocated copy of @s with NUL-termination or %NULL in
  167. * case of error
  168. */
  169. char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
  170. {
  171. char *buf;
  172. if (!s)
  173. return NULL;
  174. buf = kmalloc_track_caller(len + 1, gfp);
  175. if (buf) {
  176. memcpy(buf, s, len);
  177. buf[len] = '\0';
  178. }
  179. return buf;
  180. }
  181. EXPORT_SYMBOL(kmemdup_nul);
  182. static kmem_buckets *user_buckets __ro_after_init;
  183. static int __init init_user_buckets(void)
  184. {
  185. user_buckets = kmem_buckets_create("memdup_user", 0, 0, INT_MAX, NULL);
  186. return 0;
  187. }
  188. subsys_initcall(init_user_buckets);
  189. /**
  190. * memdup_user - duplicate memory region from user space
  191. *
  192. * @src: source address in user space
  193. * @len: number of bytes to copy
  194. *
  195. * Return: an ERR_PTR() on failure. Result is physically
  196. * contiguous, to be freed by kfree().
  197. */
  198. void *memdup_user(const void __user *src, size_t len)
  199. {
  200. void *p;
  201. p = kmem_buckets_alloc_track_caller(user_buckets, len, GFP_USER | __GFP_NOWARN);
  202. if (!p)
  203. return ERR_PTR(-ENOMEM);
  204. if (copy_from_user(p, src, len)) {
  205. kfree(p);
  206. return ERR_PTR(-EFAULT);
  207. }
  208. return p;
  209. }
  210. EXPORT_SYMBOL(memdup_user);
  211. /**
  212. * vmemdup_user - duplicate memory region from user space
  213. *
  214. * @src: source address in user space
  215. * @len: number of bytes to copy
  216. *
  217. * Return: an ERR_PTR() on failure. Result may be not
  218. * physically contiguous. Use kvfree() to free.
  219. */
  220. void *vmemdup_user(const void __user *src, size_t len)
  221. {
  222. void *p;
  223. p = kmem_buckets_valloc(user_buckets, len, GFP_USER);
  224. if (!p)
  225. return ERR_PTR(-ENOMEM);
  226. if (copy_from_user(p, src, len)) {
  227. kvfree(p);
  228. return ERR_PTR(-EFAULT);
  229. }
  230. return p;
  231. }
  232. EXPORT_SYMBOL(vmemdup_user);
  233. /**
  234. * strndup_user - duplicate an existing string from user space
  235. * @s: The string to duplicate
  236. * @n: Maximum number of bytes to copy, including the trailing NUL.
  237. *
  238. * Return: newly allocated copy of @s or an ERR_PTR() in case of error
  239. */
  240. char *strndup_user(const char __user *s, long n)
  241. {
  242. char *p;
  243. long length;
  244. length = strnlen_user(s, n);
  245. if (!length)
  246. return ERR_PTR(-EFAULT);
  247. if (length > n)
  248. return ERR_PTR(-EINVAL);
  249. p = memdup_user(s, length);
  250. if (IS_ERR(p))
  251. return p;
  252. p[length - 1] = '\0';
  253. return p;
  254. }
  255. EXPORT_SYMBOL(strndup_user);
  256. /**
  257. * memdup_user_nul - duplicate memory region from user space and NUL-terminate
  258. *
  259. * @src: source address in user space
  260. * @len: number of bytes to copy
  261. *
  262. * Return: an ERR_PTR() on failure.
  263. */
  264. void *memdup_user_nul(const void __user *src, size_t len)
  265. {
  266. char *p;
  267. /*
  268. * Always use GFP_KERNEL, since copy_from_user() can sleep and
  269. * cause pagefault, which makes it pointless to use GFP_NOFS
  270. * or GFP_ATOMIC.
  271. */
  272. p = kmalloc_track_caller(len + 1, GFP_KERNEL);
  273. if (!p)
  274. return ERR_PTR(-ENOMEM);
  275. if (copy_from_user(p, src, len)) {
  276. kfree(p);
  277. return ERR_PTR(-EFAULT);
  278. }
  279. p[len] = '\0';
  280. return p;
  281. }
  282. EXPORT_SYMBOL(memdup_user_nul);
  283. /* Check if the vma is being used as a stack by this task */
  284. int vma_is_stack_for_current(struct vm_area_struct *vma)
  285. {
  286. struct task_struct * __maybe_unused t = current;
  287. return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
  288. }
  289. /*
  290. * Change backing file, only valid to use during initial VMA setup.
  291. */
  292. void vma_set_file(struct vm_area_struct *vma, struct file *file)
  293. {
  294. /* Changing an anonymous vma with this is illegal */
  295. get_file(file);
  296. swap(vma->vm_file, file);
  297. fput(file);
  298. }
  299. EXPORT_SYMBOL(vma_set_file);
  300. #ifndef STACK_RND_MASK
  301. #define STACK_RND_MASK (0x7ff >> (PAGE_SHIFT - 12)) /* 8MB of VA */
  302. #endif
  303. unsigned long randomize_stack_top(unsigned long stack_top)
  304. {
  305. unsigned long random_variable = 0;
  306. if (current->flags & PF_RANDOMIZE) {
  307. random_variable = get_random_long();
  308. random_variable &= STACK_RND_MASK;
  309. random_variable <<= PAGE_SHIFT;
  310. }
  311. #ifdef CONFIG_STACK_GROWSUP
  312. return PAGE_ALIGN(stack_top) + random_variable;
  313. #else
  314. return PAGE_ALIGN(stack_top) - random_variable;
  315. #endif
  316. }
  317. /**
  318. * randomize_page - Generate a random, page aligned address
  319. * @start: The smallest acceptable address the caller will take.
  320. * @range: The size of the area, starting at @start, within which the
  321. * random address must fall.
  322. *
  323. * If @start + @range would overflow, @range is capped.
  324. *
  325. * NOTE: Historical use of randomize_range, which this replaces, presumed that
  326. * @start was already page aligned. We now align it regardless.
  327. *
  328. * Return: A page aligned address within [start, start + range). On error,
  329. * @start is returned.
  330. */
  331. unsigned long randomize_page(unsigned long start, unsigned long range)
  332. {
  333. if (!PAGE_ALIGNED(start)) {
  334. range -= PAGE_ALIGN(start) - start;
  335. start = PAGE_ALIGN(start);
  336. }
  337. if (start > ULONG_MAX - range)
  338. range = ULONG_MAX - start;
  339. range >>= PAGE_SHIFT;
  340. if (range == 0)
  341. return start;
  342. return start + (get_random_long() % range << PAGE_SHIFT);
  343. }
  344. #ifdef CONFIG_ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT
  345. unsigned long __weak arch_randomize_brk(struct mm_struct *mm)
  346. {
  347. /* Is the current task 32bit ? */
  348. if (!IS_ENABLED(CONFIG_64BIT) || is_compat_task())
  349. return randomize_page(mm->brk, SZ_32M);
  350. return randomize_page(mm->brk, SZ_1G);
  351. }
  352. unsigned long arch_mmap_rnd(void)
  353. {
  354. unsigned long rnd;
  355. #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
  356. if (is_compat_task())
  357. rnd = get_random_long() & ((1UL << mmap_rnd_compat_bits) - 1);
  358. else
  359. #endif /* CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS */
  360. rnd = get_random_long() & ((1UL << mmap_rnd_bits) - 1);
  361. return rnd << PAGE_SHIFT;
  362. }
  363. static int mmap_is_legacy(struct rlimit *rlim_stack)
  364. {
  365. if (current->personality & ADDR_COMPAT_LAYOUT)
  366. return 1;
  367. /* On parisc the stack always grows up - so a unlimited stack should
  368. * not be an indicator to use the legacy memory layout. */
  369. if (rlim_stack->rlim_cur == RLIM_INFINITY &&
  370. !IS_ENABLED(CONFIG_STACK_GROWSUP))
  371. return 1;
  372. return sysctl_legacy_va_layout;
  373. }
  374. /*
  375. * Leave enough space between the mmap area and the stack to honour ulimit in
  376. * the face of randomisation.
  377. */
  378. #define MIN_GAP (SZ_128M)
  379. #define MAX_GAP (STACK_TOP / 6 * 5)
  380. static unsigned long mmap_base(unsigned long rnd, struct rlimit *rlim_stack)
  381. {
  382. #ifdef CONFIG_STACK_GROWSUP
  383. /*
  384. * For an upwards growing stack the calculation is much simpler.
  385. * Memory for the maximum stack size is reserved at the top of the
  386. * task. mmap_base starts directly below the stack and grows
  387. * downwards.
  388. */
  389. return PAGE_ALIGN_DOWN(mmap_upper_limit(rlim_stack) - rnd);
  390. #else
  391. unsigned long gap = rlim_stack->rlim_cur;
  392. unsigned long pad = stack_guard_gap;
  393. /* Account for stack randomization if necessary */
  394. if (current->flags & PF_RANDOMIZE)
  395. pad += (STACK_RND_MASK << PAGE_SHIFT);
  396. /* Values close to RLIM_INFINITY can overflow. */
  397. if (gap + pad > gap)
  398. gap += pad;
  399. if (gap < MIN_GAP && MIN_GAP < MAX_GAP)
  400. gap = MIN_GAP;
  401. else if (gap > MAX_GAP)
  402. gap = MAX_GAP;
  403. return PAGE_ALIGN(STACK_TOP - gap - rnd);
  404. #endif
  405. }
  406. void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
  407. {
  408. unsigned long random_factor = 0UL;
  409. if (current->flags & PF_RANDOMIZE)
  410. random_factor = arch_mmap_rnd();
  411. if (mmap_is_legacy(rlim_stack)) {
  412. mm->mmap_base = TASK_UNMAPPED_BASE + random_factor;
  413. clear_bit(MMF_TOPDOWN, &mm->flags);
  414. } else {
  415. mm->mmap_base = mmap_base(random_factor, rlim_stack);
  416. set_bit(MMF_TOPDOWN, &mm->flags);
  417. }
  418. }
  419. #elif defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
  420. void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
  421. {
  422. mm->mmap_base = TASK_UNMAPPED_BASE;
  423. clear_bit(MMF_TOPDOWN, &mm->flags);
  424. }
  425. #endif
  426. #ifdef CONFIG_MMU
  427. EXPORT_SYMBOL_IF_KUNIT(arch_pick_mmap_layout);
  428. #endif
  429. /**
  430. * __account_locked_vm - account locked pages to an mm's locked_vm
  431. * @mm: mm to account against
  432. * @pages: number of pages to account
  433. * @inc: %true if @pages should be considered positive, %false if not
  434. * @task: task used to check RLIMIT_MEMLOCK
  435. * @bypass_rlim: %true if checking RLIMIT_MEMLOCK should be skipped
  436. *
  437. * Assumes @task and @mm are valid (i.e. at least one reference on each), and
  438. * that mmap_lock is held as writer.
  439. *
  440. * Return:
  441. * * 0 on success
  442. * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded.
  443. */
  444. int __account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc,
  445. struct task_struct *task, bool bypass_rlim)
  446. {
  447. unsigned long locked_vm, limit;
  448. int ret = 0;
  449. mmap_assert_write_locked(mm);
  450. locked_vm = mm->locked_vm;
  451. if (inc) {
  452. if (!bypass_rlim) {
  453. limit = task_rlimit(task, RLIMIT_MEMLOCK) >> PAGE_SHIFT;
  454. if (locked_vm + pages > limit)
  455. ret = -ENOMEM;
  456. }
  457. if (!ret)
  458. mm->locked_vm = locked_vm + pages;
  459. } else {
  460. WARN_ON_ONCE(pages > locked_vm);
  461. mm->locked_vm = locked_vm - pages;
  462. }
  463. pr_debug("%s: [%d] caller %ps %c%lu %lu/%lu%s\n", __func__, task->pid,
  464. (void *)_RET_IP_, (inc) ? '+' : '-', pages << PAGE_SHIFT,
  465. locked_vm << PAGE_SHIFT, task_rlimit(task, RLIMIT_MEMLOCK),
  466. ret ? " - exceeded" : "");
  467. return ret;
  468. }
  469. EXPORT_SYMBOL_GPL(__account_locked_vm);
  470. /**
  471. * account_locked_vm - account locked pages to an mm's locked_vm
  472. * @mm: mm to account against, may be NULL
  473. * @pages: number of pages to account
  474. * @inc: %true if @pages should be considered positive, %false if not
  475. *
  476. * Assumes a non-NULL @mm is valid (i.e. at least one reference on it).
  477. *
  478. * Return:
  479. * * 0 on success, or if mm is NULL
  480. * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded.
  481. */
  482. int account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc)
  483. {
  484. int ret;
  485. if (pages == 0 || !mm)
  486. return 0;
  487. mmap_write_lock(mm);
  488. ret = __account_locked_vm(mm, pages, inc, current,
  489. capable(CAP_IPC_LOCK));
  490. mmap_write_unlock(mm);
  491. return ret;
  492. }
  493. EXPORT_SYMBOL_GPL(account_locked_vm);
  494. unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
  495. unsigned long len, unsigned long prot,
  496. unsigned long flag, unsigned long pgoff)
  497. {
  498. unsigned long ret;
  499. struct mm_struct *mm = current->mm;
  500. unsigned long populate;
  501. LIST_HEAD(uf);
  502. ret = security_mmap_file(file, prot, flag);
  503. if (!ret) {
  504. if (mmap_write_lock_killable(mm))
  505. return -EINTR;
  506. ret = do_mmap(file, addr, len, prot, flag, 0, pgoff, &populate,
  507. &uf);
  508. mmap_write_unlock(mm);
  509. userfaultfd_unmap_complete(mm, &uf);
  510. if (populate)
  511. mm_populate(ret, populate);
  512. }
  513. return ret;
  514. }
  515. unsigned long vm_mmap(struct file *file, unsigned long addr,
  516. unsigned long len, unsigned long prot,
  517. unsigned long flag, unsigned long offset)
  518. {
  519. if (unlikely(offset + PAGE_ALIGN(len) < offset))
  520. return -EINVAL;
  521. if (unlikely(offset_in_page(offset)))
  522. return -EINVAL;
  523. return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
  524. }
  525. EXPORT_SYMBOL(vm_mmap);
  526. static gfp_t kmalloc_gfp_adjust(gfp_t flags, size_t size)
  527. {
  528. /*
  529. * We want to attempt a large physically contiguous block first because
  530. * it is less likely to fragment multiple larger blocks and therefore
  531. * contribute to a long term fragmentation less than vmalloc fallback.
  532. * However make sure that larger requests are not too disruptive - no
  533. * OOM killer and no allocation failure warnings as we have a fallback.
  534. */
  535. if (size > PAGE_SIZE) {
  536. flags |= __GFP_NOWARN;
  537. if (!(flags & __GFP_RETRY_MAYFAIL))
  538. flags |= __GFP_NORETRY;
  539. /* nofail semantic is implemented by the vmalloc fallback */
  540. flags &= ~__GFP_NOFAIL;
  541. }
  542. return flags;
  543. }
  544. /**
  545. * __kvmalloc_node - attempt to allocate physically contiguous memory, but upon
  546. * failure, fall back to non-contiguous (vmalloc) allocation.
  547. * @size: size of the request.
  548. * @b: which set of kmalloc buckets to allocate from.
  549. * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
  550. * @node: numa node to allocate from
  551. *
  552. * Uses kmalloc to get the memory but if the allocation fails then falls back
  553. * to the vmalloc allocator. Use kvfree for freeing the memory.
  554. *
  555. * GFP_NOWAIT and GFP_ATOMIC are not supported, neither is the __GFP_NORETRY modifier.
  556. * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
  557. * preferable to the vmalloc fallback, due to visible performance drawbacks.
  558. *
  559. * Return: pointer to the allocated memory of %NULL in case of failure
  560. */
  561. void *__kvmalloc_node_noprof(DECL_BUCKET_PARAMS(size, b), gfp_t flags, int node)
  562. {
  563. void *ret;
  564. /*
  565. * It doesn't really make sense to fallback to vmalloc for sub page
  566. * requests
  567. */
  568. ret = __kmalloc_node_noprof(PASS_BUCKET_PARAMS(size, b),
  569. kmalloc_gfp_adjust(flags, size),
  570. node);
  571. if (ret || size <= PAGE_SIZE)
  572. return ret;
  573. /* non-sleeping allocations are not supported by vmalloc */
  574. if (!gfpflags_allow_blocking(flags))
  575. return NULL;
  576. /* Don't even allow crazy sizes */
  577. if (unlikely(size > INT_MAX)) {
  578. WARN_ON_ONCE(!(flags & __GFP_NOWARN));
  579. return NULL;
  580. }
  581. /*
  582. * kvmalloc() can always use VM_ALLOW_HUGE_VMAP,
  583. * since the callers already cannot assume anything
  584. * about the resulting pointer, and cannot play
  585. * protection games.
  586. */
  587. return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END,
  588. flags, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
  589. node, __builtin_return_address(0));
  590. }
  591. EXPORT_SYMBOL(__kvmalloc_node_noprof);
  592. /**
  593. * kvfree() - Free memory.
  594. * @addr: Pointer to allocated memory.
  595. *
  596. * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
  597. * It is slightly more efficient to use kfree() or vfree() if you are certain
  598. * that you know which one to use.
  599. *
  600. * Context: Either preemptible task context or not-NMI interrupt.
  601. */
  602. void kvfree(const void *addr)
  603. {
  604. if (is_vmalloc_addr(addr))
  605. vfree(addr);
  606. else
  607. kfree(addr);
  608. }
  609. EXPORT_SYMBOL(kvfree);
  610. /**
  611. * kvfree_sensitive - Free a data object containing sensitive information.
  612. * @addr: address of the data object to be freed.
  613. * @len: length of the data object.
  614. *
  615. * Use the special memzero_explicit() function to clear the content of a
  616. * kvmalloc'ed object containing sensitive data to make sure that the
  617. * compiler won't optimize out the data clearing.
  618. */
  619. void kvfree_sensitive(const void *addr, size_t len)
  620. {
  621. if (likely(!ZERO_OR_NULL_PTR(addr))) {
  622. memzero_explicit((void *)addr, len);
  623. kvfree(addr);
  624. }
  625. }
  626. EXPORT_SYMBOL(kvfree_sensitive);
  627. /**
  628. * kvrealloc - reallocate memory; contents remain unchanged
  629. * @p: object to reallocate memory for
  630. * @size: the size to reallocate
  631. * @flags: the flags for the page level allocator
  632. *
  633. * If @p is %NULL, kvrealloc() behaves exactly like kvmalloc(). If @size is 0
  634. * and @p is not a %NULL pointer, the object pointed to is freed.
  635. *
  636. * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
  637. * initial memory allocation, every subsequent call to this API for the same
  638. * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
  639. * __GFP_ZERO is not fully honored by this API.
  640. *
  641. * In any case, the contents of the object pointed to are preserved up to the
  642. * lesser of the new and old sizes.
  643. *
  644. * This function must not be called concurrently with itself or kvfree() for the
  645. * same memory allocation.
  646. *
  647. * Return: pointer to the allocated memory or %NULL in case of error
  648. */
  649. void *kvrealloc_noprof(const void *p, size_t size, gfp_t flags)
  650. {
  651. void *n;
  652. if (is_vmalloc_addr(p))
  653. return vrealloc_noprof(p, size, flags);
  654. n = krealloc_noprof(p, size, kmalloc_gfp_adjust(flags, size));
  655. if (!n) {
  656. /* We failed to krealloc(), fall back to kvmalloc(). */
  657. n = kvmalloc_noprof(size, flags);
  658. if (!n)
  659. return NULL;
  660. if (p) {
  661. /* We already know that `p` is not a vmalloc address. */
  662. kasan_disable_current();
  663. memcpy(n, kasan_reset_tag(p), ksize(p));
  664. kasan_enable_current();
  665. kfree(p);
  666. }
  667. }
  668. return n;
  669. }
  670. EXPORT_SYMBOL(kvrealloc_noprof);
  671. /**
  672. * __vmalloc_array - allocate memory for a virtually contiguous array.
  673. * @n: number of elements.
  674. * @size: element size.
  675. * @flags: the type of memory to allocate (see kmalloc).
  676. */
  677. void *__vmalloc_array_noprof(size_t n, size_t size, gfp_t flags)
  678. {
  679. size_t bytes;
  680. if (unlikely(check_mul_overflow(n, size, &bytes)))
  681. return NULL;
  682. return __vmalloc_noprof(bytes, flags);
  683. }
  684. EXPORT_SYMBOL(__vmalloc_array_noprof);
  685. /**
  686. * vmalloc_array - allocate memory for a virtually contiguous array.
  687. * @n: number of elements.
  688. * @size: element size.
  689. */
  690. void *vmalloc_array_noprof(size_t n, size_t size)
  691. {
  692. return __vmalloc_array_noprof(n, size, GFP_KERNEL);
  693. }
  694. EXPORT_SYMBOL(vmalloc_array_noprof);
  695. /**
  696. * __vcalloc - allocate and zero memory for a virtually contiguous array.
  697. * @n: number of elements.
  698. * @size: element size.
  699. * @flags: the type of memory to allocate (see kmalloc).
  700. */
  701. void *__vcalloc_noprof(size_t n, size_t size, gfp_t flags)
  702. {
  703. return __vmalloc_array_noprof(n, size, flags | __GFP_ZERO);
  704. }
  705. EXPORT_SYMBOL(__vcalloc_noprof);
  706. /**
  707. * vcalloc - allocate and zero memory for a virtually contiguous array.
  708. * @n: number of elements.
  709. * @size: element size.
  710. */
  711. void *vcalloc_noprof(size_t n, size_t size)
  712. {
  713. return __vmalloc_array_noprof(n, size, GFP_KERNEL | __GFP_ZERO);
  714. }
  715. EXPORT_SYMBOL(vcalloc_noprof);
  716. struct anon_vma *folio_anon_vma(struct folio *folio)
  717. {
  718. unsigned long mapping = (unsigned long)folio->mapping;
  719. if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
  720. return NULL;
  721. return (void *)(mapping - PAGE_MAPPING_ANON);
  722. }
  723. /**
  724. * folio_mapping - Find the mapping where this folio is stored.
  725. * @folio: The folio.
  726. *
  727. * For folios which are in the page cache, return the mapping that this
  728. * page belongs to. Folios in the swap cache return the swap mapping
  729. * this page is stored in (which is different from the mapping for the
  730. * swap file or swap device where the data is stored).
  731. *
  732. * You can call this for folios which aren't in the swap cache or page
  733. * cache and it will return NULL.
  734. */
  735. struct address_space *folio_mapping(struct folio *folio)
  736. {
  737. struct address_space *mapping;
  738. /* This happens if someone calls flush_dcache_page on slab page */
  739. if (unlikely(folio_test_slab(folio)))
  740. return NULL;
  741. if (unlikely(folio_test_swapcache(folio)))
  742. return swap_address_space(folio->swap);
  743. mapping = folio->mapping;
  744. if ((unsigned long)mapping & PAGE_MAPPING_FLAGS)
  745. return NULL;
  746. return mapping;
  747. }
  748. EXPORT_SYMBOL(folio_mapping);
  749. /**
  750. * folio_copy - Copy the contents of one folio to another.
  751. * @dst: Folio to copy to.
  752. * @src: Folio to copy from.
  753. *
  754. * The bytes in the folio represented by @src are copied to @dst.
  755. * Assumes the caller has validated that @dst is at least as large as @src.
  756. * Can be called in atomic context for order-0 folios, but if the folio is
  757. * larger, it may sleep.
  758. */
  759. void folio_copy(struct folio *dst, struct folio *src)
  760. {
  761. long i = 0;
  762. long nr = folio_nr_pages(src);
  763. for (;;) {
  764. copy_highpage(folio_page(dst, i), folio_page(src, i));
  765. if (++i == nr)
  766. break;
  767. cond_resched();
  768. }
  769. }
  770. EXPORT_SYMBOL(folio_copy);
  771. int folio_mc_copy(struct folio *dst, struct folio *src)
  772. {
  773. long nr = folio_nr_pages(src);
  774. long i = 0;
  775. for (;;) {
  776. if (copy_mc_highpage(folio_page(dst, i), folio_page(src, i)))
  777. return -EHWPOISON;
  778. if (++i == nr)
  779. break;
  780. cond_resched();
  781. }
  782. return 0;
  783. }
  784. EXPORT_SYMBOL(folio_mc_copy);
  785. int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
  786. int sysctl_overcommit_ratio __read_mostly = 50;
  787. unsigned long sysctl_overcommit_kbytes __read_mostly;
  788. int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
  789. unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
  790. unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
  791. int overcommit_ratio_handler(const struct ctl_table *table, int write, void *buffer,
  792. size_t *lenp, loff_t *ppos)
  793. {
  794. int ret;
  795. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  796. if (ret == 0 && write)
  797. sysctl_overcommit_kbytes = 0;
  798. return ret;
  799. }
  800. static void sync_overcommit_as(struct work_struct *dummy)
  801. {
  802. percpu_counter_sync(&vm_committed_as);
  803. }
  804. int overcommit_policy_handler(const struct ctl_table *table, int write, void *buffer,
  805. size_t *lenp, loff_t *ppos)
  806. {
  807. struct ctl_table t;
  808. int new_policy = -1;
  809. int ret;
  810. /*
  811. * The deviation of sync_overcommit_as could be big with loose policy
  812. * like OVERCOMMIT_ALWAYS/OVERCOMMIT_GUESS. When changing policy to
  813. * strict OVERCOMMIT_NEVER, we need to reduce the deviation to comply
  814. * with the strict "NEVER", and to avoid possible race condition (even
  815. * though user usually won't too frequently do the switching to policy
  816. * OVERCOMMIT_NEVER), the switch is done in the following order:
  817. * 1. changing the batch
  818. * 2. sync percpu count on each CPU
  819. * 3. switch the policy
  820. */
  821. if (write) {
  822. t = *table;
  823. t.data = &new_policy;
  824. ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  825. if (ret || new_policy == -1)
  826. return ret;
  827. mm_compute_batch(new_policy);
  828. if (new_policy == OVERCOMMIT_NEVER)
  829. schedule_on_each_cpu(sync_overcommit_as);
  830. sysctl_overcommit_memory = new_policy;
  831. } else {
  832. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  833. }
  834. return ret;
  835. }
  836. int overcommit_kbytes_handler(const struct ctl_table *table, int write, void *buffer,
  837. size_t *lenp, loff_t *ppos)
  838. {
  839. int ret;
  840. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  841. if (ret == 0 && write)
  842. sysctl_overcommit_ratio = 0;
  843. return ret;
  844. }
  845. /*
  846. * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
  847. */
  848. unsigned long vm_commit_limit(void)
  849. {
  850. unsigned long allowed;
  851. if (sysctl_overcommit_kbytes)
  852. allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
  853. else
  854. allowed = ((totalram_pages() - hugetlb_total_pages())
  855. * sysctl_overcommit_ratio / 100);
  856. allowed += total_swap_pages;
  857. return allowed;
  858. }
  859. /*
  860. * Make sure vm_committed_as in one cacheline and not cacheline shared with
  861. * other variables. It can be updated by several CPUs frequently.
  862. */
  863. struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
  864. /*
  865. * The global memory commitment made in the system can be a metric
  866. * that can be used to drive ballooning decisions when Linux is hosted
  867. * as a guest. On Hyper-V, the host implements a policy engine for dynamically
  868. * balancing memory across competing virtual machines that are hosted.
  869. * Several metrics drive this policy engine including the guest reported
  870. * memory commitment.
  871. *
  872. * The time cost of this is very low for small platforms, and for big
  873. * platform like a 2S/36C/72T Skylake server, in worst case where
  874. * vm_committed_as's spinlock is under severe contention, the time cost
  875. * could be about 30~40 microseconds.
  876. */
  877. unsigned long vm_memory_committed(void)
  878. {
  879. return percpu_counter_sum_positive(&vm_committed_as);
  880. }
  881. EXPORT_SYMBOL_GPL(vm_memory_committed);
  882. /*
  883. * Check that a process has enough memory to allocate a new virtual
  884. * mapping. 0 means there is enough memory for the allocation to
  885. * succeed and -ENOMEM implies there is not.
  886. *
  887. * We currently support three overcommit policies, which are set via the
  888. * vm.overcommit_memory sysctl. See Documentation/mm/overcommit-accounting.rst
  889. *
  890. * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
  891. * Additional code 2002 Jul 20 by Robert Love.
  892. *
  893. * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
  894. *
  895. * Note this is a helper function intended to be used by LSMs which
  896. * wish to use this logic.
  897. */
  898. int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
  899. {
  900. long allowed;
  901. unsigned long bytes_failed;
  902. vm_acct_memory(pages);
  903. /*
  904. * Sometimes we want to use more memory than we have
  905. */
  906. if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
  907. return 0;
  908. if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
  909. if (pages > totalram_pages() + total_swap_pages)
  910. goto error;
  911. return 0;
  912. }
  913. allowed = vm_commit_limit();
  914. /*
  915. * Reserve some for root
  916. */
  917. if (!cap_sys_admin)
  918. allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
  919. /*
  920. * Don't let a single process grow so big a user can't recover
  921. */
  922. if (mm) {
  923. long reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
  924. allowed -= min_t(long, mm->total_vm / 32, reserve);
  925. }
  926. if (percpu_counter_read_positive(&vm_committed_as) < allowed)
  927. return 0;
  928. error:
  929. bytes_failed = pages << PAGE_SHIFT;
  930. pr_warn_ratelimited("%s: pid: %d, comm: %s, bytes: %lu not enough memory for the allocation\n",
  931. __func__, current->pid, current->comm, bytes_failed);
  932. vm_unacct_memory(pages);
  933. return -ENOMEM;
  934. }
  935. /**
  936. * get_cmdline() - copy the cmdline value to a buffer.
  937. * @task: the task whose cmdline value to copy.
  938. * @buffer: the buffer to copy to.
  939. * @buflen: the length of the buffer. Larger cmdline values are truncated
  940. * to this length.
  941. *
  942. * Return: the size of the cmdline field copied. Note that the copy does
  943. * not guarantee an ending NULL byte.
  944. */
  945. int get_cmdline(struct task_struct *task, char *buffer, int buflen)
  946. {
  947. int res = 0;
  948. unsigned int len;
  949. struct mm_struct *mm = get_task_mm(task);
  950. unsigned long arg_start, arg_end, env_start, env_end;
  951. if (!mm)
  952. goto out;
  953. if (!mm->arg_end)
  954. goto out_mm; /* Shh! No looking before we're done */
  955. spin_lock(&mm->arg_lock);
  956. arg_start = mm->arg_start;
  957. arg_end = mm->arg_end;
  958. env_start = mm->env_start;
  959. env_end = mm->env_end;
  960. spin_unlock(&mm->arg_lock);
  961. len = arg_end - arg_start;
  962. if (len > buflen)
  963. len = buflen;
  964. res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
  965. /*
  966. * If the nul at the end of args has been overwritten, then
  967. * assume application is using setproctitle(3).
  968. */
  969. if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
  970. len = strnlen(buffer, res);
  971. if (len < res) {
  972. res = len;
  973. } else {
  974. len = env_end - env_start;
  975. if (len > buflen - res)
  976. len = buflen - res;
  977. res += access_process_vm(task, env_start,
  978. buffer+res, len,
  979. FOLL_FORCE);
  980. res = strnlen(buffer, res);
  981. }
  982. }
  983. out_mm:
  984. mmput(mm);
  985. out:
  986. return res;
  987. }
  988. int __weak memcmp_pages(struct page *page1, struct page *page2)
  989. {
  990. char *addr1, *addr2;
  991. int ret;
  992. addr1 = kmap_local_page(page1);
  993. addr2 = kmap_local_page(page2);
  994. ret = memcmp(addr1, addr2, PAGE_SIZE);
  995. kunmap_local(addr2);
  996. kunmap_local(addr1);
  997. return ret;
  998. }
  999. #ifdef CONFIG_PRINTK
  1000. /**
  1001. * mem_dump_obj - Print available provenance information
  1002. * @object: object for which to find provenance information.
  1003. *
  1004. * This function uses pr_cont(), so that the caller is expected to have
  1005. * printed out whatever preamble is appropriate. The provenance information
  1006. * depends on the type of object and on how much debugging is enabled.
  1007. * For example, for a slab-cache object, the slab name is printed, and,
  1008. * if available, the return address and stack trace from the allocation
  1009. * and last free path of that object.
  1010. */
  1011. void mem_dump_obj(void *object)
  1012. {
  1013. const char *type;
  1014. if (kmem_dump_obj(object))
  1015. return;
  1016. if (vmalloc_dump_obj(object))
  1017. return;
  1018. if (is_vmalloc_addr(object))
  1019. type = "vmalloc memory";
  1020. else if (virt_addr_valid(object))
  1021. type = "non-slab/vmalloc memory";
  1022. else if (object == NULL)
  1023. type = "NULL pointer";
  1024. else if (object == ZERO_SIZE_PTR)
  1025. type = "zero-size pointer";
  1026. else
  1027. type = "non-paged memory";
  1028. pr_cont(" %s\n", type);
  1029. }
  1030. EXPORT_SYMBOL_GPL(mem_dump_obj);
  1031. #endif
  1032. /*
  1033. * A driver might set a page logically offline -- PageOffline() -- and
  1034. * turn the page inaccessible in the hypervisor; after that, access to page
  1035. * content can be fatal.
  1036. *
  1037. * Some special PFN walkers -- i.e., /proc/kcore -- read content of random
  1038. * pages after checking PageOffline(); however, these PFN walkers can race
  1039. * with drivers that set PageOffline().
  1040. *
  1041. * page_offline_freeze()/page_offline_thaw() allows for a subsystem to
  1042. * synchronize with such drivers, achieving that a page cannot be set
  1043. * PageOffline() while frozen.
  1044. *
  1045. * page_offline_begin()/page_offline_end() is used by drivers that care about
  1046. * such races when setting a page PageOffline().
  1047. */
  1048. static DECLARE_RWSEM(page_offline_rwsem);
  1049. void page_offline_freeze(void)
  1050. {
  1051. down_read(&page_offline_rwsem);
  1052. }
  1053. void page_offline_thaw(void)
  1054. {
  1055. up_read(&page_offline_rwsem);
  1056. }
  1057. void page_offline_begin(void)
  1058. {
  1059. down_write(&page_offline_rwsem);
  1060. }
  1061. EXPORT_SYMBOL(page_offline_begin);
  1062. void page_offline_end(void)
  1063. {
  1064. up_write(&page_offline_rwsem);
  1065. }
  1066. EXPORT_SYMBOL(page_offline_end);
  1067. #ifndef flush_dcache_folio
  1068. void flush_dcache_folio(struct folio *folio)
  1069. {
  1070. long i, nr = folio_nr_pages(folio);
  1071. for (i = 0; i < nr; i++)
  1072. flush_dcache_page(folio_page(folio, i));
  1073. }
  1074. EXPORT_SYMBOL(flush_dcache_folio);
  1075. #endif