sam4l/
ast.rs

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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Implementation of a single hardware timer.
//!
//! - Author: Amit Levy <levya@cs.stanford.edu>
//! - Author: Philip Levis <pal@cs.stanford.edu>
//! - Date: September 17, 2020

use crate::pm::{self, PBDClock};
use kernel::hil::time::{self, Ticks};
use kernel::hil::Controller;
use kernel::utilities::cells::OptionalCell;
use kernel::utilities::registers::interfaces::{ReadWriteable, Readable, Writeable};
use kernel::utilities::registers::{register_bitfields, ReadOnly, ReadWrite, WriteOnly};
use kernel::utilities::StaticRef;
use kernel::ErrorCode;

/// Minimum number of clock tics to make sure ALARM0 register is synchronized
///
/// The datasheet has the following ominous language (Section 19.5.3.2):
///
/// > Because of synchronization, the transfer of the alarm value will not
/// > happen immediately. When changing/setting the alarm value, the user must
/// > make sure that the counter will not count the selected alarm value before
/// > the value is transferred to the register. In that case, the first alarm
/// > interrupt after the change will not be triggered.
///
/// In practice, we've observed that when the alarm is set for a counter value
/// less than or equal to four tics ahead of the current counter value, the
/// alarm interrupt doesn't fire. Thus, we simply round up to at least eight
/// tics. Seems safe enough and in practice has seemed to work.
const ALARM0_SYNC_TICS: u32 = 8;

#[repr(C)]
struct AstRegisters {
    cr: ReadWrite<u32, Control::Register>,
    cv: ReadWrite<u32, Value::Register>,
    sr: ReadOnly<u32, Status::Register>,
    scr: WriteOnly<u32, Interrupt::Register>,
    ier: WriteOnly<u32, Interrupt::Register>,
    idr: WriteOnly<u32, Interrupt::Register>,
    imr: ReadOnly<u32, Interrupt::Register>,
    wer: ReadWrite<u32, Event::Register>,
    // 0x20
    ar0: ReadWrite<u32, Value::Register>,
    ar1: ReadWrite<u32, Value::Register>,
    _reserved0: [u32; 2],
    pir0: ReadWrite<u32, PeriodicInterval::Register>,
    pir1: ReadWrite<u32, PeriodicInterval::Register>,
    _reserved1: [u32; 2],
    // 0x40
    clock: ReadWrite<u32, ClockControl::Register>,
    dtr: ReadWrite<u32, DigitalTuner::Register>,
    eve: WriteOnly<u32, Event::Register>,
    evd: WriteOnly<u32, Event::Register>,
    evm: ReadOnly<u32, Event::Register>,
    calv: ReadWrite<u32, Calendar::Register>, // we leave out parameter and version
}

register_bitfields![u32,
    Control [
        /// Prescalar Select
        PSEL OFFSET(16) NUMBITS(5) [],
        /// Clear on Alarm 1
        CA1  OFFSET(9) NUMBITS(1) [
            NoClearCounter = 0,
            ClearCounter = 1
        ],
        /// Clear on Alarm 0
        CA0  OFFSET(8) NUMBITS(1) [
            NoClearCounter = 0,
            ClearCounter = 1
        ],
        /// Calendar Mode
        CAL  OFFSET(2) NUMBITS(1) [
            CounterMode = 0,
            CalendarMode = 1
        ],
        /// Prescalar Clear
        PCLR OFFSET(1) NUMBITS(1) [],
        /// Enable
        EN   OFFSET(0) NUMBITS(1) [
            Disable = 0,
            Enable = 1
        ]
    ],

    Value [
        VALUE OFFSET(0) NUMBITS(32) []
    ],

    Status [
        /// Clock Ready
        CLKRDY 29,
        /// Clock Busy
        CLKBUSY 28,
        /// AST Ready
        READY 25,
        /// AST Busy
        BUSY 24,
        /// Periodic 0
        PER0 16,
        /// Alarm 0
        ALARM0 8,
        /// Overflow
        OVF 0
    ],

    Interrupt [
        /// Clock Ready
        CLKRDY 29,
        /// AST Ready
        READY 25,
        /// Periodic 0
        PER0 16,
        /// Alarm 0
        ALARM0 8,
        /// Overflow
        OVF 0
    ],

    Event [
        /// Periodic 0
        PER0 16,
        /// Alarm 0
        ALARM0 8,
        /// Overflow
        OVF 0
    ],

    PeriodicInterval [
        /// Interval Select
        INSEL OFFSET(0) NUMBITS(5) []
    ],

    ClockControl [
        /// Clock Source Selection
        CSSEL OFFSET(8) NUMBITS(3) [
            RCSYS = 0,
            OSC32 = 1,
            APBClock = 2,
            GCLK = 3,
            Clk1k = 4
        ],
        /// Clock Enable
        CEN   OFFSET(0) NUMBITS(1) [
            Disable = 0,
            Enable = 1
        ]
    ],

    DigitalTuner [
        VALUE OFFSET(8) NUMBITS(8) [],
        ADD   OFFSET(5) NUMBITS(1) [],
        EXP   OFFSET(0) NUMBITS(5) []
    ],

    Calendar [
        YEAR  OFFSET(26) NUMBITS(6) [],
        MONTH OFFSET(22) NUMBITS(4) [],
        DAY   OFFSET(17) NUMBITS(5) [],
        HOUR  OFFSET(12) NUMBITS(5) [],
        MIN   OFFSET( 6) NUMBITS(6) [],
        SEC   OFFSET( 0) NUMBITS(6) []
    ]
];

const AST_ADDRESS: StaticRef<AstRegisters> =
    unsafe { StaticRef::new(0x400F0800 as *const AstRegisters) };

pub struct Ast<'a> {
    registers: StaticRef<AstRegisters>,
    callback: OptionalCell<&'a dyn time::AlarmClient>,
}

impl Ast<'_> {
    pub const fn new() -> Self {
        Self {
            registers: AST_ADDRESS,
            callback: OptionalCell::empty(),
        }
    }
}

impl Controller for Ast<'_> {
    type Config = &'static dyn time::AlarmClient;

    fn configure(&self, client: Self::Config) {
        self.callback.set(client);

        pm::enable_clock(pm::Clock::PBD(PBDClock::AST));
        self.select_clock(Clock::ClockOsc32);
        self.disable();
        self.disable_alarm_irq();
        self.set_prescalar(0); // 32KHz / (2^(0 + 1)) = 16KHz
        self.enable_alarm_wake();

        self.clear_alarm();
    }
}

#[repr(usize)]
#[allow(dead_code)]
enum Clock {
    ClockRCSys = 0,
    ClockOsc32 = 1,
    ClockAPB = 2,
    ClockGclk2 = 3,
    Clock1K = 4,
}

impl Ast<'_> {
    fn clock_busy(&self) -> bool {
        self.registers.sr.is_set(Status::CLKBUSY)
    }

    fn busy(&self) -> bool {
        self.registers.sr.is_set(Status::BUSY)
    }

    /// Clears the alarm bit in the status register (indicating the alarm value
    /// has been reached).
    fn clear_alarm(&self) {
        while self.busy() {}
        self.registers.scr.write(Interrupt::ALARM0::SET);
        while self.busy() {}
    }

    // Configure the clock to use to drive the AST
    fn select_clock(&self, clock: Clock) {
        // Disable clock by setting first bit to zero
        while self.clock_busy() {}
        self.registers.clock.modify(ClockControl::CEN::CLEAR);
        while self.clock_busy() {}

        // Select clock
        self.registers
            .clock
            .write(ClockControl::CSSEL.val(clock as u32));
        while self.clock_busy() {}

        // Re-enable clock
        self.registers.clock.modify(ClockControl::CEN::SET);
        while self.clock_busy() {}
    }

    /// Enables the AST registers
    fn enable(&self) {
        while self.busy() {}
        self.registers.cr.modify(Control::EN::SET);
        while self.busy() {}
    }

    /// Disable the AST registers
    fn disable(&self) {
        while self.busy() {}
        self.registers.cr.modify(Control::EN::CLEAR);
        while self.busy() {}
    }

    fn is_enabled(&self) -> bool {
        let regs: &AstRegisters = &self.registers;
        while self.busy() {}
        regs.cr.is_set(Control::EN)
    }

    /// Returns if an alarm is currently set
    fn is_alarm_enabled(&self) -> bool {
        while self.busy() {}
        self.registers.sr.is_set(Status::ALARM0)
    }

    fn set_prescalar(&self, val: u8) {
        while self.busy() {}
        self.registers.cr.modify(Control::PSEL.val(val as u32));
        while self.busy() {}
    }

    fn enable_alarm_irq(&self) {
        self.registers.ier.write(Interrupt::ALARM0::SET);
    }

    fn disable_alarm_irq(&self) {
        self.registers.idr.write(Interrupt::ALARM0::SET);
    }

    fn enable_alarm_wake(&self) {
        while self.busy() {}
        self.registers.wer.modify(Event::ALARM0::SET);
        while self.busy() {}
    }

    fn get_counter(&self) -> u32 {
        while self.busy() {}
        self.registers.cv.read(Value::VALUE)
    }

    fn set_counter(&self, val: u32) {
        let regs: &AstRegisters = &self.registers;
        while self.busy() {}
        regs.cv.set(val);
    }

    pub fn handle_interrupt(&self) {
        self.clear_alarm();
        self.callback.map(|cb| {
            cb.alarm();
        });
    }
}

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

    fn now(&self) -> Self::Ticks {
        Self::Ticks::from(self.get_counter())
    }
}

impl<'a> time::Counter<'a> for Ast<'a> {
    fn set_overflow_client(&self, _client: &'a dyn time::OverflowClient) {}

    fn start(&self) -> Result<(), ErrorCode> {
        self.enable();
        Ok(())
    }

    fn stop(&self) -> Result<(), ErrorCode> {
        self.disable();
        Ok(())
    }

    fn reset(&self) -> Result<(), ErrorCode> {
        self.set_counter(0);
        Ok(())
    }

    fn is_running(&self) -> bool {
        self.is_enabled()
    }
}

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

    fn set_alarm(&self, reference: Self::Ticks, dt: Self::Ticks) {
        let now = Self::Ticks::from(self.get_counter());
        let mut expire = reference.wrapping_add(dt);
        if !now.within_range(reference, expire) {
            // We have already passed when: just fire ASAP
            // Note this will also trigger the increment below
            expire = now;
        }

        // Firing is too close in the future, delay it a bit
        // to make sure we don't miss the tick
        if expire.wrapping_sub(now).into_u32() <= ALARM0_SYNC_TICS {
            expire = now.wrapping_add(Self::Ticks::from(ALARM0_SYNC_TICS));
        }

        // Clear any alarm event that may be pending before setting new alarm.
        self.clear_alarm();

        while self.busy() {}
        self.registers
            .ar0
            .write(Value::VALUE.val(expire.into_u32()));

        while self.busy() {}
        self.enable_alarm_irq();
        self.enable();
    }

    fn get_alarm(&self) -> Self::Ticks {
        while self.busy() {}
        Self::Ticks::from(self.registers.ar0.read(Value::VALUE))
    }

    fn disarm(&self) -> Result<(), ErrorCode> {
        // After disabling the IRQ and clearing the alarm bit in the
        // status register, the NVIC bit is also guaranteed to be clear.
        self.disable_alarm_irq();
        self.clear_alarm();
        Ok(())
    }

    fn is_armed(&self) -> bool {
        self.is_alarm_enabled()
    }

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