Repository navigation
Conversation
casaroli
requested review from
Donny9,
GUIDINGLI,
Ouss4,
anchao,
davids5,
hartmannathan,
jerpelea,
pussuw,
xiaoxiang781216 and
yamt
as code owners
November 19, 2026 14:52
|
casaroli
force-pushed
the
fb-exit-syscall-up
branch
from
November 19, 2026 21:16
b90ac5f to
2dbe966
Compare
casaroli
marked this pull request as draft
November 20, 2026 09:52
casaroli
marked this pull request as ready for review
November 20, 2026 09:52
casaroli
force-pushed
the
fb-exit-syscall-up
branch
from
November 25, 2026 12:09
2dbe966 to
f909a87
Compare
casaroli
marked this pull request as draft
November 26, 2026 14:01
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>
casaroli
force-pushed
the
fb-exit-syscall-up
branch
from
November 27, 2026 10:30
f909a87 to
557b5dc
Compare
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
force-pushed
the
fb-exit-syscall-up
branch
from
November 28, 2026 09:06
557b5dc to
7e9fd78
Compare
casaroli
marked this pull request as draft
November 29, 2026 08:49
casaroli
marked this pull request as ready for review
November 29, 2026 08:49
GUIDINGLI
approved these changes
Dec 1, 2026
jerpelea
approved these changes
Dec 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When a thread ends its process (
exit(),_exit()or a fatal signal),group_kill_children()cancels the other threads, andnxtask_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 defaultCONFIG_CANCELLATION_POINTS=nthis 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:
libs/libc: Check the lock of the task information.The kernel copy of libc takesta_lock(getenv()for$PWDin the inode search,getcwd(),lib_getfullpath(),env_dup(),env_sanitize_secure(), thesetenv()family,pthread_atfork(),fork()). Most callers ignored the result ofnxrmutex_lock(), and then unlocked a lock that they did not hold. Now each caller checks it. With commit 3 the lock fails withECANCELEDfor a thread that its process end canceled; a relative path lookup then fails instead of using the home directory.sched/pthread: Leave the join queue when pthread_join() is canceled.A cancellation ends the wait ofpthread_join()withECANCELED(today withCONFIG_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 andpthread_join()returns the error.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 withECANCELED. 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 afternxnotify_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, andnxtask_terminate()and its SMP call leave itsTCB_FLAG_EXIT_PROCESSINGset, which the thread can have set itself and whichnxtask_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 ofrecv()oraccept()).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 newCONFIG_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 setTCB_FLAG_SYSCALL(see the note inx86_64_syscall()), so it keeps the old behaviour too.Impact
PROTECTED and KERNEL builds on ARM64 and RISC-V:
_exit()). The exit status of the process does not change.nxsig_timedwait()takes a canceled wait (SIG_CANCEL_TIMEOUT) also withoutCONFIG_CANCELLATION_POINTS.pthread_cancel()still ends a thread at once.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:
getenv()returns NULL witherrno,setenv()andfork()return -1.env_sanitize_secure()returnsintnow (internal; one caller,exec_module()).pthread_join()returnsECANCELEDwhen a cancellation ended its wait, instead of 0 with an old exit value.Testing
Test programs (standalone, from
/system/binover 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 sendsSIGKILL(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(UDPrecv()),tty(ptyread()),join(pthread_join()of a thread inpause()),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 callspthread_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 inepoll_wait(),poll()oraccept()(MODE), and the main thread calls_exit().qemu-armv8a:knsh, 1 CPU, master 3e66f0a vs this PR:
mm_granfree.c:69assertion (page pool)* "kill" runs report "wrong status" in every round on master and with this PR:
waitpid()gives exit status 0 for a child thatSIGKILLended. Not changed by this PR.The "join kill" and "mutex kill" hangs are the same on master:
SIGKILLof 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 inread()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: allexitandtexitcases PASS with pool +0, exceptvfork, which corrupts the user heap of the child on master and with this PR alike (mm_extend.c:91).tmpfilein 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 infs/v9fswithout it (a fid used after it is freed), also with no end of a process; with it,tmpfilein the 9p root passes in all three modes.On 4 CPUs the
killmode oftmpfilein 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 theSIGKILLpath on SMP a thread can still end inside a system call. Not analyzed further. Theexitandtexitmodes do not show it.exitraceon 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 CPUexitraceis too slow to be useful: its threads wait in busy loops.)With
CONFIG_DEBUG_ASSERTIONS,exitraceon 4 CPUs: 3 x 1000 rounds, no assertion (the lost update oftcb->flagsfrom another CPU is gone since #21804).tlsraceon 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 withepoll_wait()andaccept()before round 100; this PR: 3 x 300 and 3 x 1000 rounds PASS, andexitrace,sysexit(exit and texit) andptyintrPASS on the same image. With the defaultCONFIG_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
exitPASS for mutex, pipe, semwait and join (master: pipe hangs). Thekillmode 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 withCANCELLATION_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 withCANCELLATION_POINTS,SMP,ENABLE_PARTIAL_SIGNALS, withoutMM_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 appstesting/ostest/intstack.con 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
-Werroron 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 -gpasses. Documentation: commit 4.Not in this PR