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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Internal Timer

use kernel::hil::time;
use kernel::hil::time::{Alarm, ConvertTicks, Counter, Ticks, Ticks32, Time};
use kernel::utilities::cells::OptionalCell;
use kernel::utilities::registers::interfaces::{ReadWriteable, Readable, Writeable};
use kernel::utilities::registers::register_bitfields;
use kernel::ErrorCode;
use riscv_csr::csr::ReadWriteRiscvCsr;

/// 50MHz `Frequency`
#[derive(Debug)]
pub struct Freq50MHz;
impl time::Frequency for Freq50MHz {
    fn frequency() -> u32 {
        50_000_000
    }
}

pub enum TimerNumber {
    ZERO,
    ONE,
}

register_bitfields![usize,
    MITCNT [
        COUNT OFFSET(0) NUMBITS(32) []
    ],
    MITB [
        BOUND OFFSET(0) NUMBITS(32) []
    ],
    MITCTL [
        ENABLE OFFSET(0) NUMBITS(1) [],
        HALT_EN OFFSET(1) NUMBITS(1) [],
        PAUSE_EN OFFSET(2) NUMBITS(1) [],
    ],
];

pub struct Timer<'a> {
    number: TimerNumber,
    alarm_client: OptionalCell<&'a dyn time::AlarmClient>,

    mitcnt0: ReadWriteRiscvCsr<usize, MITCNT::Register, 0x7D2>,
    mitcnt1: ReadWriteRiscvCsr<usize, MITCNT::Register, 0x7D5>,

    mitb0: ReadWriteRiscvCsr<usize, MITB::Register, 0x7D3>,
    mitb1: ReadWriteRiscvCsr<usize, MITB::Register, 0x7D6>,

    mitctl0: ReadWriteRiscvCsr<usize, MITCTL::Register, 0x7D4>,
    mitctl1: ReadWriteRiscvCsr<usize, MITCTL::Register, 0x7D7>,
}

impl Timer<'_> {
    pub const fn new(number: TimerNumber) -> Self {
        Timer {
            number,
            alarm_client: OptionalCell::empty(),
            mitcnt0: ReadWriteRiscvCsr::new(),
            mitcnt1: ReadWriteRiscvCsr::new(),
            mitb0: ReadWriteRiscvCsr::new(),
            mitb1: ReadWriteRiscvCsr::new(),
            mitctl0: ReadWriteRiscvCsr::new(),
            mitctl1: ReadWriteRiscvCsr::new(),
        }
    }

    pub fn handle_interrupt(&self) {
        let _ = self.stop();
        self.alarm_client.map(|client| {
            client.alarm();
        });
    }
}

impl time::Time for Timer<'_> {
    type Frequency = Freq50MHz;
    type Ticks = Ticks32;

    fn now(&self) -> Self::Ticks {
        match self.number {
            TimerNumber::ZERO => Self::Ticks::from(self.mitcnt0.get() as u32),
            TimerNumber::ONE => Self::Ticks::from(self.mitcnt1.get() as u32),
        }
    }
}

impl<'a> Counter<'a> for Timer<'a> {
    fn set_overflow_client(&self, _client: &'a dyn time::OverflowClient) {
        // We have no way to know when this happens
    }

    fn start(&self) -> Result<(), ErrorCode> {
        match self.number {
            TimerNumber::ZERO => self.mitctl0.modify(MITCTL::ENABLE::SET),
            TimerNumber::ONE => self.mitctl1.modify(MITCTL::ENABLE::SET),
        };

        Ok(())
    }

    fn stop(&self) -> Result<(), ErrorCode> {
        match self.number {
            TimerNumber::ZERO => self.mitctl0.modify(MITCTL::ENABLE::CLEAR),
            TimerNumber::ONE => self.mitctl1.modify(MITCTL::ENABLE::CLEAR),
        };

        Ok(())
    }

    fn reset(&self) -> Result<(), ErrorCode> {
        // A counter is only cleared when it is equal or greater then
        // mitb.
        Err(ErrorCode::FAIL)
    }

    fn is_running(&self) -> bool {
        match self.number {
            TimerNumber::ZERO => self.mitctl0.is_set(MITCTL::ENABLE),
            TimerNumber::ONE => self.mitctl1.is_set(MITCTL::ENABLE),
        }
    }
}

impl<'a> Alarm<'a> for Timer<'a> {
    fn set_alarm_client(&self, client: &'a dyn time::AlarmClient) {
        self.alarm_client.set(client);
    }

    fn set_alarm(&self, reference: Self::Ticks, dt: Self::Ticks) {
        // Start the counter
        if !self.is_running() {
            let _ = Counter::start(self);
        }

        let now = self.now();
        let mut expire = reference.wrapping_add(dt);

        if !now.within_range(reference, expire) {
            expire = now;
        }

        let mut val = expire.into_usize();

        // 0xFFFF_FFFF is reserved to indicate disabled, don't set that value
        if val == 0xFFFF_FFFF {
            val += 1;
        }

        match self.number {
            TimerNumber::ZERO => self.mitb0.write(MITB::BOUND.val(val)),
            TimerNumber::ONE => self.mitb1.write(MITB::BOUND.val(val)),
        }
    }

    fn get_alarm(&self) -> Self::Ticks {
        match self.number {
            TimerNumber::ZERO => Self::Ticks::from(self.mitb0.read(MITB::BOUND) as u32),
            TimerNumber::ONE => Self::Ticks::from(self.mitb1.read(MITB::BOUND) as u32),
        }
    }

    fn disarm(&self) -> Result<(), ErrorCode> {
        match self.number {
            TimerNumber::ZERO => self.mitb0.write(MITB::BOUND.val(0xFFFF_FFFF)),
            TimerNumber::ONE => self.mitb1.write(MITB::BOUND.val(0xFFFF_FFFF)),
        };

        Ok(())
    }

    fn is_armed(&self) -> bool {
        match self.number {
            TimerNumber::ZERO => self.mitb0.read(MITB::BOUND) != 0xFFFF_FFFF,
            TimerNumber::ONE => self.mitb1.read(MITB::BOUND) != 0xFFFF_FFFF,
        }
    }

    fn minimum_dt(&self) -> Self::Ticks {
        Self::Ticks::from(1_u32)
    }
}

impl kernel::platform::scheduler_timer::SchedulerTimer for Timer<'_> {
    fn start(&self, us: u32) {
        let now = self.now();
        let tics = self.ticks_from_us(us);
        self.set_alarm(now, tics);
    }

    fn reset(&self) {
        let _ = self.stop();
    }

    fn arm(&self) {
        // start() has already armed the timer
    }

    fn disarm(&self) {
        // We have no way to "disarm" a timer with stopping it unless we
        // mask the interrupt in the PIC
    }

    fn get_remaining_us(&self) -> Option<u32> {
        let alarm = self.get_alarm();
        let now = self.now();

        if alarm > now {
            Some(alarm.wrapping_sub(now).into_u32())
        } else {
            None
        }
    }
}