Skip to content

rtapi: add opt-in virtual time for accelerated uspace simulation - #4893

Open
grenzland64 wants to merge 4 commits into
LinuxCNC:masterfrom
grenzland64:virtual-time
Open

grenzland64 wants to merge 4 commits into
LinuxCNC:masterfrom
grenzland64:virtual-time

Conversation

@grenzland64

@grenzland64 grenzland64 commented Nov 23, 2026 •

Copy link
Copy Markdown

Follow-up to the discussion in #4863. This is the small in-tree part I proposed there: an opt-in switch for uspace rtapi_app that lets a simulation run faster than real time. Everything specific to my use case (trace capture, gating of task and I/O) stays out of tree.

What it does

With RTAPI_VIRTUAL_TIME=1 in the environment of rtapi_app:

  • the POSIX non-realtime backend is selected, regardless of the kernel,
  • the realtime thread never sleeps between cycles,
  • rtapi_get_time() returns the thread start time plus exactly one period per completed cycle, so components see a jitter-free clock,
  • rtapi_app drops root and all capabilities at startup.

Without the variable nothing changes; all new code paths are behind the check.

RTAPI_VIRTUAL_TIME=1 halrun setup.hal

Limits

  • Single realtime thread only. Starting a second thread fails with -EBUSY. Several threads would need a scheduler that orders them in virtual time; I left that out to keep the change small.
  • Simulation only. Because root and capabilities are dropped, drivers that need privileged hardware access fail to load. This does not catch drivers that work without privileges (for example hm2_eth over UDP or gpiod). If you would prefer an explicit refusal, I am happy to add one; suggestions for the right place are welcome.
  • Only the realtime side is accelerated. Non-realtime programs (task, I/O, UIs) still run on the wall clock, so a complete LinuxCNC session needs additional coordination, which is what I keep out of tree.

Testing

  • New test tests/virtual-time: every cycle sees exactly one period on timedelta, more than 10 s of virtual time pass within 1 s of real time, and a second thread is refused.
  • scripts/runtests on tests/virtual-time, tests/threads.*, tests/rtapi*, tests/hal*, tests/uspace: 35 of 36 pass. The one failure is tests/halrmt, which needs nc; it was not installed in my build container, so I have not confirmed the cause.
  • Built run-in-place on Debian trixie (uspace, documentation build disabled), on top of 65f7467.
  • Checked by hand that with the switch rtapi_app runs with the real uid and empty capability sets, and without it behaves as before.

Not tested: RT-PREEMPT, Xenomai and RTAI hosts (the switch is meant to bypass them, but I could only run on a non-realtime kernel), and the documentation build for the new ENVIRONMENT section in rtapi_app.1.

Comment thread tests/virtual-time/test.sh Resolved
Comment thread src/rtapi/uspace_rtapi_app.hh Resolved
Comment thread src/rtapi/uspace_posix.cc Resolved
Comment thread src/rtapi/uspace_posix.cc Resolved
@BsAtHome

Copy link
Copy Markdown
Contributor

Have you tried to run the test suite in sim mode?
For run-in-place compile:

cd /your/lcnc/git/checkout/scripts
export RTAPI_VIRTUAL_TIME=1
./runtests

(or parallel tests runtests -j 32)

@grenzland64

Copy link
Copy Markdown
Author

Yes, but...

Without RTAPI_VIRTUAL_TIME (uspace, run-in-place, aarch64 Debian container, non-realtime): 380 run, 374 successful, 6 failed, 2 skipped. The six are stale-motion-status/slow-controller and five ui-smoke/* tests. They fail identically before and after the review fixes; I have not yet compared against master, so I can't say whether they come from my container or from this PR.

With export RTAPI_VIRTUAL_TIME=1: pure HAL tests pass, but tests that start a full linuxcnc session fail. The run is slow because each of those waits for a timeout; it is still going, and of the first 65 tests, 15 failed (abort/*, axis-type, ccomp/early-exit, hal-delf-live, halui/jogging, halui/mdi, hard-limits, home-absolute-encoder).

The cause is the mode itself, not the tests:

  • The servo thread no longer sleeps, so motion rewrites emcmotStatus continuously. usrmotReadEmcmotStatus() gives up after three torn seqlock reads, and task reports "can't read motion status".
  • Task, the UIs and the test scripts wait on wall-clock time while the realtime thread runs on virtual time. For example, kins-limits/jog had sampler write several GB within a minute.
  • hal-delf-live is a pure HAL test that fails for the same reason: "thread did not leave function within 1000 periods" is over almost instantly when periods take no time.

So this mode is only useful for pure HAL simulations under halrun, which is what tests/virtual-time covers. Making the full stack virtual-time aware would be a much larger change than this PR. I have added a paragraph to rtapi_app(1) that says so (f68e185). Since the mode is opt-in, nothing changes for anyone who does not set the variable.

If you think a HAL-only simulation mode is too narrow to be worth carrying, I'm happy to hear that.

@BsAtHome

Copy link
Copy Markdown
Contributor

Without the env variable set or at zero, then all tests must succeed. But, I think we need to look into making the tests function properly with virtual time too. There are lots of RT/non-RT sync problems and letting the HAL thread spin very fast exposes them. We need to look into that a bit more.

The hal-delf-live loads a custom component that uses the rtapi_get_time() to calculate the total delay period and calls rtapi_delay() to stall the thread. It is there to test removal of a function from the thread while it is running. There is obviously no time to attach to the test when the thread stall is not happening anymore. Maybe it should be disabled in sim mode if we cannot think of another way to sync up.

The tests that have a wall/virtual time mismatch, well, that is a challenge. These may also be disabled in sim mode if there is no apparent fix. But it should be investigated a bit.

@BsAtHome

Copy link
Copy Markdown
Contributor

Interestingly enough,... running all tests on my machine just stalled at tests/virtual-time and just waited in a parallel run (running runtests -n -j 32). The second parallel run made it succeed.

The third run made it stall again and it stalls in running halcmd -f two-threads.hal. Where exactly is a bit of a mystery because I cannot get a proper backtrace because it runs in a bwrap container. What I can see is a zombie of rtapi_app as a child. This can indicate that the rtapi_app's exit failed to be detected correctly by halcmd. There may be some issues there that need to be looked into (like was done for halrmt). Surely, the first race detected by your proposed change ;-)

@BsAtHome

Copy link
Copy Markdown
Contributor

FYI, the test exposes a serious bug.
Apparently, under heavy load, about every second invocation wile running stress-ng --cpu 32 on my 8 core machine, there is an exit path, somewhere, that exits an instance of a program (or crashes without a core dump) with the hal mutex locked. That will then stall the halcmd exit procedure. This will be an "interesting" search where and how this happens.

grandixximo added a commit to grandixximo/linuxcnc that referenced this pull request Nov 24, 2026
thread_task() read hal_data->threads_running twice: once to decide on
the init pass, once for the cyclic pass. A start that lands between the
two reads runs the cyclic functions once before the init functions, and
the init pass that follows runs no cyclic functions, so that cycle is
missing for every function on the thread.

Read it once per pass.

Seen with the virtual time of LinuxCNC#4893 under load: timedelta reported
a maximum of two periods in about one run out of a hundred, none in
130 runs with the fix.
grandixximo added a commit to grandixximo/linuxcnc that referenced this pull request Nov 24, 2026
When the reader of rtapi_app's stderr went away, for example
halrun x.hal | grep -q pattern, the next message killed the master with
SIGPIPE. If it held the HAL mutex at that moment, every later halcmd
spun on the mutex forever. Bertho Stultiens hit this as a hang in the
tests/virtual-time test of LinuxCNC#4893 under load.

Ignore SIGPIPE at the start of main(), so the master and every client
get EPIPE from the write instead.

tests/uspace/closed-stderr runs halrun with a stderr pipe that has no
reader: before the fix halrun exits 141 and leaves the shared memory
behind, with it the thread is created and halrun exits 0.
grandixximo added a commit to grandixximo/linuxcnc that referenced this pull request Nov 24, 2026
When the reader of rtapi_app's stderr went away, for example
halrun x.hal | grep -q pattern, the next message killed the master with
SIGPIPE. If it held the HAL mutex at that moment, every later halcmd
spun on the mutex forever. Bertho Stultiens hit this as a hang in the
tests/virtual-time test of LinuxCNC#4893 under load.

Ignore SIGPIPE at the start of main(), so the master and every client
get EPIPE from the write instead.

tests/uspace/closed-stderr runs halrun with a stderr pipe that has no
reader: before the fix halrun exits 141 and leaves the shared memory
behind, with it the thread is created and halrun exits 0.
grandixximo added a commit to grandixximo/linuxcnc that referenced this pull request Nov 24, 2026
thread_task() read hal_data->threads_running twice: once to decide on
the init pass, once for the cyclic pass. A start that lands between the
two reads runs the cyclic functions once before the init functions, and
the init pass that follows runs no cyclic functions, so that cycle is
missing for every function on the thread.

Read it once per pass.

Seen with the virtual time of LinuxCNC#4893 under load: timedelta reported
a maximum of two periods in about one run out of a hundred, none in
130 runs with the fix.
@grenzland64

Copy link
Copy Markdown
Author

I reproduced the stall and found the cause. It is not halcmd, and it is my test's fault.

The stall in tests/virtual-time

The test piped halrun two-threads.hal 2>&1 into grep -q. grep -q exits at the first match, the pipe closes, and the next write to stderr kills rtapi_app with SIGPIPE (it has the default action for that signal). If that happens while its main thread holds the HAL mutex, halcmd spins on the mutex forever.

Evidence from a hung run under load (6 CPUs, 24 busy loops): halcmd -f two-threads.hal in state R, the master a zombie with exit status signal 13, and the HAL mutex in shared memory still held by the dead master's main thread. With the output going to a file instead of the pipe, 200 of 200 runs passed under the same load.

Fixed in 6be9c88: the test now uses grep … >/dev/null, which reads to the end. I did not change the SIGPIPE handling in rtapi_app; anything else that closes its stderr early can still kill it the same way. That predates this PR and probably deserves its own fix.

Refusing the second thread earlier

Also in 6be9c88: the refusal moved from task_start() to do_task_new(), and task_new() hands the task slot back. hal_create_thread() now fails before a task exists, so nothing is left behind.

A second race the test exposed, in thread_task()

Looping the fixed test under load, about 1 run in 100 printed timedelta.0.max = 2000000 instead of 1000000. thread_task() reads threads_running twice per pass. If start lands between the two reads, the thread runs one cyclic pass, then the init cycle (which skips the cyclic functions), then continues, so the functions see a gap of two periods. This is in master too; a thread that never sleeps just hits the window far more often.

7795363 reads the flag once. Before: 4 bad of 200 and 3 bad of 300. After: 300 of 300 good, no hang. It is a separate commit, so I can move it to its own PR if you prefer.

The six failures without the variable

I ran the six on a build of the merge base (65f7467), same container:

  • The five ui-smoke tests (gmoccapy-quit, qtdragon-quit, qtdragon, touchy-fit, touchy-quit) fail there too, so they come from my container, not from this PR.
  • stale-motion-status/slow-controller passes on the base and passed 3 of 3 alone on the PR build. It failed only inside the loaded full-suite run, so I believe it is timing-sensitive rather than caused by this PR, but I have not proven that.

Not done: I have not rerun the full suite on the build that includes 7795363, only tests/virtual-time.

@BsAtHome

Copy link
Copy Markdown
Contributor

A fix for the SIGPIPE problem has been committed to master. Now rtapi_app ignores the signal and an EPIPE error is returned.

The threads_running race is also fixed in master, changing the if() handling of the inits/functions in the HAL thread.

You need to rebase to resolve the conflict.

RTAPI_VIRTUAL_TIME=1 selects the POSIX non-realtime backend, skips the
period sleep and makes rtapi_get_time() advance by exactly one period
per cycle. It is off by default and limited to a single realtime
thread. rtapi_app drops root and all capabilities in this mode, so
hardware drivers that need privileged access cannot be loaded.
Address review comments on the virtual-time change:

- rtapi_virtual_time() is now declared in uspace_rtapi_app.hh and
  defined in uspace_rtapi_main.cc, where the environment is read once
  instead of on every call. The comment says "non-zero", like the
  manual page.
- PosixApp uses its virtual_time member: the note is printed from the
  constructor, and the thread wrapper sets vtime unconditionally, since
  do_get_time() only reads it in virtual-time mode.
- The refused-second-thread case uses a static two-threads.hal and
  checks for the refusal message instead of accepting any failure.
A full LinuxCNC session does not work in this mode: motion rewrites its
status without pause, so task cannot read a consistent copy, and
everything waiting on wall-clock time no longer matches the realtime
thread.
The refusal sat in task_start(), so hal_create_thread() failed after the
task existed and left it behind. Refuse in do_task_new() instead and hand
the task slot back.

tests/virtual-time: no grep -q. It quits at the first match, the pipe
closes and the next write to stderr kills rtapi_app with SIGPIPE. When
that happens while it holds the HAL mutex, halcmd waits forever.
@grenzland64

Copy link
Copy Markdown
Author

Update: I rebased onto current master and force-pushed.

On the rebased tree in my container: tests/virtual-time and tests/uspace/closed-stderr pass, and 100 of 100 looped runs of tests/virtual-time under load (6 CPUs, 24 busy loops) are good, no hang. I have not rerun the full suite on it.

@BsAtHome

Copy link
Copy Markdown
Contributor

Running all tests (parallel) normally works as expected. However, running in sim mode fails quite a lot. Everything (most?) with the sampler will cause the disk to overflow. The attached file is an incomplete summary of failures. I had to abort the parallel run because the container(s) ran out of space. I noticed that running parallel in sim mode is actually slower. There are a lot of sync problems when running a real config.

This is a starting point to look at the failing tests and see why they fail and if they can be repaired for sim mode or we must drop them in sim mode. The fact that some tests crashed (shared memory not cleaned up) is a sure sign that there are things that need fixing.

simfail.txt

@BsAtHome

Copy link
Copy Markdown
Contributor

The full machine tests fail because the RT motion-controller (emcmotController()) runs continuously hammering the emcmotStatus struct so fast that only a very tiny window exists where the non-RT reader usrmotReadEmcmotStatus() can read the emcmotStatus data.

Probably, in sim-mode, you need a mutex to forcefully block the motion controller for a moment and allow non-RT to read a consistent data snapshot. For this we need to add a configuration that is interfaced from non-RT to RT.

The usrmotWriteEmcmotCommand() interaction with the motion-command-handler (emcmotCommandHandler()) is protected with a mutex, where task can lock onto.

Similar issues will also be seen with the emcmotInternal and emcmotConfigstructures and maybe also the emcmotError structure. These need RT/non-RT interaction where non-RT is the slave waiting for a window of opportunity to read a consistent snapshot. When RT is running boundlessly in the sim, then that window is very small and leads to timeouts. Therefore, it must be enforced using a mutex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants