summaryrefslogtreecommitdiff
path: root/code/ecp/fe310/time.c
blob: 1346fea03010503464a1c76b858c509bedfca2ea (plain)
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
#include <core.h>
#include <tr.h>

#include <eos/eos.h>
#include <eos/event.h>
#include <eos/timer.h>

#include "encoding.h"
#include "platform.h"

extern ECPSocket *_ecp_tr_sock;

static void timer_handler(unsigned char type) {
    ecp_cts_t next = ecp_timer_exe(_ecp_tr_sock);
    if (next) {
        volatile uint64_t *mtime = (uint64_t *) (CLINT_CTRL_ADDR + CLINT_MTIME);
        uint64_t tick = *mtime + next * (uint64_t)RTC_FREQ / 1000;
        eos_timer_set(tick, EOS_TIMER_ETYPE_ECP, 0);
    }
}

int ecp_tm_init(ECPContext *ctx) {
    eos_timer_set_handler(EOS_TIMER_ETYPE_ECP, timer_handler, EOS_EVT_FLAG_NET_BUF_ACQ);
    return ECP_OK;
}

ecp_cts_t ecp_tm_abstime_ms(ecp_cts_t msec) {
    volatile uint64_t *mtime = (uint64_t *) (CLINT_CTRL_ADDR + CLINT_MTIME);

    uint64_t now_ms = *mtime * 1000 / RTC_FREQ;
    return now_ms + msec;
}

void ecp_tm_sleep_ms(ecp_cts_t msec) {
    volatile uint64_t *mtime = (uint64_t *) (CLINT_CTRL_ADDR + CLINT_MTIME);

    uint64_t now_ms = *mtime * 1000 / RTC_FREQ;
    while (*mtime * 1000 / RTC_FREQ < now_ms + msec);
}

void ecp_tm_timer_set(ecp_cts_t next) {
    volatile uint64_t *mtime = (uint64_t *) (CLINT_CTRL_ADDR + CLINT_MTIME);
    uint64_t tick = *mtime + next * (uint64_t)RTC_FREQ / 1000;
    eos_timer_set(tick, EOS_TIMER_ETYPE_ECP, 1);
}