freertos-in-rust 0.1.0

FreeRTOS kernel ported to Rust - no_std, no C FFI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
/*
 * FreeRTOS Kernel <DEVELOPMENT BRANCH>
 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * SPDX-License-Identifier: MIT
 *
 * [AMENDMENT] This module is the Rust port of event_groups.c.
 * It provides event group functionality for FreeRTOS.
 * Event groups allow tasks to wait on combinations of event bits.
 */

//! Event Groups Implementation
//!
//! This module provides event groups for FreeRTOS.
//! An event group is a collection of bits that tasks can wait on.
//!
//! ## Key Concepts
//!
//! - Each event group contains 24 usable bits (32-bit ticks) or 8 bits (16-bit)
//! - Tasks can wait for any or all of a set of bits to be set
//! - Bits can be set from tasks or ISRs
//! - Bits can be cleared automatically when a task unblocks
//!
//! ## API Functions
//!
//! - [`xEventGroupCreate`] / [`xEventGroupCreateStatic`] - Create an event group
//! - [`xEventGroupWaitBits`] - Wait for bits to be set
//! - [`xEventGroupSetBits`] - Set bits in the event group
//! - [`xEventGroupClearBits`] - Clear bits in the event group
//! - [`xEventGroupSync`] - Synchronization (rendezvous) point

#![allow(unused_variables)]
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(static_mut_refs)]

use core::ffi::c_void;
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
use core::ptr;

use crate::config::*;
use crate::kernel::list::*;
use crate::kernel::tasks::*;
use crate::memory::*;
use crate::trace::*;
use crate::types::*;

// =============================================================================
// Event Bits Control Constants
// =============================================================================

/// Clear events on exit bit (stored in event list item value)
#[cfg(feature = "tick-16bit")]
pub const eventCLEAR_EVENTS_ON_EXIT_BIT: EventBits_t = 0x0100;

#[cfg(all(not(feature = "tick-16bit"), not(feature = "tick-64bit")))]
pub const eventCLEAR_EVENTS_ON_EXIT_BIT: EventBits_t = 0x0100_0000;

#[cfg(feature = "tick-64bit")]
pub const eventCLEAR_EVENTS_ON_EXIT_BIT: EventBits_t = 0x0100_0000_0000_0000;

/// Bit set to indicate task was unblocked due to bit set (not timeout)
#[cfg(feature = "tick-16bit")]
pub const eventUNBLOCKED_DUE_TO_BIT_SET: EventBits_t = 0x0200;

#[cfg(all(not(feature = "tick-16bit"), not(feature = "tick-64bit")))]
pub const eventUNBLOCKED_DUE_TO_BIT_SET: EventBits_t = 0x0200_0000;

#[cfg(feature = "tick-64bit")]
pub const eventUNBLOCKED_DUE_TO_BIT_SET: EventBits_t = 0x0200_0000_0000_0000;

/// Wait for all bits (AND vs OR wait condition)
#[cfg(feature = "tick-16bit")]
pub const eventWAIT_FOR_ALL_BITS: EventBits_t = 0x0400;

#[cfg(all(not(feature = "tick-16bit"), not(feature = "tick-64bit")))]
pub const eventWAIT_FOR_ALL_BITS: EventBits_t = 0x0400_0000;

#[cfg(feature = "tick-64bit")]
pub const eventWAIT_FOR_ALL_BITS: EventBits_t = 0x0400_0000_0000_0000;

/// Mask for control bytes (top 8 bits of EventBits_t)
#[cfg(feature = "tick-16bit")]
pub const eventEVENT_BITS_CONTROL_BYTES: EventBits_t = 0xFF00;

#[cfg(all(not(feature = "tick-16bit"), not(feature = "tick-64bit")))]
pub const eventEVENT_BITS_CONTROL_BYTES: EventBits_t = 0xFF00_0000;

#[cfg(feature = "tick-64bit")]
pub const eventEVENT_BITS_CONTROL_BYTES: EventBits_t = 0xFF00_0000_0000_0000;

// =============================================================================
// Type Definitions
// =============================================================================

/// EventBits_t is the same as TickType_t
pub type EventBits_t = TickType_t;

// =============================================================================
// Event Group Structure
// =============================================================================

/// Event Group Control Block
#[repr(C)]
pub struct EventGroupDef_t {
    /// The current event bits
    pub uxEventBits: EventBits_t,

    /// List of tasks waiting for bits
    pub xTasksWaitingForBits: List_t,

    /// Trace facility number
    #[cfg(feature = "trace-facility")]
    pub uxEventGroupNumber: UBaseType_t,

    /// Whether statically allocated
    #[cfg(any(feature = "alloc", feature = "heap-4", feature = "heap-5"))]
    pub ucStaticallyAllocated: u8,
}

/// Type alias for EventGroupDef_t
pub type EventGroup_t = EventGroupDef_t;

// =============================================================================
// Static Event Group (for static allocation)
// =============================================================================

/// Static buffer for event group allocation
#[repr(C)]
pub struct StaticEventGroup_t {
    /// Placeholder - event bits
    pub xDummy1: EventBits_t,
    /// Placeholder - list
    pub xDummy2: StaticList_t,
    /// Placeholder - trace number
    #[cfg(feature = "trace-facility")]
    pub uxDummy3: UBaseType_t,
    /// Placeholder - static flag
    #[cfg(any(feature = "alloc", feature = "heap-4", feature = "heap-5"))]
    pub ucDummy4: u8,
}

/// Static list placeholder type
#[repr(C)]
pub struct StaticList_t {
    _data: List_t,
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Coverage test marker (no-op)
#[inline(always)]
fn mtCOVERAGE_TEST_MARKER() {}

// =============================================================================
// Event Group Creation
// =============================================================================

/// Create an event group (dynamic allocation)
#[cfg(any(feature = "alloc", feature = "heap-4", feature = "heap-5"))]
pub fn xEventGroupCreate() -> EventGroupHandle_t {
    traceENTER_xEventGroupCreate();

    let pxEventBits: *mut EventGroup_t =
        unsafe { pvPortMalloc(core::mem::size_of::<EventGroup_t>()) as *mut EventGroup_t };

    if !pxEventBits.is_null() {
        unsafe {
            (*pxEventBits).uxEventBits = 0;
            vListInitialise(&mut (*pxEventBits).xTasksWaitingForBits);
            (*pxEventBits).ucStaticallyAllocated = pdFALSE as u8;
        }

        traceEVENT_GROUP_CREATE(pxEventBits as *mut c_void);
    } else {
        traceEVENT_GROUP_CREATE_FAILED();
    }

    traceRETURN_xEventGroupCreate(pxEventBits);

    pxEventBits as EventGroupHandle_t
}

/// Create an event group (static allocation)
pub fn xEventGroupCreateStatic(pxEventGroupBuffer: *mut StaticEventGroup_t) -> EventGroupHandle_t {
    traceENTER_xEventGroupCreateStatic(pxEventGroupBuffer);

    configASSERT(!pxEventGroupBuffer.is_null());

    // Verify StaticEventGroup_t is same size as EventGroup_t
    #[cfg(debug_assertions)]
    {
        let static_size = core::mem::size_of::<StaticEventGroup_t>();
        let event_group_size = core::mem::size_of::<EventGroup_t>();
        configASSERT(static_size == event_group_size);
    }

    let pxEventBits = pxEventGroupBuffer as *mut EventGroup_t;

    if !pxEventBits.is_null() {
        unsafe {
            (*pxEventBits).uxEventBits = 0;
            vListInitialise(&mut (*pxEventBits).xTasksWaitingForBits);

            #[cfg(any(feature = "alloc", feature = "heap-4", feature = "heap-5"))]
            {
                (*pxEventBits).ucStaticallyAllocated = pdTRUE as u8;
            }
        }

        traceEVENT_GROUP_CREATE(pxEventBits as *mut c_void);
    } else {
        traceEVENT_GROUP_CREATE_FAILED();
    }

    traceRETURN_xEventGroupCreateStatic(pxEventBits);

    pxEventBits as EventGroupHandle_t
}

// =============================================================================
// Event Group Wait Functions
// =============================================================================

/// Wait for bits to be set in an event group
///
/// # Arguments
/// * `xEventGroup` - Event group handle
/// * `uxBitsToWaitFor` - Bits to wait for
/// * `xClearOnExit` - Clear bits when unblocking
/// * `xWaitForAllBits` - Wait for all bits (AND) or any bit (OR)
/// * `xTicksToWait` - Block time
///
/// # Returns
/// The event bits value when unblocked (or timed out)
pub fn xEventGroupWaitBits(
    xEventGroup: EventGroupHandle_t,
    uxBitsToWaitFor: EventBits_t,
    xClearOnExit: BaseType_t,
    xWaitForAllBits: BaseType_t,
    mut xTicksToWait: TickType_t,
) -> EventBits_t {
    let pxEventBits = xEventGroup as *mut EventGroup_t;
    let mut uxReturn: EventBits_t;
    let mut uxControlBits: EventBits_t = 0;
    let xWaitConditionMet: BaseType_t;
    let xAlreadyYielded: BaseType_t;
    let mut xTimeoutOccurred: BaseType_t = pdFALSE;

    traceENTER_xEventGroupWaitBits(
        xEventGroup,
        uxBitsToWaitFor,
        xClearOnExit,
        xWaitForAllBits,
        xTicksToWait,
    );

    configASSERT(!xEventGroup.is_null());
    configASSERT((uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES) == 0);
    configASSERT(uxBitsToWaitFor != 0);

    vTaskSuspendAll();

    unsafe {
        let uxCurrentEventBits = (*pxEventBits).uxEventBits;

        xWaitConditionMet =
            prvTestWaitCondition(uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits);

        if xWaitConditionMet != pdFALSE {
            uxReturn = uxCurrentEventBits;
            xTicksToWait = 0;

            if xClearOnExit != pdFALSE {
                (*pxEventBits).uxEventBits &= !uxBitsToWaitFor;
            }
        } else if xTicksToWait == 0 {
            uxReturn = uxCurrentEventBits;
            xTimeoutOccurred = pdTRUE;
        } else {
            if xClearOnExit != pdFALSE {
                uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;
            }
            if xWaitForAllBits != pdFALSE {
                uxControlBits |= eventWAIT_FOR_ALL_BITS;
            }

            vTaskPlaceOnUnorderedEventList(
                &mut (*pxEventBits).xTasksWaitingForBits,
                uxBitsToWaitFor | uxControlBits,
                xTicksToWait,
            );

            uxReturn = 0;

            traceEVENT_GROUP_WAIT_BITS_BLOCK(
                xEventGroup as *mut c_void,
                uxBitsToWaitFor as UBaseType_t,
            );
        }
    }

    xAlreadyYielded = xTaskResumeAll();

    if xTicksToWait != 0 {
        if xAlreadyYielded == pdFALSE {
            portYIELD_WITHIN_API();
        }

        uxReturn = uxTaskResetEventItemValue();

        if (uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET) == 0 {
            taskENTER_CRITICAL();
            unsafe {
                uxReturn = (*pxEventBits).uxEventBits;

                if prvTestWaitCondition(uxReturn, uxBitsToWaitFor, xWaitForAllBits) != pdFALSE {
                    if xClearOnExit != pdFALSE {
                        (*pxEventBits).uxEventBits &= !uxBitsToWaitFor;
                    }
                }

                xTimeoutOccurred = pdTRUE;
            }
            taskEXIT_CRITICAL();
        }

        uxReturn &= !eventEVENT_BITS_CONTROL_BYTES;
    }

    traceEVENT_GROUP_WAIT_BITS_END(
        xEventGroup as *mut c_void,
        uxBitsToWaitFor as UBaseType_t,
        xTimeoutOccurred,
    );

    traceRETURN_xEventGroupWaitBits(uxReturn);

    uxReturn
}

/// Synchronization point (rendezvous)
///
/// Sets bits and then waits for all specified bits to be set.
pub fn xEventGroupSync(
    xEventGroup: EventGroupHandle_t,
    uxBitsToSet: EventBits_t,
    uxBitsToWaitFor: EventBits_t,
    mut xTicksToWait: TickType_t,
) -> EventBits_t {
    let pxEventBits = xEventGroup as *mut EventGroup_t;
    let uxOriginalBitValue: EventBits_t;
    let mut uxReturn: EventBits_t;
    let xAlreadyYielded: BaseType_t;
    let mut xTimeoutOccurred: BaseType_t = pdFALSE;

    traceENTER_xEventGroupSync(xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTicksToWait);

    configASSERT((uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES) == 0);
    configASSERT(uxBitsToWaitFor != 0);

    vTaskSuspendAll();

    unsafe {
        uxOriginalBitValue = (*pxEventBits).uxEventBits;

        let _ = xEventGroupSetBits(xEventGroup, uxBitsToSet);

        if ((uxOriginalBitValue | uxBitsToSet) & uxBitsToWaitFor) == uxBitsToWaitFor {
            uxReturn = uxOriginalBitValue | uxBitsToSet;
            (*pxEventBits).uxEventBits &= !uxBitsToWaitFor;
            xTicksToWait = 0;
        } else {
            if xTicksToWait != 0 {
                traceEVENT_GROUP_SYNC_BLOCK(
                    xEventGroup as *mut c_void,
                    uxBitsToSet as UBaseType_t,
                    uxBitsToWaitFor as UBaseType_t,
                );

                vTaskPlaceOnUnorderedEventList(
                    &mut (*pxEventBits).xTasksWaitingForBits,
                    uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS,
                    xTicksToWait,
                );

                uxReturn = 0;
            } else {
                uxReturn = (*pxEventBits).uxEventBits;
                xTimeoutOccurred = pdTRUE;
            }
        }
    }

    xAlreadyYielded = xTaskResumeAll();

    if xTicksToWait != 0 {
        if xAlreadyYielded == pdFALSE {
            portYIELD_WITHIN_API();
        }

        uxReturn = uxTaskResetEventItemValue();

        if (uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET) == 0 {
            taskENTER_CRITICAL();
            unsafe {
                uxReturn = (*pxEventBits).uxEventBits;

                if (uxReturn & uxBitsToWaitFor) == uxBitsToWaitFor {
                    (*pxEventBits).uxEventBits &= !uxBitsToWaitFor;
                }
            }
            taskEXIT_CRITICAL();

            xTimeoutOccurred = pdTRUE;
        }

        uxReturn &= !eventEVENT_BITS_CONTROL_BYTES;
    }

    traceEVENT_GROUP_SYNC_END(
        xEventGroup as *mut c_void,
        uxBitsToSet as UBaseType_t,
        uxBitsToWaitFor as UBaseType_t,
        xTimeoutOccurred,
    );

    traceRETURN_xEventGroupSync(uxReturn);

    uxReturn
}

// =============================================================================
// Event Group Set/Clear Functions
// =============================================================================

/// Set bits in an event group
///
/// # Arguments
/// * `xEventGroup` - Event group handle
/// * `uxBitsToSet` - Bits to set
///
/// # Returns
/// The event bits value after setting
#[allow(unused_assignments)] // C pattern: initialize to fail
pub fn xEventGroupSetBits(
    xEventGroup: EventGroupHandle_t,
    uxBitsToSet: EventBits_t,
) -> EventBits_t {
    let pxEventBits = xEventGroup as *mut EventGroup_t;
    let mut uxBitsToClear: EventBits_t = 0;
    let mut xMatchFound: BaseType_t = pdFALSE;
    let uxReturnBits: EventBits_t;

    traceENTER_xEventGroupSetBits(xEventGroup, uxBitsToSet);

    configASSERT(!xEventGroup.is_null());
    configASSERT((uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES) == 0);

    unsafe {
        let pxList = &(*pxEventBits).xTasksWaitingForBits;
        let pxListEnd = listGET_END_MARKER(pxList);

        vTaskSuspendAll();

        traceEVENT_GROUP_SET_BITS(xEventGroup as *mut c_void, uxBitsToSet as UBaseType_t);

        let mut pxListItem = listGET_HEAD_ENTRY(pxList);

        (*pxEventBits).uxEventBits |= uxBitsToSet;

        while pxListItem != pxListEnd as *mut ListItem_t {
            let pxNext = listGET_NEXT(pxListItem);
            let mut uxBitsWaitedFor = listGET_LIST_ITEM_VALUE(pxListItem);
            xMatchFound = pdFALSE;

            let uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;
            uxBitsWaitedFor &= !eventEVENT_BITS_CONTROL_BYTES;

            if (uxControlBits & eventWAIT_FOR_ALL_BITS) == 0 {
                // OR wait - any bit matches
                if (uxBitsWaitedFor & (*pxEventBits).uxEventBits) != 0 {
                    xMatchFound = pdTRUE;
                }
            } else if (uxBitsWaitedFor & (*pxEventBits).uxEventBits) == uxBitsWaitedFor {
                // AND wait - all bits match
                xMatchFound = pdTRUE;
            }

            if xMatchFound != pdFALSE {
                if (uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT) != 0 {
                    uxBitsToClear |= uxBitsWaitedFor;
                }

                let _ = xTaskRemoveFromUnorderedEventList(
                    pxListItem,
                    (*pxEventBits).uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET,
                );
            }

            pxListItem = pxNext;
        }

        (*pxEventBits).uxEventBits &= !uxBitsToClear;

        uxReturnBits = (*pxEventBits).uxEventBits;
    }

    let _ = xTaskResumeAll();

    traceRETURN_xEventGroupSetBits(uxReturnBits);

    uxReturnBits
}

/// Clear bits in an event group
///
/// # Arguments
/// * `xEventGroup` - Event group handle
/// * `uxBitsToClear` - Bits to clear
///
/// # Returns
/// The event bits value before clearing
pub fn xEventGroupClearBits(
    xEventGroup: EventGroupHandle_t,
    uxBitsToClear: EventBits_t,
) -> EventBits_t {
    let pxEventBits = xEventGroup as *mut EventGroup_t;
    let uxReturn: EventBits_t;

    traceENTER_xEventGroupClearBits(xEventGroup, uxBitsToClear);

    configASSERT(!xEventGroup.is_null());
    configASSERT((uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES) == 0);

    taskENTER_CRITICAL();
    unsafe {
        traceEVENT_GROUP_CLEAR_BITS(xEventGroup as *mut c_void, uxBitsToClear as UBaseType_t);

        uxReturn = (*pxEventBits).uxEventBits;
        (*pxEventBits).uxEventBits &= !uxBitsToClear;
    }
    taskEXIT_CRITICAL();

    traceRETURN_xEventGroupClearBits(uxReturn);

    uxReturn
}

/// Get bits from an event group (from ISR)
pub fn xEventGroupGetBitsFromISR(xEventGroup: EventGroupHandle_t) -> EventBits_t {
    let pxEventBits = xEventGroup as *const EventGroup_t;
    let uxReturn: EventBits_t;

    traceENTER_xEventGroupGetBitsFromISR(xEventGroup);

    unsafe {
        let uxSavedInterruptStatus = taskENTER_CRITICAL_FROM_ISR();
        uxReturn = (*pxEventBits).uxEventBits;
        taskEXIT_CRITICAL_FROM_ISR(uxSavedInterruptStatus);
    }

    traceRETURN_xEventGroupGetBitsFromISR(uxReturn);

    uxReturn
}

/// Get current bits (convenience function)
#[inline(always)]
pub fn xEventGroupGetBits(xEventGroup: EventGroupHandle_t) -> EventBits_t {
    xEventGroupClearBits(xEventGroup, 0)
}

// =============================================================================
// Event Group Delete
// =============================================================================

/// Delete an event group
pub fn vEventGroupDelete(xEventGroup: EventGroupHandle_t) {
    let pxEventBits = xEventGroup as *mut EventGroup_t;

    traceENTER_vEventGroupDelete(xEventGroup);

    configASSERT(!pxEventBits.is_null());

    unsafe {
        let pxTasksWaitingForBits = &(*pxEventBits).xTasksWaitingForBits;

        vTaskSuspendAll();

        traceEVENT_GROUP_DELETE(xEventGroup as *mut c_void);

        while listCURRENT_LIST_LENGTH(pxTasksWaitingForBits) > 0 {
            configASSERT(
                (*pxTasksWaitingForBits).xListEnd.pxNext
                    != &(*pxTasksWaitingForBits).xListEnd as *const _ as *mut _,
            );

            let _ = xTaskRemoveFromUnorderedEventList(
                (*pxTasksWaitingForBits).xListEnd.pxNext,
                eventUNBLOCKED_DUE_TO_BIT_SET,
            );
        }
    }

    let _ = xTaskResumeAll();

    #[cfg(any(feature = "alloc", feature = "heap-4", feature = "heap-5"))]
    unsafe {
        if (*pxEventBits).ucStaticallyAllocated == pdFALSE as u8 {
            vPortFree(pxEventBits as *mut c_void);
        }
    }

    traceRETURN_vEventGroupDelete();
}

// =============================================================================
// Static Buffer Query
// =============================================================================

/// Get the static buffer used by a statically allocated event group
pub fn xEventGroupGetStaticBuffer(
    xEventGroup: EventGroupHandle_t,
    ppxEventGroupBuffer: *mut *mut StaticEventGroup_t,
) -> BaseType_t {
    let pxEventBits = xEventGroup as *mut EventGroup_t;
    let xReturn: BaseType_t;

    traceENTER_xEventGroupGetStaticBuffer(xEventGroup, ppxEventGroupBuffer);

    configASSERT(!pxEventBits.is_null());
    configASSERT(!ppxEventGroupBuffer.is_null());

    #[cfg(any(feature = "alloc", feature = "heap-4", feature = "heap-5"))]
    {
        xReturn = unsafe {
            if (*pxEventBits).ucStaticallyAllocated == pdTRUE as u8 {
                *ppxEventGroupBuffer = pxEventBits as *mut StaticEventGroup_t;
                pdTRUE
            } else {
                pdFALSE
            }
        };
    }

    #[cfg(not(any(feature = "alloc", feature = "heap-4", feature = "heap-5")))]
    {
        xReturn = unsafe {
            *ppxEventGroupBuffer = pxEventBits as *mut StaticEventGroup_t;
            pdTRUE
        };
    }

    traceRETURN_xEventGroupGetStaticBuffer(xReturn);

    xReturn
}

// =============================================================================
// Callback Functions (for ISR support via timer pend)
// =============================================================================

/// Callback to set bits (used by xEventGroupSetBitsFromISR)
pub extern "C" fn vEventGroupSetBitsCallback(pvEventGroup: *mut c_void, ulBitsToSet: u32) {
    traceENTER_vEventGroupSetBitsCallback(pvEventGroup, ulBitsToSet);

    let _ = xEventGroupSetBits(
        pvEventGroup as EventGroupHandle_t,
        ulBitsToSet as EventBits_t,
    );

    traceRETURN_vEventGroupSetBitsCallback();
}

/// Callback to clear bits (used by xEventGroupClearBitsFromISR)
pub extern "C" fn vEventGroupClearBitsCallback(pvEventGroup: *mut c_void, ulBitsToClear: u32) {
    traceENTER_vEventGroupClearBitsCallback(pvEventGroup, ulBitsToClear);

    let _ = xEventGroupClearBits(
        pvEventGroup as EventGroupHandle_t,
        ulBitsToClear as EventBits_t,
    );

    traceRETURN_vEventGroupClearBitsCallback();
}

// =============================================================================
// ISR Functions (require timer pend function call support)
// =============================================================================

/// Set bits from ISR (requires INCLUDE_xTimerPendFunctionCall)
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
pub fn xEventGroupSetBitsFromISR(
    xEventGroup: EventGroupHandle_t,
    uxBitsToSet: EventBits_t,
    pxHigherPriorityTaskWoken: *mut BaseType_t,
) -> BaseType_t {
    use crate::kernel::timers::xTimerPendFunctionCallFromISR;

    traceENTER_xEventGroupSetBitsFromISR(xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken);

    traceEVENT_GROUP_SET_BITS_FROM_ISR(xEventGroup as *mut c_void, uxBitsToSet as UBaseType_t);

    let xReturn = xTimerPendFunctionCallFromISR(
        vEventGroupSetBitsCallback,
        xEventGroup as *mut c_void,
        uxBitsToSet as u32,
        pxHigherPriorityTaskWoken,
    );

    traceRETURN_xEventGroupSetBitsFromISR(xReturn);

    xReturn
}

/// Clear bits from ISR (requires INCLUDE_xTimerPendFunctionCall)
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
pub fn xEventGroupClearBitsFromISR(
    xEventGroup: EventGroupHandle_t,
    uxBitsToClear: EventBits_t,
) -> BaseType_t {
    use crate::kernel::timers::xTimerPendFunctionCallFromISR;

    traceENTER_xEventGroupClearBitsFromISR(xEventGroup, uxBitsToClear);

    traceEVENT_GROUP_CLEAR_BITS_FROM_ISR(xEventGroup as *mut c_void, uxBitsToClear as UBaseType_t);

    let xReturn = xTimerPendFunctionCallFromISR(
        vEventGroupClearBitsCallback,
        xEventGroup as *mut c_void,
        uxBitsToClear as u32,
        ptr::null_mut(),
    );

    traceRETURN_xEventGroupClearBitsFromISR(xReturn);

    xReturn
}

// =============================================================================
// Trace Facility Functions
// =============================================================================

/// Get event group number (for trace facility)
#[cfg(feature = "trace-facility")]
pub fn uxEventGroupGetNumber(xEventGroup: EventGroupHandle_t) -> UBaseType_t {
    let xReturn: UBaseType_t;

    traceENTER_uxEventGroupGetNumber(xEventGroup);

    if xEventGroup.is_null() {
        xReturn = 0;
    } else {
        let pxEventBits = xEventGroup as *const EventGroup_t;
        xReturn = unsafe { (*pxEventBits).uxEventGroupNumber };
    }

    traceRETURN_uxEventGroupGetNumber(xReturn);

    xReturn
}

/// Set event group number (for trace facility)
#[cfg(feature = "trace-facility")]
pub fn vEventGroupSetNumber(xEventGroup: EventGroupHandle_t, uxEventGroupNumber: UBaseType_t) {
    traceENTER_vEventGroupSetNumber(xEventGroup, uxEventGroupNumber);

    unsafe {
        (*(xEventGroup as *mut EventGroup_t)).uxEventGroupNumber = uxEventGroupNumber;
    }

    traceRETURN_vEventGroupSetNumber();
}

// =============================================================================
// Private Functions
// =============================================================================

/// Test if wait condition is met
fn prvTestWaitCondition(
    uxCurrentEventBits: EventBits_t,
    uxBitsToWaitFor: EventBits_t,
    xWaitForAllBits: BaseType_t,
) -> BaseType_t {
    let mut xWaitConditionMet: BaseType_t = pdFALSE;

    if xWaitForAllBits == pdFALSE {
        // OR condition - any bit set is a match
        if (uxCurrentEventBits & uxBitsToWaitFor) != 0 {
            xWaitConditionMet = pdTRUE;
        }
    } else {
        // AND condition - all bits must be set
        if (uxCurrentEventBits & uxBitsToWaitFor) == uxBitsToWaitFor {
            xWaitConditionMet = pdTRUE;
        }
    }

    xWaitConditionMet
}

// =============================================================================
// Trace Stubs
// =============================================================================

#[inline(always)]
fn traceENTER_xEventGroupCreate() {}
#[inline(always)]
fn traceRETURN_xEventGroupCreate(_pxEventBits: *mut EventGroup_t) {}
#[inline(always)]
fn traceENTER_xEventGroupCreateStatic(_pxEventGroupBuffer: *mut StaticEventGroup_t) {}
#[inline(always)]
fn traceRETURN_xEventGroupCreateStatic(_pxEventBits: *mut EventGroup_t) {}
#[inline(always)]
fn traceENTER_xEventGroupWaitBits(
    _xEventGroup: EventGroupHandle_t,
    _uxBitsToWaitFor: EventBits_t,
    _xClearOnExit: BaseType_t,
    _xWaitForAllBits: BaseType_t,
    _xTicksToWait: TickType_t,
) {
}
#[inline(always)]
fn traceRETURN_xEventGroupWaitBits(_uxReturn: EventBits_t) {}
#[inline(always)]
fn traceENTER_xEventGroupSync(
    _xEventGroup: EventGroupHandle_t,
    _uxBitsToSet: EventBits_t,
    _uxBitsToWaitFor: EventBits_t,
    _xTicksToWait: TickType_t,
) {
}
#[inline(always)]
fn traceRETURN_xEventGroupSync(_uxReturn: EventBits_t) {}
#[inline(always)]
fn traceENTER_xEventGroupSetBits(_xEventGroup: EventGroupHandle_t, _uxBitsToSet: EventBits_t) {}
#[inline(always)]
fn traceRETURN_xEventGroupSetBits(_uxReturnBits: EventBits_t) {}
#[inline(always)]
fn traceENTER_xEventGroupClearBits(_xEventGroup: EventGroupHandle_t, _uxBitsToClear: EventBits_t) {}
#[inline(always)]
fn traceRETURN_xEventGroupClearBits(_uxReturn: EventBits_t) {}
#[inline(always)]
fn traceENTER_xEventGroupGetBitsFromISR(_xEventGroup: EventGroupHandle_t) {}
#[inline(always)]
fn traceRETURN_xEventGroupGetBitsFromISR(_uxReturn: EventBits_t) {}
#[inline(always)]
fn traceENTER_vEventGroupDelete(_xEventGroup: EventGroupHandle_t) {}
#[inline(always)]
fn traceRETURN_vEventGroupDelete() {}
#[inline(always)]
fn traceENTER_xEventGroupGetStaticBuffer(
    _xEventGroup: EventGroupHandle_t,
    _ppxEventGroupBuffer: *mut *mut StaticEventGroup_t,
) {
}
#[inline(always)]
fn traceRETURN_xEventGroupGetStaticBuffer(_xReturn: BaseType_t) {}
#[inline(always)]
fn traceENTER_vEventGroupSetBitsCallback(_pvEventGroup: *mut c_void, _ulBitsToSet: u32) {}
#[inline(always)]
fn traceRETURN_vEventGroupSetBitsCallback() {}
#[inline(always)]
fn traceENTER_vEventGroupClearBitsCallback(_pvEventGroup: *mut c_void, _ulBitsToClear: u32) {}
#[inline(always)]
fn traceRETURN_vEventGroupClearBitsCallback() {}
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
#[inline(always)]
fn traceENTER_xEventGroupSetBitsFromISR(
    _xEventGroup: EventGroupHandle_t,
    _uxBitsToSet: EventBits_t,
    _pxHigherPriorityTaskWoken: *mut BaseType_t,
) {
}
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
#[inline(always)]
fn traceRETURN_xEventGroupSetBitsFromISR(_xReturn: BaseType_t) {}
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
#[inline(always)]
fn traceENTER_xEventGroupClearBitsFromISR(
    _xEventGroup: EventGroupHandle_t,
    _uxBitsToClear: EventBits_t,
) {
}
#[cfg(all(feature = "pend-function-call", feature = "timers"))]
#[inline(always)]
fn traceRETURN_xEventGroupClearBitsFromISR(_xReturn: BaseType_t) {}
#[cfg(feature = "trace-facility")]
#[inline(always)]
fn traceENTER_uxEventGroupGetNumber(_xEventGroup: EventGroupHandle_t) {}
#[cfg(feature = "trace-facility")]
#[inline(always)]
fn traceRETURN_uxEventGroupGetNumber(_xReturn: UBaseType_t) {}
#[cfg(feature = "trace-facility")]
#[inline(always)]
fn traceENTER_vEventGroupSetNumber(
    _xEventGroup: EventGroupHandle_t,
    _uxEventGroupNumber: UBaseType_t,
) {
}
#[cfg(feature = "trace-facility")]
#[inline(always)]
fn traceRETURN_vEventGroupSetNumber() {}