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