summaryrefslogtreecommitdiffstats
path: root/firmware/src/timer.rs
blob: b9908b54ab1face2dcb3abb0205878e0a26695e3 (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
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
218
219
220
221
222
223
224
225
use crate::{
    hw::mcu,
    mutex::{AnyCtx, LazyMainInit, MainCtx, MutexCell},
};

#[allow(non_snake_case)]
pub struct TimerPeriph {
    pub TC0: mcu::TC0,
}

// SAFETY: This variable is initialized when constructing the MainCtx.
pub static TIMER_PERIPH: LazyMainInit<TimerPeriph> = unsafe { LazyMainInit::uninit() };

static TIMER_UPPER: MutexCell<u8> = MutexCell::new(0);

pub const TIMER_TICK_US: u8 = 16; // 16 us per tick.

pub fn timer_init(m: &MainCtx) {
    // Timer 0 configuration:
    // CS: 256 -> 16 us per timer tick.
    TIMER_PERIPH
        .deref(m)
        .TC0
        .tccr0
        .write(|w| w.cs0().running_clk_256());
}

// SAFETY: This function may only do atomic-read-only accesses, because it's
//         called from all contexts, including interrupt context.
#[inline(always)]
pub fn timer_get(a: &AnyCtx) -> Timestamp {
    // SAFETY: This function only does atomic peripheral read-only accesses.
    //         Therefore, it is safe to pretend to be the main context, even
    //         if we were actually called from irq context.
    let m = unsafe { a.to_main_ctx() };

    TIMER_PERIPH.deref(&m).TC0.tcnt0.read().bits().into()
}

#[inline(never)]
pub fn timer_get_large(m: &MainCtx) -> LargeTimestamp {
    let mut upper = TIMER_UPPER.get(m);
    let mut lower = TIMER_PERIPH.deref(m).TC0.tcnt0.read().bits();

    // Increment the upper part, if the lower part had an overflow.
    if TIMER_PERIPH.deref(m).TC0.tifr.read().tov0().bit() {
        TIMER_PERIPH.deref(m).TC0.tifr.write(|w| w.tov0().set_bit());
        lower = TIMER_PERIPH.deref(m).TC0.tcnt0.read().bits();
        upper = upper.wrapping_add(1);
        TIMER_UPPER.set(m, upper);
    }

    ((upper as u16) << 8 | lower as u16).into()
}

macro_rules! impl_timestamp {
    ($rel:ident, $abs:ident, $reltype:ty, $abstype:ty) => {
        #[derive(PartialEq, Eq, Copy, Clone)]
        pub struct $abs(pub $abstype);

        impl $abs {
            #[inline]
            pub const fn new() -> Self {
                $abs(0)
            }

            #[inline]
            pub const fn from_ticks(ticks: $abstype) -> Self {
                $abs(ticks)
            }

            #[inline]
            pub const fn from_micros(us: u32) -> $abs {
                $abs((us / TIMER_TICK_US as u32) as $abstype)
            }

            #[inline]
            pub const fn from_millis(ms: u32) -> $abs {
                $abs(((ms * 1000) / TIMER_TICK_US as u32) as $abstype)
            }
        }

        impl Default for $abs {
            #[inline]
            fn default() -> Self {
                Self::new()
            }
        }

        impl Ord for $abs {
            #[inline]
            fn cmp(&self, other: &Self) -> core::cmp::Ordering {
                if self.0 == other.0 {
                    core::cmp::Ordering::Equal
                } else if self.0.wrapping_sub(other.0) & (1 << (<$abstype>::BITS - 1)) == 0 {
                    core::cmp::Ordering::Greater
                } else {
                    core::cmp::Ordering::Less
                }
            }
        }

        impl PartialOrd for $abs {
            #[inline]
            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
                Some(self.cmp(other))
            }
        }

        impl core::ops::Add<$rel> for $abs {
            type Output = Self;

            #[inline]
            fn add(self, other: $rel) -> Self::Output {
                self.0.wrapping_add(other.0 as $abstype).into()
            }
        }

        impl core::ops::Sub for $abs {
            type Output = $rel;

            #[inline]
            fn sub(self, other: Self) -> Self::Output {
                (self.0.wrapping_sub(other.0) as $reltype).into()
            }
        }

        impl From<$abstype> for $abs {
            #[inline]
            fn from(stamp: $abstype) -> Self {
                $abs(stamp)
            }
        }

        impl From<$abs> for $abstype {
            #[inline]
            fn from(stamp: $abs) -> Self {
                stamp.0
            }
        }
    };
}

macro_rules! impl_reltimestamp {
    ($rel:ident, $abs:ident, $reltype:ty, $abstype:ty) => {
        #[derive(PartialEq, Eq, Copy, Clone, PartialOrd, Ord)]
        pub struct $rel(pub $reltype);

        impl $rel {
            #[inline]
            pub const fn new() -> Self {
                $rel(0)
            }

            #[inline]
            pub const fn from_ticks(ticks: $reltype) -> Self {
                $rel(ticks)
            }

            #[inline]
            pub const fn from_micros(us: i32) -> $rel {
                $rel((us / TIMER_TICK_US as i32) as $reltype)
            }

            #[inline]
            pub const fn from_millis(ms: i32) -> $rel {
                $rel(((ms * 1000) / TIMER_TICK_US as i32) as $reltype)
            }
        }

        impl Default for $rel {
            #[inline]
            fn default() -> Self {
                Self::new()
            }
        }

        impl core::ops::Add<$rel> for $rel {
            type Output = Self;

            #[inline]
            fn add(self, other: $rel) -> Self::Output {
                self.0.wrapping_add(other.0).into()
            }
        }

        impl core::ops::Sub for $rel {
            type Output = $rel;

            #[inline]
            fn sub(self, other: Self) -> Self::Output {
                self.0.wrapping_sub(other.0).into()
            }
        }

        impl From<$reltype> for $rel {
            #[inline]
            fn from(relstamp: $reltype) -> Self {
                $rel(relstamp)
            }
        }

        impl From<$rel> for $reltype {
            #[inline]
            fn from(relstamp: $rel) -> Self {
                relstamp.0
            }
        }
    };
}

impl_timestamp!(RelTimestamp, Timestamp, i8, u8);
impl_timestamp!(RelLargeTimestamp, LargeTimestamp, i16, u16);

impl_reltimestamp!(RelTimestamp, Timestamp, i8, u8);
impl_reltimestamp!(RelLargeTimestamp, LargeTimestamp, i16, u16);

impl From<LargeTimestamp> for Timestamp {
    #[inline]
    fn from(stamp: LargeTimestamp) -> Timestamp {
        (stamp.0 as u8).into()
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface