xref: /kvm-unit-tests/lib/riscv/asm/csr.h (revision 05a764725512259a073c804f2616fb4f5ac461e8)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 #ifndef _ASMRISCV_CSR_H_
3 #define _ASMRISCV_CSR_H_
4 #include <linux/const.h>
5 
6 #define CSR_SSTATUS		0x100
7 #define CSR_STVEC		0x105
8 #define CSR_SSCRATCH		0x140
9 #define CSR_SEPC		0x141
10 #define CSR_SCAUSE		0x142
11 #define CSR_STVAL		0x143
12 
13 /* Exception cause high bit - is an interrupt if set */
14 #define CAUSE_IRQ_FLAG		(_AC(1, UL) << (__riscv_xlen - 1))
15 
16 /* Exception causes */
17 #define EXC_INST_MISALIGNED	0
18 #define EXC_INST_ACCESS		1
19 #define EXC_INST_ILLEGAL	2
20 #define EXC_BREAKPOINT		3
21 #define EXC_LOAD_MISALIGNED	4
22 #define EXC_LOAD_ACCESS		5
23 #define EXC_STORE_MISALIGNED	6
24 #define EXC_STORE_ACCESS	7
25 #define EXC_SYSCALL		8
26 #define EXC_HYPERVISOR_SYSCALL	9
27 #define EXC_SUPERVISOR_SYSCALL	10
28 #define EXC_INST_PAGE_FAULT	12
29 #define EXC_LOAD_PAGE_FAULT	13
30 #define EXC_STORE_PAGE_FAULT	15
31 #define EXC_INST_GUEST_PAGE_FAULT	20
32 #define EXC_LOAD_GUEST_PAGE_FAULT	21
33 #define EXC_VIRTUAL_INST_FAULT		22
34 #define EXC_STORE_GUEST_PAGE_FAULT	23
35 
36 #ifndef __ASSEMBLY__
37 
38 #define csr_swap(csr, val)					\
39 ({								\
40 	unsigned long __v = (unsigned long)(val);		\
41 	__asm__ __volatile__ ("csrrw %0, " __ASM_STR(csr) ", %1"\
42 				: "=r" (__v) : "rK" (__v)	\
43 				: "memory");			\
44 	__v;							\
45 })
46 
47 #define csr_read(csr)						\
48 ({								\
49 	register unsigned long __v;				\
50 	__asm__ __volatile__ ("csrr %0, " __ASM_STR(csr)	\
51 				: "=r" (__v) :			\
52 				: "memory");			\
53 	__v;							\
54 })
55 
56 #define csr_write(csr, val)					\
57 ({								\
58 	unsigned long __v = (unsigned long)(val);		\
59 	__asm__ __volatile__ ("csrw " __ASM_STR(csr) ", %0"	\
60 				: : "rK" (__v)			\
61 				: "memory");			\
62 })
63 
64 #define csr_read_set(csr, val)					\
65 ({								\
66 	unsigned long __v = (unsigned long)(val);		\
67 	__asm__ __volatile__ ("csrrs %0, " __ASM_STR(csr) ", %1"\
68 				: "=r" (__v) : "rK" (__v)	\
69 				: "memory");			\
70 	__v;							\
71 })
72 
73 #define csr_set(csr, val)					\
74 ({								\
75 	unsigned long __v = (unsigned long)(val);		\
76 	__asm__ __volatile__ ("csrs " __ASM_STR(csr) ", %0"	\
77 				: : "rK" (__v)			\
78 				: "memory");			\
79 })
80 
81 #define csr_read_clear(csr, val)				\
82 ({								\
83 	unsigned long __v = (unsigned long)(val);		\
84 	__asm__ __volatile__ ("csrrc %0, " __ASM_STR(csr) ", %1"\
85 				: "=r" (__v) : "rK" (__v)	\
86 				: "memory");			\
87 	__v;							\
88 })
89 
90 #define csr_clear(csr, val)					\
91 ({								\
92 	unsigned long __v = (unsigned long)(val);		\
93 	__asm__ __volatile__ ("csrc " __ASM_STR(csr) ", %0"	\
94 				: : "rK" (__v)			\
95 				: "memory");			\
96 })
97 
98 #endif /* !__ASSEMBLY__ */
99 #endif /* _ASMRISCV_CSR_H_ */
100