1 /* $OpenBSD: usertc.c,v 1.3 2023/02/05 13:37:51 kettenis Exp $ */
2 /*
3 * Copyright (c) 2020 Mark Kettenis <kettenis@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 #include <sys/types.h>
19 #include <sys/timetc.h>
20
21 static inline uint64_t
agtimer_readcnt64_sun50i(void)22 agtimer_readcnt64_sun50i(void)
23 {
24 uint64_t val;
25 int retry;
26
27 __asm volatile("isb" ::: "memory");
28 for (retry = 0; retry < 150; retry++) {
29 __asm volatile("mrs %x0, CNTVCT_EL0" : "=r" (val));
30
31 if (((val + 1) & 0x1ff) > 1)
32 break;
33 }
34
35 return val;
36 }
37
38 static inline u_int
agtimer_get_timecount_default(struct timecounter * tc)39 agtimer_get_timecount_default(struct timecounter *tc)
40 {
41 uint64_t val;
42
43 /*
44 * No need to work around Cortex-A73 errata 858921 since we
45 * only look at the low 32 bits here.
46 */
47 __asm volatile("isb" ::: "memory");
48 __asm volatile("mrs %x0, CNTVCT_EL0" : "=r" (val));
49 return (val & 0xffffffff);
50 }
51
52 static inline u_int
agtimer_get_timecount_sun50i(struct timecounter * tc)53 agtimer_get_timecount_sun50i(struct timecounter *tc)
54 {
55 return agtimer_readcnt64_sun50i();
56 }
57
58 static int
tc_get_timecount(struct timekeep * tk,u_int * tc)59 tc_get_timecount(struct timekeep *tk, u_int *tc)
60 {
61 switch (tk->tk_user) {
62 case TC_AGTIMER:
63 *tc = agtimer_get_timecount_default(NULL);
64 return 0;
65 case TC_AGTIMER_SUN50I:
66 *tc = agtimer_get_timecount_sun50i(NULL);
67 return 0;
68 }
69
70 return -1;
71 }
72
73 int (*const _tc_get_timecount)(struct timekeep *, u_int *) = tc_get_timecount;
74