1 /*
2  * Copyright (c) 2006-2021, RT-Thread Development Team
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Change Logs:
7  * Date           Author       Notes
8  * 2018/10/28     Bernard      The unify RISC-V porting code.
9  */
10 
11 #include <rthw.h>
12 #include <rtthread.h>
13 
14 #include <encoding.h>
15 #include <clint.h>
16 #include <sysctl.h>
17 
18 static volatile unsigned long tick_cycles = 0;
19 
rt_hw_tick_isr(void)20 int rt_hw_tick_isr(void)
21 {
22     uint64_t core_id = current_coreid();
23 
24     clint->mtimecmp[core_id] += tick_cycles;
25     rt_tick_increase();
26 
27     return 0;
28 }
29 
30 /* Sets and enable the timer interrupt */
rt_hw_tick_init(void)31 int rt_hw_tick_init(void)
32 {
33     /* Read core id */
34     unsigned long core_id = current_coreid();
35     unsigned long interval = 1000/RT_TICK_PER_SECOND;
36 
37     /* Clear the Machine-Timer bit in MIE */
38     clear_csr(mie, MIP_MTIP);
39 
40     /* calculate the tick cycles */
41     tick_cycles = interval * sysctl_clock_get_freq(SYSCTL_CLOCK_CPU) / CLINT_CLOCK_DIV / 1000ULL - 1;
42     /* Set mtimecmp by core id */
43     clint->mtimecmp[core_id] = clint->mtime + tick_cycles;
44 
45     /* Enable the Machine-Timer bit in MIE */
46     set_csr(mie, MIP_MTIP);
47 
48     return 0;
49 }
50