Skip to content

sched/tcb: add a reference count to the TCB to prevent it from being deleted - #21774

Draft
zyfeier wants to merge 15 commits into
apache:masterfrom
zyfeier:sched-signal-atomic-flags
Draft

zyfeier wants to merge 15 commits into
apache:masterfrom
zyfeier:sched-signal-atomic-flags

Conversation

@zyfeier

@zyfeier zyfeier commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Gives the TCB a reference count so a TCB obtained through
nxsched_get_tcb() cannot be freed while the caller still uses it,
and closes the teardown races around a task that is terminated while
it holds references on other tasks.

Nine commits:

  1. sched/tcb: add a reference count to the TCB — the core
    mechanism: nxsched_get_tcb() takes a reference on the target and
    one on this_task(), nxsched_put_tcb() drops them; the last
    reference posts exit_sem so the terminating task can finish
    releasing the TCB. nxsched_verify_pid() is added for callers that
    only need existence checks. nxsched_releasepid() is split out of
    nxsched_release_tcb(), and the error-recovery paths of
    task_init, fork and pthread_create release the pid explicitly.
    All in-tree call sites are updated.

  2. sched/backtrace: drop the TCB reference after taking the backtrace.

  3. signal: fix use-after-free of the group signal candidate TCBs —
    group_signal() tracks pids instead of TCB pointers across the
    search, and the search's return value no longer leaks the probe
    used for the "is waiting for this signal" test.

  4. sched/tcb: do not count a reference of the running task on itself.

  5. exit: move the position of nxsched_releasepid backward.

  6. sched/exit: fix release pid outof critical_section.

  7. sched/signal: do not deliver signals for a thread that is exiting —
    queued signal actions are dropped and nxsig_pendingset() reports
    no pending signal for a thread in exit or kill processing: its task
    group may already be released (KASAN-reported use-after-free
    otherwise).

  8. sched/tcb: park the dying task without a timer — the re-entry
    guards in nxsched_put_tcb(), pthread_exit() and _exit() park
    in an infinite usleep(1000) loop, which pulls the nanosleep,
    watchdog and timer family into the paging-locked text through
    nxsched_foreach() (~1.6K overflow on boards with a small locked
    region, e.g. ea3131:pgnsh). They now park in
    nxsched_park_task(): removed from the ready-to-run list, blocked
    on the signal wait list, switched away for good.

  9. sched/tcb: let a killed task drop its TCB references before removal —
    the references a task holds on other tasks are counted in a new
    tcb->holds. nxtask_terminate() waits for the target's holds to
    reach zero before it removes the target; the target parks itself
    at its last nxsched_put_tcb(). The re-entry guards of
    pthread_exit() and task_restart() become set-and-test
    arbitrations, so a terminate() that won the same window is the one
    that tears the task down. task_restart() waits the same way,
    marked with EXIT_PROCESSING only: a restarted task must keep
    running until it is reset. A stopped target is woken before the
    wait; nxsched_suspend() no longer stops a task being
    terminated; child_handler() skips tasks in exit processing.

Impact

  • New feature? No, robustness fix.
  • ABI: struct tcb_s grows (atomic_t refs, atomic_t holds,
    sem_t exit_sem); internal to the kernel, no user-space ABI change.
  • Security: fixes use-after-free windows on task teardown.

Testing

Host: Ubuntu x86_64, CI image ghcr.io/apache/nuttx/apache-nuttx-ci-linux,
master 4360319. tools/checkpatch.sh -c -u -m -g master..HEAD passes.

Runtime, ostest ostest_main: Exiting with status 0, no assertion in
the log:

Configuration Covers
sim:ostest full run, zero assertions
qemu-armv8a:nsh_smp (4 CPUs) ARM64 + SMP; the smp test (8 threads, two rounds) ends with result=0 for every thread

Exit-path cmocka suite (15 cases: exit() with live siblings, SIGKILL,
task_delete, pthread_cancel, waitpid, the order of closing files versus
notifying the parent), each case run separately on this tree and on
master — identical verdicts on both trees, i.e. no regression; the cases
that fail or hang do so identically on master (known exit-path issues,
to be fixed separately):

Legs Result
sim UP (nsh + suite config) 15/15 identical
sim SMP (nsh + suite + SMP) 15/15 identical

One of those cases, kill_refholder, deletes a sender in the middle of a
signal storm, so task_delete() lands between a nxsched_get_tcb() and
its nxsched_put_tcb(): the delete returns in bounded time and the
stormed task still exits afterwards, i.e. a killed holder does not leak
its references.

Build (CI image): smartl-c906:knsh (kernel build, symbol resolution)
and stm32l476vg-disco:knsh (small-memory canary) link cleanly.

@zyfeier
zyfeier marked this pull request as ready for review November 12, 2026 08:47
@github-actions github-actions Bot added Arch: arm Issues related to ARM (32-bit) architecture Arch: arm64 Issues related to ARM64 (64-bit) architecture Arch: risc-v Issues related to the RISC-V (32-bit or 64-bit) architecture Arch: x86_64 Issues related to the x86_64 architecture Area: Drivers Drivers issues Size: L The size of the change in this PR is large labels Nov 12, 2026
@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

arduino-mega2560

  • flash: .text +4,952 B (+7.2%, 73,834 B / 262,144 B, total: 28% used)
  • sram: .bss +16 B (+0.6%, 2,837 B / 8,192 B, total: 35% used)

esp32-devkitc

  • ROM: .flash.text +1,156 B (+0.9%, 136,144 B / 4,194,272 B, total: 3% used)
  • dram0_0_seg: .dram0.bss +16 B (+0.2%, 10,488 B / 180,736 B, total: 6% used)
  • irom0_0_seg: .flash.text +1,156 B (+1.1%, 101,796 B / 3,342,304 B, total: 3% used)

hifive1-revb

  • flash: .text +1,088 B (+1.3%, 87,848 B / 4,194,304 B, total: 2% used)
  • sram: .bss +32 B (+0.8%, 3,892 B / 16,384 B, total: 24% used)

mirtoo

  • kseg0_progmem: .text +800 B (+1.3%, 64,556 B / 131,072 B, total: 49% used)
  • kseg1_datamem: .bss +16 B (+0.6%, 2,708 B / 32,256 B, total: 8% used)

mps2-an500-citest

  • flash: .text +1,496 B (+0.6%, 255,996 B / 4,194,304 B, total: 6% used)
  • sram1: .bss +16 B (+0.1%, 16,488 B / 16,777,216 B, total: 0% used)

mps2-an500-citest-protected

  • flash: .text +1,576 B (+1.3%, 124,168 B / 4,194,304 B, total: 3% used)
  • sram1: .bss +16 B (+0.2%, 8,536 B / 16,777,216 B, total: 0% used)

qemu-armv7a-citest

  • ROM: .data +32 B, .init_section +2,232 B, .text +1,864 B (+0.7%, 566,672 B / 1,048,576 B, total: 54% used)

qemu-armv7a-citest-knsh

  • ROM: .init_section +2,760 B, .text +1,336 B (+2.5%, 169,368 B / 1,048,576 B, total: 16% used)

qemu-armv8a

  • Code: .rodata +64 B, .text._assert +8 B, .text._exit +52 B, .text.arm64_fatal_handler +12 B, .text.child_handler +8 B, .text.dump_task +4 B, .text.group_cancel_children_handler +16 B, .text.group_signal +32 B, .text.group_signal_handler +20 B, .text.load_module -12 B, .text.mm_memdump +24 B, .text.nx_pthread_create +28 B, .text.nx_pthread_exit +44 B, .text.nx_start +32 B, .text.nxsched_get_param -12 B, .text.nxsched_get_scheduler +12 B, .text.nxsched_get_stackinfo +36 B, .text.nxsched_get_tcb +88 B, .text.nxsched_reaped +12 B, .text.nxsched_release_tcb -4 B, .text.nxsched_releasepid +104 B, .text.nxsched_set_param +36 B, .text.nxsem_wait_slow +12 B, .text.nxsig_deliver +64 B, .text.nxsig_dispatch +24 B, .text.nxsig_event_valid +16 B, .text.nxsig_kill_target +20 B, .text.nxsig_pendingset +32 B, .text.nxsig_source_queued +12 B, .text.nxsig_tgkill +8 B, .text.nxtask_delete +40 B, .text.nxtask_init +28 B, .text.nxtask_setup_fork +60 B, .text.nxtask_terminate +36 B, .text.nxtask_uninit +12 B, .text.nxthread_setup_scheduler +12 B, .text.posix_spawnattr_init -16 B, .text.proc_open -12 B, .text.proc_opendir -20 B, .text.proc_read +20 B, .text.proc_stat -28 B, .text.proc_write +4 B, .text.procfs_readdir +16 B, .text.pthread_cancel +24 B, .text.pthread_completejoin +8 B, .text.pthread_detach +12 B, .text.pthread_join +44 B, .text.spawn_execattrs -4 B, .text.sync +32 B, .text.task_getgroup +12 B, .text.task_restart +108 B, .text.task_spawn -16 B, .text.timer_gethandle +8 B, .text.work_queue_priority_wq +8 B (+0.5%, 389,392 B)
  • Data: .bss.g_idletcb +32 B (+0.0%, 78,553 B)

qemu-intel64

  • Code: .text +2,382 B (+0.0%, 8,713,568 B)
  • Data: .rodata +160 B (+0.1%, 110,057 B)

rx65n-rsk2mb

  • RAM: .bss +32 B (+0.5%, 7,092 B / 262,144 B, total: 3% used)
  • ROM: .text +928 B (+1.0%, 95,952 B / 2,097,152 B, total: 5% used)

s698pm-dkit

  • Code: .text +3,568 B (+0.9%, 420,256 B)
  • Data: .bss +32 B (+0.3%, 12,288 B)

stm32-nucleo-f103rb

  • flash: .text +612 B (+1.8%, 35,176 B / 131,072 B, total: 27% used)
  • sram: .bss +16 B (+0.6%, 2,588 B / 20,480 B, total: 13% used)

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

Comment thread sched/group/group_killchildren.c Resolved
GUIDINGLI
GUIDINGLI previously approved these changes Nov 12, 2026
@xiaoxiang781216

Copy link
Copy Markdown
Contributor

@zyfeier please rebase your change to the last master which fix the ci issue.

Comment thread sched/misc/deadlock.c Resolved
Comment thread sched/pthread/pthread_exit.c Resolved
@zyfeier
zyfeier force-pushed the sched-signal-atomic-flags branch 6 times, most recently from e7c6907 to e631fd4 Compare November 30, 2026 10:05
@zyfeier
zyfeier force-pushed the sched-signal-atomic-flags branch from e631fd4 to 5843e70 Compare December 1, 2026 06:24
@github-actions github-actions Bot added Size: L The size of the change in this PR is large and removed Size: XL The size of the change in this PR is very large. Consider breaking down the PR into smaller pieces. labels Dec 1, 2026
@zyfeier
zyfeier force-pushed the sched-signal-atomic-flags branch from 5843e70 to 3b7ab8d Compare December 1, 2026 06:55
@zyfeier
zyfeier marked this pull request as draft December 2, 2026 03:38
zyfeier and others added 15 commits December 2, 2026 17:34
nucleo-g431rb:cansock, b-g431b-esc1:cansock and lx_cpu:nsh have less
than 1 KB of free flash, so a change of ordinary size in a core
component, such as the TCB reference count, pushes them over the
limit.

They cannot use DEFAULT_SMALL, which also drops features these
images use, so disable only the three options it would turn off for
code size: MM_INLINE_ADDFREECHUNK, SCHED_INLINE_ADDPRIORITIZED and
LIBC_INLINE_QUEUE.  Each function is then emitted once instead of in
every caller.  This frees about 820 bytes on the stm32g4 boards and
about 1.5 KB on lx_cpu.

Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
…deleted

Holding a big lock around the TCB is often only needed to keep the TCB
alive across a call that may release the task; replacing those big
locks with smaller ones would risk lock recursion.  Instead, let
nxsched_get_tcb() take a reference on the TCB it returns, and add
nxsched_put_tcb() to drop it, so a TCB pointer stays valid for as long
as the reference is held.

Take the reference wherever code keeps a TCB pointer across a blocking
operation (signal delivery, timers, work queues, pthread join, child
reaping, etc.), and split nxsched_releasepid() out of
nxsched_release_tcb() so the pid hash entry and the TCB can be released
independently.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
sched_backtrace_handler() dropped its reference on the TCB before
calling up_backtrace() on it, so the task could exit and its TCB be
freed while its stack was being walked.  Drop the reference after the
backtrace instead.

Signed-off-by: wangzhi16 <wangzhi16@xiaomi.com>
group_signal_handler() stored the candidate TCB pointers (default,
unblocked, awakened, dispatched) in the caller's info struct across
group_foreachchild() iterations.  Each iteration drops its TCB
reference at the exit, so the stored pointers dangle once the
iteration that filled them returns, and group_signal() dereferences
them after the loop.

Store PIDs instead of TCB pointers in struct group_signal_s and
re-resolve the chosen pid through nxsched_get_tcb() after the loop,
so the dispatch operates on a freshly referenced TCB.

Signed-off-by: huojianchao <huojianchao@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
nxsched_get_tcb() took a reference on the TCB it returned and one more
on this_task(), and nxsched_release_pid() waits until all references of
the exiting task are dropped.  When a task looks up its own TCB and then
exits before the matching nxsched_put_tcb(), for example from a signal
handler that calls _exit() while group_signal() still holds the TCB of
the task, the references are never dropped and the task sleeps forever
in nxsched_release_pid().

The running task cannot be freed under itself, so do not count a
reference when the TCB is the running task, in nxsched_get_tcb() and in
nxsched_put_tcb().

Signed-off-by: hujun5 <hujun5@xiaomi.com>
nxtask_exithook() takes mutexes, and nxmutex_lock() looks up the
holder with nxsched_get_tcb().  _exit() and pthread_exit() released the
pid before calling it, so that lookup no longer found the exiting task.
Release the pid after nxtask_exithook() instead.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
When thread is pthread_exit(), and other thread do pthread_cancel,
nxtask_terminate -> release_pid ->
                     pthread_exit -> pthread_completejoin
                       -> process exit because self pid not in pidhash
Cause try cancel the exiting thread lead to task abnormal exit.

Also, we should keep nxtask_exithook before release pid align with the
behavior in nx_pthread_exit.

Signed-off-by: buxiasen <buxiasen@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
nxtask_exithook() releases the task group in group_leave() and only then
blocks in nxsched_release_pid(), while the thread itself remains resumable
until up_exit(). A signal armed for such a thread is then delivered after
the group is gone: the signal trampoline re-enters nxsig_deliver() and the
delivery path dereferences the released group through rtcb->group, which
KASAN reports as a write use-after-free.

Drop queued signal actions instead of delivering them once the thread is
in exit or kill processing, mirroring the check nxsig_tcbdispatch()
already performs, and report no pending signal from nxsig_pendingset()
for such a thread.

Signed-off-by: anpeiyun <anpeiyun@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
A task killed between nxsched_get_tcb() and nxsched_put_tcb() never
ran its put again: the killer waited forever in nxsched_releasepid()
and the TCB the target referenced was never released.

Count the references a task holds on others in a new tcb->holds.
nxtask_terminate() waits for holds to reach zero before it removes
the target; the target drops its last hold in nxsched_put_tcb(),
sees the flag and stops itself there.  The re-entry guard of
task_restart() becomes a set-and-test arbitration, so a terminate()
that won the same window is the one that tears the task down.

task_restart() waits the same way before it resets a task, marked
with EXIT_PROCESSING only: a restarted task must keep running until
it is reset (a reference taken between the wait and the removal is
lost with the discarded context: a known limitation).  A stopped
target is woken before the wait, nxsched_suspend() no longer stops
a task being terminated, and child_handler() skips tasks whose task
group may already be released.

Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
A task that discovers it is already inside a termination flow (the
re-entry guards in nxsched_put_tcb(), pthread_exit() and exit()) parks
itself in an infinite usleep(1000) loop.  That pulls the whole
nanosleep, watchdog and timer family into the paging-locked text
section through nxsched_foreach() (a locked resident caller of
put_tcb), overflowing the locked section by ~1.6K on boards with a
small locked region, e.g. ea3131:pgnsh.

Extract nxsched_park_task() and park the way nxsig_clockwait() does,
minus the timer: remove ourselves from the ready-to-run list, block on
the signal wait list via nxsched_add_blocked() and switch away for
good.  The termination path already handles a task blocked in
TSTATE_WAIT_SIG (that is exactly the state the usleep version ended up
in via nxsig_clockwait), so no changes are needed on the killer side;
the exit-time wd_cancel() simply becomes a no-op because the watchdog
was never armed.

Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
sched_backtrace_handler() and nxsched_get_affinity() entered the
critical section only to keep the TCB they looked up from being
freed while they used it.  nxsched_get_tcb() now holds a reference
on the TCB until nxsched_put_tcb(), so the critical section is no
longer needed there.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
Several paths entered the critical section only to keep a TCB alive
while they used it, or around work that is already protected:

  - nxsched_get_param() (for another task) and task_reparent()
    (without group members) hold a reference on every TCB they use.
  - lpwork_boostpriority() and lpwork_restorepriority() only need to
    keep the worker threads from running before all priorities are
    set, which sched_lock() gives.
  - nxsched_set_scheduler() already holds sched_lock() and the TCB
    reference around the policy update.
  - sched_lock() updates only the state of the running task.
  - irq_callback() takes a snapshot of counters for procfs, where a
    torn read is harmless.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
The scheduling policy applied by POSIX_SPAWN_SETSCHEDULER can only
differ from SCHED_FIFO when round-robin or sporadic scheduling is
configured.  On builds that support neither (CONFIG_RR_INTERVAL == 0
and CONFIG_SCHED_SPORADIC disabled), every task uses SCHED_FIFO and
the SETSCHEDULER handling in spawn_execattrs() is dead code.

Guard that handling with 'CONFIG_RR_INTERVAL > 0 ||
defined(CONFIG_SCHED_SPORADIC)'.  On FIFO-only builds this removes the
only static reference to nxsched_set_scheduler() from posix_spawn(),
allowing the linker to garbage-collect it.  POSIX_SPAWN_SETSCHEDPARAM
(priority) is unaffected and still honored.

The POSIX_SPAWN_SETSCHEDULER macro itself remains defined, so callers
continue to compile unchanged; only the no-op handling is dropped.
The matching report in posix_spawnattr_dump() is guarded by the same
condition.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
spawn_execattrs() took a pid and looked up the TCB again with
nxsched_get_tcb()/nxsched_put_tcb() for the signal mask and the new
session, and applied the priority through nxsched_set_param(pid, ...).
Both callers, exec_module() and nxtask_spawn_create(), already hold the
TCB of the new task, so the lookups and the reference count round
trips are redundant.

Change the prototype to take the TCB:

  - The signal mask and the session IDs are written to the TCB and
    its group directly.
  - Without sporadic scheduling, the priority-only path calls
    nxsched_set_priority(tcb, ...) instead of looking the pid up
    again; the sporadic path still uses nxsched_set_param().
  - pid is taken once from tcb->pid for the remaining logging and
    scheduler policy calls.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
Several spawn and exec paths called nxsched_get_param(0, &param), or
_SCHED_GETPARAM(0, &param) in libc, only to get the priority of the
calling task.  That fills a whole struct sched_param and has its own
error handling, while these callers need only the sched_priority of
the current TCB.

Read it from the TCB instead:

  - load_default_priority() takes the priority from nxsched_self().
  - nxtask_spawn_exec() takes it from this_task() for both the default
    attributes and a zero priority in the given attributes.
  - posix_spawnattr_init() still needs _SCHED_GETPARAM to copy the
    sporadic scheduling fields, so the local struct sched_param and the
    call are built only with CONFIG_SCHED_SPORADIC.

No functional change.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
@zyfeier
zyfeier force-pushed the sched-signal-atomic-flags branch from 3b7ab8d to 4d833a5 Compare December 2, 2026 09:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Arch: arm Issues related to ARM (32-bit) architecture Arch: arm64 Issues related to ARM64 (64-bit) architecture Arch: risc-v Issues related to the RISC-V (32-bit or 64-bit) architecture Arch: x86_64 Issues related to the x86_64 architecture Area: BINFMT Board: arm Size: XL The size of the change in this PR is very large. Consider breaking down the PR into smaller pieces.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants