Traditionally, Linux was seen as capable of handling high throughput but not ideal for workloads demanding low-latency, predictable responses in the microsecond range. That perception has changed significantly with the maturation of PREEMPT_RT, the real-time Linux patchset.
PREEMPT_RT makes the Linux kernel almost entirely preemptible (threaded interrupt handlers, sleeping spinlocks, priority inheritance, etc.) and greatly improves its determinism. Properly configured and validated on a given platform, it can achieve bounded worst-case latencies in the microsecond range.
No kernel can offer an absolute guarantee: the achievable latency still depends on the hardware, the drivers, the firmware and the configuration, which is why measuring on your own target is essential, as we discuss below. This allows Linux to meet demanding real-time constraints while retaining its rich ecosystem, hardware support, and maintainability.
The PREEMPT_RT patch has been partially merged into the mainline Linux kernel, starting from version 5.15. On September 20, 2024, with the 6.12 release, PREEMPT_RT was fully merged and made available on the supported architectures: x86, x86_64, RISC-V, and ARM64.
Applying the RT Patch
Even though PREEMPT_RT has been merged into the mainline, you may still need to apply the RT patch, for example when you are running an older stable kernel, or a vendor kernel based on one.
Even on a recent release, a small RT patch queue is still carried on top of mainline to fix bugs, enable platforms or add other improvements not (yet) available on mainline. For example, the RT patch for 6.18 (version rt9) mainly enables RT on 32-bit ARM and PowerPC and makes the Intel i915 graphics driver compatible with RT, along with a few fixes for the serial console and printk.
If your kernel is based on a tree that is close to the upstream stable tree, the simplest solution is to use the linux-stable-rt git repository. Its tags match the patch archives published on kernel.org. Select the branch closest to your kernel version, then rebase or merge your Linux branch with the RT branch. For each kernel branch, there are two types of RT branches:
v6.6-rt: The kernel stable branch v6.6 is merged into this v6.6-rt branch.v6.6-rt-rebase: This RT branch is rebased on top of each stable release. The commit history is exactly like applying the patches from thepatches-6.6.*.tar.xzarchive described below.
However, you may not be able to use the RT git repository directly. A common case is a vendor tree (a SoC vendor’s BSP kernel, for example), which contains many out-of-tree changes on top of a stable kernel. In this situation, you will have to apply the RT patch on top of your own tree. The patches are published on kernel.org.
You should download the patch that is closest to your kernel version. For example, for the 6.6.73 release, the closest patch is rt48, which can be found in the older directory. If possible, avoid the real-time RC patch, which has the following version format: -rtXX-rcY.
There are two versions of the same RT patch:
patch-6.6.74-rt48.patch.xz: This archive contains a single patch, without any commit messages.patches-6.6.74-rt48.tar.xz: This archive contains individual patches, each accompanied by a commit message explaining the change. If you plan to apply the patches to your Linux Git repository, this method is recommended, as it makes it easier to resolve any potential conflicts.
Enabling PREEMPT_RT
For example, using make menuconfig, set CONFIG_PREEMPT_RT=y. Then build your kernel as usual.
To check that the device is running a kernel with PREEMPT_RT enabled, one of these checks can be performed:
dmesg | grep PREEMPTshould return a line similar to this:
[ 0.000000] Linux version 6.6.73-rt48+ ... #0 SMP PREEMPT_RT ...uname -ashows the preemption model selected when compiling the kernel. It must show “PREEMPT_RT”.zcat /proc/config.gz | grep CONFIG_PREEMPT_RTshould indicate that the configuration is enabled (=y).cat /sys/kernel/realtimeshould return1.
About cpufreq
cpufreq is the subsystem of the Linux kernel which changes the clock frequency of CPU cores dynamically at runtime, in order to provide either high performance or low power consumption based on the current CPU load. It provides a good balance between performance and power saving, which is ideal for most non-realtime workloads.
If the device supports cpufreq, it is recommended to disable it or set the scaling governor to “performance” for all cores. The scaling governor is the policy that decides at which frequency each core runs. With a governor such as “ondemand“, the frequency follows the load: an idle core is slowed down, and has to ramp its frequency back up when there is work to do. During this transition, code runs more slowly and execution time is hard to predict, which directly increases and spreads out wake-up latencies. The “performance” governor, on the other hand, keeps every core at its maximum frequency, trading power consumption for predictability.
For example, on a device running an i.MX8QM, the maximum latency is around 500µs with the “ondemand” governor, compared to 50µs with the “performance” governor.
The governor can be changed from a terminal through sysfs:
- List the governors supported by the first core
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors - Show the governor currently in use
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor - Select the “performance” governor on all cores
for gov in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo performance > "$gov" done
This setting is not persistent: it is lost after a reboot. To make it permanent, set it from an init script or a systemd unit, or select “performance” as the default governor in the kernel configuration (CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE=y).
Measuring Latency
To evaluate real-time behavior, the most commonly used tool is cyclictest, which is part of the rt-tests project.
cyclictest acts as a replacement for actual real-time workloads. It can run a specified number of threads with real-time priority at a given interval (in microseconds). It tracks observed latencies and reports them to a measurement thread.
cyclictest requires the following kernel configuration options:
CONFIG_HIGH_RES_TIMERS=yfor latency measurement.CONFIG_CPU_IDLE=yfor access to /dev/cpu_dma_latency (optional).
To ensure accurate measurements during stress testing, real-time throttling should be disabled. By default, the kernel reserves part of each period for non-real-time tasks: with the default settings, real-time tasks get 950,000 µs of runtime in every 1,000,000 µs period (leaving 50,000 µs for non-real-time tasks). A real-time task that runs longer than its budget within a period gets throttled, which would pollute the measurements.
To disable this, sched_rt_runtime_us should be set to its maximum value so that /proc/sys/kernel/sched_rt_runtime_us should equal /proc/sys/kernel/sched_rt_period_us.
cat /proc/sys/kernel/sched_rt_period_us echo 1000000 > /proc/sys/kernel/sched_rt_runtime_us
Alternatively, writing -1 to sched_rt_runtime_us disables the throttling altogether (see sched(7)). However, this may not work on certain kernel versions, so writing the value of sched_rt_period_us explicitly, as above, is the safest option.
The following example runs one thread per CPU with SCHED_FIFO priority 80. Reported values are in microseconds:
cyclictest -m -S -p 80 --policy=fifo
The options used are:
-m: lock the current and future memory allocations (mlockall) to avoid page faults.-S: standard SMP testing, i.e. one measurement thread per CPU, all with the same priority.-p 80 --policy=fifo: run the threads with the SCHED_FIFO policy and a real-time priority of 80.
Here is an example of the output, obtained after a long run on a 6-core system under load:
# /dev/cpu_dma_latency set to 0us policy: fifo: loadavg: 14.81 14.81 14.64 10/194 8639 T: 0 ( 3500) P:80 I:1000 C:7059852 Min: 4 Act: 8 Avg: 7 Max: 69 T: 1 ( 3501) P:80 I:1500 C:4706562 Min: 4 Act: 9 Avg: 9 Max: 89 T: 2 ( 3502) P:80 I:2000 C:3529916 Min: 4 Act: 9 Avg: 10 Max: 58 T: 3 ( 3503) P:80 I:2500 C:2823930 Min: 4 Act: 9 Avg: 11 Max: 67 T: 4 ( 3504) P:80 I:3000 C:2353272 Min: 2 Act: 6 Avg: 9 Max: 95 T: 5 ( 3505) P:80 I:3500 C:2017088 Min: 2 Act: 7 Avg: 9 Max: 91
The first lines show that cyclictest set /dev/cpu_dma_latency to 0 µs, which prevents the CPUs from entering deep idle states. Then there is one line per measurement thread:
T: thread index, followed by its PID between parentheses.P: real-time priority of the thread.I: wake-up interval of the thread, in µs. The first thread uses 1000 µs, and by default each following thread adds 500 µs, so that the threads do not all wake up at the same time.C: number of cycles (wake-ups) completed so far.Min,Act,Avg,Max: minimum, latest, average and maximum latency measured, in µs. A latency is the difference between the time the thread was supposed to wake up and the time it actually ran.
The most important value to watch is Max. The average is usually excellent, even on a non-real-time kernel; it is the worst case that makes the difference for a real-time system. Here, the worst latency observed over several million cycles is 95 µs.
In parallel with cyclictest, the system should be loaded to properly measure maximum latency. For this, stress-ng can be used. For example, on a CPU with 6 cores, the following command can be executed:
stress-ng -c 6 --iomix 2 --iomix-bytes 20M -m 2 --vm-bytes 100M
The command should be executed from a directory on the same partition and file system that your typical BSP (or application) will access during runtime. If there are multiple devices or partitions, the I/O stress test should be executed on all of them.
Additionally, it is recommended to run a network load in parallel, for example, using iperf3. If your device lacks a network card, iperf3 can be run on the localhost network, with the device executing both the client and the server.
Any additional relevant loads should be added. It is crucial to test in an environment as close as possible to your typical use case. All peripherals normally used in your application should be accessed. This is very important, as we shall see!
Finally, the test should run for as long as possible. A minimum test should not run less than one hour.
Debugging latency spikes
While cyclictest is a reliable tool for evaluating real-time behavior, it does not help identify the root causes of wakeup latencies in real-time tasks. If significant latency spikes (e.g., exceeding 200 µs) are observed during testing, additional tools are needed to diagnose their origin.
To know the cause of a latency spike, it is useful to know what code was being executed in the kernel when the latency occurred, and the rtla tool provides exactly this. The Real-Time Linux Analysis (rtla) toolkit provides a userspace interface for analyzing latency sources using kernel tracers, including timerlat, available in the mainline kernel, and osnoise. These tools help identify and measure different classes of latency:
- osnoise: Uses the osnoise tracer with all potential sources of operating system noise enabled, such as preemption, softirqs, and IRQs.
- hwnoise: Also leverages the osnoise tracer but with interrupts disabled, focusing on noise caused by non-maskable interrupts and other hardware-related sources.
- timerlat: Measures timer IRQ and thread latency using the timerlat tracer.
You may wonder why we initially went through cyclictest at all, if we end up using rtla to get the blocking stack trace. The reason is that rtla needs a special kernel configuration, with tracing support enabled (see below), which you probably do not want in a production kernel. cyclictest, on the other hand, works with a “production” kernel, which makes it the right tool to validate it. rtla is only needed when a problem has been found and its source must be identified.
To use rtla, ensure your kernel has tracing support enabled by verifying the following kernel configuration options:
CONFIG_TRACING=yCONFIG_FTRACE=y
Additionally, we will also want to enable some tracers:
CONFIG_OSNOISE_TRACER=yCONFIG_HWLAT_TRACER=yCONFIG_TIMERLAT_TRACER=y
The rtla timerlat tool operates similarly to cyclictest: it schedules a timer, sleeps on it, and measures latencies by comparing the expected and actual wake-up times. However, rtla timerlat provides deeper insights. When it detects a latency exceeding a predefined threshold, it generates a kernel stack trace of the blocking thread, along with timing details. The blocking thread, in this context, is the thread that prevents the timely context switch to the awakened thread, for example because it runs with interrupts disabled or because preemption was disabled, or that forces the kernel to wait before servicing an interrupt handler. This helps pinpoint why the kernel failed to schedule the application on time, directly identifying the kernel component responsible for the latency.
You can now repeat our earlier cyclictest-based testing, but this time using rtla timerlat, with the same system load. The following command runs a test similar to the previous cyclictest setup. However, with the following command, it automatically stops if the latency exceeds 400µs and prints a kernel stack trace of the blocking thread:
rtla timerlat top -P f:80 -a 400
The options used are:
-P f:80: run the measurement threads with the SCHED_FIFO policy (f) and a priority of 80.-a 400: auto-analysis mode. Stop the tracing as soon as a latency exceeds 400µs, and print the analysis of the event.
For details on the flags used, refer to the help message of
rtla timerlat top -h or refer to the source code.
As long as no latency exceeds the threshold, rtla keeps refreshing a table like this one showing the latency statistics:
0 00:49:39 | IRQ Timer Latency (us) | Thread Timer Latency (us) CPU COUNT | cur min avg max | cur min avg max 0 #2978573 | 4 0 2 49 | 27 12 19 85 1 #2978573 | 3 0 2 40 | 18 12 17 73 2 #2978573 | 3 0 2 32 | 22 12 17 66 3 #2978573 | 2 0 2 37 | 17 12 17 58 4 #2978573 | 6 0 1 37 | 32 7 10 93 5 #2978573 | 5 0 1 35 | 28 6 10 78
The first line shows the elapsed time of the test (here, 49 minutes and 39 seconds). Then there is one line per CPU, with:
COUNT: number of timer activations on this CPU.- IRQ Timer Latency: the delay between the moment the timer was supposed to fire and the moment its interrupt handler actually started to run, with the current (
cur), minimum, average and maximum values in µs. - Thread Timer Latency: the delay between the expected time and the moment the real-time thread actually ran. This is the value comparable to the cyclictest latency, and it includes the IRQ latency.
Here again, the maximum values are the ones to look at: the worst thread latency is 93 µs, which is consistent with the cyclictest results above. The difference between the two columns also tells where time is spent: a high IRQ latency means that something prevented the interrupt from being handled (for example, interrupts masked or a CPU running firmware), while a high thread latency with a low IRQ latency points to scheduling delays after the interrupt.
Practical issue: Latency Spike Analysis on i.MX8QM
During testing on an i.MX8QM, the following trace was observed in the rtla output after few minutes (below the the table showing the latency statistics):
## CPU 2 hit stop tracing, analyzing it ##
IRQ handler delay: 0.00 us (0.00 %)
IRQ latency: 1168.45 us
Blocking thread:
kworker/u13:4:4265
Blocking thread stack trace
-> timerlat_irq
-> __hrtimer_run_queues
-> hrtimer_interrupt
-> arch_timer_handler_phys
-> handle_percpu_devid_irq
-> generic_handle_domain_irq
-> gic_handle_irq
-> call_on_irq_stack
-> do_interrupt_handler
-> el1_interrupt
-> el1h_64_irq_handler
-> el1h_64_irq
-> __arm_smccc_smc
-> rtc_set_time
-> sync_hw_clock
-> process_one_work
-> worker_thread
-> kthread
-> ret_from_fork
The trace reads from bottom to top: a kernel worker (kworker) runs sync_hw_clock(), which calls rtc_set_time(), which executes an smc instruction (__arm_smccc_smc). The timer interrupt arrives while the CPU is in this call, and its handling of timerlat_irq is delayed by more than 1 ms: the IRQ latency is 1168.45 µs, far above our 400 µs threshold.
By searching who provides the rtc_set_time symbol, it was identified that the latency spike originates from the IMX RTC driver, specifically due to an SMC call when the RTC time is set.
Validation Steps:
- To confirm the RTC driver as the sole source of the issue, the RTC device was unbound from its driver:
echo system-controller:rtc > /sys/class/rtc/rtc0/device/driver/unbind
Re-running the tests after unbinding the RTC driver revealed no further latency issues. - With the RTC device probed, running cyclictest alone and executing the
hwclock -wcommand reproduced the latency spike, confirming the RTC set time as the trigger. - Similarly, running cyclictest and executing the
hwclockcommand, which reads the RTC time, did not reproduce the latency spike. This is interesting because reading the RTC time also triggers an SMC call, yet it does not introduce any latency, like when setting the time.
Root Cause Investigation:
Before diving into the firmware, let’s recap what we know so far and which questions it raises:
- What is slow? Setting the RTC time. The kernel does it periodically through
sync_hw_clock(), which copies the system time to the RTC, and we can trigger it manually withhwclock -w. - What is an SMC? The RTC driver does not access the RTC hardware itself, it asks the firmware to do it, through a Secure Monitor Call (SMC). On ARM64, this instruction makes the CPU leave the operating system (exception level EL1) and jump into the most privileged firmware (EL3). The call is synchronous: the CPU only comes back to Linux once the firmware has finished and returned a result.
- Why is firmware involved? The firmware running at EL3 is Trusted Firmware-A (TF-A), the reference implementation of the ARM secure monitor. It is the component that responds to SMC calls, and on the i.MX8 it implements the vendor-specific services used by Linux, including the RTC.
- Why does it hurt real-time? While a CPU is waiting for the SMC to return, Linux cannot run on it, and cannot serve the pending timer interrupt either. The duration of the SMC call is therefore directly added to the latency, and the kernel has no way to preempt it.
So the question becomes: what does TF-A do during this call to take that long? The SMC call leads to the following sequence in the Trusted Firmware-A (TF-A):
This final function executes an RPC handled by the System Controller Firmware (SCFW), which runs on the System Controller Processor (SCP), which is a dedicated ARM Cortex-M4 core embedded in the i.MX8 SoC. This core owns resources such as the RTC, and the application cores have to ask it to access them.
Following the RPC call, the timer_set_rtc_time() function (source) is executed on the Cortex-M4. This function calls SNVS_SetRtc(), but its source code is unavailable, only the object file is accessible.
To validate this analysis, the imx_srtc_set_time() function was patched to immediately return 0, effectively bypassing the RPC call and confirming its role in the latency spike.
Conclusion
We have confirmed that the latency spike comes from the firmware, not from Linux itself. This raises a legitimate question: since the work is done by firmware running on a separate core, why does the SMC call block the application core while it waits? It could be done asynchronously, so that the CPU would be free to serve interrupts in the meantime.
The answer is that the current architecture is synchronous: the SMC call only returns once the System Controller has answered the RPC. Making it asynchronous would require modifying this architecture, in the TF-A and in the interface with the SCFW.
In practice, this means that the RTC must be treated as a source of latency on this platform. This is also a good illustration of why the system must be tested with all the peripherals used by the application: a plain cyclictest run without using the RTC would never have revealed this issue.
If you’re interested in getting more details about PREEMPT_RT and Real-Time on Linux, check out our Real-time Linux with PREEMPT_RT training.
