pebble
  • Tutorials
  • Get the SDK
  • Guides
  • Documentation
  • PebbleOS
  • Mobile App
  • Examples
  • Index 01
  • Community
  • Blog
  • More
Privacy
Cookies
Publish

PebbleOS

  • Overview
  • Start here
    • Getting started guide
  • Pebble Firmware
    • Overview
    • Playground
    • Application SDK
  • Development
    • The pbl CLI
    • Build system
    • Samples
    • Emulator and simulator
    • Testing
    • Debugging
    • Conventions
  • System
    • Architecture overview
    • Kernel
      • Threads
      • Syscalls
      • Interrupts
      • Time and delays
      • Work queues
      • Boot
      • Idle
      • Memory
      • Fatal errors and assertions
      • Reboot and power-off
      • Print
      • Compiler abstraction
      • Kernel internals
    • Drivers
    • Subsystems
    • Libraries
    • Third-party
  • Hardware
    • Boards
    • Board Add-ons
    • Programmers
  • Community
    • Contribution Guidelines
  • Reference
    • Reference
    • Kconfig options

Kernel internals

kernel/ implements include/pbl/kernel. It replaced a FreeRTOS shim; the comparison and benchmark sections below record how the two compared while both existed.

Layout

sched.c        ready lists, tick, block/wake, idle thread, start
timer.c        timeout queue and timers
idle.c         idle states, with CONFIG_CPU_IDLE
thread.c       thread lifecycle and priorities
mutex.c        recursive mutex with priority inheritance
sem.c          counting semaphore
msgq.c         message queue
poll.c         poll group
irq.c          nestable interrupt lock
debug.c        thread walk, saved PC and return address, stack and run-time stats
kernel.h       the interface between the objects, the scheduler and the arch
arch/arch.h    what an arch must provide
arch/arm/      Cortex-M port: context switch, SVC, MPU, idle
arch/riscv/    RISC-V port: trap entry, context switch, CLIC
arch/posix/    host port: threads are pthreads, time is virtual; for tests
kernel_test.h  harness entry points used by tests/kernel

Design

Scheduling. Fixed priorities, CONFIG_KERNEL_NUM_PRIORITIES of them, one FIFO ready list per priority and a bitmap picked with clz, so choosing the next thread is O(1). The choice is kept in sched_next, updated whenever a ready list changes, so a context switch only has to load it. Threads of equal priority round-robin on every tick (as FreeRTOS does with time slicing) and on pbl_thread_yield(). The running thread stays on its ready list; blocking removes it.

Blocking. Every object owns a struct pbl_waitq: a singly linked list ordered by priority, FIFO within a priority. sched_block() moves the current thread onto the object’s wait queue and the timeout list, requests a switch and drops the interrupt lock; it returns with the lock re-taken and the wake code. Semaphores and mutexes hand their token straight to the woken thread, so a wake is never spurious and a lower-priority giver cannot steal it back. Queues and poll groups wake one waiter and let it re-check.

Timeouts. One queue for blocked threads, sleeps and timers alike, sorted by absolute expiry in 64-bit ticks, so nothing wraps. The tick ISR expires its head, waking the thread or running the timer callback, and the idle thread asks it how long it may sleep. Insertion is O(n) in the number of pending timeouts, which on this firmware is a handful.

Priority inheritance. Single level: a waiter raises the owner to its own priority. Each thread keeps the list of the mutexes it holds, and runs at the higher of its base priority and the most urgent waiter of any of them, worked out again when it unlocks one and when a waiter gives up. A boosted thread is re-sorted in its ready list or wait queue.

Interrupts. The kernel’s own critical sections raise BASEPRI to the level of interrupt priority 0 with arch_irq_lock(), which returns the previous level for arch_irq_unlock() to restore: a few inline instructions, and nothing to keep count of. pbl_irq_lock() is that plus a nesting counter, for callers with nowhere to keep the key. Zero-latency ISRs, above that level, may not call the kernel. They take the most urgent level, above the configurable faults, as radio schedulers require. Object operations run under that lock; there is no separate scheduler lock inside the kernel. pbl_sched_lock() defers switches until unlocked.

Idle. The idle thread yields to other threads at its priority, then calls the arch idle hook with the ticks until the next timeout. The arch masks interrupts and hands over to the kernel’s idle, which either waits for the next tick or, with CONFIG_CPU_IDLE, picks one of the SoC’s idle states (idle.c) and reprograms the clock event device around it (see Idle).

Threads. struct pbl_thread is caller-owned; the backend state lives in its backend member, first in the struct so the arch code can find the saved stack pointer at offset zero. Stacks are filled with a pattern at creation for the high-water mark. Returning from the entry function ends the thread. A thread suspended while blocked sees the blocking call fail with -EINTR when resumed; the process manager only suspends threads it is about to kill or resumes immediately.

No allocation. Nothing in the backend calls an allocator; PBL_*_DEFINE initialisers are complete and pbl_kernel_init() returns at once.

Cortex-M arch

The saved context keeps the layout of the FreeRTOS port: CONTROL, r4-r11, PSPLIM on ARMv8-M, EXC_RETURN, then the hardware frame, with s16-s31 in between when the FP context is active. Core dumps and the fault handler read that layout unchanged. PendSV saves the context, makes sched_next the current thread under BASEPRI, rewrites the four per-thread MPU regions through the RBAR alias registers and restores. Supervisor calls keep the port’s numbers: 0 starts the scheduler, 1 yields, 2 raises privilege. SVC 2 is honoured only from a syscall stub in .syscall_text or from the return of an pbl_user_call() callback. For a syscall it copies the exception frame onto the thread’s syscall stack when it was created with one, records the caller’s stack pointer and return address in the thread, and points the return at the code that drops privilege again (kernel/arch/arm/syscall.c).

The vector table (kernel/arch/arm/vector_table.c) is a constant array in .isr_vector. PBL_LISTIFY() expands its CONFIG_NUM_IRQS slots to pbl_isr_<n>, each a weak alias of arch_irq_spurious() that PBL_IRQ_CONNECT() or PBL_IRQ_DIRECT() overrides with a strong definition, n being the line’s PBL_SOC_IRQN_<line>. Each binding also drops a {irq, prio} record into the irq_prio iterable section, which pbl_irq_init() walks to program the NVIC after pointing VTOR at the table. With CONFIG_ARCH_VECTOR_TABLE_RAM, selected by SoCs whose vector fetches from flash bypass the cache, VTOR points at a copy of the table in RAM instead. A weak default never pulls an object out of a static library, so a binding inside a stlib library only takes effect when something else in the same object is referenced.

pbl_cur is privileged kernel data, which PendSV sets with a plain store. pbl_thread_current() and pebble_task_get_current() also run unprivileged inside apps, so the port keeps arch_cur_user in .kernel_unpriv_ro_bss, the firmware’s unprivileged-readable kernel data: the last thread that ran unprivileged, which is what pbl_thread_current() returns to unprivileged code. Writing that section goes through the MPU on ARMv8-M, as pbl_mpu_user_ro_write() does, so PendSV only does it when switching to an unprivileged thread other than the last one, and a thread sets it when it first drops privilege.

RISC-V arch

The port runs in machine mode, without an MPU (no ARCH_HAS_MPU) or unprivileged threads. It sticks to what the RISC-V specifications define; what a core does its own way comes in as capabilities its CPU option selects, and what its vendor adds, such as custom CSRs, through riscv_cpu.h, which the vendor’s directory, kernel/arch/riscv/vendor/<vendor>, provides:

Capability

Meaning

RISCV_CLIC

A CLIC, vectoring every line in hardware through mtvt. RISCV_CLIC_INTCTL_BITS and RISCV_CLIC_IRQ_OFFSET give the level bits it implements and the mcause code of its first line.

RISCV_HW_STACKING

On an interrupt, the core stacks ra, t0-t2 and a0-a5, then the mcause and mepc of the trap it was in. mret returns as the current mcause and mepc say, then takes them all back. Bit 0 of the stacked mepc tells that the core moved sp 4 bytes down first, to align the frame on 8.

RISCV_WFI_NEEDS_MIE

The core only wakes from wfi with interrupts unmasked. The trap entry returns the interrupt that ends the idle wfi to the idle code, masked and still pending, so it is taken once idling is over, as on a core that wakes masked.

RISCV_CPU_CYCLE_COUNTER

mcycle does not count: the CPU provides the cycle counter.

The trap entry (kernel/arch/riscv/trap.S) handles cores with a CLIC that stack in hardware. Every mtvt entry is the trap entry, which faults on exceptions and otherwise calls the line’s pbl_isr_<n> from arch_riscv_irq_table, on the ISR stack for the outermost interrupt, with interrupts unmasked so that more urgent levels preempt it. The lowest CLIC level is the threads’, which no interrupt preempts. PBL_IRQ_CONNECT() priorities map to the levels above the switch’s, 0 the most urgent.

The first level above the threads’ is the thread switch’s own, a line the CPU raises (riscv_cpu_switch_raise()), as PendSV is on ARM: it only ever interrupts a thread, so every switched-out thread holds the frame the core stacked, with s0, s1 and the mepc and mcause to return with below it, and mret resumes any of them. A new thread starts from such a context, made up. The kernel lock clears mstatus.MIE, masking every interrupt. A core may take the switch a few cycles after unmasking: a thread that unmasks with one pending waits for it (riscv_cpu_switch_pending()), or it would run on past where it blocked.

The Nordic VPR (CPU_NORDIC_VPR) has all four capabilities. Its vendor directory, kernel/arch/riscv/vendor/nordic, raises the switch through a VEVIF task, the last one, and counts cycles with VTIM, its two 16-bit timers combined, both custom CSRs.

POSIX arch and tests

Each kernel thread is a pthread; exactly one runs at a time, and control passes when the kernel would switch. Interrupts are simulated: a test wraps calls in pbl_test_isr_enter()/exit() and delivers ticks with pbl_test_tick(). When every thread is blocked, the idle hook jumps the clock to the next timeout. This makes the scheduling decisions exactly reproducible, so tests/kernel/test_kernel.c can assert trace strings such as “lhLHMd” for the priority-inheritance scenario.

Compared with other kernels

FreeRTOS (fork)

NuttX

ThreadX

Native

Ready queue

list per priority, clz optional

list per priority

bitmap + list

bitmap + list

Time slicing

per tick

configurable

per thread

per tick

Timeouts

two delayed lists

wdog list

per-timer wheel

single absolute list

Wait queues

priority ordered

priority ordered

FIFO or priority

priority ordered

Mutex PI

single level

multi level

single level

single level

Sem/mutex wake

wake, retry

handoff

handoff

handoff

Static objects

since v9

no

yes

yes

Idle

idle task hook

tickless

tickless

idle thread + SoC hook

Stack overflow

pattern / MPU guard

canary

analysis

PSPLIM (v8-M), MPU guard, pattern

Thread exit

must not return

returns

returns

returns

What was taken from where:

  • Direct handoff on semaphores and mutexes (ThreadX, NuttX). Removes the give-then-retry race and the spurious wakeups the fork’s queue-based semaphores have.

  • Priority-ordered wait queues with FIFO within a priority (everyone).

  • Completed static initialisers, so nothing has to run before objects are usable.

  • A poll group that scans members from a rotating cursor, for fairness, and no rule about draining members only through the group, which the FreeRTOS queue set imposes and which this firmware’s event loop tiptoes around.

  • Threads may return from their entry function (everyone but FreeRTOS).

  • Saved registers of the running thread are read from its live exception frame when asked from an ISR, so the task watchdog reports the real stuck PC instead of a stale context (a FreeRTOS limitation here).

  • Thread struct reuse is checked: creating a thread in a struct whose previous thread is still alive asserts.

Not done, on purpose or for later:

  • Multi-level priority inheritance (NuttX). The firmware never nests locks deeply enough for it to matter, and the fork did not have it either.

  • Timer wheels (ThreadX) or delta lists for timeouts. The pending timeout count here is small; an O(n) insert keeps the code obvious.

  • Run-time statistics in cycles from the DWT counter instead of ticks. QEMU has no DWT, so it is left for a board with one.

  • Per-thread preemption threshold (ThreadX) and memory domains. The MPU regions stay per thread as the firmware defines them today.

  • Multicore. Everything assumes one CPU.

Benchmarks

The numbers below come from a throwaway micro-benchmark harness that ran in place of KernelMain on QEMU; it is not kept in the tree. Times came from the tick counter refined with the SysTick down-counter, so they are QEMU virtual time: only the relative numbers between the two backends on the same board mean anything.

Results in ns per iteration (2026-09-02, -Os, all boot services still running in the background):

Benchmark

gabbro shim

gabbro native

flint shim

flint native

irq_lock_unlock

151

142

82

102

mutex_lock_unlock (uncontended)

927

413

610

283

sem_give_take (no wait)

658

347

398

247

msgq_put_get (4 bytes, no wait)

723

602

458

341

yield_switch (two equal-priority threads)

10869

11323

10756

10588

sem_pingpong (round trip, two switches)

28647

23715

26421

21401

msgq_pingpong (round trip)

30805

25265

26433

22376

poll_wake (three-queue group, one wake)

29109

24520

25681

23205

irq_to_thread (pended IRQ to waiting thread)

2000

1620

1384

1244

thread_create_exit

33149

24441

29712

21871

sleep_1_tick

997605

1001495

998345

996250

Reading the numbers:

  • Uncontended primitives are 1.2x to 2.2x faster natively. The shim pays for the FreeRTOS queue machinery plus the wrapper, the native objects are a counter or a byte ring with an owner pointer.

  • Anything that context switches is dominated by PendSV plus the MPU reprogramming and the QEMU cost of the exception itself, so the two backends land within 20% of each other. yield_switch is the same code path in both and shows the noise floor of the method: about 5%.

  • sleep_1_tick is a sanity check that the tick source runs at CONFIG_KERNEL_TICK_HZ.

  • thread_create_exit sleeps a tick every 16 iterations (excluded from the measurement) so that FreeRTOS’s idle task can reclaim deleted TCBs; the kernel needs no reclamation since the thread object is static.

Code size of the kernel library alone (the toolchain’s size, -Os):

Board

FreeRTOS shim + FreeRTOS

Native

QEMU, Gabbro (Cortex-M33)

12541 text / 57 data / 744 bss

4725 text / 0 data / 1218 bss

QEMU, Flint (Cortex-M4)

12403 text / 57 data / 744 bss

4725 text / 0 data / 1218 bss

The native bss is mostly the 1 KiB idle stack; the shim’s idle task stack comes out of the FreeRTOS heap instead.

Verification

  • tests/kernel/test_kernel: 18 host tests on the POSIX arch.

  • QEMU, Gabbro and Flint: boot to the watchface, launch an app from the launcher and back out, a gdb breakpoint sweep on every assert and fault entry point, and the benchmark suite. Not yet run on real hardware.

Generated from PebbleOS 7416f78a1. This page is maintained in the pebbleos repository: docs/kernel/internals.md.

Overview

  • Layout
  • Design
  • Cortex-M arch
  • RISC-V arch
  • POSIX arch and tests
  • Compared with other kernels
  • Benchmarks
  • Verification