Skip to content
wangchdoPublic

About

Compact preemptive RTOS with a from-scratch TCP/IP stack and devicetree-driven drivers -- ARM, RISC-V, QEMU, ~50K LOC.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

eastra

License: Apache-2.0 Language: C11 Platforms

A compact, complete preemptive RTOS platform for bare-metal 32/64-bit machines, with a TCP/IP stack written from scratch (BSD-style sockets, DHCP/DNS/SNTP/HTTP clients -- ~60 Mbit/s UDP on a $20 Cortex-M4 board, no lwIP, no blobs): devicetree-driven driver framework, audio, filesystems, touch GUI via LVGL, and multi-architecture support -- everything a real product needs, in about 50 K lines of C with no external runtime dependencies. It boots on QEMU (virt machines) and on real hardware (ALIENTEK STM32F407ZG Explorer, Nordic nRF5340 DK), with an arch/board split meant to make porting straightforward. The codebase is small enough to read end to end and every subsystem is covered by on-device test suites -- valuable whether you ship it or study it.

lvgl_studio on the ALIENTEK Explorer: SNTP clock, live gauges, weather

lvgl_studio on the Explorer board -- SNTP-synchronized clock, live potentiometer/CPU-load gauges, weather over HTTP.

Why eastra

  • Real numbers, on cheap hardware: ~60 Mbit/s UDP TX and ~40 Mbit/s flood RX with zero corruption, measured on a 100 Mbit link through the STM32F407's Ethernet MAC -- with a TCP/IP stack written from scratch (not lwIP, not pre-optimized silicon blobs).
  • Deterministic memory, no surprises in the IRQ path: fixed nbuf/memp pools served smallest-fit first -- the receive interrupt never touches the heap or takes a lock. The heap itself is TLSF: O(1) alloc/free, bounded worst case.
  • Priority inheritance that is actually tested: recursive mutexes with PI, verified by on-target suites alongside the scheduler, IPC, and network stacks (kernel, TCP/UDP/socket/DHCP, peripherals -- all runnable from the shell).
  • Devicetree + Kconfig composition in the Zephyr shape, without Zephyr's size: board.dts per board, per-driver Jinja2 templates, phandle-ordered bring-up, and an image that contains exactly what the board and your app enable.
  • Readable core: the whole platform is ~50 K lines of C with no external runtime dependencies -- you can hold the TCP fast path or the scheduler in your head, and the tree is organized so you can find anything in two hops.

Layout

Directory Contents
arch/ Architecture ports: riscv (M-mode, CLINT/PLIC), arm (Cortex-M: SysTick/NVIC/PendSV), arm64 (EL1, GIC)
kernel/ Scheduler, threads, IPC, tick timers, workqueue, heap, IRQ dispatch
drivers/ Driver framework + drivers (see below)
subsys/ Console, shell, logging, network stack, audio, filesystem, SD, input bus, IPC/RPMsg, Bluetooth, LVGL
samples/ Runnable examples: application/ (own main()), commands/ (shell demos)
lib/ printk, ring buffer, TLSF heap (libc comes from the toolchain)
boards/ Board support (defconfig + devicetree + bring-up)
soc/ SoC glue (Kconfig defaults + shared .dtsi)
cmake/ Build helpers: eas_library(), Kconfig integration, toolchains, external manifest
scripts/ Devicetree generator, Kconfig driver, style checkers, PC-side test helpers, manifest tooling
test/ host/ unit tests (CTest); target/ on-device test suites

Kernel

  • Fixed-priority bitmap scheduler with per-priority run queues (O(1) pick); the queueing policy is a Kconfig choice: SCHED_PRIORITY (preemptive FIFO), SCHED_RR (round-robin with TIMESLICE_TICKS), or SCHED_COOP. On Cortex-M the deferred context switch runs at lowest exception priority (tail-chaining aware) and survives spurious PendSV wakes.
  • Threads with static or heap stacks, naming, and sleep/yield; suspend/resume and exit/delete are available, a thread whose entry returns terminates itself, and the idle thread reclaims heap-backed threads that exited.
  • IPC: counting semaphores, recursive mutexes with priority inheritance, event groups, message queues (circular buffer, blocking on both ends).
  • One-shot tick timers (eas_timer) with IRQ-safe ordered insert, start/stop from any context; monotonic clock with wrap-safe expiry comparisons (CLOCK_EXPIRED).
  • Workqueue (eas_work_submit, delayed work eas_dwork_schedule driven by kernel timers) on a configurable worker thread.
  • Runtime IRQ registration (eas_irq_connect) over a fixed vector table, per-arch nesting policy.
  • Bounded heap (eas_malloc/calloc/free) with alignment, backed by a TLSF allocator.

Not modeled (deliberately, so far): SMP, FPU context (all ports are soft-float / no-FP builds), tickless idle, MPU management, userspace.

Architecture ports and boards

The porting surface is <eas/arch.h>: context switch, IRQ lock/restore, timer tick, CPU idle. Three ports are in tree:

Arch Core machinery
riscv M-mode trap vector, CLINT timer, PLIC interrupts (RV32/RV64)
arm Cortex-M3/4/7/33 (Armv7-M / Armv8-M Mainline): vector table, PendSV switch, SysTick, NVIC; dual IRQ masking (PRIMASK vs BASEPRI)
arm64 ARMv8-A EL1 exceptions, GICv2 (GIC-400) interrupts, generic timer

Boards (each with defconfig + board.dts + clock bring-up):

Board SoC / chip Highlights
qemu/riscv64, qemu/riscv32 QEMU virt ns16550 UART, PLIC; riscv64 adds an e1000 NIC (full net stack)
qemu/arm64 QEMU virt (cortex-a53) PL011 UART, GIC
qemu/b-l475 STM32L4x5 (B-L475E-IOT01A) Cortex-M4, USART1/2
nrf5340dk Nordic nRF5340 app core Cortex-M33, UARTE (EasyDMA), IPC mailbox to the network core (BLE RPMsg)
stm32f407zg-explorer ALIENTEK Explorer STM32F407ZGT6 the actively developed hardware target @ 168 MHz (see below)

The boards/stm32f407zg-explorer board brings up every on-board peripheral: USART1 console, Ethernet MAC + YT8512C RMII PHY, I2S2 + ES8388 codec (audio card), soft-I2C (EEPROM/codec) and touch I2C, GT9xxx capacitive touch, FSMC SRAM (1 MiB) and FSMC LCD (800x480 RGB565), gpio-keys, ADC/DAC, TIM2/3/9/14 (PWM/capture), SD over SPI and native SDIO, with DHCP + DNS + SNTP on the wire.

The ALIENTEK Explorer board wired up: Ethernet to the PC peer, ST-Link, USB-serial console

Touch recorder with live VU meter   Hardware controls page: LEDs and DAC slider

Touch recorder (electret mic, live VU) and the hardware-controls page (LED switches, DAC slider) -- the Explorer board in action.

Boot log and shell over the USB-serial console

Devicetree and the driver framework

Drivers hang off a shared struct device (name / api / config / data / init triple) declared per instance from the devicetree. Boards carry a board.dts; scripts/dt/gen_dt.py renders per-driver Jinja2 templates into generated/dt_devices.h, giving each instance a DT_<label> device pointer and DT_<label>_INIT() hook. Nodes may group per-entry tuples as child nodes (used by gpio-keys). Drivers register via eas_library() with WHOLE_ARCHIVE and are gated by Kconfig so an image composes to exactly what the board enables. Driver instances come up through the generated dt_init_early() / dt_init_late() hooks in phandle dependency order (never EAS_SYS_INIT).

Class Drivers
Serial uart_16550 (ns16550), uart_pl011 (ARM), uart_stm32 (IRQ-driven), uart_nrfx (UARTE EasyDMA)
GPIO gpio_stm32 (AF mux + claim check), gpio_nrfx; pinctrl_stm32 backend
I2C i2c_stm32 (polled HW master), i2c_soft_stm32 (bit-bang)
I2S / DMA i2s_stm32 (double-buffered DMA playback + I2Sxext slave capture), dma_stm32 (per-stream, ring mode)
Audio ES8388 codec behind a generic codec class (routes, DAI, gain/ALC, volume)
SRAM / Display fsmc_sram_stm32 (1 MiB @ 0x68000000), fsmc_lcd_stm32 (8080-parallel TFT, RGB565 windows)
Ethernet e1000 (QEMU virt NIC), eth_stm32 (MAC + DMA, YT8512C RMII PHY)
SD sdio_stm32 (native SDIO host), sd_spi (SPI-mode host bit-banged on GPIO)
Input gpio-keys (polling + debounce), gt9xxx capacitive touch (polled, feeds the input bus)
ADC / DAC adc_stm32 (12-bit polled), dac_stm32
Timer timer_stm32 (TIM2..5/9: periodic IRQs, PWM channels, input capture)
Mailbox mailbox_nrf5340 (IPC doorbells to the network core)
Sensors qma6100p accelerometer, st480mc magnetometer (soft-I2C), dht11 temp/humidity (bit-bang)

Subsystems

  • console / shell -- UART console over stream ring buffers with line-atomic printk coexistence; a line shell with link-time command registration (EAS_SHELL_CMD_ADD) and line history/editing.
  • log -- structured logging (EAS_LOG_REGISTER, per-module compile-time levels, runtime narrowing via log level), deferred drain thread + byte ring that never blocks (drop-counted).
  • input -- Zephyr-style input event bus (input_report / listeners) feeding buttons and the LVGL pointer device.
  • audio -- sound-card layer composing a control-port codec + I2S DAI from a devicetree node: audio_open/read/write/close, volume, power sequencing, routing.
  • sd / fs -- bus-agnostic SD card protocol stack (SDSC/SDHC/SDXC, CID/CSD decode) over SDIO or SPI hosts; FatFS bridge (drive 0 = SD card, lazy disk init so card-less boot works). FatFS sources come from the external manifest.
  • ipc / bluetooth -- RPMsg static-vrings link over the IPC mailbox (wire-compatible with Zephyr's ipc_rpmsg_static_vrings, name service included), and a mynewt-nimble host port whose HCI transport rides that RPMsg link to the nRF5340 network core (Zephyr hci_ipc-compatible).
  • lvgl -- LVGL port: kernel heap as LVGL stdlib, tick over the kernel clock, RGB565 partial flush to the display driver with the draw buffer and LVGL heap in external FSMC SRAM, pointer indev from the input bus.

TCP/IP stack

subsys/net is a single-threaded lwIP-style stack: drivers post received frames to a mailbox from ISR context; a net thread owns all protocol state under one recursive core lock; periodic timers (ARP aging, TCP retransmit) run from the same thread.

  • Buffers: flat contiguous nbufs with headroom push/pull and refcounts; the buffer pool set is described in the devicetree (eas,nbuf-pools: block classes from small control packets to full frames), served smallest-fit first without the heap or its lock in the RX interrupt, with the heap as overflow. Fixed memp pools back TCP segments and bookkeeping structures.
  • Ethernet / ARP: framing, broadcast tagging; ARP cache with pending queues (packets park until resolution) and aging.
  • IPv4: routing/next-hop selection, header checksums, DF set on output (no fragment reassembly).
  • ICMP: answers echo requests in place, mirroring the requester's payload; minimal ping client (the ping sample, hostname-capable via DNS).
  • UDP: sockets with recv callbacks; RX checksum verification and length sanity.
  • TCP: three-way handshake (active and passive, listener backlog with accept callbacks, simultaneous open), RFC 6298 RTT estimation with RTO backoff, fast retransmit on bare duplicate ACKs, out-of-order receive queue with in-order delivery, peer-window flow control with segment splitting and zero-window persist probes, graceful close through FIN_WAIT/TIME_WAIT (including half-close reception), and a receive window bounded by the out-of-order capacity.
  • Application libraries: DHCP client, DNS client, SNTP client.
  • Sockets: BSD-style API (eas/net/socket.h) -- AF_INET stream/dgram sockets, blocking + O_NONBLOCK, SO_RCVTIMEO / SO_SNDTIMEO, poll()/select().

Throughput on the Explorer board over 100 Mbit Ethernet: ~60 Mbit/s UDP TX, ~40 Mbit/s UDP RX (flood), zero-corruption delivery.

External content (manifest)

The repository is a pure platform tree: third-party sources (FatFS, mynewt-nimble, LVGL) and product apps live outside it, in an assembly root of your choosing, described by a manifest.yaml (pinned url/rev per project):

<assembly root>/          e.g. C:\repos\eastra-project\
├── manifest.yaml         the assembly manifest: platform + projects (name/url/rev/path)
├── eastra/               this platform checkout (the build entry)
├── apps/                 your product apps (optional; own build entries)
└── third_party/          third-party checkouts, pinned per the manifest
    ├── fatfs/
    ├── lvgl/
    └── mynewt-nimble/

Configs that need them (CONFIG_FS_FATFS, CONFIG_BLUETOOTH, LVGL) require the root: configure the platform checkout with -DMANIFEST=<file> (or build.py --ext <manifest.yaml>), or set EAS_BASE/MANIFEST when building an external app as its own entry. The build never fetches anything itself; scripts/external/repos.py manages the checkouts against the pins:

python scripts/external/repos.py ../manifest.yaml status         # ok/mismatch/dirty/missing
python scripts/external/repos.py ../manifest.yaml fetch --force  # clone + align pins

The full assembly guide (manifest format, dual-mode app entries, the framework-side plumbing) lives in docs/external-content.md.

Boot-time initialization (EAS_SYS_INIT)

Non-driver code registers into the boot sequence with EAS_SYS_INIT(fn, level, prio) (include/eas/init.h): a linker-section entry, gathered per level and run at the fixed points -- EARLY (eas_boot, after the board, no services), PRE_SCHED (kernel objects up, scheduler not yet), SYSTEM (main thread, once the console and scheduler are up: subsystems needing thread context self-register here -- logging drain 5, shell 10, the net chain 30/40/50/60 = stack / board NIC facts / late DT phase / deployment config) and APP (right before main() -- module auto-starts; N entries may coexist). Driver instances keep the devicetree-generated bring-up (dt_init_early/dt_init_late, phandle dependency order). The application entry is int main(void) (eas/app.h): the board's main thread calls it last, a linked app overrides the weak default (WHOLE_ARCHIVE library required).

Samples and tests

  • samples/application/: application samples -- each overrides the board's weak main() (eas/app.h) and self-starts at boot: log_demo (logging sequence), lvgl_studio (LVGL clock/touch studio app, SNTP-driven), bleprph (BLE peripheral advertising; needs NimBLE + MANIFEST, runs on nrf5340dk). At most ONE may be linked into an image (a second one fails the link with a duplicate main): build one standalone (cmake -S samples/application/log_demo -B build/log_demo -DBOARD=<board>) or select it with -DMODULES=samples/application/log_demo -- never group-expand this directory. build.py --app <name> wraps the standalone entry.
  • samples/commands/: command-driven demos -- modules only (-DMODULES=samples/commands takes the whole group): blink, adc, audio, button, dac, dma, fs (FatFS-on-SD shell, needs MANIFEST), ping, pwm, pwmdac, sd, timer.
  • test/host/: kernel data-structure unit tests under CTest (dlist/slist/mlist, heap, ringbuf, string, thread/sem/mutex/msgq/ event with an arch stub), no toolchain or QEMU needed.
  • test/target/: on-device suites -- test_kernel (scheduler/IPC/work/mm), test_net (nbuf/routing unit tests, test_udp/test_tcp on-wire runs, test_socket socket-layer runs, test_dhcp, netstress UDP tx/rx/echo) and test_periph (gpio/i2c/spi). PC-side peers live in scripts/: test_net_helper.py (--board-ip for real hardware), netstress_helper.py.

Getting started

1. Build and boot on QEMU (RISC-V 64-bit)

cmake -B build/qemu_riscv64 -DBOARD=qemu/riscv64 -GNinja
cmake --build build/qemu_riscv64
cmake --build build/qemu_riscv64 --target qemu

You should see the boot banner and a shell prompt:

[eastra] qemu_riscv64 boot

[eastra] main_entry...
$

Type help to list shell commands, or test_kernel to run the on-target kernel test suite.

2. Build and flash the STM32F407ZG Explorer

Board defconfigs carry hardware facts only (RAM, IRQs, drivers); which samples ship in the image is app config, selected with -DMODULES=<sample dir>:

cmake -B build/stm32f407zg-explorer -DBOARD=stm32f407zg-explorer ^
      -DMODULES="samples/commands/audio;samples/commands/button" -GNinja
cmake --build build/stm32f407zg-explorer
cmake --build build/stm32f407zg-explorer --target flash   # OpenOCD + ST-Link

Each entry's prj.conf merges over the board defconfig (later entries win); a .config fragment file works as an entry too. Samples live under samples/<group>/<name>/ -- Kconfig, CMakeLists.txt and a self-enabling prj.conf -- and are discovered automatically; write your own app directory to combine them or tune knobs. The flash target programs the ELF, verifies it, and resumes at the reset vector. With the audio sample in, on the shell try audio play / audio rec; with blink, blink on; with fs (needs -DMANIFEST), fs mount / fs ls. PC-side peer for the ping and net samples: python scripts/test_net_helper.py --board-ip <board-ip> --bind-ip <pc-eth-ip>, ...

Third-party-dependent samples (bleprph, fs, lvgl_studio) need -DMANIFEST when built as standalone entries.

3. Edit the configuration

cmake --build build/qemu_riscv64 --target menuconfig
cmake --build build/qemu_riscv64

Common knobs: CONFIG_TICKS_PER_SEC, CONFIG_MAIN_STACK_SIZE, CONFIG_NET_* (mailbox, thread, nbuf pool), CONFIG_TCP_* (MSS, RTOs, segment pool, ooo queue), CONFIG_ARP_*, ...

MODULES fragments re-apply on every regeneration, so symbols they set are pinned over menuconfig edits -- change the fragment, not the .config.

4. Run host-side unit tests

cmake -B build_host -S test/host -GNinja
cmake --build build_host
ctest --test-dir build_host --output-on-failure

5. Use clang/lld instead of GCC

cmake -B build/qemu_riscv64-clang -DBOARD=qemu/riscv64 -DEAS_TOOLCHAIN=clang -GNinja
cmake --build build/qemu_riscv64-clang
cmake --build build/qemu_riscv64-clang --target qemu

6. Check code style

python scripts/check_style.py           # C + CMake, report only
python scripts/check_style.py --fix-c   # rewrite C/C++ files in place

7. Speed up rebuilds with a compiler cache

cmake -B build/qemu_riscv64 -DBOARD=qemu/riscv64 -DEAS_USE_CCACHE=ON -GNinja

EAS_USE_CCACHE=ON fronts the cross compiler with ccache from PATH; pass a program name instead (e.g. -DEAS_USE_CCACHE=sccache) to use another launcher.

Licensing

Copyright 2026 Chengdong Wang. The repository is provided under the Apache License 2.0 (see LICENSE); each source file carries an SPDX-License-Identifier header.

Two files keep a different, compatible license, as their headers state:

  • lib/heap/tlsf.{c,h} -- MIT, derived from mattconte/tlsf via the copy vendored in LVGL (upstream notice retained in the file headers). MIT-licensed content may be included in an Apache-2.0 project.
  • samples/application/lvgl_studio/wx_cn_24.c -- a generated bitmap font subset of Noto Sans SC (SIL Open Font License 1.1).

Third-party sources (LVGL, FatFS, mynewt-nimble) are not distributed in this repository: the external manifest.yaml pins them and scripts/external/repos.py fetches them into your assembly at the versions you choose. Their licenses apply to those checkouts:

Project License
LVGL MIT
FatFS BSD-3-Clause
mynewt-nimble Apache-2.0

About

Compact preemptive RTOS with a from-scratch TCP/IP stack and devicetree-driven drivers -- ARM, RISC-V, QEMU, ~50K LOC.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages