Interrupts in FreeRTOS

How xSemaphoreGiveFromISR wakes a task without switching, how portYIELD_FROM_ISR asks for the switch, and what xYieldPending does when the handler does not ask.

Deferred interrupt handling 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 one interrupt through the FreeRTOS source, from the handler’s give to the task switch after the interrupt returns. The interrupts lesson explains the idea. Set the step level to Line and jump to tick 3, where the UART interrupt fires while Main runs and Handler waits for the semaphore S.

The handler in the application tab is three lines:

void UART_IRQHandler( void )
{
    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
    xSemaphoreGiveFromISR( S, &xHigherPriorityTaskWoken );
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}

Why a separate API

A task that calls xSemaphoreGive() may be switched out inside the call, and may block if it waits for space in a queue. An ISR can do neither: it is not a task, it runs on the interrupted task’s context, and nothing could resume it later. So every call an ISR may use has a FromISR twin that never blocks and never switches. Instead it tells the caller whether a switch would be needed.

The interrupt’s priority matters too. On a Cortex-M, FreeRTOS masks interrupts up to configMAX_SYSCALL_INTERRUPT_PRIORITY while it changes its lists. An interrupt above that level is never masked, so it must not call FreeRTOS at all; one at or below it may call the FromISR functions. That is why the application sets the UART’s priority to configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY in main().

xQueueGiveFromISR

xSemaphoreGiveFromISR() is a macro for xQueueGiveFromISR(), the semaphore form of a queue send.

BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue,
                              BaseType_t * const pxHigherPriorityTaskWoken )
{
    BaseType_t xReturn;
    UBaseType_t uxSavedInterruptStatus;
    Queue_t * const pxQueue = xQueue;

    traceENTER_xQueueGiveFromISR( xQueue, pxHigherPriorityTaskWoken );

    /* Similar to xQueueGenericSendFromISR() but used with semaphores where the
     * item size is 0.  Don't directly wake a task that was blocked on a queue
     * read, instead return a flag to say whether a context switch is required or
     * not (i.e. has a task with a higher priority than us been woken by this
     * post). */

    /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR()
     * if the item size is not 0. */
    configASSERT( ( pxQueue != NULL ) && ( pxQueue->uxItemSize == 0 ) );

    /* Normally a mutex would not be given from an interrupt, especially if
     * there is a mutex holder, as priority inheritance makes no sense for an
     * interrupt, only tasks. */
    configASSERT( ( pxQueue != NULL ) && !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) );

    /* RTOS ports that support interrupt nesting have the concept of a maximum
     * system call (or maximum API call) interrupt priority.  Interrupts that are
     * above the maximum system call priority are kept permanently enabled, even
     * when the RTOS kernel is in a critical section, but cannot make any calls to
     * FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
     * then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
     * failure if a FreeRTOS API function is called from an interrupt that has been
     * assigned a priority above the configured maximum system call priority.
     * Only FreeRTOS functions that end in FromISR can be called from interrupts
     * that have been assigned a priority at or (logically) below the maximum
     * system call interrupt priority.  FreeRTOS maintains a separate interrupt
     * safe API to ensure interrupt entry is as fast and as simple as possible.
     * More information (albeit Cortex-M specific) is provided on the following
     * link: https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
    portASSERT_IF_INTERRUPT_PRIORITY_INVALID();

    /* MISRA Ref 4.7.1 [Return value shall be checked] */
    /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#dir-47 */
    /* coverity[misra_c_2012_directive_4_7_violation] */
    uxSavedInterruptStatus = ( UBaseType_t ) taskENTER_CRITICAL_FROM_ISR();
    {
        const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;

        /* When the queue is used to implement a semaphore no data is ever
         * moved through the queue but it is still valid to see if the queue 'has
         * space'. */
        if( uxMessagesWaiting < pxQueue->uxLength )
        {
            const int8_t cTxLock = pxQueue->cTxLock;

            traceQUEUE_SEND_FROM_ISR( pxQueue );

            /* A task can only have an inherited priority if it is a mutex
             * holder - and if there is a mutex holder then the mutex cannot be
             * given from an ISR.  As this is the ISR version of the function it
             * can be assumed there is no mutex holder and no need to determine if
             * priority disinheritance is needed.  Simply increase the count of
             * messages (semaphores) available. */
            pxQueue->uxMessagesWaiting = ( UBaseType_t ) ( uxMessagesWaiting + ( UBaseType_t ) 1 );

            /* The event list is not altered if the queue is locked.  This will
             * be done when the queue is unlocked later. */
            if( cTxLock == queueUNLOCKED )
            {
                #if ( configUSE_QUEUE_SETS == 1 )
                {
                    if( pxQueue->pxQueueSetContainer != NULL )
                    {
                        if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE )
                        {
                            /* The semaphore is a member of a queue set, and
                             * posting to the queue set caused a higher priority
                             * task to unblock.  A context switch is required. */
                            if( pxHigherPriorityTaskWoken != NULL )
                            {
                                *pxHigherPriorityTaskWoken = pdTRUE;
                            }
                            else
                            {
                                mtCOVERAGE_TEST_MARKER();
                            }
                        }
                        else
                        {
                            mtCOVERAGE_TEST_MARKER();
                        }
                    }
                    else
                    {
                        if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
                        {
                            if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
                            {
                                /* The task waiting has a higher priority so
                                 *  record that a context switch is required. */
                                if( pxHigherPriorityTaskWoken != NULL )
                                {
                                    *pxHigherPriorityTaskWoken = pdTRUE;
                                }
                                else
                                {
                                    mtCOVERAGE_TEST_MARKER();
                                }
                            }
                            else
                            {
                                mtCOVERAGE_TEST_MARKER();
                            }
                        }
                        else
                        {
                            mtCOVERAGE_TEST_MARKER();
                        }
                    }
                }
                #else /* configUSE_QUEUE_SETS */
                {
                    if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
                    {
                        if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
                        {
                            /* The task waiting has a higher priority so record that a
                             * context switch is required. */
                            if( pxHigherPriorityTaskWoken != NULL )
                            {
                                *pxHigherPriorityTaskWoken = pdTRUE;
                            }
                            else
                            {
                                mtCOVERAGE_TEST_MARKER();
                            }
                        }
                        else
                        {
                            mtCOVERAGE_TEST_MARKER();
                        }
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }
                }
                #endif /* configUSE_QUEUE_SETS */
            }
            else
            {
                /* Increment the lock count so the task that unlocks the queue
                 * knows that data was posted while it was locked. */
                prvIncrementQueueTxLock( pxQueue, cTxLock );
            }

            xReturn = pdPASS;
        }
        else
        {
            traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue );
            xReturn = errQUEUE_FULL;
        }
    }
    taskEXIT_CRITICAL_FROM_ISR( uxSavedInterruptStatus );

    traceRETURN_xQueueGiveFromISR( xReturn );

    return xReturn;
}

queue.c, lines 1338–1506 · FreeRTOS V11.3.3 · MIT license

  1. taskENTER_CRITICAL_FROM_ISR() raises the interrupt mask. An ISR cannot suspend the scheduler, as vTaskDelay() does; masking interrupts is the only way to keep the lists still.
  2. S is empty (uxMessagesWaiting is 0, and the length of a semaphore is 1), so there is room. The count becomes 1.
  3. A task waits in xTasksWaitingToReceive, so xTaskRemoveFromEventList() wakes it.
  4. It returns pdTRUE because the woken task is more urgent than the interrupted one, and the function stores pdTRUE in *pxHigherPriorityTaskWoken.

The queueUNLOCKED test is for a queue that a task is in the middle of using: the ISR then leaves the lists alone and only counts the give in cTxLock, and the task processes it when it unlocks the queue. In the simulator an interrupt never arrives inside a kernel call, so the queue is always unlocked here.

BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList )
{
    TCB_t * pxUnblockedTCB;
    BaseType_t xReturn;

    traceENTER_xTaskRemoveFromEventList( pxEventList );

    /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION.  It can also be
     * called from a critical section within an ISR. */

    /* The event list is sorted in priority order, so the first in the list can
     * be removed as it is known to be the highest priority.  Remove the TCB from
     * the delayed list, and add it to the ready list.
     *
     * If an event is for a queue that is locked then this function will never
     * get called - the lock count on the queue will get modified instead.  This
     * means exclusive access to the event list is guaranteed here.
     *
     * This function assumes that a check has already been made to ensure that
     * pxEventList is not empty. */
    /* 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_OWNER_OF_HEAD_ENTRY( pxEventList );
    configASSERT( pxUnblockedTCB );
    listREMOVE_ITEM( &( pxUnblockedTCB->xEventListItem ) );

    if( uxSchedulerSuspended == ( UBaseType_t ) 0U )
    {
        listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) );
        prvAddTaskToReadyList( pxUnblockedTCB );

        #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
    }
    else
    {
        /* The delayed and ready lists cannot be accessed, so hold this task
         * pending until the scheduler is resumed. */
        listINSERT_END( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
    }

    #if ( configNUMBER_OF_CORES == 1 )
    {
        if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
        {
            /* Return true if the task removed from the event list has a higher
             * priority than the calling task.  This allows the calling task to know if
             * it should force a context switch now. */
            xReturn = pdTRUE;

            /* Mark that a yield is pending in case the user is not using the
             * "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
            xYieldPendings[ 0 ] = pdTRUE;
        }
        else
        {
            xReturn = pdFALSE;
        }
    }
    #else /* #if ( configNUMBER_OF_CORES == 1 ) */
    {
        xReturn = pdFALSE;

        #if ( configUSE_PREEMPTION == 1 )
        {
            prvYieldForTask( pxUnblockedTCB );

            if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE )
            {
                xReturn = pdTRUE;
            }
        }
        #endif /* #if ( configUSE_PREEMPTION == 1 ) */
    }
    #endif /* #if ( configNUMBER_OF_CORES == 1 ) */

    traceRETURN_xTaskRemoveFromEventList( xReturn );
    return xReturn;
}

tasks.c, lines 5500–5590 · FreeRTOS V11.3.3 · MIT license

Two things happen in xTaskRemoveFromEventList() that matter for interrupts. Handler goes back into its ready list (the scheduler is not suspended, so it can go straight there instead of into xPendingReadyList). And because it is more urgent than pxCurrentTCB, xYieldPendings[ 0 ] is set to pdTRUE: the kernel itself remembers that a switch is due, whatever the ISR does next.

portYIELD_FROM_ISR

#define portEND_SWITCHING_ISR( xSwitchRequired ) \
    do                                           \
    {                                            \
        if( xSwitchRequired != pdFALSE )         \
        {                                        \
            traceISR_EXIT_TO_SCHEDULER();        \
            portYIELD();                         \
        }                                        \
        else                                     \
        {                                        \
            traceISR_EXIT();                     \
        }                                        \
    } while( 0 )

portable/GCC/ARM_CM3/portmacro.h, lines 98–110 · FreeRTOS V11.3.3 · MIT license

On the Cortex-M3 port, portYIELD_FROM_ISR() is portEND_SWITCHING_ISR(), and yielding only means setting the PendSV exception pending. PendSV has the lowest priority of all, so it waits until the tick interrupt and the UART handler have both returned. Then it runs the context switch: vTaskSwitchContext() picks Handler, and Handler returns from the xSemaphoreTake() it was blocked in. It takes S as its retry loop goes round, still at tick 3.

In this simulator the tick handler may have set PendSV pending too (to wake a delayed task or to time-slice). There is still only one switch: PendSV runs once, after every interrupt has returned.

When the handler does not yield

Turn Yield from ISR off and step through tick 3 again. Everything up to the end of xQueueGiveFromISR() is the same: Handler is ready and xYieldPending is pdTRUE in the variables (the panel’s name for xYieldPendings[ 0 ]). But the ISR returns without setting PendSV, and Main carries on.

The pending flag is not forgotten. Two places act on it:

  • The next tick: xTaskIncrementTick() returns pdTRUE when xYieldPendings[ 0 ] is set, so the tick interrupt requests the switch. That is what happens at tick 4.
  • The next time a task resumes the scheduler: xTaskResumeAll() switches at once when the flag is set. A task that calls vTaskDelay() right after such an interrupt is switched out inside xTaskResumeAll(), before vTaskDelay() gets to its own yield.
BaseType_t xTaskResumeAll( void )
{
    TCB_t * pxTCB = NULL;
    BaseType_t xAlreadyYielded = pdFALSE;

    traceENTER_xTaskResumeAll();

    #if ( configNUMBER_OF_CORES > 1 )
        if( xSchedulerRunning != pdFALSE )
    #endif
    {
        /* It is possible that an ISR caused a task to be removed from an event
         * list while the scheduler was suspended.  If this was the case then the
         * removed task will have been added to the xPendingReadyList.  Once the
         * scheduler has been resumed it is safe to move all the pending ready
         * tasks from this list into their appropriate ready list. */
        taskENTER_CRITICAL();
        {
            const BaseType_t xCoreID = ( BaseType_t ) portGET_CORE_ID();

            /* If uxSchedulerSuspended is zero then this function does not match a
             * previous call to vTaskSuspendAll(). */
            configASSERT( uxSchedulerSuspended != 0U );

            uxSchedulerSuspended = ( UBaseType_t ) ( uxSchedulerSuspended - 1U );
            portRELEASE_TASK_LOCK( xCoreID );

            if( uxSchedulerSuspended == ( UBaseType_t ) 0U )
            {
                if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U )
                {
                    /* Move any readied tasks from the pending list into the
                     * appropriate ready list. */
                    while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE )
                    {
                        /* 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] */
                        pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) );
                        listREMOVE_ITEM( &( pxTCB->xEventListItem ) );
                        portMEMORY_BARRIER();
                        listREMOVE_ITEM( &( pxTCB->xStateListItem ) );
                        prvAddTaskToReadyList( pxTCB );

                        #if ( configNUMBER_OF_CORES == 1 )
                        {
                            /* If the moved task has a priority higher than the current
                             * task then a yield must be performed. */
                            if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
                            {
                                xYieldPendings[ xCoreID ] = pdTRUE;
                            }
                            else
                            {
                                mtCOVERAGE_TEST_MARKER();
                            }
                        }
                        #else /* #if ( configNUMBER_OF_CORES == 1 ) */
                        {
                            /* All appropriate tasks yield at the moment a task is added to xPendingReadyList.
                             * If the current core yielded then vTaskSwitchContext() has already been called
                             * which sets xYieldPendings for the current core to pdTRUE. */
                        }
                        #endif /* #if ( configNUMBER_OF_CORES == 1 ) */
                    }

                    if( pxTCB != NULL )
                    {
                        /* A task was unblocked while the scheduler was suspended,
                         * which may have prevented the next unblock time from being
                         * re-calculated, in which case re-calculate it now.  Mainly
                         * important for low power tickless implementations, where
                         * this can prevent an unnecessary exit from low power
                         * state. */
                        prvResetNextTaskUnblockTime();
                    }

                    /* If any ticks occurred while the scheduler was suspended then
                     * they should be processed now.  This ensures the tick count does
                     * not  slip, and that any delayed tasks are resumed at the correct
                     * time.
                     *
                     * It should be safe to call xTaskIncrementTick here from any core
                     * since we are in a critical section and xTaskIncrementTick itself
                     * protects itself within a critical section. Suspending the scheduler
                     * from any core causes xTaskIncrementTick to increment uxPendedCounts. */
                    {
                        TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */

                        if( xPendedCounts > ( TickType_t ) 0U )
                        {
                            do
                            {
                                if( xTaskIncrementTick() != pdFALSE )
                                {
                                    /* Other cores are interrupted from
                                     * within xTaskIncrementTick(). */
                                    xYieldPendings[ xCoreID ] = pdTRUE;
                                }
                                else
                                {
                                    mtCOVERAGE_TEST_MARKER();
                                }

                                --xPendedCounts;
                            } while( xPendedCounts > ( TickType_t ) 0U );

                            xPendedTicks = 0;
                        }
                        else
                        {
                            mtCOVERAGE_TEST_MARKER();
                        }
                    }

                    if( xYieldPendings[ xCoreID ] != pdFALSE )
                    {
                        #if ( configUSE_PREEMPTION != 0 )
                        {
                            xAlreadyYielded = pdTRUE;
                        }
                        #endif /* #if ( configUSE_PREEMPTION != 0 ) */

                        #if ( configNUMBER_OF_CORES == 1 )
                        {
                            taskYIELD_TASK_CORE_IF_USING_PREEMPTION( pxCurrentTCB );
                        }
                        #endif /* #if ( configNUMBER_OF_CORES == 1 ) */
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }
                }
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        taskEXIT_CRITICAL();
    }

    traceRETURN_xTaskResumeAll( xAlreadyYielded );

    return xAlreadyYielded;
}

tasks.c, lines 4064–4210 · FreeRTOS V11.3.3 · MIT license

The cost is latency: up to one tick before the woken task runs. In this run it costs an interrupt too. At tick 8 Handler is woken but not switched in; at tick 9 the next interrupt finds S still given, and xQueueGiveFromISR() takes the errQUEUE_FULL branch. That event is lost.

Leaving out the yield is occasionally done on purpose, to batch several interrupts before the task runs, but it is more often a bug: the woken task runs late, and nothing in the code says why.