util.c 16 KB

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