-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimer.c
113 lines (91 loc) · 1.79 KB
/
timer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include "os.h"
#define MAX_TIMER 10
#define TIMER_INTERVAL CLINT_TIMEBASE_FREQ
extern void schedule(void);
static struct timer timer_list[MAX_TIMER];
static uint32_t _tick = 0;
void timer_load(int interval)
{
/* each CPU has a separate source of timer interrupts. */
int id = r_mhartid();
*(uint64_t*)CLINT_MTIMECMP(id) = *(uint64_t*)CLINT_MTIME + interval;
}
void timer_init()
{
struct timer *t = &(timer_list[0]);
for (int i = 0; i < MAX_TIMER; i++)
{
t->func = NULL;
t->arg = NULL;
t++;
}
/*
* On reset, mtime is cleared to zero, but the mtimecmp registers
* are not reset. So we have to init the mtimecmp manually.
*/
timer_load(TIMER_INTERVAL);
/* enable machine-mode timer interrupts. */
w_mie(r_mie() | MIE_MTIE);
}
struct timer *timer_create(void (*handler)(void *arg), void *arg, uint32_t timeout)
{
if (handler == NULL || timeout == 0)
{
return NULL;
}
spin_lock();
struct timer *t = &(timer_list[0]);
for(int i = 0; i < MAX_TIMER; i++)
{
if (t->func == NULL)
break;
t++;
}
if (t->func != NULL)
{
spin_unlock();
return NULL;
}
t->func = handler;
t->arg = arg;
t->timeout_tick = _tick + timeout;
spin_unlock();
return t;
}
void timer_delete(struct timer *timer)
{
spin_lock();
struct timer *t = &(timer_list[0]);
for (int i = 0; i < MAX_TIMER; i++) {
if (t == timer) {
t->func = NULL;
t->arg = NULL;
break;
}
t++;
}
spin_unlock();
}
static inline void timer_check()
{
struct timer *t = &(timer_list[0]);
for (int i = 0; i < MAX_TIMER; i++) {
if (NULL != t->func) {
if (_tick >= t->timeout_tick) {
t->func(t->arg);
t->func = NULL;
t->arg = NULL;
break;
}
}
t++;
}
}
void timer_handler()
{
_tick++;
printf("tick: %d\n", _tick);
timer_check();
timer_load(TIMER_INTERVAL);
schedule();
}