blob: ace2aea69f1a834ca7526a1bfa4070205b82579e [file] [log] [blame]
Matt Mackall30992c92006-01-08 01:01:43 -08001#include <linux/slab.h>
2#include <linux/string.h>
3#include <linux/module.h>
Davi Arnaut96840aa2006-03-24 03:18:42 -08004#include <linux/err.h>
5#include <asm/uaccess.h>
Matt Mackall30992c92006-01-08 01:01:43 -08006
7/**
Pekka Enberg40c07ae2006-03-25 03:06:43 -08008 * __kzalloc - allocate memory. The memory is set to zero.
Matt Mackall30992c92006-01-08 01:01:43 -08009 * @size: how many bytes of memory are required.
10 * @flags: the type of memory to allocate.
11 */
Pekka Enberg40c07ae2006-03-25 03:06:43 -080012void *__kzalloc(size_t size, gfp_t flags)
Matt Mackall30992c92006-01-08 01:01:43 -080013{
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -070014 void *ret = kmalloc_track_caller(size, flags);
Matt Mackall30992c92006-01-08 01:01:43 -080015 if (ret)
16 memset(ret, 0, size);
17 return ret;
18}
Pekka Enberg40c07ae2006-03-25 03:06:43 -080019EXPORT_SYMBOL(__kzalloc);
Matt Mackall30992c92006-01-08 01:01:43 -080020
21/*
22 * kstrdup - allocate space for and copy an existing string
23 *
24 * @s: the string to duplicate
25 * @gfp: the GFP mask used in the kmalloc() call when allocating memory
26 */
27char *kstrdup(const char *s, gfp_t gfp)
28{
29 size_t len;
30 char *buf;
31
32 if (!s)
33 return NULL;
34
35 len = strlen(s) + 1;
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -070036 buf = kmalloc_track_caller(len, gfp);
Matt Mackall30992c92006-01-08 01:01:43 -080037 if (buf)
38 memcpy(buf, s, len);
39 return buf;
40}
41EXPORT_SYMBOL(kstrdup);
Davi Arnaut96840aa2006-03-24 03:18:42 -080042
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -070043/**
44 * kmemdup - duplicate region of memory
45 *
46 * @src: memory region to duplicate
47 * @len: memory region length
48 * @gfp: GFP mask to use
49 */
50void *kmemdup(const void *src, size_t len, gfp_t gfp)
51{
52 void *p;
53
Christoph Hellwig1d2c8ee2006-10-04 02:15:25 -070054 p = kmalloc_track_caller(len, gfp);
Alexey Dobriyan1a2f67b2006-09-30 23:27:20 -070055 if (p)
56 memcpy(p, src, len);
57 return p;
58}
59EXPORT_SYMBOL(kmemdup);
60
Davi Arnaut96840aa2006-03-24 03:18:42 -080061/*
62 * strndup_user - duplicate an existing string from user space
63 *
64 * @s: The string to duplicate
65 * @n: Maximum number of bytes to copy, including the trailing NUL.
66 */
67char *strndup_user(const char __user *s, long n)
68{
69 char *p;
70 long length;
71
72 length = strnlen_user(s, n);
73
74 if (!length)
75 return ERR_PTR(-EFAULT);
76
77 if (length > n)
78 return ERR_PTR(-EINVAL);
79
80 p = kmalloc(length, GFP_KERNEL);
81
82 if (!p)
83 return ERR_PTR(-ENOMEM);
84
85 if (copy_from_user(p, s, length)) {
86 kfree(p);
87 return ERR_PTR(-EFAULT);
88 }
89
90 p[length - 1] = '\0';
91
92 return p;
93}
94EXPORT_SYMBOL(strndup_user);