master
c 75 lines 2.21 KB
Raw
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3 * QEMU LoongArch constant timer support
4 *
5 * Copyright (c) 2021 Loongson Technology Corporation Limited
6 */
7
8 #include "qemu/osdep.h"
9 #include "qemu/timer.h"
10 #include "cpu.h"
11 #include "internals.h"
12 #include "cpu-csr.h"
13
14 #define TIMER_PERIOD 10 /* 10 ns period for 100 MHz frequency */
15 #define CONSTANT_TIMER_TICK_MASK 0xfffffffffffcUL
16 #define CONSTANT_TIMER_ENABLE 0x1UL
17
18 uint64_t cpu_loongarch_get_constant_timer_counter(LoongArchCPU *cpu)
19 {
20 return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) / TIMER_PERIOD;
21 }
22
23 uint64_t cpu_loongarch_get_constant_timer_ticks(LoongArchCPU *cpu)
24 {
25 CPULoongArchState *env = &cpu->env;
26 CPUSysState *sys = env_sys(env);
27 uint64_t now, expire;
28
29 if ((sys->CSR_TCFG & CONSTANT_TIMER_ENABLE) &&
30 (sys->CSR_TVAL < sys->CSR_TCFG)) {
31 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
32 expire = timer_expire_time_ns(&cpu->timer);
33 sys->CSR_TVAL = (expire - now) / TIMER_PERIOD;
34 }
35
36 return sys->CSR_TVAL;
37 }
38
39 void cpu_loongarch_store_constant_timer_config(LoongArchCPU *cpu,
40 uint64_t value)
41 {
42 CPULoongArchState *env = &cpu->env;
43 CPUSysState *sys = env_sys(env);
44 uint64_t now, next;
45
46 sys->CSR_TCFG = value;
47 if (value & CONSTANT_TIMER_ENABLE) {
48 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
49 next = now + (value & CONSTANT_TIMER_TICK_MASK) * TIMER_PERIOD;
50 timer_mod(&cpu->timer, next);
51 sys->CSR_TVAL = sys->CSR_TCFG & CONSTANT_TIMER_TICK_MASK;
52 } else {
53 timer_del(&cpu->timer);
54 sys->CSR_TVAL = 0;
55 }
56 }
57
58 void loongarch_constant_timer_cb(void *opaque)
59 {
60 LoongArchCPU *cpu = opaque;
61 CPULoongArchState *env = &cpu->env;
62 CPUSysState *sys = env_sys(env);
63 uint64_t now, next;
64
65 if (FIELD_EX64(sys->CSR_TCFG, CSR_TCFG, PERIODIC)) {
66 now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
67 next = now + (sys->CSR_TCFG & CONSTANT_TIMER_TICK_MASK) * TIMER_PERIOD;
68 timer_mod(&cpu->timer, next);
69 sys->CSR_TVAL = sys->CSR_TCFG & CONSTANT_TIMER_TICK_MASK;
70 } else {
71 sys->CSR_TVAL = CONSTANT_TIMER_TICK_MASK;
72 }
73
74 loongarch_cpu_set_irq(opaque, IRQ_TIMER, 1);
75 }