From 3b4c10e790e63ac328a7bdb98451ac11d5935731 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Thu, 26 Nov 2020 18:07:22 +0100 Subject: Removed monotonic trait, moved to rtic-core --- src/lib.rs | 44 -------------------------------------------- 1 file changed, 44 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index f1fb550..385b5ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -108,50 +108,6 @@ impl From for Peripherals { } } -/// A fraction -pub struct Fraction { - /// The numerator - pub numerator: u32, - - /// The denominator - pub denominator: u32, -} - -/// A monotonic clock / counter -pub trait Monotonic { - /// A measurement of this clock, use `CYCCNT` as a reference implementation for `Instant`. - /// Note that the Instant must be a signed value such as `i32`. - type Instant: Copy + Ord + Sub; - - /// The ratio between the system timer (SysTick) frequency and this clock frequency, i.e. - /// `Monotonic clock * Fraction = System clock` - /// - /// The ratio must be expressed in *reduced* `Fraction` form to prevent overflows. That is - /// `2 / 3` instead of `4 / 6` - fn ratio() -> Fraction; - - /// Returns the current time - /// - /// # Correctness - /// - /// This function is *allowed* to return nonsensical values if called before `reset` is invoked - /// by the runtime. Therefore application authors should *not* call this function during the - /// `#[init]` phase. - fn now() -> Self::Instant; - - /// Resets the counter to *zero* - /// - /// # Safety - /// - /// This function will be called *exactly once* by the RTIC runtime after `#[init]` returns and - /// before tasks can start; this is also the case in multi-core applications. User code must - /// *never* call this function. - unsafe fn reset(); - - /// A `Self::Instant` that represents a count of *zero* - fn zero() -> Self::Instant; -} - /// Sets the given `interrupt` as pending /// /// This is a convenience function around -- cgit v1.2.3 From ef50aeb2e8245b69843280fabb62589c0716ffdd Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Thu, 3 Dec 2020 21:04:06 +0100 Subject: Save, init generation fixed --- Cargo.toml | 3 +- examples/test_new_monotonic.rs | 21 +++ macros/Cargo.toml | 2 +- macros/src/check.rs | 14 +- macros/src/codegen.rs | 2 - macros/src/codegen/init.rs | 28 +++- macros/src/codegen/module.rs | 6 + macros/src/codegen/post_init.rs | 3 + macros/src/codegen/util.rs | 8 ++ macros/src/lib.rs | 2 +- src/export.rs | 2 +- src/lib.rs | 68 +-------- src/tq.rs | 312 ++++++++++++++++++++-------------------- 13 files changed, 229 insertions(+), 242 deletions(-) create mode 100644 examples/test_new_monotonic.rs (limited to 'src') diff --git a/Cargo.toml b/Cargo.toml index 9a10ec2..679dcc0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,8 @@ required-features = ["__v7"] [dependencies] cortex-m = "0.6.2" cortex-m-rtic-macros = { path = "macros", version = "0.6.0-alpha.0" } -rtic-core = "0.3.1" +rtic-core = { git = "https://github.com/rtic-rs/rtic-core", branch = "new_monotonic" } +#rtic-core = "0.3.1" heapless = "0.5.0" bare-metal = "1.0.0" diff --git a/examples/test_new_monotonic.rs b/examples/test_new_monotonic.rs new file mode 100644 index 0000000..5aac48b --- /dev/null +++ b/examples/test_new_monotonic.rs @@ -0,0 +1,21 @@ +//! examples/test_new_monotonic.rs + +#![no_main] +#![no_std] + +use panic_semihosting as _; // panic handler +use rtic::app; + +#[app(device = lm3s6965)] +mod app { + #[monotonic(binds = SomeISR1)] + type Mono1 = hal::Mono1; + + #[monotonic(binds = SomeISR2)] + type Mono2 = hal::Mono2; + + #[init] + fn init(cx: init::Context) -> (init::LateResources, init::Monotonics) { + } +} + diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 3af48c7..6996bef 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -22,5 +22,5 @@ proc-macro2 = "1" proc-macro-error = "1" quote = "1" syn = "1" -rtic-syntax = { git = "https://github.com/rtic-rs/rtic-syntax", branch = "master", version = "0.5.0-alpha.0" } +rtic-syntax = { git = "https://github.com/rtic-rs/rtic-syntax", branch = "new_monotonic", version = "0.5.0-alpha.0" } diff --git a/macros/src/check.rs b/macros/src/check.rs index e3161cb..42bd90d 100644 --- a/macros/src/check.rs +++ b/macros/src/check.rs @@ -62,18 +62,6 @@ pub fn app(app: &App, _analysis: &Analysis) -> parse::Result { for (name, task) in &app.hardware_tasks { let name_s = task.args.binds.to_string(); match &*name_s { - "SysTick" => { - // If the timer queue is used, then SysTick is unavailable - if app.args.monotonic.is_some() { - return Err(parse::Error::new( - name.span(), - "this exception can't be used because it's being used by the runtime", - )); - } else { - // OK - } - } - "NonMaskableInt" | "HardFault" => { return Err(parse::Error::new( name.span(), @@ -88,7 +76,7 @@ pub fn app(app: &App, _analysis: &Analysis) -> parse::Result { if let Some(device) = app.args.device.clone() { Ok(Extra { device, - monotonic: app.args.monotonic.clone(), + monotonic: None, peripherals: app.args.peripherals, }) } else { diff --git a/macros/src/codegen.rs b/macros/src/codegen.rs index 3cddf57..52940bc 100644 --- a/macros/src/codegen.rs +++ b/macros/src/codegen.rs @@ -61,8 +61,6 @@ pub fn app(app: &App, analysis: &Analysis, extra: &Extra) -> TokenStream2 { use super::*; #[no_mangle] unsafe extern "C" fn #main() -> ! { - let _TODO: () = (); - #(#assertion_stmts)* #(#pre_init_stmts)* diff --git a/macros/src/codegen/init.rs b/macros/src/codegen/init.rs index 6376ce3..6b57add 100644 --- a/macros/src/codegen/init.rs +++ b/macros/src/codegen/init.rs @@ -58,6 +58,24 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> CodegenResult { } )); + let monotonic_types: Vec<_> = app + .monotonics + .iter() + .map(|(_, monotonic)| { + let mono = &monotonic.ty; + quote! {#mono} + }) + .collect(); + let monotonics = util::monotonics_ident(&name); + + root_init.push(quote!( + /// Monotonics used by the system + #[allow(non_snake_case)] + pub struct #monotonics( + #(#monotonic_types),* + ); + )); + let mut locals_pat = None; let mut locals_new = None; if !init.locals.is_empty() { @@ -72,10 +90,16 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> CodegenResult { let attrs = &init.attrs; let stmts = &init.stmts; let locals_pat = locals_pat.iter(); + + let mut user_init_return = vec![quote! {#name::LateResources}]; + if !app.monotonics.is_empty() { + user_init_return.push(quote! {#name::Monotonics}); + } + let user_init = Some(quote!( #(#attrs)* #[allow(non_snake_case)] - fn #name(#(#locals_pat,)* #context: #name::Context) -> #name::LateResources { + fn #name(#(#locals_pat,)* #context: #name::Context) -> (#(#user_init_return,)*) { #(#stmts)* } )); @@ -92,7 +116,7 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> CodegenResult { let app_path = quote! {crate::#app_name}; let locals_new = locals_new.iter(); let call_init = Some( - quote!(let late = #app_path::#name(#(#locals_new,)* #name::Context::new(core.into()));), + quote!(let (late, monotonics) = #app_path::#name(#(#locals_new,)* #name::Context::new(core.into()));), ); root_init.push(module::codegen( diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index 2ff4801..d398a1a 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -131,11 +131,17 @@ pub fn codegen( if let Context::Init = ctxt { let init = &app.inits.first().unwrap(); let late_resources = util::late_resources_ident(&init.name); + let monotonics = util::monotonics_ident(&init.name); items.push(quote!( #[doc(inline)] pub use super::#late_resources as LateResources; )); + + items.push(quote!( + #[doc(inline)] + pub use super::#monotonics as Monotonics; + )); } let doc = match ctxt { diff --git a/macros/src/codegen/post_init.rs b/macros/src/codegen/post_init.rs index 5545944..9174dae 100644 --- a/macros/src/codegen/post_init.rs +++ b/macros/src/codegen/post_init.rs @@ -25,6 +25,9 @@ pub fn codegen(app: &App, analysis: &Analysis) -> Vec { } } + // Forget the monotonics so they won't be dropped. + stmts.push(quote!(core::mem::forget(monotonics);)); + // Enable the interrupts -- this completes the `init`-ialization phase stmts.push(quote!(rtic::export::interrupt::enable();)); diff --git a/macros/src/codegen/util.rs b/macros/src/codegen/util.rs index fb8f1a8..4273ee2 100644 --- a/macros/src/codegen/util.rs +++ b/macros/src/codegen/util.rs @@ -111,6 +111,14 @@ pub fn late_resources_ident(init: &Ident) -> Ident { ) } +/// Generates a pre-reexport identifier for the "monotonics" struct +pub fn monotonics_ident(init: &Ident) -> Ident { + Ident::new( + &format!("{}Monotonics", init.to_string()), + Span::call_site(), + ) +} + /// Mangle an ident pub fn mangle_ident(ident: &Ident) -> Ident { Ident::new( diff --git a/macros/src/lib.rs b/macros/src/lib.rs index dc37eae..c9136e5 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -1,4 +1,4 @@ -#![deny(warnings)] +// #![deny(warnings)] extern crate proc_macro; diff --git a/src/export.rs b/src/export.rs index 72d954a..46793aa 100644 --- a/src/export.rs +++ b/src/export.rs @@ -3,7 +3,7 @@ use core::{ sync::atomic::{AtomicBool, Ordering}, }; -pub use crate::tq::{NotReady, TimerQueue}; +//pub use crate::tq::{NotReady, TimerQueue}; pub use bare_metal::CriticalSection; #[cfg(armv7m)] pub use cortex_m::register::basepri; diff --git a/src/lib.rs b/src/lib.rs index 385b5ea..c1930b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,82 +32,20 @@ #![deny(missing_docs)] #![deny(rust_2018_compatibility)] #![deny(rust_2018_idioms)] -#![deny(warnings)] +// #![deny(warnings)] #![no_std] use core::ops::Sub; -use cortex_m::{ - interrupt::Nr, - peripheral::{CBP, CPUID, DCB, DWT, FPB, FPU, ITM, MPU, NVIC, SCB, TPIU}, -}; +use cortex_m::{interrupt::Nr, peripheral::NVIC}; pub use cortex_m_rtic_macros::app; -pub use rtic_core::{prelude as mutex_prelude, Exclusive, Mutex}; +pub use rtic_core::{prelude as mutex_prelude, Exclusive, monotonic::Monotonic, Mutex}; -#[cfg(armv7m)] -pub mod cyccnt; #[doc(hidden)] pub mod export; #[doc(hidden)] mod tq; -/// `cortex_m::Peripherals` minus `SYST` -#[allow(non_snake_case)] -pub struct Peripherals { - /// Cache and branch predictor maintenance operations (not present on Cortex-M0 variants) - pub CBP: CBP, - - /// CPUID - pub CPUID: CPUID, - - /// Debug Control Block - pub DCB: DCB, - - /// Data Watchpoint and Trace unit - 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: SCB, - - // SysTick: System Timer - // pub SYST: SYST, - /// Trace Port Interface Unit (not present on Cortex-M0 variants) - pub TPIU: TPIU, -} - -impl From for Peripherals { - fn from(p: cortex_m::Peripherals) -> Self { - Self { - CBP: p.CBP, - CPUID: p.CPUID, - DCB: p.DCB, - DWT: p.DWT, - FPB: p.FPB, - FPU: p.FPU, - ITM: p.ITM, - MPU: p.MPU, - NVIC: p.NVIC, - SCB: p.SCB, - TPIU: p.TPIU, - } - } -} - /// Sets the given `interrupt` as pending /// /// This is a convenience function around diff --git a/src/tq.rs b/src/tq.rs index b2a84c8..f2539a9 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -1,156 +1,156 @@ -use core::{ - cmp::{self, Ordering}, - convert::TryInto, - mem, - ops::Sub, -}; - -use cortex_m::peripheral::{SCB, SYST}; -use heapless::{binary_heap::Min, ArrayLength, BinaryHeap}; - -use crate::Monotonic; - -pub struct TimerQueue(pub BinaryHeap, N, Min>) -where - M: Monotonic, - ::Output: TryInto, - N: ArrayLength>, - T: Copy; - -impl TimerQueue -where - M: Monotonic, - ::Output: TryInto, - N: ArrayLength>, - T: Copy, -{ - /// # Safety - /// - /// Writing to memory with a transmute in order to enable - /// interrupts of the SysTick timer - /// - /// Enqueue a task without checking if it is full - #[inline] - pub unsafe fn enqueue_unchecked(&mut self, nr: NotReady) { - let mut is_empty = true; - // Check if the top contains a non-empty element and if that element is - // greater than nr - let if_heap_max_greater_than_nr = self - .0 - .peek() - .map(|head| { - is_empty = false; - nr.instant < head.instant - }) - .unwrap_or(true); - if if_heap_max_greater_than_nr { - if is_empty { - mem::transmute::<_, SYST>(()).enable_interrupt(); - } - - // Set SysTick pending - SCB::set_pendst(); - } - - self.0.push_unchecked(nr); - } - - /// Dequeue a task from the TimerQueue - #[inline] - pub fn dequeue(&mut self) -> Option<(T, u8)> { - unsafe { - if let Some(instant) = self.0.peek().map(|p| p.instant) { - let now = M::now(); - - if instant < now { - // task became ready - let nr = self.0.pop_unchecked(); - - Some((nr.task, nr.index)) - } else { - // set a new timeout - const MAX: u32 = 0x00ffffff; - - let ratio = M::ratio(); - let dur = match (instant - now).try_into().ok().and_then(|x| { - x.checked_mul(ratio.numerator) - .map(|x| x / ratio.denominator) - }) { - None => MAX, - - // ARM Architecture Reference Manual says: - // "Setting SYST_RVR to zero has the effect of - // disabling the SysTick counter independently - // of the counter enable bit." - Some(0) => 1, - - Some(x) => cmp::min(MAX, x), - }; - mem::transmute::<_, SYST>(()).set_reload(dur); - - // Start counting down from the new reload - mem::transmute::<_, SYST>(()).clear_current(); - - None - } - } else { - // The queue is empty - mem::transmute::<_, SYST>(()).disable_interrupt(); - - None - } - } - } -} - -pub struct NotReady -where - T: Copy, - M: Monotonic, - ::Output: TryInto, -{ - pub index: u8, - pub instant: M::Instant, - pub task: T, -} - -impl Eq for NotReady -where - T: Copy, - M: Monotonic, - ::Output: TryInto, -{ -} - -impl Ord for NotReady -where - T: Copy, - M: Monotonic, - ::Output: TryInto, -{ - fn cmp(&self, other: &Self) -> Ordering { - self.instant.cmp(&other.instant) - } -} - -impl PartialEq for NotReady -where - T: Copy, - M: Monotonic, - ::Output: TryInto, -{ - fn eq(&self, other: &Self) -> bool { - self.instant == other.instant - } -} - -impl PartialOrd for NotReady -where - T: Copy, - M: Monotonic, - ::Output: TryInto, -{ - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(&other)) - } -} +// use core::{ +// cmp::{self, Ordering}, +// convert::TryInto, +// mem, +// ops::Sub, +// }; +// +// use cortex_m::peripheral::{SCB, SYST}; +// use heapless::{binary_heap::Min, ArrayLength, BinaryHeap}; +// +// use crate::Monotonic; +// +// pub struct TimerQueue(pub BinaryHeap, N, Min>) +// where +// M: Monotonic, +// ::Output: TryInto, +// N: ArrayLength>, +// T: Copy; +// +// impl TimerQueue +// where +// M: Monotonic, +// ::Output: TryInto, +// N: ArrayLength>, +// T: Copy, +// { +// /// # Safety +// /// +// /// Writing to memory with a transmute in order to enable +// /// interrupts of the SysTick timer +// /// +// /// Enqueue a task without checking if it is full +// #[inline] +// pub unsafe fn enqueue_unchecked(&mut self, nr: NotReady) { +// let mut is_empty = true; +// // Check if the top contains a non-empty element and if that element is +// // greater than nr +// let if_heap_max_greater_than_nr = self +// .0 +// .peek() +// .map(|head| { +// is_empty = false; +// nr.instant < head.instant +// }) +// .unwrap_or(true); +// if if_heap_max_greater_than_nr { +// if is_empty { +// mem::transmute::<_, SYST>(()).enable_interrupt(); +// } +// +// // Set SysTick pending +// SCB::set_pendst(); +// } +// +// self.0.push_unchecked(nr); +// } +// +// /// Dequeue a task from the TimerQueue +// #[inline] +// pub fn dequeue(&mut self) -> Option<(T, u8)> { +// unsafe { +// if let Some(instant) = self.0.peek().map(|p| p.instant) { +// let now = M::now(); +// +// if instant < now { +// // task became ready +// let nr = self.0.pop_unchecked(); +// +// Some((nr.task, nr.index)) +// } else { +// // set a new timeout +// const MAX: u32 = 0x00ffffff; +// +// let ratio = M::ratio(); +// let dur = match (instant - now).try_into().ok().and_then(|x| { +// x.checked_mul(ratio.numerator) +// .map(|x| x / ratio.denominator) +// }) { +// None => MAX, +// +// // ARM Architecture Reference Manual says: +// // "Setting SYST_RVR to zero has the effect of +// // disabling the SysTick counter independently +// // of the counter enable bit." +// Some(0) => 1, +// +// Some(x) => cmp::min(MAX, x), +// }; +// mem::transmute::<_, SYST>(()).set_reload(dur); +// +// // Start counting down from the new reload +// mem::transmute::<_, SYST>(()).clear_current(); +// +// None +// } +// } else { +// // The queue is empty +// mem::transmute::<_, SYST>(()).disable_interrupt(); +// +// None +// } +// } +// } +// } +// +// pub struct NotReady +// where +// T: Copy, +// M: Monotonic, +// ::Output: TryInto, +// { +// pub index: u8, +// pub instant: M::Instant, +// pub task: T, +// } +// +// impl Eq for NotReady +// where +// T: Copy, +// M: Monotonic, +// ::Output: TryInto, +// { +// } +// +// impl Ord for NotReady +// where +// T: Copy, +// M: Monotonic, +// ::Output: TryInto, +// { +// fn cmp(&self, other: &Self) -> Ordering { +// self.instant.cmp(&other.instant) +// } +// } +// +// impl PartialEq for NotReady +// where +// T: Copy, +// M: Monotonic, +// ::Output: TryInto, +// { +// fn eq(&self, other: &Self) -> bool { +// self.instant == other.instant +// } +// } +// +// impl PartialOrd for NotReady +// where +// T: Copy, +// M: Monotonic, +// ::Output: TryInto, +// { +// fn partial_cmp(&self, other: &Self) -> Option { +// Some(self.cmp(&other)) +// } +// } -- cgit v1.2.3 From b23bb1192c8dc1f2e8f157db2147b1737abc1033 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Tue, 8 Dec 2020 20:49:13 +0100 Subject: TQ handlers being generated --- examples/test_new_monotonic.rs | 8 +- macros/src/check.rs | 2 - macros/src/codegen/dispatchers.rs | 28 +++--- macros/src/codegen/hardware_tasks.rs | 17 ++-- macros/src/codegen/module.rs | 180 ++++++++++++++++++----------------- macros/src/codegen/pre_init.rs | 37 +++---- macros/src/codegen/software_tasks.rs | 25 ++--- macros/src/codegen/timer_queue.rs | 20 ++-- macros/src/codegen/util.rs | 6 +- src/export.rs | 2 +- 10 files changed, 171 insertions(+), 154 deletions(-) (limited to 'src') diff --git a/examples/test_new_monotonic.rs b/examples/test_new_monotonic.rs index 5aac48b..b389058 100644 --- a/examples/test_new_monotonic.rs +++ b/examples/test_new_monotonic.rs @@ -6,7 +6,7 @@ use panic_semihosting as _; // panic handler use rtic::app; -#[app(device = lm3s6965)] +#[app(device = lm3s6965, dispatchers = [UART])] mod app { #[monotonic(binds = SomeISR1)] type Mono1 = hal::Mono1; @@ -17,5 +17,11 @@ mod app { #[init] fn init(cx: init::Context) -> (init::LateResources, init::Monotonics) { } + + #[task] + fn task1(_: task1::Context) {} + + #[task] + fn task2(_: task2::Context) {} } diff --git a/macros/src/check.rs b/macros/src/check.rs index 42bd90d..374fced 100644 --- a/macros/src/check.rs +++ b/macros/src/check.rs @@ -6,7 +6,6 @@ use syn::{parse, Path}; pub struct Extra { pub device: Path, - pub monotonic: Option, pub peripherals: bool, } @@ -76,7 +75,6 @@ pub fn app(app: &App, _analysis: &Analysis) -> parse::Result { if let Some(device) = app.args.device.clone() { Ok(Extra { device, - monotonic: None, peripherals: app.args.peripherals, }) } else { diff --git a/macros/src/codegen/dispatchers.rs b/macros/src/codegen/dispatchers.rs index a6c695f..d0a3ba0 100644 --- a/macros/src/codegen/dispatchers.rs +++ b/macros/src/codegen/dispatchers.rs @@ -70,19 +70,21 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec::now();)), - Some(quote!(, instant)), - ) - } else { - (None, None) - }; + // let (let_instant, instant) = if let Some(ref m) = extra.monotonic { + // ( + // Some(quote!(let instant = <#m as rtic::Monotonic>::now();)), + // Some(quote!(, instant)), + // ) + // } else { + // (None, None) + // }; + let (let_instant, instant) = (quote!(), quote!()); let locals_new = if task.locals.is_empty() { quote!() diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index d398a1a..2c42adc 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -23,24 +23,25 @@ pub fn codegen( let mut lt = None; match ctxt { Context::Init => { - if let Some(m) = &extra.monotonic { - fields.push(quote!( - /// System start time = `Instant(0 /* cycles */)` - pub start: <#m as rtic::Monotonic>::Instant - )); - - values.push(quote!(start: <#m as rtic::Monotonic>::zero())); - - fields.push(quote!( - /// Core (Cortex-M) peripherals minus the SysTick - pub core: rtic::Peripherals - )); - } else { - fields.push(quote!( - /// Core (Cortex-M) peripherals - pub core: rtic::export::Peripherals - )); - } + // TODO: What fields are needed? + // if let Some(m) = &extra.monotonic { + // fields.push(quote!( + // /// System start time = `Instant(0 /* cycles */)` + // pub start: <#m as rtic::Monotonic>::Instant + // )); + + // values.push(quote!(start: <#m as rtic::Monotonic>::zero())); + + // fields.push(quote!( + // /// Core (Cortex-M) peripherals minus the SysTick + // pub core: rtic::Peripherals + // )); + // } else { + // fields.push(quote!( + // /// Core (Cortex-M) peripherals + // pub core: rtic::export::Peripherals + // )); + // } if extra.peripherals { let device = &extra.device; @@ -67,29 +68,31 @@ pub fn codegen( Context::Idle => {} Context::HardwareTask(..) => { - if let Some(m) = &extra.monotonic { - fields.push(quote!( - /// Time at which this handler started executing - pub start: <#m as rtic::Monotonic>::Instant - )); + // TODO: What fields are needed for monotonic? + // if let Some(m) = &extra.monotonic { + // fields.push(quote!( + // /// Time at which this handler started executing + // pub start: <#m as rtic::Monotonic>::Instant + // )); - values.push(quote!(start: instant)); + // values.push(quote!(start: instant)); - needs_instant = true; - } + // needs_instant = true; + // } } Context::SoftwareTask(..) => { - if let Some(m) = &extra.monotonic { - fields.push(quote!( - /// The time at which this task was scheduled to run - pub scheduled: <#m as rtic::Monotonic>::Instant - )); + // TODO: What fields are needed for monotonic? + // if let Some(m) = &extra.monotonic { + // fields.push(quote!( + // /// The time at which this task was scheduled to run + // pub scheduled: <#m as rtic::Monotonic>::Instant + // )); - values.push(quote!(scheduled: instant)); + // values.push(quote!(scheduled: instant)); - needs_instant = true; - } + // needs_instant = true; + // } } } @@ -152,11 +155,7 @@ pub fn codegen( }; let core = if ctxt.is_init() { - if extra.monotonic.is_some() { - Some(quote!(core: rtic::Peripherals,)) - } else { - Some(quote!(core: rtic::export::Peripherals,)) - } + Some(quote!(core: rtic::export::Peripherals,)) } else { None }; @@ -167,13 +166,15 @@ pub fn codegen( Some(quote!(priority: &#lt rtic::export::Priority)) }; - let instant = if needs_instant { - let m = extra.monotonic.clone().expect("RTIC-ICE: UNREACHABLE"); + // TODO: What is needed for the new monotonic? + // let instant = if needs_instant { + // let m = extra.monotonic.clone().expect("RTIC-ICE: UNREACHABLE"); - Some(quote!(, instant: <#m as rtic::Monotonic>::Instant)) - } else { - None - }; + // Some(quote!(, instant: <#m as rtic::Monotonic>::Instant)) + // } else { + // None + // }; + let instant = quote!(); items.push(quote!( /// Execution context @@ -250,50 +251,51 @@ pub fn codegen( })); - // Schedule caller - if let Some(m) = &extra.monotonic { - let instants = util::instants_ident(name); - - let tq = util::tq_ident(); - let t = util::schedule_t_ident(); - - items.push(quote!( - #(#cfgs)* - pub fn schedule( - instant: <#m as rtic::Monotonic>::Instant - #(,#args)* - ) -> Result<(), #ty> { - unsafe { - use rtic::Mutex as _; - use rtic::mutex_prelude::*; - - let input = #tupled; - if let Some(index) = rtic::export::interrupt::free(|_| #app_path::#fq.dequeue()) { - #app_path::#inputs - .get_unchecked_mut(usize::from(index)) - .as_mut_ptr() - .write(input); - - #app_path::#instants - .get_unchecked_mut(usize::from(index)) - .as_mut_ptr() - .write(instant); - - let nr = rtic::export::NotReady { - instant, - index, - task: #app_path::#t::#name, - }; - - rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked(nr)); - - Ok(()) - } else { - Err(input) - } - } - })); - } + // TODO: Needs updating for new monotonic. + // // Schedule caller + // if let Some(m) = &extra.monotonic { + // let instants = util::instants_ident(name); + + // let tq = util::tq_ident(); + // let t = util::schedule_t_ident(); + + // items.push(quote!( + // #(#cfgs)* + // pub fn schedule( + // instant: <#m as rtic::Monotonic>::Instant + // #(,#args)* + // ) -> Result<(), #ty> { + // unsafe { + // use rtic::Mutex as _; + // use rtic::mutex_prelude::*; + + // let input = #tupled; + // if let Some(index) = rtic::export::interrupt::free(|_| #app_path::#fq.dequeue()) { + // #app_path::#inputs + // .get_unchecked_mut(usize::from(index)) + // .as_mut_ptr() + // .write(input); + + // #app_path::#instants + // .get_unchecked_mut(usize::from(index)) + // .as_mut_ptr() + // .write(instant); + + // let nr = rtic::export::NotReady { + // instant, + // index, + // task: #app_path::#t::#name, + // }; + + // rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked(nr)); + + // Ok(()) + // } else { + // Err(input) + // } + // } + // })); + // } } if !items.is_empty() { diff --git a/macros/src/codegen/pre_init.rs b/macros/src/codegen/pre_init.rs index 969de84..dfdb30a 100644 --- a/macros/src/codegen/pre_init.rs +++ b/macros/src/codegen/pre_init.rs @@ -74,24 +74,25 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec>(); - if let Some(m) = &extra.monotonic { - let instants = util::instants_ident(name); - - let uninit = mk_uninit(); - mod_app.push(quote!( - #uninit - /// Buffer that holds the instants associated to the inputs of a task - static mut #instants: - [core::mem::MaybeUninit<<#m as rtic::Monotonic>::Instant>; #cap_lit] = - [#(#elems,)*]; - )); - } + // TODO: Update for new monotonic + // if let Some(m) = &extra.monotonic { + // let instants = util::instants_ident(name); + + // let uninit = mk_uninit(); + // mod_app.push(quote!( + // #uninit + // /// Buffer that holds the instants associated to the inputs of a task + // static mut #instants: + // [core::mem::MaybeUninit<<#m as rtic::Monotonic>::Instant>; #cap_lit] = + // [#(#elems,)*]; + // )); + // } let uninit = mk_uninit(); let inputs_ident = util::inputs_ident(name); diff --git a/macros/src/codegen/timer_queue.rs b/macros/src/codegen/timer_queue.rs index fa2c7b3..ccde957 100644 --- a/macros/src/codegen/timer_queue.rs +++ b/macros/src/codegen/timer_queue.rs @@ -8,7 +8,7 @@ use crate::{analyze::Analysis, check::Extra, codegen::util}; pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec { let mut items = vec![]; - if let Some(m) = &extra.monotonic { + if !app.monotonics.is_empty() { let t = util::schedule_t_ident(); // Enumeration of `schedule`-able tasks @@ -36,12 +36,17 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec Vec Vec>(); - let sys_tick = util::suffixed("SysTick"); + let bound_interrupt = &monotonic.args.binds; items.push(quote!( #[no_mangle] - unsafe fn #sys_tick() { + unsafe fn #bound_interrupt() { use rtic::Mutex as _; while let Some((task, index)) = rtic::export::interrupt::free(|_| #tq.dequeue()) @@ -106,5 +113,6 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec Ident { } /// Generates an identifier for a timer queue -/// -/// At most there is one timer queue -pub fn tq_ident() -> Ident { - Ident::new(&"TQ".to_string(), Span::call_site()) +pub fn tq_ident(name: &str) -> Ident { + Ident::new(&format!("TQ_{}", name), Span::call_site()) } diff --git a/src/export.rs b/src/export.rs index 46793aa..dedff2f 100644 --- a/src/export.rs +++ b/src/export.rs @@ -3,7 +3,7 @@ use core::{ sync::atomic::{AtomicBool, Ordering}, }; -//pub use crate::tq::{NotReady, TimerQueue}; +// pub use crate::tq::{NotReady, TimerQueue}; pub use bare_metal::CriticalSection; #[cfg(armv7m)] pub use cortex_m::register::basepri; -- cgit v1.2.3 From 97a48983d2859740983cbf342e1287182426ed44 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Thu, 10 Dec 2020 20:33:13 +0100 Subject: More work --- examples/test_new_monotonic.rs | 6 +- macros/src/codegen.rs | 14 ++- macros/src/codegen/assertions.rs | 8 +- macros/src/codegen/dispatchers.rs | 2 +- macros/src/codegen/init.rs | 53 +--------- macros/src/codegen/module.rs | 212 +++++++++++++++++++------------------- macros/src/codegen/pre_init.rs | 39 +++---- macros/src/codegen/timer_queue.rs | 2 +- src/export.rs | 8 ++ src/lib.rs | 5 +- 10 files changed, 164 insertions(+), 185 deletions(-) (limited to 'src') diff --git a/examples/test_new_monotonic.rs b/examples/test_new_monotonic.rs index b389058..d2530c6 100644 --- a/examples/test_new_monotonic.rs +++ b/examples/test_new_monotonic.rs @@ -9,10 +9,10 @@ use rtic::app; #[app(device = lm3s6965, dispatchers = [UART])] mod app { #[monotonic(binds = SomeISR1)] - type Mono1 = hal::Mono1; + type MyMono1 = hal::Mono1; - #[monotonic(binds = SomeISR2)] - type Mono2 = hal::Mono2; + #[monotonic(binds = SomeISR2, default = true)] + type MyMono2 = hal::Mono2; #[init] fn init(cx: init::Context) -> (init::LateResources, init::Monotonics) { diff --git a/macros/src/codegen.rs b/macros/src/codegen.rs index 52940bc..03bac84 100644 --- a/macros/src/codegen.rs +++ b/macros/src/codegen.rs @@ -27,13 +27,13 @@ pub fn app(app: &App, analysis: &Analysis, extra: &Extra) -> TokenStream2 { let mut user = vec![]; // Generate the `main` function - let assertion_stmts = assertions::codegen(analysis); + let assertion_stmts = assertions::codegen(app, analysis); - let pre_init_stmts = pre_init::codegen(&app, analysis, extra); + let pre_init_stmts = pre_init::codegen(app, analysis, extra); let (mod_app_init, root_init, user_init, call_init) = init::codegen(app, analysis, extra); - let post_init_stmts = post_init::codegen(&app, analysis); + let post_init_stmts = post_init::codegen(app, analysis); let (mod_app_idle, root_idle, user_idle, call_idle) = idle::codegen(app, analysis, extra); @@ -104,12 +104,20 @@ pub fn app(app: &App, analysis: &Analysis, extra: &Extra) -> TokenStream2 { )); } + let monotonic_imports: Vec<_> = app.monotonics.iter().map(|(_, monotonic)| { + let name = &monotonic.ident; + let ty = &monotonic.ty; + quote!(pub type #name = #ty;) + }).collect(); + quote!( /// Implementation details pub mod #name { /// Always include the device crate which contains the vector table use #device as you_must_enable_the_rt_feature_for_the_pac_in_your_cargo_toml; + #(#monotonic_imports)* + #(#user_imports)* /// User code from within the module diff --git a/macros/src/codegen/assertions.rs b/macros/src/codegen/assertions.rs index 4d9aae4..a8a4491 100644 --- a/macros/src/codegen/assertions.rs +++ b/macros/src/codegen/assertions.rs @@ -2,9 +2,10 @@ use proc_macro2::TokenStream as TokenStream2; use quote::quote; use crate::analyze::Analysis; +use rtic_syntax::ast::App; /// Generates compile-time assertions that check that types implement the `Send` / `Sync` traits -pub fn codegen(analysis: &Analysis) -> Vec { +pub fn codegen(app: &App, analysis: &Analysis) -> Vec { let mut stmts = vec![]; for ty in &analysis.send_types { @@ -15,5 +16,10 @@ pub fn codegen(analysis: &Analysis) -> Vec { stmts.push(quote!(rtic::export::assert_sync::<#ty>();)); } + for (_, monotonic) in &app.monotonics { + let ty = &monotonic.ty; + stmts.push(quote!(rtic::export::assert_monotonic::<#ty>();)); + } + stmts } diff --git a/macros/src/codegen/dispatchers.rs b/macros/src/codegen/dispatchers.rs index d0a3ba0..01fb511 100644 --- a/macros/src/codegen/dispatchers.rs +++ b/macros/src/codegen/dispatchers.rs @@ -5,7 +5,7 @@ use rtic_syntax::ast::App; use crate::{analyze::Analysis, check::Extra, codegen::util}; /// Generates task dispatchers -pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec { +pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec { let mut items = vec![]; let interrupts = &analysis.interrupts; diff --git a/macros/src/codegen/init.rs b/macros/src/codegen/init.rs index 6b57add..66c3bc4 100644 --- a/macros/src/codegen/init.rs +++ b/macros/src/codegen/init.rs @@ -5,7 +5,7 @@ use rtic_syntax::{ast::App, Context}; use crate::{ analyze::Analysis, check::Extra, - codegen::{locals, module, resources_struct, util}, + codegen::{locals, module, resources_struct}, }; type CodegenResult = ( @@ -32,50 +32,6 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> CodegenResult { let mut root_init = vec![]; - let late_fields = analysis - .late_resources - .iter() - .flat_map(|resources| { - resources.iter().map(|name| { - let ty = &app.late_resources[name].ty; - let cfgs = &app.late_resources[name].cfgs; - - quote!( - #(#cfgs)* - pub #name: #ty - ) - }) - }) - .collect::>(); - - let late_resources = util::late_resources_ident(&name); - - root_init.push(quote!( - /// Resources initialized at runtime - #[allow(non_snake_case)] - pub struct #late_resources { - #(#late_fields),* - } - )); - - let monotonic_types: Vec<_> = app - .monotonics - .iter() - .map(|(_, monotonic)| { - let mono = &monotonic.ty; - quote! {#mono} - }) - .collect(); - let monotonics = util::monotonics_ident(&name); - - root_init.push(quote!( - /// Monotonics used by the system - #[allow(non_snake_case)] - pub struct #monotonics( - #(#monotonic_types),* - ); - )); - let mut locals_pat = None; let mut locals_new = None; if !init.locals.is_empty() { @@ -91,15 +47,12 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> CodegenResult { let stmts = &init.stmts; let locals_pat = locals_pat.iter(); - let mut user_init_return = vec![quote! {#name::LateResources}]; - if !app.monotonics.is_empty() { - user_init_return.push(quote! {#name::Monotonics}); - } + let user_init_return = quote! {#name::LateResources, #name::Monotonics}; let user_init = Some(quote!( #(#attrs)* #[allow(non_snake_case)] - fn #name(#(#locals_pat,)* #context: #name::Context) -> (#(#user_init_return,)*) { + fn #name(#(#locals_pat,)* #context: #name::Context) -> (#user_init_return) { #(#stmts)* } )); diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index 2c42adc..6dd6e9a 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -19,29 +19,13 @@ pub fn codegen( let name = ctxt.ident(app); - let mut needs_instant = false; let mut lt = None; match ctxt { Context::Init => { - // TODO: What fields are needed? - // if let Some(m) = &extra.monotonic { - // fields.push(quote!( - // /// System start time = `Instant(0 /* cycles */)` - // pub start: <#m as rtic::Monotonic>::Instant - // )); - - // values.push(quote!(start: <#m as rtic::Monotonic>::zero())); - - // fields.push(quote!( - // /// Core (Cortex-M) peripherals minus the SysTick - // pub core: rtic::Peripherals - // )); - // } else { - // fields.push(quote!( - // /// Core (Cortex-M) peripherals - // pub core: rtic::export::Peripherals - // )); - // } + fields.push(quote!( + /// Core (Cortex-M) peripherals + pub core: rtic::export::Peripherals + )); if extra.peripherals { let device = &extra.device; @@ -68,31 +52,11 @@ pub fn codegen( Context::Idle => {} Context::HardwareTask(..) => { - // TODO: What fields are needed for monotonic? - // if let Some(m) = &extra.monotonic { - // fields.push(quote!( - // /// Time at which this handler started executing - // pub start: <#m as rtic::Monotonic>::Instant - // )); - - // values.push(quote!(start: instant)); - - // needs_instant = true; - // } + // None for now. } Context::SoftwareTask(..) => { - // TODO: What fields are needed for monotonic? - // if let Some(m) = &extra.monotonic { - // fields.push(quote!( - // /// The time at which this task was scheduled to run - // pub scheduled: <#m as rtic::Monotonic>::Instant - // )); - - // values.push(quote!(scheduled: instant)); - - // needs_instant = true; - // } + // None for now. } } @@ -132,18 +96,45 @@ pub fn codegen( } if let Context::Init = ctxt { - let init = &app.inits.first().unwrap(); - let late_resources = util::late_resources_ident(&init.name); - let monotonics = util::monotonics_ident(&init.name); + let late_fields = analysis + .late_resources + .iter() + .flat_map(|resources| { + resources.iter().map(|name| { + let ty = &app.late_resources[name].ty; + let cfgs = &app.late_resources[name].cfgs; + + quote!( + #(#cfgs)* + pub #name: #ty + ) + }) + }) + .collect::>(); items.push(quote!( - #[doc(inline)] - pub use super::#late_resources as LateResources; + /// Resources initialized at runtime + #[allow(non_snake_case)] + pub struct LateResources { + #(#late_fields),* + } )); + let monotonic_types: Vec<_> = app + .monotonics + .iter() + .map(|(_, monotonic)| { + let mono = &monotonic.ident; + quote! {#mono} + }) + .collect(); + items.push(quote!( - #[doc(inline)] - pub use super::#monotonics as Monotonics; + /// Monotonics used by the system + #[allow(non_snake_case)] + pub struct Monotonics( + #(#monotonic_types),* + ); )); } @@ -166,16 +157,6 @@ pub fn codegen( Some(quote!(priority: &#lt rtic::export::Priority)) }; - // TODO: What is needed for the new monotonic? - // let instant = if needs_instant { - // let m = extra.monotonic.clone().expect("RTIC-ICE: UNREACHABLE"); - - // Some(quote!(, instant: <#m as rtic::Monotonic>::Instant)) - // } else { - // None - // }; - let instant = quote!(); - items.push(quote!( /// Execution context pub struct Context<#lt> { @@ -184,7 +165,7 @@ pub fn codegen( impl<#lt> Context<#lt> { #[inline(always)] - pub unsafe fn new(#core #priority #instant) -> Self { + pub unsafe fn new(#core #priority) -> Self { Context { #(#values,)* } @@ -202,7 +183,7 @@ pub fn codegen( let cfgs = &spawnee.cfgs; // Store a copy of the task cfgs task_cfgs = cfgs.clone(); - let (args, tupled, _untupled, ty) = util::regroup_inputs(&spawnee.inputs); + let (args, tupled, untupled, ty) = util::regroup_inputs(&spawnee.inputs); let args = &args; let tupled = &tupled; let fq = util::fq_ident(name); @@ -251,51 +232,70 @@ pub fn codegen( })); - // TODO: Needs updating for new monotonic. - // // Schedule caller - // if let Some(m) = &extra.monotonic { - // let instants = util::instants_ident(name); - - // let tq = util::tq_ident(); - // let t = util::schedule_t_ident(); - - // items.push(quote!( - // #(#cfgs)* - // pub fn schedule( - // instant: <#m as rtic::Monotonic>::Instant - // #(,#args)* - // ) -> Result<(), #ty> { - // unsafe { - // use rtic::Mutex as _; - // use rtic::mutex_prelude::*; - - // let input = #tupled; - // if let Some(index) = rtic::export::interrupt::free(|_| #app_path::#fq.dequeue()) { - // #app_path::#inputs - // .get_unchecked_mut(usize::from(index)) - // .as_mut_ptr() - // .write(input); - - // #app_path::#instants - // .get_unchecked_mut(usize::from(index)) - // .as_mut_ptr() - // .write(instant); - - // let nr = rtic::export::NotReady { - // instant, - // index, - // task: #app_path::#t::#name, - // }; - - // rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked(nr)); - - // Ok(()) - // } else { - // Err(input) - // } - // } - // })); - // } + // Schedule caller + for (_, monotonic) in &app.monotonics { + let instants = util::instants_ident(name); + + let tq = util::tq_ident(&monotonic.ident.to_string()); + let t = util::schedule_t_ident(); + let m = &monotonic.ident; + + if monotonic.args.default { + items.push(quote!(pub use #m::spawn_after;)); + items.push(quote!(pub use #m::spawn_at;)); + } + + items.push(quote!( + pub mod #m { + #(#cfgs)* + pub fn spawn_after( + duration: rtic::Duration, + #(,#args)* + ) -> Result<(), #ty> { + let instant = <#app_path::#m as rtic::Monotonic>::now(); + + spawn_at(instant + duration, #(,#untupled)*) + } + + #(#cfgs)* + pub fn spawn_at( + instant: Instant<#app_path::#m as rtic::Monotonic> + #(,#args)* + ) -> Result<(), #ty> { + unsafe { + use rtic::Mutex as _; + use rtic::mutex_prelude::*; + + let input = #tupled; + if let Some(index) = rtic::export::interrupt::free(|_| #app_path::#fq.dequeue()) { + #app_path::#inputs + .get_unchecked_mut(usize::from(index)) + .as_mut_ptr() + .write(input); + + #app_path::#instants + .get_unchecked_mut(usize::from(index)) + .as_mut_ptr() + .write(instant); + + let nr = rtic::export::NotReady { + instant, + index, + task: #app_path::#t::#name, + }; + + rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked(nr)); + + // TODO: After adding the scheduled task, check and setup the timer. + + Ok(()) + } else { + Err(input) + } + } + } + })); + } } if !items.is_empty() { diff --git a/macros/src/codegen/pre_init.rs b/macros/src/codegen/pre_init.rs index dfdb30a..26ba558 100644 --- a/macros/src/codegen/pre_init.rs +++ b/macros/src/codegen/pre_init.rs @@ -74,25 +74,26 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec Vec { +pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec { let mut items = vec![]; if !app.monotonics.is_empty() { diff --git a/src/export.rs b/src/export.rs index dedff2f..080b1f6 100644 --- a/src/export.rs +++ b/src/export.rs @@ -16,6 +16,7 @@ pub use cortex_m::{ use heapless::spsc::SingleCore; pub use heapless::{consts, i::Queue as iQueue, spsc::Queue}; pub use heapless::{i::BinaryHeap as iBinaryHeap, BinaryHeap}; +pub use rtic_core::monotonic::Monotonic; pub type SCFQ = Queue; pub type SCRQ = Queue<(T, u8), N, u8, SingleCore>; @@ -112,6 +113,13 @@ where { } +#[inline(always)] +pub fn assert_monotonic() +where + T: Monotonic, +{ +} + /// Lock the resource proxy by setting the BASEPRI /// and running the closure with interrupt::free /// diff --git a/src/lib.rs b/src/lib.rs index c1930b0..ade1267 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,7 +39,10 @@ use core::ops::Sub; use cortex_m::{interrupt::Nr, peripheral::NVIC}; pub use cortex_m_rtic_macros::app; -pub use rtic_core::{prelude as mutex_prelude, Exclusive, monotonic::Monotonic, Mutex}; +pub use rtic_core::{ + monotonic::{Clock, Instant, Monotonic}, + prelude as mutex_prelude, Exclusive, Mutex, +}; #[doc(hidden)] pub mod export; -- cgit v1.2.3 From 8e8ec9b7b879adae8d4de6cb2320b9b19290a7e0 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sat, 12 Dec 2020 23:24:54 +0100 Subject: Monotonic codegen now passing compile stage --- macros/src/codegen/dispatchers.rs | 19 +-- macros/src/codegen/module.rs | 21 ++- macros/src/codegen/software_tasks.rs | 29 ++-- macros/src/codegen/timer_queue.rs | 8 +- macros/src/codegen/util.rs | 20 +-- src/export.rs | 2 +- src/lib.rs | 4 +- src/tq.rs | 307 +++++++++++++++++------------------ 8 files changed, 190 insertions(+), 220 deletions(-) (limited to 'src') diff --git a/macros/src/codegen/dispatchers.rs b/macros/src/codegen/dispatchers.rs index 01fb511..d3adee0 100644 --- a/macros/src/codegen/dispatchers.rs +++ b/macros/src/codegen/dispatchers.rs @@ -70,22 +70,6 @@ pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec Vec { let #tupled = #inputs.get_unchecked(usize::from(index)).as_ptr().read(); - #let_instant #fq.split().0.enqueue_unchecked(index); let priority = &rtic::export::Priority::new(PRIORITY); #app_path::#name( #locals_new - #name::Context::new(priority #instant) + #name::Context::new(priority) #(,#pats)* ) } diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index 6dd6e9a..0f495d9 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -18,6 +18,8 @@ pub fn codegen( let mut task_cfgs = vec![]; let name = ctxt.ident(app); + let app_name = &app.name; + let app_path = quote! {crate::#app_name}; let mut lt = None; match ctxt { @@ -125,7 +127,7 @@ pub fn codegen( .iter() .map(|(_, monotonic)| { let mono = &monotonic.ident; - quote! {#mono} + quote! {#app_path::#mono} }) .collect(); @@ -190,9 +192,6 @@ pub fn codegen( let rq = util::rq_ident(priority); let inputs = util::inputs_ident(name); - let app_name = &app.name; - let app_path = quote! {crate::#app_name}; - let device = &extra.device; let enum_ = util::interrupt_ident(); let interrupt = &analysis @@ -234,11 +233,13 @@ pub fn codegen( // Schedule caller for (_, monotonic) in &app.monotonics { - let instants = util::instants_ident(name); + let instants = util::monotonic_instants_ident(name, &monotonic.ident); let tq = util::tq_ident(&monotonic.ident.to_string()); let t = util::schedule_t_ident(); let m = &monotonic.ident; + let m_isr = &monotonic.args.binds; + let enum_ = util::interrupt_ident(); if monotonic.args.default { items.push(quote!(pub use #m::spawn_after;)); @@ -259,7 +260,7 @@ pub fn codegen( #(#cfgs)* pub fn spawn_at( - instant: Instant<#app_path::#m as rtic::Monotonic> + instant: rtic::Instant<#app_path::#m> #(,#args)* ) -> Result<(), #ty> { unsafe { @@ -284,9 +285,11 @@ pub fn codegen( task: #app_path::#t::#name, }; - rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked(nr)); - - // TODO: After adding the scheduled task, check and setup the timer. + rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked( + nr, + || rtic::export::NVIC::unmask(#app_path::you_must_enable_the_rt_feature_for_the_pac_in_your_cargo_toml::#enum_::#m_isr), + || rtic::pend(#app_path::you_must_enable_the_rt_feature_for_the_pac_in_your_cargo_toml::#enum_::#m_isr), + )); Ok(()) } else { diff --git a/macros/src/codegen/software_tasks.rs b/macros/src/codegen/software_tasks.rs index 7b884ea..ebe7bdf 100644 --- a/macros/src/codegen/software_tasks.rs +++ b/macros/src/codegen/software_tasks.rs @@ -57,19 +57,22 @@ pub fn codegen( .map(|_| quote!(core::mem::MaybeUninit::uninit())) .collect::>(); - // TODO: Update for new monotonic - // if let Some(m) = &extra.monotonic { - // let instants = util::instants_ident(name); - - // let uninit = mk_uninit(); - // mod_app.push(quote!( - // #uninit - // /// Buffer that holds the instants associated to the inputs of a task - // static mut #instants: - // [core::mem::MaybeUninit<<#m as rtic::Monotonic>::Instant>; #cap_lit] = - // [#(#elems,)*]; - // )); - // } + let app_name = &app.name; + let app_path = quote! {crate::#app_name}; + + for (_, monotonic) in &app.monotonics { + let instants = util::monotonic_instants_ident(name, &monotonic.ident); + let m = &monotonic.ident; + + let uninit = mk_uninit(); + mod_app.push(quote!( + #uninit + /// Buffer that holds the instants associated to the inputs of a task + static mut #instants: + [core::mem::MaybeUninit>; #cap_lit] = + [#(#elems,)*]; + )); + } let uninit = mk_uninit(); let inputs_ident = util::inputs_ident(name); diff --git a/macros/src/codegen/timer_queue.rs b/macros/src/codegen/timer_queue.rs index f219eef..dc29835 100644 --- a/macros/src/codegen/timer_queue.rs +++ b/macros/src/codegen/timer_queue.rs @@ -67,6 +67,8 @@ pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec Vec Vec>(); let bound_interrupt = &monotonic.args.binds; + items.push(quote!( #[no_mangle] unsafe fn #bound_interrupt() { use rtic::Mutex as _; - while let Some((task, index)) = rtic::export::interrupt::free(|_| #tq.dequeue()) + while let Some((task, index)) = rtic::export::interrupt::free(|_| #tq.dequeue( + || rtic::export::NVIC::unmask(you_must_enable_the_rt_feature_for_the_pac_in_your_cargo_toml::#enum_::#bound_interrupt), + )) { match task { #(#arms)* diff --git a/macros/src/codegen/util.rs b/macros/src/codegen/util.rs index d9310dd..329a7dd 100644 --- a/macros/src/codegen/util.rs +++ b/macros/src/codegen/util.rs @@ -77,8 +77,8 @@ pub fn inputs_ident(task: &Ident) -> Ident { } /// Generates an identifier for the `INSTANTS` buffer (`schedule` API) -pub fn instants_ident(task: &Ident) -> Ident { - Ident::new(&format!("{}_INSTANTS", task), Span::call_site()) +pub fn monotonic_instants_ident(task: &Ident, monotonic: &Ident) -> Ident { + Ident::new(&format!("{}_{}_INSTANTS", task, monotonic), Span::call_site()) } pub fn interrupt_ident() -> Ident { @@ -103,22 +103,6 @@ pub fn is_exception(name: &Ident) -> bool { ) } -/// Generates a pre-reexport identifier for the "late resources" struct -pub fn late_resources_ident(init: &Ident) -> Ident { - Ident::new( - &format!("{}LateResources", init.to_string()), - Span::call_site(), - ) -} - -/// Generates a pre-reexport identifier for the "monotonics" struct -pub fn monotonics_ident(init: &Ident) -> Ident { - Ident::new( - &format!("{}Monotonics", init.to_string()), - Span::call_site(), - ) -} - /// Mangle an ident pub fn mangle_ident(ident: &Ident) -> Ident { Ident::new( diff --git a/src/export.rs b/src/export.rs index 080b1f6..ab5984e 100644 --- a/src/export.rs +++ b/src/export.rs @@ -3,7 +3,7 @@ use core::{ sync::atomic::{AtomicBool, Ordering}, }; -// pub use crate::tq::{NotReady, TimerQueue}; +pub use crate::tq::{NotReady, TimerQueue}; pub use bare_metal::CriticalSection; #[cfg(armv7m)] pub use cortex_m::register::basepri; diff --git a/src/lib.rs b/src/lib.rs index ade1267..c85090f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,12 +35,10 @@ // #![deny(warnings)] #![no_std] -use core::ops::Sub; - use cortex_m::{interrupt::Nr, peripheral::NVIC}; pub use cortex_m_rtic_macros::app; pub use rtic_core::{ - monotonic::{Clock, Instant, Monotonic}, + monotonic::{self, Clock, Duration, Instant, Monotonic}, prelude as mutex_prelude, Exclusive, Mutex, }; diff --git a/src/tq.rs b/src/tq.rs index f2539a9..2bfb651 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -1,156 +1,151 @@ -// use core::{ -// cmp::{self, Ordering}, -// convert::TryInto, -// mem, -// ops::Sub, -// }; -// -// use cortex_m::peripheral::{SCB, SYST}; -// use heapless::{binary_heap::Min, ArrayLength, BinaryHeap}; -// -// use crate::Monotonic; -// -// pub struct TimerQueue(pub BinaryHeap, N, Min>) -// where -// M: Monotonic, -// ::Output: TryInto, -// N: ArrayLength>, -// T: Copy; -// -// impl TimerQueue -// where -// M: Monotonic, -// ::Output: TryInto, -// N: ArrayLength>, -// T: Copy, -// { -// /// # Safety -// /// -// /// Writing to memory with a transmute in order to enable -// /// interrupts of the SysTick timer -// /// -// /// Enqueue a task without checking if it is full -// #[inline] -// pub unsafe fn enqueue_unchecked(&mut self, nr: NotReady) { -// let mut is_empty = true; -// // Check if the top contains a non-empty element and if that element is -// // greater than nr -// let if_heap_max_greater_than_nr = self -// .0 -// .peek() -// .map(|head| { -// is_empty = false; -// nr.instant < head.instant -// }) -// .unwrap_or(true); -// if if_heap_max_greater_than_nr { -// if is_empty { -// mem::transmute::<_, SYST>(()).enable_interrupt(); -// } -// -// // Set SysTick pending -// SCB::set_pendst(); -// } -// -// self.0.push_unchecked(nr); -// } -// -// /// Dequeue a task from the TimerQueue -// #[inline] -// pub fn dequeue(&mut self) -> Option<(T, u8)> { -// unsafe { -// if let Some(instant) = self.0.peek().map(|p| p.instant) { -// let now = M::now(); -// -// if instant < now { -// // task became ready -// let nr = self.0.pop_unchecked(); -// -// Some((nr.task, nr.index)) -// } else { -// // set a new timeout -// const MAX: u32 = 0x00ffffff; -// -// let ratio = M::ratio(); -// let dur = match (instant - now).try_into().ok().and_then(|x| { -// x.checked_mul(ratio.numerator) -// .map(|x| x / ratio.denominator) -// }) { -// None => MAX, -// -// // ARM Architecture Reference Manual says: -// // "Setting SYST_RVR to zero has the effect of -// // disabling the SysTick counter independently -// // of the counter enable bit." -// Some(0) => 1, -// -// Some(x) => cmp::min(MAX, x), -// }; -// mem::transmute::<_, SYST>(()).set_reload(dur); -// -// // Start counting down from the new reload -// mem::transmute::<_, SYST>(()).clear_current(); -// -// None -// } -// } else { -// // The queue is empty -// mem::transmute::<_, SYST>(()).disable_interrupt(); -// -// None -// } -// } -// } -// } -// -// pub struct NotReady -// where -// T: Copy, -// M: Monotonic, -// ::Output: TryInto, -// { -// pub index: u8, -// pub instant: M::Instant, -// pub task: T, -// } -// -// impl Eq for NotReady -// where -// T: Copy, -// M: Monotonic, -// ::Output: TryInto, -// { -// } -// -// impl Ord for NotReady -// where -// T: Copy, -// M: Monotonic, -// ::Output: TryInto, -// { -// fn cmp(&self, other: &Self) -> Ordering { -// self.instant.cmp(&other.instant) -// } -// } -// -// impl PartialEq for NotReady -// where -// T: Copy, -// M: Monotonic, -// ::Output: TryInto, -// { -// fn eq(&self, other: &Self) -> bool { -// self.instant == other.instant -// } -// } -// -// impl PartialOrd for NotReady -// where -// T: Copy, -// M: Monotonic, -// ::Output: TryInto, -// { -// fn partial_cmp(&self, other: &Self) -> Option { -// Some(self.cmp(&other)) -// } -// } +use crate::{Instant, Monotonic}; +use core::cmp::Ordering; +use heapless::{binary_heap::Min, ArrayLength, BinaryHeap}; + +pub struct TimerQueue(pub BinaryHeap, N, Min>) +where + M: Monotonic, + N: ArrayLength>, + T: Copy; + +impl TimerQueue +where + M: Monotonic, + N: ArrayLength>, + T: Copy, +{ + /// # Safety + /// + /// Writing to memory with a transmute in order to enable + /// interrupts of the SysTick timer + /// + /// Enqueue a task without checking if it is full + #[inline] + pub unsafe fn enqueue_unchecked( + &mut self, + nr: NotReady, + enable_interrupt: F1, + pend_handler: F2, + ) where + F1: FnOnce(), + F2: FnOnce(), + { + let mut is_empty = true; + // Check if the top contains a non-empty element and if that element is + // greater than nr + let if_heap_max_greater_than_nr = self + .0 + .peek() + .map(|head| { + is_empty = false; + nr.instant < head.instant + }) + .unwrap_or(true); + if if_heap_max_greater_than_nr { + if is_empty { + // mem::transmute::<_, SYST>(()).enable_interrupt(); + enable_interrupt(); + } + + // Set SysTick pending + // SCB::set_pendst(); + pend_handler(); + } + + self.0.push_unchecked(nr); + } + + /// Check if the timer queue is empty. + #[inline] + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Dequeue a task from the TimerQueue + #[inline] + pub fn dequeue(&mut self, disable_interrupt: F) -> Option<(T, u8)> + where + F: FnOnce(), + { + unsafe { + M::clear_compare(); + + if let Some(instant) = self.0.peek().map(|p| p.instant) { + let now = M::now(); + + match instant.checked_duration_since(&now) { + None => { + // instant < now + // task became ready + let nr = self.0.pop_unchecked(); + + Some((nr.task, nr.index)) + } + Some(dur) => { + // TODO: Fix this hack... + let new_instant = *now.duration_since_epoch().integer() + *dur.integer(); + M::set_compare(new_instant); + + // Start counting down from the new reload + // mem::transmute::<_, SYST>(()).clear_current(); + + None + } + } + } else { + // The queue is empty + // mem::transmute::<_, SYST>(()).disable_interrupt(); + disable_interrupt(); + + None + } + } + } +} + +pub struct NotReady +where + T: Copy, + M: Monotonic, +{ + pub index: u8, + pub instant: Instant, + pub task: T, +} + +impl Eq for NotReady +where + T: Copy, + M: Monotonic, +{ +} + +impl Ord for NotReady +where + T: Copy, + M: Monotonic, +{ + fn cmp(&self, other: &Self) -> Ordering { + self.instant.cmp(&other.instant) + } +} + +impl PartialEq for NotReady +where + T: Copy, + M: Monotonic, +{ + fn eq(&self, other: &Self) -> bool { + self.instant == other.instant + } +} + +impl PartialOrd for NotReady +where + T: Copy, + M: Monotonic, +{ + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(&other)) + } +} -- cgit v1.2.3 From 35b4ec0d0435879cca97536b5c866fc2ac2e9210 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sun, 13 Dec 2020 00:06:50 +0100 Subject: Reexport embedded-time as rtic::time --- macros/src/codegen/module.rs | 4 ++-- macros/src/codegen/software_tasks.rs | 2 +- src/lib.rs | 2 +- src/tq.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index 0f495d9..2b6042c 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -250,7 +250,7 @@ pub fn codegen( pub mod #m { #(#cfgs)* pub fn spawn_after( - duration: rtic::Duration, + duration: rtic::time::duration::Duration, #(,#args)* ) -> Result<(), #ty> { let instant = <#app_path::#m as rtic::Monotonic>::now(); @@ -260,7 +260,7 @@ pub fn codegen( #(#cfgs)* pub fn spawn_at( - instant: rtic::Instant<#app_path::#m> + instant: rtic::time::Instant<#app_path::#m> #(,#args)* ) -> Result<(), #ty> { unsafe { diff --git a/macros/src/codegen/software_tasks.rs b/macros/src/codegen/software_tasks.rs index ebe7bdf..53de50b 100644 --- a/macros/src/codegen/software_tasks.rs +++ b/macros/src/codegen/software_tasks.rs @@ -69,7 +69,7 @@ pub fn codegen( #uninit /// Buffer that holds the instants associated to the inputs of a task static mut #instants: - [core::mem::MaybeUninit>; #cap_lit] = + [core::mem::MaybeUninit>; #cap_lit] = [#(#elems,)*]; )); } diff --git a/src/lib.rs b/src/lib.rs index c85090f..0840589 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,7 +38,7 @@ use cortex_m::{interrupt::Nr, peripheral::NVIC}; pub use cortex_m_rtic_macros::app; pub use rtic_core::{ - monotonic::{self, Clock, Duration, Instant, Monotonic}, + monotonic::{self, embedded_time as time, Monotonic}, prelude as mutex_prelude, Exclusive, Mutex, }; diff --git a/src/tq.rs b/src/tq.rs index 2bfb651..a98eed6 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -1,4 +1,4 @@ -use crate::{Instant, Monotonic}; +use crate::{time::Instant, Monotonic}; use core::cmp::Ordering; use heapless::{binary_heap::Min, ArrayLength, BinaryHeap}; -- cgit v1.2.3 From dd52539e32690c5cff73efe40c5d443b770d82a0 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sun, 13 Dec 2020 00:09:44 +0100 Subject: Less ... hacky? --- src/tq.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/tq.rs b/src/tq.rs index a98eed6..8859392 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -81,9 +81,10 @@ where Some((nr.task, nr.index)) } - Some(dur) => { + Some(_) => { // TODO: Fix this hack... - let new_instant = *now.duration_since_epoch().integer() + *dur.integer(); + // Extract the compare time + let new_instant = *instant.duration_since_epoch().integer(); M::set_compare(new_instant); // Start counting down from the new reload -- cgit v1.2.3 From 0e134a41b5f53843b5e1c90cd0633ae56b7a3113 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sun, 13 Dec 2020 14:20:28 +0100 Subject: Double check the compare instant --- src/tq.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/tq.rs b/src/tq.rs index 8859392..5903b3f 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -84,13 +84,22 @@ where Some(_) => { // TODO: Fix this hack... // Extract the compare time - let new_instant = *instant.duration_since_epoch().integer(); - M::set_compare(new_instant); + M::set_compare(*instant.duration_since_epoch().integer()); + + // Double check that the instant we set is really in the future, else + // dequeue. If the monotonic is fast enough it can happen that from the + // read of now to the set of the compare, the time can overflow. This is to + // guard against this. + if instant.checked_duration_since(&M::now()).is_none() { + let nr = self.0.pop_unchecked(); + + Some((nr.task, nr.index)) + } else { + None + } // Start counting down from the new reload // mem::transmute::<_, SYST>(()).clear_current(); - - None } } } else { -- cgit v1.2.3 From aaa92ea2fac23d2679b5efc1178a45d994762bca Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sun, 13 Dec 2020 17:48:11 +0100 Subject: Cleanup --- macros/src/codegen/module.rs | 7 --- macros/src/codegen/timer_queue.rs | 4 -- src/tq.rs | 103 ++++++++++++++++++-------------------- 3 files changed, 49 insertions(+), 65 deletions(-) (limited to 'src') diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index bf77c4d..d15b5ec 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -204,10 +204,6 @@ pub fn codegen( items.push(quote!( #(#cfgs)* pub fn spawn(#(#args,)*) -> Result<(), #ty> { - // #let_instant // do we need it? - use rtic::Mutex as _; - use rtic::mutex_prelude::*; - let input = #tupled; unsafe { @@ -277,9 +273,6 @@ pub fn codegen( #(,#args)* ) -> Result<(), #ty> { unsafe { - use rtic::Mutex as _; - use rtic::mutex_prelude::*; - let input = #tupled; if let Some(index) = rtic::export::interrupt::free(|_| #app_path::#fq.dequeue()) { #app_path::#inputs diff --git a/macros/src/codegen/timer_queue.rs b/macros/src/codegen/timer_queue.rs index ef0fda3..99dfa5b 100644 --- a/macros/src/codegen/timer_queue.rs +++ b/macros/src/codegen/timer_queue.rs @@ -68,8 +68,6 @@ pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec Vec(pub BinaryHeap, N, Min>) +pub struct TimerQueue(pub BinaryHeap, N, Min>) where - M: Monotonic, - N: ArrayLength>, - T: Copy; + Mono: Monotonic, + N: ArrayLength>, + Task: Copy; -impl TimerQueue +impl TimerQueue where - M: Monotonic, - N: ArrayLength>, - T: Copy, + Mono: Monotonic, + N: ArrayLength>, + Task: Copy, { /// # Safety /// @@ -23,7 +23,7 @@ where #[inline] pub unsafe fn enqueue_unchecked( &mut self, - nr: NotReady, + nr: NotReady, enable_interrupt: F1, pend_handler: F2, ) where @@ -63,44 +63,39 @@ where /// Dequeue a task from the TimerQueue #[inline] - pub fn dequeue(&mut self, disable_interrupt: F) -> Option<(T, u8)> + pub fn dequeue(&mut self, disable_interrupt: F) -> Option<(Task, u8)> where F: FnOnce(), { unsafe { - M::clear_compare(); + Mono::clear_compare(); if let Some(instant) = self.0.peek().map(|p| p.instant) { - let now = M::now(); - - match instant.checked_duration_since(&now) { - None => { - // instant < now - // task became ready + if instant < Mono::now() { + // instant < now + // task became ready + let nr = self.0.pop_unchecked(); + + Some((nr.task, nr.index)) + } else { + // TODO: Fix this hack... + // Extract the compare time + Mono::set_compare(*instant.duration_since_epoch().integer()); + + // Double check that the instant we set is really in the future, else + // dequeue. If the monotonic is fast enough it can happen that from the + // read of now to the set of the compare, the time can overflow. This is to + // guard against this. + if instant < Mono::now() { let nr = self.0.pop_unchecked(); Some((nr.task, nr.index)) + } else { + None } - Some(_) => { - // TODO: Fix this hack... - // Extract the compare time - M::set_compare(*instant.duration_since_epoch().integer()); - - // Double check that the instant we set is really in the future, else - // dequeue. If the monotonic is fast enough it can happen that from the - // read of now to the set of the compare, the time can overflow. This is to - // guard against this. - if instant.checked_duration_since(&M::now()).is_none() { - let nr = self.0.pop_unchecked(); - - Some((nr.task, nr.index)) - } else { - None - } - - // Start counting down from the new reload - // mem::transmute::<_, SYST>(()).clear_current(); - } + + // Start counting down from the new reload + // mem::transmute::<_, SYST>(()).clear_current(); } } else { // The queue is empty @@ -113,47 +108,47 @@ where } } -pub struct NotReady +pub struct NotReady where - T: Copy, - M: Monotonic, + Task: Copy, + Mono: Monotonic, { pub index: u8, - pub instant: Instant, - pub task: T, + pub instant: Instant, + pub task: Task, } -impl Eq for NotReady +impl Eq for NotReady where - T: Copy, - M: Monotonic, + Task: Copy, + Mono: Monotonic, { } -impl Ord for NotReady +impl Ord for NotReady where - T: Copy, - M: Monotonic, + Task: Copy, + Mono: Monotonic, { fn cmp(&self, other: &Self) -> Ordering { self.instant.cmp(&other.instant) } } -impl PartialEq for NotReady +impl PartialEq for NotReady where - T: Copy, - M: Monotonic, + Task: Copy, + Mono: Monotonic, { fn eq(&self, other: &Self) -> bool { self.instant == other.instant } } -impl PartialOrd for NotReady +impl PartialOrd for NotReady where - T: Copy, - M: Monotonic, + Task: Copy, + Mono: Monotonic, { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(&other)) -- cgit v1.2.3 From 0658d53843d5452085e7458269e0abebbf431971 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Sun, 10 Jan 2021 15:47:25 +0100 Subject: cleanup --- src/tq.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/tq.rs b/src/tq.rs index be854a5..4c89a66 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -72,14 +72,13 @@ where if let Some(instant) = self.0.peek().map(|p| p.instant) { if instant < Mono::now() { - // instant < now // task became ready let nr = self.0.pop_unchecked(); Some((nr.task, nr.index)) } else { // TODO: Fix this hack... - // Extract the compare time + // Extract the compare time. Mono::set_compare(*instant.duration_since_epoch().integer()); // Double check that the instant we set is really in the future, else @@ -93,13 +92,9 @@ where } else { None } - - // Start counting down from the new reload - // mem::transmute::<_, SYST>(()).clear_current(); } } else { - // The queue is empty - // mem::transmute::<_, SYST>(()).disable_interrupt(); + // The queue is empty, disable the interrupt. disable_interrupt(); None -- cgit v1.2.3 From ebf2f058a4d2a1fcf118144b9893dc3038939bad Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Thu, 18 Feb 2021 19:30:59 +0100 Subject: Now with new monotonic trait and crate --- Cargo.toml | 1 + macros/src/codegen.rs | 24 ++++++++++++- macros/src/codegen/init.rs | 2 +- macros/src/codegen/module.rs | 16 +++++---- macros/src/codegen/post_init.rs | 18 ++++++---- macros/src/codegen/pre_init.rs | 20 ++++++++--- macros/src/codegen/software_tasks.rs | 2 +- macros/src/codegen/timer_queue.rs | 21 ++++++++--- macros/src/codegen/util.rs | 10 ++++++ src/export.rs | 4 +-- src/lib.rs | 6 ++-- src/tq.rs | 68 +++++++++++++++++++++--------------- 12 files changed, 134 insertions(+), 58 deletions(-) (limited to 'src') diff --git a/Cargo.toml b/Cargo.toml index 2063135..3729038 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,7 @@ required-features = ["__v7"] cortex-m = "0.7.0" cortex-m-rtic-macros = { path = "macros", version = "0.6.0-alpha.0" } rtic-core = { git = "https://github.com/rtic-rs/rtic-core", branch = "new_monotonic" } +rtic-monotonic = { git = "https://github.com/rtic-rs/rtic-monotonic", branch = "master" } #rtic-core = "0.3.1" heapless = "0.5.0" bare-metal = "1.0.0" diff --git a/macros/src/codegen.rs b/macros/src/codegen.rs index bb8aa4e..bdfcd36 100644 --- a/macros/src/codegen.rs +++ b/macros/src/codegen.rs @@ -104,13 +104,35 @@ pub fn app(app: &App, analysis: &Analysis, extra: &Extra) -> TokenStream2 { )); } + let app_name = &app.name; + let app_path = quote! {crate::#app_name}; + let monotonic_imports: Vec<_> = app .monotonics .iter() .map(|(_, monotonic)| { let name = &monotonic.ident; let ty = &monotonic.ty; - quote!(pub type #name = #ty;) + let mangled_name = util::mangle_monotonic_type(&name.to_string()); + let ident = util::monotonic_ident(&name.to_string()); + quote! { + #[doc(hidden)] + pub type #mangled_name = #ty; + + pub mod #name { + pub fn now() -> rtic::time::Instant<#app_path::#mangled_name> { + rtic::export::interrupt::free(|_| { + use rtic::Monotonic as _; + use rtic::time::Clock as _; + if let Ok(v) = unsafe{ (&*#app_path::#ident.as_ptr()).try_now() } { + v + } else { + unreachable!("Your monotonic is not infallible!") + } + }) + } + } + } }) .collect(); diff --git a/macros/src/codegen/init.rs b/macros/src/codegen/init.rs index 66c3bc4..aa9adcb 100644 --- a/macros/src/codegen/init.rs +++ b/macros/src/codegen/init.rs @@ -69,7 +69,7 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> CodegenResult { let app_path = quote! {crate::#app_name}; let locals_new = locals_new.iter(); let call_init = Some( - quote!(let (late, monotonics) = #app_path::#name(#(#locals_new,)* #name::Context::new(core.into()));), + quote!(let (late, mut monotonics) = #app_path::#name(#(#locals_new,)* #name::Context::new(core.into()));), ); root_init.push(module::codegen( diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index 93fbeae..f0f403b 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -126,7 +126,7 @@ pub fn codegen( .monotonics .iter() .map(|(_, monotonic)| { - let mono = &monotonic.ident; + let mono = util::mangle_monotonic_type(&monotonic.ident.to_string()); quote! {#app_path::#mono} }) .collect(); @@ -234,6 +234,7 @@ pub fn codegen( let tq = util::tq_ident(&monotonic.ident.to_string()); let t = util::schedule_t_ident(); let m = &monotonic.ident; + let m_mangled = util::mangle_monotonic_type(&monotonic.ident.to_string()); let m_isr = &monotonic.args.binds; let enum_ = util::interrupt_ident(); @@ -242,9 +243,10 @@ pub fn codegen( items.push(quote!(pub use #m::spawn_at;)); } - let (unmask, pend) = if &*m_isr.to_string() == "SysTick" { + let (enable_interrupt, pend) = if &*m_isr.to_string() == "SysTick" { ( - quote!(core::mem::transmute::<_, cortex_m::peripheral::SYST>(()).disable_interrupt()), + quote!(core::mem::transmute::<_, cortex_m::peripheral::SYST>(()) + .enable_interrupt()), quote!(cortex_m::peripheral::SCB::set_pendst()), ) } else { @@ -263,16 +265,16 @@ pub fn codegen( #(,#args)* ) -> Result<(), #ty> where D: rtic::time::duration::Duration + rtic::time::fixed_point::FixedPoint, - D::T: Into<<#app_path::#m as rtic::time::Clock>::T>, + D::T: Into<<#app_path::#m_mangled as rtic::time::Clock>::T>, { - let instant = <#app_path::#m as rtic::Monotonic>::now(); + let instant = #app_path::#m::now(); spawn_at(instant + duration, #(,#untupled)*) } #(#cfgs)* pub fn spawn_at( - instant: rtic::time::Instant<#app_path::#m> + instant: rtic::time::Instant<#app_path::#m_mangled> #(,#args)* ) -> Result<(), #ty> { unsafe { @@ -296,7 +298,7 @@ pub fn codegen( rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked( nr, - || #unmask, + || #enable_interrupt, || #pend, )); diff --git a/macros/src/codegen/post_init.rs b/macros/src/codegen/post_init.rs index 9268e04..b6cf47c 100644 --- a/macros/src/codegen/post_init.rs +++ b/macros/src/codegen/post_init.rs @@ -1,6 +1,7 @@ -use proc_macro2::TokenStream as TokenStream2; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use rtic_syntax::ast::App; +use syn::Index; use crate::{analyze::Analysis, codegen::util}; @@ -25,12 +26,17 @@ pub fn codegen(app: &App, analysis: &Analysis) -> Vec { } } - for (monotonic, _) in app.monotonics.iter() { - stmts.push(quote!(#monotonic::reset();)); - } + for (i, (monotonic, _)) in app.monotonics.iter().enumerate() { + let idx = Index { + index: i as u32, + span: Span::call_site(), + }; + stmts.push(quote!(monotonics.#idx.reset();)); - // Forget the monotonics so they won't be dropped. - stmts.push(quote!(core::mem::forget(monotonics);)); + // Store the monotonic + let name = util::monotonic_ident(&monotonic.to_string()); + stmts.push(quote!(#name.as_mut_ptr().write(monotonics.#idx);)); + } // Enable the interrupts -- this completes the `init`-ialization phase stmts.push(quote!(rtic::export::interrupt::enable();)); diff --git a/macros/src/codegen/pre_init.rs b/macros/src/codegen/pre_init.rs index e7b1b03..fbfff3b 100644 --- a/macros/src/codegen/pre_init.rs +++ b/macros/src/codegen/pre_init.rs @@ -77,14 +77,17 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec Vec(()) + .enable_interrupt(); + } )); } else { // NOTE this also checks that the interrupt exists in the `Interrupt` enumeration @@ -101,10 +110,13 @@ pub fn codegen(app: &App, analysis: &Analysis, extra: &Extra) -> Vec Vec Vec); + + items.push(quote!( + #[doc = #doc] + static mut #mono: #mono_ty = core::mem::MaybeUninit::uninit(); + )); } // Timer queue handler @@ -100,8 +112,8 @@ pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec>(); let bound_interrupt = &monotonic.args.binds; - let enable_isr = if &*bound_interrupt.to_string() == "SysTick" { - quote!(core::mem::transmute::<_, cortex_m::peripheral::SYST>(()).enable_interrupt()) + let disable_isr = if &*bound_interrupt.to_string() == "SysTick" { + quote!(core::mem::transmute::<_, cortex_m::peripheral::SYST>(()).disable_interrupt()) } else { quote!(rtic::export::NVIC::mask(#rt_err::#enum_::#bound_interrupt)) }; @@ -111,7 +123,8 @@ pub fn codegen(app: &App, analysis: &Analysis, _extra: &Extra) -> Vec Ident { Ident::new(&format!("TQ_{}", name), Span::call_site()) } +/// Generates an identifier for monotonic timer storage +pub fn monotonic_ident(name: &str) -> Ident { + Ident::new(&format!("MONOTONIC_STORAGE_{}", name), Span::call_site()) +} + +/// Generates an identifier for monotonic timer storage +pub fn mangle_monotonic_type(name: &str) -> Ident { + Ident::new(&format!("MonotonicMangled{}", name), Span::call_site()) +} + /// The name to get better RT flag errors pub fn rt_err_ident() -> Ident { Ident::new( diff --git a/src/export.rs b/src/export.rs index ab5984e..91a4a5e 100644 --- a/src/export.rs +++ b/src/export.rs @@ -16,7 +16,7 @@ pub use cortex_m::{ use heapless::spsc::SingleCore; pub use heapless::{consts, i::Queue as iQueue, spsc::Queue}; pub use heapless::{i::BinaryHeap as iBinaryHeap, BinaryHeap}; -pub use rtic_core::monotonic::Monotonic; +pub use rtic_monotonic as monotonic; pub type SCFQ = Queue; pub type SCRQ = Queue<(T, u8), N, u8, SingleCore>; @@ -116,7 +116,7 @@ where #[inline(always)] pub fn assert_monotonic() where - T: Monotonic, + T: monotonic::Monotonic, { } diff --git a/src/lib.rs b/src/lib.rs index 1d4df65..16f2e9f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -37,10 +37,8 @@ use cortex_m::{interrupt::InterruptNumber, peripheral::NVIC}; pub use cortex_m_rtic_macros::app; -pub use rtic_core::{ - monotonic::{self, embedded_time as time, Monotonic}, - prelude as mutex_prelude, Exclusive, Mutex, -}; +pub use rtic_core::{prelude as mutex_prelude, Exclusive, Mutex}; +pub use rtic_monotonic::{self, embedded_time as time, Monotonic}; #[doc(hidden)] pub mod export; diff --git a/src/tq.rs b/src/tq.rs index 4c89a66..6697f10 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -1,4 +1,7 @@ -use crate::{time::Instant, Monotonic}; +use crate::{ + time::{Clock, Instant}, + Monotonic, +}; use core::cmp::Ordering; use heapless::{binary_heap::Min, ArrayLength, BinaryHeap}; @@ -42,7 +45,7 @@ where }) .unwrap_or(true); if if_heap_max_greater_than_nr { - if is_empty { + if Mono::DISABLE_INTERRUPT_ON_EMPTY_QUEUE && is_empty { // mem::transmute::<_, SYST>(()).enable_interrupt(); enable_interrupt(); } @@ -61,44 +64,53 @@ where self.0.is_empty() } + #[inline] + fn unwrapper(val: Result) -> T { + if let Ok(v) = val { + v + } else { + unreachable!("Your monotonic is not infallible") + } + } + /// Dequeue a task from the TimerQueue #[inline] - pub fn dequeue(&mut self, disable_interrupt: F) -> Option<(Task, u8)> + pub fn dequeue(&mut self, disable_interrupt: F, mono: &mut Mono) -> Option<(Task, u8)> where F: FnOnce(), { - unsafe { - Mono::clear_compare(); + mono.clear_compare_flag(); + + if let Some(instant) = self.0.peek().map(|p| p.instant) { + if instant < Self::unwrapper(Clock::try_now(mono)) { + // task became ready + let nr = unsafe { self.0.pop_unchecked() }; - if let Some(instant) = self.0.peek().map(|p| p.instant) { - if instant < Mono::now() { - // task became ready - let nr = self.0.pop_unchecked(); + Some((nr.task, nr.index)) + } else { + // TODO: Fix this hack... + // Extract the compare time. + mono.set_compare(*instant.duration_since_epoch().integer()); + + // Double check that the instant we set is really in the future, else + // dequeue. If the monotonic is fast enough it can happen that from the + // read of now to the set of the compare, the time can overflow. This is to + // guard against this. + if instant < Self::unwrapper(Clock::try_now(mono)) { + let nr = unsafe { self.0.pop_unchecked() }; Some((nr.task, nr.index)) } else { - // TODO: Fix this hack... - // Extract the compare time. - Mono::set_compare(*instant.duration_since_epoch().integer()); - - // Double check that the instant we set is really in the future, else - // dequeue. If the monotonic is fast enough it can happen that from the - // read of now to the set of the compare, the time can overflow. This is to - // guard against this. - if instant < Mono::now() { - let nr = self.0.pop_unchecked(); - - Some((nr.task, nr.index)) - } else { - None - } + None } - } else { - // The queue is empty, disable the interrupt. + } + } else { + // The queue is empty, disable the interrupt. + if Mono::DISABLE_INTERRUPT_ON_EMPTY_QUEUE { disable_interrupt(); - - None } + + None } } } -- cgit v1.2.3 From e52088bbd8f4f15b0d49ced8a24c5a2fc8c8c11f Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Mon, 22 Feb 2021 20:15:13 +0100 Subject: Of by 1 --- src/tq.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/tq.rs b/src/tq.rs index 6697f10..541ffcd 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -82,7 +82,7 @@ where mono.clear_compare_flag(); if let Some(instant) = self.0.peek().map(|p| p.instant) { - if instant < Self::unwrapper(Clock::try_now(mono)) { + if instant <= Self::unwrapper(Clock::try_now(mono)) { // task became ready let nr = unsafe { self.0.pop_unchecked() }; @@ -96,7 +96,7 @@ where // dequeue. If the monotonic is fast enough it can happen that from the // read of now to the set of the compare, the time can overflow. This is to // guard against this. - if instant < Self::unwrapper(Clock::try_now(mono)) { + if instant <= Self::unwrapper(Clock::try_now(mono)) { let nr = unsafe { self.0.pop_unchecked() }; Some((nr.task, nr.index)) -- cgit v1.2.3 From 82d051e8e967522af735fff47a1738ce4952f950 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Mon, 22 Feb 2021 20:59:03 +0100 Subject: Added enable/disable timer calls --- macros/src/codegen/module.rs | 21 +++++++++++++++------ src/tq.rs | 5 ++++- 2 files changed, 19 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index f0f403b..76641fa 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -230,11 +230,13 @@ pub fn codegen( // Schedule caller for (_, monotonic) in &app.monotonics { let instants = util::monotonic_instants_ident(name, &monotonic.ident); + let monotonic_name = monotonic.ident.to_string(); let tq = util::tq_ident(&monotonic.ident.to_string()); let t = util::schedule_t_ident(); let m = &monotonic.ident; - let m_mangled = util::mangle_monotonic_type(&monotonic.ident.to_string()); + let m_mangled = util::mangle_monotonic_type(&monotonic_name); + let m_ident = util::monotonic_ident(&monotonic_name); let m_isr = &monotonic.args.binds; let enum_ = util::interrupt_ident(); @@ -296,11 +298,18 @@ pub fn codegen( task: #app_path::#t::#name, }; - rtic::export::interrupt::free(|_| #app_path::#tq.enqueue_unchecked( - nr, - || #enable_interrupt, - || #pend, - )); + rtic::export::interrupt::free(|_| + if let Some(mono) = #app_path::#m_ident.as_mut() { + #app_path::#tq.enqueue_unchecked( + nr, + || #enable_interrupt, + || #pend, + mono) + } else { + // We can only use the timer queue if `init` has returned, and it + // writes the `Some(monotonic)` we are accessing here. + core::hint::unreachable_unchecked() + }); Ok(()) } else { diff --git a/src/tq.rs b/src/tq.rs index 541ffcd..a637007 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -29,6 +29,7 @@ where nr: NotReady, enable_interrupt: F1, pend_handler: F2, + mono: &mut Mono, ) where F1: FnOnce(), F2: FnOnce(), @@ -46,7 +47,8 @@ where .unwrap_or(true); if if_heap_max_greater_than_nr { if Mono::DISABLE_INTERRUPT_ON_EMPTY_QUEUE && is_empty { - // mem::transmute::<_, SYST>(()).enable_interrupt(); + // mem::transmute::<_, SYST>(()).enable_interrupt();A + mono.enable_timer(); enable_interrupt(); } @@ -108,6 +110,7 @@ where // The queue is empty, disable the interrupt. if Mono::DISABLE_INTERRUPT_ON_EMPTY_QUEUE { disable_interrupt(); + mono.disable_timer(); } None -- cgit v1.2.3 From 56d99c02bd809dfa96d6c1f102e046533c5c631f Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Mon, 22 Feb 2021 20:59:23 +0100 Subject: Updated to new interface --- src/tq.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/tq.rs b/src/tq.rs index a637007..063bbd8 100644 --- a/src/tq.rs +++ b/src/tq.rs @@ -90,9 +90,8 @@ where Some((nr.task, nr.index)) } else { - // TODO: Fix this hack... - // Extract the compare time. - mono.set_compare(*instant.duration_since_epoch().integer()); + // Set compare + mono.set_compare(&instant); // Double check that the instant we set is really in the future, else // dequeue. If the monotonic is fast enough it can happen that from the -- cgit v1.2.3 From 767d46e05bbc88eb3c236cf468f9432c7fe0ce05 Mon Sep 17 00:00:00 2001 From: Emil Fresk Date: Thu, 25 Feb 2021 17:32:12 +0100 Subject: Review fixes --- Cargo.toml | 1 - macros/src/codegen.rs | 3 ++- macros/src/codegen/module.rs | 8 ++------ src/lib.rs | 2 +- 4 files changed, 5 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/Cargo.toml b/Cargo.toml index 5589aa6..0a96451 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,7 +53,6 @@ required-features = ["__v7"] [dependencies] cortex-m = "0.7.0" cortex-m-rtic-macros = { path = "macros", version = "0.6.0-alpha.0" } -# rtic-core = { git = "https://github.com/rtic-rs/rtic-core", branch = "new_monotonic" } rtic-monotonic = { git = "https://github.com/rtic-rs/rtic-monotonic", branch = "master" } rtic-core = "0.3.1" heapless = "0.5.0" diff --git a/macros/src/codegen.rs b/macros/src/codegen.rs index 32e7da0..7885a4a 100644 --- a/macros/src/codegen.rs +++ b/macros/src/codegen.rs @@ -127,6 +127,7 @@ pub fn app(app: &App, analysis: &Analysis, extra: &Extra) -> TokenStream2 { #[doc(hidden)] pub type #mangled_name = #ty; + /// This module holds the static implementation for `#name::now()` #[allow(non_snake_case)] pub mod #name { /// Access the global `Monotonic` implementation, not that this will panic @@ -154,7 +155,7 @@ pub fn app(app: &App, analysis: &Analysis, extra: &Extra) -> TokenStream2 { let rt_err = util::rt_err_ident(); quote!( - /// Implementation details + /// The RTIC application module pub mod #name { /// Always include the device crate which contains the vector table use #device as #rt_err; diff --git a/macros/src/codegen/module.rs b/macros/src/codegen/module.rs index e480b86..25260be 100644 --- a/macros/src/codegen/module.rs +++ b/macros/src/codegen/module.rs @@ -53,13 +53,9 @@ pub fn codegen( Context::Idle => {} - Context::HardwareTask(..) => { - // None for now. - } + Context::HardwareTask(_) => {} - Context::SoftwareTask(..) => { - // None for now. - } + Context::SoftwareTask(_) => {} } if ctxt.has_locals(app) { diff --git a/src/lib.rs b/src/lib.rs index 16f2e9f..8220739 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ #![deny(missing_docs)] #![deny(rust_2018_compatibility)] #![deny(rust_2018_idioms)] -// #![deny(warnings)] +#![deny(warnings)] #![no_std] use cortex_m::{interrupt::InterruptNumber, peripheral::NVIC}; -- cgit v1.2.3