Skip to main content

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