xref: /linux/arch/x86/include/asm/uaccess.h (revision c01044cc819160323f3ca4acd44fca487c4432e6)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _ASM_X86_UACCESS_H
3 #define _ASM_X86_UACCESS_H
4 /*
5  * User space memory access functions
6  */
7 #include <linux/compiler.h>
8 #include <linux/kasan-checks.h>
9 #include <linux/string.h>
10 #include <asm/asm.h>
11 #include <asm/page.h>
12 #include <asm/smap.h>
13 #include <asm/extable.h>
14 
15 /*
16  * The fs value determines whether argument validity checking should be
17  * performed or not.  If get_fs() == USER_DS, checking is performed, with
18  * get_fs() == KERNEL_DS, checking is bypassed.
19  *
20  * For historical reasons, these macros are grossly misnamed.
21  */
22 
23 #define MAKE_MM_SEG(s)	((mm_segment_t) { (s) })
24 
25 #define KERNEL_DS	MAKE_MM_SEG(-1UL)
26 #define USER_DS 	MAKE_MM_SEG(TASK_SIZE_MAX)
27 
28 #define get_fs()	(current->thread.addr_limit)
29 static inline void set_fs(mm_segment_t fs)
30 {
31 	current->thread.addr_limit = fs;
32 	/* On user-mode return, check fs is correct */
33 	set_thread_flag(TIF_FSCHECK);
34 }
35 
36 #define uaccess_kernel() (get_fs().seg == KERNEL_DS.seg)
37 #define user_addr_max() (current->thread.addr_limit.seg)
38 
39 /*
40  * Test whether a block of memory is a valid user space address.
41  * Returns 0 if the range is valid, nonzero otherwise.
42  */
43 static inline bool __chk_range_not_ok(unsigned long addr, unsigned long size, unsigned long limit)
44 {
45 	/*
46 	 * If we have used "sizeof()" for the size,
47 	 * we know it won't overflow the limit (but
48 	 * it might overflow the 'addr', so it's
49 	 * important to subtract the size from the
50 	 * limit, not add it to the address).
51 	 */
52 	if (__builtin_constant_p(size))
53 		return unlikely(addr > limit - size);
54 
55 	/* Arbitrary sizes? Be careful about overflow */
56 	addr += size;
57 	if (unlikely(addr < size))
58 		return true;
59 	return unlikely(addr > limit);
60 }
61 
62 #define __range_not_ok(addr, size, limit)				\
63 ({									\
64 	__chk_user_ptr(addr);						\
65 	__chk_range_not_ok((unsigned long __force)(addr), size, limit); \
66 })
67 
68 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
69 static inline bool pagefault_disabled(void);
70 # define WARN_ON_IN_IRQ()	\
71 	WARN_ON_ONCE(!in_task() && !pagefault_disabled())
72 #else
73 # define WARN_ON_IN_IRQ()
74 #endif
75 
76 /**
77  * access_ok - Checks if a user space pointer is valid
78  * @addr: User space pointer to start of block to check
79  * @size: Size of block to check
80  *
81  * Context: User context only. This function may sleep if pagefaults are
82  *          enabled.
83  *
84  * Checks if a pointer to a block of memory in user space is valid.
85  *
86  * Note that, depending on architecture, this function probably just
87  * checks that the pointer is in the user space range - after calling
88  * this function, memory access functions may still return -EFAULT.
89  *
90  * Return: true (nonzero) if the memory block may be valid, false (zero)
91  * if it is definitely invalid.
92  */
93 #define access_ok(addr, size)					\
94 ({									\
95 	WARN_ON_IN_IRQ();						\
96 	likely(!__range_not_ok(addr, size, user_addr_max()));		\
97 })
98 
99 extern int __get_user_1(void);
100 extern int __get_user_2(void);
101 extern int __get_user_4(void);
102 extern int __get_user_8(void);
103 extern int __get_user_nocheck_1(void);
104 extern int __get_user_nocheck_2(void);
105 extern int __get_user_nocheck_4(void);
106 extern int __get_user_nocheck_8(void);
107 extern int __get_user_bad(void);
108 
109 #define __uaccess_begin() stac()
110 #define __uaccess_end()   clac()
111 #define __uaccess_begin_nospec()	\
112 ({					\
113 	stac();				\
114 	barrier_nospec();		\
115 })
116 
117 /*
118  * This is the smallest unsigned integer type that can fit a value
119  * (up to 'long long')
120  */
121 #define __inttype(x) __typeof__(		\
122 	__typefits(x,char,			\
123 	  __typefits(x,short,			\
124 	    __typefits(x,int,			\
125 	      __typefits(x,long,0ULL)))))
126 
127 #define __typefits(x,type,not) \
128 	__builtin_choose_expr(sizeof(x)<=sizeof(type),(unsigned type)0,not)
129 
130 /*
131  * This is used for both get_user() and __get_user() to expand to
132  * the proper special function call that has odd calling conventions
133  * due to returning both a value and an error, and that depends on
134  * the size of the pointer passed in.
135  *
136  * Careful: we have to cast the result to the type of the pointer
137  * for sign reasons.
138  *
139  * The use of _ASM_DX as the register specifier is a bit of a
140  * simplification, as gcc only cares about it as the starting point
141  * and not size: for a 64-bit value it will use %ecx:%edx on 32 bits
142  * (%ecx being the next register in gcc's x86 register sequence), and
143  * %rdx on 64 bits.
144  *
145  * Clang/LLVM cares about the size of the register, but still wants
146  * the base register for something that ends up being a pair.
147  */
148 #define do_get_user_call(fn,x,ptr)					\
149 ({									\
150 	int __ret_gu;							\
151 	register __inttype(*(ptr)) __val_gu asm("%"_ASM_DX);		\
152 	__chk_user_ptr(ptr);						\
153 	asm volatile("call __" #fn "_%P4"				\
154 		     : "=a" (__ret_gu), "=r" (__val_gu),		\
155 			ASM_CALL_CONSTRAINT				\
156 		     : "0" (ptr), "i" (sizeof(*(ptr))));		\
157 	(x) = (__force __typeof__(*(ptr))) __val_gu;			\
158 	__builtin_expect(__ret_gu, 0);					\
159 })
160 
161 /**
162  * get_user - Get a simple variable from user space.
163  * @x:   Variable to store result.
164  * @ptr: Source address, in user space.
165  *
166  * Context: User context only. This function may sleep if pagefaults are
167  *          enabled.
168  *
169  * This macro copies a single simple variable from user space to kernel
170  * space.  It supports simple types like char and int, but not larger
171  * data types like structures or arrays.
172  *
173  * @ptr must have pointer-to-simple-variable type, and the result of
174  * dereferencing @ptr must be assignable to @x without a cast.
175  *
176  * Return: zero on success, or -EFAULT on error.
177  * On error, the variable @x is set to zero.
178  */
179 #define get_user(x,ptr) ({ might_fault(); do_get_user_call(get_user,x,ptr); })
180 
181 /**
182  * __get_user - Get a simple variable from user space, with less checking.
183  * @x:   Variable to store result.
184  * @ptr: Source address, in user space.
185  *
186  * Context: User context only. This function may sleep if pagefaults are
187  *          enabled.
188  *
189  * This macro copies a single simple variable from user space to kernel
190  * space.  It supports simple types like char and int, but not larger
191  * data types like structures or arrays.
192  *
193  * @ptr must have pointer-to-simple-variable type, and the result of
194  * dereferencing @ptr must be assignable to @x without a cast.
195  *
196  * Caller must check the pointer with access_ok() before calling this
197  * function.
198  *
199  * Return: zero on success, or -EFAULT on error.
200  * On error, the variable @x is set to zero.
201  */
202 #define __get_user(x,ptr) do_get_user_call(get_user_nocheck,x,ptr)
203 
204 
205 #ifdef CONFIG_X86_32
206 #define __put_user_goto_u64(x, addr, label)			\
207 	asm_volatile_goto("\n"					\
208 		     "1:	movl %%eax,0(%1)\n"		\
209 		     "2:	movl %%edx,4(%1)\n"		\
210 		     _ASM_EXTABLE_UA(1b, %l2)			\
211 		     _ASM_EXTABLE_UA(2b, %l2)			\
212 		     : : "A" (x), "r" (addr)			\
213 		     : : label)
214 
215 #else
216 #define __put_user_goto_u64(x, ptr, label) \
217 	__put_user_goto(x, ptr, "q", "er", label)
218 #endif
219 
220 extern void __put_user_bad(void);
221 
222 /*
223  * Strange magic calling convention: pointer in %ecx,
224  * value in %eax(:%edx), return value in %ecx. clobbers %rbx
225  */
226 extern void __put_user_1(void);
227 extern void __put_user_2(void);
228 extern void __put_user_4(void);
229 extern void __put_user_8(void);
230 extern void __put_user_nocheck_1(void);
231 extern void __put_user_nocheck_2(void);
232 extern void __put_user_nocheck_4(void);
233 extern void __put_user_nocheck_8(void);
234 
235 #define do_put_user_call(fn,x,ptr)					\
236 ({									\
237 	int __ret_pu;							\
238 	register __typeof__(*(ptr)) __val_pu asm("%"_ASM_AX);		\
239 	__chk_user_ptr(ptr);						\
240 	__val_pu = (x);							\
241 	asm volatile("call __" #fn "_%P[size]"				\
242 		     : "=c" (__ret_pu),					\
243 			ASM_CALL_CONSTRAINT				\
244 		     : "0" (ptr),					\
245 		       "r" (__val_pu),					\
246 		       [size] "i" (sizeof(*(ptr)))			\
247 		     :"ebx");						\
248 	__builtin_expect(__ret_pu, 0);					\
249 })
250 
251 /**
252  * put_user - Write a simple value into user space.
253  * @x:   Value to copy to user space.
254  * @ptr: Destination address, in user space.
255  *
256  * Context: User context only. This function may sleep if pagefaults are
257  *          enabled.
258  *
259  * This macro copies a single simple value from kernel space to user
260  * space.  It supports simple types like char and int, but not larger
261  * data types like structures or arrays.
262  *
263  * @ptr must have pointer-to-simple-variable type, and @x must be assignable
264  * to the result of dereferencing @ptr.
265  *
266  * Return: zero on success, or -EFAULT on error.
267  */
268 #define put_user(x, ptr) ({ might_fault(); do_put_user_call(put_user,x,ptr); })
269 
270 /**
271  * __put_user - Write a simple value into user space, with less checking.
272  * @x:   Value to copy to user space.
273  * @ptr: Destination address, in user space.
274  *
275  * Context: User context only. This function may sleep if pagefaults are
276  *          enabled.
277  *
278  * This macro copies a single simple value from kernel space to user
279  * space.  It supports simple types like char and int, but not larger
280  * data types like structures or arrays.
281  *
282  * @ptr must have pointer-to-simple-variable type, and @x must be assignable
283  * to the result of dereferencing @ptr.
284  *
285  * Caller must check the pointer with access_ok() before calling this
286  * function.
287  *
288  * Return: zero on success, or -EFAULT on error.
289  */
290 #define __put_user(x, ptr) do_put_user_call(put_user_nocheck,x,ptr)
291 
292 #define __put_user_size(x, ptr, size, label)				\
293 do {									\
294 	__chk_user_ptr(ptr);						\
295 	switch (size) {							\
296 	case 1:								\
297 		__put_user_goto(x, ptr, "b", "iq", label);		\
298 		break;							\
299 	case 2:								\
300 		__put_user_goto(x, ptr, "w", "ir", label);		\
301 		break;							\
302 	case 4:								\
303 		__put_user_goto(x, ptr, "l", "ir", label);		\
304 		break;							\
305 	case 8:								\
306 		__put_user_goto_u64(x, ptr, label);			\
307 		break;							\
308 	default:							\
309 		__put_user_bad();					\
310 	}								\
311 } while (0)
312 
313 #ifdef CONFIG_CC_HAS_ASM_GOTO_OUTPUT
314 
315 #ifdef CONFIG_X86_32
316 #define __get_user_asm_u64(x, ptr, label) do {				\
317 	unsigned int __gu_low, __gu_high;				\
318 	const unsigned int __user *__gu_ptr;				\
319 	__gu_ptr = (const void __user *)(ptr);				\
320 	__get_user_asm(__gu_low, ptr, "l", "=r", label);		\
321 	__get_user_asm(__gu_high, ptr+1, "l", "=r", label);		\
322 	(x) = ((unsigned long long)__gu_high << 32) | __gu_low;		\
323 } while (0)
324 #else
325 #define __get_user_asm_u64(x, ptr, label)				\
326 	__get_user_asm(x, ptr, "q", "=r", label)
327 #endif
328 
329 #define __get_user_size(x, ptr, size, label)				\
330 do {									\
331 	__chk_user_ptr(ptr);						\
332 	switch (size) {							\
333 	unsigned char x_u8__;						\
334 	case 1:								\
335 		__get_user_asm(x_u8__, ptr, "b", "=q", label);		\
336 		(x) = x_u8__;						\
337 		break;							\
338 	case 2:								\
339 		__get_user_asm(x, ptr, "w", "=r", label);		\
340 		break;							\
341 	case 4:								\
342 		__get_user_asm(x, ptr, "l", "=r", label);		\
343 		break;							\
344 	case 8:								\
345 		__get_user_asm_u64(x, ptr, label);			\
346 		break;							\
347 	default:							\
348 		(x) = __get_user_bad();					\
349 	}								\
350 } while (0)
351 
352 #define __get_user_asm(x, addr, itype, ltype, label)			\
353 	asm_volatile_goto("\n"						\
354 		     "1:	mov"itype" %[umem],%[output]\n"		\
355 		     _ASM_EXTABLE_UA(1b, %l2)				\
356 		     : [output] ltype(x)				\
357 		     : [umem] "m" (__m(addr))				\
358 		     : : label)
359 
360 #else // !CONFIG_CC_HAS_ASM_GOTO_OUTPUT
361 
362 #ifdef CONFIG_X86_32
363 #define __get_user_asm_u64(x, ptr, retval)				\
364 ({									\
365 	__typeof__(ptr) __ptr = (ptr);					\
366 	asm volatile("\n"						\
367 		     "1:	movl %[lowbits],%%eax\n"		\
368 		     "2:	movl %[highbits],%%edx\n"		\
369 		     "3:\n"						\
370 		     ".section .fixup,\"ax\"\n"				\
371 		     "4:	mov %[efault],%[errout]\n"		\
372 		     "	xorl %%eax,%%eax\n"				\
373 		     "	xorl %%edx,%%edx\n"				\
374 		     "	jmp 3b\n"					\
375 		     ".previous\n"					\
376 		     _ASM_EXTABLE_UA(1b, 4b)				\
377 		     _ASM_EXTABLE_UA(2b, 4b)				\
378 		     : [errout] "=r" (retval),				\
379 		       [output] "=&A"(x)				\
380 		     : [lowbits] "m" (__m(__ptr)),			\
381 		       [highbits] "m" __m(((u32 __user *)(__ptr)) + 1),	\
382 		       [efault] "i" (-EFAULT), "0" (retval));		\
383 })
384 
385 #else
386 #define __get_user_asm_u64(x, ptr, retval) \
387 	 __get_user_asm(x, ptr, retval, "q", "=r")
388 #endif
389 
390 #define __get_user_size(x, ptr, size, retval)				\
391 do {									\
392 	unsigned char x_u8__;						\
393 									\
394 	retval = 0;							\
395 	__chk_user_ptr(ptr);						\
396 	switch (size) {							\
397 	case 1:								\
398 		__get_user_asm(x_u8__, ptr, retval, "b", "=q");		\
399 		(x) = x_u8__;						\
400 		break;							\
401 	case 2:								\
402 		__get_user_asm(x, ptr, retval, "w", "=r");		\
403 		break;							\
404 	case 4:								\
405 		__get_user_asm(x, ptr, retval, "l", "=r");		\
406 		break;							\
407 	case 8:								\
408 		__get_user_asm_u64(x, ptr, retval);			\
409 		break;							\
410 	default:							\
411 		(x) = __get_user_bad();					\
412 	}								\
413 } while (0)
414 
415 #define __get_user_asm(x, addr, err, itype, ltype)			\
416 	asm volatile("\n"						\
417 		     "1:	mov"itype" %[umem],%[output]\n"		\
418 		     "2:\n"						\
419 		     ".section .fixup,\"ax\"\n"				\
420 		     "3:	mov %[efault],%[errout]\n"		\
421 		     "	xorl %k[output],%k[output]\n"			\
422 		     "	jmp 2b\n"					\
423 		     ".previous\n"					\
424 		     _ASM_EXTABLE_UA(1b, 3b)				\
425 		     : [errout] "=r" (err),				\
426 		       [output] ltype(x)				\
427 		     : [umem] "m" (__m(addr)),				\
428 		       [efault] "i" (-EFAULT), "0" (err))
429 
430 #endif // CONFIG_CC_ASM_GOTO_OUTPUT
431 
432 /* FIXME: this hack is definitely wrong -AK */
433 struct __large_struct { unsigned long buf[100]; };
434 #define __m(x) (*(struct __large_struct __user *)(x))
435 
436 /*
437  * Tell gcc we read from memory instead of writing: this is because
438  * we do not write to any memory gcc knows about, so there are no
439  * aliasing issues.
440  */
441 #define __put_user_goto(x, addr, itype, ltype, label)			\
442 	asm_volatile_goto("\n"						\
443 		"1:	mov"itype" %0,%1\n"				\
444 		_ASM_EXTABLE_UA(1b, %l2)				\
445 		: : ltype(x), "m" (__m(addr))				\
446 		: : label)
447 
448 extern unsigned long
449 copy_from_user_nmi(void *to, const void __user *from, unsigned long n);
450 extern __must_check long
451 strncpy_from_user(char *dst, const char __user *src, long count);
452 
453 extern __must_check long strnlen_user(const char __user *str, long n);
454 
455 unsigned long __must_check clear_user(void __user *mem, unsigned long len);
456 unsigned long __must_check __clear_user(void __user *mem, unsigned long len);
457 
458 #ifdef CONFIG_ARCH_HAS_COPY_MC
459 unsigned long __must_check
460 copy_mc_to_kernel(void *to, const void *from, unsigned len);
461 #define copy_mc_to_kernel copy_mc_to_kernel
462 
463 unsigned long __must_check
464 copy_mc_to_user(void *to, const void *from, unsigned len);
465 #endif
466 
467 /*
468  * movsl can be slow when source and dest are not both 8-byte aligned
469  */
470 #ifdef CONFIG_X86_INTEL_USERCOPY
471 extern struct movsl_mask {
472 	int mask;
473 } ____cacheline_aligned_in_smp movsl_mask;
474 #endif
475 
476 #define ARCH_HAS_NOCACHE_UACCESS 1
477 
478 #ifdef CONFIG_X86_32
479 # include <asm/uaccess_32.h>
480 #else
481 # include <asm/uaccess_64.h>
482 #endif
483 
484 /*
485  * The "unsafe" user accesses aren't really "unsafe", but the naming
486  * is a big fat warning: you have to not only do the access_ok()
487  * checking before using them, but you have to surround them with the
488  * user_access_begin/end() pair.
489  */
490 static __must_check __always_inline bool user_access_begin(const void __user *ptr, size_t len)
491 {
492 	if (unlikely(!access_ok(ptr,len)))
493 		return 0;
494 	__uaccess_begin_nospec();
495 	return 1;
496 }
497 #define user_access_begin(a,b)	user_access_begin(a,b)
498 #define user_access_end()	__uaccess_end()
499 
500 #define user_access_save()	smap_save()
501 #define user_access_restore(x)	smap_restore(x)
502 
503 #define unsafe_put_user(x, ptr, label)	\
504 	__put_user_size((__typeof__(*(ptr)))(x), (ptr), sizeof(*(ptr)), label)
505 
506 #ifdef CONFIG_CC_HAS_ASM_GOTO_OUTPUT
507 #define unsafe_get_user(x, ptr, err_label)					\
508 do {										\
509 	__inttype(*(ptr)) __gu_val;						\
510 	__get_user_size(__gu_val, (ptr), sizeof(*(ptr)), err_label);		\
511 	(x) = (__force __typeof__(*(ptr)))__gu_val;				\
512 } while (0)
513 #else // !CONFIG_CC_HAS_ASM_GOTO_OUTPUT
514 #define unsafe_get_user(x, ptr, err_label)					\
515 do {										\
516 	int __gu_err;								\
517 	__inttype(*(ptr)) __gu_val;						\
518 	__get_user_size(__gu_val, (ptr), sizeof(*(ptr)), __gu_err);		\
519 	(x) = (__force __typeof__(*(ptr)))__gu_val;				\
520 	if (unlikely(__gu_err)) goto err_label;					\
521 } while (0)
522 #endif // CONFIG_CC_HAS_ASM_GOTO_OUTPUT
523 
524 /*
525  * We want the unsafe accessors to always be inlined and use
526  * the error labels - thus the macro games.
527  */
528 #define unsafe_copy_loop(dst, src, len, type, label)				\
529 	while (len >= sizeof(type)) {						\
530 		unsafe_put_user(*(type *)(src),(type __user *)(dst),label);	\
531 		dst += sizeof(type);						\
532 		src += sizeof(type);						\
533 		len -= sizeof(type);						\
534 	}
535 
536 #define unsafe_copy_to_user(_dst,_src,_len,label)			\
537 do {									\
538 	char __user *__ucu_dst = (_dst);				\
539 	const char *__ucu_src = (_src);					\
540 	size_t __ucu_len = (_len);					\
541 	unsafe_copy_loop(__ucu_dst, __ucu_src, __ucu_len, u64, label);	\
542 	unsafe_copy_loop(__ucu_dst, __ucu_src, __ucu_len, u32, label);	\
543 	unsafe_copy_loop(__ucu_dst, __ucu_src, __ucu_len, u16, label);	\
544 	unsafe_copy_loop(__ucu_dst, __ucu_src, __ucu_len, u8, label);	\
545 } while (0)
546 
547 #define HAVE_GET_KERNEL_NOFAULT
548 
549 #ifdef CONFIG_CC_HAS_ASM_GOTO_OUTPUT
550 #define __get_kernel_nofault(dst, src, type, err_label)			\
551 	__get_user_size(*((type *)(dst)), (__force type __user *)(src),	\
552 			sizeof(type), err_label)
553 #else // !CONFIG_CC_HAS_ASM_GOTO_OUTPUT
554 #define __get_kernel_nofault(dst, src, type, err_label)			\
555 do {									\
556 	int __kr_err;							\
557 									\
558 	__get_user_size(*((type *)(dst)), (__force type __user *)(src),	\
559 			sizeof(type), __kr_err);			\
560 	if (unlikely(__kr_err))						\
561 		goto err_label;						\
562 } while (0)
563 #endif // CONFIG_CC_HAS_ASM_GOTO_OUTPUT
564 
565 #define __put_kernel_nofault(dst, src, type, err_label)			\
566 	__put_user_size(*((type *)(src)), (__force type __user *)(dst),	\
567 			sizeof(type), err_label)
568 
569 #endif /* _ASM_X86_UACCESS_H */
570 
571