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/sync/event.rs

kernel/sync/
event.rs

1// Copyright 2025 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::ptr::NonNull;
16use core::sync::atomic::Ordering;
17
18use pw_atomic::{AtomicAdd, AtomicLoad, AtomicSub, AtomicZero};
19use pw_status::Result;
20use pw_time_core::Instant;
21
22use crate::scheduler::{WaitQueueLock, WaitQueueLockGuard, WaitType, WakeList, WakeResult};
23use crate::{Kernel, SchedulerState, SpinLockGuard};
24
25/// Configuration for the behavior of an [`Event`].
26#[derive(Eq, PartialEq)]
27pub enum EventConfig {
28    /// When an [`Event`] is signaled, the first waiter to observe that signal
29    /// automatically clears the signaled state, returning the `Event` to the
30    /// un-signaled state.
31    AutoReset,
32    /// When an [`Event`] is signaled, it remains signaled indefinitely until
33    /// [`unsignal`] is called, which returns the `Event` to the un-signaled
34    /// state.
35    ///
36    /// [`unsignal`]: EventSignaler::unsignal
37    ManualReset,
38}
39
40struct EventState {
41    signaled: bool,
42}
43
44/// A basic synchronization primitive allowing threads to block on an event
45/// happening.
46///
47/// An `Event` starts in an un-signaled state. Threads can use [`wait`] or
48/// [`wait_until`] to block until the state has changed to signaled. The signal
49/// state is controlled by an [`EventSignaler`] via the [`signal_and_wake`] and [`unsignal`]
50/// methods.
51///
52/// Depending on what [`EventConfig`] is used, [`signal_and_wake`] may either set the
53/// signal permanently, or it may be automatically cleared once a single waiter
54/// has been un-blocked by it.
55///
56/// # Panics
57///
58/// Panics on drop if there are [`EventSignaler`]s referencing this object.
59///
60/// [`wait`]: Event::wait
61/// [`wait_until`]: Event::wait_until
62/// [`signal_and_wake`]: EventSignaler::signal_and_wake
63/// [`unsignal`]: EventSignaler::unsignal
64pub struct Event<K: Kernel> {
65    kernel: K,
66    config: EventConfig,
67    state: WaitQueueLock<K, EventState>,
68    signalers: K::AtomicUsize,
69}
70
71/// A signaler for an [`Event`]
72///
73/// [`EventSignaler`] is returned from [`Event::get_signaler()`] and is used to
74/// signal the referenced Event.  It can be cloned and the referenced [`Event`]
75/// will panic if it is dropped when any [`EventSignaler`]s still reference it.
76pub struct EventSignaler<K: Kernel> {
77    event: NonNull<Event<K>>,
78}
79
80// SAFETY: Event will panic if there are outstanding signalers referencing it
81// guaranteeing that the event pointer will always be valid.
82unsafe impl<K: Kernel> Send for EventSignaler<K> {}
83unsafe impl<K: Kernel> Sync for EventSignaler<K> {}
84
85impl<K: Kernel> Clone for EventSignaler<K> {
86    fn clone(&self) -> Self {
87        self.event()
88            .signalers
89            // TODO: rationalize ordering
90            .fetch_add(1, Ordering::SeqCst);
91        Self { event: self.event }
92    }
93}
94
95impl<K: Kernel> Drop for EventSignaler<K> {
96    fn drop(&mut self) {
97        self.event()
98            .signalers
99            // TODO: rationalize ordering
100            .fetch_sub(1, Ordering::SeqCst);
101    }
102}
103
104impl<K: Kernel> EventSignaler<K> {
105    fn event(&self) -> &Event<K> {
106        // SAFETY: An `Event` will panic if there are outstanding signalers
107        // referencing it.  Since we bind the lifetime of the `&Event` to the
108        // lifetime of this signaler, we are assured the Event will remain
109        // valid.
110        unsafe { self.event.as_ref() }
111    }
112
113    /// Signals the `Event` and wakes any waiting threads, rescheduling if needed.
114    ///
115    /// Consumes the signaler so no references to the event remain before threads
116    /// are woken, which avoids use-after-free on stack-allocated events.
117    ///
118    /// For long-lived events, the signaler can be cloned to signal multiple times
119    /// or from multiple threads.  It is up to the user to ensure that the
120    /// [`Event`] is only dropped after all signalers are dropped.
121    ///
122    /// # Interrupt context
123    ///
124    /// This method *is* safe to call in an interrupt context.
125    pub fn signal_and_wake(self) {
126        let kernel = self.event().kernel;
127        let sched = kernel.get_scheduler().lock(kernel);
128        let _ = self.signal_and_wake_locked(kernel, sched);
129    }
130
131    /// Sets the `Event`'s state to signaled and wakes waiters while holding the scheduler lock.
132    ///
133    /// Consumes the signaler, matching [`Self::signal_and_wake`].
134    ///
135    /// # Interrupt context
136    ///
137    /// This method *is* safe to call in an interrupt context.
138    pub(crate) fn signal_and_wake_locked<'a>(
139        self,
140        kernel: K,
141        sched: SpinLockGuard<'a, K, SchedulerState<K>>,
142    ) -> SpinLockGuard<'a, K, SchedulerState<K>> {
143        let mut wake_list = WakeList::new();
144        let sched = self.signal_and_dequeue_locked(sched, &mut wake_list);
145        wake_list.wake_and_reschedule(kernel, sched)
146    }
147
148    /// Signals the event and dequeues waiters into `wake_list` without waking them.
149    ///
150    /// Consumes `self` so no signaler references remain before the caller wakes the threads.
151    pub(crate) fn signal_and_dequeue_locked<'a>(
152        self,
153        sched: SpinLockGuard<'a, K, SchedulerState<K>>,
154        wake_list: &mut WakeList<K>,
155    ) -> SpinLockGuard<'a, K, SchedulerState<K>> {
156        // `state` (`WaitQueueLockGuard`) borrows the `EventSignaler` through
157        // `event()`, preventing `drop(self)` from being called before
158        // `state.into_sched()`. Wrap `self` in `ManuallyDrop` so we can
159        // manually decrement `event.signalers` while `state` is still held.
160        let this = core::mem::ManuallyDrop::new(self);
161        let event = this.event();
162        let state = event.state.inherit_sched_lock(sched);
163
164        let state = event.signal_locked_dequeue(state, wake_list);
165        // Decrement the signaler count while holding `state` so that once
166        // `WaitQueueLock` uses a fine-grained lock, a waiter taking the fast
167        // path in `Event::wait` cannot observe `state.signaled == true` and
168        // drop a stack-allocated `Event` before the signaler count is updated.
169        event.signalers.fetch_sub(1, Ordering::SeqCst);
170        state.into_sched()
171    }
172
173    /// Sets the `Event`'s state to un-signaled.
174    ///
175    /// # Interrupt context
176    ///
177    /// This method *is* safe to call in an interrupt context.
178    pub fn unsignal(&self) {
179        self.event().unsignal();
180    }
181}
182
183unsafe impl<K: Kernel> Sync for Event<K> {}
184unsafe impl<K: Kernel> Send for Event<K> {}
185
186impl<K: Kernel> Event<K> {
187    /// Constructs a new `Event` with the given configuration.
188    ///
189    #[must_use]
190    pub const fn new(kernel: K, config: EventConfig) -> Self {
191        Self {
192            kernel,
193            config,
194            state: WaitQueueLock::new(kernel, EventState { signaled: false }),
195            signalers: K::AtomicUsize::ZERO,
196        }
197    }
198
199    /// Returns an [`EventSignaler`] for signaling an `Event`.
200    ///
201    #[must_use]
202    pub fn get_signaler(&self) -> EventSignaler<K> {
203        self.signalers.fetch_add(1, Ordering::SeqCst);
204        EventSignaler {
205            event: NonNull::from_ref(self),
206        }
207    }
208
209    /// Waits until the `Event` is in the signaled state.
210    ///
211    /// If the event's configuration is [`AutoReset`], the thread which is
212    /// un-blocked by a signal also clears that signal, resetting its value to
213    /// un-signaled.
214    ///
215    /// [`AutoReset`]: EventConfig::AutoReset
216    ///
217    /// # Interrupt context
218    ///
219    /// This method is *not* safe to call in an interrupt context.
220    pub fn wait(&self) -> Result<()> {
221        let mut state = self.state.lock();
222        if !state.signaled {
223            let (_, ret) = state.wait(WaitType::Interruptible);
224            return ret;
225        } else if self.config == EventConfig::AutoReset {
226            state.signaled = false;
227        }
228        Ok(())
229    }
230
231    /// Waits until the `Event` is in the signaled state or the `deadline` is
232    /// reached, whichever happens first.
233    ///
234    /// If the event's configuration is [`EventConfig::AutoReset`], the thread
235    /// which is un-blocked by a signal also clears that signal, resetting its
236    /// value to un-signaled.
237    ///
238    /// # Interrupt context
239    ///
240    /// This method is *not* safe to call in an interrupt context.
241    pub fn wait_until(&self, deadline: Instant<K::Clock>) -> Result<()> {
242        let mut state = self.state.lock();
243        if !state.signaled {
244            let (_state, result) = state.wait_until(WaitType::Interruptible, deadline);
245            return result;
246        } else if self.config == EventConfig::AutoReset {
247            state.signaled = false;
248        }
249
250        Ok(())
251    }
252
253    /// Updates the event's state and dequeues its waiters into `wake_list` without waking them.
254    fn signal_locked_dequeue<'lock, 'sched>(
255        &self,
256        mut state: WaitQueueLockGuard<'lock, 'sched, K, EventState>,
257        wake_list: &mut WakeList<K>,
258    ) -> WaitQueueLockGuard<'lock, 'sched, K, EventState> {
259        if !state.signaled {
260            match self.config {
261                EventConfig::AutoReset => {
262                    if state.dequeue_one(wake_list) == WakeResult::QueueEmpty {
263                        state.signaled = true;
264                    }
265                }
266                EventConfig::ManualReset => {
267                    state.signaled = true;
268                    let _ = state.dequeue_all(wake_list);
269                }
270            }
271        }
272        state
273    }
274
275    fn unsignal(&self) {
276        self.state.lock().signaled = false;
277    }
278}
279
280impl<K: Kernel> Drop for Event<K> {
281    fn drop(&mut self) {
282        // TODO: rationalize ordering
283        let num_signalers = self.signalers.load(Ordering::SeqCst);
284        if num_signalers > 0 {
285            pw_assert::panic!(
286                "Event droped with {} active signalers",
287                num_signalers as usize
288            )
289        }
290    }
291}