2 * User address space access functions.
4 * For licencing details see kernel-base/COPYING
7 #include <linux/highmem.h>
8 #include <linux/module.h>
10 #include <asm/word-at-a-time.h>
13 * best effort, GUP based copy_from_user() that is NMI-safe
16 copy_from_user_nmi(void *to, const void __user *from, unsigned long n)
18 unsigned long offset, addr = (unsigned long)from;
19 unsigned long size, len = 0;
25 ret = __get_user_pages_fast(addr, 1, 0, &page);
29 offset = addr & (PAGE_SIZE - 1);
30 size = min(PAGE_SIZE - offset, n - len);
32 map = kmap_atomic(page);
33 memcpy(to, map+offset, size);
45 EXPORT_SYMBOL_GPL(copy_from_user_nmi);
47 static inline unsigned long count_bytes(unsigned long mask)
49 mask = (mask - 1) & ~mask;
51 return count_masked_bytes(mask);
55 * Do a strncpy, return length of string without final '\0'.
56 * 'count' is the user-supplied count (return 'count' if we
57 * hit it), 'max' is the address space maximum (and we return
58 * -EFAULT if we hit it).
60 static inline long do_strncpy_from_user(char *dst, const char __user *src, long count, unsigned long max)
65 * Truncate 'max' to the user-specified limit, so that
66 * we only have one limit we need to check in the loop
71 while (max >= sizeof(unsigned long)) {
74 /* Fall back to byte-at-a-time if we get a page fault */
75 if (unlikely(__get_user(c,(unsigned long __user *)(src+res))))
77 /* This can write a few bytes past the NUL character, but that's ok */
78 *(unsigned long *)(dst+res) = c;
81 return res + count_bytes(c);
82 res += sizeof(unsigned long);
83 max -= sizeof(unsigned long);
89 if (unlikely(__get_user(c,src+res)))
99 * Uhhuh. We hit 'max'. But was that the user-specified maximum
100 * too? If so, that's ok - we got as much as the user asked for.
106 * Nope: we hit the address space limit, and we still had more
107 * characters the caller would have wanted. That's an EFAULT.
113 * strncpy_from_user: - Copy a NUL terminated string from userspace.
114 * @dst: Destination address, in kernel space. This buffer must be at
115 * least @count bytes long.
116 * @src: Source address, in user space.
117 * @count: Maximum number of bytes to copy, including the trailing NUL.
119 * Copies a NUL-terminated string from userspace to kernel space.
121 * On success, returns the length of the string (not including the trailing
124 * If access to userspace fails, returns -EFAULT (some data may have been
127 * If @count is smaller than the length of the string, copies @count bytes
128 * and returns @count.
131 strncpy_from_user(char *dst, const char __user *src, long count)
133 unsigned long max_addr, src_addr;
135 if (unlikely(count <= 0))
138 max_addr = current_thread_info()->addr_limit.seg;
139 src_addr = (unsigned long)src;
140 if (likely(src_addr < max_addr)) {
141 unsigned long max = max_addr - src_addr;
142 return do_strncpy_from_user(dst, src, count, max);
146 EXPORT_SYMBOL(strncpy_from_user);