rusty_rtos_kernel_core/events.rs
1//! Event groups: `event_groups.c`.
2//!
3//! An event group is a word of bits and a list of the tasks waiting on some
4//! of them. It is the one FreeRTOS primitive with no queue underneath — a
5//! waiter's *condition* lives in its own event list item, so setting a bit
6//! is one walk of that list asking each waiter whether it is satisfied.
7//!
8//! # The item value is the condition
9//!
10//! `vTaskPlaceOnUnorderedEventList` writes the bits a task is waiting for
11//! into `xEventListItem`, where a priority-ordered event list would have
12//! kept `configMAX_PRIORITIES - uxPriority`. The top byte carries three
13//! flags with it — clear-on-exit, wait-for-all, and the one the unblocker
14//! sets to say *why* the task woke — which is why the usable bits are the
15//! bottom 24 and every comparison masks first.
16//!
17//! A task that times out is taken off the event list by the tick, so its
18//! item value keeps the flags it blocked with and *not* the
19//! unblocked-due-to-bit-set one. That difference is the whole of the C's
20//! timeout test, and it is why this module needs no timeout flag of its own.
21
22use rusty_rtos_core::config::Config;
23use rusty_rtos_core::error::{Error, Result};
24use rusty_rtos_core::handle::{EventGroupHandle, TaskHandle};
25use rusty_rtos_core::hooks::TickHook;
26use rusty_rtos_core::isr::Woken;
27use rusty_rtos_core::list::ListId;
28use rusty_rtos_core::port::Port;
29use rusty_rtos_core::trace::{Event, Trace};
30
31use crate::kernel::{Kernel, OwedTrace};
32use crate::lists_for;
33use crate::queue::Wait::{self, Ready};
34
35/// `EventGroup_t`: the bits, and nothing else — the list of waiting tasks
36/// is one of the kernel's, named by the group's arena index.
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct EventGroup {
39 /// `uxEventBits`.
40 pub(crate) bits: u32,
41}
42
43/// `eventCLEAR_EVENTS_ON_EXIT_BIT`.
44const CLEAR_EVENTS_ON_EXIT: u64 = 0x0100_0000;
45/// `eventUNBLOCKED_DUE_TO_BIT_SET`.
46const UNBLOCKED_DUE_TO_BIT_SET: u64 = 0x0200_0000;
47/// `eventWAIT_FOR_ALL_BITS`.
48const WAIT_FOR_ALL_BITS: u64 = 0x0400_0000;
49/// `eventEVENT_BITS_CONTROL_BYTES`: the top byte of a 32-bit `EventBits_t`,
50/// which the three flags and `taskEVENT_LIST_ITEM_VALUE_IN_USE` share.
51pub(crate) const EVENT_BITS_CONTROL_BYTES: u64 = 0xff00_0000;
52
53/// The `function` a `TickHook::pended` sees for `xEventGroupSetBitsFromISR`.
54pub const PENDED_SET_BITS: u16 = u16::MAX;
55/// The `function` a `TickHook::pended` sees for
56/// `xEventGroupClearBitsFromISR`.
57pub const PENDED_CLEAR_BITS: u16 = u16::MAX - 1;
58
59impl<
60 C: Config,
61 P: Port,
62 T: Trace,
63 H,
64 const TASKS: usize,
65 const ITEMS: usize,
66 const LISTS: usize,
67 const QUEUES: usize,
68 const SLOTS: usize,
69 const BUFFERS: usize,
70 const BYTES: usize,
71 const TIMERS: usize,
72 const GROUPS: usize,
73 const TIMER_CMDS: usize,
74> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
75where
76 H: TickHook<Self>,
77{
78 /// `xTasksWaitingForBits` of one group.
79 pub(crate) fn event_group_list(group: EventGroupHandle) -> ListId {
80 let base = u8::try_from(lists_for(C::MAX_PRIORITIES, QUEUES, 0)).unwrap_or(u8::MAX);
81 base.saturating_add(u8::try_from(group.index()).unwrap_or(u8::MAX))
82 }
83
84 /// `prvTestWaitCondition`.
85 const fn wait_condition_met(current: u32, wait_for: u32, all: bool) -> bool {
86 if all {
87 current & wait_for == wait_for
88 } else {
89 current & wait_for != 0
90 }
91 }
92
93 /// `xEventGroupCreate`.
94 ///
95 /// # Errors
96 /// [`Error::Full`] when the arena is full, which is `NULL` in the C.
97 pub fn event_group_create(&mut self) -> Result<EventGroupHandle> {
98 self.account_for_allocation();
99 let group = self
100 .groups
101 .try_insert(EventGroup::default())
102 .map_err(|_| Error::Full)?;
103 // `vListInitialise( &( pxEventBits->xTasksWaitingForBits ) )`. The
104 // arena hands slots back out, so a group's list is whatever the
105 // last group at that index left behind.
106 // C calls `vListInitialise( &( pxEventBits->xTasksWaitingForBits ) )`
107 // here because its list is a field of memory `pvPortMalloc` just
108 // handed over, so it holds garbage. Ours is a slot in a shared list
109 // array indexed by the group's arena index, and it is already empty:
110 // `event_group_delete` unblocks every waiter before it discards the
111 // slot. Mirroring the C literally -- draining the list on every
112 // create -- cost **84 bytes of flash** for a loop that cannot iterate.
113 //
114 // What makes that safe is not this comment but
115 // `a_reused_group_slot_does_not_inherit_the_last_groups_waiters`, which
116 // blocks a real waiter, deletes the group under it, and checks the
117 // reused slot comes back clean. It was poison-verified: with delete's
118 // drain disabled it is the ONE test that fails.
119 let tick = self.tick;
120 self.note_exits();
121 self.trace.event(tick, Event::EventGroupCreate { group });
122 Ok(group)
123 }
124
125 /// `vEventGroupDelete`.
126 ///
127 /// Every waiter is unblocked with a value of zero and the bit-set flag,
128 /// so each wakes, finds its condition unmet, and reports what the C
129 /// reports: a timeout.
130 ///
131 /// # Errors
132 /// [`Error::Gone`] for a stale handle.
133 pub fn event_group_delete(&mut self, group: EventGroupHandle) -> Result<()> {
134 self.groups.resolve(group)?;
135 self.suspend_all();
136 let list = Self::event_group_list(group);
137 // Every waiter comes off here, which is what lets `event_group_create`
138 // skip a drain of its own -- see the slot-reuse test.
139 while let Ok(Some(item)) = self.lists.head(list) {
140 self.remove_from_unordered_event_list(item, UNBLOCKED_DUE_TO_BIT_SET)?;
141 }
142 let _ = self.groups.discard(group);
143 let _ = self.resume_all();
144 // `vPortFree( pxEventBits )`, outside the resume — and every
145 // `heap_N.c` wraps free the same way it wraps malloc, so it costs
146 // its own outermost exit.
147 self.account_for_allocation();
148 Ok(())
149 }
150
151 /// `xEventGroupGetBits`, which the C defines as
152 /// `xEventGroupClearBits( xEventGroup, 0 )` — so it costs the same
153 /// critical section a clear does.
154 ///
155 /// # Errors
156 /// [`Error::Gone`] for a stale handle.
157 pub fn event_group_bits(&mut self, group: EventGroupHandle) -> Result<u32> {
158 self.event_group_clear_bits(group, 0)
159 }
160
161 /// `xEventGroupGetBitsFromISR`. The Posix port's interrupt mask costs
162 /// nothing, so neither does this.
163 ///
164 /// # Errors
165 /// [`Error::Gone`] for a stale handle.
166 pub fn event_group_bits_from_isr(&self, group: EventGroupHandle) -> Result<u32> {
167 Ok(self.groups.resolve(group)?.bits)
168 }
169
170 /// `xEventGroupClearBits`: the bits as they were, then cleared.
171 ///
172 /// # Errors
173 /// [`Error::Gone`] for a stale handle.
174 pub fn event_group_clear_bits(&mut self, group: EventGroupHandle, bits: u32) -> Result<u32> {
175 self.enter_critical();
176 // `traceEVENT_GROUP_CLEAR_BITS` is not one of the harness's hooks.
177 let result = self.groups.resolve_mut(group).map(|g| {
178 let before = g.bits;
179 g.bits &= !bits;
180 before
181 });
182 self.exit_critical();
183 result
184 }
185
186 /// `xEventGroupSetBits`: set them, then wake every waiter the new value
187 /// satisfies and clear whatever those waiters asked to have cleared.
188 ///
189 /// # Errors
190 /// [`Error::Gone`] for a stale handle.
191 pub fn event_group_set_bits(&mut self, group: EventGroupHandle, bits: u32) -> Result<u32> {
192 self.groups.resolve(group)?;
193 let list = Self::event_group_list(group);
194 self.suspend_all();
195 let tick = self.tick;
196 self.note_exits();
197 self.trace
198 .event(tick, Event::EventGroupSetBits { group, bits });
199 // Keep what the set produced: when no waiter asks for a clear — which
200 // is every call that wakes nobody, and the common one — it is already
201 // the answer, and the tail below need not resolve the group again.
202 let mut after: u32 = 0;
203 if let Ok(g) = self.groups.resolve_mut(group) {
204 g.bits |= bits;
205 after = g.bits;
206 }
207 let mut to_clear: u32 = 0;
208 let mut item = self.lists.head(list)?;
209 while let Some(this) = item {
210 // The next one is read before this one is unblocked, because
211 // unblocking takes it off the list this walk is standing in.
212 // One lookup for both: see `ListsOf::next_and_value`.
213 let (next, value) = self.lists.next_and_value(this)?;
214 let control = value & EVENT_BITS_CONTROL_BYTES;
215 let waited_for = (value & !EVENT_BITS_CONTROL_BYTES) as u32;
216 // `after` IS this value. The walk only takes waiters OFF the
217 // list -- the comment on `to_clear` below says so, and the clear
218 // is applied after the loop -- so the group's bits cannot change
219 // while it runs, and resolving them again per waiter was an arena
220 // lookup per iteration to re-read a word already in hand. LLVM
221 // cannot hoist it because `remove_from_unordered_event_list` takes
222 // `&mut self` and stands between the read and the next one.
223 let current = after;
224 if Self::wait_condition_met(current, waited_for, control & WAIT_FOR_ALL_BITS != 0) {
225 if control & CLEAR_EVENTS_ON_EXIT != 0 {
226 to_clear |= waited_for;
227 }
228 self.remove_from_unordered_event_list(
229 this,
230 u64::from(current) | UNBLOCKED_DUE_TO_BIT_SET,
231 )?;
232 }
233 item = next;
234 }
235 let result = if to_clear == 0 {
236 // `bits &= !0` is the identity, so there is nothing to write, and
237 // the walk above only ever takes waiters OFF the list — it does
238 // not touch the group's bits.
239 after
240 } else {
241 match self.groups.resolve_mut(group) {
242 Ok(g) => {
243 g.bits &= !to_clear;
244 g.bits
245 }
246 Err(_) => 0,
247 }
248 };
249 let _ = self.resume_all_inline();
250 Ok(result)
251 }
252
253 /// `xEventGroupSetBitsFromISR`.
254 ///
255 /// An interrupt cannot walk the waiting list, so the C hands the job to
256 /// the daemon task through `xTimerPendFunctionCallFromISR` and answers
257 /// whether the daemon took it, not what the bits became.
258 ///
259 /// # Errors
260 /// As the queue send behind `xTimerPendFunctionCallFromISR`.
261 pub fn event_group_set_bits_from_isr(
262 &mut self,
263 group: EventGroupHandle,
264 bits: u32,
265 ) -> Result<(bool, Woken)> {
266 self.pend_group_call(PENDED_SET_BITS, group, bits)
267 }
268
269 /// `xEventGroupClearBitsFromISR`, deferred the same way.
270 ///
271 /// # Errors
272 /// As the queue send behind `xTimerPendFunctionCallFromISR`.
273 pub fn event_group_clear_bits_from_isr(
274 &mut self,
275 group: EventGroupHandle,
276 bits: u32,
277 ) -> Result<(bool, Woken)> {
278 self.pend_group_call(PENDED_CLEAR_BITS, group, bits)
279 }
280
281 /// The group's handle is `pvParameter1` and the bits are
282 /// `ulParameter2`, exactly as the C passes them.
283 fn pend_group_call(
284 &mut self,
285 function: u16,
286 group: EventGroupHandle,
287 bits: u32,
288 ) -> Result<(bool, Woken)> {
289 self.timer_pend_function_call_from_isr(function, u64::from(group.index()), u64::from(bits))
290 }
291
292 /// The daemon task's half of those two: `vEventGroupSetBitsCallback`
293 /// and `vEventGroupClearBitsCallback`.
294 ///
295 /// A [`TickHook::pended`] implementation routes [`PENDED_SET_BITS`] and
296 /// [`PENDED_CLEAR_BITS`] here; every other `function` is the
297 /// application's own.
298 ///
299 /// # Errors
300 /// [`Error::Gone`] when the group has been deleted since.
301 pub fn event_group_pended_call(
302 &mut self,
303 function: u16,
304 param1: u64,
305 param2: u64,
306 ) -> Result<()> {
307 let Some(group) = self.groups.handle_at(param1 as u16) else {
308 return Err(Error::Gone);
309 };
310 let bits = param2 as u32;
311 match function {
312 PENDED_SET_BITS => {
313 self.event_group_set_bits(group, bits)?;
314 }
315 PENDED_CLEAR_BITS => {
316 self.event_group_clear_bits(group, bits)?;
317 }
318 _ => {}
319 }
320 Ok(())
321 }
322
323 /// `xEventGroupWaitBits`.
324 ///
325 /// The C blocks in the middle of this function and finishes it on the
326 /// far side of the switch. A kernel with no stacks cannot, so a call
327 /// that has to block answers [`Wait::Blocked`] and is called again; the
328 /// second call *is* the far side, and starts at
329 /// `uxTaskResetEventItemValue`.
330 ///
331 /// # Errors
332 /// [`Error::Gone`] for a stale handle.
333 pub fn event_group_wait_bits(
334 &mut self,
335 group: EventGroupHandle,
336 wait_for: u32,
337 clear_on_exit: bool,
338 wait_for_all: bool,
339 ticks: u64,
340 ) -> Result<Wait<u32>> {
341 let caller = self.current();
342 if self.take_event_resume(caller) {
343 let value = self.reset_event_item_value(caller)?;
344 let bits = self.finish_wait(group, value, wait_for, clear_on_exit, wait_for_all)?;
345 self.trace_wait_bits_end(
346 caller,
347 group,
348 wait_for,
349 value & UNBLOCKED_DUE_TO_BIT_SET == 0,
350 );
351 return Ok(Ready(bits));
352 }
353
354 self.groups.resolve(group)?;
355 self.suspend_all();
356 let current = self.groups.resolve(group)?.bits;
357 let mut blocked = false;
358 let mut timed_out = false;
359 let mut result = current;
360 if Self::wait_condition_met(current, wait_for, wait_for_all) {
361 // Merging this clear into the resolve above -- one `resolve_mut`
362 // serving both the read and the write, which the borrow checker
363 // allows because `wait_condition_met` takes no borrow of `self` --
364 // removes one arena lookup (`slli` -1) and measured **+20 B** on
365 // 2026-09-25. Refuted: what it costs is branch shape, which is the
366 // same wall `list.rs`'s five passes hit.
367 if clear_on_exit {
368 if let Ok(g) = self.groups.resolve_mut(group) {
369 g.bits &= !wait_for;
370 }
371 }
372 } else if ticks == 0 {
373 timed_out = true;
374 } else {
375 let mut control = 0;
376 if clear_on_exit {
377 control |= CLEAR_EVENTS_ON_EXIT;
378 }
379 if wait_for_all {
380 control |= WAIT_FOR_ALL_BITS;
381 }
382 self.place_on_unordered_event_list(
383 Self::event_group_list(group),
384 u64::from(wait_for) | control,
385 ticks,
386 )?;
387 result = 0;
388 let tick = self.tick;
389 self.note_exits();
390 self.trace.event(
391 tick,
392 Event::EventGroupWaitBitsBlock {
393 group,
394 bits: wait_for,
395 },
396 );
397 blocked = true;
398 }
399 let already_yielded = self.resume_all_inline();
400 if blocked {
401 if !already_yielded {
402 self.yield_or_owe(caller);
403 }
404 self.set_event_resume(caller);
405 return Ok(Wait::Blocked);
406 }
407 self.trace_wait_bits_end(caller, group, wait_for, timed_out);
408 Ok(Ready(result))
409 }
410
411 /// `xEventGroupSync`: set some bits, then wait for a set that usually
412 /// includes them — the rendezvous every task in a group must reach.
413 ///
414 /// It has its own two trace points, `traceEVENT_GROUP_SYNC_BLOCK` and
415 /// `traceEVENT_GROUP_SYNC_END`, which the Kairos harness does not hook.
416 /// The `xEventGroupSetBits` inside it traces as itself, and that is the
417 /// only line a sync puts in the trace.
418 ///
419 /// # Errors
420 /// [`Error::Gone`] for a stale handle.
421 pub fn event_group_sync(
422 &mut self,
423 group: EventGroupHandle,
424 set: u32,
425 wait_for: u32,
426 ticks: u64,
427 ) -> Result<Wait<u32>> {
428 let caller = self.current();
429 if self.take_event_resume(caller) {
430 let value = self.reset_event_item_value(caller)?;
431 // `xEventGroupSync`'s tail IS the wait tail with both flags true:
432 // its re-test is always wait-for-all, and its clear is not
433 // conditional on a flag. This used to be a separate `finish_sync`
434 // holding its own copy of the twenty lines below.
435 return Ok(Ready(self.finish_wait(group, value, wait_for, true, true)?));
436 }
437
438 self.groups.resolve(group)?;
439 self.suspend_all();
440 let original = self.groups.resolve(group)?.bits;
441 self.event_group_set_bits(group, set)?;
442 let mut blocked = false;
443 let result;
444 if (original | set) & wait_for == wait_for {
445 result = original | set;
446 if let Ok(g) = self.groups.resolve_mut(group) {
447 g.bits &= !wait_for;
448 }
449 } else if ticks == 0 {
450 result = self.groups.resolve(group)?.bits;
451 } else {
452 self.place_on_unordered_event_list(
453 Self::event_group_list(group),
454 u64::from(wait_for) | CLEAR_EVENTS_ON_EXIT | WAIT_FOR_ALL_BITS,
455 ticks,
456 )?;
457 result = 0;
458 blocked = true;
459 }
460 let already_yielded = self.resume_all();
461 if blocked {
462 if !already_yielded {
463 self.yield_or_owe(caller);
464 }
465 self.set_event_resume(caller);
466 return Ok(Wait::Blocked);
467 }
468 Ok(Ready(result))
469 }
470
471 /// The tail of `xEventGroupWaitBits` past the switch: a task woken by
472 /// the unblocker already has its answer in the item value, and one
473 /// woken by the tick has to look at the group again.
474 /// The tail both `xEventGroupWaitBits` and `xEventGroupSync` run once the
475 /// wait is over: re-test the bits, clear what was waited for, answer what
476 /// the group held.
477 ///
478 /// `sync`'s tail was a second copy of this with `wait_for_all` and
479 /// `clear_on_exit` frozen true (`wait_condition_met(b, w, true)` is exactly
480 /// `b & w == w`). Folding the two together is **byte-identical** and takes
481 /// twenty duplicated lines out -- but ONLY with the attribute below.
482 ///
483 /// Deleting the twin alone measured **+34 B**: at two callers LLVM stopped
484 /// inlining and emitted a shared symbol, which costs more than the copy it
485 /// saves because each caller freezes different constants. `inline(always)`
486 /// restores the two specialising copies, so this is a source-duplication
487 /// win at zero flash cost, not a flash win.
488 #[inline(always)]
489 fn finish_wait(
490 &mut self,
491 group: EventGroupHandle,
492 value: u64,
493 wait_for: u32,
494 clear_on_exit: bool,
495 wait_for_all: bool,
496 ) -> Result<u32> {
497 if value & UNBLOCKED_DUE_TO_BIT_SET != 0 {
498 return Ok((value & !EVENT_BITS_CONTROL_BYTES) as u32);
499 }
500 self.enter_critical();
501 let bits = self.groups.resolve(group).map(|g| g.bits);
502 if let Ok(bits) = bits {
503 if Self::wait_condition_met(bits, wait_for, wait_for_all) && clear_on_exit {
504 if let Ok(g) = self.groups.resolve_mut(group) {
505 g.bits &= !wait_for;
506 }
507 }
508 }
509 self.exit_critical();
510 Ok((u64::from(bits?) & !EVENT_BITS_CONTROL_BYTES) as u32)
511 }
512
513 /// `traceEVENT_GROUP_WAIT_BITS_END`, owed to `caller` when the
514 /// `xTaskResumeAll` before it has already handed the CPU on.
515 fn trace_wait_bits_end(
516 &mut self,
517 caller: TaskHandle,
518 group: EventGroupHandle,
519 bits: u32,
520 timed_out: bool,
521 ) {
522 self.trace_failure_or_owe(
523 caller,
524 OwedTrace::EventGroupWaitBitsEnd {
525 group,
526 bits,
527 timed_out,
528 },
529 );
530 }
531}
532
533// ================================================================ tests ==
534
535/// `events.rs` had no unit test at all (`docs/HOLES.md`, H3).
536///
537/// `EventGroupsDemo` does cover this file against the C, so unlike
538/// `timer.rs` and `stream.rs` these are not the only evidence there is.
539/// What they add is ISOLATION: the scenario exercises the whole file at
540/// once and a divergence points at a trace line, whereas each of these
541/// names one return-value contract and fails on its own.
542///
543/// The two worth reading are the ones about what a call ANSWERS, because
544/// both return a bit set that a caller is likely to assume is something
545/// else.
546#[cfg(test)]
547#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
548mod tests {
549 use rusty_rtos_core::config::Config;
550 use rusty_rtos_core::hooks::NoTickHook;
551
552 use crate::events::{PENDED_CLEAR_BITS, PENDED_SET_BITS};
553 use crate::queue::Wait;
554 use crate::system::tests::{NoTrace, TestConfig, TestPort};
555
556 /// Three tasks, one queue for the timer daemon, and two event groups.
557 /// The ISR half of this API defers through the timer command queue, so
558 /// a timer slot has to exist even though no timer is ever created.
559 type K = crate::Kernel<
560 TestConfig,
561 TestPort,
562 NoTrace,
563 NoTickHook,
564 4,
565 { crate::list_slots_for(4, 1, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 2)) },
566 { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 2) },
567 1,
568 2,
569 0,
570 0,
571 1,
572 2,
573 { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
574 >;
575
576 fn kernel() -> K {
577 K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
578 }
579
580 /// A started kernel with the daemon PARKED, so work it defers stays
581 /// deferred until a test asks for it.
582 fn started() -> K {
583 let mut k = kernel();
584 let h = k.start_scheduler().expect("start");
585 k.suspend(Some(h.timer)).expect("park the daemon");
586 k
587 }
588
589 /// `xEventGroupClearBits`:
590 ///
591 /// ```c
592 /// /* The value returned is the event group value prior to the bits being
593 /// * cleared. */
594 /// uxReturn = pxEventBits->uxEventBits;
595 /// pxEventBits->uxEventBits &= ~uxBitsToClear;
596 /// ```
597 ///
598 /// BEFORE, not after -- so the return value still contains the bits the
599 /// call just cleared, and a caller who reads it as "what is left" has
600 /// it exactly backwards.
601 #[test]
602 fn clear_bits_answers_the_value_from_before_the_clear() {
603 let mut k = kernel();
604 let g = k.event_group_create().expect("a group");
605 k.event_group_set_bits(g, 0b1111).expect("set");
606
607 assert_eq!(
608 k.event_group_clear_bits(g, 0b0101),
609 Ok(0b1111),
610 "the value BEFORE: it still has the bits being cleared in it"
611 );
612 assert_eq!(
613 k.event_group_bits(g),
614 Ok(0b1010),
615 "and this is what is actually left"
616 );
617 }
618
619 /// `xEventGroupSetBits` answers the value AFTER any waiter it just
620 /// unblocked has taken its bits away:
621 ///
622 /// ```c
623 /// if( xMatchFound != pdFALSE ) {
624 /// if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != 0 ) {
625 /// uxBitsToClear |= uxBitsWaitedFor;
626 /// }
627 /// ...
628 /// }
629 /// pxEventBits->uxEventBits &= ~uxBitsToClear;
630 /// uxReturnBits = pxEventBits->uxEventBits;
631 /// ```
632 ///
633 /// So **a set can return a value that does not contain the bit it just
634 /// set.** The waiter woke inside the call, its clear-on-exit ran, and
635 /// the snapshot is taken afterwards. A caller that asserts the returned
636 /// value has its own bit in it is writing a race.
637 #[test]
638 fn set_bits_answers_a_value_a_woken_waiter_has_already_cleared() {
639 let mut k = kernel();
640 let g = k.event_group_create().expect("a group");
641 k.create_task("w", 1).expect("a waiter");
642 let h = k.start_scheduler().expect("start");
643 k.suspend(Some(h.timer)).expect("park the daemon");
644
645 // Get the waiter onto the CPU and block it with CLEAR ON EXIT.
646 let mut blocked = false;
647 for _ in 0..50_u32 {
648 let running = k.name_of(k.current()).expect("a name");
649 if running.as_str() == "w" {
650 assert_eq!(
651 k.event_group_wait_bits(g, 0b0001, true, false, 20),
652 Ok(Wait::Blocked)
653 );
654 blocked = true;
655 break;
656 }
657 k.switch_context();
658 }
659 assert!(blocked, "never got the waiter onto the CPU");
660
661 // Set the bit it is waiting for, from another context.
662 assert_eq!(
663 k.event_group_set_bits(g, 0b0001),
664 Ok(0b0000),
665 "the bit was set, the waiter matched, its clear-on-exit ran, \
666 and the snapshot came after all of that"
667 );
668 assert_eq!(k.event_group_bits(g), Ok(0b0000));
669 }
670
671 /// The same set with a waiter that does NOT clear on exit leaves the
672 /// bit where it is -- which is the control test for the one above, and
673 /// the reason the surprise is about clear-on-exit and not about
674 /// waking.
675 #[test]
676 fn set_bits_keeps_the_bit_when_the_waiter_does_not_clear_on_exit() {
677 let mut k = kernel();
678 let g = k.event_group_create().expect("a group");
679 k.create_task("w", 1).expect("a waiter");
680 let h = k.start_scheduler().expect("start");
681 k.suspend(Some(h.timer)).expect("park the daemon");
682
683 let mut blocked = false;
684 for _ in 0..50_u32 {
685 let running = k.name_of(k.current()).expect("a name");
686 if running.as_str() == "w" {
687 assert_eq!(
688 k.event_group_wait_bits(g, 0b0001, false, false, 20),
689 Ok(Wait::Blocked)
690 );
691 blocked = true;
692 break;
693 }
694 k.switch_context();
695 }
696 assert!(blocked, "never got the waiter onto the CPU");
697
698 assert_eq!(
699 k.event_group_set_bits(g, 0b0001),
700 Ok(0b0001),
701 "no clear-on-exit, so the bit is still there when the set returns"
702 );
703 }
704
705 /// `xWaitForAllBits`: ANY is a non-empty intersection, ALL is a
706 /// superset. With the bits already present neither call blocks, so
707 /// this isolates the predicate from the blocking machinery.
708 #[test]
709 fn wait_for_all_needs_every_bit_and_wait_for_any_needs_one() {
710 let mut k = kernel();
711 let g = k.event_group_create().expect("a group");
712 k.event_group_set_bits(g, 0b0001).expect("set one of two");
713
714 // ANY, with one of the two present: satisfied at once.
715 assert_eq!(
716 k.event_group_wait_bits(g, 0b0011, false, false, 0),
717 Ok(Wait::Ready(0b0001)),
718 "one of the two is enough for ANY"
719 );
720
721 // ALL, with the same bits: not satisfied, and a zero block time
722 // means it gives up immediately and reports what it found.
723 assert_eq!(
724 k.event_group_wait_bits(g, 0b0011, false, true, 0),
725 Ok(Wait::Ready(0b0001)),
726 "ALL is not met, and the answer is still the CURRENT bits -- \
727 the return value does not say whether the wait succeeded"
728 );
729
730 k.event_group_set_bits(g, 0b0010).expect("set the other");
731 assert_eq!(
732 k.event_group_wait_bits(g, 0b0011, false, true, 0),
733 Ok(Wait::Ready(0b0011)),
734 "now ALL is met"
735 );
736 }
737
738 /// Clear-on-exit clears only the bits that were WAITED FOR, not the
739 /// whole group -- so an unrelated bit set by someone else survives a
740 /// wait that consumed its own.
741 #[test]
742 fn clear_on_exit_takes_only_the_bits_that_were_waited_for() {
743 let mut k = kernel();
744 let g = k.event_group_create().expect("a group");
745 k.event_group_set_bits(g, 0b1101).expect("set");
746
747 assert_eq!(
748 k.event_group_wait_bits(g, 0b0001, true, false, 0),
749 Ok(Wait::Ready(0b1101)),
750 "the answer is the value at the moment the wait was satisfied"
751 );
752 assert_eq!(
753 k.event_group_bits(g),
754 Ok(0b1100),
755 "and only bit 0 was taken: the other two were nobody's business"
756 );
757 }
758
759 /// ★ A group's waiting list lives in a SHARED array indexed by the group's
760 /// arena slot, so a new group is handed whatever list the last group at
761 /// that index left behind. C has no such hazard -- its list is a field of
762 /// freshly-`pvPortMalloc`'d memory, which is why `xEventGroupCreate` calls
763 /// `vListInitialise` on it.
764 ///
765 /// `event_group_create` used to mirror that literally, draining the list on
766 /// every create. It does not need to: `event_group_delete` unblocks every
767 /// waiter before it discards the slot, so the list is already empty. The
768 /// drain was worth **84 bytes of flash** (2026-09-25) and this test is the
769 /// entire reason it is safe to have removed it.
770 ///
771 /// Without a BLOCKED waiter this proves nothing -- an empty list is empty
772 /// either way -- so the waiter here is real and on the CPU, and the middle
773 /// assertion checks the list is genuinely non-empty before the delete.
774 #[test]
775 fn a_reused_group_slot_does_not_inherit_the_last_groups_waiters() {
776 let mut k = kernel();
777 let g = k.event_group_create().expect("a group");
778 k.create_task("w", 1).expect("a waiter");
779 let h = k.start_scheduler().expect("start");
780 k.suspend(Some(h.timer)).expect("park the daemon");
781
782 let list = K::event_group_list(g);
783 let mut blocked = false;
784 for _ in 0..50_u32 {
785 if k.name_of(k.current()).expect("a name").as_str() == "w" {
786 assert_eq!(
787 k.event_group_wait_bits(g, 0b0011, false, true, 50),
788 Ok(Wait::Blocked),
789 "ALL of two bits, neither set"
790 );
791 blocked = true;
792 break;
793 }
794 k.switch_context();
795 }
796 assert!(blocked, "never got the waiter onto the CPU");
797 assert!(
798 k.lists.head(list).expect("a list").is_some(),
799 "the premise: a blocked waiter IS on the group's list, so the list this test is about is not trivially empty"
800 );
801
802 k.event_group_delete(g).expect("delete");
803 assert!(
804 k.lists.head(list).expect("a list").is_none(),
805 "delete unblocks every waiter, so it leaves the list empty -- this is the invariant that replaced create's drain"
806 );
807
808 let g2 = k.event_group_create().expect("a second group");
809 assert_eq!(
810 g2.index(),
811 g.index(),
812 "the premise of the hazard: the arena reused the same slot, so both groups name the SAME list"
813 );
814 assert!(
815 k.lists
816 .head(K::event_group_list(g2))
817 .expect("a list")
818 .is_none(),
819 "and the fresh group has inherited no waiters"
820 );
821 }
822
823 /// A group starts with no bits set, and delete does not leave the
824 /// handle usable.
825 #[test]
826 fn a_new_group_is_empty_and_a_deleted_one_is_gone() {
827 let mut k = kernel();
828 let g = k.event_group_create().expect("a group");
829 assert_eq!(k.event_group_bits(g), Ok(0));
830
831 k.event_group_delete(g).expect("delete");
832 assert!(
833 k.event_group_bits(g).is_err(),
834 "a stale handle is an error, not a zero"
835 );
836 }
837 /// The ALL/ANY predicate, with a detector that can actually SEE the
838 /// difference.
839 ///
840 /// `prvTestWaitCondition`:
841 ///
842 /// ```c
843 /// if( xWaitForAllBits == pdFALSE ) {
844 /// if( ( uxCurrentEventBits & uxBitsToWaitFor ) != 0 ) { xWaitConditionMet = pdTRUE; }
845 /// } else {
846 /// if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor ) { xWaitConditionMet = pdTRUE; }
847 /// }
848 /// ```
849 ///
850 /// The earlier version of this test compared RETURN VALUES, and with a
851 /// zero block time an unsatisfied wait answers the current bits just
852 /// like a satisfied one -- so it could not tell the two apart, and
853 /// `cargo mutants` proved it: `&` to `|`, `&` to `^` and `==` to `!=`
854 /// all survived it.
855 ///
856 /// CLEAR-ON-EXIT is the detector. It runs only when the wait was
857 /// satisfied, so the bits afterwards say which branch was taken.
858 #[test]
859 fn the_all_and_any_predicates_decide_whether_clear_on_exit_runs() {
860 // ANY, one of two bits present: satisfied, so clear-on-exit runs.
861 let mut k = kernel();
862 let g = k.event_group_create().expect("a group");
863 k.event_group_set_bits(g, 0b0001).expect("set");
864 k.event_group_wait_bits(g, 0b0011, true, false, 0)
865 .expect("wait");
866 assert_eq!(
867 k.event_group_bits(g),
868 Ok(0b0000),
869 "ANY was satisfied by one bit, so clear-on-exit took it"
870 );
871
872 // ALL, one of two bits present: NOT satisfied, so nothing is taken.
873 let mut k = kernel();
874 let g = k.event_group_create().expect("a group");
875 k.event_group_set_bits(g, 0b0001).expect("set");
876 k.event_group_wait_bits(g, 0b0011, true, true, 0)
877 .expect("wait");
878 assert_eq!(
879 k.event_group_bits(g),
880 Ok(0b0001),
881 "ALL was NOT satisfied, so clear-on-exit did not run"
882 );
883
884 // ALL, both bits present: satisfied, and only the waited-for bits go.
885 let mut k = kernel();
886 let g = k.event_group_create().expect("a group");
887 k.event_group_set_bits(g, 0b1011).expect("set");
888 k.event_group_wait_bits(g, 0b0011, true, true, 0)
889 .expect("wait");
890 assert_eq!(
891 k.event_group_bits(g),
892 Ok(0b1000),
893 "ALL satisfied: bits 0 and 1 taken, bit 3 was nobody's business"
894 );
895 }
896
897 /// `xEventGroupSetBitsFromISR` does not set any bits.
898 ///
899 /// ```c
900 /// xReturn = xTimerPendFunctionCallFromISR( &vEventGroupSetBitsCallback,
901 /// ( void * ) xEventGroup,
902 /// ( uint32_t ) uxBitsToSet,
903 /// pxHigherPriorityTaskWoken );
904 /// ```
905 ///
906 /// The whole body is a deferral to the timer daemon, so the answer is
907 /// "the callback was queued" and the group is untouched until the
908 /// daemon runs it. An ISR that sets a bit and an ISR that asks for a
909 /// bit to be set are different things, and this is the second.
910 #[test]
911 fn set_bits_from_isr_only_queues_the_work() {
912 let mut k = started();
913 let g = k.event_group_create().expect("a group");
914
915 let (queued, _woken) = k.event_group_set_bits_from_isr(g, 0b0101).expect("isr");
916 assert!(queued, "the callback was queued");
917 assert_eq!(
918 k.event_group_bits(g),
919 Ok(0),
920 "and NOTHING is set yet: the daemon has not run"
921 );
922
923 // The daemon's half, which is what `TickHook::pended` routes to.
924 k.event_group_pended_call(PENDED_SET_BITS, u64::from(g.index()), 0b0101)
925 .expect("the daemon runs the callback");
926 assert_eq!(k.event_group_bits(g), Ok(0b0101));
927 }
928
929 /// `xEventGroupClearBitsFromISR` is the same deferral, with the
930 /// clearing callback.
931 #[test]
932 fn clear_bits_from_isr_only_queues_the_work() {
933 let mut k = started();
934 let g = k.event_group_create().expect("a group");
935 k.event_group_set_bits(g, 0b1111).expect("set");
936
937 let (queued, _woken) = k.event_group_clear_bits_from_isr(g, 0b0101).expect("isr");
938 assert!(queued, "the callback was queued");
939 assert_eq!(
940 k.event_group_bits(g),
941 Ok(0b1111),
942 "and nothing is cleared yet"
943 );
944
945 k.event_group_pended_call(PENDED_CLEAR_BITS, u64::from(g.index()), 0b0101)
946 .expect("the daemon runs the callback");
947 assert_eq!(k.event_group_bits(g), Ok(0b1010));
948 }
949
950 /// `xEventGroupGetBitsFromISR` is the odd one out: it reads the bits
951 /// DIRECTLY under an interrupt-safe critical section, with no
952 /// deferral, so it is the only ISR call here whose answer is current.
953 #[test]
954 fn bits_from_isr_reads_directly_and_is_not_deferred() {
955 let mut k = started();
956 let g = k.event_group_create().expect("a group");
957 assert_eq!(k.event_group_bits_from_isr(g), Ok(0));
958
959 k.event_group_set_bits(g, 0b0110).expect("set from a task");
960 assert_eq!(
961 k.event_group_bits_from_isr(g),
962 Ok(0b0110),
963 "read straight through, unlike set and clear"
964 );
965 assert_eq!(k.event_group_bits_from_isr(g), k.event_group_bits(g));
966 }
967
968 /// A pended call naming a group that does not exist is an error, not a
969 /// silent no-op: the daemon runs these long after the ISR that asked,
970 /// and the group can have been deleted in between.
971 #[test]
972 fn a_pended_call_for_a_deleted_group_is_an_error() {
973 let mut k = started();
974 let g = k.event_group_create().expect("a group");
975 let index = u64::from(g.index());
976 k.event_group_delete(g).expect("delete");
977
978 assert!(
979 k.event_group_pended_call(PENDED_SET_BITS, index, 0b0001)
980 .is_err(),
981 "the slot is empty and the daemon must not write into it"
982 );
983 }
984 /// `xEventGroupSync` when the rendezvous completes on the spot.
985 ///
986 /// ```c
987 /// uxOriginalBitValue = pxEventBits->uxEventBits;
988 /// ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet );
989 /// if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor )
990 /// {
991 /// uxReturn = ( uxOriginalBitValue | uxBitsToSet );
992 /// pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
993 /// xTicksToWait = 0;
994 /// }
995 /// ```
996 ///
997 /// The answer is the value from BEFORE the clear -- it still contains
998 /// the bits the call is about to take away, and it contains the ones
999 /// this caller just set. Reading it as "what is left in the group" is
1000 /// exactly wrong, twice over.
1001 #[test]
1002 fn a_sync_that_completes_answers_the_value_from_before_it_clears() {
1003 let mut k = kernel();
1004 let g = k.event_group_create().expect("a group");
1005 k.event_group_set_bits(g, 0b0001)
1006 .expect("the other half arrived");
1007
1008 assert_eq!(
1009 k.event_group_sync(g, 0b0010, 0b0011, 0),
1010 Ok(Wait::Ready(0b0011)),
1011 "original | set, INCLUDING the bits it is about to clear"
1012 );
1013 assert_eq!(
1014 k.event_group_bits(g),
1015 Ok(0b0000),
1016 "and the rendezvous bits are gone: sync always clears on exit"
1017 );
1018 }
1019
1020 /// The bits are set EVEN WHEN the rendezvous does not complete, which
1021 /// is the whole point of a rendezvous: this caller's arrival has to be
1022 /// visible to the participants who have not arrived yet.
1023 ///
1024 /// The C sets them unconditionally, before it tests the condition.
1025 #[test]
1026 fn a_sync_that_does_not_complete_still_leaves_its_own_bits_set() {
1027 let mut k = kernel();
1028 let g = k.event_group_create().expect("a group");
1029
1030 assert_eq!(
1031 k.event_group_sync(g, 0b0001, 0b0011, 0),
1032 Ok(Wait::Ready(0b0001)),
1033 "not satisfied, so the answer is the CURRENT bits"
1034 );
1035 assert_eq!(
1036 k.event_group_bits(g),
1037 Ok(0b0001),
1038 "and this caller's arrival is still recorded for the others"
1039 );
1040 }
1041
1042 /// A sync takes only the bits it waited for, and leaves anything else
1043 /// in the group alone.
1044 #[test]
1045 fn a_sync_clears_only_its_own_rendezvous_bits() {
1046 let mut k = kernel();
1047 let g = k.event_group_create().expect("a group");
1048 k.event_group_set_bits(g, 0b1000)
1049 .expect("somebody else's bit");
1050
1051 assert_eq!(
1052 k.event_group_sync(g, 0b0001, 0b0001, 0),
1053 Ok(Wait::Ready(0b1001)),
1054 "the answer carries the unrelated bit too"
1055 );
1056 assert_eq!(
1057 k.event_group_bits(g),
1058 Ok(0b1000),
1059 "and the unrelated bit survives the clear"
1060 );
1061 }
1062
1063 /// The WHOLE round trip of a blocked wait: block, be woken by a set,
1064 /// and then RUN AGAIN to take the completion path.
1065 ///
1066 /// The earlier tests here stopped at the wake-up and never resumed the
1067 /// waiter, so `finish_wait` -- everything that decides what a resumed
1068 /// wait ANSWERS -- was never reached at all. `cargo mutants` found it
1069 /// as a dozen survivors in one function.
1070 #[test]
1071 fn a_woken_waiter_resumes_and_is_told_which_bits_satisfied_it() {
1072 // NOT `started()`: this creates its own task before starting, and
1073 // the scheduler can only be started once.
1074 let mut k = kernel();
1075 let g = k.event_group_create().expect("a group");
1076 k.create_task("w", 1).expect("a waiter");
1077 let h = k.start_scheduler().expect("start");
1078 k.suspend(Some(h.timer)).expect("park the daemon");
1079
1080 // Get the waiter onto the CPU and block it, clearing on exit.
1081 let mut blocked = false;
1082 for _ in 0..50_u32 {
1083 if k.name_of(k.current()).expect("a name").as_str() == "w" {
1084 assert_eq!(
1085 k.event_group_wait_bits(g, 0b0011, true, true, 50),
1086 Ok(Wait::Blocked),
1087 "ALL of two bits, neither set yet"
1088 );
1089 blocked = true;
1090 break;
1091 }
1092 k.switch_context();
1093 }
1094 assert!(blocked, "never got the waiter onto the CPU");
1095
1096 // One bit is not enough for an ALL wait: it must stay blocked.
1097 k.event_group_set_bits(g, 0b0001).expect("half of it");
1098 assert_eq!(
1099 k.event_group_bits(g),
1100 Ok(0b0001),
1101 "one bit does not satisfy ALL, so nothing was consumed"
1102 );
1103
1104 // The second completes it, and the waiter's clear-on-exit runs.
1105 k.event_group_set_bits(g, 0b0010).expect("the other half");
1106 assert_eq!(
1107 k.event_group_bits(g),
1108 Ok(0b0000),
1109 "both bits matched, so the waiter took them"
1110 );
1111
1112 // Now RESUME it: the same call at the same pc takes the finish path.
1113 let mut finished = false;
1114 for _ in 0..50_u32 {
1115 if k.name_of(k.current()).expect("a name").as_str() == "w" {
1116 assert_eq!(
1117 k.event_group_wait_bits(g, 0b0011, true, true, 50),
1118 Ok(Wait::Ready(0b0011)),
1119 "it is told the bits that satisfied it, not what is \
1120 left in the group after its own clear"
1121 );
1122 finished = true;
1123 break;
1124 }
1125 k.switch_context();
1126 }
1127 assert!(finished, "the waiter never ran again");
1128 }
1129
1130 /// A real two-task rendezvous, which is the only way to reach
1131 /// `finish_sync` -- the path that decides what a BLOCKED sync answers
1132 /// when somebody else completes it.
1133 ///
1134 /// `cargo mutants` left sixteen survivors in that one function after
1135 /// the three single-task sync tests, for the same reason `finish_wait`
1136 /// had twelve: nothing ever blocked on a sync and then ran again.
1137 ///
1138 /// The C blocks the first arrival with
1139 /// `uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS`,
1140 /// so a rendezvous is always ALL-bits and always clears.
1141 #[test]
1142 fn two_tasks_rendezvous_and_the_one_that_waited_is_told_it_completed() {
1143 let mut k = kernel();
1144 let g = k.event_group_create().expect("a group");
1145 k.create_task("a", 1).expect("first arrival");
1146 k.create_task("b", 1).expect("second arrival");
1147 let h = k.start_scheduler().expect("start");
1148 k.suspend(Some(h.timer)).expect("park the daemon");
1149
1150 const A: u32 = 0b0001;
1151 const B: u32 = 0b0010;
1152 const BOTH: u32 = A | B;
1153
1154 // `a` arrives first: it sets its own bit and blocks on both.
1155 let mut waited = false;
1156 for _ in 0..50_u32 {
1157 if k.name_of(k.current()).expect("a name").as_str() == "a" {
1158 assert_eq!(
1159 k.event_group_sync(g, A, BOTH, 50),
1160 Ok(Wait::Blocked),
1161 "only one of the two has arrived"
1162 );
1163 waited = true;
1164 break;
1165 }
1166 k.switch_context();
1167 }
1168 assert!(waited, "task a never reached the CPU");
1169 assert_eq!(
1170 k.event_group_bits(g),
1171 Ok(A),
1172 "and its arrival is recorded while it waits"
1173 );
1174
1175 // `b` arrives second: the rendezvous completes inside ITS call.
1176 let mut completed = false;
1177 for _ in 0..50_u32 {
1178 if k.name_of(k.current()).expect("a name").as_str() == "b" {
1179 assert_eq!(
1180 k.event_group_sync(g, B, BOTH, 50),
1181 Ok(Wait::Ready(BOTH)),
1182 "the second arrival sees both and does not block"
1183 );
1184 completed = true;
1185 break;
1186 }
1187 k.switch_context();
1188 }
1189 assert!(completed, "task b never reached the CPU");
1190 assert_eq!(
1191 k.event_group_bits(g),
1192 Ok(0),
1193 "the rendezvous bits are consumed once, not twice"
1194 );
1195
1196 // `a` resumes and takes the completion path.
1197 let mut resumed = false;
1198 for _ in 0..50_u32 {
1199 if k.name_of(k.current()).expect("a name").as_str() == "a" {
1200 assert_eq!(
1201 k.event_group_sync(g, A, BOTH, 50),
1202 Ok(Wait::Ready(BOTH)),
1203 "it is told the rendezvous completed, even though the group is empty again by the time it runs"
1204 );
1205 resumed = true;
1206 break;
1207 }
1208 k.switch_context();
1209 }
1210 assert!(resumed, "task a never ran again");
1211 }
1212}