util.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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 "internal.h"
  28. #ifndef __GENKSYMS__
  29. #include <trace/hooks/syscall_check.h>
  30. #endif
  31. /**
  32. * kfree_const - conditionally free memory
  33. * @x: pointer to the memory
  34. *
  35. * Function calls kfree only if @x is not in .rodata section.
  36. */
  37. void kfree_const(const void *x)
  38. {
  39. if (!is_kernel_rodata((unsigned long)x))
  40. kfree(x);
  41. }
  42. EXPORT_SYMBOL(kfree_const);
  43. /**
  44. * kstrdup - allocate space for and copy an existing string
  45. * @s: the string to duplicate
  46. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  47. *
  48. * Return: newly allocated copy of @s or %NULL in case of error
  49. */
  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. */
  115. void *kmemdup(const void *src, size_t len, gfp_t gfp)
  116. {
  117. void *p;
  118. p = kmalloc_track_caller(len, gfp);
  119. if (p)
  120. memcpy(p, src, len);
  121. return p;
  122. }
  123. EXPORT_SYMBOL(kmemdup);
  124. /**
  125. * kmemdup_nul - Create a NUL-terminated string from unterminated data
  126. * @s: The data to stringify
  127. * @len: The size of the data
  128. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  129. *
  130. * Return: newly allocated copy of @s with NUL-termination or %NULL in
  131. * case of error
  132. */
  133. char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
  134. {
  135. char *buf;
  136. if (!s)
  137. return NULL;
  138. buf = kmalloc_track_caller(len + 1, gfp);
  139. if (buf) {
  140. memcpy(buf, s, len);
  141. buf[len] = '\0';
  142. }
  143. return buf;
  144. }
  145. EXPORT_SYMBOL(kmemdup_nul);
  146. /**
  147. * memdup_user - duplicate memory region from user space
  148. *
  149. * @src: source address in user space
  150. * @len: number of bytes to copy
  151. *
  152. * Return: an ERR_PTR() on failure. Result is physically
  153. * contiguous, to be freed by kfree().
  154. */
  155. void *memdup_user(const void __user *src, size_t len)
  156. {
  157. void *p;
  158. p = kmalloc_track_caller(len, GFP_USER | __GFP_NOWARN);
  159. if (!p)
  160. return ERR_PTR(-ENOMEM);
  161. if (copy_from_user(p, src, len)) {
  162. kfree(p);
  163. return ERR_PTR(-EFAULT);
  164. }
  165. return p;
  166. }
  167. EXPORT_SYMBOL(memdup_user);
  168. /**
  169. * vmemdup_user - duplicate memory region from user space
  170. *
  171. * @src: source address in user space
  172. * @len: number of bytes to copy
  173. *
  174. * Return: an ERR_PTR() on failure. Result may be not
  175. * physically contiguous. Use kvfree() to free.
  176. */
  177. void *vmemdup_user(const void __user *src, size_t len)
  178. {
  179. void *p;
  180. p = kvmalloc(len, GFP_USER);
  181. if (!p)
  182. return ERR_PTR(-ENOMEM);
  183. if (copy_from_user(p, src, len)) {
  184. kvfree(p);
  185. return ERR_PTR(-EFAULT);
  186. }
  187. return p;
  188. }
  189. EXPORT_SYMBOL(vmemdup_user);
  190. /**
  191. * strndup_user - duplicate an existing string from user space
  192. * @s: The string to duplicate
  193. * @n: Maximum number of bytes to copy, including the trailing NUL.
  194. *
  195. * Return: newly allocated copy of @s or an ERR_PTR() in case of error
  196. */
  197. char *strndup_user(const char __user *s, long n)
  198. {
  199. char *p;
  200. long length;
  201. length = strnlen_user(s, n);
  202. if (!length)
  203. return ERR_PTR(-EFAULT);
  204. if (length > n)
  205. return ERR_PTR(-EINVAL);
  206. p = memdup_user(s, length);
  207. if (IS_ERR(p))
  208. return p;
  209. p[length - 1] = '\0';
  210. return p;
  211. }
  212. EXPORT_SYMBOL(strndup_user);
  213. /**
  214. * memdup_user_nul - duplicate memory region from user space and NUL-terminate
  215. *
  216. * @src: source address in user space
  217. * @len: number of bytes to copy
  218. *
  219. * Return: an ERR_PTR() on failure.
  220. */
  221. void *memdup_user_nul(const void __user *src, size_t len)
  222. {
  223. char *p;
  224. /*
  225. * Always use GFP_KERNEL, since copy_from_user() can sleep and
  226. * cause pagefault, which makes it pointless to use GFP_NOFS
  227. * or GFP_ATOMIC.
  228. */
  229. p = kmalloc_track_caller(len + 1, GFP_KERNEL);
  230. if (!p)
  231. return ERR_PTR(-ENOMEM);
  232. if (copy_from_user(p, src, len)) {
  233. kfree(p);
  234. return ERR_PTR(-EFAULT);
  235. }
  236. p[len] = '\0';
  237. return p;
  238. }
  239. EXPORT_SYMBOL(memdup_user_nul);
  240. void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
  241. struct vm_area_struct *prev)
  242. {
  243. struct vm_area_struct *next;
  244. vma->vm_prev = prev;
  245. if (prev) {
  246. next = prev->vm_next;
  247. prev->vm_next = vma;
  248. } else {
  249. next = mm->mmap;
  250. mm->mmap = vma;
  251. }
  252. vma->vm_next = next;
  253. if (next)
  254. next->vm_prev = vma;
  255. }
  256. void __vma_unlink_list(struct mm_struct *mm, struct vm_area_struct *vma)
  257. {
  258. struct vm_area_struct *prev, *next;
  259. next = vma->vm_next;
  260. prev = vma->vm_prev;
  261. if (prev)
  262. prev->vm_next = next;
  263. else
  264. mm->mmap = next;
  265. if (next)
  266. next->vm_prev = prev;
  267. }
  268. /* Check if the vma is being used as a stack by this task */
  269. int vma_is_stack_for_current(struct vm_area_struct *vma)
  270. {
  271. struct task_struct * __maybe_unused t = current;
  272. return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
  273. }
  274. #ifndef STACK_RND_MASK
  275. #define STACK_RND_MASK (0x7ff >> (PAGE_SHIFT - 12)) /* 8MB of VA */
  276. #endif
  277. unsigned long randomize_stack_top(unsigned long stack_top)
  278. {
  279. unsigned long random_variable = 0;
  280. if (current->flags & PF_RANDOMIZE) {
  281. random_variable = get_random_long();
  282. random_variable &= STACK_RND_MASK;
  283. random_variable <<= PAGE_SHIFT;
  284. }
  285. #ifdef CONFIG_STACK_GROWSUP
  286. return PAGE_ALIGN(stack_top) + random_variable;
  287. #else
  288. return PAGE_ALIGN(stack_top) - random_variable;
  289. #endif
  290. }
  291. #ifdef CONFIG_ARCH_WANT_DEFAULT_TOPDOWN_MMAP_LAYOUT
  292. unsigned long arch_randomize_brk(struct mm_struct *mm)
  293. {
  294. /* Is the current task 32bit ? */
  295. if (!IS_ENABLED(CONFIG_64BIT) || is_compat_task())
  296. return randomize_page(mm->brk, SZ_32M);
  297. return randomize_page(mm->brk, SZ_1G);
  298. }
  299. unsigned long arch_mmap_rnd(void)
  300. {
  301. unsigned long rnd;
  302. #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
  303. if (is_compat_task())
  304. rnd = get_random_long() & ((1UL << mmap_rnd_compat_bits) - 1);
  305. else
  306. #endif /* CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS */
  307. rnd = get_random_long() & ((1UL << mmap_rnd_bits) - 1);
  308. return rnd << PAGE_SHIFT;
  309. }
  310. EXPORT_SYMBOL_GPL(arch_mmap_rnd);
  311. static int mmap_is_legacy(struct rlimit *rlim_stack)
  312. {
  313. if (current->personality & ADDR_COMPAT_LAYOUT)
  314. return 1;
  315. if (rlim_stack->rlim_cur == RLIM_INFINITY)
  316. return 1;
  317. return sysctl_legacy_va_layout;
  318. }
  319. /*
  320. * Leave enough space between the mmap area and the stack to honour ulimit in
  321. * the face of randomisation.
  322. */
  323. #define MIN_GAP (SZ_128M)
  324. #define MAX_GAP (STACK_TOP / 6 * 5)
  325. static unsigned long mmap_base(unsigned long rnd, struct rlimit *rlim_stack)
  326. {
  327. unsigned long gap = rlim_stack->rlim_cur;
  328. unsigned long pad = stack_guard_gap;
  329. /* Account for stack randomization if necessary */
  330. if (current->flags & PF_RANDOMIZE)
  331. pad += (STACK_RND_MASK << PAGE_SHIFT);
  332. /* Values close to RLIM_INFINITY can overflow. */
  333. if (gap + pad > gap)
  334. gap += pad;
  335. if (gap < MIN_GAP)
  336. gap = MIN_GAP;
  337. else if (gap > MAX_GAP)
  338. gap = MAX_GAP;
  339. return PAGE_ALIGN(STACK_TOP - gap - rnd);
  340. }
  341. void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
  342. {
  343. unsigned long random_factor = 0UL;
  344. if (current->flags & PF_RANDOMIZE)
  345. random_factor = arch_mmap_rnd();
  346. if (mmap_is_legacy(rlim_stack)) {
  347. mm->mmap_base = TASK_UNMAPPED_BASE + random_factor;
  348. mm->get_unmapped_area = arch_get_unmapped_area;
  349. } else {
  350. mm->mmap_base = mmap_base(random_factor, rlim_stack);
  351. mm->get_unmapped_area = arch_get_unmapped_area_topdown;
  352. }
  353. }
  354. #elif defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
  355. void arch_pick_mmap_layout(struct mm_struct *mm, struct rlimit *rlim_stack)
  356. {
  357. mm->mmap_base = TASK_UNMAPPED_BASE;
  358. mm->get_unmapped_area = arch_get_unmapped_area;
  359. }
  360. #endif
  361. /**
  362. * __account_locked_vm - account locked pages to an mm's locked_vm
  363. * @mm: mm to account against
  364. * @pages: number of pages to account
  365. * @inc: %true if @pages should be considered positive, %false if not
  366. * @task: task used to check RLIMIT_MEMLOCK
  367. * @bypass_rlim: %true if checking RLIMIT_MEMLOCK should be skipped
  368. *
  369. * Assumes @task and @mm are valid (i.e. at least one reference on each), and
  370. * that mmap_lock is held as writer.
  371. *
  372. * Return:
  373. * * 0 on success
  374. * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded.
  375. */
  376. int __account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc,
  377. struct task_struct *task, bool bypass_rlim)
  378. {
  379. unsigned long locked_vm, limit;
  380. int ret = 0;
  381. mmap_assert_write_locked(mm);
  382. locked_vm = mm->locked_vm;
  383. if (inc) {
  384. if (!bypass_rlim) {
  385. limit = task_rlimit(task, RLIMIT_MEMLOCK) >> PAGE_SHIFT;
  386. if (locked_vm + pages > limit)
  387. ret = -ENOMEM;
  388. }
  389. if (!ret)
  390. mm->locked_vm = locked_vm + pages;
  391. } else {
  392. WARN_ON_ONCE(pages > locked_vm);
  393. mm->locked_vm = locked_vm - pages;
  394. }
  395. pr_debug("%s: [%d] caller %ps %c%lu %lu/%lu%s\n", __func__, task->pid,
  396. (void *)_RET_IP_, (inc) ? '+' : '-', pages << PAGE_SHIFT,
  397. locked_vm << PAGE_SHIFT, task_rlimit(task, RLIMIT_MEMLOCK),
  398. ret ? " - exceeded" : "");
  399. return ret;
  400. }
  401. EXPORT_SYMBOL_GPL(__account_locked_vm);
  402. /**
  403. * account_locked_vm - account locked pages to an mm's locked_vm
  404. * @mm: mm to account against, may be NULL
  405. * @pages: number of pages to account
  406. * @inc: %true if @pages should be considered positive, %false if not
  407. *
  408. * Assumes a non-NULL @mm is valid (i.e. at least one reference on it).
  409. *
  410. * Return:
  411. * * 0 on success, or if mm is NULL
  412. * * -ENOMEM if RLIMIT_MEMLOCK would be exceeded.
  413. */
  414. int account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc)
  415. {
  416. int ret;
  417. if (pages == 0 || !mm)
  418. return 0;
  419. mmap_write_lock(mm);
  420. ret = __account_locked_vm(mm, pages, inc, current,
  421. capable(CAP_IPC_LOCK));
  422. mmap_write_unlock(mm);
  423. return ret;
  424. }
  425. EXPORT_SYMBOL_GPL(account_locked_vm);
  426. unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
  427. unsigned long len, unsigned long prot,
  428. unsigned long flag, unsigned long pgoff)
  429. {
  430. unsigned long ret;
  431. struct mm_struct *mm = current->mm;
  432. unsigned long populate;
  433. LIST_HEAD(uf);
  434. ret = security_mmap_file(file, prot, flag);
  435. if (!ret) {
  436. if (mmap_write_lock_killable(mm))
  437. return -EINTR;
  438. ret = do_mmap(file, addr, len, prot, flag, pgoff, &populate,
  439. &uf);
  440. mmap_write_unlock(mm);
  441. userfaultfd_unmap_complete(mm, &uf);
  442. if (populate)
  443. mm_populate(ret, populate);
  444. }
  445. trace_android_vh_check_mmap_file(file, prot, flag, ret);
  446. return ret;
  447. }
  448. unsigned long vm_mmap(struct file *file, unsigned long addr,
  449. unsigned long len, unsigned long prot,
  450. unsigned long flag, unsigned long offset)
  451. {
  452. if (unlikely(offset + PAGE_ALIGN(len) < offset))
  453. return -EINVAL;
  454. if (unlikely(offset_in_page(offset)))
  455. return -EINVAL;
  456. return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
  457. }
  458. EXPORT_SYMBOL(vm_mmap);
  459. /**
  460. * kvmalloc_node - attempt to allocate physically contiguous memory, but upon
  461. * failure, fall back to non-contiguous (vmalloc) allocation.
  462. * @size: size of the request.
  463. * @flags: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
  464. * @node: numa node to allocate from
  465. *
  466. * Uses kmalloc to get the memory but if the allocation fails then falls back
  467. * to the vmalloc allocator. Use kvfree for freeing the memory.
  468. *
  469. * Reclaim modifiers - __GFP_NORETRY and __GFP_NOFAIL are not supported.
  470. * __GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
  471. * preferable to the vmalloc fallback, due to visible performance drawbacks.
  472. *
  473. * Please note that any use of gfp flags outside of GFP_KERNEL is careful to not
  474. * fall back to vmalloc.
  475. *
  476. * Return: pointer to the allocated memory of %NULL in case of failure
  477. */
  478. void *kvmalloc_node(size_t size, gfp_t flags, int node)
  479. {
  480. gfp_t kmalloc_flags = flags;
  481. void *ret;
  482. /*
  483. * vmalloc uses GFP_KERNEL for some internal allocations (e.g page tables)
  484. * so the given set of flags has to be compatible.
  485. */
  486. if ((flags & GFP_KERNEL) != GFP_KERNEL)
  487. return kmalloc_node(size, flags, node);
  488. /*
  489. * We want to attempt a large physically contiguous block first because
  490. * it is less likely to fragment multiple larger blocks and therefore
  491. * contribute to a long term fragmentation less than vmalloc fallback.
  492. * However make sure that larger requests are not too disruptive - no
  493. * OOM killer and no allocation failure warnings as we have a fallback.
  494. */
  495. if (size > PAGE_SIZE) {
  496. kmalloc_flags |= __GFP_NOWARN;
  497. if (!(kmalloc_flags & __GFP_RETRY_MAYFAIL))
  498. kmalloc_flags |= __GFP_NORETRY;
  499. }
  500. ret = kmalloc_node(size, kmalloc_flags, node);
  501. /*
  502. * It doesn't really make sense to fallback to vmalloc for sub page
  503. * requests
  504. */
  505. if (ret || size <= PAGE_SIZE)
  506. return ret;
  507. /* Don't even allow crazy sizes */
  508. if (unlikely(size > INT_MAX)) {
  509. WARN_ON_ONCE(!(flags & __GFP_NOWARN));
  510. return NULL;
  511. }
  512. return __vmalloc_node(size, 1, flags, node,
  513. __builtin_return_address(0));
  514. }
  515. EXPORT_SYMBOL(kvmalloc_node);
  516. /**
  517. * kvfree() - Free memory.
  518. * @addr: Pointer to allocated memory.
  519. *
  520. * kvfree frees memory allocated by any of vmalloc(), kmalloc() or kvmalloc().
  521. * It is slightly more efficient to use kfree() or vfree() if you are certain
  522. * that you know which one to use.
  523. *
  524. * Context: Either preemptible task context or not-NMI interrupt.
  525. */
  526. void kvfree(const void *addr)
  527. {
  528. if (is_vmalloc_addr(addr))
  529. vfree(addr);
  530. else
  531. kfree(addr);
  532. }
  533. EXPORT_SYMBOL(kvfree);
  534. /**
  535. * kvfree_sensitive - Free a data object containing sensitive information.
  536. * @addr: address of the data object to be freed.
  537. * @len: length of the data object.
  538. *
  539. * Use the special memzero_explicit() function to clear the content of a
  540. * kvmalloc'ed object containing sensitive data to make sure that the
  541. * compiler won't optimize out the data clearing.
  542. */
  543. void kvfree_sensitive(const void *addr, size_t len)
  544. {
  545. if (likely(!ZERO_OR_NULL_PTR(addr))) {
  546. memzero_explicit((void *)addr, len);
  547. kvfree(addr);
  548. }
  549. }
  550. EXPORT_SYMBOL(kvfree_sensitive);
  551. static inline void *__page_rmapping(struct page *page)
  552. {
  553. unsigned long mapping;
  554. mapping = (unsigned long)page->mapping;
  555. mapping &= ~PAGE_MAPPING_FLAGS;
  556. return (void *)mapping;
  557. }
  558. /* Neutral page->mapping pointer to address_space or anon_vma or other */
  559. void *page_rmapping(struct page *page)
  560. {
  561. page = compound_head(page);
  562. return __page_rmapping(page);
  563. }
  564. /*
  565. * Return true if this page is mapped into pagetables.
  566. * For compound page it returns true if any subpage of compound page is mapped.
  567. */
  568. bool page_mapped(struct page *page)
  569. {
  570. int i;
  571. if (likely(!PageCompound(page)))
  572. return atomic_read(&page->_mapcount) >= 0;
  573. page = compound_head(page);
  574. if (atomic_read(compound_mapcount_ptr(page)) >= 0)
  575. return true;
  576. if (PageHuge(page))
  577. return false;
  578. for (i = 0; i < compound_nr(page); i++) {
  579. if (atomic_read(&page[i]._mapcount) >= 0)
  580. return true;
  581. }
  582. return false;
  583. }
  584. EXPORT_SYMBOL(page_mapped);
  585. struct anon_vma *page_anon_vma(struct page *page)
  586. {
  587. unsigned long mapping;
  588. page = compound_head(page);
  589. mapping = (unsigned long)page->mapping;
  590. if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
  591. return NULL;
  592. return __page_rmapping(page);
  593. }
  594. struct address_space *page_mapping(struct page *page)
  595. {
  596. struct address_space *mapping;
  597. page = compound_head(page);
  598. /* This happens if someone calls flush_dcache_page on slab page */
  599. if (unlikely(PageSlab(page)))
  600. return NULL;
  601. if (unlikely(PageSwapCache(page))) {
  602. swp_entry_t entry;
  603. entry.val = page_private(page);
  604. return swap_address_space(entry);
  605. }
  606. mapping = page->mapping;
  607. if ((unsigned long)mapping & PAGE_MAPPING_ANON)
  608. return NULL;
  609. return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
  610. }
  611. EXPORT_SYMBOL(page_mapping);
  612. /*
  613. * For file cache pages, return the address_space, otherwise return NULL
  614. */
  615. struct address_space *page_mapping_file(struct page *page)
  616. {
  617. if (unlikely(PageSwapCache(page)))
  618. return NULL;
  619. return page_mapping(page);
  620. }
  621. /* Slow path of page_mapcount() for compound pages */
  622. int __page_mapcount(struct page *page)
  623. {
  624. int ret;
  625. ret = atomic_read(&page->_mapcount) + 1;
  626. /*
  627. * For file THP page->_mapcount contains total number of mapping
  628. * of the page: no need to look into compound_mapcount.
  629. */
  630. if (!PageAnon(page) && !PageHuge(page))
  631. return ret;
  632. page = compound_head(page);
  633. ret += atomic_read(compound_mapcount_ptr(page)) + 1;
  634. if (PageDoubleMap(page))
  635. ret--;
  636. return ret;
  637. }
  638. EXPORT_SYMBOL_GPL(__page_mapcount);
  639. int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
  640. int sysctl_overcommit_ratio __read_mostly = 50;
  641. unsigned long sysctl_overcommit_kbytes __read_mostly;
  642. int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
  643. unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
  644. unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
  645. int overcommit_ratio_handler(struct ctl_table *table, int write, void *buffer,
  646. size_t *lenp, loff_t *ppos)
  647. {
  648. int ret;
  649. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  650. if (ret == 0 && write)
  651. sysctl_overcommit_kbytes = 0;
  652. return ret;
  653. }
  654. static void sync_overcommit_as(struct work_struct *dummy)
  655. {
  656. percpu_counter_sync(&vm_committed_as);
  657. }
  658. int overcommit_policy_handler(struct ctl_table *table, int write, void *buffer,
  659. size_t *lenp, loff_t *ppos)
  660. {
  661. struct ctl_table t;
  662. int new_policy = -1;
  663. int ret;
  664. /*
  665. * The deviation of sync_overcommit_as could be big with loose policy
  666. * like OVERCOMMIT_ALWAYS/OVERCOMMIT_GUESS. When changing policy to
  667. * strict OVERCOMMIT_NEVER, we need to reduce the deviation to comply
  668. * with the strict "NEVER", and to avoid possible race condtion (even
  669. * though user usually won't too frequently do the switching to policy
  670. * OVERCOMMIT_NEVER), the switch is done in the following order:
  671. * 1. changing the batch
  672. * 2. sync percpu count on each CPU
  673. * 3. switch the policy
  674. */
  675. if (write) {
  676. t = *table;
  677. t.data = &new_policy;
  678. ret = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  679. if (ret || new_policy == -1)
  680. return ret;
  681. mm_compute_batch(new_policy);
  682. if (new_policy == OVERCOMMIT_NEVER)
  683. schedule_on_each_cpu(sync_overcommit_as);
  684. sysctl_overcommit_memory = new_policy;
  685. } else {
  686. ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
  687. }
  688. return ret;
  689. }
  690. int overcommit_kbytes_handler(struct ctl_table *table, int write, void *buffer,
  691. size_t *lenp, loff_t *ppos)
  692. {
  693. int ret;
  694. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  695. if (ret == 0 && write)
  696. sysctl_overcommit_ratio = 0;
  697. return ret;
  698. }
  699. /*
  700. * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
  701. */
  702. unsigned long vm_commit_limit(void)
  703. {
  704. unsigned long allowed;
  705. if (sysctl_overcommit_kbytes)
  706. allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
  707. else
  708. allowed = ((totalram_pages() - hugetlb_total_pages())
  709. * sysctl_overcommit_ratio / 100);
  710. allowed += total_swap_pages;
  711. return allowed;
  712. }
  713. /*
  714. * Make sure vm_committed_as in one cacheline and not cacheline shared with
  715. * other variables. It can be updated by several CPUs frequently.
  716. */
  717. struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
  718. /*
  719. * The global memory commitment made in the system can be a metric
  720. * that can be used to drive ballooning decisions when Linux is hosted
  721. * as a guest. On Hyper-V, the host implements a policy engine for dynamically
  722. * balancing memory across competing virtual machines that are hosted.
  723. * Several metrics drive this policy engine including the guest reported
  724. * memory commitment.
  725. *
  726. * The time cost of this is very low for small platforms, and for big
  727. * platform like a 2S/36C/72T Skylake server, in worst case where
  728. * vm_committed_as's spinlock is under severe contention, the time cost
  729. * could be about 30~40 microseconds.
  730. */
  731. unsigned long vm_memory_committed(void)
  732. {
  733. return percpu_counter_sum_positive(&vm_committed_as);
  734. }
  735. EXPORT_SYMBOL_GPL(vm_memory_committed);
  736. /*
  737. * Check that a process has enough memory to allocate a new virtual
  738. * mapping. 0 means there is enough memory for the allocation to
  739. * succeed and -ENOMEM implies there is not.
  740. *
  741. * We currently support three overcommit policies, which are set via the
  742. * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting.rst
  743. *
  744. * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
  745. * Additional code 2002 Jul 20 by Robert Love.
  746. *
  747. * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
  748. *
  749. * Note this is a helper function intended to be used by LSMs which
  750. * wish to use this logic.
  751. */
  752. int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
  753. {
  754. long allowed;
  755. vm_acct_memory(pages);
  756. /*
  757. * Sometimes we want to use more memory than we have
  758. */
  759. if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
  760. return 0;
  761. if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
  762. if (pages > totalram_pages() + total_swap_pages)
  763. goto error;
  764. return 0;
  765. }
  766. allowed = vm_commit_limit();
  767. /*
  768. * Reserve some for root
  769. */
  770. if (!cap_sys_admin)
  771. allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
  772. /*
  773. * Don't let a single process grow so big a user can't recover
  774. */
  775. if (mm) {
  776. long reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
  777. allowed -= min_t(long, mm->total_vm / 32, reserve);
  778. }
  779. if (percpu_counter_read_positive(&vm_committed_as) < allowed)
  780. return 0;
  781. error:
  782. vm_unacct_memory(pages);
  783. return -ENOMEM;
  784. }
  785. /**
  786. * get_cmdline() - copy the cmdline value to a buffer.
  787. * @task: the task whose cmdline value to copy.
  788. * @buffer: the buffer to copy to.
  789. * @buflen: the length of the buffer. Larger cmdline values are truncated
  790. * to this length.
  791. *
  792. * Return: the size of the cmdline field copied. Note that the copy does
  793. * not guarantee an ending NULL byte.
  794. */
  795. int get_cmdline(struct task_struct *task, char *buffer, int buflen)
  796. {
  797. int res = 0;
  798. unsigned int len;
  799. struct mm_struct *mm = get_task_mm(task);
  800. unsigned long arg_start, arg_end, env_start, env_end;
  801. if (!mm)
  802. goto out;
  803. if (!mm->arg_end)
  804. goto out_mm; /* Shh! No looking before we're done */
  805. spin_lock(&mm->arg_lock);
  806. arg_start = mm->arg_start;
  807. arg_end = mm->arg_end;
  808. env_start = mm->env_start;
  809. env_end = mm->env_end;
  810. spin_unlock(&mm->arg_lock);
  811. len = arg_end - arg_start;
  812. if (len > buflen)
  813. len = buflen;
  814. res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
  815. /*
  816. * If the nul at the end of args has been overwritten, then
  817. * assume application is using setproctitle(3).
  818. */
  819. if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
  820. len = strnlen(buffer, res);
  821. if (len < res) {
  822. res = len;
  823. } else {
  824. len = env_end - env_start;
  825. if (len > buflen - res)
  826. len = buflen - res;
  827. res += access_process_vm(task, env_start,
  828. buffer+res, len,
  829. FOLL_FORCE);
  830. res = strnlen(buffer, res);
  831. }
  832. }
  833. out_mm:
  834. mmput(mm);
  835. out:
  836. return res;
  837. }
  838. int __weak memcmp_pages(struct page *page1, struct page *page2)
  839. {
  840. char *addr1, *addr2;
  841. int ret;
  842. addr1 = kmap_atomic(page1);
  843. addr2 = kmap_atomic(page2);
  844. ret = memcmp(addr1, addr2, PAGE_SIZE);
  845. kunmap_atomic(addr2);
  846. kunmap_atomic(addr1);
  847. return ret;
  848. }