diff options
Diffstat (limited to 'embassy-executor/src')
| -rw-r--r-- | embassy-executor/src/metadata.rs | 93 | ||||
| -rw-r--r-- | embassy-executor/src/raw/deadline.rs | 44 | ||||
| -rw-r--r-- | embassy-executor/src/raw/mod.rs | 8 | ||||
| -rw-r--r-- | embassy-executor/src/raw/run_queue.rs | 213 | ||||
| -rw-r--r-- | embassy-executor/src/raw/run_queue_atomics.rs | 88 | ||||
| -rw-r--r-- | embassy-executor/src/raw/run_queue_critical_section.rs | 74 |
6 files changed, 356 insertions, 164 deletions
diff --git a/embassy-executor/src/metadata.rs b/embassy-executor/src/metadata.rs index f92c9b37c..bc0df0f83 100644 --- a/embassy-executor/src/metadata.rs +++ b/embassy-executor/src/metadata.rs | |||
| @@ -1,17 +1,25 @@ | |||
| 1 | #[cfg(feature = "metadata-name")] | 1 | #[cfg(feature = "metadata-name")] |
| 2 | use core::cell::Cell; | 2 | use core::cell::Cell; |
| 3 | use core::future::{poll_fn, Future}; | 3 | use core::future::{poll_fn, Future}; |
| 4 | #[cfg(feature = "scheduler-priority")] | ||
| 5 | use core::sync::atomic::{AtomicU8, Ordering}; | ||
| 4 | use core::task::Poll; | 6 | use core::task::Poll; |
| 5 | 7 | ||
| 6 | #[cfg(feature = "metadata-name")] | 8 | #[cfg(feature = "metadata-name")] |
| 7 | use critical_section::Mutex; | 9 | use critical_section::Mutex; |
| 8 | 10 | ||
| 9 | use crate::raw; | 11 | use crate::raw; |
| 12 | #[cfg(feature = "scheduler-deadline")] | ||
| 13 | use crate::raw::Deadline; | ||
| 10 | 14 | ||
| 11 | /// Metadata associated with a task. | 15 | /// Metadata associated with a task. |
| 12 | pub struct Metadata { | 16 | pub struct Metadata { |
| 13 | #[cfg(feature = "metadata-name")] | 17 | #[cfg(feature = "metadata-name")] |
| 14 | name: Mutex<Cell<Option<&'static str>>>, | 18 | name: Mutex<Cell<Option<&'static str>>>, |
| 19 | #[cfg(feature = "scheduler-priority")] | ||
| 20 | priority: AtomicU8, | ||
| 21 | #[cfg(feature = "scheduler-deadline")] | ||
| 22 | deadline: raw::Deadline, | ||
| 15 | } | 23 | } |
| 16 | 24 | ||
| 17 | impl Metadata { | 25 | impl Metadata { |
| @@ -19,12 +27,26 @@ impl Metadata { | |||
| 19 | Self { | 27 | Self { |
| 20 | #[cfg(feature = "metadata-name")] | 28 | #[cfg(feature = "metadata-name")] |
| 21 | name: Mutex::new(Cell::new(None)), | 29 | name: Mutex::new(Cell::new(None)), |
| 30 | #[cfg(feature = "scheduler-priority")] | ||
| 31 | priority: AtomicU8::new(0), | ||
| 32 | // NOTE: The deadline is set to zero to allow the initializer to reside in `.bss`. This | ||
| 33 | // will be lazily initalized in `initialize_impl` | ||
| 34 | #[cfg(feature = "scheduler-deadline")] | ||
| 35 | deadline: raw::Deadline::new_unset(), | ||
| 22 | } | 36 | } |
| 23 | } | 37 | } |
| 24 | 38 | ||
| 25 | pub(crate) fn reset(&self) { | 39 | pub(crate) fn reset(&self) { |
| 26 | #[cfg(feature = "metadata-name")] | 40 | #[cfg(feature = "metadata-name")] |
| 27 | critical_section::with(|cs| self.name.borrow(cs).set(None)); | 41 | critical_section::with(|cs| self.name.borrow(cs).set(None)); |
| 42 | |||
| 43 | #[cfg(feature = "scheduler-priority")] | ||
| 44 | self.set_priority(0); | ||
| 45 | |||
| 46 | // By default, deadlines are set to the maximum value, so that any task WITH | ||
| 47 | // a set deadline will ALWAYS be scheduled BEFORE a task WITHOUT a set deadline | ||
| 48 | #[cfg(feature = "scheduler-deadline")] | ||
| 49 | self.unset_deadline(); | ||
| 28 | } | 50 | } |
| 29 | 51 | ||
| 30 | /// Get the metadata for the current task. | 52 | /// Get the metadata for the current task. |
| @@ -52,4 +74,75 @@ impl Metadata { | |||
| 52 | pub fn set_name(&self, name: &'static str) { | 74 | pub fn set_name(&self, name: &'static str) { |
| 53 | critical_section::with(|cs| self.name.borrow(cs).set(Some(name))) | 75 | critical_section::with(|cs| self.name.borrow(cs).set(Some(name))) |
| 54 | } | 76 | } |
| 77 | |||
| 78 | /// Get this task's priority. | ||
| 79 | #[cfg(feature = "scheduler-priority")] | ||
| 80 | pub fn priority(&self) -> u8 { | ||
| 81 | self.priority.load(Ordering::Relaxed) | ||
| 82 | } | ||
| 83 | |||
| 84 | /// Set this task's priority. | ||
| 85 | #[cfg(feature = "scheduler-priority")] | ||
| 86 | pub fn set_priority(&self, priority: u8) { | ||
| 87 | self.priority.store(priority, Ordering::Relaxed) | ||
| 88 | } | ||
| 89 | |||
| 90 | /// Get this task's deadline. | ||
| 91 | #[cfg(feature = "scheduler-deadline")] | ||
| 92 | pub fn deadline(&self) -> u64 { | ||
| 93 | self.deadline.instant_ticks() | ||
| 94 | } | ||
| 95 | |||
| 96 | /// Set this task's deadline. | ||
| 97 | /// | ||
| 98 | /// This method does NOT check whether the deadline has already passed. | ||
| 99 | #[cfg(feature = "scheduler-deadline")] | ||
| 100 | pub fn set_deadline(&self, instant_ticks: u64) { | ||
| 101 | self.deadline.set(instant_ticks); | ||
| 102 | } | ||
| 103 | |||
| 104 | /// Remove this task's deadline. | ||
| 105 | /// This brings it back to the defaul where it's not scheduled ahead of other tasks. | ||
| 106 | #[cfg(feature = "scheduler-deadline")] | ||
| 107 | pub fn unset_deadline(&self) { | ||
| 108 | self.deadline.set(Deadline::UNSET_TICKS); | ||
| 109 | } | ||
| 110 | |||
| 111 | /// Set this task's deadline `duration_ticks` in the future from when | ||
| 112 | /// this future is polled. This deadline is saturated to the max tick value. | ||
| 113 | /// | ||
| 114 | /// Analogous to `Timer::after`. | ||
| 115 | #[cfg(all(feature = "scheduler-deadline", feature = "embassy-time-driver"))] | ||
| 116 | pub fn set_deadline_after(&self, duration_ticks: u64) { | ||
| 117 | let now = embassy_time_driver::now(); | ||
| 118 | |||
| 119 | // Since ticks is a u64, saturating add is PROBABLY overly cautious, leave | ||
| 120 | // it for now, we can probably make this wrapping_add for performance | ||
| 121 | // reasons later. | ||
| 122 | let deadline = now.saturating_add(duration_ticks); | ||
| 123 | |||
| 124 | self.set_deadline(deadline); | ||
| 125 | } | ||
| 126 | |||
| 127 | /// Set the this task's deadline `increment_ticks` from the previous deadline. | ||
| 128 | /// | ||
| 129 | /// This deadline is saturated to the max tick value. | ||
| 130 | /// | ||
| 131 | /// Note that by default (unless otherwise set), tasks start life with the deadline | ||
| 132 | /// not set, which means this method will have no effect. | ||
| 133 | /// | ||
| 134 | /// Analogous to one increment of `Ticker::every().next()`. | ||
| 135 | /// | ||
| 136 | /// Returns the deadline that was set. | ||
| 137 | #[cfg(feature = "scheduler-deadline")] | ||
| 138 | pub fn increment_deadline(&self, duration_ticks: u64) { | ||
| 139 | let last = self.deadline(); | ||
| 140 | |||
| 141 | // Since ticks is a u64, saturating add is PROBABLY overly cautious, leave | ||
| 142 | // it for now, we can probably make this wrapping_add for performance | ||
| 143 | // reasons later. | ||
| 144 | let deadline = last.saturating_add(duration_ticks); | ||
| 145 | |||
| 146 | self.set_deadline(deadline); | ||
| 147 | } | ||
| 55 | } | 148 | } |
diff --git a/embassy-executor/src/raw/deadline.rs b/embassy-executor/src/raw/deadline.rs new file mode 100644 index 000000000..cc89fadb0 --- /dev/null +++ b/embassy-executor/src/raw/deadline.rs | |||
| @@ -0,0 +1,44 @@ | |||
| 1 | use core::sync::atomic::{AtomicU32, Ordering}; | ||
| 2 | |||
| 3 | /// A type for interacting with the deadline of the current task | ||
| 4 | /// | ||
| 5 | /// Requires the `scheduler-deadline` feature. | ||
| 6 | /// | ||
| 7 | /// Note: Interacting with the deadline should be done locally in a task. | ||
| 8 | /// In theory you could try to set or read the deadline from another task, | ||
| 9 | /// but that will result in weird (though not unsound) behavior. | ||
| 10 | pub(crate) struct Deadline { | ||
| 11 | instant_ticks_hi: AtomicU32, | ||
| 12 | instant_ticks_lo: AtomicU32, | ||
| 13 | } | ||
| 14 | |||
| 15 | impl Deadline { | ||
| 16 | pub(crate) const fn new(instant_ticks: u64) -> Self { | ||
| 17 | Self { | ||
| 18 | instant_ticks_hi: AtomicU32::new((instant_ticks >> 32) as u32), | ||
| 19 | instant_ticks_lo: AtomicU32::new(instant_ticks as u32), | ||
| 20 | } | ||
| 21 | } | ||
| 22 | |||
| 23 | pub(crate) const fn new_unset() -> Self { | ||
| 24 | Self::new(Self::UNSET_TICKS) | ||
| 25 | } | ||
| 26 | |||
| 27 | pub(crate) fn set(&self, instant_ticks: u64) { | ||
| 28 | self.instant_ticks_hi | ||
| 29 | .store((instant_ticks >> 32) as u32, Ordering::Relaxed); | ||
| 30 | self.instant_ticks_lo.store(instant_ticks as u32, Ordering::Relaxed); | ||
| 31 | } | ||
| 32 | |||
| 33 | /// Deadline value in ticks, same time base and ticks as `embassy-time` | ||
| 34 | pub(crate) fn instant_ticks(&self) -> u64 { | ||
| 35 | let hi = self.instant_ticks_hi.load(Ordering::Relaxed) as u64; | ||
| 36 | let lo = self.instant_ticks_lo.load(Ordering::Relaxed) as u64; | ||
| 37 | |||
| 38 | (hi << 32) | lo | ||
| 39 | } | ||
| 40 | |||
| 41 | /// Sentinel value representing an "unset" deadline, which has lower priority | ||
| 42 | /// than any other set deadline value | ||
| 43 | pub(crate) const UNSET_TICKS: u64 = u64::MAX; | ||
| 44 | } | ||
diff --git a/embassy-executor/src/raw/mod.rs b/embassy-executor/src/raw/mod.rs index 4280c5750..9f36c60bc 100644 --- a/embassy-executor/src/raw/mod.rs +++ b/embassy-executor/src/raw/mod.rs | |||
| @@ -7,8 +7,6 @@ | |||
| 7 | //! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe | 7 | //! Using this module requires respecting subtle safety contracts. If you can, prefer using the safe |
| 8 | //! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_executor_macros::task) macro, which are fully safe. | 8 | //! [executor wrappers](crate::Executor) and the [`embassy_executor::task`](embassy_executor_macros::task) macro, which are fully safe. |
| 9 | 9 | ||
| 10 | #[cfg_attr(target_has_atomic = "ptr", path = "run_queue_atomics.rs")] | ||
| 11 | #[cfg_attr(not(target_has_atomic = "ptr"), path = "run_queue_critical_section.rs")] | ||
| 12 | mod run_queue; | 10 | mod run_queue; |
| 13 | 11 | ||
| 14 | #[cfg_attr(all(cortex_m, target_has_atomic = "32"), path = "state_atomics_arm.rs")] | 12 | #[cfg_attr(all(cortex_m, target_has_atomic = "32"), path = "state_atomics_arm.rs")] |
| @@ -28,6 +26,9 @@ pub(crate) mod util; | |||
| 28 | #[cfg_attr(feature = "turbowakers", path = "waker_turbo.rs")] | 26 | #[cfg_attr(feature = "turbowakers", path = "waker_turbo.rs")] |
| 29 | mod waker; | 27 | mod waker; |
| 30 | 28 | ||
| 29 | #[cfg(feature = "scheduler-deadline")] | ||
| 30 | mod deadline; | ||
| 31 | |||
| 31 | use core::future::Future; | 32 | use core::future::Future; |
| 32 | use core::marker::PhantomData; | 33 | use core::marker::PhantomData; |
| 33 | use core::mem; | 34 | use core::mem; |
| @@ -38,6 +39,8 @@ use core::sync::atomic::AtomicPtr; | |||
| 38 | use core::sync::atomic::Ordering; | 39 | use core::sync::atomic::Ordering; |
| 39 | use core::task::{Context, Poll, Waker}; | 40 | use core::task::{Context, Poll, Waker}; |
| 40 | 41 | ||
| 42 | #[cfg(feature = "scheduler-deadline")] | ||
| 43 | pub(crate) use deadline::Deadline; | ||
| 41 | use embassy_executor_timer_queue::TimerQueueItem; | 44 | use embassy_executor_timer_queue::TimerQueueItem; |
| 42 | #[cfg(feature = "arch-avr")] | 45 | #[cfg(feature = "arch-avr")] |
| 43 | use portable_atomic::AtomicPtr; | 46 | use portable_atomic::AtomicPtr; |
| @@ -96,6 +99,7 @@ extern "Rust" fn __embassy_time_queue_item_from_waker(waker: &Waker) -> &'static | |||
| 96 | pub(crate) struct TaskHeader { | 99 | pub(crate) struct TaskHeader { |
| 97 | pub(crate) state: State, | 100 | pub(crate) state: State, |
| 98 | pub(crate) run_queue_item: RunQueueItem, | 101 | pub(crate) run_queue_item: RunQueueItem, |
| 102 | |||
| 99 | pub(crate) executor: AtomicPtr<SyncExecutor>, | 103 | pub(crate) executor: AtomicPtr<SyncExecutor>, |
| 100 | poll_fn: SyncUnsafeCell<Option<unsafe fn(TaskRef)>>, | 104 | poll_fn: SyncUnsafeCell<Option<unsafe fn(TaskRef)>>, |
| 101 | 105 | ||
diff --git a/embassy-executor/src/raw/run_queue.rs b/embassy-executor/src/raw/run_queue.rs new file mode 100644 index 000000000..b8b052310 --- /dev/null +++ b/embassy-executor/src/raw/run_queue.rs | |||
| @@ -0,0 +1,213 @@ | |||
| 1 | use core::ptr::{addr_of_mut, NonNull}; | ||
| 2 | |||
| 3 | use cordyceps::sorted_list::Links; | ||
| 4 | use cordyceps::Linked; | ||
| 5 | #[cfg(any(feature = "scheduler-priority", feature = "scheduler-deadline"))] | ||
| 6 | use cordyceps::SortedList; | ||
| 7 | |||
| 8 | #[cfg(target_has_atomic = "ptr")] | ||
| 9 | type TransferStack<T> = cordyceps::TransferStack<T>; | ||
| 10 | |||
| 11 | #[cfg(not(target_has_atomic = "ptr"))] | ||
| 12 | type TransferStack<T> = MutexTransferStack<T>; | ||
| 13 | |||
| 14 | use super::{TaskHeader, TaskRef}; | ||
| 15 | |||
| 16 | /// Use `cordyceps::sorted_list::Links` as the singly linked list | ||
| 17 | /// for RunQueueItems. | ||
| 18 | pub(crate) type RunQueueItem = Links<TaskHeader>; | ||
| 19 | |||
| 20 | /// Implements the `Linked` trait, allowing for singly linked list usage | ||
| 21 | /// of any of cordyceps' `TransferStack` (used for the atomic runqueue), | ||
| 22 | /// `SortedList` (used with the DRS scheduler), or `Stack`, which is | ||
| 23 | /// popped atomically from the `TransferStack`. | ||
| 24 | unsafe impl Linked<Links<TaskHeader>> for TaskHeader { | ||
| 25 | type Handle = TaskRef; | ||
| 26 | |||
| 27 | // Convert a TaskRef into a TaskHeader ptr | ||
| 28 | fn into_ptr(r: TaskRef) -> NonNull<TaskHeader> { | ||
| 29 | r.ptr | ||
| 30 | } | ||
| 31 | |||
| 32 | // Convert a TaskHeader into a TaskRef | ||
| 33 | unsafe fn from_ptr(ptr: NonNull<TaskHeader>) -> TaskRef { | ||
| 34 | TaskRef { ptr } | ||
| 35 | } | ||
| 36 | |||
| 37 | // Given a pointer to a TaskHeader, obtain a pointer to the Links structure, | ||
| 38 | // which can be used to traverse to other TaskHeader nodes in the linked list | ||
| 39 | unsafe fn links(ptr: NonNull<TaskHeader>) -> NonNull<Links<TaskHeader>> { | ||
| 40 | let ptr: *mut TaskHeader = ptr.as_ptr(); | ||
| 41 | NonNull::new_unchecked(addr_of_mut!((*ptr).run_queue_item)) | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | /// Atomic task queue using a very, very simple lock-free linked-list queue: | ||
| 46 | /// | ||
| 47 | /// To enqueue a task, task.next is set to the old head, and head is atomically set to task. | ||
| 48 | /// | ||
| 49 | /// Dequeuing is done in batches: the queue is emptied by atomically replacing head with | ||
| 50 | /// null. Then the batch is iterated following the next pointers until null is reached. | ||
| 51 | /// | ||
| 52 | /// Note that batches will be iterated in the reverse order as they were enqueued. This is OK | ||
| 53 | /// for our purposes: it can't create fairness problems since the next batch won't run until the | ||
| 54 | /// current batch is completely processed, so even if a task enqueues itself instantly (for example | ||
| 55 | /// by waking its own waker) can't prevent other tasks from running. | ||
| 56 | pub(crate) struct RunQueue { | ||
| 57 | stack: TransferStack<TaskHeader>, | ||
| 58 | } | ||
| 59 | |||
| 60 | impl RunQueue { | ||
| 61 | pub const fn new() -> Self { | ||
| 62 | Self { | ||
| 63 | stack: TransferStack::new(), | ||
| 64 | } | ||
| 65 | } | ||
| 66 | |||
| 67 | /// Enqueues an item. Returns true if the queue was empty. | ||
| 68 | /// | ||
| 69 | /// # Safety | ||
| 70 | /// | ||
| 71 | /// `item` must NOT be already enqueued in any queue. | ||
| 72 | #[inline(always)] | ||
| 73 | pub(crate) unsafe fn enqueue(&self, task: TaskRef, _tok: super::state::Token) -> bool { | ||
| 74 | self.stack.push_was_empty( | ||
| 75 | task, | ||
| 76 | #[cfg(not(target_has_atomic = "ptr"))] | ||
| 77 | _tok, | ||
| 78 | ) | ||
| 79 | } | ||
| 80 | |||
| 81 | /// # Standard atomic runqueue | ||
| 82 | /// | ||
| 83 | /// Empty the queue, then call `on_task` for each task that was in the queue. | ||
| 84 | /// NOTE: It is OK for `on_task` to enqueue more tasks. In this case they're left in the queue | ||
| 85 | /// and will be processed by the *next* call to `dequeue_all`, *not* the current one. | ||
| 86 | #[cfg(not(any(feature = "scheduler-priority", feature = "scheduler-deadline")))] | ||
| 87 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | ||
| 88 | let taken = self.stack.take_all(); | ||
| 89 | for taskref in taken { | ||
| 90 | run_dequeue(&taskref); | ||
| 91 | on_task(taskref); | ||
| 92 | } | ||
| 93 | } | ||
| 94 | |||
| 95 | /// # Earliest Deadline First Scheduler | ||
| 96 | /// | ||
| 97 | /// This algorithm will loop until all enqueued tasks are processed. | ||
| 98 | /// | ||
| 99 | /// Before polling a task, all currently enqueued tasks will be popped from the | ||
| 100 | /// runqueue, and will be added to the working `sorted` list, a linked-list that | ||
| 101 | /// sorts tasks by their deadline, with nearest deadline items in the front, and | ||
| 102 | /// furthest deadline items in the back. | ||
| 103 | /// | ||
| 104 | /// After popping and sorting all pending tasks, the SOONEST task will be popped | ||
| 105 | /// from the front of the queue, and polled by calling `on_task` on it. | ||
| 106 | /// | ||
| 107 | /// This process will repeat until the local `sorted` queue AND the global | ||
| 108 | /// runqueue are both empty, at which point this function will return. | ||
| 109 | #[cfg(any(feature = "scheduler-priority", feature = "scheduler-deadline"))] | ||
| 110 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | ||
| 111 | let mut sorted = SortedList::<TaskHeader>::new_with_cmp(|lhs, rhs| { | ||
| 112 | // compare by priority first | ||
| 113 | #[cfg(feature = "scheduler-priority")] | ||
| 114 | { | ||
| 115 | let lp = lhs.metadata.priority(); | ||
| 116 | let rp = rhs.metadata.priority(); | ||
| 117 | if lp != rp { | ||
| 118 | return lp.cmp(&rp).reverse(); | ||
| 119 | } | ||
| 120 | } | ||
| 121 | // compare deadlines in case of tie. | ||
| 122 | #[cfg(feature = "scheduler-deadline")] | ||
| 123 | { | ||
| 124 | let ld = lhs.metadata.deadline(); | ||
| 125 | let rd = rhs.metadata.deadline(); | ||
| 126 | if ld != rd { | ||
| 127 | return ld.cmp(&rd); | ||
| 128 | } | ||
| 129 | } | ||
| 130 | core::cmp::Ordering::Equal | ||
| 131 | }); | ||
| 132 | |||
| 133 | loop { | ||
| 134 | // For each loop, grab any newly pended items | ||
| 135 | let taken = self.stack.take_all(); | ||
| 136 | |||
| 137 | // Sort these into the list - this is potentially expensive! We do an | ||
| 138 | // insertion sort of new items, which iterates the linked list. | ||
| 139 | // | ||
| 140 | // Something on the order of `O(n * m)`, where `n` is the number | ||
| 141 | // of new tasks, and `m` is the number of already pending tasks. | ||
| 142 | sorted.extend(taken); | ||
| 143 | |||
| 144 | // Pop the task with the SOONEST deadline. If there are no tasks | ||
| 145 | // pending, then we are done. | ||
| 146 | let Some(taskref) = sorted.pop_front() else { | ||
| 147 | return; | ||
| 148 | }; | ||
| 149 | |||
| 150 | // We got one task, mark it as dequeued, and process the task. | ||
| 151 | run_dequeue(&taskref); | ||
| 152 | on_task(taskref); | ||
| 153 | } | ||
| 154 | } | ||
| 155 | } | ||
| 156 | |||
| 157 | /// atomic state does not require a cs... | ||
| 158 | #[cfg(target_has_atomic = "ptr")] | ||
| 159 | #[inline(always)] | ||
| 160 | fn run_dequeue(taskref: &TaskRef) { | ||
| 161 | taskref.header().state.run_dequeue(); | ||
| 162 | } | ||
| 163 | |||
| 164 | /// ...while non-atomic state does | ||
| 165 | #[cfg(not(target_has_atomic = "ptr"))] | ||
| 166 | #[inline(always)] | ||
| 167 | fn run_dequeue(taskref: &TaskRef) { | ||
| 168 | critical_section::with(|cs| { | ||
| 169 | taskref.header().state.run_dequeue(cs); | ||
| 170 | }) | ||
| 171 | } | ||
| 172 | |||
| 173 | /// A wrapper type that acts like TransferStack by wrapping a normal Stack in a CS mutex | ||
| 174 | #[cfg(not(target_has_atomic = "ptr"))] | ||
| 175 | struct MutexTransferStack<T: Linked<cordyceps::stack::Links<T>>> { | ||
| 176 | inner: critical_section::Mutex<core::cell::UnsafeCell<cordyceps::Stack<T>>>, | ||
| 177 | } | ||
| 178 | |||
| 179 | #[cfg(not(target_has_atomic = "ptr"))] | ||
| 180 | impl<T: Linked<cordyceps::stack::Links<T>>> MutexTransferStack<T> { | ||
| 181 | const fn new() -> Self { | ||
| 182 | Self { | ||
| 183 | inner: critical_section::Mutex::new(core::cell::UnsafeCell::new(cordyceps::Stack::new())), | ||
| 184 | } | ||
| 185 | } | ||
| 186 | |||
| 187 | /// Push an item to the transfer stack, returning whether the stack was previously empty | ||
| 188 | fn push_was_empty(&self, item: T::Handle, token: super::state::Token) -> bool { | ||
| 189 | // SAFETY: The critical-section mutex guarantees that there is no *concurrent* access | ||
| 190 | // for the lifetime of the token, but does NOT protect against re-entrant access. | ||
| 191 | // However, we never *return* the reference, nor do we recurse (or call another method | ||
| 192 | // like `take_all`) that could ever allow for re-entrant aliasing. Therefore, the | ||
| 193 | // presence of the critical section is sufficient to guarantee exclusive access to | ||
| 194 | // the `inner` field for the purposes of this function. | ||
| 195 | let inner = unsafe { &mut *self.inner.borrow(token).get() }; | ||
| 196 | let is_empty = inner.is_empty(); | ||
| 197 | inner.push(item); | ||
| 198 | is_empty | ||
| 199 | } | ||
| 200 | |||
| 201 | fn take_all(&self) -> cordyceps::Stack<T> { | ||
| 202 | critical_section::with(|cs| { | ||
| 203 | // SAFETY: The critical-section mutex guarantees that there is no *concurrent* access | ||
| 204 | // for the lifetime of the token, but does NOT protect against re-entrant access. | ||
| 205 | // However, we never *return* the reference, nor do we recurse (or call another method | ||
| 206 | // like `push_was_empty`) that could ever allow for re-entrant aliasing. Therefore, the | ||
| 207 | // presence of the critical section is sufficient to guarantee exclusive access to | ||
| 208 | // the `inner` field for the purposes of this function. | ||
| 209 | let inner = unsafe { &mut *self.inner.borrow(cs).get() }; | ||
| 210 | inner.take_all() | ||
| 211 | }) | ||
| 212 | } | ||
| 213 | } | ||
diff --git a/embassy-executor/src/raw/run_queue_atomics.rs b/embassy-executor/src/raw/run_queue_atomics.rs deleted file mode 100644 index ce511d79a..000000000 --- a/embassy-executor/src/raw/run_queue_atomics.rs +++ /dev/null | |||
| @@ -1,88 +0,0 @@ | |||
| 1 | use core::ptr; | ||
| 2 | use core::ptr::NonNull; | ||
| 3 | use core::sync::atomic::{AtomicPtr, Ordering}; | ||
| 4 | |||
| 5 | use super::{TaskHeader, TaskRef}; | ||
| 6 | use crate::raw::util::SyncUnsafeCell; | ||
| 7 | |||
| 8 | pub(crate) struct RunQueueItem { | ||
| 9 | next: SyncUnsafeCell<Option<TaskRef>>, | ||
| 10 | } | ||
| 11 | |||
| 12 | impl RunQueueItem { | ||
| 13 | pub const fn new() -> Self { | ||
| 14 | Self { | ||
| 15 | next: SyncUnsafeCell::new(None), | ||
| 16 | } | ||
| 17 | } | ||
| 18 | } | ||
| 19 | |||
| 20 | /// Atomic task queue using a very, very simple lock-free linked-list queue: | ||
| 21 | /// | ||
| 22 | /// To enqueue a task, task.next is set to the old head, and head is atomically set to task. | ||
| 23 | /// | ||
| 24 | /// Dequeuing is done in batches: the queue is emptied by atomically replacing head with | ||
| 25 | /// null. Then the batch is iterated following the next pointers until null is reached. | ||
| 26 | /// | ||
| 27 | /// Note that batches will be iterated in the reverse order as they were enqueued. This is OK | ||
| 28 | /// for our purposes: it can't create fairness problems since the next batch won't run until the | ||
| 29 | /// current batch is completely processed, so even if a task enqueues itself instantly (for example | ||
| 30 | /// by waking its own waker) can't prevent other tasks from running. | ||
| 31 | pub(crate) struct RunQueue { | ||
| 32 | head: AtomicPtr<TaskHeader>, | ||
| 33 | } | ||
| 34 | |||
| 35 | impl RunQueue { | ||
| 36 | pub const fn new() -> Self { | ||
| 37 | Self { | ||
| 38 | head: AtomicPtr::new(ptr::null_mut()), | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | /// Enqueues an item. Returns true if the queue was empty. | ||
| 43 | /// | ||
| 44 | /// # Safety | ||
| 45 | /// | ||
| 46 | /// `item` must NOT be already enqueued in any queue. | ||
| 47 | #[inline(always)] | ||
| 48 | pub(crate) unsafe fn enqueue(&self, task: TaskRef, _: super::state::Token) -> bool { | ||
| 49 | let mut was_empty = false; | ||
| 50 | |||
| 51 | self.head | ||
| 52 | .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |prev| { | ||
| 53 | was_empty = prev.is_null(); | ||
| 54 | unsafe { | ||
| 55 | // safety: the pointer is either null or valid | ||
| 56 | let prev = NonNull::new(prev).map(|ptr| TaskRef::from_ptr(ptr.as_ptr())); | ||
| 57 | // safety: there are no concurrent accesses to `next` | ||
| 58 | task.header().run_queue_item.next.set(prev); | ||
| 59 | } | ||
| 60 | Some(task.as_ptr() as *mut _) | ||
| 61 | }) | ||
| 62 | .ok(); | ||
| 63 | |||
| 64 | was_empty | ||
| 65 | } | ||
| 66 | |||
| 67 | /// Empty the queue, then call `on_task` for each task that was in the queue. | ||
| 68 | /// NOTE: It is OK for `on_task` to enqueue more tasks. In this case they're left in the queue | ||
| 69 | /// and will be processed by the *next* call to `dequeue_all`, *not* the current one. | ||
| 70 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | ||
| 71 | // Atomically empty the queue. | ||
| 72 | let ptr = self.head.swap(ptr::null_mut(), Ordering::AcqRel); | ||
| 73 | |||
| 74 | // safety: the pointer is either null or valid | ||
| 75 | let mut next = unsafe { NonNull::new(ptr).map(|ptr| TaskRef::from_ptr(ptr.as_ptr())) }; | ||
| 76 | |||
| 77 | // Iterate the linked list of tasks that were previously in the queue. | ||
| 78 | while let Some(task) = next { | ||
| 79 | // If the task re-enqueues itself, the `next` pointer will get overwritten. | ||
| 80 | // Therefore, first read the next pointer, and only then process the task. | ||
| 81 | // safety: there are no concurrent accesses to `next` | ||
| 82 | next = unsafe { task.header().run_queue_item.next.get() }; | ||
| 83 | |||
| 84 | task.header().state.run_dequeue(); | ||
| 85 | on_task(task); | ||
| 86 | } | ||
| 87 | } | ||
| 88 | } | ||
diff --git a/embassy-executor/src/raw/run_queue_critical_section.rs b/embassy-executor/src/raw/run_queue_critical_section.rs deleted file mode 100644 index 86c4085ed..000000000 --- a/embassy-executor/src/raw/run_queue_critical_section.rs +++ /dev/null | |||
| @@ -1,74 +0,0 @@ | |||
| 1 | use core::cell::Cell; | ||
| 2 | |||
| 3 | use critical_section::{CriticalSection, Mutex}; | ||
| 4 | |||
| 5 | use super::TaskRef; | ||
| 6 | |||
| 7 | pub(crate) struct RunQueueItem { | ||
| 8 | next: Mutex<Cell<Option<TaskRef>>>, | ||
| 9 | } | ||
| 10 | |||
| 11 | impl RunQueueItem { | ||
| 12 | pub const fn new() -> Self { | ||
| 13 | Self { | ||
| 14 | next: Mutex::new(Cell::new(None)), | ||
| 15 | } | ||
| 16 | } | ||
| 17 | } | ||
| 18 | |||
| 19 | /// Atomic task queue using a very, very simple lock-free linked-list queue: | ||
| 20 | /// | ||
| 21 | /// To enqueue a task, task.next is set to the old head, and head is atomically set to task. | ||
| 22 | /// | ||
| 23 | /// Dequeuing is done in batches: the queue is emptied by atomically replacing head with | ||
| 24 | /// null. Then the batch is iterated following the next pointers until null is reached. | ||
| 25 | /// | ||
| 26 | /// Note that batches will be iterated in the reverse order as they were enqueued. This is OK | ||
| 27 | /// for our purposes: it can't create fairness problems since the next batch won't run until the | ||
| 28 | /// current batch is completely processed, so even if a task enqueues itself instantly (for example | ||
| 29 | /// by waking its own waker) can't prevent other tasks from running. | ||
| 30 | pub(crate) struct RunQueue { | ||
| 31 | head: Mutex<Cell<Option<TaskRef>>>, | ||
| 32 | } | ||
| 33 | |||
| 34 | impl RunQueue { | ||
| 35 | pub const fn new() -> Self { | ||
| 36 | Self { | ||
| 37 | head: Mutex::new(Cell::new(None)), | ||
| 38 | } | ||
| 39 | } | ||
| 40 | |||
| 41 | /// Enqueues an item. Returns true if the queue was empty. | ||
| 42 | /// | ||
| 43 | /// # Safety | ||
| 44 | /// | ||
| 45 | /// `item` must NOT be already enqueued in any queue. | ||
| 46 | #[inline(always)] | ||
| 47 | pub(crate) unsafe fn enqueue(&self, task: TaskRef, cs: CriticalSection<'_>) -> bool { | ||
| 48 | let prev = self.head.borrow(cs).replace(Some(task)); | ||
| 49 | task.header().run_queue_item.next.borrow(cs).set(prev); | ||
| 50 | |||
| 51 | prev.is_none() | ||
| 52 | } | ||
| 53 | |||
| 54 | /// Empty the queue, then call `on_task` for each task that was in the queue. | ||
| 55 | /// NOTE: It is OK for `on_task` to enqueue more tasks. In this case they're left in the queue | ||
| 56 | /// and will be processed by the *next* call to `dequeue_all`, *not* the current one. | ||
| 57 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | ||
| 58 | // Atomically empty the queue. | ||
| 59 | let mut next = critical_section::with(|cs| self.head.borrow(cs).take()); | ||
| 60 | |||
| 61 | // Iterate the linked list of tasks that were previously in the queue. | ||
| 62 | while let Some(task) = next { | ||
| 63 | // If the task re-enqueues itself, the `next` pointer will get overwritten. | ||
| 64 | // Therefore, first read the next pointer, and only then process the task. | ||
| 65 | |||
| 66 | critical_section::with(|cs| { | ||
| 67 | next = task.header().run_queue_item.next.borrow(cs).get(); | ||
| 68 | task.header().state.run_dequeue(cs); | ||
| 69 | }); | ||
| 70 | |||
| 71 | on_task(task); | ||
| 72 | } | ||
| 73 | } | ||
| 74 | } | ||
