1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//! Timers
use core::{fmt, marker::PhantomData};
use r3_core::{
    closure::Closure,
    kernel::{traits, SetTimerDelayError, SetTimerPeriodError, StartTimerError, StopTimerError},
    time::Duration,
    utils::Init,
};

use crate::{
    error::NoAccessError,
    klock::{assume_cpu_lock, lock_cpu, CpuLockCell, CpuLockGuard, CpuLockTokenRefMut},
    timeout,
    utils::pin::static_pin,
    Id, KernelCfg2, KernelTraits, System,
};

pub(super) type TimerId = Id;

impl<Traits: KernelTraits> System<Traits> {
    /// Get the [`TimerCb`] for the specified raw ID.
    ///
    /// # Safety
    ///
    /// See [`crate::bad_id`].
    #[inline]
    unsafe fn timer_cb(this: TimerId) -> Result<&'static TimerCb<Traits>, NoAccessError> {
        Traits::get_timer_cb(this.get() - 1).ok_or_else(|| unsafe { crate::bad_id() })
    }
}

unsafe impl<Traits: KernelTraits> traits::KernelTimer for System<Traits> {
    type RawTimerId = TimerId;

    #[cfg_attr(not(feature = "inline_syscall"), inline(never))]
    unsafe fn raw_timer_start(this: TimerId) -> Result<(), StartTimerError> {
        let mut lock = lock_cpu::<Traits>()?;
        // Safety: The caller is responsible for providing a valid object ID
        let timer_cb = unsafe { Self::timer_cb(this)? };
        start_timer(lock.borrow_mut(), timer_cb);
        Ok(())
    }

    #[cfg_attr(not(feature = "inline_syscall"), inline(never))]
    unsafe fn raw_timer_stop(this: TimerId) -> Result<(), StopTimerError> {
        let mut lock = lock_cpu::<Traits>()?;
        // Safety: The caller is responsible for providing a valid object ID
        let timer_cb = unsafe { Self::timer_cb(this)? };
        stop_timer(lock.borrow_mut(), timer_cb);
        Ok(())
    }

    #[cfg_attr(not(feature = "inline_syscall"), inline(never))]
    unsafe fn raw_timer_set_delay(
        this: TimerId,
        delay: Option<Duration>,
    ) -> Result<(), SetTimerDelayError> {
        let time32 = if let Some(x) = delay {
            timeout::time32_from_duration(x)?
        } else {
            timeout::BAD_DURATION32
        };
        let mut lock = lock_cpu::<Traits>()?;
        // Safety: The caller is responsible for providing a valid object ID
        let timer_cb = unsafe { Self::timer_cb(this)? };
        set_timer_delay(lock.borrow_mut(), timer_cb, time32);
        Ok(())
    }

    #[cfg_attr(not(feature = "inline_syscall"), inline(never))]
    unsafe fn raw_timer_set_period(
        this: TimerId,
        period: Option<Duration>,
    ) -> Result<(), SetTimerPeriodError> {
        let time32 = if let Some(x) = period {
            timeout::time32_from_duration(x)?
        } else {
            timeout::BAD_DURATION32
        };
        let mut lock = lock_cpu::<Traits>()?;
        // Safety: The caller is responsible for providing a valid object ID
        let timer_cb = unsafe { Self::timer_cb(this)? };
        set_timer_period(lock.borrow_mut(), timer_cb, time32);
        Ok(())
    }
}

/// *Timer control block* - the state data of a timer.
///
/// This type isn't technically public but needs to be `pub` so that it can be
/// referred to by a macro.
#[doc(hidden)]
pub struct TimerCb<Traits: KernelCfg2> {
    /// The static properties of the timer.
    pub(super) attr: &'static TimerAttr<Traits>,

    /// The timeout object for the timer.
    ///
    ///  - If the delay is `Some(_)` and the timer is in the Active state, the
    ///    timeout object is linked. The delay is implicitly defined in this
    ///    case.
    ///
    ///  - If the delay is `None` or the timer is in the Dormant state, the
    ///    timeout object is unlinked. The delay can be retrieved by
    ///    [`timeout::Timeout::at_raw`].
    ///
    pub(super) timeout: timeout::Timeout<Traits>,

    /// `true` iff the timer is in the Active state.
    pub(super) active: CpuLockCell<Traits, bool>,

    pub(super) period: CpuLockCell<Traits, timeout::Time32>,
}

impl<Traits: KernelTraits> Init for TimerCb<Traits> {
    #[allow(clippy::declare_interior_mutable_const)]
    const INIT: Self = Self {
        attr: &Init::INIT,
        timeout: Init::INIT,
        active: Init::INIT,
        period: Init::INIT,
    };
}

impl<Traits: KernelTraits> fmt::Debug for TimerCb<Traits> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("TimerCb")
            .field("self", &(self as *const _))
            .field("attr", &self.attr)
            .field("timeout", &self.timeout)
            .field("active", &self.active)
            .field("period", &self.period)
            .finish()
    }
}

/// The static properties of a timer.
///
/// This type isn't technically public but needs to be `pub` so that it can be
/// referred to by a macro.
#[doc(hidden)]
pub struct TimerAttr<Traits> {
    /// The entry point of the timer.
    ///
    /// # Safety
    ///
    /// This is only meant to be used by a kernel port, as a timer callback,
    /// not by user code. Using this in other ways may cause an undefined
    /// behavior.
    pub(super) entry_point: Closure,

    /// The initial state of the timer.
    pub(super) init_active: bool,

    pub(super) _phantom: PhantomData<Traits>,
}

impl<Traits> Init for TimerAttr<Traits> {
    const INIT: Self = Self {
        entry_point: Closure::INIT,
        init_active: false,
        _phantom: PhantomData,
    };
}

impl<Traits: KernelTraits> fmt::Debug for TimerAttr<Traits> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("TimerAttr")
            .field("entry_point", &self.entry_point)
            .finish()
    }
}

/// Initialize a timer at boot time.
#[inline]
pub(super) fn init_timer<Traits: KernelTraits>(
    mut lock: CpuLockTokenRefMut<'_, Traits>,
    timer_cb: &'static TimerCb<Traits>,
) {
    if timer_cb.attr.init_active {
        // Get the initial delay value
        let delay = timer_cb.timeout.at_raw(lock.borrow_mut());

        if delay != timeout::BAD_DURATION32 {
            // Schedule the first tick
            timeout::insert_timeout(lock.borrow_mut(), static_pin(&timer_cb.timeout));
        }

        timer_cb.active.replace(&mut *lock, true);
    }
}

/// The core portion of [`Timer::start`].
#[inline]
fn start_timer<Traits: KernelTraits>(
    mut lock: CpuLockTokenRefMut<'_, Traits>,
    timer_cb: &'static TimerCb<Traits>,
) {
    if timer_cb.active.get(&*lock) {
        return;
    }

    // Get the current delay value
    let delay = timer_cb.timeout.at_raw(lock.borrow_mut());

    if delay != timeout::BAD_DURATION32 {
        // Schedule the next tick
        timer_cb
            .timeout
            .set_expiration_after(lock.borrow_mut(), delay);
        timeout::insert_timeout(lock.borrow_mut(), static_pin(&timer_cb.timeout));
    }

    timer_cb.active.replace(&mut *lock, true);
}

/// The core portion of [`Timer::stop`].
#[inline]
fn stop_timer<Traits: KernelTraits>(
    mut lock: CpuLockTokenRefMut<'_, Traits>,
    timer_cb: &TimerCb<Traits>,
) {
    if timer_cb.timeout.is_linked(lock.borrow_mut()) {
        debug_assert!(timer_cb.active.get(&*lock));

        // Capture the current delay value
        let delay = timer_cb
            .timeout
            .saturating_duration_until_timeout(lock.borrow_mut());

        // Unlink the timeout
        timeout::remove_timeout(lock.borrow_mut(), &timer_cb.timeout);

        // Store the captured delay value
        timer_cb.timeout.set_at_raw(lock.borrow_mut(), delay);
    }

    timer_cb.active.replace(&mut *lock, false);
}

/// The core portion of [`Timer::set_delay`].
#[inline]
fn set_timer_delay<Traits: KernelTraits>(
    mut lock: CpuLockTokenRefMut<'_, Traits>,
    timer_cb: &'static TimerCb<Traits>,
    delay: timeout::Time32,
) {
    let is_active = timer_cb.active.get(&*lock);

    if timer_cb.timeout.is_linked(lock.borrow_mut()) {
        timeout::remove_timeout(lock.borrow_mut(), &timer_cb.timeout);
    }

    if is_active && delay != timeout::BAD_DURATION32 {
        timer_cb
            .timeout
            .set_expiration_after(lock.borrow_mut(), delay);
        timeout::insert_timeout(lock.borrow_mut(), static_pin(&timer_cb.timeout));
    } else {
        timer_cb.timeout.set_at_raw(lock.borrow_mut(), delay);
    }
}

/// The core portion of [`Timer::set_period`].
#[inline]
fn set_timer_period<Traits: KernelTraits>(
    mut lock: CpuLockTokenRefMut<'_, Traits>,
    timer: &TimerCb<Traits>,
    period: timeout::Time32,
) {
    timer.period.replace(&mut *lock, period);
}

/// The timeout callback function for a timer. This function should be
/// registered as a callback function when initializing [`TimerCb::timeout`].
///
/// `i` is an index into [`super::KernelCfg2::timer_cb_pool`].
pub(super) fn timer_timeout_handler<Traits: KernelTraits>(
    i: usize,
    mut lock: CpuLockGuard<Traits>,
) -> CpuLockGuard<Traits> {
    let timer_cb = Traits::get_timer_cb(i).unwrap();

    // Schedule the next tick
    debug_assert!(!timer_cb.timeout.is_linked(lock.borrow_mut()));
    debug_assert!(timer_cb.active.get(&*lock));

    let period = timer_cb.period.get(&*lock);
    if period == timeout::BAD_DURATION32 {
        timer_cb
            .timeout
            .set_at_raw(lock.borrow_mut(), timeout::BAD_DURATION32);
    } else {
        timer_cb
            .timeout
            .adjust_expiration(lock.borrow_mut(), period);
        timeout::insert_timeout(lock.borrow_mut(), static_pin(&timer_cb.timeout));
    }

    // Release CPU Lock before calling the application-provided callback
    // function
    drop(lock);

    timer_cb.attr.entry_point.call();

    // Re-acquire CPU Lock
    lock_cpu().unwrap_or_else(|_| unsafe { assume_cpu_lock() })
}