The user wants an implementation of a Real-Time Operating System (RTOS) task scheduler in C for an embedded system.
1. Analyze the Request:
Goal: Implement an RTOS task scheduler.
Language: C.
Target: Embedded system (implies resource constraints, deterministic behavior, no standard library usage if possible or strictly controlled).
Type: "Real-time" implies we need to handle priorities, context switching, and potentially timing mechanisms (tick).
2. Determine the Scope:
Writing a full production-grade RTOS (like FreeRTOS or Zephyr) is too complex for a single response. I need to create a cooperative or preemptive minimal viable scheduler that demonstrates the core concepts:
A scheduler algorithm (e.g., Priority-based Round Robin or simple Round Robin).
A system tick (SysTick).
3. Choose the Architecture:
Cooperative vs. Preemptive: Preemptive is more "real-time" and standard for RTOS demos, but it's much harder to implement generically in portable C because context switching is architecture-specific (assembly required for register manipulation). Cooperative is easier but less "RTOS-like" in terms of hard real-time responsiveness.
Decision: I will implement a Preemptive, Priority-based Scheduler but abstract the architecture-specific context switching part into clearly marked assembly or pseudo-assembly placeholders (using ARM Cortex-M as the standard example, as it's the most common embedded target). This makes the example concrete and usable.
Stack Frame: On ARM Cortex-M, the hardware pushes R0-R3, R12, LR, PC, xPSR when an interrupt occurs. The software needs to push R4-R11. The initial stack must look like it was interrupted.
Scheduling Logic:
Find the highest priority task in the READY state.
If it's different from current_task, trigger a context switch.
6. Refining the Implementation Details:
Portability: I need to warn the user that context switching requires assembly specific to the MCU (ARM, AVR, RISC-V). I'll target ARM Cortex-M (STM32, NRF52, etc.) because it's the industry standard for this type of coding exercise.
Simplicity vs. Robustness:
Fixed number of tasks (simple array) vs. Linked list. -> Array is simpler.
No semaphores/mutexes (keep it to just scheduling).
Simple delay mechanism.
7. Step-by-Step Code Construction:
Headers:stdint.h, stdbool.h.
Configuration: Define stack sizes, max tasks.
Context Switching (The tricky part): I need to explain how it works.
Save R4-R11 to current task stack.
Save current task SP to TCB.
Load next task SP from TCB.
Load R4-R11 from stack.
Return from exception (restores R0-R3, PC, etc).
The Scheduler Function:
Iterate through all tasks.
Find the one with state == READY and highest_priority.
Set next_task.
The SysTick Handler:
Decrement sleep counters.
Wake up tasks.
Call the scheduler.
8. Structuring the Explanation:
Introduction: Acknowledge the complexity and the target architecture (Cortex-M).
Part 1: Data Structures: TCB and Stack.
Part 2: The Context Switch (Assembly): This is crucial.
Part 3: The API (C code): Create Task, Start, Yield.
Part 4: The Main Example: How to use it.
Disclaimer: Educational purposes, not production-ready (no protection, starvation handling, etc.).
9. Self-Correction/Review during drafting:
Correction: Initially, I thought about a cooperative scheduler because it's pure C. But the prompt asks for an RTOS. A cooperative scheduler is just a switch statement wrapper. Preemptive is the "real deal". I must use assembly. I will write the assembly for GNU Assembler (GCC).
Refinement: The stack initialization is specific. Cortex-M expects xPSR at the top, then PC, LR, etc. I must get the bit for xPSR correct (Thumb mode bit).
10. Final Code Assembly (Mental Check of the Cortex-M Assembly):
11. Output Generation: (Proceeding to generate the response based on these steps).
Implementing a full Real-Time Operating System (RTOS) from scratch is a complex task involving architecture-specific assembly code for context switching. However, I can provide a minimal, functional preemptive scheduler for the ARM Cortex-M architecture (the most common 32-bit embedded MCU).
This implementation includes the core components:
Task Control Block (TCB): Data structure to hold task state.
Context Switching: Assembly code to save/restore CPU registers.
Scheduler: Logic to decide which task runs next (Priority-based).
SysTick: Hardware timer to trigger the context switch.
This contains the logic for managing tasks. Note the inclusion of __asm blocks or specific CMSIS instructions, assuming a GCC/ARM compiler.
c
3. Example Usage (main.c)
Here is how you would use this in your embedded application.
c
#include "rtos.h"
#include <stdio.h> // Assumes you have a way to print (e.g., ITM, UART)
TCB_t task1_tcb;
TCB_t task2_tcb;
void Task1_Function(void) {
while(1) {
printf("Task 1 Running\n");
RTOS_Delay(1000); // Sleep for 1 second
// Task blocks here, CPU switches to Task 2
}
}
void Task2_Function(void) {
while(1) {
printf("Task 2 Running\n");
RTOS_Delay(500); // Sleep for 0.5 seconds
}
}
int main(void) {
// Hardware Init (Clocks, GPIOs, etc.)
// SystemInit();
RTOS_Init();
RTOS_CreateTask(&task1_tcb, "Task 1", Task1_Function, 1);
RTOS_CreateTask(&task2_tcb, "Task 2", Task2_Function, 2); // Lower priority
// In a real scenario, you need a specific ASM startup routine
// to restore the first context.
// RTOS_Start();
while(1);
}
Key Concepts Explained
Context Switching (PendSV):
We use the PendSV (Pendable Service Call) interrupt. It is designed specifically for OS context switching because it can be configured to the lowest priority, ensuring a context switch only happens when no other interrupts are running.
The __attribute__((naked)) function means the compiler adds no prologue/epilogue code; we have full control over registers.
We save registers R4-R11 (the "callee-saved" registers). The hardware automatically saves R0-R3, R12, LR, PC, xPSR onto the stack when the interrupt fires.
Stack Initialization:
Each task needs its own stack.
We "fake" the stack contents. We push the initial values of registers so that when the context switcher "restores" this task for the first time, it pops the PC (Program Counter) pointing to Task_Function, effectively booting the task.
RTOS_Delay:
This is a blocking call. It changes the task state to BLOCKED and triggers a yield (PendSV).
The SysTick handler decrements the delay counter. When it hits 0, it marks the task as READY.
Limitations for Production
This is a minimal educational example. A production RTOS (like FreeRTOS or Zephyr) adds:
Mutexes/Semaphores: To prevent race conditions when tasks share resources.
Linked Lists: To efficiently manage ready/blocked lists (O(1) operations).
MPU Support: Memory Protection Unit support to crash a rogue task without crashing the kernel.
Tickless Idle: To save power by stopping the clock when no tasks are scheduled to run.
#include "rtos.h"
#include <string.h>
// --- Global Scheduler State ---
static TCB_t* current_task = NULL;
static TCB_t* next_task = NULL;
static TCB_t task_list[MAX_TASKS];
static uint32_t task_count = 0;
// --- Context Switching (Architecture Specific) ---
// For ARM Cortex-M, the hardware saves R0-R3, R12, LR, PC, xPSR automatically.
// We must save R4-R11 manually.
__attribute__((naked)) void PendSV_Handler(void) {
// 1. Save current context (Manual save R4-R11)
__asm volatile (
"MRS R0, PSP\n" // Get Process Stack Pointer
"STMDB R0!, {R4-R11}\n" // Push R4-R11 onto stack
"LDR R1, =current_task\n"
"LDR R2, [R1]\n" // Get address of current TCB
"STR R0, [R2]\n" // Save new SP into TCB
);
// 2. Run Scheduler Logic (C function)
extern void RTOS_Schedule(void);
RTOS_Schedule();
// 3. Restore next context
__asm volatile (
"LDR R0, =current_task\n"
"LDR R1, [R0]\n" // Load address of current_task (now updated)
"LDR R2, [R1]\n" // Load the SP from the TCB
"LDMIA R2!, {R4-R11}\n" // Pop R4-R11
"MSR PSP, R2\n" // Set Process Stack Pointer
"ISB\n" // Instruction Synchronization Barrier
"BX LR\n" // Return from exception
);
}
// --- Scheduler Logic ---
void RTOS_Schedule(void) {
TCB_t *highest_prio_task = NULL;
uint32_t highest_prio = 0xFFFFFFFF; // Max uint
// Simple Round-Robin within Priority, or Strict Priority?
// Here: Strict Priority Search.
for(int i = 0; i < task_count; i++) {
if (task_list[i].state == TASK_READY || task_list[i].state == TASK_RUNNING) {
if (task_list[i].priority < highest_prio) {
highest_prio = task_list[i].priority;
highest_prio_task = &task_list[i];
}
}
}
// If we found a task (and it's not the same as current, though switching is safe anyway)
if (highest_prio_task != NULL) {
if (current_task != NULL && current_task->state == TASK_RUNNING) {
current_task->state = TASK_READY;
}
current_task = highest_prio_task;
current_task->state = TASK_RUNNING;
}
}
// --- System Tick Handler ---
// Called by hardware every 1ms
void SysTick_Handler(void) {
// Handle delays
for(int i = 0; i < task_count; i++) {
if (task_list[i].state == TASK_BLOCKED && task_list[i].delay_ticks > 0) {
task_list[i].delay_ticks--;
if (task_list[i].delay_ticks == 0) {
task_list[i].state = TASK_READY;
}
}
}
// Trigger context switch
SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk;
}
// --- API Implementation ---
void RTOS_Init(void) {
// Set PendSV priority to lowest (0xFF) so it doesn't interrupt critical IRQs
NVIC_SetPriority(PendSV_IRQn, 0xFF);
task_count = 0;
memset(task_list, 0, sizeof(task_list));
}
void RTOS_CreateTask(TCB_t *tcb, const char *name, void (*task_func)(void), uint32_t priority) {
// 1. Setup TCB
tcb->task_id = task_count++;
strcpy((char*)tcb->task_name, name); // Simplified
tcb->priority = priority;
tcb->state = TASK_READY;
// 2. Setup Stack
// Cortex-M stack grows downward.
// We need to initialize the stack frame as if the task was interrupted
// before running the first instruction.
uint32_t *stack = tcb->stack_base + STACK_SIZE;
// xPSR (Thumb bit must be set = 1 << 24)
*(--stack) = 0x01000000;
// PC (Program Counter -> task entry point)
*(--stack) = (uint32_t)task_func;
// LR (Link Register -> return address, usually fatal for tasks)
*(--stack) = 0xFFFFFFFD;
// R12, R3, R2, R1, R0 (Hardware pushed)
for (int i = 0; i < 5; i++) {
*(--stack) = 0x00000000;
}
// R4-R11 (Software pushed - initialize to 0)
for (int i = 0; i < 8; i++) {
*(--stack) = 0x00000000;
}
tcb->stack_ptr = stack;
}
void RTOS_Delay(uint32_t ticks) {
if (current_task == NULL) return;
// Enter critical section (disable interrupts)
__disable_irq();
current_task->delay_ticks = ticks;
current_task->state = TASK_BLOCKED;
// Force immediate context switch
SCB->ICSR |= SCB_ICSR_PENDSVSET_Msk;
// Exit critical section
__enable_irq();
// Wait until context switch actually happens (barrier)
__asm volatile ("nop");
}
void RTOS_Start(void) {
// Find the first task to run
RTOS_Schedule();
// Setup PSP (Process Stack Pointer) to the first task
__set_PSP((uint32_t)current_task->stack_ptr);
// Switch to use PSP, Thread Mode (unprivileged)
__set_CONTROL(0x02);
__ISB();
// Start SysTick Timer
SysTick_Config(SystemCoreClock / SYSTICK_FREQ);
// Jump to the first task
// Note: In a real OS, we would load the context and use 'BX LR'.
// Here, since we set the stack frame manually, we restore R4-R11
// and then trigger the exception return logic manually.
// Simplified: Just call the function for this demo (Not strictly preemptive start).
// In a real ASM file, you would have a "StartFirstTask" routine.
// For this C approximation, we rely on the first SysTick to trigger the switch
// or manually branch.
}