1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3 * Supervisor Mode Access Prevention support
4 *
5 * Copyright (C) 2012 Intel Corporation
6 * Author: H. Peter Anvin <hpa@linux.intel.com>
7 */
8
9 #ifndef _ASM_X86_SMAP_H
10 #define _ASM_X86_SMAP_H
11
12 #include <asm/nops.h>
13 #include <asm/cpufeatures.h>
14 #include <asm/alternative.h>
15
16 /* "Raw" instruction opcodes */
17 #define __ASM_CLAC ".byte 0x0f,0x01,0xca"
18 #define __ASM_STAC ".byte 0x0f,0x01,0xcb"
19
20 #ifdef __ASSEMBLY__
21
22 #ifdef CONFIG_X86_SMAP
23
24 #define ASM_CLAC \
25 ALTERNATIVE "", __ASM_CLAC, X86_FEATURE_SMAP
26
27 #define ASM_STAC \
28 ALTERNATIVE "", __ASM_STAC, X86_FEATURE_SMAP
29
30 #else /* CONFIG_X86_SMAP */
31
32 #define ASM_CLAC
33 #define ASM_STAC
34
35 #endif /* CONFIG_X86_SMAP */
36
37 #else /* __ASSEMBLY__ */
38
39 #ifdef CONFIG_X86_SMAP
40
clac(void)41 static __always_inline void clac(void)
42 {
43 /* Note: a barrier is implicit in alternative() */
44 alternative("", __ASM_CLAC, X86_FEATURE_SMAP);
45 }
46
stac(void)47 static __always_inline void stac(void)
48 {
49 /* Note: a barrier is implicit in alternative() */
50 alternative("", __ASM_STAC, X86_FEATURE_SMAP);
51 }
52
smap_save(void)53 static __always_inline unsigned long smap_save(void)
54 {
55 unsigned long flags;
56
57 asm volatile ("# smap_save\n\t"
58 ALTERNATIVE("jmp 1f", "", X86_FEATURE_SMAP)
59 "pushf; pop %0; " __ASM_CLAC "\n\t"
60 "1:"
61 : "=rm" (flags) : : "memory", "cc");
62
63 return flags;
64 }
65
smap_restore(unsigned long flags)66 static __always_inline void smap_restore(unsigned long flags)
67 {
68 asm volatile ("# smap_restore\n\t"
69 ALTERNATIVE("jmp 1f", "", X86_FEATURE_SMAP)
70 "push %0; popf\n\t"
71 "1:"
72 : : "g" (flags) : "memory", "cc");
73 }
74
75 /* These macros can be used in asm() statements */
76 #define ASM_CLAC \
77 ALTERNATIVE("", __ASM_CLAC, X86_FEATURE_SMAP)
78 #define ASM_STAC \
79 ALTERNATIVE("", __ASM_STAC, X86_FEATURE_SMAP)
80
81 #else /* CONFIG_X86_SMAP */
82
clac(void)83 static inline void clac(void) { }
stac(void)84 static inline void stac(void) { }
85
smap_save(void)86 static inline unsigned long smap_save(void) { return 0; }
smap_restore(unsigned long flags)87 static inline void smap_restore(unsigned long flags) { }
88
89 #define ASM_CLAC
90 #define ASM_STAC
91
92 #endif /* CONFIG_X86_SMAP */
93
94 #endif /* __ASSEMBLY__ */
95
96 #endif /* _ASM_X86_SMAP_H */
97