use rusty_rtos_core::config::Config;
use rusty_rtos_core::error::{Error, Result};
use rusty_rtos_core::handle::{QueueHandle, TaskHandle, TimerHandle};
use rusty_rtos_core::hooks::TickHook;
use rusty_rtos_core::isr::Woken;
use rusty_rtos_core::list::ListId;
use rusty_rtos_core::port::Port;
use rusty_rtos_core::trace::{Event, Trace};
use crate::kernel::{Kernel, OwedTrace};
use crate::name::Name;
use crate::queue::{Position, Ready, Wait};
pub const MAX_TIMER_COMMANDS: usize = 32;
pub(crate) const STATUS_ACTIVE: u8 = 0x01;
pub(crate) const STATUS_AUTORELOAD: u8 = 0x04;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Command {
ExecuteCallbackFromIsr,
ExecuteCallback,
Start,
Reset,
Stop,
ChangePeriod,
Delete,
StartFromIsr,
ResetFromIsr,
StopFromIsr,
ChangePeriodFromIsr,
}
impl Command {
pub const FIRST_FROM_ISR: i32 = 6;
#[must_use]
pub const fn id(self) -> i32 {
match self {
Self::ExecuteCallbackFromIsr => -2,
Self::ExecuteCallback => -1,
Self::Start => 1,
Self::Reset => 2,
Self::Stop => 3,
Self::ChangePeriod => 4,
Self::Delete => 5,
Self::StartFromIsr => 6,
Self::ResetFromIsr => 7,
Self::StopFromIsr => 8,
Self::ChangePeriodFromIsr => 9,
}
}
const fn is_from_isr(self) -> bool {
self.id() >= Self::FIRST_FROM_ISR
}
const fn is_start_or_reset(self) -> bool {
matches!(
self,
Self::Start | Self::StartFromIsr | Self::Reset | Self::ResetFromIsr
)
}
const fn is_stop(self) -> bool {
matches!(self, Self::Stop | Self::StopFromIsr)
}
const fn is_change_period(self) -> bool {
matches!(self, Self::ChangePeriod | Self::ChangePeriodFromIsr)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Message {
pub command: Command,
pub(crate) value: u64,
pub(crate) timer: TimerHandle,
pub(crate) param1: u64,
pub(crate) function: u16,
}
impl Default for Message {
fn default() -> Self {
Self {
command: Command::Stop,
value: 0,
timer: TimerHandle::NULL,
param1: 0,
function: 0,
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Timer {
pub(crate) name: Name,
pub(crate) period: u64,
pub(crate) id: u64,
pub(crate) callback: u16,
pub(crate) status: u8,
}
impl<
C: Config,
P: Port,
T: Trace,
H,
const TASKS: usize,
const ITEMS: usize,
const LISTS: usize,
const QUEUES: usize,
const SLOTS: usize,
const BUFFERS: usize,
const BYTES: usize,
const TIMERS: usize,
const GROUPS: usize,
> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS>
where
H: TickHook<Self>,
{
pub(crate) fn timer_list(&self) -> ListId {
let base = C::MAX_PRIORITIES.saturating_add(4);
base.saturating_add(u8::from(self.timers_swapped))
}
pub(crate) fn overflow_timer_list(&self) -> ListId {
let base = C::MAX_PRIORITIES.saturating_add(4);
base.saturating_add(u8::from(!self.timers_swapped))
}
pub(crate) fn timer_item(timer: TimerHandle) -> u16 {
(TASKS.saturating_mul(2) as u16).saturating_add(timer.index())
}
pub fn timer_create(
&mut self,
name: &str,
period: u64,
auto_reload: bool,
id: u64,
callback: u16,
) -> Result<TimerHandle> {
if period == 0 {
return Err(Error::InvalidArgument);
}
self.account_for_allocation();
let status = if auto_reload { STATUS_AUTORELOAD } else { 0 };
let handle = self
.timers
.try_insert(Timer {
name: Name::new(name, crate::NAME_CAPACITY),
period,
id,
callback,
status,
})
.map_err(|_| Error::Full)?;
self.check_for_valid_list_and_queue()?;
let tick = self.tick;
let name = self
.timers
.resolve(handle)
.map(|t| t.name)
.unwrap_or_default();
self.trace.note_exits(self.port.exits());
self.trace.event(
tick,
Event::TimerCreate {
timer: handle,
name: name.as_str(),
},
);
Ok(handle)
}
pub(crate) fn check_for_valid_list_and_queue(&mut self) -> Result<()> {
self.enter_critical();
let result = if self.timer_queue == QueueHandle::NULL {
match self.queue_create(C::TIMER_QUEUE_LENGTH) {
Ok(queue) => {
self.timer_queue = queue;
Ok(())
}
Err(e) => Err(e),
}
} else {
Ok(())
};
self.exit_critical();
result
}
pub fn timer_id(&mut self, timer: TimerHandle) -> Result<u64> {
self.enter_critical();
let id = self.timers.resolve(timer).map(|t| t.id);
self.exit_critical();
id
}
pub fn timer_set_id(&mut self, timer: TimerHandle, id: u64) -> Result<()> {
self.enter_critical();
let result = self.timers.resolve_mut(timer).map(|t| {
t.id = id;
});
self.exit_critical();
result
}
pub fn timer_period(&self, timer: TimerHandle) -> Result<u64> {
self.timers.resolve(timer).map(|t| t.period)
}
pub fn timer_is_active(&mut self, timer: TimerHandle) -> Result<bool> {
self.enter_critical();
let active = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_ACTIVE) != 0);
self.exit_critical();
active
}
pub fn timer_expiry_time(&self, timer: TimerHandle) -> Result<u64> {
self.timers.resolve(timer)?;
self.lists.value(Self::timer_item(timer))
}
pub fn timer_auto_reload(&mut self, timer: TimerHandle) -> Result<bool> {
self.enter_critical();
let auto = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_AUTORELOAD) != 0);
self.exit_critical();
auto
}
pub fn timer_set_auto_reload(&mut self, timer: TimerHandle, auto: bool) -> Result<()> {
self.enter_critical();
let result = self.timers.resolve_mut(timer).map(|t| {
if auto {
t.status |= STATUS_AUTORELOAD;
} else {
t.status &= !STATUS_AUTORELOAD;
}
});
self.exit_critical();
result
}
pub fn timer_command(
&mut self,
timer: TimerHandle,
command: Command,
value: u64,
ticks: u64,
) -> Result<Wait<bool>> {
let message = Message {
command,
value,
timer,
..Message::default()
};
if command.is_from_isr() {
self.trace_command_send(timer, command, value);
return Ok(Ready(false));
}
let ticks = if self.is_running() { ticks } else { 0 };
let caller = self.current();
match self.post_timer_message(message, ticks) {
Ok(Wait::Blocked) => Ok(Wait::Blocked),
Ok(Ready(ok)) => {
self.trace_command_send_for(caller, timer, command, value);
Ok(Ready(ok))
}
Err(Error::Full) => {
self.trace_command_send_for(caller, timer, command, value);
Ok(Ready(false))
}
Err(e) => Err(e),
}
}
pub fn timer_start(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
let now = self.tick;
self.timer_command(timer, Command::Start, now, ticks)
}
pub fn timer_stop(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
self.timer_command(timer, Command::Stop, 0, ticks)
}
pub fn timer_reset(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
let now = self.tick;
self.timer_command(timer, Command::Reset, now, ticks)
}
pub fn timer_change_period(
&mut self,
timer: TimerHandle,
period: u64,
ticks: u64,
) -> Result<Wait<bool>> {
if period == 0 {
return Err(Error::InvalidArgument);
}
self.timer_command(timer, Command::ChangePeriod, period, ticks)
}
pub fn timer_delete(&mut self, timer: TimerHandle, ticks: u64) -> Result<Wait<bool>> {
self.timer_command(timer, Command::Delete, 0, ticks)
}
pub fn timer_start_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
let now = self.tick_count_from_isr();
self.timer_command_from_isr(timer, Command::StartFromIsr, now)
}
pub fn timer_stop_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
self.timer_command_from_isr(timer, Command::StopFromIsr, 0)
}
pub fn timer_reset_from_isr(&mut self, timer: TimerHandle) -> Result<(bool, Woken)> {
let now = self.tick_count_from_isr();
self.timer_command_from_isr(timer, Command::ResetFromIsr, now)
}
pub fn timer_change_period_from_isr(
&mut self,
timer: TimerHandle,
period: u64,
) -> Result<(bool, Woken)> {
self.timer_command_from_isr(timer, Command::ChangePeriodFromIsr, period)
}
pub fn timer_command_from_isr(
&mut self,
timer: TimerHandle,
command: Command,
value: u64,
) -> Result<(bool, Woken)> {
if !command.is_from_isr() || (command.is_change_period() && value == 0) {
self.trace_command_send(timer, command, value);
return Ok((false, Woken::NO));
}
let message = Message {
command,
value,
timer,
..Message::default()
};
let (ok, woken) = self.post_timer_message_from_isr(message)?;
self.trace_command_send(timer, command, value);
Ok((ok, woken))
}
pub fn timer_pend_function_call(
&mut self,
function: u16,
param1: u64,
param2: u64,
ticks: u64,
) -> Result<Wait<bool>> {
let message = Message {
command: Command::ExecuteCallback,
value: param2,
timer: TimerHandle::NULL,
param1,
function,
};
self.post_timer_message(message, ticks)
}
pub fn timer_pend_function_call_from_isr(
&mut self,
function: u16,
param1: u64,
param2: u64,
) -> Result<(bool, Woken)> {
let message = Message {
command: Command::ExecuteCallbackFromIsr,
value: param2,
timer: TimerHandle::NULL,
param1,
function,
};
self.post_timer_message_from_isr(message)
}
fn trace_command_send(&mut self, timer: TimerHandle, command: Command, value: u64) {
let tick = self.tick;
let name = self
.timers
.resolve(timer)
.map(|t| t.name)
.unwrap_or_default();
self.trace.note_exits(self.port.exits());
self.trace.event(
tick,
Event::TimerCommandSend {
timer,
name: name.as_str(),
command: command.id(),
value,
},
);
}
fn trace_command_send_for(
&mut self,
caller: TaskHandle,
timer: TimerHandle,
command: Command,
value: u64,
) {
let name = self
.timers
.resolve(timer)
.map(|t| t.name)
.unwrap_or_default();
self.trace_failure_or_owe(
caller,
OwedTrace::TimerCommandSend {
timer,
name,
command: command.id(),
value,
},
);
}
fn post_timer_message(&mut self, message: Message, ticks: u64) -> Result<Wait<bool>> {
let slot = self.stage_timer_message(message);
match self.queue_send_generic(self.timer_queue, slot, ticks, Position::Back)? {
Wait::Blocked => Ok(Wait::Blocked),
Ready(()) => {
self.commit_timer_message();
Ok(Ready(true))
}
}
}
fn post_timer_message_from_isr(&mut self, message: Message) -> Result<(bool, Woken)> {
let slot = self.stage_timer_message(message);
match self.queue_send_from_isr(self.timer_queue, slot) {
Ok(woken) => {
self.commit_timer_message();
Ok((true, woken))
}
Err(Error::Full) => Ok((false, Woken::NO)),
Err(e) => Err(e),
}
}
fn stage_timer_message(&mut self, message: Message) -> u64 {
let slot = self.timer_message_next;
if self.timer_queue_has_room() {
if let Some(cell) = self.timer_messages.get_mut(slot) {
*cell = message;
}
}
slot as u64
}
fn commit_timer_message(&mut self) {
self.timer_message_next = self
.timer_message_next
.saturating_add(1)
.checked_rem(C::TIMER_QUEUE_LENGTH)
.unwrap_or(0);
}
fn timer_queue_has_room(&self) -> bool {
self.queues
.resolve(self.timer_queue)
.is_ok_and(|q| q.waiting < q.length)
}
pub fn timer_next_expire(&self) -> (u64, bool) {
let list = self.timer_list();
let empty = self.lists.is_empty(list).unwrap_or(true);
if empty {
(0, true)
} else {
(self.lists.head_value(list).unwrap_or(0), false)
}
}
#[must_use]
pub fn overflow_timer_list_is_empty(&self) -> bool {
self.lists
.is_empty(self.overflow_timer_list())
.unwrap_or(true)
}
pub fn timer_sample_time_now(&mut self) -> Result<(u64, bool)> {
let now = self.tick;
let switched = now < self.timer_last_time;
if switched {
self.switch_timer_lists()?;
}
self.timer_last_time = now;
Ok((now, switched))
}
fn switch_timer_lists(&mut self) -> Result<()> {
while self.lists.is_empty(self.timer_list()) == Ok(false) {
let next = self.lists.head_value(self.timer_list()).unwrap_or(0);
self.process_expired_timer(next, Self::MAX_DELAY)?;
}
self.timers_swapped = !self.timers_swapped;
Ok(())
}
pub fn process_expired_timer(&mut self, expire_at: u64, now: u64) -> Result<()> {
let list = self.timer_list();
let Ok(Some(item)) = self.lists.head(list) else {
return Ok(());
};
let _ = self.lists.remove(item);
let Some(timer) = self.timer_of_item(item) else {
return Ok(());
};
let auto = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_AUTORELOAD) != 0)
.unwrap_or(false);
if auto {
self.reload_timer(timer, expire_at, now)?;
} else if let Ok(t) = self.timers.resolve_mut(timer) {
t.status &= !STATUS_ACTIVE;
}
self.fire_timer(timer);
Ok(())
}
fn reload_timer(&mut self, timer: TimerHandle, expired_at: u64, now: u64) -> Result<()> {
let mut expired_at = expired_at;
loop {
let period = self
.timers
.resolve(timer)
.map(|t| t.period)
.unwrap_or(1)
.max(1);
let next = expired_at.wrapping_add(period) & Self::MAX_DELAY;
if !self.insert_timer_in_active_list(timer, next, now, expired_at)? {
return Ok(());
}
expired_at = next;
self.fire_timer(timer);
}
}
fn fire_timer(&mut self, timer: TimerHandle) {
let (name, callback, id) = match self.timers.resolve(timer) {
Ok(t) => (t.name, t.callback, t.id),
Err(_) => return,
};
let tick = self.tick;
self.trace.note_exits(self.port.exits());
self.trace.event(
tick,
Event::TimerExpired {
timer,
name: name.as_str(),
},
);
H::timer(self, timer, callback, id);
}
pub fn insert_timer_in_active_list(
&mut self,
timer: TimerHandle,
expiry: u64,
now: u64,
command_time: u64,
) -> Result<bool> {
let item = Self::timer_item(timer);
if self.lists.container(item)?.is_some() {
let _ = self.lists.remove(item);
}
self.lists.set_value(item, expiry)?;
let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
if expiry <= now {
if now.wrapping_sub(command_time) & Self::MAX_DELAY >= period {
return Ok(true);
}
let list = self.overflow_timer_list();
self.lists.insert(list, item, expiry)?;
} else {
if now < command_time && expiry >= command_time {
return Ok(true);
}
let list = self.timer_list();
self.lists.insert(list, item, expiry)?;
}
Ok(false)
}
pub fn process_one_timer_command(&mut self, ticks: u64) -> Result<Wait<bool>> {
let slot = match self.queue_receive(self.timer_queue, ticks) {
Ok(Ready(slot)) => slot,
Ok(Wait::Blocked) => return Ok(Wait::Blocked),
Err(_) => return Ok(Ready(false)),
};
let message = self
.timer_messages
.get(slot as usize)
.copied()
.unwrap_or_default();
if message.command.id() < 0 {
H::pended(self, message.function, message.param1, message.value);
return Ok(Ready(true));
}
let timer = message.timer;
if self.timers.resolve(timer).is_err() {
return Ok(Ready(true));
}
let item = Self::timer_item(timer);
if self.lists.container(item)?.is_some() {
let _ = self.lists.remove(item);
}
let (now, _switched) = self.timer_sample_time_now()?;
if message.command.is_start_or_reset() {
if let Ok(t) = self.timers.resolve_mut(timer) {
t.status |= STATUS_ACTIVE;
}
let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
let expiry = message.value.wrapping_add(period) & Self::MAX_DELAY;
if self.insert_timer_in_active_list(timer, expiry, now, message.value)? {
let auto = self
.timers
.resolve(timer)
.map(|t| (t.status & STATUS_AUTORELOAD) != 0)
.unwrap_or(false);
if auto {
self.reload_timer(timer, expiry, now)?;
} else if let Ok(t) = self.timers.resolve_mut(timer) {
t.status &= !STATUS_ACTIVE;
}
self.fire_timer(timer);
}
} else if message.command.is_stop() {
if let Ok(t) = self.timers.resolve_mut(timer) {
t.status &= !STATUS_ACTIVE;
}
} else if message.command.is_change_period() {
if let Ok(t) = self.timers.resolve_mut(timer) {
t.status |= STATUS_ACTIVE;
t.period = message.value;
}
let period = self.timers.resolve(timer).map(|t| t.period).unwrap_or(1);
let expiry = now.wrapping_add(period) & Self::MAX_DELAY;
let _ = self.insert_timer_in_active_list(timer, expiry, now, now)?;
} else if message.command == Command::Delete {
let _ = self.timers.remove(timer);
}
Ok(Ready(true))
}
fn timer_of_item(&self, item: u16) -> Option<TimerHandle> {
let base = TASKS.saturating_mul(2) as u16;
let index = item.checked_sub(base)?;
self.timers.handle_at(index)
}
}