Back to home page

LXR

 
 

    


0001 #include <linux/mm.h>
0002 #include <linux/slab.h>
0003 #include <linux/string.h>
0004 #include <linux/compiler.h>
0005 #include <linux/export.h>
0006 #include <linux/err.h>
0007 #include <linux/sched.h>
0008 #include <linux/security.h>
0009 #include <linux/swap.h>
0010 #include <linux/swapops.h>
0011 #include <linux/mman.h>
0012 #include <linux/hugetlb.h>
0013 #include <linux/vmalloc.h>
0014 
0015 #include <asm/sections.h>
0016 #include <linux/uaccess.h>
0017 
0018 #include "internal.h"
0019 
0020 static inline int is_kernel_rodata(unsigned long addr)
0021 {
0022     return addr >= (unsigned long)__start_rodata &&
0023         addr < (unsigned long)__end_rodata;
0024 }
0025 
0026 /**
0027  * kfree_const - conditionally free memory
0028  * @x: pointer to the memory
0029  *
0030  * Function calls kfree only if @x is not in .rodata section.
0031  */
0032 void kfree_const(const void *x)
0033 {
0034     if (!is_kernel_rodata((unsigned long)x))
0035         kfree(x);
0036 }
0037 EXPORT_SYMBOL(kfree_const);
0038 
0039 /**
0040  * kstrdup - allocate space for and copy an existing string
0041  * @s: the string to duplicate
0042  * @gfp: the GFP mask used in the kmalloc() call when allocating memory
0043  */
0044 char *kstrdup(const char *s, gfp_t gfp)
0045 {
0046     size_t len;
0047     char *buf;
0048 
0049     if (!s)
0050         return NULL;
0051 
0052     len = strlen(s) + 1;
0053     buf = kmalloc_track_caller(len, gfp);
0054     if (buf)
0055         memcpy(buf, s, len);
0056     return buf;
0057 }
0058 EXPORT_SYMBOL(kstrdup);
0059 
0060 /**
0061  * kstrdup_const - conditionally duplicate an existing const string
0062  * @s: the string to duplicate
0063  * @gfp: the GFP mask used in the kmalloc() call when allocating memory
0064  *
0065  * Function returns source string if it is in .rodata section otherwise it
0066  * fallbacks to kstrdup.
0067  * Strings allocated by kstrdup_const should be freed by kfree_const.
0068  */
0069 const char *kstrdup_const(const char *s, gfp_t gfp)
0070 {
0071     if (is_kernel_rodata((unsigned long)s))
0072         return s;
0073 
0074     return kstrdup(s, gfp);
0075 }
0076 EXPORT_SYMBOL(kstrdup_const);
0077 
0078 /**
0079  * kstrndup - allocate space for and copy an existing string
0080  * @s: the string to duplicate
0081  * @max: read at most @max chars from @s
0082  * @gfp: the GFP mask used in the kmalloc() call when allocating memory
0083  */
0084 char *kstrndup(const char *s, size_t max, gfp_t gfp)
0085 {
0086     size_t len;
0087     char *buf;
0088 
0089     if (!s)
0090         return NULL;
0091 
0092     len = strnlen(s, max);
0093     buf = kmalloc_track_caller(len+1, gfp);
0094     if (buf) {
0095         memcpy(buf, s, len);
0096         buf[len] = '\0';
0097     }
0098     return buf;
0099 }
0100 EXPORT_SYMBOL(kstrndup);
0101 
0102 /**
0103  * kmemdup - duplicate region of memory
0104  *
0105  * @src: memory region to duplicate
0106  * @len: memory region length
0107  * @gfp: GFP mask to use
0108  */
0109 void *kmemdup(const void *src, size_t len, gfp_t gfp)
0110 {
0111     void *p;
0112 
0113     p = kmalloc_track_caller(len, gfp);
0114     if (p)
0115         memcpy(p, src, len);
0116     return p;
0117 }
0118 EXPORT_SYMBOL(kmemdup);
0119 
0120 /**
0121  * memdup_user - duplicate memory region from user space
0122  *
0123  * @src: source address in user space
0124  * @len: number of bytes to copy
0125  *
0126  * Returns an ERR_PTR() on failure.
0127  */
0128 void *memdup_user(const void __user *src, size_t len)
0129 {
0130     void *p;
0131 
0132     /*
0133      * Always use GFP_KERNEL, since copy_from_user() can sleep and
0134      * cause pagefault, which makes it pointless to use GFP_NOFS
0135      * or GFP_ATOMIC.
0136      */
0137     p = kmalloc_track_caller(len, GFP_KERNEL);
0138     if (!p)
0139         return ERR_PTR(-ENOMEM);
0140 
0141     if (copy_from_user(p, src, len)) {
0142         kfree(p);
0143         return ERR_PTR(-EFAULT);
0144     }
0145 
0146     return p;
0147 }
0148 EXPORT_SYMBOL(memdup_user);
0149 
0150 /*
0151  * strndup_user - duplicate an existing string from user space
0152  * @s: The string to duplicate
0153  * @n: Maximum number of bytes to copy, including the trailing NUL.
0154  */
0155 char *strndup_user(const char __user *s, long n)
0156 {
0157     char *p;
0158     long length;
0159 
0160     length = strnlen_user(s, n);
0161 
0162     if (!length)
0163         return ERR_PTR(-EFAULT);
0164 
0165     if (length > n)
0166         return ERR_PTR(-EINVAL);
0167 
0168     p = memdup_user(s, length);
0169 
0170     if (IS_ERR(p))
0171         return p;
0172 
0173     p[length - 1] = '\0';
0174 
0175     return p;
0176 }
0177 EXPORT_SYMBOL(strndup_user);
0178 
0179 /**
0180  * memdup_user_nul - duplicate memory region from user space and NUL-terminate
0181  *
0182  * @src: source address in user space
0183  * @len: number of bytes to copy
0184  *
0185  * Returns an ERR_PTR() on failure.
0186  */
0187 void *memdup_user_nul(const void __user *src, size_t len)
0188 {
0189     char *p;
0190 
0191     /*
0192      * Always use GFP_KERNEL, since copy_from_user() can sleep and
0193      * cause pagefault, which makes it pointless to use GFP_NOFS
0194      * or GFP_ATOMIC.
0195      */
0196     p = kmalloc_track_caller(len + 1, GFP_KERNEL);
0197     if (!p)
0198         return ERR_PTR(-ENOMEM);
0199 
0200     if (copy_from_user(p, src, len)) {
0201         kfree(p);
0202         return ERR_PTR(-EFAULT);
0203     }
0204     p[len] = '\0';
0205 
0206     return p;
0207 }
0208 EXPORT_SYMBOL(memdup_user_nul);
0209 
0210 void __vma_link_list(struct mm_struct *mm, struct vm_area_struct *vma,
0211         struct vm_area_struct *prev, struct rb_node *rb_parent)
0212 {
0213     struct vm_area_struct *next;
0214 
0215     vma->vm_prev = prev;
0216     if (prev) {
0217         next = prev->vm_next;
0218         prev->vm_next = vma;
0219     } else {
0220         mm->mmap = vma;
0221         if (rb_parent)
0222             next = rb_entry(rb_parent,
0223                     struct vm_area_struct, vm_rb);
0224         else
0225             next = NULL;
0226     }
0227     vma->vm_next = next;
0228     if (next)
0229         next->vm_prev = vma;
0230 }
0231 
0232 /* Check if the vma is being used as a stack by this task */
0233 int vma_is_stack_for_current(struct vm_area_struct *vma)
0234 {
0235     struct task_struct * __maybe_unused t = current;
0236 
0237     return (vma->vm_start <= KSTK_ESP(t) && vma->vm_end >= KSTK_ESP(t));
0238 }
0239 
0240 #if defined(CONFIG_MMU) && !defined(HAVE_ARCH_PICK_MMAP_LAYOUT)
0241 void arch_pick_mmap_layout(struct mm_struct *mm)
0242 {
0243     mm->mmap_base = TASK_UNMAPPED_BASE;
0244     mm->get_unmapped_area = arch_get_unmapped_area;
0245 }
0246 #endif
0247 
0248 /*
0249  * Like get_user_pages_fast() except its IRQ-safe in that it won't fall
0250  * back to the regular GUP.
0251  * If the architecture not support this function, simply return with no
0252  * page pinned
0253  */
0254 int __weak __get_user_pages_fast(unsigned long start,
0255                  int nr_pages, int write, struct page **pages)
0256 {
0257     return 0;
0258 }
0259 EXPORT_SYMBOL_GPL(__get_user_pages_fast);
0260 
0261 /**
0262  * get_user_pages_fast() - pin user pages in memory
0263  * @start:  starting user address
0264  * @nr_pages:   number of pages from start to pin
0265  * @write:  whether pages will be written to
0266  * @pages:  array that receives pointers to the pages pinned.
0267  *      Should be at least nr_pages long.
0268  *
0269  * Returns number of pages pinned. This may be fewer than the number
0270  * requested. If nr_pages is 0 or negative, returns 0. If no pages
0271  * were pinned, returns -errno.
0272  *
0273  * get_user_pages_fast provides equivalent functionality to get_user_pages,
0274  * operating on current and current->mm, with force=0 and vma=NULL. However
0275  * unlike get_user_pages, it must be called without mmap_sem held.
0276  *
0277  * get_user_pages_fast may take mmap_sem and page table locks, so no
0278  * assumptions can be made about lack of locking. get_user_pages_fast is to be
0279  * implemented in a way that is advantageous (vs get_user_pages()) when the
0280  * user memory area is already faulted in and present in ptes. However if the
0281  * pages have to be faulted in, it may turn out to be slightly slower so
0282  * callers need to carefully consider what to use. On many architectures,
0283  * get_user_pages_fast simply falls back to get_user_pages.
0284  */
0285 int __weak get_user_pages_fast(unsigned long start,
0286                 int nr_pages, int write, struct page **pages)
0287 {
0288     return get_user_pages_unlocked(start, nr_pages, pages,
0289                        write ? FOLL_WRITE : 0);
0290 }
0291 EXPORT_SYMBOL_GPL(get_user_pages_fast);
0292 
0293 unsigned long vm_mmap_pgoff(struct file *file, unsigned long addr,
0294     unsigned long len, unsigned long prot,
0295     unsigned long flag, unsigned long pgoff)
0296 {
0297     unsigned long ret;
0298     struct mm_struct *mm = current->mm;
0299     unsigned long populate;
0300 
0301     ret = security_mmap_file(file, prot, flag);
0302     if (!ret) {
0303         if (down_write_killable(&mm->mmap_sem))
0304             return -EINTR;
0305         ret = do_mmap_pgoff(file, addr, len, prot, flag, pgoff,
0306                     &populate);
0307         up_write(&mm->mmap_sem);
0308         if (populate)
0309             mm_populate(ret, populate);
0310     }
0311     return ret;
0312 }
0313 
0314 unsigned long vm_mmap(struct file *file, unsigned long addr,
0315     unsigned long len, unsigned long prot,
0316     unsigned long flag, unsigned long offset)
0317 {
0318     if (unlikely(offset + PAGE_ALIGN(len) < offset))
0319         return -EINVAL;
0320     if (unlikely(offset_in_page(offset)))
0321         return -EINVAL;
0322 
0323     return vm_mmap_pgoff(file, addr, len, prot, flag, offset >> PAGE_SHIFT);
0324 }
0325 EXPORT_SYMBOL(vm_mmap);
0326 
0327 void kvfree(const void *addr)
0328 {
0329     if (is_vmalloc_addr(addr))
0330         vfree(addr);
0331     else
0332         kfree(addr);
0333 }
0334 EXPORT_SYMBOL(kvfree);
0335 
0336 static inline void *__page_rmapping(struct page *page)
0337 {
0338     unsigned long mapping;
0339 
0340     mapping = (unsigned long)page->mapping;
0341     mapping &= ~PAGE_MAPPING_FLAGS;
0342 
0343     return (void *)mapping;
0344 }
0345 
0346 /* Neutral page->mapping pointer to address_space or anon_vma or other */
0347 void *page_rmapping(struct page *page)
0348 {
0349     page = compound_head(page);
0350     return __page_rmapping(page);
0351 }
0352 
0353 /*
0354  * Return true if this page is mapped into pagetables.
0355  * For compound page it returns true if any subpage of compound page is mapped.
0356  */
0357 bool page_mapped(struct page *page)
0358 {
0359     int i;
0360 
0361     if (likely(!PageCompound(page)))
0362         return atomic_read(&page->_mapcount) >= 0;
0363     page = compound_head(page);
0364     if (atomic_read(compound_mapcount_ptr(page)) >= 0)
0365         return true;
0366     if (PageHuge(page))
0367         return false;
0368     for (i = 0; i < hpage_nr_pages(page); i++) {
0369         if (atomic_read(&page[i]._mapcount) >= 0)
0370             return true;
0371     }
0372     return false;
0373 }
0374 EXPORT_SYMBOL(page_mapped);
0375 
0376 struct anon_vma *page_anon_vma(struct page *page)
0377 {
0378     unsigned long mapping;
0379 
0380     page = compound_head(page);
0381     mapping = (unsigned long)page->mapping;
0382     if ((mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
0383         return NULL;
0384     return __page_rmapping(page);
0385 }
0386 
0387 struct address_space *page_mapping(struct page *page)
0388 {
0389     struct address_space *mapping;
0390 
0391     page = compound_head(page);
0392 
0393     /* This happens if someone calls flush_dcache_page on slab page */
0394     if (unlikely(PageSlab(page)))
0395         return NULL;
0396 
0397     if (unlikely(PageSwapCache(page))) {
0398         swp_entry_t entry;
0399 
0400         entry.val = page_private(page);
0401         return swap_address_space(entry);
0402     }
0403 
0404     mapping = page->mapping;
0405     if ((unsigned long)mapping & PAGE_MAPPING_ANON)
0406         return NULL;
0407 
0408     return (void *)((unsigned long)mapping & ~PAGE_MAPPING_FLAGS);
0409 }
0410 EXPORT_SYMBOL(page_mapping);
0411 
0412 /* Slow path of page_mapcount() for compound pages */
0413 int __page_mapcount(struct page *page)
0414 {
0415     int ret;
0416 
0417     ret = atomic_read(&page->_mapcount) + 1;
0418     /*
0419      * For file THP page->_mapcount contains total number of mapping
0420      * of the page: no need to look into compound_mapcount.
0421      */
0422     if (!PageAnon(page) && !PageHuge(page))
0423         return ret;
0424     page = compound_head(page);
0425     ret += atomic_read(compound_mapcount_ptr(page)) + 1;
0426     if (PageDoubleMap(page))
0427         ret--;
0428     return ret;
0429 }
0430 EXPORT_SYMBOL_GPL(__page_mapcount);
0431 
0432 int sysctl_overcommit_memory __read_mostly = OVERCOMMIT_GUESS;
0433 int sysctl_overcommit_ratio __read_mostly = 50;
0434 unsigned long sysctl_overcommit_kbytes __read_mostly;
0435 int sysctl_max_map_count __read_mostly = DEFAULT_MAX_MAP_COUNT;
0436 unsigned long sysctl_user_reserve_kbytes __read_mostly = 1UL << 17; /* 128MB */
0437 unsigned long sysctl_admin_reserve_kbytes __read_mostly = 1UL << 13; /* 8MB */
0438 
0439 int overcommit_ratio_handler(struct ctl_table *table, int write,
0440                  void __user *buffer, size_t *lenp,
0441                  loff_t *ppos)
0442 {
0443     int ret;
0444 
0445     ret = proc_dointvec(table, write, buffer, lenp, ppos);
0446     if (ret == 0 && write)
0447         sysctl_overcommit_kbytes = 0;
0448     return ret;
0449 }
0450 
0451 int overcommit_kbytes_handler(struct ctl_table *table, int write,
0452                  void __user *buffer, size_t *lenp,
0453                  loff_t *ppos)
0454 {
0455     int ret;
0456 
0457     ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
0458     if (ret == 0 && write)
0459         sysctl_overcommit_ratio = 0;
0460     return ret;
0461 }
0462 
0463 /*
0464  * Committed memory limit enforced when OVERCOMMIT_NEVER policy is used
0465  */
0466 unsigned long vm_commit_limit(void)
0467 {
0468     unsigned long allowed;
0469 
0470     if (sysctl_overcommit_kbytes)
0471         allowed = sysctl_overcommit_kbytes >> (PAGE_SHIFT - 10);
0472     else
0473         allowed = ((totalram_pages - hugetlb_total_pages())
0474                * sysctl_overcommit_ratio / 100);
0475     allowed += total_swap_pages;
0476 
0477     return allowed;
0478 }
0479 
0480 /*
0481  * Make sure vm_committed_as in one cacheline and not cacheline shared with
0482  * other variables. It can be updated by several CPUs frequently.
0483  */
0484 struct percpu_counter vm_committed_as ____cacheline_aligned_in_smp;
0485 
0486 /*
0487  * The global memory commitment made in the system can be a metric
0488  * that can be used to drive ballooning decisions when Linux is hosted
0489  * as a guest. On Hyper-V, the host implements a policy engine for dynamically
0490  * balancing memory across competing virtual machines that are hosted.
0491  * Several metrics drive this policy engine including the guest reported
0492  * memory commitment.
0493  */
0494 unsigned long vm_memory_committed(void)
0495 {
0496     return percpu_counter_read_positive(&vm_committed_as);
0497 }
0498 EXPORT_SYMBOL_GPL(vm_memory_committed);
0499 
0500 /*
0501  * Check that a process has enough memory to allocate a new virtual
0502  * mapping. 0 means there is enough memory for the allocation to
0503  * succeed and -ENOMEM implies there is not.
0504  *
0505  * We currently support three overcommit policies, which are set via the
0506  * vm.overcommit_memory sysctl.  See Documentation/vm/overcommit-accounting
0507  *
0508  * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
0509  * Additional code 2002 Jul 20 by Robert Love.
0510  *
0511  * cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
0512  *
0513  * Note this is a helper function intended to be used by LSMs which
0514  * wish to use this logic.
0515  */
0516 int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
0517 {
0518     long free, allowed, reserve;
0519 
0520     VM_WARN_ONCE(percpu_counter_read(&vm_committed_as) <
0521             -(s64)vm_committed_as_batch * num_online_cpus(),
0522             "memory commitment underflow");
0523 
0524     vm_acct_memory(pages);
0525 
0526     /*
0527      * Sometimes we want to use more memory than we have
0528      */
0529     if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
0530         return 0;
0531 
0532     if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
0533         free = global_page_state(NR_FREE_PAGES);
0534         free += global_node_page_state(NR_FILE_PAGES);
0535 
0536         /*
0537          * shmem pages shouldn't be counted as free in this
0538          * case, they can't be purged, only swapped out, and
0539          * that won't affect the overall amount of available
0540          * memory in the system.
0541          */
0542         free -= global_node_page_state(NR_SHMEM);
0543 
0544         free += get_nr_swap_pages();
0545 
0546         /*
0547          * Any slabs which are created with the
0548          * SLAB_RECLAIM_ACCOUNT flag claim to have contents
0549          * which are reclaimable, under pressure.  The dentry
0550          * cache and most inode caches should fall into this
0551          */
0552         free += global_page_state(NR_SLAB_RECLAIMABLE);
0553 
0554         /*
0555          * Leave reserved pages. The pages are not for anonymous pages.
0556          */
0557         if (free <= totalreserve_pages)
0558             goto error;
0559         else
0560             free -= totalreserve_pages;
0561 
0562         /*
0563          * Reserve some for root
0564          */
0565         if (!cap_sys_admin)
0566             free -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
0567 
0568         if (free > pages)
0569             return 0;
0570 
0571         goto error;
0572     }
0573 
0574     allowed = vm_commit_limit();
0575     /*
0576      * Reserve some for root
0577      */
0578     if (!cap_sys_admin)
0579         allowed -= sysctl_admin_reserve_kbytes >> (PAGE_SHIFT - 10);
0580 
0581     /*
0582      * Don't let a single process grow so big a user can't recover
0583      */
0584     if (mm) {
0585         reserve = sysctl_user_reserve_kbytes >> (PAGE_SHIFT - 10);
0586         allowed -= min_t(long, mm->total_vm / 32, reserve);
0587     }
0588 
0589     if (percpu_counter_read_positive(&vm_committed_as) < allowed)
0590         return 0;
0591 error:
0592     vm_unacct_memory(pages);
0593 
0594     return -ENOMEM;
0595 }
0596 
0597 /**
0598  * get_cmdline() - copy the cmdline value to a buffer.
0599  * @task:     the task whose cmdline value to copy.
0600  * @buffer:   the buffer to copy to.
0601  * @buflen:   the length of the buffer. Larger cmdline values are truncated
0602  *            to this length.
0603  * Returns the size of the cmdline field copied. Note that the copy does
0604  * not guarantee an ending NULL byte.
0605  */
0606 int get_cmdline(struct task_struct *task, char *buffer, int buflen)
0607 {
0608     int res = 0;
0609     unsigned int len;
0610     struct mm_struct *mm = get_task_mm(task);
0611     unsigned long arg_start, arg_end, env_start, env_end;
0612     if (!mm)
0613         goto out;
0614     if (!mm->arg_end)
0615         goto out_mm;    /* Shh! No looking before we're done */
0616 
0617     down_read(&mm->mmap_sem);
0618     arg_start = mm->arg_start;
0619     arg_end = mm->arg_end;
0620     env_start = mm->env_start;
0621     env_end = mm->env_end;
0622     up_read(&mm->mmap_sem);
0623 
0624     len = arg_end - arg_start;
0625 
0626     if (len > buflen)
0627         len = buflen;
0628 
0629     res = access_process_vm(task, arg_start, buffer, len, FOLL_FORCE);
0630 
0631     /*
0632      * If the nul at the end of args has been overwritten, then
0633      * assume application is using setproctitle(3).
0634      */
0635     if (res > 0 && buffer[res-1] != '\0' && len < buflen) {
0636         len = strnlen(buffer, res);
0637         if (len < res) {
0638             res = len;
0639         } else {
0640             len = env_end - env_start;
0641             if (len > buflen - res)
0642                 len = buflen - res;
0643             res += access_process_vm(task, env_start,
0644                          buffer+res, len,
0645                          FOLL_FORCE);
0646             res = strnlen(buffer, res);
0647         }
0648     }
0649 out_mm:
0650     mmput(mm);
0651 out:
0652     return res;
0653 }