Skip to main content

embassy_executor/
metadata.rs

1#[cfg(feature = "metadata-name")]
2use core::cell::Cell;
3use core::future::{Future, poll_fn};
4#[cfg(feature = "scheduler-priority")]
5use core::sync::atomic::{AtomicU8, Ordering};
6use core::task::Poll;
7
8#[cfg(feature = "metadata-name")]
9use critical_section::Mutex;
10
11#[cfg(feature = "scheduler-deadline")]
12use crate::raw::Deadline;
13use crate::raw::{self, TaskRef};
14
15/// A reference to metadata of a particular task
16pub struct MetadataRef {
17    #[allow(dead_code, reason = "only used when metadata is active")]
18    task: TaskRef,
19}
20
21impl MetadataRef {
22    /// Get a new reference to metadata of a task
23    pub const fn new(task: TaskRef) -> Self {
24        Self { task }
25    }
26
27    /// Get the metadata for the current task.
28    ///
29    /// You can use this to read or modify the current task's metadata.
30    ///
31    /// This function is `async` just to get access to the current async
32    /// context. It returns instantly, it does not block/yield.
33    pub fn for_current_task() -> impl Future<Output = Self> {
34        poll_fn(|cx| Poll::Ready(Self::new(raw::task_from_waker(cx.waker()))))
35    }
36
37    #[allow(dead_code, reason = "only used when metadata is active")]
38    fn metadata(&self) -> &Metadata {
39        &self.task.header().metadata
40    }
41
42    /// Get this task's name
43    ///
44    /// Tasks declared with `#[task]` default to their function name, or to the macro's
45    /// `name = "..."` argument. [`set_name`](Self::set_name) replaces the default.
46    ///
47    /// `None` only for tasks spawned without the macros.
48    ///
49    /// NOTE: this takes a critical section.
50    #[cfg(feature = "metadata-name")]
51    pub fn name(&self) -> Option<&'static str> {
52        self.metadata().name()
53    }
54
55    /// Set this task's name, replacing the default from `#[task]` or `#[main]`.
56    ///
57    /// NOTE: this takes a critical section.
58    #[cfg(feature = "metadata-name")]
59    pub fn set_name(&self, name: &'static str) {
60        self.metadata().set_name(name);
61        #[cfg(feature = "trace")]
62        crate::raw::trace::TraceImpl::task_name_set(self.task, name);
63    }
64
65    /// Get this task's priority.
66    #[cfg(feature = "scheduler-priority")]
67    pub fn priority(&self) -> u8 {
68        self.metadata().priority()
69    }
70
71    /// Set this task's priority.
72    #[cfg(feature = "scheduler-priority")]
73    pub fn set_priority(&self, priority: u8) {
74        self.metadata().set_priority(priority);
75        #[cfg(feature = "trace")]
76        crate::raw::trace::TraceImpl::task_priority_set(self.task, priority);
77    }
78
79    /// Get this task's deadline.
80    #[cfg(feature = "scheduler-deadline")]
81    pub fn deadline(&self) -> u64 {
82        self.metadata().deadline()
83    }
84
85    /// Set this task's deadline.
86    ///
87    /// This method does NOT check whether the deadline has already passed.
88    #[cfg(feature = "scheduler-deadline")]
89    pub fn set_deadline(&self, instant_ticks: u64) {
90        self.metadata().set_deadline(instant_ticks);
91        #[cfg(feature = "trace")]
92        crate::raw::trace::TraceImpl::task_deadline_set(self.task, instant_ticks);
93    }
94
95    /// Remove this task's deadline.
96    /// This brings it back to the default where it's not scheduled ahead of other tasks.
97    #[cfg(feature = "scheduler-deadline")]
98    pub fn unset_deadline(&self) {
99        self.set_deadline(Deadline::UNSET_TICKS);
100    }
101
102    /// Set this task's deadline `duration_ticks` in the future from when
103    /// this future is polled. This deadline is saturated to the max tick value.
104    ///
105    /// Analogous to `Timer::after`.
106    #[cfg(all(feature = "scheduler-deadline", feature = "embassy-time-driver"))]
107    pub fn set_deadline_after(&self, duration_ticks: u64) {
108        let now = embassy_time_driver::now();
109
110        // Since ticks is a u64, saturating add is PROBABLY overly cautious, leave
111        // it for now, we can probably make this wrapping_add for performance
112        // reasons later.
113        let deadline = now.saturating_add(duration_ticks);
114
115        self.set_deadline(deadline);
116    }
117
118    /// Set the this task's deadline `increment_ticks` from the previous deadline.
119    ///
120    /// This deadline is saturated to the max tick value.
121    ///
122    /// Note that by default (unless otherwise set), tasks start life with the deadline
123    /// not set, which means this method will have no effect.
124    ///
125    /// Analogous to one increment of `Ticker::every().next()`.
126    ///
127    /// Returns the deadline that was set.
128    #[cfg(feature = "scheduler-deadline")]
129    pub fn increment_deadline(&self, duration_ticks: u64) {
130        let last = self.deadline();
131
132        // Since ticks is a u64, saturating add is PROBABLY overly cautious, leave
133        // it for now, we can probably make this wrapping_add for performance
134        // reasons later.
135        let deadline = last.saturating_add(duration_ticks);
136
137        self.set_deadline(deadline);
138    }
139}
140
141/// Metadata associated with a task.
142pub(crate) struct Metadata {
143    /// The macro default or the name given to `set_name`, see [`MetadataRef::name`].
144    #[cfg(feature = "metadata-name")]
145    name: Mutex<Cell<Option<&'static str>>>,
146    #[cfg(feature = "scheduler-priority")]
147    priority: AtomicU8,
148    #[cfg(feature = "scheduler-deadline")]
149    deadline: raw::Deadline,
150}
151
152impl Metadata {
153    pub(crate) const fn new() -> Self {
154        Self {
155            #[cfg(feature = "metadata-name")]
156            name: Mutex::new(Cell::new(None)),
157            #[cfg(feature = "scheduler-priority")]
158            priority: AtomicU8::new(0),
159            // NOTE: The deadline is set to zero to allow the initializer to reside in `.bss`. This
160            // will be lazily initialized in `initialize_impl`
161            #[cfg(feature = "scheduler-deadline")]
162            deadline: raw::Deadline::new_unset(),
163        }
164    }
165
166    /// Initialize the metadata for a freshly spawned task: `name` is its default name
167    /// (see [`MetadataRef::name`]), priority and deadline start unset.
168    pub(crate) fn init(&self, name: Option<&'static str>) {
169        #[cfg(feature = "metadata-name")]
170        critical_section::with(|cs| self.name.borrow(cs).set(name));
171        #[cfg(not(feature = "metadata-name"))]
172        let _ = name;
173
174        #[cfg(feature = "scheduler-priority")]
175        self.set_priority(0);
176
177        // By default, deadlines are set to the maximum value, so that any task WITH
178        // a set deadline will ALWAYS be scheduled BEFORE a task WITHOUT a set deadline
179        #[cfg(feature = "scheduler-deadline")]
180        self.set_deadline(Deadline::UNSET_TICKS);
181    }
182
183    /// Get this task's name
184    ///
185    /// NOTE: this takes a critical section.
186    #[cfg(feature = "metadata-name")]
187    fn name(&self) -> Option<&'static str> {
188        critical_section::with(|cs| self.name.borrow(cs).get())
189    }
190
191    /// Set this task's name
192    ///
193    /// NOTE: this takes a critical section.
194    #[cfg(feature = "metadata-name")]
195    fn set_name(&self, name: &'static str) {
196        critical_section::with(|cs| self.name.borrow(cs).set(Some(name)))
197    }
198
199    /// Get this task's priority.
200    #[cfg(feature = "scheduler-priority")]
201    pub fn priority(&self) -> u8 {
202        self.priority.load(Ordering::Relaxed)
203    }
204
205    /// Set this task's priority.
206    #[cfg(feature = "scheduler-priority")]
207    fn set_priority(&self, priority: u8) {
208        self.priority.store(priority, Ordering::Relaxed)
209    }
210
211    /// Get this task's deadline.
212    #[cfg(feature = "scheduler-deadline")]
213    pub fn deadline(&self) -> u64 {
214        self.deadline.instant_ticks()
215    }
216
217    /// Set this task's deadline.
218    ///
219    /// This method does NOT check whether the deadline has already passed.
220    #[cfg(feature = "scheduler-deadline")]
221    fn set_deadline(&self, instant_ticks: u64) {
222        self.deadline.set(instant_ticks);
223    }
224}
225
226/// A unique ID for a task
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
228pub struct TaskId(pub(crate) usize);
229impl TaskId {
230    /// Get the id as a raw number
231    pub fn get(&self) -> usize {
232        self.0
233    }
234}
235
236/// A unique ID for an executor
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
238pub struct ExecutorId(pub(crate) usize);
239impl ExecutorId {
240    /// Get the id as a raw number
241    pub fn get(&self) -> usize {
242        self.0
243    }
244}