Rtos

From j4flmao/agent-skills · View interactive version

Rtos is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about FreeRTOS, task priorities, xTaskCreate, ISR-safe queues, mutex vs semaphore, priority inversion, task notifications, task stack overflow or Zephyr threads. Produces RTOS task design, ISR deferral and timing analysis. Not for bare-metal superloops (use c-cpp-patterns or b

How to use this skill

Skill file

RTOS Engineering (FreeRTOS / Zephyr)

Purpose

Turn a firmware feature into a set of tasks, priorities and communication primitives that meet deadlines deterministically. The skill covers how the FreeRTOS kernel actually schedules, which primitive to use for each interaction, how to keep ISRs short, how to size stacks and heaps statically, and how to prove timing on the target.

Agent Protocol

Trigger

"FreeRTOS", "RTOS task", "xTaskCreate", "task priority", "mutex vs semaphore", "priority inversion", "task notification", "stack overflow", "Zephyr thread", "RTOS queue", "ISR to task", "hard real-time", "rate monotonic", "EDF", "WCET", "RTOS vs Linux", "PREEMPT_RT".

Input Context

Output Artifact

Task table, primitive choices, C code for tasks/ISRs, FreeRTOSConfig.h settings. No file unless requested.

Response Format

Tasks: {name | priority | period/deadline | stack words | blocks on}
IPC: {producer -> primitive -> consumer}
ISRs: {source | work done in ISR | deferred to}
Config: {key FreeRTOSConfig.h settings}
Code: {snippet}
Verification: {WCET/response-time check, stack high-water marks, trace}

0. Is It Real-Time, and Which Platform?

1. How the FreeRTOS Scheduler Works

2. Task Design Rules

  1. One task per independent timing domain (sensor sampling, control loop, comms, UI), not one per feature.
  2. Assign priorities by deadline (Rate/Deadline Monotonic): shorter deadline → higher priority. Not by "importance".
  3. Every task blocks somewhere (xQueueReceive, ulTaskNotifyTake, vTaskDelayUntil). A task that never blocks starves everything below it.
  4. Periodic tasks use vTaskDelayUntil(&lastWake, period) (or xTaskDelayUntil) — vTaskDelay drifts because it is relative to the call time.
  5. Create everything at startup with static allocation; never create/delete tasks in steady state.
#define CTRL_STACK_WORDS 512
static StackType_t ctrlStack[CTRL_STACK_WORDS];
static StaticTask_t ctrlTcb;

static void vControlTask(void *arg)
{
    (void)arg;
    TickType_t lastWake = xTaskGetTickCount();
    const TickType_t period = pdMS_TO_TICKS(5);       /* 200 Hz loop */
    for (;;) {
        vTaskDelayUntil(&lastWake, period);
        control_step();                                /* bounded WCET */
    }
}

void app_start(void)
{
    TaskHandle_t h = xTaskCreateStatic(vControlTask, "ctrl", CTRL_STACK_WORDS,
                                       NULL, tskIDLE_PRIORITY + 4, ctrlStack, &ctrlTcb);
    configASSERT(h != NULL);
    vTaskStartScheduler();                             /* does not return */
    for (;;) { }
}

Note: the stack depth argument is in words (StackType_t), not bytes.

3. Choosing the Communication Primitive

| Need | Primitive | Notes |

|------|-----------|-------|

| ISR or task signals one specific task | Direct-to-task notification (xTaskNotifyGive / vTaskNotifyGiveFromISR, ulTaskNotifyTake) | Fastest and smallest; one receiver only |

| Pass data by copy | Queue (xQueueSend, xQueueReceive) | Items copied; send pointers to static buffers for large data |

| Byte stream / variable messages, one writer one reader | Stream / message buffer | Single writer + single reader unless you add locking |

| Protect a shared resource | Mutex (xSemaphoreCreateMutexStatic) | Has priority inheritance; never take in an ISR |

| Count events / resources | Counting semaphore | No inheritance |

| Wait on several flags | Event group | Bits limited by configTICK_TYPE_WIDTH_IN_BITS (24 usable bits for 32-bit ticks) |

| Deferred function call | Timer service / xTimerPendFunctionCallFromISR | Runs in the timer daemon task — keep callbacks short and non-blocking |

Mutex vs binary semaphore: a mutex has an owner and priority inheritance and must be released by the task that took it; a binary semaphore is for signalling and has neither.

4. Priority Inversion and Inheritance

Classic failure (Mars Pathfinder, 1997): low task holds a lock, high task blocks on it, medium task preempts low — high waits on medium. FreeRTOS mutexes apply priority inheritance: the holder is raised to the highest waiter's priority and lowered again when it gives the mutex back (the original priority is restored once it holds no more mutexes, and in current versions a waiter that times out can lower the inherited priority again). Inheritance is not transitive-safe against long critical sections: keep mutex-held code short, never block on another primitive while holding a mutex, and take multiple mutexes in a fixed global order to avoid deadlock.

5. ISRs and Deferral

void ADC_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    sample_buf[idx] = ADC1->DR;                         /* read clears the flag on many parts */
    vTaskNotifyGiveFromISR(adcTaskHandle, &woken);
    portYIELD_FROM_ISR(woken);                          /* switch now if a higher task woke */
}

6. Memory and Stacks

7. Timing Verification

8. Zephyr Equivalents

| FreeRTOS | Zephyr |

|----------|--------|

| xTaskCreateStatic | K_THREAD_DEFINE / k_thread_create |

| Priorities: higher number = higher | Lower number = higher; negative = cooperative (non-preemptible) |

| Queue | k_msgq |

| Mutex (inheritance) | k_mutex (inheritance) |

| Task notification | k_sem / k_event / k_poll |

| FromISR APIs | Same APIs, ISR-safe variants marked; use K_NO_WAIT in ISRs |

9. Anti-Patterns

| Anti-pattern | Consequence | Fix |

|--------------|-------------|-----|

| Busy-wait polling a flag in a task | Starves lower priorities, wastes power | Block on notification/queue |

| vTaskDelay for periodic work | Period drift | vTaskDelayUntil |

| Mutex in ISR / blocking call in ISR | Kernel corruption or hard fault | Notify a task |

| Same priority for everything | Round-robin jitter, missed deadlines | Deadline-monotonic priorities |

| Large structs passed through queues by value | Long copies inside critical sections | Pass pointer to pool buffer |

| Holding a mutex while waiting on a queue | Deadlock / unbounded inversion | Release before blocking |

| Unchecked return values (pdFAIL, NULL) | Silent failures | configASSERT + error path |

10. Checklist

References

Merged Material

Content folded in from overlapping skills and notes.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.