Section 6.33

Zephyr RTOS

Full name: Zephyr real-time operating system (RTOS).

Definition

Zephyr is an open-source real-time operating system (RTOS) for microcontrollers §6.1 and other small devices. An RTOS is an operating system built so that the time it takes to react to an event can be bounded. Zephyr supplies a kernel (threads, a scheduler, interrupt §6.11 handling, timers and synchronization objects), device drivers §6.38, and protocol stacks such as Bluetooth and networking. The application and the parts of Zephyr it selects are compiled into one firmware image, and build options choose those parts. The Linux Foundation hosts the project.

The idea

A small device must sample a sensor every 10 ms, answer a radio peer and write a log to flash. One big loop copes until one job takes long and the others miss their moment. An RTOS splits the work into threads, each a separate sequence of steps with its own stack, and a scheduler decides which thread runs; interrupts let hardware events cut in on any of them. Zephyr provides this machinery, with the drivers and protocol stacks that a connected device needs.

The price is that the application no longer runs every line itself. Zephyr may call a function that the application wrote from an interrupt handler §6.12, from a shared worker thread, or from a thread of the Bluetooth stack. That context decides how long the function may take, whether it may wait, how much stack it has, and what it delays. The core skill with Zephyr is to know, for every piece of code, which context runs it.

How it works

One image, chosen at build time. Zephyr has no separate kernel program and, in the usual configuration, no processes. The kernel, the drivers, the protocol stacks and the application are linked into one executable. Kconfig §6.40, a system of named build options such as CONFIG_BT=y to include Bluetooth, selects the software parts. Devicetree §6.39, a text description of the hardware, tells the drivers which hardware exists and where. A kernel service is therefore an ordinary function call: k_sem_take() runs on the stack of the thread that calls it, and if the semaphore §9.6 is not available and the caller allowed a waiting time, the calling thread is put to sleep.

Execution contexts. Every piece of code runs in one of these contexts.

Bluetooth host §7.4 threads. The Bluetooth host is the upper part of a Bluetooth stack: the protocols above the radio link. Zephyr’s host processes received data on its own work queue, the Bluetooth receive work queue, whose thread is named BT RX WQ. Most callbacks §14.22 from the host to the application, for example when a peer connects or writes a value, run on that thread. In current Zephyr source the thread is cooperative: its priority option CONFIG_BT_RX_PRIO defaults to 8, which becomes thread priority −8-8 with the default 16 cooperative priority levels. A cooperative thread §6.37 keeps the processor until it waits or yields, as the cooperative and preemptive scheduling entry explains. Its stack size is CONFIG_BT_RX_STACK_SIZE, whose help text says to raise it when callbacks need extra stack. Long computations go to a separate long work queue (CONFIG_BT_LONG_WQ) at a preemptive priority, so they do not hold up received data. One example is the elliptic-curve Diffie-Hellman key agreement §19.1.5 in Low Energy Secure Connections §7.21 pairing, the procedure by which two Bluetooth devices create shared keys. These names and defaults have changed between releases.

User mode. By default every Zephyr thread §6.35 is a supervisor thread: it runs in the processor’s privileged mode and can access all memory and every peripheral. With the build option CONFIG_USERSPACE, a thread can instead be created as a user thread. A user thread runs in the processor’s unprivileged mode and is confined by a memory protection unit §6.8 (MPU), the hardware on microcontrollers that checks every memory access against a short table of allowed regions, or on larger processors by a memory management unit §6.9 (MMU). It can read the program code and constant data, write its own stack, and access only the further memory partitions in its memory domain, the set of memory regions assigned to it. It reaches kernel services only through system calls, in which the kernel checks the arguments and checks that the thread holds permission for the kernel object, such as a semaphore, that it names. Without an MPU or MMU, user mode is not available.

Worked example

A phone writes a value to a Zephyr device over Bluetooth. The radio hardware raises an interrupt, and an ISR in the Bluetooth controller, the lower part of the stack that drives the radio, handles it (interrupt context). The host then processes the received data on the BT RX WQ thread and calls the application’s write callback there (a cooperative thread).

Stack budget. Suppose the receive thread’s stack is 1200 bytes. Zephyr’s thread analyzer (CONFIG_THREAD_ANALYZER) reports each thread’s peak stack use; in a test run in which the host calls an empty callback, it shows a peak of 900 bytes. If the host’s functions already use all 900 bytes when they call the callback, the callback has 1200−900=3001200 - 900 = 300 bytes left, and a callback with a 512-byte local buffer runs at least 512−300=212512 - 300 = 212 bytes past the end of the stack and overwrites the memory beyond it: a stack overflow §4.10. The peak does not show that the host’s functions use 900 bytes at the call: it is the deepest point of the whole run, and that point may lie on a path that does not call the callback. So the overflow is possible, not certain, and a safe budget counts the full 900 bytes. Raising CONFIG_BT_RX_STACK_SIZE to at least 900+512=1412900 + 512 = 1412 bytes, plus a margin for everything else on the stack while the callback runs, such as its other local variables and the functions it calls, for example to 1536 bytes, removes this overflow on every path that the test run took. A path that the test run did not take may need more stack, and no measurement rules that out.

Time. Suppose the callback must also compress a log, 40 ms of processor time. Done inside the callback, the job holds the cooperative receive thread for 40 ms: no other thread runs, and received data waits. Moved to the system workqueue, which is also cooperative by default, the job still holds the processor for 40 ms once it starts. Moved to an application thread with a preemptive priority, such as 10, it runs only while no higher-priority thread is ready, and the receive thread takes over as soon as new data arrives. Only the last placement spares the other threads the 40 ms delay.

Stated precisely

Four facts settle how a piece of code behaves, and all four come from the documentation and configuration of the release in use:

  1. the context that runs the code: interrupt context, the calling thread, a named work queue thread, or a dedicated thread;

  2. that context’s priority, and whether the priority is cooperative (negative) or preemptive (zero or positive);

  3. the stack left for the code, which is the context’s stack size minus what the functions that called the code already use on the same stack;

  4. whether the code may wait: interrupt code must never wait, and code on a shared work queue or on a protocol stack’s thread must not wait long, because everything queued behind it waits too.

The trusted computing base §1.4 (TCB) for a security goal is the set of components whose failure can break that goal. Without CONFIG_USERSPACE, all code in the image runs privileged in one address space, so any defect in any linked component (application, library, driver or protocol stack) can read or overwrite any memory. The TCB for every goal then contains the whole image, together with the boot code and the hardware. With user mode, the code of a user thread leaves the TCB for each goal that depends only on memory and kernel objects not granted to that thread. The kernel, the supervisor threads, the ISRs and the drivers stay inside it.

Limits and common mistakes

Zephyr provides mechanisms that make bounded timing possible; it does not make an application meet its deadlines. Whether deadlines are met depends on the application’s own execution times §9.32, priorities and shared resources, which a schedulability §9.37 analysis checks.

A callback’s name does not say where it runs, and defaults change between releases: thread priorities, stack sizes and even which threads exist. Advice written for another release or board is not evidence about the release in use.

Without user mode, threads are not isolated the way processes are on a desktop operating system: a stray pointer in one thread can corrupt another thread, the kernel or a driver. Hardware stack protection (CONFIG_HW_STACK_PROTECTION) uses the MPU to place a guard region at the end of each stack. It catches stack overflows, but it is not user mode and stops nothing else.

User mode confines only code that runs on the processor. A direct memory access §4.36 (DMA) engine, which copies memory without the processor, is not checked by the MPU, so a driver that programs it can reach any memory unless the chip protects such transfers separately. The MPU also has few regions, eight on the Arm Cortex-M4 §6.3, which limits how many memory partitions a user thread can have at once.

Questions answered

Which services execute in the kernel, work queues, or dedicated threads?

In Zephyr, kernel services execute in the context of whoever calls them: the kernel is linked into the same image as the application, so a kernel call such as taking a semaphore runs on the calling thread’s stack, or inside the interrupt handler that makes the call. Interrupt context runs the interrupt service routines (ISRs), the functions that the hardware starts for each interrupt, and the expiry functions of kernel timers. Work queues run deferred work: the system workqueue runs work items that drivers, subsystems and the application submit; the Bluetooth host processes received data, and makes most of its callbacks to the application, on its own receive work queue, and runs long cryptographic computations on a separate long work queue. Dedicated threads include the main thread, the idle thread, the logging thread when logging is deferred, and every thread the application creates.

The placement depends on the release and its build options, so confirm it for each service: read the interface documentation and the help text of the Kconfig options, and check at run time with the thread analyzer, which lists every thread with its stack use. Placement matters because it fixes the code’s priority and stack, and whether the code may wait.

Related entries: Zephyr thread (§6.35), Zephyr workqueue (§6.36), Schedulability (§9.37), Cooperative and preemptive scheduling (§6.37), Real-time system (§6.34), Memory protection unit (MPU) (§6.8), Privilege level (§6.10), Interrupt service routine (ISR) (§6.12), Trusted computing base (TCB) (§1.4), BLE Controller and Host (§7.4). Further reading: [13, 14].