diff options
| author | James Munns <[email protected]> | 2025-04-01 18:50:12 +0200 |
|---|---|---|
| committer | Dario Nieuwenhuis <[email protected]> | 2025-09-11 14:45:06 +0200 |
| commit | ba0426f767bb602750bed4fae87a156b661c0e92 (patch) | |
| tree | d813feec4d54039e0f5a2c82c18b499c38326f06 /embassy-executor/src/raw | |
| parent | 8c70aafd4be63ff7af895f116444fb81438ae6e0 (diff) | |
Combine DRS and non-DRS atomic scheduler, using cordyceps
Diffstat (limited to 'embassy-executor/src/raw')
| -rw-r--r-- | embassy-executor/src/raw/deadline.rs (renamed from embassy-executor/src/raw/run_queue_drs_atomics.rs) | 102 | ||||
| -rw-r--r-- | embassy-executor/src/raw/mod.rs | 18 | ||||
| -rw-r--r-- | embassy-executor/src/raw/run_queue_atomics.rs | 110 |
3 files changed, 80 insertions, 150 deletions
diff --git a/embassy-executor/src/raw/run_queue_drs_atomics.rs b/embassy-executor/src/raw/deadline.rs index 047265954..3f60936cc 100644 --- a/embassy-executor/src/raw/run_queue_drs_atomics.rs +++ b/embassy-executor/src/raw/deadline.rs | |||
| @@ -1,97 +1,5 @@ | |||
| 1 | use super::{TaskHeader, TaskRef}; | 1 | use core::future::{poll_fn, Future}; |
| 2 | use cordyceps::{SortedList, TransferStack}; | ||
| 3 | use core::future::{Future, poll_fn}; | ||
| 4 | use core::task::Poll; | 2 | use core::task::Poll; |
| 5 | use core::ptr::{addr_of_mut, NonNull}; | ||
| 6 | use cordyceps::sorted_list::Links; | ||
| 7 | use cordyceps::Linked; | ||
| 8 | |||
| 9 | pub(crate) type RunQueueItem = Links<TaskHeader>; | ||
| 10 | |||
| 11 | unsafe impl Linked<Links<TaskHeader>> for super::TaskHeader { | ||
| 12 | type Handle = TaskRef; | ||
| 13 | |||
| 14 | fn into_ptr(r: Self::Handle) -> NonNull<Self> { | ||
| 15 | r.ptr.cast() | ||
| 16 | } | ||
| 17 | |||
| 18 | unsafe fn from_ptr(ptr: NonNull<Self>) -> Self::Handle { | ||
| 19 | let ptr: NonNull<TaskHeader> = ptr; | ||
| 20 | TaskRef { ptr } | ||
| 21 | } | ||
| 22 | |||
| 23 | unsafe fn links(ptr: NonNull<Self>) -> NonNull<Links<TaskHeader>> { | ||
| 24 | let ptr: *mut TaskHeader = ptr.as_ptr(); | ||
| 25 | NonNull::new_unchecked(addr_of_mut!((*ptr).run_queue_item)) | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | /// Atomic task queue using a very, very simple lock-free linked-list queue: | ||
| 30 | /// | ||
| 31 | /// To enqueue a task, task.next is set to the old head, and head is atomically set to task. | ||
| 32 | /// | ||
| 33 | /// Dequeuing is done in batches: the queue is emptied by atomically replacing head with | ||
| 34 | /// null. Then the batch is iterated following the next pointers until null is reached. | ||
| 35 | /// | ||
| 36 | /// Note that batches will be iterated in the reverse order as they were enqueued. This is OK | ||
| 37 | /// for our purposes: it can't create fairness problems since the next batch won't run until the | ||
| 38 | /// current batch is completely processed, so even if a task enqueues itself instantly (for example | ||
| 39 | /// by waking its own waker) can't prevent other tasks from running. | ||
| 40 | pub(crate) struct RunQueue { | ||
| 41 | stack: TransferStack<TaskHeader>, | ||
| 42 | } | ||
| 43 | |||
| 44 | impl RunQueue { | ||
| 45 | pub const fn new() -> Self { | ||
| 46 | Self { | ||
| 47 | stack: TransferStack::new(), | ||
| 48 | } | ||
| 49 | } | ||
| 50 | |||
| 51 | /// Enqueues an item. Returns true if the queue was empty. | ||
| 52 | /// | ||
| 53 | /// # Safety | ||
| 54 | /// | ||
| 55 | /// `item` must NOT be already enqueued in any queue. | ||
| 56 | #[inline(always)] | ||
| 57 | pub(crate) unsafe fn enqueue(&self, task: TaskRef, _: super::state::Token) -> bool { | ||
| 58 | self.stack.push_was_empty(task) | ||
| 59 | } | ||
| 60 | |||
| 61 | /// Empty the queue, then call `on_task` for each task that was in the queue. | ||
| 62 | /// NOTE: It is OK for `on_task` to enqueue more tasks. In this case they're left in the queue | ||
| 63 | /// and will be processed by the *next* call to `dequeue_all`, *not* the current one. | ||
| 64 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | ||
| 65 | // SAFETY: `deadline` can only be set through the `Deadline` interface, which | ||
| 66 | // only allows access to this value while the given task is being polled. | ||
| 67 | // This acts as mutual exclusion for access. | ||
| 68 | let mut sorted = SortedList::<TaskHeader>::new_custom(|lhs, rhs| unsafe { | ||
| 69 | lhs.deadline.get().cmp(&rhs.deadline.get()) | ||
| 70 | }); | ||
| 71 | |||
| 72 | loop { | ||
| 73 | // For each loop, grab any newly pended items | ||
| 74 | let taken = self.stack.take_all(); | ||
| 75 | |||
| 76 | // Sort these into the list - this is potentially expensive! We do an | ||
| 77 | // insertion sort of new items, which iterates the linked list. | ||
| 78 | // | ||
| 79 | // Something on the order of `O(n * m)`, where `n` is the number | ||
| 80 | // of new tasks, and `m` is the number of already pending tasks. | ||
| 81 | sorted.extend(taken); | ||
| 82 | |||
| 83 | // Pop the task with the SOONEST deadline. If there are no tasks | ||
| 84 | // pending, then we are done. | ||
| 85 | let Some(taskref) = sorted.pop_front() else { | ||
| 86 | return; | ||
| 87 | }; | ||
| 88 | |||
| 89 | // We got one task, mark it as dequeued, and process the task. | ||
| 90 | taskref.header().state.run_dequeue(); | ||
| 91 | on_task(taskref); | ||
| 92 | } | ||
| 93 | } | ||
| 94 | } | ||
| 95 | 3 | ||
| 96 | /// A type for interacting with the deadline of the current task | 4 | /// A type for interacting with the deadline of the current task |
| 97 | pub struct Deadline { | 5 | pub struct Deadline { |
| @@ -194,10 +102,10 @@ impl Deadline { | |||
| 194 | 102 | ||
| 195 | // SAFETY: A task can only modify its own deadline, while the task is being | 103 | // SAFETY: A task can only modify its own deadline, while the task is being |
| 196 | // polled, meaning that there cannot be concurrent access to the deadline. | 104 | // polled, meaning that there cannot be concurrent access to the deadline. |
| 197 | let deadline = unsafe { | 105 | let deadline = unsafe { task.header().deadline.get() }; |
| 198 | task.header().deadline.get() | 106 | Poll::Ready(Self { |
| 199 | }; | 107 | instant_ticks: deadline, |
| 200 | Poll::Ready(Self { instant_ticks: deadline }) | 108 | }) |
| 201 | }) | 109 | }) |
| 202 | } | 110 | } |
| 203 | } | 111 | } |
diff --git a/embassy-executor/src/raw/mod.rs b/embassy-executor/src/raw/mod.rs index 2e5941ef7..0dd247d30 100644 --- a/embassy-executor/src/raw/mod.rs +++ b/embassy-executor/src/raw/mod.rs | |||
| @@ -7,14 +7,7 @@ | |||
| 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( | 10 | #[cfg_attr(target_has_atomic = "ptr", path = "run_queue_atomics.rs")] |
| 11 | all(not(feature = "drs-scheduler"), target_has_atomic = "ptr"), | ||
| 12 | path = "run_queue_atomics.rs", | ||
| 13 | )] | ||
| 14 | #[cfg_attr( | ||
| 15 | all(feature = "drs-scheduler", target_has_atomic = "ptr"), | ||
| 16 | path = "run_queue_drs_atomics.rs", | ||
| 17 | )] | ||
| 18 | #[cfg_attr(not(target_has_atomic = "ptr"), path = "run_queue_critical_section.rs")] | 11 | #[cfg_attr(not(target_has_atomic = "ptr"), path = "run_queue_critical_section.rs")] |
| 19 | mod run_queue; | 12 | mod run_queue; |
| 20 | 13 | ||
| @@ -35,6 +28,9 @@ pub(crate) mod util; | |||
| 35 | #[cfg_attr(feature = "turbowakers", path = "waker_turbo.rs")] | 28 | #[cfg_attr(feature = "turbowakers", path = "waker_turbo.rs")] |
| 36 | mod waker; | 29 | mod waker; |
| 37 | 30 | ||
| 31 | #[cfg(feature = "drs-scheduler")] | ||
| 32 | mod deadline; | ||
| 33 | |||
| 38 | use core::future::Future; | 34 | use core::future::Future; |
| 39 | use core::marker::PhantomData; | 35 | use core::marker::PhantomData; |
| 40 | use core::mem; | 36 | use core::mem; |
| @@ -50,6 +46,9 @@ use embassy_executor_timer_queue::TimerQueueItem; | |||
| 50 | #[cfg(feature = "arch-avr")] | 46 | #[cfg(feature = "arch-avr")] |
| 51 | use portable_atomic::AtomicPtr; | 47 | use portable_atomic::AtomicPtr; |
| 52 | 48 | ||
| 49 | #[cfg(feature = "drs-scheduler")] | ||
| 50 | pub use deadline::Deadline; | ||
| 51 | |||
| 53 | use self::run_queue::{RunQueue, RunQueueItem}; | 52 | use self::run_queue::{RunQueue, RunQueueItem}; |
| 54 | use self::state::State; | 53 | use self::state::State; |
| 55 | use self::util::{SyncUnsafeCell, UninitCell}; | 54 | use self::util::{SyncUnsafeCell, UninitCell}; |
| @@ -62,9 +61,6 @@ extern "Rust" fn __embassy_time_queue_item_from_waker(waker: &Waker) -> &'static | |||
| 62 | unsafe { task_from_waker(waker).timer_queue_item() } | 61 | unsafe { task_from_waker(waker).timer_queue_item() } |
| 63 | } | 62 | } |
| 64 | 63 | ||
| 65 | #[cfg(feature = "drs-scheduler")] | ||
| 66 | pub use run_queue::Deadline; | ||
| 67 | |||
| 68 | /// Raw task header for use in task pointers. | 64 | /// Raw task header for use in task pointers. |
| 69 | /// | 65 | /// |
| 70 | /// A task can be in one of the following states: | 66 | /// A task can be in one of the following states: |
diff --git a/embassy-executor/src/raw/run_queue_atomics.rs b/embassy-executor/src/raw/run_queue_atomics.rs index ce511d79a..bc5d38250 100644 --- a/embassy-executor/src/raw/run_queue_atomics.rs +++ b/embassy-executor/src/raw/run_queue_atomics.rs | |||
| @@ -1,19 +1,36 @@ | |||
| 1 | use core::ptr; | 1 | use core::ptr::{addr_of_mut, NonNull}; |
| 2 | use core::ptr::NonNull; | 2 | |
| 3 | use core::sync::atomic::{AtomicPtr, Ordering}; | 3 | use cordyceps::sorted_list::Links; |
| 4 | use cordyceps::{Linked, SortedList, TransferStack}; | ||
| 4 | 5 | ||
| 5 | use super::{TaskHeader, TaskRef}; | 6 | use super::{TaskHeader, TaskRef}; |
| 6 | use crate::raw::util::SyncUnsafeCell; | ||
| 7 | 7 | ||
| 8 | pub(crate) struct RunQueueItem { | 8 | /// Use `cordyceps::sorted_list::Links` as the singly linked list |
| 9 | next: SyncUnsafeCell<Option<TaskRef>>, | 9 | /// for RunQueueItems. |
| 10 | } | 10 | pub(crate) type RunQueueItem = Links<TaskHeader>; |
| 11 | 11 | ||
| 12 | impl RunQueueItem { | 12 | /// Implements the `Linked` trait, allowing for singly linked list usage |
| 13 | pub const fn new() -> Self { | 13 | /// of any of cordyceps' `TransferStack` (used for the atomic runqueue), |
| 14 | Self { | 14 | /// `SortedList` (used with the DRS scheduler), or `Stack`, which is |
| 15 | next: SyncUnsafeCell::new(None), | 15 | /// popped atomically from the `TransferStack`. |
| 16 | } | 16 | unsafe impl Linked<Links<TaskHeader>> for TaskHeader { |
| 17 | type Handle = TaskRef; | ||
| 18 | |||
| 19 | // Convert a TaskRef into a TaskHeader ptr | ||
| 20 | fn into_ptr(r: TaskRef) -> NonNull<TaskHeader> { | ||
| 21 | r.ptr | ||
| 22 | } | ||
| 23 | |||
| 24 | // Convert a TaskHeader into a TaskRef | ||
| 25 | unsafe fn from_ptr(ptr: NonNull<TaskHeader>) -> TaskRef { | ||
| 26 | TaskRef { ptr } | ||
| 27 | } | ||
| 28 | |||
| 29 | // Given a pointer to a TaskHeader, obtain a pointer to the Links structure, | ||
| 30 | // which can be used to traverse to other TaskHeader nodes in the linked list | ||
| 31 | unsafe fn links(ptr: NonNull<TaskHeader>) -> NonNull<Links<TaskHeader>> { | ||
| 32 | let ptr: *mut TaskHeader = ptr.as_ptr(); | ||
| 33 | NonNull::new_unchecked(addr_of_mut!((*ptr).run_queue_item)) | ||
| 17 | } | 34 | } |
| 18 | } | 35 | } |
| 19 | 36 | ||
| @@ -29,13 +46,13 @@ impl RunQueueItem { | |||
| 29 | /// current batch is completely processed, so even if a task enqueues itself instantly (for example | 46 | /// 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. | 47 | /// by waking its own waker) can't prevent other tasks from running. |
| 31 | pub(crate) struct RunQueue { | 48 | pub(crate) struct RunQueue { |
| 32 | head: AtomicPtr<TaskHeader>, | 49 | stack: TransferStack<TaskHeader>, |
| 33 | } | 50 | } |
| 34 | 51 | ||
| 35 | impl RunQueue { | 52 | impl RunQueue { |
| 36 | pub const fn new() -> Self { | 53 | pub const fn new() -> Self { |
| 37 | Self { | 54 | Self { |
| 38 | head: AtomicPtr::new(ptr::null_mut()), | 55 | stack: TransferStack::new(), |
| 39 | } | 56 | } |
| 40 | } | 57 | } |
| 41 | 58 | ||
| @@ -46,43 +63,52 @@ impl RunQueue { | |||
| 46 | /// `item` must NOT be already enqueued in any queue. | 63 | /// `item` must NOT be already enqueued in any queue. |
| 47 | #[inline(always)] | 64 | #[inline(always)] |
| 48 | pub(crate) unsafe fn enqueue(&self, task: TaskRef, _: super::state::Token) -> bool { | 65 | pub(crate) unsafe fn enqueue(&self, task: TaskRef, _: super::state::Token) -> bool { |
| 49 | let mut was_empty = false; | 66 | self.stack.push_was_empty(task) |
| 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 | } | 67 | } |
| 66 | 68 | ||
| 67 | /// Empty the queue, then call `on_task` for each task that was in the queue. | 69 | /// 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 | 70 | /// 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. | 71 | /// and will be processed by the *next* call to `dequeue_all`, *not* the current one. |
| 72 | #[cfg(not(feature = "drs-scheduler"))] | ||
| 70 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | 73 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { |
| 71 | // Atomically empty the queue. | 74 | let taken = self.stack.take_all(); |
| 72 | let ptr = self.head.swap(ptr::null_mut(), Ordering::AcqRel); | 75 | for taskref in taken { |
| 76 | taskref.header().state.run_dequeue(); | ||
| 77 | on_task(taskref); | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | /// Empty the queue, then call `on_task` for each task that was in the queue. | ||
| 82 | /// NOTE: It is OK for `on_task` to enqueue more tasks. In this case they're left in the queue | ||
| 83 | /// and will be processed by the *next* call to `dequeue_all`, *not* the current one. | ||
| 84 | #[cfg(feature = "drs-scheduler")] | ||
| 85 | pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) { | ||
| 86 | // SAFETY: `deadline` can only be set through the `Deadline` interface, which | ||
| 87 | // only allows access to this value while the given task is being polled. | ||
| 88 | // This acts as mutual exclusion for access. | ||
| 89 | let mut sorted = | ||
| 90 | SortedList::<TaskHeader>::new_custom(|lhs, rhs| unsafe { lhs.deadline.get().cmp(&rhs.deadline.get()) }); | ||
| 91 | |||
| 92 | loop { | ||
| 93 | // For each loop, grab any newly pended items | ||
| 94 | let taken = self.stack.take_all(); | ||
| 73 | 95 | ||
| 74 | // safety: the pointer is either null or valid | 96 | // Sort these into the list - this is potentially expensive! We do an |
| 75 | let mut next = unsafe { NonNull::new(ptr).map(|ptr| TaskRef::from_ptr(ptr.as_ptr())) }; | 97 | // insertion sort of new items, which iterates the linked list. |
| 98 | // | ||
| 99 | // Something on the order of `O(n * m)`, where `n` is the number | ||
| 100 | // of new tasks, and `m` is the number of already pending tasks. | ||
| 101 | sorted.extend(taken); | ||
| 76 | 102 | ||
| 77 | // Iterate the linked list of tasks that were previously in the queue. | 103 | // Pop the task with the SOONEST deadline. If there are no tasks |
| 78 | while let Some(task) = next { | 104 | // pending, then we are done. |
| 79 | // If the task re-enqueues itself, the `next` pointer will get overwritten. | 105 | let Some(taskref) = sorted.pop_front() else { |
| 80 | // Therefore, first read the next pointer, and only then process the task. | 106 | return; |
| 81 | // safety: there are no concurrent accesses to `next` | 107 | }; |
| 82 | next = unsafe { task.header().run_queue_item.next.get() }; | ||
| 83 | 108 | ||
| 84 | task.header().state.run_dequeue(); | 109 | // We got one task, mark it as dequeued, and process the task. |
| 85 | on_task(task); | 110 | taskref.header().state.run_dequeue(); |
| 111 | on_task(taskref); | ||
| 86 | } | 112 | } |
| 87 | } | 113 | } |
| 88 | } | 114 | } |
