Skip to content

sched/task: End a thread in a system call when the call is over. - #22069

Open
casaroli wants to merge 4 commits into
apache:masterfrom
casaroli:fb-exit-syscall-up
Open

casaroli wants to merge 4 commits into
apache:masterfrom
casaroli:fb-exit-syscall-up

Conversation

@casaroli

@casaroli casaroli commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When a thread ends its process (exit(), _exit() or a fatal signal), group_kill_children() cancels the other threads, and nxtask_terminate() ends each of them where it is. A thread in a system call can hold locks and references there, and kernel objects can be on its kernel stack (a request that a device completes, a callback that a driver calls). Nothing gives them up: a lock stays held for ever, a file is never closed, or a driver later writes into the freed stack. With the default CONFIG_CANCELLATION_POINTS=n this happens to every thread that is in a system call when its process ends.

This PR ends such a thread only when its system call is over. Each commit fixes one thing:

  1. libs/libc: Check the lock of the task information. The kernel copy of libc takes ta_lock (getenv() for $PWD in the inode search, getcwd(), lib_getfullpath(), env_dup(), env_sanitize_secure(), the setenv() family, pthread_atfork(), fork()). Most callers ignored the result of nxrmutex_lock(), and then unlocked a lock that they did not hold. Now each caller checks it. With commit 3 the lock fails with ECANCELED for a thread that its process end canceled; a relative path lookup then fails instead of using the home directory.
  2. sched/pthread: Leave the join queue when pthread_join() is canceled. A cancellation ends the wait of pthread_join() with ECANCELED (today with CONFIG_CANCELLATION_POINTS, and with commit 3 at the end of the process). pthread_join() ignored it and left the caller in the join queue of the other thread. When the caller ended first, pthread_completejoin() later walked into its freed TCB. Now the caller leaves the queue and pthread_join() returns the error.
  3. sched/task: End a thread in a system call when the call is over. For the forced cancellation of an ending process, a thread in a system call (TCB_FLAG_SYSCALL) is marked in a new TCB field, kcancel, and not ended. A wait that a signal ends, and a wait for a mutex in user memory (its holder can have ended with the process), end with ECANCELED. A wait that no signal ends (TCB_FLAG_UNINTERRUPTIBLE) and a wait for a kernel mutex complete first. The marked thread does not start such a wait again. nxsig_unmask_pendingsignal(), which the architecture calls at the end of each system call, then ends the thread; it holds nothing of the kernel there. nxtask_terminate() and its SMP call check again, because the thread can enter a system call after nxnotify_cancellation() looked at it. group_kill_children() walks the member list again after each cancellation, because a woken member can end and leave the list. A thread that ends by itself at the same time (_exit(), pthread_exit()) is left to that end: it is not marked, and nxtask_terminate() and its SMP call leave its TCB_FLAG_EXIT_PROCESSING set, which the thread can have set itself and which nxtask_exithook() needs. For the end of the process, pthread_cancel() does not run the cleanup handlers of the thread (tls_cleanup_popall()) any more, as _exit() runs none: a thread in a system call on another CPU is not ended in the call, and the call does the same cleanup itself when it returns (for example the callback of recv() or accept()).
  4. Documentation: The end of a thread that is in a system call. cancellation_points.rst.

This needs an architecture that ends a system call in the context of the thread. ARM64 and RISC-V do (dispatch_syscall()) and select the new CONFIG_ARCH_HAVE_SYSCALL_THREAD_RETURN. The other architectures with system calls (ARMv6-M/7-M/8-M, ARMv7-A/R, ARMv8-R, MIPS, MISOC, Xtensa) end a system call in the SVC exception handler, where the thread cannot end; they keep the old behaviour. x86_64 does not set TCB_FLAG_SYSCALL (see the note in x86_64_syscall()), so it keeps the old behaviour too.

Impact

PROTECTED and KERNEL builds on ARM64 and RISC-V:

  • A thread in a system call ends when the call returns, not inside it. No cleanup handler of the canceled thread runs (the process ends as with _exit()). The exit status of the process does not change.
  • A thread that waits in the kernel for a device that never answers keeps its process from its end, as a single-threaded process is kept today.
  • nxsig_timedwait() takes a canceled wait (SIG_CANCEL_TIMEOUT) also without CONFIG_CANCELLATION_POINTS.
  • An asynchronous pthread_cancel() still ends a thread at once.
  • One byte in struct tcb_s. Text, measured on an earlier version of this PR without the rule for a thread in its own end (a few more instructions): qemu-armv8a:knsh +1024 bytes, rv-virt:knsh64 +860, rv-virt:pnsh64 (kernel part) +1016.

All builds:

  • Commit 1: when the environment lock fails, getenv() returns NULL with errno, setenv() and fork() return -1. env_sanitize_secure() returns int now (internal; one caller, exec_module()).
  • Commit 2: pthread_join() returns ECANCELED when a cancellation ended its wait, instead of 0 with an old exit value.
  • FLAT builds and the other architectures: no change of behaviour beyond commits 1 and 2. Text (the same earlier version): qemu-armv8a:nsh +340 bytes, mps2-an500:citest_protected (kernel part) +168.

Testing

Test programs (standalone, from /system/bin over 9p, qemu-armv8a under HVF, CONFIG_MM_FILL_ALLOCATIONS=y):

  • sysexit OP 40 DIR MODE: 40 rounds; each round forks a child with 3 worker threads in one kind of system call, and the child ends after a random time up to 100 ms: its main thread calls _exit(7) (exit), the parent sends SIGKILL (kill), or a fourth thread calls _exit(7) (texit). After each round the parent uses the same kind of object (a lock that stays held stops it). It checks the exit status and the page pool and kernel heap of /proc/meminfo. OP: tmpfile (open, write, close, unlink; in a tmpfs and in the 9p root), pipe, local (AF_UNIX socketpair), mmap, poll, semwait, mutex (pthread_mutex_lock() of a mutex that the main thread holds), sleep, net (UDP recv()), tty (pty read()), join (pthread_join() of a thread in pause()), vfork, spin (user code only).
  • exitrace ROUNDS MODE: each round forks a child with 3 threads that wait for a start flag. Then the main thread calls _exit(7), and at the same moment (a random spin of a few microseconds) each thread calls pthread_exit() (pexit) or _exit(7) (texit). On SMP the end of the process then cancels threads that are in their own end.
  • ptyintr: see below.
  • tlsrace ROUNDS MODE (CONFIG_TLS_NCLEANUP=4): each round forks a child with 3 threads in epoll_wait(), poll() or accept() (MODE), and the main thread calls _exit().

qemu-armv8a:knsh, 1 CPU, master 3e66f0a vs this PR:

Test master this PR
ostest status 0 status 0
sysexit tmpfile (tmpfs) exit / kill / texit PASS / hang / not run PASS / PASS* / PASS
sysexit tmpfile (9p root) kernel fault in the virtio interrupt (nested exception) PASS / PASS* / PASS
sysexit pipe, local hang in the first round PASS / PASS* / PASS
sysexit poll kernel fault PASS / PASS* / PASS
sysexit mmap mm_granfree.c:69 assertion (page pool) PASS / PASS* / PASS, pool +0
sysexit join kernel fault exit PASS, kill hangs (see below)
sysexit vfork kernel fault PASS / PASS* / PASS
sysexit mutex exit PASS, kill hangs exit PASS, kill hangs (see below)
sysexit semwait, sleep, net, spin, tty PASS / PASS* / PASS PASS / PASS* / PASS

* "kill" runs report "wrong status" in every round on master and with this PR: waitpid() gives exit status 0 for a child that SIGKILL ended. Not changed by this PR.

The "join kill" and "mutex kill" hangs are the same on master: SIGKILL of the process goes to a thread in a wait that no signal ends (pthread_join(), a mutex), and stays pending there. Not changed by this PR.

ptyintr: 40 children each open a pty pair, start a thread that blocks in read() of the slave, and _exit() after 20 ms. master: the kernel heap grows by 50 KiB, and after about 33 rounds no pty pair can be opened any more (the pairs of the ended processes are never freed). This PR: +128 bytes, all pairs freed (the same as a run with no reader).

qemu-armv8a:knsh, 4 CPUs (CONFIG_SMP): ostest status 0 on both. sysexit: master as on 1 CPU. This PR: all exit and texit cases PASS with pool +0, except vfork, which corrupts the user heap of the child on master and with this PR alike (mm_extend.c:91). tmpfile in the 9p root needs the separate fix "fs/v9fs: Do not release the directory fid twice in unlink." (#22065): on 4 CPUs, master and this PR fault in fs/v9fs without it (a fid used after it is freed), also with no end of a process; with it, tmpfile in the 9p root passes in all three modes.

On 4 CPUs the kill mode of tmpfile in a tmpfs sometimes stops (4 of 11 runs, with and without the rule of commit 3 for a thread in its own end; master stops in this case on 1 CPU already): the other threads of the child wait for the tmpfs lock, and the thread that holds it has ended. So in the SIGKILL path on SMP a thread can still end inside a system call. Not analyzed further. The exit and texit modes do not show it.

exitrace on 4 CPUs: master: kernel fault in the first rounds (group_foreachchild() walks the freed TCB of a member that ended). This PR: 2 x 1000 pexit rounds and 1000 texit rounds, all with the right exit status, in each of 2 boots. (On 1 CPU exitrace is too slow to be useful: its threads wait in busy loops.)

With CONFIG_DEBUG_ASSERTIONS, exitrace on 4 CPUs: 3 x 1000 rounds, no assertion (the lost update of tcb->flags from another CPU is gone since #21804).

tlsrace on 4 CPUs (qemu-armv8a:knsh, CONFIG_TLS_NCLEANUP=4): master: kernel fault in all three modes; the previous head of this PR (557b5dc): kernel fault with epoll_wait() and accept() before round 100; this PR: 3 x 300 and 3 x 1000 rounds PASS, and exitrace, sysexit (exit and texit) and ptyintr PASS on the same image. With the default CONFIG_TLS_NCLEANUP=0: ostest status 0.

qemu-armv8a:knsh, 1 CPU, CONFIG_CANCELLATION_POINTS=y: ostest status 0; sysexit as without it.

qemu-armv8a:nsh (flat), 1 and 4 CPUs: ostest status 0 on master and with this PR.

rv-virt:knsh64 (QEMU TCG, 1 hart): ostest status 0. sysexit exit PASS for mutex, pipe, semwait and join (master: pipe hangs). The kill mode hangs on RISC-V with master and with this PR alike. rv-virt:pnsh64 (protected), 1 and 4 harts: ostest status 0.

Builds in the NuttX CI image (EXTRAFLAGS="-Wno-cpp -Werror"), this PR: all OK, no compiler warnings (only the linker's RWX-segment note, also on master): qemu-armv8a:knsh (also with CANCELLATION_POINTS, SMP, GROUP_KILL_CHILDREN_TIMEOUT_MS -1 and 100, DISABLE_ALL_SIGNALS), qemu-armv8a:nsh, nsh_smp, rv-virt:knsh64, ksmp64, knsh (rv32), pnsh64 (also with CANCELLATION_POINTS, SMP, ENABLE_PARTIAL_SIGNALS, without MM_KERNEL_HEAP), pnsh, nsh64, smp64, mps2-an500:citest_protected, mps2-an500:knsh, qemu-armv7a:knsh, qemu-intel64:knsh_romfs, qemu-intel64:nsh, sim:ostest. sim:smp fails in apps testing/ostest/intstack.c on master and with this PR alike. sim:ostest (CI image): 4 of 5 loops in 900 s on a loaded host, master and this PR alike.

Rebased on master 695d403: qemu-armv8a:knsh and qemu-armv8a:nsh build with no warning, and ostest exits with status 0 on both (1 CPU). The CI image builds 13 of 13 configs with -Werror on this head (qemu-armv8a knsh variants and nsh, rv-virt knsh64, ksmp64, pnsh64 and citest, mps2-an500:citest_protected, qemu-intel64:knsh_romfs, sim:ostest).

tools/checkpatch.sh -c -u -m -g passes. Documentation: commit 4.

Not in this PR

  • FLAT builds still end a thread where it is, also inside the OS.
  • The other architectures with system calls (see above) keep the old behaviour. They need to end a system call in the context of the thread first.

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

esp32-devkitc

  • ROM: .flash.text +204 B (+0.2%, 133,980 B / 4,194,272 B, total: 3% used)
  • irom0_0_seg: .flash.text +204 B (+0.2%, 99,640 B / 3,342,304 B, total: 3% used)

hifive1-revb

  • flash: .text +176 B (+0.2%, 85,672 B / 4,194,304 B, total: 2% used)

mps2-an500-citest

  • flash: .text +208 B (+0.1%, 248,800 B / 4,194,304 B, total: 6% used)

mps2-an500-citest-protected

  • flash: .text +168 B (+0.1%, 117,096 B / 4,194,304 B, total: 3% used)

qemu-armv8a

  • Code: .text.clearenv +36 B, .text.env_dup +12 B, .text.getcwd +20 B, .text.getenv +16 B, .text.group_kill_children +156 B, .text.inode_search_setup +24 B, .text.nxsig_timedwait +32 B, .text.pthread_join +144 B, .text.putenv +12 B, .text.setenv +12 B, .text.unsetenv +32 B (+0.1%, 379,756 B)

qemu-intel64

  • Code: .text +410 B (+0.0%, 8,708,456 B)

rx65n-rsk2mb

  • ROM: .text +96 B (+0.1%, 93,464 B / 2,097,152 B, total: 4% used)

s698pm-dkit

  • Code: .text +816 B (+0.2%, 412,272 B)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

@casaroli
casaroli marked this pull request as draft November 20, 2026 09:52
@casaroli
casaroli marked this pull request as ready for review November 20, 2026 09:52
Comment thread sched/task/task.h Resolved
@casaroli
casaroli marked this pull request as draft November 26, 2026 14:01
@casaroli
casaroli marked this pull request as ready for review November 26, 2026 14:01
The lock of the task information, ta_lock, is in the memory of the
process.  The kernel copy of libc takes it too: getenv() for $PWD in the
inode search, getcwd() and lib_getfullpath(), env_dup() when a task
starts or forks, env_sanitize_secure() in exec.  Most of the callers did
not check the result of nxrmutex_lock().  When the lock fails, they use
the environment without the lock, and then unlock a lock that they do
not hold: the assertion "rmutex->count > 0" in nxrmutex_unlock(), or
without assertions a count that wraps and a lock that stays held.

The lock will fail with ECANCELED in the kernel: a thread that the end
of its process cancels in a system call must not wait for a mutex in
the memory of the process, whose holder can have ended ("sched/task: End
a thread in a system call when the call is over.").

Check the result in each function that takes ta_lock, and fail:

- getenv() returns NULL, with errno set to the error of the lock;
- setenv(), unsetenv(), putenv() and clearenv() return -1 with errno;
- env_dup() returns the error, and env_sanitize_secure() returns it now
  too: exec fails;
- openlog() changes nothing, and __res_state() returns NULL;
- pthread_atfork() returns the error;
- fork() and vfork() fail when the prepare handlers or the lock of the
  copy cannot run, and the child handlers do not run then.

getcwd(), the inode search and lib_getfullpath() use the home directory
when $PWD is not set.  When the lock in getenv() fails with ECANCELED,
they must not do that: a relative path then names a file in another
directory.  They fail with ECANCELED.

pthread_key_create(), pthread_key_delete() and atexit() check the result
already.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
pthread_join() puts the calling thread into the join queue of the
thread that it waits for, and pthread_completejoin() posts each thread
of that queue when the thread ends.  A cancellation ends the wait of
pthread_join() with ECANCELED (nxnotify_cancellation(): the join wait
ends also in a system call).  pthread_join() ignored the result: it
returned the old join value with success, and the caller stayed in the
join queue.  The caller then ended (the cancellation point), its TCB was
freed, and the end of the other thread walked the queue into the freed
TCB and posted a semaphore in it.

When the wait fails, take the caller out of the join queue, under the
group mutex that pthread_completejoin() holds, and return the error.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
When a thread ends its process (exit(), _exit() or a signal),
group_kill_children() goes through pthread_cancel() or nxtask_delete() to
nxtask_terminate(), which ends each other thread where it is.  A thread
in a system call can hold locks and references there, and kernel objects
can be on its kernel stack: a request that a device completes, or a
callback that a driver calls.  Nothing gives the locks and references
up, and the driver later writes into the freed stack.  The result is a
kernel panic, a lock that stays held for ever, or a file that is never
closed.

For this forced cancellation, mark the thread instead, while it is in a
system call (TCB_FLAG_SYSCALL), in a new field of the TCB, kcancel.
nxnotify_cancellation() then:

- ends a wait that a signal ends with ECANCELED, so that the call
  returns;
- ends the wait for a mutex of user code with ECANCELED: no signal ends
  a mutex wait, but the holder can have ended with the process
  (pthread_mutex_lock(), or the lock of the environment in getenv());
- lets a wait for a mutex of the kernel go on: its holder gives it up
  when its own system call is over;
- lets a wait that no signal ends complete (TCB_FLAG_UNINTERRUPTIBLE),
  except pthread_join(), which waits only for its own semaphore;
- lets a thread that SIGSTOP stopped in its system call run.

A marked thread does not start a wait that the cancellation ends: the
semaphore, mutex of user code, signal and message queue waits fail at
once with ECANCELED.  A mutex is of user code when it is in the user
address environment (kernel build) or in the user data, bss or heap
(protected build); nxsem_wait_slow() notes it in the TCB while the
thread waits, as the wait can use a kernel mapping of the mutex.  The
mark is not counted once the thread ends (TCB_FLAG_EXIT_PROCESSING): its
end closes files and takes locks.

nxsig_unmask_pendingsignal(), which the architecture calls at the end of
a system call, calls nxtask_kcancel(), which ends the thread there.  It
holds nothing then.  The end is the one of a thread that pthread_cancel()
or nxtask_delete() ends at once, but no cleanup handler runs: the
process ends as by _exit().  The mark is a field of its own because only
the thread itself writes tcb->flags.  The thread also changes kcancel
without the critical section, so a thread that runs on another CPU is
marked only on its CPU, in the SMP call of nxtask_terminate().

A thread that ends by itself (_exit(), pthread_exit()) notes this in
kcancel first.  The end of its process does not mark it and does not end
it: it ends by itself, and its waits there must not end early.  For such
a thread nxtask_terminate() and its SMP call also leave
TCB_FLAG_EXIT_PROCESSING set: the thread can have set it itself, and
nxtask_exithook() needs it.

This needs an architecture that ends a system call in the context of the
thread: ARM64 and RISC-V (dispatch_syscall()) select the new
ARCH_HAVE_SYSCALL_THREAD_RETURN.  The other architectures end a system
call in the exception handler, where the thread cannot end; they keep
the old behaviour, as the flat build does.

pthread_cancel() can block after nxnotify_cancellation() found the thread
outside of a system call and before nxtask_terminate() ends it:
pthread_completejoin() takes the group mutex and allocates memory.  The
other threads run then, and the thread can enter a system call.  So
nxtask_terminate() checks again in its critical section, and its SMP call
on the CPU of the thread checks again there.  For the same reason,
group_kill_children() does not keep a pointer into the list of the
members across a cancellation: a member that it woke can end and leave
the list.  It starts at the head of the list again after each
cancellation, and skips the members that are canceled already.  It
locks the scheduler during the walk, so that a woken thread runs only
when a cancellation blocks.

For the end of the process, pthread_cancel() does not run the cleanup
handlers of the thread (tls_cleanup_popall()) any more: _exit() runs
none.  Also, a thread that runs in a system call on another CPU is not
ended in the call (nxtask_terminate() leaves it to the end of the call).
The handlers that the call pushed, for example tcp_callback_cleanup() in
recv(), must not run then: the call does the same cleanup itself when it
returns.

nxsig_timedwait() took SIG_CANCEL_TIMEOUT only with
CONFIG_CANCELLATION_POINTS; now the end of a process gives it without
that option too, so take it in every config, as nxsig_clockwait() does.
group_kill_children() declares its wait counter only where it reads it.

An asynchronous pthread_cancel() still ends a thread at once, also in a
system call.  A thread that waits for a device that never answers keeps
its process from its end.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
cancellation_points.rst: in the PROTECTED and KERNEL builds on ARM64 and
RISC-V, the end of the process ends a thread that is in a system call
only when the call returns.  Such a thread does not start a wait that a
signal ends, and does not wait for a mutex in the memory of the process.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
@casaroli
casaroli marked this pull request as draft November 29, 2026 08:49
@casaroli
casaroli marked this pull request as ready for review November 29, 2026 08:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area: BINFMT Size: L The size of the change in this PR is large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants