util.c 16 KB

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