summaryrefslogtreecommitdiff
path: root/ports/risc-v64/gnu/example_build/bananapi-f3/hwtimer.c
blob: 4881ba3ccb7fba83fb01e70b086cd48851bbe485 (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
46
47
48
49
50
51
52
53
54
55
56
/***************************************************************************
 * Copyright (c) 2026 10xEngineers
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which is available at
 * https://opensource.org/licenses/MIT.
 *
 * SPDX-License-Identifier: MIT
 **************************************************************************/

#include "tx_port.h"
#include "csr.h"
#include "hwtimer.h"

/*
 * SBI legacy set_timer ecall
 *
 * EID (a7) = 0  (SBI_SET_TIMER)
 * a0       = absolute mtime compare value
 *
 * Programs mtimecmp for the current hart and clears sip.STIP.
 */
static inline void sbi_set_timer(uint64_t stime_value)
{
    register uint64_t a0 asm("a0") = stime_value;
    register uint64_t a7 asm("a7") = 0;  /* SBI_SET_TIMER */
    asm volatile("ecall"
                 : "+r"(a0)
                 : "r"(a7)
                 : "memory");
}

/*
 * Read the free-running mtime counter via the rdtime pseudo-instruction.
 * Accessible from S-mode per RISC-V Priv Spec §10.1 (Zicntr extension).
 */
static inline uint64_t read_time(void)
{
    uint64_t t;
    asm volatile("rdtime %0" : "=r"(t));
    return t;
}

int hwtimer_init(void)
{
    uint64_t now = read_time();
    sbi_set_timer(now + TICKNUM_PER_TIMER);
    return 0;
}

int hwtimer_handler(void)
{
    uint64_t now = read_time();
    sbi_set_timer(now + TICKNUM_PER_TIMER);
    return 0;
}