xref: /optee_os/lib/libutee/include/riscv_user_sysreg.h (revision 53877f84472e6d29f2695bfe20d05bed577325c1)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * Copyright (c) 2023 Andes Technology Corporation
4  */
5 #ifndef RISCV_USER_SYSREG_H
6 #define RISCV_USER_SYSREG_H
7 
8 #include <stdint.h>
9 
10 #define read_csr(csr)							\
11 	({								\
12 		register unsigned long v;				\
13 		asm volatile ("csrr %0, " #csr : "=r"(v) : : "memory");	\
14 		v;							\
15 	})
16 
read_time(void)17 static inline __noprof uint64_t read_time(void)
18 {
19 	uint64_t time = 0;
20 	uint32_t hi __maybe_unused = 0;
21 	uint32_t lo __maybe_unused = 0;
22 
23 #ifdef RV32
24 	do {
25 		hi = read_csr(timeh);
26 		lo = read_csr(time);
27 	} while (hi != read_csr(timeh));
28 
29 	time = SHIFT_U64(hi, 32) | lo;
30 #else /*RV64*/
31 	time = read_csr(time);
32 #endif /*RV32*/
33 
34 	return time;
35 }
36 
37 /* These barriers need to enforce ordering on both devices and memory. */
mb(void)38 static inline __noprof void mb(void)
39 {
40 	asm volatile ("fence" : : : "memory");
41 }
42 
barrier_read_counter_timer(void)43 static inline __noprof uint64_t barrier_read_counter_timer(void)
44 {
45 	mb();	/* Get timer value after pending operations have completed */
46 	return read_time();
47 }
48 
read_cntfrq(void)49 static inline __noprof uint32_t read_cntfrq(void)
50 {
51 	return CFG_RISCV_MTIME_RATE;
52 }
53 
54 #endif /* RISCV_USER_SYSREG_H */
55