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
//! Real Time For the Masses (RTFM) framework for ARM Cortex-M microcontrollers
//!
//! **IMPORTANT**: This crate is published as [`cortex-m-rtfm`] on crates.io but the name of the
//! library is `rtfm`.
//!
//! [`cortex-m-rtfm`]: https://crates.io/crates/cortex-m-rtfm
//!
//! The user level documentation can be found [here].
//!
//! [here]: https://japaric.github.io/cortex-m-rtfm/book/en/
//!
//! Don't forget to check the documentation of the [`#[app]`] attribute, which is the main component
//! of the framework.
//!
//! [`#[app]`]: ../cortex_m_rtfm_macros/attr.app.html
//!
//! # Minimum Supported Rust Version (MSRV)
//!
//! This crate is guaranteed to compile on stable Rust 1.36 (2018 edition) and up. It *might*
//! compile on older versions but that may change in any new patch release.
//!
//! # Semantic Versioning
//!
//! Like the Rust project, this crate adheres to [SemVer]: breaking changes in the API and semantics
//! require a *semver bump* (a new minor version release), with the exception of breaking changes
//! that fix soundness issues -- those are considered bug fixes and can be landed in a new patch
//! release.
//!
//! [SemVer]: https://semver.org/spec/v2.0.0.html
//!
//! # Cargo features
//!
//! - `timer-queue`. This opt-in feature enables the `schedule` API which can be used to schedule
//! tasks to run in the future. Also see [`Instant`] and [`Duration`].
//!
//! [`Instant`]: struct.Instant.html
//! [`Duration`]: struct.Duration.html
//!
//! - `nightly`. Enabling this opt-in feature makes RTFM internally use the unstable
//! `core::mem::MaybeUninit` API and unstable `const_fn` language feature to reduce static memory
//! usage, runtime overhead and initialization overhead. This feature requires a nightly compiler
//! and may stop working at any time!

#![cfg_attr(feature = "nightly", feature(maybe_uninit_extra))]
#![deny(missing_docs)]
#![deny(warnings)]
#![no_std]

#[cfg(feature = "timer-queue")]
use core::cmp::Ordering;
use core::{fmt, ops};

#[cfg(not(feature = "timer-queue"))]
use cortex_m::peripheral::SYST;
use cortex_m::{
    interrupt::Nr,
    peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, TPIU},
};
pub use cortex_m_rtfm_macros::app;

#[doc(hidden)]
pub mod export;
#[doc(hidden)]
#[cfg(feature = "timer-queue")]
mod tq;

#[cfg(all(feature = "timer-queue", armv6m))]
compile_error!(
    "The `timer-queue` feature is currently not supported on ARMv6-M (`thumbv6m-none-eabi`)"
);

/// Core peripherals
///
/// This is `cortex_m::Peripherals` minus the peripherals that the RTFM runtime uses
///
/// - The `NVIC` field is never present.
/// - When the `timer-queue` feature is enabled the following fields are *not* present: `DWT` and
/// `SYST`.
#[allow(non_snake_case)]
pub struct Peripherals<'a> {
    /// Cache and branch predictor maintenance operations (not present on Cortex-M0 variants)
    pub CBP: CBP,

    /// CPUID
    pub CPUID: CPUID,

    /// Debug Control Block (by value if the `timer-queue` feature is disabled)
    #[cfg(feature = "timer-queue")]
    pub DCB: &'a mut DCB,

    /// Debug Control Block (borrowed if the `timer-queue` feature is enabled)
    #[cfg(not(feature = "timer-queue"))]
    pub DCB: DCB,

    /// Data Watchpoint and Trace unit (not present if the `timer-queue` feature is enabled)
    #[cfg(not(feature = "timer-queue"))]
    pub DWT: DWT,

    /// Flash Patch and Breakpoint unit (not present on Cortex-M0 variants)
    pub FPB: FPB,

    /// Floating Point Unit (only present on `thumbv7em-none-eabihf`)
    pub FPU: FPU,

    /// Instrumentation Trace Macrocell (not present on Cortex-M0 variants)
    pub ITM: ITM,

    /// Memory Protection Unit
    pub MPU: MPU,

    // Nested Vector Interrupt Controller
    // pub NVIC: NVIC,
    /// System Control Block
    pub SCB: &'a mut SCB,

    /// SysTick: System Timer (not present if the `timer-queue` is enabled)
    #[cfg(not(feature = "timer-queue"))]
    pub SYST: SYST,

    /// Trace Port Interface Unit (not present on Cortex-M0 variants)
    pub TPIU: TPIU,
}

/// A measurement of a monotonically nondecreasing clock. Opaque and useful only with `Duration`
///
/// This data type is only available when the `timer-queue` feature is enabled
///
/// **NOTE:** Both `Instant` and `Duration` are only meant to be used with the `schedule` API.
///
/// We can't stop you from using `Instant.sub` to measure things so please be aware that you won't
/// be able to measure events that span longer than `(1 << 31) - 1` core clock cycles.
///
/// Also note that adding a duration equal or greater than `(1 << 31).cycles()` to an `Instant` will
/// effectively overflow it. There's a debug assertion in place to prevent this user error but it's
/// not possible to catch this error with 100% success rate because one can write `(instant +
/// duration) + duration` to bypass runtime checks.<Paste>
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg(feature = "timer-queue")]
pub struct Instant(i32);

#[cfg(feature = "timer-queue")]
impl Instant {
    /// IMPLEMENTATION DETAIL. DO NOT USE
    #[doc(hidden)]
    pub fn artificial(timestamp: i32) -> Self {
        Instant(timestamp)
    }

    /// Returns an instant corresponding to "now"
    pub fn now() -> Self {
        Instant(DWT::get_cycle_count() as i32)
    }

    /// Returns the amount of time elapsed since this instant was created.
    pub fn elapsed(&self) -> Duration {
        Instant::now() - *self
    }

    /// Returns the amount of time elapsed from another instant to this one.
    pub fn duration_since(&self, earlier: Instant) -> Duration {
        let diff = self.0 - earlier.0;
        assert!(diff >= 0, "second instant is later than self");
        Duration(diff as u32)
    }
}

#[cfg(feature = "timer-queue")]
impl ops::AddAssign<Duration> for Instant {
    fn add_assign(&mut self, dur: Duration) {
        debug_assert!(dur.0 < (1 << 31));
        self.0 = self.0.wrapping_add(dur.0 as i32);
    }
}

#[cfg(feature = "timer-queue")]
impl ops::Add<Duration> for Instant {
    type Output = Self;

    fn add(mut self, dur: Duration) -> Self {
        self += dur;
        self
    }
}

#[cfg(feature = "timer-queue")]
impl ops::SubAssign<Duration> for Instant {
    fn sub_assign(&mut self, dur: Duration) {
        // XXX should this be a non-debug assertion?
        debug_assert!(dur.0 < (1 << 31));
        self.0 = self.0.wrapping_sub(dur.0 as i32);
    }
}

#[cfg(feature = "timer-queue")]
impl ops::Sub<Duration> for Instant {
    type Output = Self;

    fn sub(mut self, dur: Duration) -> Self {
        self -= dur;
        self
    }
}

#[cfg(feature = "timer-queue")]
impl ops::Sub<Instant> for Instant {
    type Output = Duration;

    fn sub(self, other: Instant) -> Duration {
        self.duration_since(other)
    }
}

#[cfg(feature = "timer-queue")]
impl Ord for Instant {
    fn cmp(&self, rhs: &Self) -> Ordering {
        self.0.wrapping_sub(rhs.0).cmp(&0)
    }
}

#[cfg(feature = "timer-queue")]
impl PartialOrd for Instant {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

/// A `Duration` type to represent a span of time.
///
/// This data type is only available when the `timer-queue` feature is enabled
///
/// **NOTE:** Both `Instant` and `Duration` are only meant to be used with the `schedule` API.
///
/// `Duration` has a resolution of 1 core clock cycle and an effective (half-open) range of `0..(1
/// << 31)` (end not included) *core clock cycles*.
///
/// Be aware that scheduling a (periodic) task more than `(1 << 24).cycles()` in the future will
/// incur in additional overhead proportional to the value of the `Duration`. If you need periodic
/// tasks with periods greater than `1 << 24` (e.g. with periods in seconds) you likely don't a
/// resolution of one core clock cycle so we suggest you use a hardware timer with an appropriate
/// prescaler.
#[derive(Clone, Copy, Default, Eq, Ord, PartialEq, PartialOrd)]
#[cfg(feature = "timer-queue")]
pub struct Duration(u32);

#[cfg(feature = "timer-queue")]
impl Duration {
    /// Returns the total number of clock cycles contained by this `Duration`
    pub fn as_cycles(&self) -> u32 {
        self.0
    }
}

#[cfg(feature = "timer-queue")]
impl ops::AddAssign for Duration {
    fn add_assign(&mut self, dur: Duration) {
        self.0 += dur.0;
    }
}

#[cfg(feature = "timer-queue")]
impl ops::Add<Duration> for Duration {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Duration(self.0 + other.0)
    }
}

#[cfg(feature = "timer-queue")]
impl ops::SubAssign for Duration {
    fn sub_assign(&mut self, rhs: Duration) {
        self.0 -= rhs.0;
    }
}

#[cfg(feature = "timer-queue")]
impl ops::Sub<Duration> for Duration {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        Duration(self.0 - rhs.0)
    }
}

/// Adds the `cycles` method to the `u32` type
///
/// This trait is only available when the `timer-queue` feature is enabled
#[cfg(feature = "timer-queue")]
pub trait U32Ext {
    /// Converts the `u32` value into clock cycles
    fn cycles(self) -> Duration;
}

#[cfg(feature = "timer-queue")]
impl U32Ext for u32 {
    fn cycles(self) -> Duration {
        Duration(self)
    }
}

/// Memory safe access to shared resources
///
/// In RTFM, locks are implemented as critical sections that prevent other tasks from *starting*.
/// These critical sections are implemented by temporarily increasing the dynamic priority (see
/// [BASEPRI]) of the current context. Entering and leaving these critical sections is always done
/// in constant time (a few instructions).
///
/// [BASEPRI]: https://developer.arm.com/products/architecture/cpu-architecture/m-profile/docs/100701/latest/special-purpose-mask-registers
pub trait Mutex {
    /// Data protected by the mutex
    type T;

    /// Creates a critical section and grants temporary access to the protected data
    fn lock<R, F>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Self::T) -> R;
}

impl<'a, M> Mutex for &'a mut M
where
    M: Mutex,
{
    type T = M::T;

    fn lock<R, F>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Self::T) -> R,
    {
        (**self).lock(f)
    }
}

/// Newtype over `&'a mut T` that implements the `Mutex` trait
///
/// The `Mutex` implementation for this type is a no-op, no critical section is created
pub struct Exclusive<'a, T>(pub &'a mut T);

impl<'a, T> Mutex for Exclusive<'a, T> {
    type T = T;

    fn lock<R, F>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Self::T) -> R,
    {
        f(self.0)
    }
}

impl<'a, T> fmt::Debug for Exclusive<'a, T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<'a, T> fmt::Display for Exclusive<'a, T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl<'a, T> ops::Deref for Exclusive<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.0
    }
}

impl<'a, T> ops::DerefMut for Exclusive<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.0
    }
}

/// Sets the given `interrupt` as pending
///
/// This is a convenience function around
/// [`NVIC::pend`](../cortex_m/peripheral/struct.NVIC.html#method.pend)
pub fn pend<I>(interrupt: I)
where
    I: Nr,
{
    NVIC::pend(interrupt)
}