Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/scheduler/timer.rs

kernel/scheduler/
timer.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use core::ptr::NonNull;
16
17use foreign_box::ForeignBox;
18use list::{ForeignList, Link};
19use pw_time_core::Instant;
20
21use crate::Kernel;
22
23list::define_adapter!(pub TimerCallbackListAdapter<K: Kernel> => Timer<K>::link);
24
25pub trait TimerCallback<K: Kernel> {
26    fn callback(
27        &mut self,
28        kernel: K,
29        timer: ForeignBox<Timer<K>>,
30        now: Instant<K::Clock>,
31    ) -> Option<ForeignBox<Timer<K>>>;
32}
33
34impl<K, F> TimerCallback<K> for F
35where
36    K: Kernel,
37    F: FnMut(K, ForeignBox<Timer<K>>, Instant<K::Clock>) -> Option<ForeignBox<Timer<K>>>,
38{
39    fn callback(
40        &mut self,
41        kernel: K,
42        timer: ForeignBox<Timer<K>>,
43        now: Instant<K::Clock>,
44    ) -> Option<ForeignBox<Timer<K>>> {
45        self(kernel, timer, now)
46    }
47}
48
49#[allow(dead_code)]
50pub struct Timer<K: Kernel> {
51    deadline: Instant<K::Clock>,
52    // XXX: make private
53    pub callback: Option<ForeignBox<dyn TimerCallback<K>>>,
54    link: Link,
55}
56
57impl<K: Kernel> Timer<K> {
58    #[allow(dead_code)]
59    #[must_use]
60    pub fn new(deadline: Instant<K::Clock>, callback: ForeignBox<dyn TimerCallback<K>>) -> Self {
61        Self {
62            deadline,
63            callback: Some(callback),
64            link: Link::new(),
65        }
66    }
67
68    pub fn set(&mut self, deadline: Instant<K::Clock>) {
69        self.deadline = deadline
70    }
71}
72
73#[allow(dead_code)]
74pub struct TimerQueue<K: Kernel> {
75    queue: ForeignList<Timer<K>, TimerCallbackListAdapter<K>>,
76}
77
78unsafe impl<K: Kernel> Sync for TimerQueue<K> {}
79unsafe impl<K: Kernel> Send for TimerQueue<K> {}
80
81impl<K: Kernel> TimerQueue<K> {
82    #[must_use]
83    pub const fn new() -> Self {
84        Self {
85            queue: ForeignList::new(),
86        }
87    }
88
89    pub fn get_next_exipred_callback(
90        &mut self,
91        now: Instant<K::Clock>,
92    ) -> Option<ForeignBox<Timer<K>>> {
93        // TODO - konkers: An optimization opportunity exists here to implement
94        // a something like `peek_front(|front| front.deadline > now)` which
95        // would eliminate the popping and re-pushing of the non-expired
96        // callback.
97        let callback = self.queue.pop_head()?;
98        if callback.deadline > now {
99            self.queue.push_front(callback);
100            return None;
101        }
102
103        Some(callback)
104    }
105}
106
107#[allow(dead_code)]
108pub fn schedule_timer<K: Kernel>(kernel: K, timer: ForeignBox<Timer<K>>) {
109    let mut timer_queue = kernel.get_timer_queue().lock(kernel);
110    timer_queue
111        .queue
112        .sorted_insert_by_key(timer, |timer| timer.deadline);
113}
114
115/// # Safety
116///
117/// `timer` must point to a valid [`TimerCallback`] object which is in the
118/// timer queue.
119pub unsafe fn cancel_timer<K: Kernel>(
120    kernel: K,
121    timer: NonNull<Timer<K>>,
122) -> Option<ForeignBox<Timer<K>>> {
123    let mut timer_queue = kernel.get_timer_queue().lock(kernel);
124    unsafe { timer_queue.queue.remove_element(timer) }
125}
126
127/// # Safety
128///
129/// `timer` must point to a valid [`TimerCallback`] object which is in the
130/// timer queue.
131pub unsafe fn cancel_and_consume_timer<K: Kernel>(kernel: K, timer: NonNull<Timer<K>>) {
132    if let Some(mut callback) = unsafe { cancel_timer(kernel, timer) } {
133        if let Some(callback) = callback.callback.take() {
134            callback.consume();
135        }
136        callback.consume();
137    }
138}
139
140#[allow(dead_code)]
141pub fn process_queue<K: Kernel>(kernel: K, now: Instant<K::Clock>) {
142    let mut timer_queue = kernel.get_timer_queue().lock(kernel);
143    while let Some(mut callback) = timer_queue.get_next_exipred_callback(now) {
144        // Drop the timer queue lock before processing callbacks.  This is
145        // Safe to do because the callback is already removed from the queue.
146        drop(timer_queue);
147
148        let Some(mut callback_fn) = callback.callback.take() else {
149            pw_assert::panic!("No callback function found on timer");
150        };
151        match callback_fn.callback(kernel, callback, now) {
152            Some(mut next_callback) => {
153                next_callback.callback = Some(callback_fn);
154                schedule_timer(kernel, next_callback);
155            }
156            None => {
157                let _ = callback_fn.consume();
158            }
159        }
160
161        // Require timer queue lock.
162        timer_queue = kernel.get_timer_queue().lock(kernel);
163    }
164}