Loading…
Running FreeRTOS on a RISC-V Core

Running FreeRTOS on a RISC-V Core

hardware riscv computer-architecture rtl Superscalar FreeRTOS RTOS Traps CSR Verilator CLI Debugging OpenSource

This post documents the implementation, debugging, and verification required to run FreeRTOS and an interactive command-line interface on the dual-issue RV32IM superscalar processor core from earlier posts. It is the same core that ran DOOM, and the same microarchitecture that achieved 0.7271 CPI on CoreMark.

Transitioning from running standalone bare-metal benchmarks to hosting a preemptive real-time operating system required microarchitectural infrastructure that bare-metal code never touched. The core lacked a functional machine-mode trap architecture, timer interrupts, memory-mapped CLINT timer registers, a fully decoded CSR file, and a bidirectional console interface for interactive command input.

The software environment covers three operating modes: a baseline queue demonstration that validates preemptive context switching between tasks, an allocation-heavy task churn stress test that validates dynamic memory reclamation under heap_4, and an interactive command console built using FreeRTOS-Plus-CLI to inspect runtime kernel state directly over UART. Everything runs in simulation under Verilator with cycle-accurate cross-checks in Icarus Verilog.

Python:     3.13.0
Verilator:  5.032 (Debian 5.032-1+b2)
Iverilog:   Icarus Verilog 12.0
GCC:        riscv64-unknown-elf-gcc 14.2.0 (mabi=ilp32)
Binutils:   GNU binutils 2.44
Target ISA: RV32IM_Zicsr_Zifencei

Summary of Results

Target / MetricSpecification / MeasurementVerification Status
Core ArchitectureIn-order, 5-stage, dual-issue RV32IM superscalarValidated on Verilator & Icarus
Branch PredictorHybrid PHT (Local + Global + Chooser) + 256-entry BTB + 16-entry RASGreen across regression suite
Instruction Memory64 KB single-cycle SRAM at 0x0000_0000 (INST_WORDS = 16384)Sized for RTOS image
Data Memory64 KB dual-port SRAM at 0x8000_0000 (DATA_WORDS = 16384)Top of stack at 0x8000FF00
Timer / CLINT64-bit mtime (0x1000_0008) and mtimecmp (0x1000_0000)1000 cycles per OS tick
Console I/OBidirectional UART at 0x1000_0010 with 256-byte circular RX FIFONon-blocking getchar / putchar
FreeRTOS Demo1,017,410 cycles, 1036 machine traps takenClean MMIO store termination
Stress Test270,403 cycles, 450 machine traps taken24 churn cycles, 0 heap leaks
CLI Automated Run272,477 cycles, 257 machine traps taken7 commands exercised cleanly
CLI Scripted Run98,716 cycles, 55 machine traps takenStreaming UART input from file
Trap Pairing Suite388 pairing tests + 62-point timer interrupt sweep (450 total)450 PASS, 0 FAIL

What FreeRTOS Demands of the Hardware

FreeRTOS on RV32I runs strictly in machine mode. The kernel port expects:

  • Unrestricted machine-mode CSR reads and writes for mstatus, mie, mtvec, mepc, mcause, and mip.
  • A machine timer exposed as two 64-bit memory-mapped registers: free-running counter mtime and compare threshold mtimecmp.
  • An aligned trap vector target that saves task contexts on interrupts and exceptions, returning execution via mret.
  • Functional interrupt enable controls in mstatus (MIE, MPIE) and mie (MTIE, MEIE).
  • An ecall instruction that vectors directly to the trap handler rather than halting the processor.

The port accesses the timer and compare registers through ordinary memory-mapped loads and stores rather than custom instructions. Both memory-mapped addresses must be defined at compile time:

#define configMTIME_BASE_ADDRESS    ( 0x10000008 )
#define configMTIMECMP_BASE_ADDRESS ( 0x10000000 )

Having both addresses explicitly configured caught several early configuration bugs at compile time rather than as silent runtime deadlocks on the initial tick. Because this core omits an MMU and physical memory protection (PMP), tasks execute without hardware memory isolation, and the idle task spins in a loop rather than executing a wait-for-interrupt instruction (wfi).

The core under test had the full dual-issue pipeline, the hybrid branch predictor with local, global, and chooser tables, the BTB, and the return address stack. However, its initial CSR implementation aliased multiple architectural registers into a shared 16-word storage array indexed by addr[3:0]. While sufficient for bare-metal benchmarks, this aliasing broke the moment the kernel attempted critical sections. FreeRTOS disables interrupts with csrc mstatus, 8 and restores them with csrs mstatus, 8. In an aliased CSR file, that clear targeted the storage word shared with other registers, leaving interrupts enabled during task queue manipulations.


Hardware Microarchitecture & RTL Implementation

Bringing the core to a state where it could execute the FreeRTOS scheduler required restructuring the CSR storage, designing a synchronous trap controller, routing timer interrupts into the instruction fetch pipeline, and expanding the memory controller with bidirectional serial communication.

+-----------------------------------------------------------------------------------+
|                        Dual-Issue RV32IM Pipeline with Traps                      |
+-----------------------------------------------------------------------------------+
|  [ IF Stage ]  Fetch pair: instr0 (PC), instr1 (PC+4)                             |
|       |        Branch Predictor (Local + Global + Chooser PHT, 256 BTB, 16 RAS)   |
|       v                                                                           |
|  [ ID Stage ]  Dual Decoder + Hazard Detection + Inter-Slot Dependency Check      |
|       |        Synchronous Trap Unit: Detects ecall / mret in Slot 0 / Slot 1     |
|       |        Squashes wrong-path ecalls on branch/jump redirects                |
|       v                                                                           |
|  [ EX Stage ]  Dual ALU (Single-cycle 64-bit MUL / Divider) + Branch Resolution   |
|       |        Redirects PC on mispredict; flushes younger wrong-path fetches     |
|       v                                                                           |
|  [ MEM Stage]  Dual-Port Memory Controller (0x0000 IMEM, 0x8000 DMEM)             |
|       |        MMIO Aperture (0x1000): mtime, mtimecmp, UART RX/TX, Exit, Traps   |
|       v                                                                           |
|  [ WB Stage ]  Decoded CSR File (12 registers, 2 write ports, slot forwarding)    |
|                Register File (32 x 32-bit, 4 read ports, 2 write ports)           |
+-----------------------------------------------------------------------------------+

Decoded Machine-Mode CSR File

The CSR array was rewritten into a dedicated register file with twelve fully decoded architectural entries: mstatus, mie, mtvec, mscratch, mepc, mcause, mtval, mip, mvendorid, marchid, mimpid, mhartid, and custom control register trapctrl at 0x7C0.

The module provides two independent write ports, one dedicated to each issue slot. When both instructions in an issue pair modify the same CSR in the same cycle, the younger instruction (slot 1) takes precedence, and slot 1 forwards the updated value written by slot 0.

Privilege state transitions adhere strictly to the RISC-V privileged architecture specification:

  • On trap entry: mstatus.MPP is set to machine mode (2'b11), mstatus.MPIE captures the current mstatus.MIE bit, and mstatus.MIE is cleared to disable interrupts.
  • On executing mret: mstatus.MIE is restored from mstatus.MPIE, and mstatus.MPIE resets to 1.
  • mip.MTIP is driven directly by the hardware comparator wire (irq_mtip = (mtime >= mtimecmp)), remaining asserted until software writes a future compare deadline to mtimecmp.
  • mtvec resets to 0x0000_0100.

Register 0x7C0 (CSR_TRAPCTRL) acts as a compatibility bridge: bit 0 toggles between legacy execution where ecall stops the processor (required by older regression tests) and operating system execution where ecall vectors to mtvec.

Synchronous Trap Unit

Synchronous traps (ecall and mret) are decoded out of the instruction decode stage in core_top.v. Taking the trap in decode ensures mepc captures the exact address of the trapping instruction rather than an advanced execution PC:

assign id_sync_trap0 = trap_mode && if_id_valid0 && !hz_stall_id && !hz_flush_id &&
                       !ex_redirect0 && !ex_take_branch1 &&
                       !id_ex_jal1 && !id_ex_jalr1 &&
                       (id_ecall0 || id_is_mret0);
assign id_sync_mret  = id_sync_trap0 && id_is_mret0;
assign id_sync_ecall = id_sync_trap0 && id_ecall0 && !id_is_mret0;

The synchronous trap path is strictly qualified against older pipeline flushes and redirects. If an older branch or jump in the execute stage resolves taken, any younger ecall currently in decode is wrong-path speculative filler and must be squashed rather than committed.

Asynchronous Timer Interrupt Logic

Timer interrupts are evaluated independently from synchronous exceptions. An interrupt is flagged pending whenever the 64-bit cycle counter equals or exceeds the compare value, the timer interrupt enable bit in mie is set, and global interrupts are enabled in mstatus:

assign irq_pending      = irq_mtip && mie_w[7] && irq_global_en;
assign irq_take         = irq_pending && irq_can_take && !id_sync_trap0;
assign trap_take        = sync_take || irq_take;
assign trap_redirect_pc = id_sync_mret ? mepc_w : mtvec_w;

The trap redirect occupies the highest-priority position in the next-PC selection multiplexer, overriding branch predictions, return address stack pops, and sequential fetch increments.

Memory Controller & Bidirectional UART Peripheral

The memory map partitions the 32-bit address space into separate instruction, data, and peripheral apertures:

+-------------------------------------------------------------------------+
|                         Physical Memory Layout                          |
+-------------------------------------------------------------------------+
| 0x0000_0000 - 0x0000_FFFF : 64 KB Instruction Memory (Single-cycle SRAM)|
| 0x1000_0000 - 0x1000_001F : Memory-Mapped Peripheral Block (CLINT/UART) |
| 0x8000_0000 - 0x8000_FFFF : 64 KB Data Memory (Dual-port SRAM)          |
|                             Stack Top: 0x8000FF00                       |
+-------------------------------------------------------------------------+

The peripheral aperture at 0x1000_0000 is decoded on address bits [31:12] == 0x10000. Originally, 0x1000_0010 was a write-only putchar register. Supporting an interactive command console required bidirectional serial communication, so 0x1000_0010 was upgraded to a bidirectional transceiver backed by a 256-byte circular RX FIFO in mem_top.v.

// 256-byte circular UART RX FIFO in mem_top.v
reg [7:0] rx_fifo [0:255];
reg [7:0] rx_wptr;
reg [7:0] rx_rptr;
wire      rx_empty = (rx_wptr == rx_rptr);

wire rx_read0 = mem_re0 && (mem_addr0 == `MMIO_PUTCHAR);
wire rx_read1 = mem_re1 && (mem_addr1 == `MMIO_PUTCHAR);

wire [31:0] uart_rx_data = rx_empty ? 32'hFFFF_FFFF : {24'b0, rx_fifo[rx_rptr]};
wire [31:0] uart_status  = {30'b0, 1'b1, !rx_empty};

always @(posedge clk or posedge rst) begin
    if (rst) begin
        rx_rptr <= 8'd0;
        rx_wptr <= 8'd0;
    end else if (!rx_empty && (rx_read0 || rx_read1)) begin
        rx_rptr <= rx_rptr + 8'd1;
    end
end

Writing to 0x1000_0010 outputs a character to the simulation terminal stdout via $write("%c", ...). Reading from 0x1000_0010 pops the next character from the RX FIFO. If the FIFO is empty, it returns -1 (0xFFFFFFFF), providing standard non-blocking C getchar behavior. A status register at 0x1000_001C reports whether input data is waiting (bit 0) and whether the transmitter is ready (bit 1).

The complete peripheral aperture is organized as follows:

AddressRegisterAccessFunctional Description
0x1000_0000mtimecmp lowRWCompare threshold low 32 bits (resets to 0xFFFFFFFF)
0x1000_0004mtimecmp highRWCompare threshold high 32 bits (resets to 0xFFFFFFFF)
0x1000_0008mtime lowROCycle counter low 32 bits (increments every clock)
0x1000_000Cmtime highROCycle counter high 32 bits (increments every clock)
0x1000_0010putchar / getcharRWWrite: transmits byte to stdout; Read: pops byte from RX FIFO
0x1000_0014exitWOWriting any value terminates simulation
0x1000_0018trap_countRORead-only counter tracking total taken machine traps
0x1000_001Cuart_statusROBit 0: rx_ready (!rx_empty), Bit 1: tx_ready (1'b1)

Stores to the peripheral block decode independently per issue slot to avoid dropouts when both slots write MMIO registers simultaneously:

wire putchar0 = wr0 && (mem_addr0 == `MMIO_PUTCHAR);
wire exit0    = wr0 && (mem_addr0 == `MMIO_EXIT);
wire cmplo0   = wr0 && (mem_addr0 == `MMIO_MTIMECMP_LO);
wire cmphi0   = wr0 && (mem_addr0 == `MMIO_MTIMECMP_HI);

wire [31:0] mtimecmp_lo_next = cmplo1 ? mem_wdata1 :
                               cmplo0 ? mem_wdata0 : mtimecmp[31:0];

Testbench Stream Injection

In tb/tb_rtos.v, an automated reader allows external scripts to feed commands into the simulated core. Upon reset de-assertion, the testbench checks for a local file named cli_input.txt. If the file exists, it reads each byte and pushes it directly into uut.mem.rx_fifo:

integer f_cli;
integer c_cli;
initial begin
    #30;
    f_cli = $fopen("cli_input.txt", "r");
    if (f_cli != 0) begin
        while (!$feof(f_cli)) begin
            c_cli = $fgetc(f_cli);
            if (c_cli >= 0) begin
                uut.mem.rx_fifo[uut.mem.rx_wptr] = c_cli[7:0];
                uut.mem.rx_wptr = uut.mem.rx_wptr + 8'd1;
            end
        end
        $fclose(f_cli);
    end
end

Bootstrap Assembly

The startup sequence in crt0_rtos.S configures the stack pointer to 0x8000FF00, registers freertos_risc_v_trap_handler into mtvec, arms trap mode via 0x7C0, clears the BSS segment, and enters main:

_start:
    li    sp, 0x8000FF00
    la    t0, freertos_risc_v_trap_handler
    csrw  mtvec, t0
    csrwi 0x7C0, 1
    la    t0, __bss_start
    la    t1, __bss_end
1:  bgeu  t0, t1, 2f
    sw    x0, 0(t0)
    addi  t0, t0, 4
    j     1b
2:  call  main

Microarchitectural Debugging and Failure Analysis

Bringing the core to a state where it could execute the FreeRTOS scheduler revealed multiple microarchitectural edge cases where pipeline hazards, dual-issue forwarding, and branch speculation collided with privileged trap semantics. Each failure required tracing signals through Verilator cycle dumps and inspecting the interplay between instruction pairs.

The initial software test halted immediately on the first ecall instead of vectoring to mtvec. Examining the custom control register at 0x7C0 revealed that it remained 0 despite executing csrwi 0x7C0, 1 in early assembly. The RISC-V immediate CSR instructions (csrrwi, csrrsi, csrrci) encode their 5-bit unsigned immediate in the instruction rs1 field ([19:15]). In the original pipeline, the write-data multiplexer was routed to take data solely from the register file forwarding network rather than extracting the immediate bits. Because register x1 held 0 during boot, the write port committed 0 to 0x7C0. The fix checks funct3 bit 2 to select between forwarded register data and the zero-extended immediate field:

.wdata0(id_ex_funct3_0[2] ? {27'b0, id_ex_rs1_0} : ex_rs1_fwd0),

With CSR writes functioning, the subsequent bring-up attempt resulted in an indefinite hang after printing the initial boot banner. The kernel initialized its queue structures and started the scheduler, but tasks never switched. Tracing MMIO access patterns revealed that both configMTIME_BASE_ADDRESS and configMTIMECMP_BASE_ADDRESS had been defined to the identical peripheral base address 0x1000_0000. The port read mtimecmp (initialized to all ones) as the current cycle count, computed an unattainable compare deadline, and never triggered a timer interrupt. Separating the definitions in FreeRTOSConfig.h so that mtime points to 0x10000008 and mtimecmp points to 0x10000000 allowed the hardware comparator to fire periodic ticks as intended:

#define configMTIME_BASE_ADDRESS    ( 0x10000008 )
#define configMTIMECMP_BASE_ADDRESS ( 0x10000000 )

Once the scheduler began switching tasks, console output began losing data. When tasks printed messages concurrently, characters were dropped and lines became interleaved. In the baseline memory controller, both pipeline slots shared a single write strobe for peripheral access. When the dual-issue pipeline issued stores to putchar in both slots during the same cycle, slot 0 overwrote slot 1. Implementing independent per-slot write strobes (putchar0 and putchar1) in mem_top.v allowed both bytes to commit sequentially within the same clock cycle, preserving character ordering across dual-issued stores.

After timer interrupts were operational, an unexpected failure appeared in long runs: the simulator began logging unexpected ecall exceptions approximately every 110 cycles while executing the idle task. The idle loop spins on an unconditional jump:

600: lui  a5,0x80001
604: li   a4,1
608: lw   a3,-996(a5)      # pxReadyTasksLists[0].uxNumberOfItems
60c: bltu a4,a3,614        # if ready count > 1, yield
610: j    610              # spin here
614: ecall                 # portYIELD
618: j    608

Pipeline traces captured the exact sequence:

43379  0x610   IF/ID = (608 lw, 60c bltu)   squash_s1 = 1   inter-slot load RAW, replay at 0x60c
43380  0x60c   IF/ID = bubble
43381  0x614   IF/ID = (60c bltu, 610 j)    no redirect    bltu resolves not taken, fetch ran on
43382  0x61c   IF/ID = (614 ecall, 618 j)   id_ex_jal1 = 1 the 610 j resolves in EX here
43383  0x5f00  trap taken on the ecall

The branch predictor operates solely on slot 0. When slot 1 contains an unconditional jump, the sequential fetch for the following cycle pulls in wrong-path instructions until the execute stage completes the redirect. In cycle 43382, that wrong-path fetch pair contained the ecall at 0x614. The synchronous trap logic decoded the ecall in decode and vectored to mtvec on the same cycle that the jump at 0x610 was redirecting the pipeline from execute. Adding pipeline flush guards (hz_flush_id, ex_redirect0, ex_take_branch1, id_ex_jal1, id_ex_jalr1) ensured wrong-path ecall instructions are squashed before they can alter architectural state.

Resolving the speculative trap storm exposed a subtler hazard livelock. A slot 1 trap operation is replayed to align it to slot 0 on the next cycle, ensuring mepc records the exact address of the trapping instruction. When slot 0 was an older jump that had already redirected the pipeline, the hazard unit triggered an inter-slot replay anyway, holding the fetch PC and repeatedly flushing the decode stage. Interrupts could never be taken because irq_can_take requires decode to be free of flushes. Updating the hazard unit to prioritize slot 0 control transfers and check for pending redirects resolved the livelock:

wire inter_slot_trap = s1_id_trap_op && !inter_slot_ctrl && !s0_id_trap_op;
assign flush_id  = do_flush || ((inter_slot_load_raw || inter_slot_trap ||
                    (inter_slot_ctrl && !s0_id_branch_pred_taken) ||
                    inter_slot_mem) && !eff_load_use_stall);

A final hurdle occurred during modifications to the pipeline reset logic, when an automated editor script stripped multiple sequential always blocks from core_top.v. The damaged file was reconstructed using the pre-fork baseline as a structural reference. A verification validator parsed signal assignments across both versions, comparing assigned signal sets and verifying assignment parity across reset, flush, and normal execution branches. The reconstructed module passed all 31 compliance regression tests, with baseline benchmarks matching recorded cycle counts (hello at 20 cycles, fibonacci at 239, binary_search at 426).


FreeRTOS Bring-Up and Concurrency Validation

With the microarchitecture stabilized, software bring-up focused on kernel preemption, task communication, and dynamic memory safety.

Baseline Queue Demonstration

The baseline demonstration in main.c validates preemptive context switching and inter-task communication over a queue.

A producer task at priority 1 transmits twenty sequential integers into a 4-deep queue, inserting a 50 ms delay between sends. A consumer task at priority 2 blocks on the queue, processes each message, and tracks running totals. When all twenty items are processed, the consumer queries its stack high-water mark and terminates the simulation:

FreeRTOS on rv32i-super-br-hybp-btb-ras-hzopt-luopt-fulu
[consumer] item 1 at tick 1, sum 1
[consumer] item 2 at tick 52, sum 3
[producer] sent 2 at tick 53
[consumer] item 3 at tick 103, sum 6
[producer] sent 3 at tick 104
...
[consumer] item 19 at tick 919, sum 190
[producer] sent 19 at tick 920
[consumer] item 20 at tick 970, sum 210
[consumer] done, stack high water mark 185 words left
FreeRTOS ran on the core.

The run executes in 1,017,410 cycles and records 1036 machine traps. Both Verilator and Icarus Verilog produce identical cycle counts and trap logs.

Task Churn and Dynamic Heap Reclamation

The stress test in stress.c evaluates concurrency and memory reclamation under heavy allocation churn.

Two producer tasks at priority 2 send structured 32-bit records into a four-deep queue guarded by an eight-credit counting semaphore, while two consumer tasks at priority 3 pop and validate the stream. Concurrently, a churn task creates and deletes child tasks across 24 iterations, while a software timer tracks periodic heartbeat ticks.

Dynamic task deletion initially exhausted memory. In FreeRTOS, calling vTaskDelete places task memory onto a cleanup list; the idle task performs the actual deallocation. Because worker tasks ran continuously without yielding, the idle task starved, causing heap_4 to run dry after 11 iterations.

Static delays proved unreliable because printing debug messages altered scheduling timing enough to mask failures. An adaptive polling loop replaced static sleeps, monitoring available heap bytes until memory returned to baseline levels:

for( waited = 0; waited < 50U; waited++ )
{
    if( ( unsigned int ) xPortGetFreeHeapSize() >= before )
    {
        break;
    }
    vTaskDelay( pdMS_TO_TICKS( 1 ) );
}
if( ( unsigned int ) xPortGetFreeHeapSize() < before )
{
    ulReclaimFailures++;
}

The stress test completes in 270,403 cycles with 450 traps:

[stress] FreeRTOS stress demo
[consumer] validated 60 items, errors 0, missing 0
[churn] created 24, deleted 24, shared counter 24
[timer] heartbeat fires 5
[heap] free bytes 14672, min ever 9504
[stack] consumer high water 181 words
[heap] reclaim waits max 3 ticks, failures 0
[stress] PASS

The free heap drops to 9,504 bytes during peak churn and recovers fully to 14,672 bytes upon completion.


Directed Trap-Pairing & Edge-Case Verification

To verify that trap entry and return logic functions across all issue-slot alignments, scripts/rtos/trap_pairs.py generates 388 bare-metal tests pairing ecall against every major instruction class: ALU operations, multiplies, divisions, loads, stores, taken and not-taken branches, jumps, and CSR accesses.

Each test binary pairs with a reference twin where ecall instructions are replaced with nop. Because trap entry and mret should be architecturally transparent to user registers, both binaries must write identical state across all memory locations.

A secondary test family runs a 62-point timer interrupt sweep, arming mtimecmp to fire at every individual clock cycle across a 55-cycle execution window. The interrupt fired and was serviced cleanly at all 62 arrival points without instruction leakage or context corruption.


Interactive Console Architecture: FreeRTOS-Plus-CLI Integration

Once the scheduler and queue paths were proven, I added an interactive command-line interface to allow querying system health, task states, heap usage, and hardware registers without recompiling the firmware.

FreeRTOS does not bundle a CLI in the kernel. The official project maintains an upstream companion library, FreeRTOS-Plus-CLI, in the main repository under FreeRTOS-Plus/Source/FreeRTOS-Plus-CLI/. The library provides a command parser and registration engine, exposing a single built-in command: help.

software/freertos/
├── FreeRTOSConfig.h           # configCOMMAND_INT_MAX_OUTPUT_SIZE & configUSE_TRACE_FACILITY
├── crt0_rtos.S                # Boot assembly and trap arming
├── link.ld                    # Dual-window linker script
├── build_cli.sh               # Compiler script producing freertos_cli.elf
├── cli_main.c                 # Application entry, UART loop, and console task
├── cli/
│   ├── FreeRTOS_CLI.h         # Upstream command interpreter header
│   ├── FreeRTOS_CLI.c         # Upstream command interpreter engine
│   ├── cli_commands.h         # Command declarations
│   └── cli_commands.c         # task-stats, heap-info, read-timer, trap-stats, echo, exit
└── shim/
    ├── libc_shim.c            # Freestanding memcpy, memset, strlen, strcmp
    └── mini_printf.c          # Freestanding mini_snprintf / mini_vsnprintf

Freestanding Mini-Printf Implementation

Standard FreeRTOS CLI examples rely on libc sprintf or snprintf. In a freestanding RISC-V environment without newlib runtime support, linking standard stdio pulled in floating-point emulators, heap locks, and re-entrant state tables that bloated binary size.

To avoid library bloat, I implemented a standalone string formatter in shim/mini_printf.c. It provides mini_snprintf and mini_vsnprintf with zero external dependencies, supporting strings, decimal integers, hexadecimals with width padding, and characters.

Core Command Suite

Six diagnostic commands were implemented in cli/cli_commands.c to expose microarchitectural and kernel state alongside the upstream help facility:

CommandSource FileFunctionality
helpFreeRTOS_CLI.cGenerates command listings and usage syntax
task-statscli_commands.cFormats an ASCII table showing task names, execution states, priorities, and stack high-water marks
heap-infocli_commands.cQueries heap_4 allocator metrics via xPortGetFreeHeapSize() and xPortGetMinimumEverFreeHeapSize()
read-timercli_commands.cReads kernel tick count alongside physical 64-bit mtime and mtimecmp registers
trap-statscli_commands.cReads the hardware machine trap counter at 0x1000_0018
echo <text>cli_commands.cEchoes variable-length input parameter strings back to the console
exitcli_commands.cWrites to 0x1000_0014 to cleanly stop simulation

During bring-up of the CLI application, several integration issues surfaced across the parser, formatting library, and memory layout. Multi-word arguments passed to echo initially failed validation because the command structure specified a single argument; setting the parameter count expectation to -1 configured the command definition to treat trailing words as a single variable-length payload. When printing task tables, passing length-bounded strings to mini_snprintf with %.*s specifiers produced literal *s characters because the lightweight formatter omitted precision specifiers; replacing the formatting call with a direct bounded copy into the write buffer corrected the output. Furthermore, because the compiled CLI binary expanded to approximately 34 KB, the conversion utility scripts/elf2hex.py initially truncated the image when running with default 16 KB boundaries; setting INST_WORDS=16384 and DATA_WORDS=16384 ensured full 64 KB memory images were generated without truncating executable text.

Console Task Execution

The console task (vCLICommandConsoleTask) runs at priority 2 with a 512-word stack alongside a background worker task. It polls console_getc() at 0x1000_0010, echoes incoming characters, handles backspace erasure (\b and DEL), and dispatches complete lines to FreeRTOS_CLIProcessCommand.

The interpreter supports multi-call pagination: callbacks return pdTRUE while additional output remains and pdFALSE when complete, allowing tables to stream across buffer boundaries without memory overflow.

If no characters are received over UART RX during boot, the console task executes an automated self-test sequence, exercising all seven commands before shutting down. The automated run completes in 272,477 cycles and 257 traps.

Feeding commands interactively via cli_input.txt streams input through the hardware RX FIFO in real time:

Booting FreeRTOS-Plus-CLI Demo...
Tasks created, starting scheduler...

============================================================
       FreeRTOS-Plus-CLI on RV32IM Superscalar Core         
============================================================
FreeRTOS interactive command console initialized.
Type 'help' to view available commands.

FreeRTOS> task-stats

Task         State  Prio  Stack  Num 
---------------------------------------
CLI_Console  X 2 377 2
IDLE         R 0 82 3
worker       B 1 213 1
Tmr Svc      B 7 208 4

FreeRTOS> heap-info

Free Heap Size        : 12848 bytes
Min Ever Free Heap    : 12848 bytes

FreeRTOS> read-timer

FreeRTOS Tick Count   : 45
Hardware mtime        : 0x0000000000016683
Hardware mtimecmp     : 0x00000000000166bd

FreeRTOS> echo Custom Command Over UART RX!

Custom Command Over UART RX!

FreeRTOS> exit

============================================================
         RV32I RTOS BRING-UP RESULTS
============================================================
Total cycles:  98716
Ended by:        MMIO exit store
Timed out:      NO
Traps taken:   55

How to Add Custom Commands to the CLI

Adding custom commands requires no RTL edits. The entire implementation resides in software within software/freertos/cli/cli_commands.c.

Step 1: Implement the Command Callback

Define a callback function complying with pdCOMMAND_LINE_CALLBACK. The function receives the write buffer pointer, maximum buffer length, and raw command input string:

// software/freertos/cli/cli_commands.c

static BaseType_t prvCsrDumpCommand( char *pcWriteBuffer,
                                     size_t xWriteBufferLen,
                                     const char *pcCommandString )
{
    ( void ) pcCommandString;
    uint32_t mstatus, mie, mtvec, mcause;

    // Inline assembly to read core machine registers
    __asm__ volatile( "csrr %0, mstatus" : "=r"( mstatus ) );
    __asm__ volatile( "csrr %0, mie"     : "=r"( mie ) );
    __asm__ volatile( "csrr %0, mtvec"   : "=r"( mtvec ) );
    __asm__ volatile( "csrr %0, mcause"  : "=r"( mcause ) );

    mini_snprintf( pcWriteBuffer, xWriteBufferLen,
                   "\r\nmstatus : 0x%08x\r\nmie     : 0x%08x\r\n"
                   "mtvec   : 0x%08x\r\nmcause  : 0x%08x\r\n",
                   mstatus, mie, mtvec, mcause );

    // Return pdFALSE to signal that all output has been written
    return pdFALSE;
}

If a command generates more text than can fit in a single buffer, it can maintain state in a static index, return pdTRUE, and let the console loop call it repeatedly until all chunks are transmitted.

Step 2: Define the Command Structure

Instantiate a CLI_Command_Definition_t structure providing the command invocation name, help string, callback pointer, and expected parameter count:

// software/freertos/cli/cli_commands.c

static const CLI_Command_Definition_t xCsrDumpCommand =
{
    "csr-dump",                                      // Command string (all lowercase)
    "\r\ncsr-dump:\r\n Displays machine CSRs\r\n",  // Help documentation string
    prvCsrDumpCommand,                               // Callback function pointer
    0                                                // Expected parameter count (-1 for variable)
};

Step 3: Register the Command

Register the structure within vRegisterCLICommands():

// software/freertos/cli/cli_commands.c

void vRegisterCLICommands( void )
{
    FreeRTOS_CLIRegisterCommand( &xTaskStatsCommand );
    FreeRTOS_CLIRegisterCommand( &xHeapInfoCommand );
    FreeRTOS_CLIRegisterCommand( &xReadTimerCommand );
    FreeRTOS_CLIRegisterCommand( &xTrapStatsCommand );
    FreeRTOS_CLIRegisterCommand( &xEchoCommand );
    FreeRTOS_CLIRegisterCommand( &xExitCommand );

    // Register custom command
    FreeRTOS_CLIRegisterCommand( &xCsrDumpCommand );
}

The underlying registry stores commands in a dynamically allocated linked list, so there is no arbitrary compile-time cap on the number of registered commands.

Step 4: Console Dispatch Loop

In software/freertos/cli_main.c, the console task passes the assembled command string to FreeRTOS_CLIProcessCommand and drains the output buffer:

// software/freertos/cli_main.c

static void prvExecuteCommand( const char *pcCommand )
{
    char *pcOutputBuffer;
    BaseType_t xMoreDataToFollow;

    pcOutputBuffer = FreeRTOS_CLIGetOutputBuffer();

    do
    {
        xMoreDataToFollow = FreeRTOS_CLIProcessCommand( pcCommand,
                                                        pcOutputBuffer,
                                                        configCOMMAND_INT_MAX_OUTPUT_SIZE );
        console_puts( pcOutputBuffer );
    } while( xMoreDataToFollow != pdFALSE );

    console_puts( "\r\n" );
}

Complete Verification Results

Every cycle count and trap statistic reported below represents a clean, fully reproducible run:

Program / Test SuiteCyclesTraps TakenResult / Status
Instruction Regression Suiten/an/a31 PASS, 0 FAIL
hello (Parent ELF)200Matches recorded baseline
fibonacci (Parent ELF)2390Matches recorded baseline
binary_search (Parent ELF)4260Matches recorded baseline
csr_trap_test4682Clean MMIO exit
CoreMark 1.02,233,14500.7271 CPI, legacy halt
FreeRTOS Baseline Demo1,017,4101036Clean MMIO exit (Verilator & Icarus match)
FreeRTOS Stress Demo270,403450[stress] PASS (Verilator & Icarus match)
FreeRTOS CLI (Automated)272,477257Clean MMIO exit (7 commands executed)
FreeRTOS CLI (UART Stream)98,71655Clean MMIO exit (Live UART RX execution)
Directed Trap-Pairing Tests450 programsn/a450 PASS, 0 FAIL

Build System and Execution Flow

The software binaries compile using GNU toolchains targeting rv32im_zicsr_zifencei with ilp32 ABI and medlow code model.

Step 1: Building the Software

Each software target has a dedicated compilation script inside software/freertos/:

cd software/freertos

# Build baseline queue demo -> freertos_demo.elf
bash build.sh

# Build task churn stress test -> freertos_stress.elf
bash build_stress.sh

# Build interactive CLI application -> freertos_cli.elf
bash build_cli.sh

Step 2: Generating Memory Hex Images

The linker script places instruction code at 0x00000000 and data/heap at 0x80000000. The Python conversion utility formats the ELF into Verilator memory initialization files:

INST_WORDS=16384 DATA_WORDS=16384 python3 scripts/elf2hex.py \
    software/freertos/freertos_cli.elf \
    hex/inst_mem.hex \
    hex/data_mem.hex

Step 3: Running the Simulation

Simulations execute using the compiled Verilator binary:

# Execute CLI demo with automated self-test fallback
./run_cli.sh

# Feed custom commands through the hardware UART RX FIFO
cat << 'EOF' > cli_input.txt
task-stats
heap-info
read-timer
echo Testing Custom Input Stream!
exit
EOF

./run_cli.sh

Architectural Limits and Next Steps

  • Privilege Mode: Execution runs entirely in machine mode. Tasks share a flat address space without memory protection, physical memory protection (PMP), or virtual memory translation.
  • Idle Power Management: The idle task spins on a conditional branch rather than executing wfi. While functionally valid in simulation, a physical silicon deployment would gate the core clock during idle periods to eliminate dynamic power consumption.
  • Interrupt Latency: The processor supports only the machine timer interrupt and synchronous ecall and mret exceptions. Integrating an external interrupt controller (such as a PLIC or CLIC) to service asynchronous external interrupts from the UART receiver and physical peripherals represents the primary next hardware milestone.

References and Sources

  • FreeRTOS Kernel Developer Guide and RISC-V Porting Documentation, FreeRTOS.org.
  • FreeRTOS-Plus-CLI Documentation and Source Tree, Amazon Web Services / FreeRTOS.
  • RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Document Version 20211203.
  • NEORV32 RISC-V Processor Project (stnolting/neorv32), Memory-Mapped Timer and Console Architecture.
  • SiFive Technical Notes, Machine-Mode Context Switching and portYIELD Vectoring on RV32.
  • VexRiscv FreeRTOS Porting Notes, Machine Trap Stack Frame and Return Sequences.