xref: /linux/arch/x86/lib/copy_mc.c (revision ec6347bb43395cb92126788a1a5b25302543f815)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2016-2020 Intel Corporation. All rights reserved. */
3 
4 #include <linux/jump_label.h>
5 #include <linux/uaccess.h>
6 #include <linux/export.h>
7 #include <linux/string.h>
8 #include <linux/types.h>
9 
10 #include <asm/mce.h>
11 
12 #ifdef CONFIG_X86_MCE
13 /*
14  * See COPY_MC_TEST for self-test of the copy_mc_fragile()
15  * implementation.
16  */
17 static DEFINE_STATIC_KEY_FALSE(copy_mc_fragile_key);
18 
19 void enable_copy_mc_fragile(void)
20 {
21 	static_branch_inc(&copy_mc_fragile_key);
22 }
23 #define copy_mc_fragile_enabled (static_branch_unlikely(&copy_mc_fragile_key))
24 
25 /*
26  * Similar to copy_user_handle_tail, probe for the write fault point, or
27  * source exception point.
28  */
29 __visible notrace unsigned long
30 copy_mc_fragile_handle_tail(char *to, char *from, unsigned len)
31 {
32 	for (; len; --len, to++, from++)
33 		if (copy_mc_fragile(to, from, 1))
34 			break;
35 	return len;
36 }
37 #else
38 /*
39  * No point in doing careful copying, or consulting a static key when
40  * there is no #MC handler in the CONFIG_X86_MCE=n case.
41  */
42 void enable_copy_mc_fragile(void)
43 {
44 }
45 #define copy_mc_fragile_enabled (0)
46 #endif
47 
48 /**
49  * copy_mc_to_kernel - memory copy that handles source exceptions
50  *
51  * @dst:	destination address
52  * @src:	source address
53  * @len:	number of bytes to copy
54  *
55  * Call into the 'fragile' version on systems that have trouble
56  * actually do machine check recovery. Everyone else can just
57  * use memcpy().
58  *
59  * Return 0 for success, or number of bytes not copied if there was an
60  * exception.
61  */
62 unsigned long __must_check copy_mc_to_kernel(void *dst, const void *src, unsigned len)
63 {
64 	if (copy_mc_fragile_enabled)
65 		return copy_mc_fragile(dst, src, len);
66 	memcpy(dst, src, len);
67 	return 0;
68 }
69 EXPORT_SYMBOL_GPL(copy_mc_to_kernel);
70 
71 unsigned long __must_check copy_mc_to_user(void *dst, const void *src, unsigned len)
72 {
73 	unsigned long ret;
74 
75 	if (!copy_mc_fragile_enabled)
76 		return copy_user_generic(dst, src, len);
77 
78 	__uaccess_begin();
79 	ret = copy_mc_fragile(dst, src, len);
80 	__uaccess_end();
81 	return ret;
82 }
83