util.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. #include <linux/mm.h>
  2. #include <linux/slab.h>
  3. #include <linux/string.h>
  4. #include <linux/compiler.h>
  5. #include <linux/export.h>
  6. #include <linux/err.h>
  7. #include <linux/sched.h>
  8. #include <linux/sched/mm.h>
  9. #include <linux/security.h>
  10. #include <linux/swap.h>
  11. #include <linux/swapops.h>
  12. #include <linux/mman.h>
  13. #include <linux/hugetlb.h>
  14. #include <linux/vmalloc.h>
  15. #include <linux/userfaultfd_k.h>
  16. #include <asm/sections.h>
  17. #include <linux/uaccess.h>
  18. #include "internal.h"
  19. static inline int is_kernel_rodata(unsigned long addr)
  20. {
  21. return addr >= (unsigned long)__start_rodata &&
  22. addr < (unsigned long)__end_rodata;
  23. }
  24. /**
  25. * kfree_const - conditionally free memory
  26. * @x: pointer to the memory
  27. *
  28. * Function calls kfree only if @x is not in .rodata section.
  29. */
  30. void kfree_const(const void *x)
  31. {
  32. if (!is_kernel_rodata((unsigned long)x))
  33. kfree(x);
  34. }
  35. EXPORT_SYMBOL(kfree_const);
  36. /**
  37. * kstrdup - allocate space for and copy an existing string
  38. * @s: the string to duplicate
  39. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  40. */
  41. char *kstrdup(const char *s, gfp_t gfp)
  42. {
  43. size_t len;
  44. char *buf;
  45. if (!s)
  46. return NULL;
  47. len = strlen(s) + 1;
  48. buf = kmalloc_track_caller(len, gfp);
  49. if (buf)
  50. memcpy(buf, s, len);
  51. return buf;
  52. }
  53. EXPORT_SYMBOL(kstrdup);
  54. /**
  55. * kstrdup_const - conditionally duplicate an existing const string
  56. * @s: the string to duplicate
  57. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  58. *
  59. * Function returns source string if it is in .rodata section otherwise it
  60. * fallbacks to kstrdup.
  61. * Strings allocated by kstrdup_const should be freed by kfree_const.
  62. */
  63. const char *kstrdup_const(const char *s, gfp_t gfp)
  64. {
  65. if (is_kernel_rodata((unsigned long)s))
  66. return s;
  67. return kstrdup(s, gfp);
  68. }
  69. EXPORT_SYMBOL(kstrdup_const);
  70. /**
  71. * kstrndup - allocate space for and copy an existing string
  72. * @s: the string to duplicate
  73. * @max: read at most @max chars from @s
  74. * @gfp: the GFP mask used in the kmalloc() call when allocating memory
  75. */
  76. char *kstrndup(const char *s, size_t max, gfp_t gfp)
  77. {
  78. size_t len;
  79. char *buf;
  80. if (!s)
  81. return NULL;
  82. len = strnlen(s, max);
  83. buf = kmalloc_track_caller(len+1, gfp);
  84. if (buf) {
  85. memcpy(buf, s, len);
  86. buf[len] = '\0';
  87. }
  88. return buf;
  89. }
  90. EXPORT_SYMBOL(kstrndup);
  91. /**
  92. * kmemdup - duplicate region of memory
  93. *
  94. * @src: memory region to duplicate
  95. * @len: memory region length
  96. * @gfp: GFP mask to use
  97. */
  98. void *kmemdup(const void *src, size_t len, gfp_t gfp)
  99. {
  100. void *p;
  101. p = kmalloc_track_caller(len, gfp);
  102. if (p)
  103. memcpy(p, src, len);
  104. return p;
  105. }
  106. EXPORT_SYMBOL(kmemdup);
  107. /**
  108. * memdup_user - duplicate memory region from user space
  109. *
  110. * @src: source address in user space
  111. * @len: number of bytes to copy
  112. *
  113. * Returns an ERR_PTR() on failure.
  114. */
  115. void *memdup_user(const void __user *src, size_t len)
  116. {
  117. void *p;
  118. /*
  119. * Always use GFP_KERNEL, since copy_from_user() can sleep and
  120. * cause pagefault, which makes it pointless to use GFP_NOFS
  121. * or GFP_ATOMIC.
  122. */
  123. p = kmalloc_track_caller(len, GFP_KERNEL);
  124. if (!p)
  125. return ERR_PTR(-ENOMEM);
  126. if (copy_from_user(p, src, len)) {
  127. kfree(p);
  128. return ERR_PTR(-EFAULT);
  129. }
  130. return p;
  131. }
  132. EXPORT_SYMBOL(memdup_user);
  133. /*
  134. * strndup_user - duplicate an existing string from user space
  135. * @s: The string to duplicate
  136. * @n: Maximum number of bytes to copy, including the trailing NUL.
  137. */
  138. char *strndup_user(const char __user *s, long n)
  139. {
  140. char *p;
  141. long length;
  142. length = strnlen_user(s, n);
  143. if (!length)
  144. return ERR_PTR(-EFAULT);
  145. if (length > n)
  146. return ERR_PTR(-EINVAL);
  147. p = memdup_user(s, length);
  148. if (IS_ERR(p))
  149. return p;
  150. p[length - 1] = '\0';
  151. return p;
  152. }
  153. EXPORT_SYMBOL(strndup_user);
  154. /**
  155. * memdup_user_nul - duplicate memory region from user space and NUL-terminate
  156. *
  157. * @src: source address in user space
  158. * @len: number of bytes to copy
  159. *
  160. * Returns an ERR_PTR() on failure.
  161. */
  162. void *memdup_user_nul(const void __user *src, size_t len)
  163. {
  164. char *p;
  165. /*
  166. * Always use GFP_KERNEL, since copy_from_user() can sleep and
  167. * cause pagefault, which makes it pointless to use GFP_NOFS
  168. * or GFP_ATOMIC.
  169. */
  170. p = kmalloc_track_caller(len + 1, GFP_KERNEL);
  171. if (!p)
  172. return ERR_PTR(-ENOMEM);
  173. if (copy_from_user(p, src, len)) {
  174. kfree(p);
  175. return ERR_PTR(-EFAULT);
  176. }
  177. p[len] = '\0';
  178. return p;
  179. }
  180. EXPORT_SYMBOL(memdup_user_nul);
  181. void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
  182. struct vm_area_struct *prev, struct rb_node *rb_parent)
  183. {
  184. struct vm_area_struct *next;
  185. vma->vm_prev = prev;
  186. if (prev) {
  187. next = prev->vm_next;
  188. prev->vm_next = vma;
  189. } else {
  190. mm->mmap = vma;
  191. if (rb_parent)
  192. next = rb_entry(rb_parent,
  193. struct vm_area_struct, vm_rb);
  194. else
  195. next = NULL;
  196. }
  197. vma->vm_next = next;
  198. if (next)
  199. next->vm_prev = vma;
  200. }
  201. /* Check if the vma is being used as a stack by this task */
  202. int vma_is_stack_for_current(struct vm_area_struct *vma)
  203. {
  204. struct task_struct * __maybe_unused t = current;
  205. return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
  206. }
  207. #if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
  208. void arch_pick_mmap_layout(struct mm_struct *mm)
  209. {
  210. mm->mmap_base = TASK_UNMAPPED_BASE;
  211. mm->get_unmapped_area = arch_get_unmapped_area;
  212. }
  213. #endif
  214. /*
  215. * Like get_user_pages_fast() except its IRQ-safe in that it won't fall
  216. * back to the regular GUP.
  217. * If the architecture not support this function, simply return with no
  218. * page pinned
  219. */
  220. int __weak __get_user_pages_fast(unsigned long start,
  221. int nr_pages, int write, struct page **pages)
  222. {
  223. return 0;
  224. }
  225. EXPORT_SYMBOL_GPL(__get_user_pages_fast);
  226. /**
  227. * get_user_pages_fast() - pin user pages in memory
  228. * @start: starting user address
  229. * @nr_pages: number of pages from start to pin
  230. * @write: whether pages will be written to
  231. * @pages: array that receives pointers to the pages pinned.
  232. * Should be at least nr_pages long.
  233. *
  234. * Returns number of pages pinned. This may be fewer than the number
  235. * requested. If nr_pages is 0 or negative, returns 0. If no pages
  236. * were pinned, returns -errno.
  237. *
  238. * get_user_pages_fast provides equivalent functionality to get_user_pages,
  239. * operating on current and current->mm, with force=0 and vma=NULL. However
  240. * unlike get_user_pages, it must be called without mmap_sem held.
  241. *
  242. * get_user_pages_fast may take mmap_sem and page table locks, so no
  243. * assumptions can be made about lack of locking. get_user_pages_fast is to be
  244. * implemented in a way that is advantageous (vs get_user_pages()) when the
  245. * user memory area is already faulted in and present in ptes. However if the
  246. * pages have to be faulted in, it may turn out to be slightly slower so
  247. * callers need to carefully consider what to use. On many architectures,
  248. * get_user_pages_fast simply falls back to get_user_pages.
  249. */
  250. int __weak get_user_pages_fast(unsigned long start,
  251. int nr_pages, int write, struct page **pages)
  252. {
  253. return get_user_pages_unlocked(start, nr_pages, pages,
  254. write ? FOLL_WRITE : 0);
  255. }
  256. EXPORT_SYMBOL_GPL(get_user_pages_fast);
  257. unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
  258. unsigned long len, unsigned long prot,
  259. unsigned long flag, unsigned long pgoff)
  260. {
  261. unsigned long ret;
  262. struct mm_struct *mm = current->mm;
  263. unsigned long populate;
  264. LIST_HEAD(uf);
  265. ret = security_mmap_file(file, prot, flag);
  266. if (!ret) {
  267. if (down_write_killable(&mm->mmap_sem))
  268. return -EINTR;
  269. ret = do_mmap_pgoff(file, addr, len, prot, flag, pgoff,
  270. &populate, &uf);
  271. up_write(&mm->mmap_sem);
  272. userfaultfd_unmap_complete(mm, &uf);
  273. if (populate)
  274. mm_populate(ret, populate);
  275. }
  276. return ret;
  277. }
  278. unsigned long vm_mmap(struct file *file, unsigned long addr,
  279. unsigned long len, unsigned long prot,
  280. unsigned long flag, unsigned long offset)
  281. {
  282. if (unlikely(offset + PAGE_ALIGN(len) < offset))
  283. return -EINVAL;
  284. if (unlikely(offset_in_page(offset)))
  285. return -EINVAL;
  286. return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
  287. }
  288. EXPORT_SYMBOL(vm_mmap);
  289. void kvfree(const void *addr)
  290. {
  291. if (is_vmalloc_addr(addr))
  292. vfree(addr);
  293. else
  294. kfree(addr);
  295. }
  296. EXPORT_SYMBOL(kvfree);
  297. static inline void *__page_rmapping(struct page *page)
  298. {
  299. unsigned long mapping;
  300. mapping = (unsigned long)page->mapping;
  301. mapping &= ~PAGE_MAPPING_FLAGS;
  302. return (void *)mapping;
  303. }
  304. /* Neutral page->mapping pointer to address_space or anon_vma or other */
  305. void *page_rmapping(struct page *page)
  306. {
  307. page = compound_head(page);
  308. return __page_rmapping(page);
  309. }
  310. /*
  311. * Return true if this page is mapped into pagetables.
  312. * For compound page it returns true if any subpage of compound page is mapped.
  313. */
  314. bool page_mapped(struct page *page)
  315. {
  316. int i;
  317. if (likely(!PageCompound(page)))
  318. return atomic_read(&page->_mapcount) >= 0;
  319. page = compound_head(page);
  320. if (atomic_read(compound_mapcount_ptr(page)) >= 0)
  321. return true;
  322. if (PageHuge(page))
  323. return false;
  324. for (i = 0; i < hpage_nr_pages(page); i++) {
  325. if (atomic_read(&page[i]._mapcount) >= 0)
  326. return true;
  327. }
  328. return false;
  329. }
  330. EXPORT_SYMBOL(page_mapped);
  331. struct anon_vma *page_anon_vma(struct page *page)
  332. {
  333. unsigned long mapping;
  334. page = compound_head(page);
  335. mapping = (unsigned long)page->mapping;
  336. if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
  337. return NULL;
  338. return __page_rmapping(page);
  339. }
  340. struct address_space *page_mapping(struct page *page)
  341. {
  342. struct address_space *mapping;
  343. page = compound_head(page);
  344. /* This happens if someone calls flush_dcache_page on slab page */
  345. if (unlikely(PageSlab(page)))
  346. return NULL;
  347. if (unlikely(PageSwapCache(page))) {
  348. swp_entry_t entry;
  349. entry.val = page_private(page);
  350. return swap_address_space(entry);
  351. }
  352. mapping = page->mapping;
  353. if ((unsigned long)mapping & PAGE_MAPPING_ANON)
  354. return NULL;
  355. return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
  356. }
  357. EXPORT_SYMBOL(page_mapping);
  358. /* Slow path of page_mapcount() for compound pages */
  359. int __page_mapcount(struct page *page)
  360. {
  361. int ret;
  362. ret = atomic_read(&page->_mapcount) + 1;
  363. /*
  364. * For file THP page->_mapcount contains total number of mapping
  365. * of the page: no need to look into compound_mapcount.
  366. */
  367. if (!PageAnon(page) && !PageHuge(page))
  368. return ret;
  369. page = compound_head(page);
  370. ret += atomic_read(compound_mapcount_ptr(page)) + 1;
  371. if (PageDoubleMap(page))
  372. ret--;
  373. return ret;
  374. }
  375. EXPORT_SYMBOL_GPL(__page_mapcount);
  376. int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
  377. int sysctl_overcommit_ratio __read_mostly = 50;
  378. unsigned long sysctl_overcommit_kbytes __read_mostly;
  379. int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
  380. unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
  381. unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
  382. int overcommit_ratio_handler(struct ctl_table *table, int write,
  383. void __user *buffer, size_t *lenp,
  384. loff_t *ppos)
  385. {
  386. int ret;
  387. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  388. if (ret == 0 && write)
  389. sysctl_overcommit_kbytes = 0;
  390. return ret;
  391. }
  392. int overcommit_kbytes_handler(struct ctl_table *table, int write,
  393. void __user *buffer, size_t *lenp,
  394. loff_t *ppos)
  395. {
  396. int ret;
  397. ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
  398. if (ret == 0 && write)
  399. sysctl_overcommit_ratio = 0;
  400. return ret;
  401. }
  402. /*
  403. * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
  404. */
  405. unsigned long vm_commit_limit(void)
  406. {
  407. unsigned long allowed;
  408. if (sysctl_overcommit_kbytes)
  409. allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
  410. else
  411. allowed = ((totalram_pages - hugetlb_total_pages())
  412. * sysctl_overcommit_ratio / 100);
  413. allowed += total_swap_pages;
  414. return allowed;
  415. }
  416. /*
  417. * Make sure vm_committed_as in one cacheline and not cacheline shared with
  418. * other variables. It can be updated by several CPUs frequently.
  419. */
  420. struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
  421. /*
  422. * The global memory commitment made in the system can be a metric
  423. * that can be used to drive ballooning decisions when Linux is hosted
  424. * as a guest. On Hyper-V, the host implements a policy engine for dynamically
  425. * balancing memory across competing virtual machines that are hosted.
  426. * Several metrics drive this policy engine including the guest reported
  427. * memory commitment.
  428. */
  429. unsigned long vm_memory_committed(void)
  430. {
  431. return percpu_counter_read_positive(&vm_committed_as);
  432. }
  433. EXPORT_SYMBOL_GPL(vm_memory_committed);
  434. /*
  435. * Check that a process has enough memory to allocate a new virtual
  436. * mapping. 0 means there is enough memory for the allocation to
  437. * succeed and -ENOMEM implies there is not.
  438. *
  439. * We currently support three overcommit policies, which are set via the
  440. * vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
  441. *
  442. * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
  443. * Additional code 2002 Jul 20 by Robert Love.
  444. *
  445. * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
  446. *
  447. * Note this is a helper function intended to be used by LSMs which
  448. * wish to use this logic.
  449. */
  450. int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
  451. {
  452. long free, allowed, reserve;
  453. VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
  454. -(s64)vm_committed_as_batch * num_online_cpus(),
  455. "memory commitment underflow");
  456. vm_acct_memory(pages);
  457. /*
  458. * Sometimes we want to use more memory than we have
  459. */
  460. if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
  461. return 0;
  462. if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
  463. free = global_page_state(NR_FREE_PAGES);
  464. free += global_node_page_state(NR_FILE_PAGES);
  465. /*
  466. * shmem pages shouldn't be counted as free in this
  467. * case, they can't be purged, only swapped out, and
  468. * that won't affect the overall amount of available
  469. * memory in the system.
  470. */
  471. free -= global_node_page_state(NR_SHMEM);
  472. free += get_nr_swap_pages();
  473. /*
  474. * Any slabs which are created with the
  475. * SLAB_RECLAIM_ACCOUNT flag claim to have contents
  476. * which are reclaimable, under pressure. The dentry
  477. * cache and most inode caches should fall into this
  478. */
  479. free += global_page_state(NR_SLAB_RECLAIMABLE);
  480. /*
  481. * Leave reserved pages. The pages are not for anonymous pages.
  482. */
  483. if (free <= totalreserve_pages)
  484. goto error;
  485. else
  486. free -= totalreserve_pages;
  487. /*
  488. * Reserve some for root
  489. */
  490. if (!cap_sys_admin)
  491. free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
  492. if (free > pages)
  493. return 0;
  494. goto error;
  495. }
  496. allowed = vm_commit_limit();
  497. /*
  498. * Reserve some for root
  499. */
  500. if (!cap_sys_admin)
  501. allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
  502. /*
  503. * Don't let a single process grow so big a user can't recover
  504. */
  505. if (mm) {
  506. reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
  507. allowed -= min_t(long, mm->total_vm / 32, reserve);
  508. }
  509. if (percpu_counter_read_positive(&vm_committed_as) < allowed)
  510. return 0;
  511. error:
  512. vm_unacct_memory(pages);
  513. return -ENOMEM;
  514. }
  515. /**
  516. * get_cmdline() - copy the cmdline value to a buffer.
  517. * @task: the task whose cmdline value to copy.
  518. * @buffer: the buffer to copy to.
  519. * @buflen: the length of the buffer. Larger cmdline values are truncated
  520. * to this length.
  521. * Returns the size of the cmdline field copied. Note that the copy does
  522. * not guarantee an ending NULL byte.
  523. */
  524. int get_cmdline(struct task_struct *task, char *buffer, int buflen)
  525. {
  526. int res = 0;
  527. unsigned int len;
  528. struct mm_struct *mm = get_task_mm(task);
  529. unsigned long arg_start, arg_end, env_start, env_end;
  530. if (!mm)
  531. goto out;
  532. if (!mm->arg_end)
  533. goto out_mm; /* Shh! No looking before we're done */
  534. down_read(&mm->mmap_sem);
  535. arg_start = mm->arg_start;
  536. arg_end = mm->arg_end;
  537. env_start = mm->env_start;
  538. env_end = mm->env_end;
  539. up_read(&mm->mmap_sem);
  540. len = arg_end - arg_start;
  541. if (len > buflen)
  542. len = buflen;
  543. res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
  544. /*
  545. * If the nul at the end of args has been overwritten, then
  546. * assume application is using setproctitle(3).
  547. */
  548. if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
  549. len = strnlen(buffer, res);
  550. if (len < res) {
  551. res = len;
  552. } else {
  553. len = env_end - env_start;
  554. if (len > buflen - res)
  555. len = buflen - res;
  556. res += access_process_vm(task, env_start,
  557. buffer+res, len,
  558. FOLL_FORCE);
  559. res = strnlen(buffer, res);
  560. }
  561. }
  562. out_mm:
  563. mmput(mm);
  564. out:
  565. return res;
  566. }