503 points · by jonbaer · 2y ago · 138 comments
Here are a few links to see how the work is done behind the scenes. Sadly arstechnica has only funny links and doesn't provide the actual source (why LinkedIn?).
Most of the work was done by Thomas Gleixner and team. He founded Linutronix, now (I believe) owned by Intel.
Pull request for the last printk bits: https://marc.info/?l=linux-kernel&m=172623896125062&w=2
Pull request for PREEMPT_RT in the kernel config: https://marc.info/?l=linux-kernel&m=172679265718247&w=2
This is the log of the RT patches on top of kernel v6.11.
https://git.kernel.org/pub/scm/linux/kernel/git/rt/linux-rt-...
I think there are still a few things you need on top of a vanilla kernel. For example the new printk infrastructure still needs to be adopted by the actual drivers (UART consoles and so on). But the size of the RT patchset is already much much smaller than before. And being configurable out-of-the-box is of course a big sign of confidence by Linus.
Congrats to the team!
https://wiki.linuxfoundation.org/realtime/documentation/howt...
It measures and displays the interrupt latency for each CPU core. Without the real-time patch, worst case latency can be double digit milliseconds. With the real-time patch, worst case drops to single digit microseconds. (To get consistently low latency you will also have to turn off any power saving states, as a transition between sleep states can hog the CPU, despite the RT kernel.) Cyclictest is an important tool if you're doing real-time with Linux.
As an example, if you're doing processing for software defined radio, it's the difference between the system occasionally having "blips" and the system having rock solid performance, doing what it is supposed to every time. With the real time kernel in place, I find I can do acid-test things, like running GNOME and libreoffice on the same laptop as an SDR, and the SDR doesn't skip a beat. Without the real-time kernel it would be dropping packets all over the place.
--priority=99
Apply priority 99 with care to your own code. A tight endless loop with priority 99 will override pretty well everything else, so about the only way to escape will be to turn your computer off. Been there, done that :-)
Notice that without setting the priority, default policy is other, which is the standard one most processes get unless they request else.
By setting priority (while not specifying policy), the policy becomes fifo, the highest, which is meant to give the cpu immediately and not preempt until process releases it.
This implicit change in policy is why you see such brutal effect from setting priority.
If you're developing anything on x86 that needs realtime - how do you disable SMM drivers causing unexpected latency?
And while it won't (completely) remove SMM, https://github.com/corna/me_cleaner might get rid of some stuff. I think that's more about getting rid of spyware and ring -1 security bugs than improving real-time behavior though.
The problem space is such that it doesn't necessarily mean "faster" or lower latency in any way, just that where there is latency: it's consistent.
With it, I routinely have 6 instruments at 1ms, while having dozens of chrome windows open and playing 3d shooters without issue.
It's shocking how much difference it makes over the regular (non-rt) low latency scheduler.
I haven't objectively tested it, but my feeling is that it actually makes for a nicer user experience. Sometimes Gnome can briefly freeze or feel sluggish (presumably the CPU is off doing something) and I feel that the RT kernel does away with this. It could be a placebo effect though.
in what way? I'd say responsiveness is more important to the desktop than raw performance and from my experience with nearly 2 decades of using Linux desktops, responsiveness has never been great.
If I'm switching between windows whilst encoding a video in the background, the window manager should have instant priority even if it means starving the background task of some CPU time. on GNOME this is quite bad, run a very heavy task (e.g. AI) in the background and the desktop will start to suffer.
The reason I wrote my original comment is precisely because “audio xruns at a higher latency with lower system load” is a very concrete measure of improvement that I can't fool myself about, including effects like “the system runs better when freshly booted for a while” that otherwise bias the judgements of the uninitiated towards “…and therefore the new kernel improved things!”
There isn't much on a desktop that is sensitive to latency spikes on the order of a couple ms, which a stock kernel should already be able to maintain.
Suppose your audio server attempts fancy resampling, but falls back to a crude approximation after the first xrun.
Do you experience any downsides running the RT scheduler?
My usual setup has 2 PianoTeq (physically modelled piano/electric piano/clavinet) instances, 3 SurgeXT instances (standard synthesizer), a setBfree (Tonewheel/hammond simulator) instance, and a handful of sequencers and similar for drums, as well as a bunch of routing and compressors and such.
Do you have any published music you will to share?
Thanks!
What goes into ensuring that a program is actually realtime? Are there formal proofs, or just experience and "vibes"? Is realtime coding any different from normal coding? How do modern CPU architectures, which have a lot of non-constant time instructions, branch prediction, potential for cache misses and such play into this?
Realtime mostly means predictable runtime for code. As long as its predictable, you can scale the CPU/microcontroller to fit your demands or optimize your code to fit the constraints. It’s about making sure your code can always respond in time to hardware inputs, timers, and other interrupts.
Generally the Linux kernel’s scheduling makes the system very unpredictable. RT linux tries to address that along with several other subsystems. On embedded CPUs this usually means disabling advanced features like cache, branch prediction, and speculative execution (although I don’t remember if RT handles that part since its very vendor specific).
Example: you'd probably want the airbags in your car to fire precisely at the right time to catch you and keep you safe rather than blow up in your face too late and give you a nasty neck injury in addition to the other injuries you'll likely get in a hard enough crash.
As for the hardware, you can't really use a ‘regular’ CPU and expect completely deterministic behavior. The things you mentioned (and for example caching) absolutely impact this. iirc amd/xilinx actually offer a processor that has both regular arm cores, alongside some arm real time cores for these exact reasons.
Then, there's the whole thing of hardware. Do you have one or more cores? If you have more than one core, can they introduce jitter or slowdown to each other accessing memory? And so on and so forth.
I'm laughing so so hard right now. Thanks for, among other things, confirming for me that there isn't some magic tool that I'm missing :). At least I have the benefit of working on softer real-time systems where missing a deadline might result in lower quality data but there's no lives at risk.
Setting and clearing GPIOs on task entry/exit are a nice touch for verification too.
These are relatively easy to obtain on an MCU, where there's no virtual memory, physical memory is predictable (if slow), interrupt hardware is simple, hardware watchdogs are a norm, an normally there's no need for preemptive multitasking.
But when you try to make it work in a kernel that supports VMM, kernel / userland privilege separation, user sessions separation, process separation, preemptive multitasking, and has to work on hardware with a really complex bus and a complex interrupt controller, — well, here's where magic begins.
In user space it's often about complexity and guarantees: for example, you really try not to do mallocs in a real-time thread in user space, because it's a system call that will only return in an unpredictable amount of time. Better to preallocate buffers or use the stack. Same for opening files, or stuff like that -- you want to avoid variable time syscalls and do them at thread / application setup.
Choice of algorithms needs to be such that for whatever n you're working with, that it can be processed inside of one sample generation interal. I'm mostly familiar with audio -- e.g. if you're generating audio at 44100 Hz, you need your algorithms to be able to process chunks in less than 22 microseconds.
That being said, vibes and kiss principle can get you remarkably far.
Audio-centric, but will you give a feel for what's involved.
On an ECU I worked on, the cache was turned off to not have cache misses ... no cache no problem. I argued it should be turned on and the "OK cpu load" limit decreased instead. But nope.
I wouldn't say there is any conceptual difference from normal coding, except for that you'd want to be kinda sure algorithms terminate in a reasonable time in a time constrained task. More online algorithms than normally, though.
Most of the strangeness in real time coding is actually about doing control theory stuff is my take. The program often feels like state-machine going in a circle.
Yeah, the tradeoff there is interesting. Sometimes "get it as deterministic as possible" is the right answer, even if it's slower.
> Most of the strangeness in real time coding is actually about doing control theory stuff is my take. The program often feels like state-machine going in a circle.
Lol, with my colleagues/juniors I'll often encourage them to take code that doesn't look like that and figure out if there's a sane way to turn it into "state-machine going in a circle". For problems that fit that mold, being able to say "event X in state Y will have effect Z" is really powerful for being able to reason about the system. Plus, sometimes, you can actually use that state machine to more formally reason about it or even informally just draw out the states, events, and transitions and identify if there's anywhere you might get stuck.
In rt land, you test in prod and hope for the best.
(That was very handy for handling incoming data bits to get finished bytes safely stashed before the next bit arrived at the hardware. Been a -long time- since I heard VI's mentioned.)
Afaik, the reason why real time Linux was considered impractical was to have hard RT guarantees, you needed to ensure that ALL non-preemptable sections in the kernel had bounded runtime, which was a huge burden for a fairly niche use case.
I wonder how they got around this requirement, or if they didn't, did they rewrite everything to be compliant to this rule?
Also, does this means that Linux supports priority inversion now?
I can't say, but I know that they have made wide-ranging changes to behavior, e.g. the in-kernel locks: https://www.kernel.org/doc/html/latest/locking/locktypes.htm...
I don't believe they've actually made the kernel completely preemptive, though others can correct me. This means that you cannot achieve the same realtime performance with this as you could with a mesa kernel like xenomai.
Cyclictest (from rt-test) is a tool to test exactly this. It will set an alarm and sleep on it. Then measure the offset between the time the alarm was set to, and the time the process gets the CPU.
With SCHED_FIFO (refer to sched(7)), the system is supposed to drop what it is doing the instant such a task becomes runnable, and not preempt it at all; CPU will only be released when the program voluntarily yields it by entering wait state.
Look at the max column; the unit is microseconds. There's a huge difference between behaviour of a standard voluntary preempt kernel and one with PREEMPT_RT enabled.
Linux is still Linux, and having Linux as a whole be preemptable by a separate RTOS kernel is always going to perform better in the realtime front, relative to trusting Linux to satisfy realtime for the user tasks it runs.
Incidentally, seL4[0] can pull off that trick, and do it even better: It can support mixed criticality (MCS), where hard realtime is guaranteed by proofs despite less important tasks, such as a Linux kernel under VMM, running on the same system.
A debugging tool? I do like printk debugging but I am not sure about that description :-)
One thing to keep in mind for people looking at the RT patches and thinking about things like this: these patches allow you to do RT processing on Linux, but they don't make some of the complexity go away. In the Klipper case, for example, writing to the GPIOs that actually send the signals to the steppers motors in Linux is relatively complex. You're usually making a write() syscall that's going through the VFS layer etc. to finally get to the actual pin register. On a microcontroller you can write directly to the pin register and know exactly how many clock cycles that operation is going to take.
I've seen embedded Linux code that actually opened /dev/mem and did the same thing, writing directly to GPIO registers... and that is horrifying :)
http://linuxcnc.org/
These days not sure, hard to find computer with parallel port. Combined version with microcontroller like raspberry pico (which costs < $10) should be the right way to do it. Hard real time, WiFi remote for cheap. Then computer doesn't need to be fat or realtime, almost anything, including smartphone.Marco Reps has some entertaining and informative videos on LinuxCNC with EtherCAT
On a PC you have millions of lines of kernel code, BIOS/EFI code, firmware, etc. You have complex video card drivers, complex storage devices. You have the SMM that yanks control away from the OS whenever it pleases.
The idea of running a dangerous machine controlled by that mess is frankly scary.
(disclaimer: i've never run linuxcnc)
but nowadays usually people do the hard real-time stuff on a microcontroller or fpga. amd64 processors have gotten worse and worse at hard-real-time stuff over the last 30 years, they don't come with parallel ports anymore (or any gpios), and microcontrollers have gotten much faster, much bigger, much easier to program and debug, and much cheaper. even fpgas have gotten cheaper and easier
there's not much reason nowadays to try to do your hard-real-time processing on a desktop computer with caches, virtual memory, shitty device drivers, shitty hardware you can't control, and a timesharing operating system
the interrupt processing jitter on an avr is one clock cycle normally, and i think the total interrupt latency is about 8 cycles before you can toggle a gpio. that's a guaranteed response time around 500 nanoseconds if you clock it at 16 megahertz. you are never going to get close to that with a userland process on linux, or probably anything on an amd64 cpu, and nowadays avr is a slow microcontroller. things like raspberry pi pico pioasm, padauk fppa, and especially fpgas can do a lot better than that
(disclaimer: though i have done hard-real-time processing on an avr, i haven't done it on the other platforms mentioned, and i didn't even write the interrupt handlers, just the background c++. i did have to debug with an oscilloscope though)
Historically it used RTAI; now everyone is moving to preempt-rt. The install image is now preempt-rt.
I've been on the flipside where you're streaming g-code from something that isn't hard-realtime to the realtime system. You can be surprised and let the realtime system starve, and linuxcnc does a lot more than you can fit onto a really small controller. (In particular, the way you can have fairly complicated kinematics defined in a data-driven way lets you do cool stuff).
Today my large milling machine is on a windows computer + GRBL; but I'm probably going to become impatient and go to linuxcnc.
But:
> worst-case latency timings a real-time Linux provides are quite useful to, say, the systems that monitor car brakes
I really hope my car brakes don't run Linux ;D …
(they should be running something that has a formal proof of correctness, which is outside the scope of realistically possible for Linux or any other "full-scale" OS)
(pretty sure the article author came up with that example and no Linux kernel developer is aiming for car brakes either. Same for large CNC machines - they can kill and have killed people.)
More discussion: https://news.ycombinator.com/item?id=41584907
Should audio be prioritized over the touchpad "moving" the cursor?
Yes
I presume most drivers haven't been tested in RT mode, so it's possible that RT-specific driver bugs crash your system.
A small impact on throughput is expected, but it shouldn't be noticeable to the user.
What the user can and will notice is the system not being responsive to his commands, as well as audio cuts or audio latency (to prevent cuts).
Thus PREEMPT_RT is a net win.
Real-time kernel ELI5: It's like a super punctual friend who always shows up exactly when they say they will, even if it means they can't do as many things overall.
Key points:
- Guarantees worst-case execution times
- Useful for stuff like lasers, car brakes, Mars rovers
- Been around forever as patches, now official
- Linus quote from 2006: "Controlling a laser with Linux is crazy, but..."
Honestly, this won't change much for most of us. Your Firefox tabs aren't suddenly going to be more responsive. But it's a big deal for embedded systems and industrial applications. Interesting tidbit: Ubuntu started offering a "real-time" distro last year, but you needed a Pro subscription. Wonder how this will affect that business model.
Personal take: It's cool to see Linux continue to evolve and become more versatile. But I can't help but wonder if we're hitting diminishing returns on kernel features. Maybe the next big innovations will be at higher layers of the stack?
Anyone here actually using real-time Linux in production? Would love to hear some war stories.
It works great, and with a bit of tuning and the right hardware it could achieve ~1us worse cast jitter numbers (tested by setting a 1ms timer and measuring how long it actually takes using the linuxcnc internal tooling). Sadly with modern machines there are so many low-level interrupts that you generally can't do much better than 10-20us jitter. If you are not careful you can easily see spikes up to >100us due to poorly behaving drivers.
edit: and it basically paraphrased the article..
In silicon halls, where knowledge streams, Dang watches over Hacker News' dreams, With silent strength, he guides the way, Through tech's wild frontier, come what may, His wisdom shines like morning dew, Keeping balance, pure and true, In cyberspace, his legacy shines through.
Now for penguins as well as sharks!
Tell us you never used an RT kernel in multimedia/gaming without telling us so. The difference can be astounding.
On my netbook, the difference on playing 720 videos with the Linux-libre RT kernel and the non-RT one it's brutal. Either 30FPS videos, or 10FPS at best.