Event groups in FreeRTOS

How xEventGroupWaitBits stores what a task waits for in its own list item, how xEventGroupSetBits walks every waiting task with the scheduler suspended, and why an interrupt's setBits goes through the timer service task.

Event group on FreeRTOS V11.3.3

Simulated kernel: FreeRTOS V11.3.3. This scenario and every other one are in the scheduler playground. The simulator and its data files are not covered by the site's CC BY-SA license; see their license notices.

This walkthrough follows the event groups lesson through FreeRTOS’s event_groups.c. Set the step level to Line to follow it.

What an event group is

xEventGroupCreate() allocates an EventGroup_t with two fields:

  • uxEventBits: the bits. The kernel panel shows them by name, and the raw value.
  • xTasksWaitingForBits: the tasks waiting for some of them.

EventBits_t is as wide as a tick count, here 32 bits, but the top 8 are reserved for control flags, so a group has 24 bits for the application.

Waiting: xEventGroupWaitBits

At tick 0 Upload calls xEventGroupWaitBits( E, BIT_DATA | BIT_LINK, pdTRUE, pdTRUE, portMAX_DELAY ): clear on exit, wait for all of them, with no timeout.

EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup,
                                 const EventBits_t uxBitsToWaitFor,
                                 const BaseType_t xClearOnExit,
                                 const BaseType_t xWaitForAllBits,
                                 TickType_t xTicksToWait )
{
    EventGroup_t * pxEventBits = xEventGroup;
    EventBits_t uxReturn, uxControlBits = 0;
    BaseType_t xWaitConditionMet, xAlreadyYielded;
    BaseType_t xTimeoutOccurred = pdFALSE;

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

    /* Check the user is not attempting to wait on the bits used by the kernel
     * itself, and that at least one bit is being requested. */
    configASSERT( xEventGroup );
    configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
    configASSERT( uxBitsToWaitFor != 0 );
    #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
    {
        configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
    }
    #endif

    vTaskSuspendAll();
    {
        const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits;

        /* Check to see if the wait condition is already met or not. */
        xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits );

        if( xWaitConditionMet != pdFALSE )
        {
            /* The wait condition has already been met so there is no need to
             * block. */
            uxReturn = uxCurrentEventBits;
            xTicksToWait = ( TickType_t ) 0;

            /* Clear the wait bits if requested to do so. */
            if( xClearOnExit != pdFALSE )
            {
                pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        else if( xTicksToWait == ( TickType_t ) 0 )
        {
            /* The wait condition has not been met, but no block time was
             * specified, so just return the current value. */
            uxReturn = uxCurrentEventBits;
            xTimeoutOccurred = pdTRUE;
        }
        else
        {
            /* The task is going to block to wait for its required bits to be
             * set.  uxControlBits are used to remember the specified behaviour of
             * this call to xEventGroupWaitBits() - for use when the event bits
             * unblock the task. */
            if( xClearOnExit != pdFALSE )
            {
                uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }

            if( xWaitForAllBits != pdFALSE )
            {
                uxControlBits |= eventWAIT_FOR_ALL_BITS;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }

            /* Store the bits that the calling task is waiting for in the
             * task's event list item so the kernel knows when a match is
             * found.  Then enter the blocked state. */
            vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait );

            /* This is obsolete as it will get set after the task unblocks, but
             * some compilers mistakenly generate a warning about the variable
             * being returned without being set if it is not done. */
            uxReturn = 0;

            traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor );
        }
    }
    xAlreadyYielded = xTaskResumeAll();

    if( xTicksToWait != ( TickType_t ) 0 )
    {
        if( xAlreadyYielded == pdFALSE )
        {
            taskYIELD_WITHIN_API();
        }
        else
        {
            mtCOVERAGE_TEST_MARKER();
        }

        /* The task blocked to wait for its required bits to be set - at this
         * point either the required bits were set or the block time expired.  If
         * the required bits were set they will have been stored in the task's
         * event list item, and they should now be retrieved then cleared. */
        uxReturn = uxTaskResetEventItemValue();

        if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
        {
            taskENTER_CRITICAL();
            {
                /* The task timed out, just return the current event bit value. */
                uxReturn = pxEventBits->uxEventBits;

                /* It is possible that the event bits were updated between this
                 * task leaving the Blocked state and running again. */
                if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE )
                {
                    if( xClearOnExit != pdFALSE )
                    {
                        pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }

                xTimeoutOccurred = pdTRUE;
            }
            taskEXIT_CRITICAL();
        }
        else
        {
            /* The task unblocked because the bits were set. */
        }

        /* The task blocked so control bits may have been set. */
        uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
    }

    traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred );

    /* Prevent compiler warnings when trace macros are not used. */
    ( void ) xTimeoutOccurred;

    traceRETURN_xEventGroupWaitBits( uxReturn );

    return uxReturn;
}

event_groups.c, lines 312–469 · FreeRTOS V11.3.3 · MIT license

  1. vTaskSuspendAll(): the scheduler is suspended, not interrupts.
  2. prvTestWaitCondition() checks the bits against what the task asks for, all or any. No bit is set yet, and Upload is willing to wait.
  3. The flags for “clear on exit” and “wait for all” are added to the bits waited for, and vTaskPlaceOnUnorderedEventList() blocks the task.
void vTaskPlaceOnUnorderedEventList( List_t * pxEventList,
                                     const TickType_t xItemValue,
                                     const TickType_t xTicksToWait )
{
    traceENTER_vTaskPlaceOnUnorderedEventList( pxEventList, xItemValue, xTicksToWait );

    configASSERT( pxEventList );

    /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED.  It is used by
     * the event groups implementation. */
    configASSERT( uxSchedulerSuspended != ( UBaseType_t ) 0U );

    /* Store the item value in the event list item.  It is safe to access the
     * event list item here as interrupts won't access the event list item of a
     * task that is not in the Blocked state. */
    listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );

    /* Place the event list item of the TCB at the end of the appropriate event
     * list.  It is safe to access the event list here because it is part of an
     * event group implementation - and interrupts don't access event groups
     * directly (instead they access them indirectly by pending function calls to
     * the task level). */
    listINSERT_END( pxEventList, &( pxCurrentTCB->xEventListItem ) );

    prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );

    traceRETURN_vTaskPlaceOnUnorderedEventList();
}

tasks.c, lines 5431–5458 · FreeRTOS V11.3.3 · MIT license

Where does the kernel keep what each task waits for? In the task’s own event list item. For a queue that item’s value is the task’s priority, which keeps the waiting list sorted. Here it holds the bits and the two flags instead, marked with taskEVENT_LIST_ITEM_VALUE_IN_USE so that a priority change leaves it alone. The list itself is unordered: listINSERT_END() puts the task at the end, because every waiter will be looked at anyway. Then the task goes into a delayed list, or with no timeout into xSuspendedTaskList, as for any wait.

Status does the same, asking for any of LINK and ERR. Both tasks are now in E.xTasksWaitingForBits, each with its bits shown on its chip.

Setting: xEventGroupSetBits

At tick 6 Net sets LINK:

EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup,
                                const EventBits_t uxBitsToSet )
{
    ListItem_t * pxListItem;
    ListItem_t * pxNext;
    ListItem_t const * pxListEnd;
    List_t const * pxList;
    EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits, uxReturnBits;
    EventGroup_t * pxEventBits = xEventGroup;
    BaseType_t xMatchFound = pdFALSE;

    traceENTER_xEventGroupSetBits( xEventGroup, uxBitsToSet );

    /* Check the user is not attempting to set the bits used by the kernel
     * itself. */
    configASSERT( xEventGroup );
    configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 );

    pxList = &( pxEventBits->xTasksWaitingForBits );
    pxListEnd = listGET_END_MARKER( pxList );
    vTaskSuspendAll();
    {
        traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet );

        pxListItem = listGET_HEAD_ENTRY( pxList );

        /* Set the bits. */
        pxEventBits->uxEventBits |= uxBitsToSet;

        /* See if the new bit value should unblock any tasks. */
        while( pxListItem != pxListEnd )
        {
            pxNext = listGET_NEXT( pxListItem );
            uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem );
            xMatchFound = pdFALSE;

            /* Split the bits waited for from the control bits. */
            uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;
            uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES;

            if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 )
            {
                /* Just looking for single bit being set. */
                if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 )
                {
                    xMatchFound = pdTRUE;
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
            else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor )
            {
                /* All bits are set. */
                xMatchFound = pdTRUE;
            }
            else
            {
                /* Need all bits to be set, but not all the bits were set. */
            }

            if( xMatchFound != pdFALSE )
            {
                /* The bits match.  Should the bits be cleared on exit? */
                if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 )
                {
                    uxBitsToClear |= uxBitsWaitedFor;
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }

                /* Store the actual event flag value in the task's event list
                 * item before removing the task from the event list.  The
                 * eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows
                 * that is was unblocked due to its required bits matching, rather
                 * than because it timed out. */
                vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET );
            }

            /* Move onto the next list item.  Note pxListItem->pxNext is not
             * used here as the list item may have been removed from the event list
             * and inserted into the ready/pending reading list. */
            pxListItem = pxNext;
        }

        /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT
         * bit was set in the control word. */
        pxEventBits->uxEventBits &= ~uxBitsToClear;

        /* Snapshot resulting bits. */
        uxReturnBits = pxEventBits->uxEventBits;
    }
    ( void ) xTaskResumeAll();

    traceRETURN_xEventGroupSetBits( uxReturnBits );

    return uxReturnBits;
}

event_groups.c, lines 547–647 · FreeRTOS V11.3.3 · MIT license

  1. The scheduler is suspended again. This function may wake many tasks, so it does not run with interrupts off.
  2. uxEventBits |= uxBitsToSet: the group is now DATA | LINK.
  3. The loop walks the whole list. For each task it reads the value of its list item, splits off the control flags, and tests the condition: Upload (all of DATA and LINK) is satisfied, Status (any of LINK and ERR) too.
  4. Upload clears on exit, so its bits are added to uxBitsToClear. They are not cleared yet: every waiter is tested against the same bits.
  5. Each satisfied task is woken by vTaskRemoveFromUnorderedEventList():
void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem,
                                        const TickType_t xItemValue )
{
    TCB_t * pxUnblockedTCB;

    traceENTER_vTaskRemoveFromUnorderedEventList( pxEventListItem, xItemValue );

    /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED.  It is used by
     * the event flags implementation. */
    configASSERT( uxSchedulerSuspended != ( UBaseType_t ) 0U );

    /* Store the new item value in the event list. */
    listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );

    /* Remove the event list form the event flag.  Interrupts do not access
     * event flags. */
    /* MISRA Ref 11.5.3 [Void pointer assignment] */
    /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
    /* coverity[misra_c_2012_rule_11_5_violation] */
    pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem );
    configASSERT( pxUnblockedTCB );
    listREMOVE_ITEM( pxEventListItem );

    #if ( configUSE_TICKLESS_IDLE != 0 )
    {
        /* If a task is blocked on a kernel object then xNextTaskUnblockTime
         * might be set to the blocked task's time out time.  If the task is
         * unblocked for a reason other than a timeout xNextTaskUnblockTime is
         * normally left unchanged, because it is automatically reset to a new
         * value when the tick count equals xNextTaskUnblockTime.  However if
         * tickless idling is used it might be more important to enter sleep mode
         * at the earliest possible time - so reset xNextTaskUnblockTime here to
         * ensure it is updated at the earliest possible time. */
        prvResetNextTaskUnblockTime();
    }
    #endif

    /* Remove the task from the delayed list and add it to the ready list.  The
     * scheduler is suspended so interrupts will not be accessing the ready
     * lists. */
    listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) );
    prvAddTaskToReadyList( pxUnblockedTCB );

    #if ( configNUMBER_OF_CORES == 1 )
    {
        if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
        {
            /* The unblocked task has a priority above that of the calling task, so
             * a context switch is required.  This function is called with the
             * scheduler suspended so xYieldPending is set so the context switch
             * occurs immediately that the scheduler is resumed (unsuspended). */
            xYieldPendings[ 0 ] = pdTRUE;
        }
    }
    #else /* #if ( configNUMBER_OF_CORES == 1 ) */
    {
        #if ( configUSE_PREEMPTION == 1 )
        {
            taskENTER_CRITICAL();
            {
                prvYieldForTask( pxUnblockedTCB );
            }
            taskEXIT_CRITICAL();
        }
        #endif
    }
    #endif /* #if ( configNUMBER_OF_CORES == 1 ) */

    traceRETURN_vTaskRemoveFromUnorderedEventList();
}

tasks.c, lines 5593–5662 · FreeRTOS V11.3.3 · MIT license

It stores the group’s current bits, with the flag eventUNBLOCKED_DUE_TO_BIT_SET, in the task’s list item: that is what the task’s call will return. Then it moves the task to its ready list. The scheduler is suspended, so a more urgent task cannot run yet: xYieldPendings[ 0 ] is set instead (xYieldPending in the variables).

  1. After the walk, uxBitsToClear is applied: E is empty again.
  2. xTaskResumeAll() finds the pending yield and switches to Upload at once.

Waking up

Upload returns from its taskYIELD_WITHIN_API() inside xEventGroupWaitBits(). uxTaskResetEventItemValue() reads the value that was stored for it and puts its priority back in its list item. The flag says it was woken by bits, so the value, DATA | LINK, is returned as it is. Status does the same when it runs at tick 8, and gets DATA | LINK as well: the bits as they were when it was woken, cleared since by Upload.

When a wait ends without that flag, the timeout ran out (or the task was suspended and resumed). The function then reads the bits as they are now and tests the condition once more. If the bits arrived just after the timeout, the task gets them after all, and clears them if it asked to.

From an interrupt

An interrupt handler calls xEventGroupSetBitsFromISR():

BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup,
                                      const EventBits_t uxBitsToSet,
                                      BaseType_t * pxHigherPriorityTaskWoken )
{
    BaseType_t xReturn;

    traceENTER_xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken );

    traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet );
    xReturn = xTimerPendFunctionCallFromISR( &vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken );

    traceRETURN_xEventGroupSetBitsFromISR( xReturn );

    return xReturn;
}

event_groups.c, lines 817–831 · FreeRTOS V11.3.3 · MIT license

It does not touch the group. Walking xTasksWaitingForBits has no fixed length, so it must not be done with interrupts masked. Instead it calls xTimerPendFunctionCallFromISR(), which sends a message to the timer service task: “call vEventGroupSetBitsCallback( E, BIT_DATA )”. The message goes into xTimerQueue like a timer command (it shows as setBits(E, DATA)), and wakes the timer task.

At tick 3 the timer task is the most urgent task, so portYIELD_FROM_ISR() switches to it as the interrupt returns. In prvProcessReceivedCommands() it finds a message with a negative ID, a pended function rather than a timer command, and calls it: vEventGroupSetBitsCallback() calls xEventGroupSetBits(), as any task would. In the event log the bits are set by Tmr Svc, not by Sensor.

This is why event groups from interrupts need configUSE_TIMERS and INCLUDE_xTimerPendFunctionCall, why the timer queue must have room for these messages, and why the timer task’s priority decides how soon the bits appear.