util.c 16 KB

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