summaryrefslogtreecommitdiff
path: root/ports/risc-v64/gnu/example_build/erbium/hwtimer.c
blob: 511bea596a26ea93116d74e9a888d6d992e6ca5a (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
/***************************************************************************
 * Copyright (c) 2026 Eclipse ThreadX contributors
 *
 * 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.
 *
 * AI Disclosure: This file was largely AI-generated by Claude Code (Opus 5.5).
 * The AI-generated portions may be considered public domain (CC0-1.0)
 * and not subject to the project's licence. The human contributor has
 * reviewed and verified that the code is correct.
 *
 * SPDX-License-Identifier: MIT and CC0-1.0
 **************************************************************************/

#include "tx_api.h"
#include "hwtimer.h"

/* Naturally aligned 64-bit MMIO accesses are single loads and stores on
   RV64; volatile keeps the compiler from caching or reordering them.  */
#define MTIME                   (*(volatile uint64_t *)ERBIUM_MTIME)
#define MTIMECMP                (*(volatile uint64_t *)ERBIUM_MTIMECMP)

int hwtimer_init(void)
{
    MTIMECMP = MTIME + TICKNUM_PER_TIMER;
    return 0;
}

int hwtimer_handler(void)
{
    /* Advance from the previous compare value, so trap latency does not
       accumulate as tick drift.  */
    uint64_t next = MTIMECMP + TICKNUM_PER_TIMER;
    uint64_t now = MTIME;

    if (next <= now)
        next = now + TICKNUM_PER_TIMER;

    MTIMECMP = next;
    return 0;
}