Skip to content
systemcoding.dev
RTOS

Defer Work From an ISR With xTimerPendFunctionCallFromISR

Run a function at task level from a FreeRTOS interrupt with xTimerPendFunctionCallFromISR: arguments, config flags, failure modes and alternatives.

7 min read
Summarize in AI
Flat illustration of a program timeline interrupted by an interrupt service routine, with the C, Rust and Arm logos.

An interrupt handler should be short, and the slow part of an interrupt's work belongs in a task. The usual tools for the hand-off are a semaphore, a notification or a queue, each of which needs an object and a task waiting for it. FreeRTOS offers a different shape: tell the timer service task to call a function for you. xTimerPendFunctionCallFromISR() queues a function pointer and two arguments, and the timer task calls the function at task level, in order, with no extra task or queue to create. This post uses it on FreeRTOS kernel V11.1.0 to log a UART error from an interrupt, lists the configuration it needs, the ways it can fail and the rules the deferred function must obey, and compares it with a notification. The timer machinery is described in the timer service task post.

The call

c
BaseType_t xTimerPendFunctionCallFromISR(PendedFunction_t xFunctionToPend,
                                         void *pvParameter1,
                                         uint32_t ulParameter2,
                                         BaseType_t *pxHigherPriorityTaskWoken);

The pended function has the shape void fn(void *pvParameter1, uint32_t ulParameter2). The two parameters are passed through to it unchanged. pvParameter1 is a pointer, which can also hold an integer cast to a pointer, and ulParameter2 is a 32-bit value. The last argument is the usual woken flag. The return value is pdPASS if the request was queued and pdFAIL if the timer queue was full.

The task-level twin, xTimerPendFunctionCall(), has the same parameters plus a block time instead of the woken flag.

Configuration

Two settings are required, and a third decides how soon the function runs:

FreeRTOSConfig.hc
#define configUSE_TIMERS                 1
#define INCLUDE_xTimerPendFunctionCall   1
#define configTIMER_QUEUE_LENGTH         16
#define configTIMER_TASK_PRIORITY        ( configMAX_PRIORITIES - 2 )

configUSE_TIMERS creates the timer service task, and INCLUDE_xTimerPendFunctionCall compiles the call. Without either, the function does not exist. configTIMER_QUEUE_LENGTH is the capacity of the queue shared with all timer commands, so size it for the largest burst of pended calls plus normal timer traffic. configTIMER_TASK_PRIORITY decides when the function runs: a high priority means soon after the interrupt returns, a low one means after higher-priority tasks block.

A worked example: log UART errors from the interrupt

A UART interrupt sees an overrun or framing error. It must clear the hardware flag immediately but must not call printf(). It pends a function that logs the error at task level.

uart_err.cc
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"

static volatile uint32_t s_pendFailures;

static void log_uart_error(void *param1, uint32_t status)
{
    const char *port = param1;
    printf("[%lu] %s error, status=0x%04lX%s%s\n",
           (unsigned long)xTaskGetTickCount(), port, (unsigned long)status,
           (status & 0x08) ? " overrun" : "",
           (status & 0x02) ? " framing" : "");
}

void USART2_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    uint32_t sr = USART2->SR;

    if (sr & (USART_SR_ORE | USART_SR_FE)) {
        (void)USART2->DR;                              /* reading DR clears the flags */
        if (xTimerPendFunctionCallFromISR(log_uart_error, (void *)"USART2",
                                          sr & 0xFFFFu, &woken) != pdPASS) {
            s_pendFailures++;                          /* queue was full: count it */
        }
    }
    portYIELD_FROM_ISR(woken);
}

The first parameter is a pointer to a string literal. A literal lives for the whole program, so the pointer is valid when the function runs later. The second parameter is the status register value, captured in the interrupt, because the register will have changed by the time the function runs.

With an overrun and a framing error at tick 4,120:

Text
[4120] USART2 error, status=0x000A overrun framing

The status 0x0A has bit 3 (overrun) and bit 1 (framing) set. The tick printed is the tick at which the pended function ran, which can be later than the interrupt if the timer task was held off.

Rules for the deferred function

The function runs in the timer service task, so it inherits the callback rules:

  1. It must not block. No vTaskDelay(), no waiting on a queue or semaphore with a timeout. A blocked timer task stops every timer and every other pended function.

  2. It should be short. It runs in line with timer callbacks, so a long function makes timers late.

  3. It uses the timer task's stack. printf() can use a lot of stack, so size configTIMER_TASK_STACK_DEPTH for the deepest pended function.

  4. Its parameters must stay valid. A pointer to a local variable in the interrupt is dangling when the function runs. Pass literals, statics, heap blocks you own, or values.

The third and fourth rules are about lifetime. Passing the status value by value, as above, is the safest form. If you must pass a pointer to data, point at static storage or at a buffer from a pool, and say in a comment who owns it.

What can fail

The queue is full. The call returns pdFAIL and the function never runs. The timer queue also carries timer start, stop and reset commands, so heavy timer traffic eats into the space. Count failures, as the example does, and size the queue for bursts.

The timer task is starved. A higher-priority task that never blocks keeps the function from running. The request waits in the queue indefinitely. Give the timer task a priority above your busiest tasks if deferred work must not be delayed, and know the cost: the pended function now preempts them.

Ordering is by queue order. Pended functions run in the order they were queued, interleaved with timer commands. Two interrupts that pend functions run them in the order the interrupts happened, as far as the queue is concerned.

Interrupt priority. As with every FromISR call, the interrupt must be at or above configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY, or the kernel's priority check asserts, as described in the FromISR post.

Compared with the usual hand-offs

MechanismNeedsCarriesBest for
xTimerPendFunctionCallFromISR()configUSE_TIMERS, INCLUDE_xTimerPendFunctionCall, timer queue slotA function, a pointer, a 32-bit valueOccasional work of different kinds, no dedicated task
vTaskNotifyGiveFromISR()A task handleA countOne task, one kind of event, hot path
xQueueSendFromISR()A queue and a task reading itAny item, in orderA stream of data
xSemaphoreGiveFromISR()A semaphoreA signalOne waiter, no handle
Event group from ISRconfigUSE_TIMERS and the same flagFlag bitsShared state; it is built on the same pend call

The pend-call is the most convenient when the work differs from interrupt to interrupt, because the interrupt names the function it wants, and there is no dispatcher task and no message type. It is the wrong tool for a high-rate event: each call takes a slot in a shared queue and runs a function through the timer task, which is more work than a notification to a dedicated task. For a path that fires thousands of times a second, use a notification and a task.

Event groups use this same mechanism under the hood for their interrupt-safe set, which is the subject of the event group deferral post.

Using it from a task

The task-level version lets a task push work into the timer task's context:

pend_task.cc
static void flash_flush(void *param1, uint32_t bytes)
{
    (void)param1;
    log_flush_to_flash(bytes);                 /* short; must not block */
}

void request_flush(uint32_t bytes)
{
    if (xTimerPendFunctionCall(flash_flush, NULL, bytes, pdMS_TO_TICKS(10)) != pdPASS) {
        s_pendFailures++;
    }
}

Here the third-from-last argument is the block time in ticks for the queue, 10 ms. It lets the caller wait briefly for room, which an interrupt cannot do.

Testing

A test floods the interrupt path faster than the timer task can drain and checks that the failure counter accounts for every request:

flood_test.cc
static volatile uint32_t s_ran;

static void count_run(void *p, uint32_t v)
{
    (void)p; (void)v;
    s_ran++;
}

static void flood_task(void *arg)
{
    (void)arg;
    uint32_t sent = 0, failed = 0;
    for (int i = 0; i < 100; i++) {
        BaseType_t woken = pdFALSE;
        if (xTimerPendFunctionCallFromISR(count_run, NULL, i, &woken) == pdPASS) {
            sent++;
        } else {
            failed++;
        }
    }
    vTaskDelay(pdMS_TO_TICKS(50));
    printf("sent=%lu failed=%lu ran=%lu\n", (unsigned long)sent, (unsigned long)failed,
           (unsigned long)s_ran);
    vTaskDelete(NULL);
}
Text
sent=16 failed=84 ran=16

The task runs at a priority above the timer task, so it fills the 16-slot queue before the timer task can run, and the remaining 84 requests fail. The invariant to check is that sent equals ran and sent + failed equals 100: nothing is lost silently. Calling the FromISR function from a task is acceptable in a test where the priority assertion is satisfied or disabled, and it is not a pattern for production code.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.