Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/scheduler/algorithm/priority_queue_set.rs

kernel/scheduler/algorithm/
priority_queue_set.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use core::mem::{self, MaybeUninit};
16use core::ptr::NonNull;
17
18use foreign_box::ForeignBox;
19use list::ForeignList;
20
21use crate::Kernel;
22use crate::scheduler::algorithm::priority_bitmask::PriorityBitmask;
23use crate::scheduler::thread::ThreadListAdapter;
24use crate::scheduler::{Priority, Thread};
25
26type RunQueue<K> = ForeignList<Thread<K>, ThreadListAdapter<K>>;
27
28/// A set of intrusive per-priority run queues plus a bitmask of non-empty
29/// priorities, giving constant-time `O(1)` push, pop, and removal.
30///
31/// A thread's priority is read from `algorithm_state.priority()` when it
32/// is queued and must not change while it is linked here.
33pub struct PriorityQueueSet<K: Kernel> {
34    /// One run queue per priority level.
35    ///
36    /// Index 0 is the lowest priority, `NUM_PRIORITIES - 1` is the highest.
37    run_queues: [RunQueue<K>; Priority::NUM_PRIORITIES],
38    /// Bit `p` is set iff `run_queues[p]` is non-empty.
39    ready_bitmask: PriorityBitmask,
40}
41
42impl<K: Kernel> PriorityQueueSet<K> {
43    #[must_use]
44    pub const fn new() -> Self {
45        // Initialize the array of ForeignLists. There are a few limitations
46        // from running in a `const` context that make this more complicated
47        // than usual.
48        // - ForeignList does not implement `Copy`
49        // - `Default::default` and `core::array::from_fn` don't support `const`
50        // - `const` `for` loops are an unstable feature
51        //
52        // Instead a combination of `MaybeUninit`, `while`, and `transmute` are
53        // used.
54        let run_queues = {
55            let mut queues =
56                [const { MaybeUninit::<RunQueue<K>>::uninit() }; Priority::NUM_PRIORITIES];
57
58            let mut i = 0;
59            while i < Priority::NUM_PRIORITIES {
60                queues[i].write(ForeignList::new());
61                i += 1;
62            }
63
64            // SAFETY: All elements have been initialized in the loop above.
65            unsafe {
66                mem::transmute::<
67                    [MaybeUninit<RunQueue<K>>; Priority::NUM_PRIORITIES],
68                    [RunQueue<K>; Priority::NUM_PRIORITIES],
69                >(queues)
70            }
71        };
72
73        Self {
74            run_queues,
75            ready_bitmask: PriorityBitmask::new(),
76        }
77    }
78
79    /// Enqueues `thread` at the head of its priority's run queue and marks that
80    /// priority ready.
81    #[inline]
82    pub fn push_front(&mut self, thread: ForeignBox<Thread<K>>) {
83        let priority = thread.algorithm_state.priority();
84        self.ready_bitmask.set_priority(priority);
85        self.run_queues[priority as usize].push_front(thread);
86    }
87
88    /// Enqueues `thread` at the tail of its priority's run queue and marks that
89    /// priority ready.
90    #[inline]
91    pub fn push_back(&mut self, thread: ForeignBox<Thread<K>>) {
92        let priority = thread.algorithm_state.priority();
93        self.ready_bitmask.set_priority(priority);
94        self.run_queues[priority as usize].push_back(thread);
95    }
96
97    /// Dequeues the head of the highest-priority non-empty run queue, clearing
98    /// that priority's ready bit if the queue drains.
99    ///
100    /// Returns `None` if no thread is queued.
101    #[inline]
102    pub fn pop_head(&mut self) -> Option<ForeignBox<Thread<K>>> {
103        let priority = self.ready_bitmask.get_highest_priority()?;
104        let run_queue = &mut self.run_queues[priority as usize];
105        let thread = run_queue.pop_head();
106        if run_queue.is_empty() {
107            self.ready_bitmask.clear_priority(priority);
108        }
109        thread
110    }
111
112    /// Removes a specific element from the queue set in strictly `O(1)` time.
113    ///
114    /// # Safety
115    /// Caller must ensure `element` points to a valid `Thread<K>` currently
116    /// linked in `self` at `element.as_ref().algorithm_state.priority()`.
117    // Not yet used; provided for future users. Remove the `expect` when the
118    // first caller lands.
119    #[expect(dead_code)]
120    #[inline]
121    #[must_use]
122    pub unsafe fn remove_element(&mut self, element: NonNull<Thread<K>>) -> ForeignBox<Thread<K>> {
123        // SAFETY: The caller guarantees that `element` points to a valid `Thread<K>`.
124        let priority = unsafe { element.as_ref() }.algorithm_state.priority();
125        let run_queue = &mut self.run_queues[priority as usize];
126        // SAFETY: The caller guarantees that `element` is a valid pointer to a
127        // `Thread<K>` linked in `self.run_queues[priority as usize]`.
128        let thread = unsafe { run_queue.remove_element_unchecked(element) };
129        if run_queue.is_empty() {
130            self.ready_bitmask.clear_priority(priority);
131        }
132        thread
133    }
134}