Repository navigation
Conversation
zyfeier
marked this pull request as ready for review
November 12, 2026 08:47
zyfeier
requested review from
Donny9,
GUIDINGLI,
Ouss4,
anchao,
davids5,
fjpanag,
gustavonihei,
hartmannathan,
jerpelea,
masayuki2009,
pkarashchenko,
pussuw,
simbit18,
tmedicci,
xiaoxiang781216,
yamt and
yf13
as code owners
November 12, 2026 08:47
|
GUIDINGLI
approved these changes
Nov 12, 2026
GUIDINGLI
previously approved these changes
Nov 12, 2026
Contributor
|
@zyfeier please rebase your change to the last master which fix the ci issue. |
zyfeier
force-pushed
the
sched-signal-atomic-flags
branch
6 times, most recently
from
November 30, 2026 10:05
e7c6907 to
e631fd4
Compare
zyfeier
force-pushed
the
sched-signal-atomic-flags
branch
from
December 1, 2026 06:24
e631fd4 to
5843e70
Compare
zyfeier
force-pushed
the
sched-signal-atomic-flags
branch
from
December 1, 2026 06:55
5843e70 to
3b7ab8d
Compare
zyfeier
marked this pull request as draft
December 2, 2026 03:38
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, ¶m), or
_SCHED_GETPARAM(0, ¶m) 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
force-pushed
the
sched-signal-atomic-flags
branch
from
December 2, 2026 09:51
3b7ab8d to
4d833a5
Compare
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
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:
sched/tcb: add a reference count to the TCB — the core
mechanism:
nxsched_get_tcb()takes a reference on the target andone on
this_task(),nxsched_put_tcb()drops them; the lastreference posts
exit_semso the terminating task can finishreleasing the TCB.
nxsched_verify_pid()is added for callers thatonly need existence checks.
nxsched_releasepid()is split out ofnxsched_release_tcb(), and the error-recovery paths oftask_init, fork and pthread_create release the pid explicitly.
All in-tree call sites are updated.
sched/backtrace: drop the TCB reference after taking the backtrace.
signal: fix use-after-free of the group signal candidate TCBs —
group_signal()tracks pids instead of TCB pointers across thesearch, and the search's return value no longer leaks the probe
used for the "is waiting for this signal" test.
sched/tcb: do not count a reference of the running task on itself.
exit: move the position of nxsched_releasepid backward.
sched/exit: fix release pid outof critical_section.
sched/signal: do not deliver signals for a thread that is exiting —
queued signal actions are dropped and
nxsig_pendingset()reportsno pending signal for a thread in exit or kill processing: its task
group may already be released (KASAN-reported use-after-free
otherwise).
sched/tcb: park the dying task without a timer — the re-entry
guards in
nxsched_put_tcb(),pthread_exit()and_exit()parkin 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 lockedregion, e.g. ea3131:pgnsh). They now park in
nxsched_park_task(): removed from the ready-to-run list, blockedon the signal wait list, switched away for good.
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 toreach zero before it removes the target; the target parks itself
at its last
nxsched_put_tcb(). The re-entry guards ofpthread_exit()andtask_restart()become set-and-testarbitrations, 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 beingterminated;
child_handler()skips tasks in exit processing.Impact
struct tcb_sgrows (atomic_t refs,atomic_t holds,sem_t exit_sem); internal to the kernel, no user-space ABI change.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..HEADpasses.Runtime, ostest
ostest_main: Exiting with status 0, no assertion inthe log:
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):
One of those cases,
kill_refholder, deletes a sender in the middle of asignal storm, so
task_delete()lands between anxsched_get_tcb()andits
nxsched_put_tcb(): the delete returns in bounded time and thestormed 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.