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  * 2024/07/08     Shell        Using CPUTIME as tick
10  */
11 
12 #include <rthw.h>
13 #include <rtthread.h>
14 
15 #include <drivers/cputime.h>
16 #include <encoding.h>
17 #include "sbi.h"
18 
19 #ifdef RT_USING_KTIME
20 #include <ktime.h>
21 #endif
22 
23 static volatile unsigned long tick_cycles = 0;
24 
tick_isr(void)25 int tick_isr(void)
26 {
27     rt_tick_increase();
28     sbi_set_timer(clock_cpu_gettime() + tick_cycles);
29     return 0;
30 }
31 
32 /* BSP should config clockbase frequency */
33 RT_STATIC_ASSERT(defined_clockbase_freq, CPUTIME_TIMER_FREQ != 0);
34 
35 /* Sets and enable the timer interrupt */
rt_hw_tick_init(void)36 int rt_hw_tick_init(void)
37 {
38     /* calculate the tick cycles */
39     tick_cycles = CPUTIME_TIMER_FREQ / RT_TICK_PER_SECOND;
40 
41     /* Clear the Supervisor-Timer bit in SIE */
42     clear_csr(sie, SIP_STIP);
43 
44     /* Init riscv timer */
45     riscv_cputime_init();
46 
47     /* Set timer */
48     sbi_set_timer(clock_cpu_gettime() + tick_cycles);
49 
50 #ifdef RT_USING_KTIME
51     rt_ktime_cputimer_init();
52 #endif
53     /* Enable the Supervisor-Timer bit in SIE */
54     set_csr(sie, SIP_STIP);
55 
56     return 0;
57 }
58 
59 /**
60  * This function will delay for some us.
61  *
62  * @param us the delay time of us
63  */
rt_hw_us_delay(rt_uint32_t us)64 void rt_hw_us_delay(rt_uint32_t us)
65 {
66     unsigned long start_time;
67     unsigned long end_time;
68     unsigned long run_time;
69 
70     start_time = clock_cpu_gettime();
71     end_time = start_time + us * (CPUTIME_TIMER_FREQ / 1000000);
72     do
73     {
74         run_time = clock_cpu_gettime();
75     } while(run_time < end_time);
76 }
77