1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Tasks
use core::{fmt, hash, marker::PhantomData};

use raw::KernelBase;

use super::{
    cfg, raw, raw_cfg, ActivateTaskError, Cfg, GetCurrentTaskError, GetTaskPriorityError,
    InterruptTaskError, SetTaskPriorityError, UnparkError, UnparkExactError,
};
use crate::{
    closure::{Closure, IntoClosureConst},
    utils::{Init, PhantomInvariant},
};

// ----------------------------------------------------------------------------

define_object! {
/// Represents a single task in a system.
///
#[doc = common_doc_owned_handle!()]
///
/// <div class="admonition-follows"></div>
///
/// > **Relation to Other Specifications:** Present in almost every real-time
/// > operating system.
///
/// [`RawTaskId`]: raw::KernelBase::RawTaskId
///
/// # Task States
///
/// A task may be in one of the following states:
///
///  - **Dormant** — The task is not executing, doesn't have an associated
///    execution [thread], and can be [activated].
///
///  - **Ready** — The task has an associated execution thread, which is ready to
///    be scheduled to the CPU
///
///  - **Running** — The task has an associated execution thread, which is
///    currently scheduled to the CPU
///
///  - **Waiting** — The task has an associated execution thread, which is
///    currently blocked by a blocking operation
///
/// <center>
///
#[doc = svgbobdoc::transform!(
/// ```svgbob
///                     .-------.
///    .--------------->| Ready |<--------------.
///    |                '-------'               |
///    |          dispatch | ^                  |
///    |                   | |                  |
///    | release           | |                  | activate
/// .---------.            | |           .---------.
/// | Waiting |            | |           | Dormant |
/// '---------'            | |           '---------'
///    ^                   | |                  ^
///    |                   | |                  |
///    |                   v | preempt          |
///    |          wait .---------.              |
///    '---------------| Running |--------------'
///                    '---------' exit
/// ```
)]
///
/// </center>
///
/// [thread]: crate#threads
/// [activated]: TaskMethods::activate
#[doc = include_str!("../common.md")]
pub struct Task<System: _>(System::RawTaskId);

/// Represents a single borrowed task in a system.
#[doc = include_str!("../common.md")]
pub struct TaskRef<System: raw::KernelBase>(_);

pub type StaticTask<System>;

pub trait TaskHandle {}
pub trait TaskMethods {}
}

impl<System: raw::KernelBase> StaticTask<System> {
    /// Construct a `TaskDefiner` to define a task in [a configuration
    /// function](crate#static-configuration).
    pub const fn define() -> TaskDefiner<System> {
        TaskDefiner::new()
    }
}

/// A non-`Send`, `'static` [task] reference. The lack of `Send`-ness constrains
/// its lifetime to the owning task and thus allows it to represent a [current
/// task][1] [safely][2].
///
/// See [`TaskRef`][] for the `Send` counterpart.
/// **See [`TaskMethods`][] for the operations provided by this handle
/// type.**
///
/// [1]: Self::current
/// [2]: crate#object-safety
/// [task]: Task
/// [`TaskMethods`]: #impl-TaskMethods
#[doc = include_str!("../common.md")]
pub struct LocalTask<System: raw::KernelBase>(System::RawTaskId, PhantomData<*const ()>);

// Safety: `RawTaskId` is `Sync` by its definition
unsafe impl<System: raw::KernelBase> Sync for LocalTask<System> {}
// `impl Send for LocalTask` is left out intentionally.

unsafe impl<System: raw::KernelBase> const TaskHandle for LocalTask<System> {
    type System = System;

    #[inline]
    unsafe fn from_id(id: System::RawTaskId) -> Self {
        Self(id, PhantomData)
    }

    #[inline]
    fn id(&self) -> System::RawTaskId {
        self.0
    }

    #[inline]
    fn borrow(&self) -> TaskRef<'_, Self::System> {
        TaskRef(self.0, PhantomData)
    }
}

impl<System: raw::KernelBase, T: TaskHandle<System = System>> PartialEq<T> for LocalTask<System> {
    #[inline]
    fn eq(&self, other: &T) -> bool {
        self.0 == other.id()
    }
}

impl<System: raw::KernelBase> Eq for LocalTask<System> {}

impl<System: raw::KernelBase> hash::Hash for LocalTask<System> {
    #[inline]
    fn hash<H>(&self, state: &mut H)
    where
        H: hash::Hasher,
    {
        self.borrow().hash(state)
    }
}

impl<System: raw::KernelBase> fmt::Debug for LocalTask<System> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.borrow().fmt(f)
    }
}

impl<System: raw::KernelBase> Clone for LocalTask<System> {
    #[inline]
    fn clone(&self) -> Self {
        Self(self.0, self.1)
    }
}

impl<System: raw::KernelBase> Copy for LocalTask<System> {}

impl<System: raw::KernelBase> LocalTask<System> {
    /// Get the current task (i.e., the task that is assigned to the current
    /// processor and in the Running state).
    ///
    /// Returns [`GetCurrentTaskError::BadContext`] if called from a non-task
    /// context.
    ///
    /// <div class="admonition-follows"></div>
    ///
    /// > **Rationale:** Getting a current task in a non-task context does make
    /// > sense, but the result may be soon invalidated (potentially violating
    /// > the [object safety] of `LocalTask`) and made unreliable by various
    /// > factors.
    ///
    ///
    /// [1]: crate#object-safety
    #[inline]
    pub fn current() -> Result<Self, GetCurrentTaskError> {
        // Safety: Constructing a `LocalTask` for a current task is okay.
        //         Also, `LocalTask` cannot outlive the current thread because
        //         it's `!Send`, and consequently it cannot outlive the
        //         represented task.
        System::raw_task_current().map(|id| unsafe { Self::from_id(id) })
    }
}

/// The supported operations on [`TaskHandle`].
#[doc = include_str!("../common.md")]
pub trait TaskMethods: TaskHandle {
    /// Start the execution of the task.
    #[inline]
    fn activate(&self) -> Result<(), ActivateTaskError> {
        // Safety: `Task` represents a permission to access the
        //         referenced object.
        unsafe { <Self::System as KernelBase>::raw_task_activate(self.id()) }
    }

    /// Interrupt any ongoing wait operations undertaken by the task.
    ///
    /// This method interrupt any ongoing system call that is blocking the task.
    /// The interrupted system call will return [`WaitError::Interrupted`] or
    /// [`WaitTimeoutError::Interrupted`].
    ///
    /// [`WaitError::Interrupted`]: crate::kernel::WaitError::Interrupted
    /// [`WaitTimeoutError::Interrupted`]: crate::kernel::WaitTimeoutError::Interrupted
    #[inline]
    fn interrupt(&self) -> Result<(), InterruptTaskError> {
        // Safety: `Task` represents a permission to access the
        //         referenced object.
        unsafe { <Self::System as KernelBase>::raw_task_interrupt(self.id()) }
    }

    /// Make the task's token available, unblocking [`Kernel::park`][] now or in
    /// the future.
    ///
    /// If the token is already available, this method will return without doing
    /// anything. Use [`Self::unpark_exact`] if you need to detect this
    /// condition.
    ///
    /// If the task is currently being blocked by `Kernel::park`, the token will
    /// be immediately consumed. Otherwise, it will be consumed on a next call
    /// to `Kernel::park`.
    ///
    /// [`Kernel::park`]: crate::kernel::Kernel::park
    #[inline]
    fn unpark(&self) -> Result<(), UnparkError> {
        match self.unpark_exact() {
            Ok(()) | Err(UnparkExactError::QueueOverflow) => Ok(()),
            Err(UnparkExactError::BadContext) => Err(UnparkError::BadContext),
            Err(UnparkExactError::NoAccess) => Err(UnparkError::NoAccess),
            Err(UnparkExactError::BadObjectState) => Err(UnparkError::BadObjectState),
        }
    }

    /// Make *exactly* one new token available for the task, unblocking
    /// [`Kernel::park`] now or in the future.
    ///
    /// If the token is already available, this method will return
    /// [`UnparkExactError::QueueOverflow`]. Thus, this method will succeed
    /// only if it made *exactly* one token available.
    ///
    /// If the task is currently being blocked by `Kernel::park`, the token will
    /// be immediately consumed. Otherwise, it will be consumed on a next call
    /// to `Kernel::park`.
    ///
    /// [`Kernel::park`]: crate::kernel::Kernel::park
    #[inline]
    fn unpark_exact(&self) -> Result<(), UnparkExactError> {
        // Safety: `Task` represents a permission to access the
        //         referenced object.
        unsafe { <Self::System as KernelBase>::raw_task_unpark_exact(self.id()) }
    }

    /// Set the task's base priority.
    ///
    /// A task's base priority is used to calculate its [effective priority].
    /// Tasks with lower effective priorities execute first. The base priority
    /// is reset to the initial value specified by [`TaskDefiner::priority`]
    /// upon activation.
    ///
    /// [effective priority]: Self::effective_priority
    /// [`TaskDefiner::priority`]: crate::kernel::task::TaskDefiner::priority
    ///
    /// The value must be in range `0..`[`num_task_priority_levels`]. Otherwise,
    /// this method will return [`SetTaskPriorityError::BadParam`].
    ///
    /// The task shouldn't be in the Dormant state. Otherwise, this method will
    /// return [`SetTaskPriorityError::BadObjectState`].
    ///
    /// [`num_task_priority_levels`]: crate::kernel::Cfg::num_task_priority_levels
    #[inline]
    fn set_priority(&self, priority: usize) -> Result<(), SetTaskPriorityError>
    where
        Self::System: raw::KernelTaskSetPriority,
    {
        // Safety: `Task` represents a permission to access the
        //         referenced object.
        unsafe {
            <Self::System as raw::KernelTaskSetPriority>::raw_task_set_priority(self.id(), priority)
        }
    }

    /// Get the task's base priority.
    ///
    /// The task shouldn't be in the Dormant state. Otherwise, this method will
    /// return [`GetTaskPriorityError::BadObjectState`].
    #[inline]
    fn priority(&self) -> Result<usize, GetTaskPriorityError> {
        // Safety: `Task` represents a permission to access the
        //         referenced object.
        unsafe { <Self::System as raw::KernelBase>::raw_task_priority(self.id()) }
    }

    /// Get the task's effective priority.
    ///
    /// The effective priority is calculated based on the task's [base priority]
    /// and can be temporarily raised by a [mutex locking protocol].
    ///
    /// [base priority]: Self::priority
    /// [mutex locking protocol]: crate::kernel::MutexProtocol
    ///
    /// The task shouldn't be in the Dormant state. Otherwise, this method will
    /// return [`GetTaskPriorityError::BadObjectState`].
    #[inline]
    fn effective_priority(&self) -> Result<usize, GetTaskPriorityError> {
        // Safety: `Task` represents a permission to access the
        //         referenced object.
        unsafe { <Self::System as raw::KernelBase>::raw_task_effective_priority(self.id()) }
    }
}

impl<T: TaskHandle> TaskMethods for T {}

// ----------------------------------------------------------------------------

/// The definer (static builder) for [`TaskRef`].
#[must_use = "must call `finish()` to complete registration"]
pub struct TaskDefiner<System> {
    _phantom: PhantomInvariant<System>,
    start: Option<Closure>,
    stack_size: Option<usize>,
    priority: Option<usize>,
    active: bool,
}

impl<System: raw::KernelBase> TaskDefiner<System> {
    const fn new() -> Self {
        Self {
            _phantom: Init::INIT,
            start: None,
            stack_size: None,
            priority: None,
            active: false,
        }
    }

    /// \[**Required**\] Specify the task's entry point.
    pub const fn start<C: ~const IntoClosureConst>(self, start: C) -> Self {
        Self {
            start: Some(start.into_closure_const()),
            ..self
        }
    }

    /// Specify the task's stack size.
    pub const fn stack_size(self, stack_size: usize) -> Self {
        assert!(
            self.stack_size.is_none(),
            "the task's stack is already specified"
        );

        Self {
            stack_size: Some(stack_size),
            ..self
        }
    }

    // TODO: custom stack storage

    /// \[**Required**\] Specify the task's initial base priority. Tasks with
    /// lower priority values execute first. The value must be in range
    /// `0..`[`num_task_priority_levels`].
    ///
    /// [`num_task_priority_levels`]: crate::kernel::Cfg::num_task_priority_levels
    pub const fn priority(self, priority: usize) -> Self {
        Self {
            priority: Some(priority),
            ..self
        }
    }

    /// Specify whether the task should be activated at system startup.
    /// Defaults to `false` (don't activate).
    pub const fn active(self, active: bool) -> Self {
        Self { active, ..self }
    }

    /// Complete the definition of a task, returning a reference to the
    /// task.
    pub const fn finish<C: ~const raw_cfg::CfgTask<System = System>>(
        self,
        cfg: &mut Cfg<C>,
    ) -> StaticTask<System> {
        let id = cfg.raw().task_define(
            raw_cfg::TaskDescriptor {
                phantom: Init::INIT,
                start: self
                    .start
                    .expect("`start` (task entry point) is not specified"),
                active: self.active,
                priority: self
                    .priority
                    .expect("`priority` (task entry point) is not specified"),
                stack_size: self.stack_size,
            },
            (),
        );
        unsafe { TaskRef::from_id(id) }
    }
}

/// Specifies the [`Hunk`] to use as a task's stack when included in the task's
/// property [`Bag`].
///
/// A kernel might choose to ignore this if `StackHunk` is not supported.
///
/// If a `StackHunk` is given, the stack size ([`TaskDefiner::stack_size`]) must
/// be specified explicitly.
///
/// [`Bag`]: crate::bag::Bag
/// [`Hunk`]: crate::kernel::Hunk
pub struct StackHunk<System: cfg::KernelStatic>(super::Hunk<System>);

impl<System: cfg::KernelStatic> StackHunk<System> {
    /// Construct `StackHunk`.
    ///
    /// # Safety
    ///
    /// When activating the assocaited task, the kernel will mutably borrow
    /// the region starting at `hunk` without no borrow checking.
    pub const unsafe fn new(hunk: super::Hunk<System>) -> Self {
        Self(hunk)
    }

    /// Get the referenced [`Hunk`].
    ///
    /// [`Hunk`]: crate::kernel::Hunk
    #[inline]
    pub const fn hunk(self) -> super::Hunk<System> {
        self.0
    }
}

impl<System: cfg::KernelStatic> Clone for StackHunk<System> {
    #[inline]
    fn clone(&self) -> Self {
        Self(self.0)
    }
}

impl<System: cfg::KernelStatic> Copy for StackHunk<System> {}