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