From d0529b49d3f4264da6627d1e6bd30cfebc742385 Mon Sep 17 00:00:00 2001 From: zhangyuan29 Date: Wed, 2 Dec 2026 16:24:37 +0800 Subject: [PATCH 01/15] boards: build three hot paths out of line on small flash configs 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 --- boards/arm/lpc17xx_40xx/lx_cpu/configs/nsh/defconfig | 3 +++ boards/arm/stm32g4/b-g431b-esc1/configs/cansock/defconfig | 3 +++ boards/arm/stm32g4/nucleo-g431rb/configs/cansock/defconfig | 3 +++ 3 files changed, 9 insertions(+) diff --git a/boards/arm/lpc17xx_40xx/lx_cpu/configs/nsh/defconfig b/boards/arm/lpc17xx_40xx/lx_cpu/configs/nsh/defconfig index 4a00424e79aea..3ba6eeca8fa8a 100644 --- a/boards/arm/lpc17xx_40xx/lx_cpu/configs/nsh/defconfig +++ b/boards/arm/lpc17xx_40xx/lx_cpu/configs/nsh/defconfig @@ -6,7 +6,10 @@ # modifications. # # CONFIG_EXAMPLES_ELF_FSMOUNT is not set +# CONFIG_LIBC_INLINE_QUEUE is not set +# CONFIG_MM_INLINE_ADDFREECHUNK is not set # CONFIG_NSH_DISABLE_SHUTDOWN is not set +# CONFIG_SCHED_INLINE_ADDPRIORITIZED is not set # CONFIG_SPI_EXCHANGE is not set CONFIG_ALLOW_BSD_COMPONENTS=y CONFIG_ARCH="arm" diff --git a/boards/arm/stm32g4/b-g431b-esc1/configs/cansock/defconfig b/boards/arm/stm32g4/b-g431b-esc1/configs/cansock/defconfig index e50bc8b0757c2..e6c76d1cc7882 100644 --- a/boards/arm/stm32g4/b-g431b-esc1/configs/cansock/defconfig +++ b/boards/arm/stm32g4/b-g431b-esc1/configs/cansock/defconfig @@ -5,8 +5,11 @@ # You can then do "make savedefconfig" to generate a new defconfig file that includes your # modifications. # +# CONFIG_LIBC_INLINE_QUEUE is not set +# CONFIG_MM_INLINE_ADDFREECHUNK is not set # CONFIG_NET_ETHERNET is not set # CONFIG_NET_IPv4 is not set +# CONFIG_SCHED_INLINE_ADDPRIORITIZED is not set # CONFIG_SYSTEM_DD is not set # CONFIG_TLS_EMUTLS is not set CONFIG_ALLOW_BSD_COMPONENTS=y diff --git a/boards/arm/stm32g4/nucleo-g431rb/configs/cansock/defconfig b/boards/arm/stm32g4/nucleo-g431rb/configs/cansock/defconfig index 26ea0807d5cf5..e08eda03db6f2 100644 --- a/boards/arm/stm32g4/nucleo-g431rb/configs/cansock/defconfig +++ b/boards/arm/stm32g4/nucleo-g431rb/configs/cansock/defconfig @@ -5,8 +5,11 @@ # You can then do "make savedefconfig" to generate a new defconfig file that includes your # modifications. # +# CONFIG_LIBC_INLINE_QUEUE is not set +# CONFIG_MM_INLINE_ADDFREECHUNK is not set # CONFIG_NET_ETHERNET is not set # CONFIG_NET_IPv4 is not set +# CONFIG_SCHED_INLINE_ADDPRIORITIZED is not set # CONFIG_SYSTEM_DD is not set # CONFIG_TLS_EMUTLS is not set CONFIG_ALLOW_BSD_COMPONENTS=y From b6573bb38ed8d59f39c53793bb66710720eecb8e Mon Sep 17 00:00:00 2001 From: hujun5 Date: Wed, 18 Nov 2026 17:45:02 +0800 Subject: [PATCH 02/15] sched/tcb: add a reference count to the TCB to prevent it from being 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 Signed-off-by: zhangyuan29 --- arch/arm/src/arm_a_r/arm_userfault.c | 2 + arch/arm64/src/common/arm64_fatal.c | 2 + arch/risc-v/src/common/riscv_exception.c | 2 + .../src/gd32vw55x/gdwifi/wrapper_nuttx.c | 4 +- arch/x86_64/src/intel64/intel64_irq.c | 2 + drivers/note/note_driver.c | 1 + fs/inode/inode.h | 2 +- fs/procfs/fs_procfs.c | 8 +- fs/procfs/fs_procfsproc.c | 38 ++++---- fs/vfs/fs_sync.c | 3 +- include/nuttx/sched.h | 31 +++++++ libs/libc/gdbstub/lib_gdbstub.c | 5 + mm/mm_heap/mm_memdump.c | 2 + mm/tlsf/mm_tlsf.c | 2 + sched/clock/clock_gettime.c | 7 +- sched/group/group_continue.c | 2 + sched/group/group_killchildren.c | 2 + sched/group/group_signal.c | 21 +++-- sched/group/group_suspendchildren.c | 1 + sched/init/nx_start.c | 2 + sched/misc/assert.c | 9 +- sched/misc/coredump.c | 1 + sched/misc/deadlock.c | 6 +- sched/paging/pg_miss.c | 2 + sched/paging/pg_worker.c | 2 + sched/pthread/pthread_cancel.c | 6 ++ sched/pthread/pthread_completejoin.c | 2 + sched/pthread/pthread_create.c | 11 +++ sched/pthread/pthread_detach.c | 2 + sched/pthread/pthread_exit.c | 23 +++++ sched/pthread/pthread_join.c | 6 ++ sched/sched/sched.h | 13 ++- sched/sched/sched_backtrace.c | 17 +++- sched/sched/sched_foreach.c | 6 +- sched/sched/sched_get_stackinfo.c | 11 ++- sched/sched/sched_getaffinity.c | 5 + sched/sched/sched_getparam.c | 1 + sched/sched/sched_getscheduler.c | 5 + sched/sched/sched_gettcb.c | 91 ++++++++++++++++--- sched/sched/sched_maycontrol.c | 6 +- sched/sched/sched_releasetcb.c | 24 ++--- sched/sched/sched_roundrobin.c | 2 + sched/sched/sched_rrgetinterval.c | 8 +- sched/sched/sched_setaffinity.c | 4 + sched/sched/sched_setparam.c | 5 + sched/sched/sched_setscheduler.c | 5 + sched/sched/sched_suspend.c | 2 + sched/sched/sched_verifytcb.c | 47 +++------- sched/sched/sched_waitid.c | 19 +++- sched/sched/sched_waitpid.c | 11 ++- sched/semaphore/sem_wait.c | 2 + sched/signal/sig_dispatch.c | 7 ++ sched/signal/sig_kill.c | 14 ++- sched/signal/sig_notification.c | 4 + sched/signal/sig_tgkill.c | 5 +- sched/task/task_delete.c | 5 + sched/task/task_exithook.c | 1 + sched/task/task_fork.c | 29 +++++- sched/task/task_getgroup.c | 6 +- sched/task/task_init.c | 13 +++ sched/task/task_prctl.c | 16 ++++ sched/task/task_reparent.c | 12 ++- sched/task/task_restart.c | 14 ++- sched/task/task_setup.c | 1 + sched/task/task_spawnparms.c | 3 + sched/task/task_terminate.c | 38 ++++---- sched/timer/timer_create.c | 2 +- sched/timer/timer_initialize.c | 3 + sched/wqueue/kwork_inherit.c | 6 ++ sched/wqueue/kwork_thread.c | 6 +- 70 files changed, 530 insertions(+), 148 deletions(-) diff --git a/arch/arm/src/arm_a_r/arm_userfault.c b/arch/arm/src/arm_a_r/arm_userfault.c index 0c3b15974d5f7..e3cbe6e1f0caa 100644 --- a/arch/arm/src/arm_a_r/arm_userfault.c +++ b/arch/arm/src/arm_a_r/arm_userfault.c @@ -76,6 +76,8 @@ bool arm_fault_kill(uint32_t *regs) ptcb != NULL ? get_task_name(ptcb) : "", tcb->pid, get_task_name(tcb)); + nxsched_put_tcb(ptcb); + atomic_or(&tcb->shared_flags, TCB_FLAG_FORCED_CANCEL); regs[REG_PC] = (uint32_t)_exit; diff --git a/arch/arm64/src/common/arm64_fatal.c b/arch/arm64/src/common/arm64_fatal.c index a16fe15100f1d..5918f0c16a13a 100644 --- a/arch/arm64/src/common/arm64_fatal.c +++ b/arch/arm64/src/common/arm64_fatal.c @@ -682,6 +682,8 @@ uint64_t *arm64_fatal_handler(uint64_t *regs) tcb->pid, get_task_name(tcb)); _alert("Reason: %s - %s\n", reason, desc); + nxsched_put_tcb(ptcb); + atomic_or(&tcb->shared_flags, TCB_FLAG_FORCED_CANCEL); regs[REG_ELR] = (uint64_t)_exit; diff --git a/arch/risc-v/src/common/riscv_exception.c b/arch/risc-v/src/common/riscv_exception.c index 32580a02173b7..a722fc4c7e982 100644 --- a/arch/risc-v/src/common/riscv_exception.c +++ b/arch/risc-v/src/common/riscv_exception.c @@ -119,6 +119,8 @@ static void riscv_fault_handler(uintreg_t cause, void *regs) _alert("Segmentation fault in %s (PID %d: %s)\n", get_task_name(ptcb), tcb->pid, get_task_name(tcb)); + nxsched_put_tcb(ptcb); + #ifdef CONFIG_SCHED_BACKTRACE sched_dumpstack(tcb->pid); #endif diff --git a/arch/risc-v/src/gd32vw55x/gdwifi/wrapper_nuttx.c b/arch/risc-v/src/gd32vw55x/gdwifi/wrapper_nuttx.c index 8382f51730a44..e336645d66d6c 100644 --- a/arch/risc-v/src/gd32vw55x/gdwifi/wrapper_nuttx.c +++ b/arch/risc-v/src/gd32vw55x/gdwifi/wrapper_nuttx.c @@ -586,8 +586,10 @@ char *sys_task_name_get(void *task) #if CONFIG_TASK_NAME_SIZE > 0 struct tcb_s *tcb = nxsched_get_tcb(task == NULL ? nxsched_gettid() : (pid_t)(uintptr_t)task - 1); + char *name = tcb ? tcb->name : NULL; - return tcb ? tcb->name : NULL; + nxsched_put_tcb(tcb); + return name; #else return NULL; #endif diff --git a/arch/x86_64/src/intel64/intel64_irq.c b/arch/x86_64/src/intel64/intel64_irq.c index f45b7c260b206..20e51a58121bc 100644 --- a/arch/x86_64/src/intel64/intel64_irq.c +++ b/arch/x86_64/src/intel64/intel64_irq.c @@ -557,6 +557,8 @@ static int x86_64_fault_user_isr(int irq, void *c, void *arg) ptcb != NULL ? get_task_name(ptcb) : "", tcb->pid, get_task_name(tcb)); + nxsched_put_tcb(ptcb); + /* Only a page fault sets CR2; for the others it is stale */ if (irq == ISR14) diff --git a/drivers/note/note_driver.c b/drivers/note/note_driver.c index 304ad875bbd06..bd29a15c81815 100644 --- a/drivers/note/note_driver.c +++ b/drivers/note/note_driver.c @@ -2206,6 +2206,7 @@ FAR char *note_get_taskname(pid_t pid, FAR char *buf, size_t len) if (tcb != NULL) { strlcpy(buf, tcb->name, len); + nxsched_put_tcb(tcb); return buf; } diff --git a/fs/inode/inode.h b/fs/inode/inode.h index e115d6e7ca328..50dd87b110fd1 100644 --- a/fs/inode/inode.h +++ b/fs/inode/inode.h @@ -50,7 +50,7 @@ # define FS_ADD_BACKTRACE(fd) \ do \ { \ - FAR struct tcb_s *tcb = nxsched_get_tcb(nxsched_gettid()); \ + FAR struct tcb_s *tcb = this_task(); \ if (tcb != NULL && tcb->group != NULL && \ (tcb->group->tg_flags & GROUP_FLAG_FD_BACKTRACE) != 0) \ { \ diff --git a/fs/procfs/fs_procfs.c b/fs/procfs/fs_procfs.c index 739929e06f1b2..14e5b0cdb530a 100644 --- a/fs/procfs/fs_procfs.c +++ b/fs/procfs/fs_procfs.c @@ -941,7 +941,7 @@ static int procfs_readdir(FAR struct inode *mountpt, */ while (priv->index < priv->nentries && - (nxsched_get_tcb(level0->pid[priv->index]) == NULL || + (!nxsched_verify_pid(level0->pid[priv->index]) || nxsig_kill_target(level0->pid[priv->index]) < 0)) { priv->index++; @@ -1050,6 +1050,12 @@ static int procfs_readdir(FAR struct inode *mountpt, pid_t pid = level0->pid[index]; + if (!nxsched_verify_pid(pid)) + { + ferr("ERROR: PID %d is no longer valid\n", pid); + return -ENOENT; + } + /* Save the filename=pid and file type=directory */ entry->d_type = DTYPE_DIRECTORY; diff --git a/fs/procfs/fs_procfsproc.c b/fs/procfs/fs_procfsproc.c index 50d4e1cefea0b..e463a32a0612b 100644 --- a/fs/procfs/fs_procfsproc.c +++ b/fs/procfs/fs_procfsproc.c @@ -63,6 +63,7 @@ #include #include "fs_heap.h" +#include "sched/sched.h" #if !defined(CONFIG_SCHED_CPULOAD_NONE) || defined(CONFIG_SCHED_CRITMONITOR) # include @@ -1421,6 +1422,7 @@ static ssize_t proc_groupfd(FAR struct proc_file_s *procfile, int count, if (tcb == NULL || tcb->group == NULL) { leave_critical_section(flags); + nxsched_put_tcb(tcb); break; } @@ -1433,6 +1435,7 @@ static ssize_t proc_groupfd(FAR struct proc_file_s *procfile, int count, #endif leave_critical_section(flags); + nxsched_put_tcb(tcb); if (ret < 0) { continue; @@ -1645,7 +1648,6 @@ static int proc_open(FAR struct file *filep, FAR const char *relpath, { FAR struct proc_file_s *procfile; FAR const struct proc_node_s *node; - FAR struct tcb_s *tcb; FAR char *ptr; unsigned long tmp; pid_t pid; @@ -1692,8 +1694,7 @@ static int proc_open(FAR struct file *filep, FAR const char *relpath, pid = (pid_t)tmp; - tcb = nxsched_get_tcb(pid); - if (tcb == NULL || nxsig_kill_target(pid) < 0) + if (nxsig_kill_target(pid) < 0) { ferr("ERROR: PID %d is no longer valid\n", pid); return -ENOENT; @@ -1863,6 +1864,8 @@ static ssize_t proc_read(FAR struct file *filep, FAR char *buffer, ret = proc_groupfd(procfile, count, buffer, buflen, filep->f_pos); } + nxsched_put_tcb(tcb); + /* Update the file offset */ if (ret > 0) @@ -1914,6 +1917,7 @@ static ssize_t proc_write(FAR struct file *filep, FAR const char *buffer, break; } + nxsched_put_tcb(tcb); return ret; } @@ -1969,7 +1973,6 @@ static int proc_opendir(FAR const char *relpath, { FAR struct proc_dir_s *procdir; FAR const struct proc_node_s *node; - FAR struct tcb_s *tcb; unsigned long tmp; FAR char *ptr; pid_t pid; @@ -2020,8 +2023,7 @@ static int proc_opendir(FAR const char *relpath, pid = (pid_t)tmp; - tcb = nxsched_get_tcb(pid); - if (tcb == NULL || nxsig_kill_target(pid) < 0) + if (nxsig_kill_target(pid) < 0) { ferr("ERROR: PID %d is not valid\n", pid); return -ENOENT; @@ -2111,7 +2113,6 @@ static int proc_readdir(FAR struct fs_dirent_s *dir, { FAR struct proc_dir_s *procdir; FAR const struct proc_node_s *node = NULL; - FAR struct tcb_s *tcb; unsigned int index; pid_t pid; int ret; @@ -2139,9 +2140,7 @@ static int proc_readdir(FAR struct fs_dirent_s *dir, /* Verify that the pid still refers to an active task/thread */ pid = procdir->pid; - - tcb = nxsched_get_tcb(pid); - if (tcb == NULL) + if (!nxsched_verify_pid(pid)) { ferr("ERROR: PID %d is no longer valid\n", pid); return -ENOENT; @@ -2213,10 +2212,12 @@ static int proc_rewinddir(struct fs_dirent_s *dir) static int proc_stat(const char *relpath, struct stat *buf) { FAR const struct proc_node_s *node; - FAR struct tcb_s *tcb; unsigned long tmp; FAR char *ptr; pid_t pid; +#ifdef CONFIG_SCHED_USER_IDENTITY + FAR struct tcb_s *tcb; +#endif /* Two path forms are accepted: * @@ -2258,8 +2259,7 @@ static int proc_stat(const char *relpath, struct stat *buf) pid = (pid_t)tmp; - tcb = nxsched_get_tcb(pid); - if (tcb == NULL || nxsig_kill_target(pid) < 0) + if (nxsig_kill_target(pid) < 0) { ferr("ERROR: PID %d is no longer valid\n", pid); return -ENOENT; @@ -2274,10 +2274,16 @@ static int proc_stat(const char *relpath, struct stat *buf) * the task group. */ - if (tcb->group != NULL) + tcb = nxsched_get_tcb(pid); + if (tcb != NULL) { - buf->st_uid = tcb->group->tg_euid; - buf->st_gid = tcb->group->tg_egid; + if (tcb->group != NULL) + { + buf->st_uid = tcb->group->tg_euid; + buf->st_gid = tcb->group->tg_egid; + } + + nxsched_put_tcb(tcb); } #endif diff --git a/fs/vfs/fs_sync.c b/fs/vfs/fs_sync.c index 67ab7db738ac9..29fe29e87c674 100644 --- a/fs/vfs/fs_sync.c +++ b/fs/vfs/fs_sync.c @@ -125,13 +125,14 @@ static void task_fssync(pid_t pid) if (tcb == NULL || tcb->group == NULL || fd >= fdlist_count(&tcb->group->tg_fdlist)) { + nxsched_put_tcb(tcb); leave_critical_section(flags); break; } ret = fdlist_get(&tcb->group->tg_fdlist, fd, &filep); + nxsched_put_tcb(tcb); leave_critical_section(flags); - if (ret >= 0) { file_fsync(filep); diff --git a/include/nuttx/sched.h b/include/nuttx/sched.h index 368e045989165..60cbc0d20233b 100644 --- a/include/nuttx/sched.h +++ b/include/nuttx/sched.h @@ -127,6 +127,7 @@ #define TCB_FLAG_FORCED_CANCEL (1 << 6) /* Bit 6: Pthread cancel is forced */ #define TCB_FLAG_JOIN_COMPLETED (1 << 7) /* Bit 7: Pthread join completed */ #define TCB_FLAG_REAPED (1 << 8) /* Bit 8: Exit waited for by parent */ +#define TCB_FLAG_KILL_PROCESSING (1 << 9) /* Bit 9: tcb is killed */ /* Values for struct task_group tg_flags */ @@ -695,6 +696,14 @@ struct tcb_s cpu_set_t affinity; /* Bit set of permitted CPUs */ #endif atomic_t shared_flags; /* Flags written by other tasks */ + + /* The total number that we are referenced by other tasks */ + + atomic_t refs; + + /* When we exit, we need post this sem. */ + + sem_t exit_sem; int16_t lockcount; /* 0=preemptible (not-locked) */ #ifdef CONFIG_IRQCOUNT int16_t irqcount; /* 0=Not in critical section */ @@ -1036,6 +1045,28 @@ void nxsched_foreach(nxsched_foreach_t handler, FAR void *arg); FAR struct tcb_s *nxsched_get_tcb(pid_t pid); +/**************************************************************************** + * Name: nxsched_verify_pid + * + * Description: + * Given a task ID, this function will check whether the TCB + * corresponding to the PID exists. + * + ****************************************************************************/ + +bool nxsched_verify_pid(pid_t pid); + +/**************************************************************************** + * Name: nxsched_put_tcb + * + * Description: + * Drop a reference taken with nxsched_get_tcb(); each successful + * get must be paired with a put. + * + ****************************************************************************/ + +void nxsched_put_tcb(FAR struct tcb_s *tcb); + /**************************************************************************** * Name: nxsched_releasepid * diff --git a/libs/libc/gdbstub/lib_gdbstub.c b/libs/libc/gdbstub/lib_gdbstub.c index 596df2caa4234..979af6186087e 100644 --- a/libs/libc/gdbstub/lib_gdbstub.c +++ b/libs/libc/gdbstub/lib_gdbstub.c @@ -1105,6 +1105,8 @@ static void gdb_update_regcache(FAR struct gdb_state_s *state) *(FAR uintptr_t *)(reg + g_tcbinfo.reg_off.p[i]); } } + + nxsched_put_tcb(tcb); } /**************************************************************************** @@ -1557,6 +1559,7 @@ static int gdb_query(FAR struct gdb_state_s *state) get_task_name(tcb), thread_state, tcb->sched_priority, tcb->adj_stack_size); + nxsched_put_tcb(tcb); ret = gdb_bin2hex(state->pkt_buf, sizeof(state->pkt_buf), thread_info, strlen(thread_info)); @@ -1638,6 +1641,7 @@ static int gdb_is_thread_active(FAR struct gdb_state_s *state) return -EINVAL; } + nxsched_put_tcb(tcb); state->pid = pid; gdb_send_ok_packet(state); return ret; @@ -1701,6 +1705,7 @@ static int gdb_thread_context(FAR struct gdb_state_s *state) return -EINVAL; } + nxsched_put_tcb(tcb); state->pid = pid; gdb_update_regcache(state); diff --git a/mm/mm_heap/mm_memdump.c b/mm/mm_heap/mm_memdump.c index 54a8c55406a05..17071f975ed16 100644 --- a/mm/mm_heap/mm_memdump.c +++ b/mm/mm_heap/mm_memdump.c @@ -32,6 +32,7 @@ #include #include +#include #include #include "mm_heap/mm.h" @@ -305,6 +306,7 @@ void mm_memdump(FAR struct mm_heap_s *heap, tcb->stack_alloc_ptr, tcb->adj_stack_size, name); } + nxsched_put_tcb(tcb); memdump_info_pool(&priv, heap); } else if (pid == PID_MM_FREE) diff --git a/mm/tlsf/mm_tlsf.c b/mm/tlsf/mm_tlsf.c index 83de0b8ceb1b9..dc7c66160fe4a 100644 --- a/mm/tlsf/mm_tlsf.c +++ b/mm/tlsf/mm_tlsf.c @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -1397,6 +1398,7 @@ void mm_memdump(FAR struct mm_heap_s *heap, tcb->stack_alloc_ptr, tcb->adj_stack_size, name); } + nxsched_put_tcb(tcb); memdump_info_pool(&priv, heap); } else if (pid == PID_MM_FREE) diff --git a/sched/clock/clock_gettime.c b/sched/clock/clock_gettime.c index 662b00778267c..da51edac2a6bd 100644 --- a/sched/clock/clock_gettime.c +++ b/sched/clock/clock_gettime.c @@ -186,7 +186,12 @@ int nxclock_gettime(clockid_t clock_id, FAR struct timespec *tp) } else { - return -EINVAL; + ret = -EINVAL; + } + + if (pid != 0) + { + nxsched_put_tcb(tcb); } #else ret = -EINVAL; diff --git a/sched/group/group_continue.c b/sched/group/group_continue.c index 63aa35ac1ce4c..9980fd1ee6e84 100644 --- a/sched/group/group_continue.c +++ b/sched/group/group_continue.c @@ -79,6 +79,8 @@ static int group_continue_handler(pid_t pid, FAR void *arg) { up_switch_context(this_task(), tcb); } + + nxsched_put_tcb(rtcb); } /* Always return zero. We need to visit each member of the group */ diff --git a/sched/group/group_killchildren.c b/sched/group/group_killchildren.c index 49f2662d2d87f..867dc50dad038 100644 --- a/sched/group/group_killchildren.c +++ b/sched/group/group_killchildren.c @@ -158,10 +158,12 @@ static int group_cancel_children_handler(pid_t pid, FAR void *arg) if ((rtcb->flags & TCB_FLAG_TTYPE_MASK) == TCB_FLAG_TTYPE_PTHREAD) { + nxsched_put_tcb(rtcb); ret = pthread_cancel(pid); } else { + nxsched_put_tcb(rtcb); ret = nxtask_delete(pid); } diff --git a/sched/group/group_signal.c b/sched/group/group_signal.c index 952c6a20cd373..3be1a19543be2 100644 --- a/sched/group/group_signal.c +++ b/sched/group/group_signal.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -82,7 +83,7 @@ static int group_signal_handler(pid_t pid, FAR void *arg) #ifdef CONFIG_ENABLE_ALL_SIGNALS FAR sigactq_t *sigact; #endif - int ret; + int ret = 0; /* Get the TCB associated with the group member */ @@ -102,8 +103,8 @@ static int group_signal_handler(pid_t pid, FAR void *arg) * probably blocked). */ - ret = nxsig_ismember(&tcb->sigwaitmask, info->siginfo->si_signo); - if (ret == 1 && (!info->atcb || info->siginfo->si_signo == SIGCHLD)) + if (nxsig_ismember(&tcb->sigwaitmask, info->siginfo->si_signo) == 1 && + (!info->atcb || info->siginfo->si_signo == SIGCHLD)) { /* Yes.. This means that the task is suspended, waiting for this * signal to occur. Stop looking and use this TCB. The @@ -117,7 +118,7 @@ static int group_signal_handler(pid_t pid, FAR void *arg) info->limit); if (ret < 0) { - return ret; + goto errout; } /* Limit to one thread */ @@ -126,7 +127,8 @@ static int group_signal_handler(pid_t pid, FAR void *arg) if (info->ptcb != NULL && info->siginfo->si_signo != SIGCHLD) { - return 1; /* Terminate the search */ + ret = 1; /* Terminate the search */ + goto errout; } } @@ -160,7 +162,7 @@ static int group_signal_handler(pid_t pid, FAR void *arg) info->limit); if (ret < 0) { - return ret; + goto errout; } /* Limit to one thread */ @@ -168,13 +170,16 @@ static int group_signal_handler(pid_t pid, FAR void *arg) info->ptcb = tcb; if (info->atcb != NULL) { - return 1; /* Terminate the search */ + ret = 1; /* Terminate the search */ + goto errout; } } #endif } - return 0; /* Keep searching */ +errout: + nxsched_put_tcb(tcb); + return ret; } #endif diff --git a/sched/group/group_suspendchildren.c b/sched/group/group_suspendchildren.c index dc861be52fee6..ac45015615de4 100644 --- a/sched/group/group_suspendchildren.c +++ b/sched/group/group_suspendchildren.c @@ -71,6 +71,7 @@ static int group_suspend_children_handler(pid_t pid, FAR void *arg) if (rtcb != NULL) { nxsched_suspend(rtcb); + nxsched_put_tcb(rtcb); } } diff --git a/sched/init/nx_start.c b/sched/init/nx_start.c index 53d4d28172b7a..9c5be988d1438 100644 --- a/sched/init/nx_start.c +++ b/sched/init/nx_start.c @@ -376,6 +376,8 @@ static void idle_task_initialize(void) tcb->pid = i; tcb->task_state = TSTATE_TASK_RUNNING; tcb->lockcount = 1; + tcb->refs = 1; + nxsem_init(&tcb->exit_sem, 0, 0); /* Set the entry point. This is only for debug purposes. NOTE: that * the start_t entry point is not saved. That is acceptable, however, diff --git a/sched/misc/assert.c b/sched/misc/assert.c index 10a5931e91560..8d1bc85ecd8a7 100644 --- a/sched/misc/assert.c +++ b/sched/misc/assert.c @@ -611,11 +611,6 @@ static void dump_lockholder(pid_t tid) int depth = 0; pid_t holder = INVALID_PROCESS_ID; - /* nxsched_get_tcb() holds no reference on the TCB once it returns, so - * use it as an inherently racy snapshot and read what we need from it - * immediately. - */ - tcb = nxsched_get_tcb(tid); DEBUGASSERT(tcb != NULL); @@ -638,6 +633,8 @@ static void dump_lockholder(pid_t tid) } # endif + nxsched_put_tcb(tcb); + backtrace_format(buf, sizeof(buf), stack, depth); _emerg("Deadlock(%d) holder(%d) backtrace: %s\n", tid, holder, buf); @@ -773,6 +770,8 @@ static void dump_assert_info(FAR struct tcb_s *rtcb, ptcb ? get_task_name(ptcb) : "Kernel", rtcb->entry.main); + nxsched_put_tcb(ptcb); + /* Dump current CPU registers, running task stack and backtrace. */ dump_running_task(rtcb, regs); diff --git a/sched/misc/coredump.c b/sched/misc/coredump.c index 46179e1150041..76c6b23d8270b 100644 --- a/sched/misc/coredump.c +++ b/sched/misc/coredump.c @@ -1164,6 +1164,7 @@ int coredump(FAR const struct memory_region_s *regions, elf_flush(&cinfo); + nxsched_put_tcb(cinfo.tcb); leave_critical_section(flags); return OK; diff --git a/sched/misc/deadlock.c b/sched/misc/deadlock.c index dabd652eeab13..febb322b4bc3f 100644 --- a/sched/misc/deadlock.c +++ b/sched/misc/deadlock.c @@ -90,7 +90,11 @@ static FAR struct tcb_s *deadlock_next(FAR struct tcb_s *tcb) return NULL; } - return nxsched_get_tcb(holder); + /* The caller runs in the critical section of nxsched_foreach(), which + * keeps the TCB in the pid hash, so it stays valid without a reference. + */ + + return g_pidhash[PIDHASH(holder)]; } /**************************************************************************** diff --git a/sched/paging/pg_miss.c b/sched/paging/pg_miss.c index 597ffcf3322ec..c1644f22e51f0 100644 --- a/sched/paging/pg_miss.c +++ b/sched/paging/pg_miss.c @@ -169,6 +169,8 @@ void pg_miss(void) nxsched_set_priority(wtcb, ftcb->sched_priority); } + nxsched_put_tcb(wtcb); + /* Signal the page fill worker thread. * - Is there a page fill pending? If not then signal the worker * thread to start working on the queued page fill requests. diff --git a/sched/paging/pg_worker.c b/sched/paging/pg_worker.c index 25a5e98d76cc0..6d1b72feb4b53 100644 --- a/sched/paging/pg_worker.c +++ b/sched/paging/pg_worker.c @@ -167,6 +167,8 @@ static void pg_callback(FAR struct tcb_s *tcb, int result) nxsched_set_priority(wtcb, priority); } + nxsched_put_tcb(wtcb); + /* Save the page fill result (don't permit the value -EBUSY) */ if (result == -EBUSY) diff --git a/sched/pthread/pthread_cancel.c b/sched/pthread/pthread_cancel.c index c9cfe005a7119..e8d42a9425b1f 100644 --- a/sched/pthread/pthread_cancel.c +++ b/sched/pthread/pthread_cancel.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -76,6 +77,7 @@ int pthread_cancel(pthread_t thread) if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) { + nxsched_put_tcb(tcb); return ESRCH; } @@ -88,6 +90,7 @@ int pthread_cancel(pthread_t thread) if (nxnotify_cancellation(tcb)) { + nxsched_put_tcb(tcb); return OK; } @@ -99,6 +102,7 @@ int pthread_cancel(pthread_t thread) if (tcb == this_task()) { + nxsched_put_tcb(tcb); pthread_exit(PTHREAD_CANCELED); } @@ -106,6 +110,8 @@ int pthread_cancel(pthread_t thread) tls_cleanup_popall(tcb->stack_alloc_ptr); + nxsched_put_tcb(tcb); + /* Complete pending join operations */ pthread_completejoin((pid_t)thread, PTHREAD_CANCELED); diff --git a/sched/pthread/pthread_completejoin.c b/sched/pthread/pthread_completejoin.c index f73bd3c90f076..eca920b0d794f 100644 --- a/sched/pthread/pthread_completejoin.c +++ b/sched/pthread/pthread_completejoin.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -111,6 +112,7 @@ int pthread_completejoin(pid_t pid, FAR void *exit_value) nxrmutex_unlock(&group->tg_mutex); + nxsched_put_tcb(tcb); return ret; } diff --git a/sched/pthread/pthread_create.c b/sched/pthread/pthread_create.c index c6b908055a5cc..2f4c427b6d689 100644 --- a/sched/pthread/pthread_create.c +++ b/sched/pthread/pthread_create.c @@ -252,6 +252,8 @@ int nx_pthread_create(pthread_trampoline_t trampoline, FAR pthread_t *thread, nxtask_joininit(ptcb); + nxsem_init(&ptcb->exit_sem, 0, 0); + /* Bind the parent's group to the new TCB (we have not yet joined the * group). */ @@ -504,6 +506,15 @@ int nx_pthread_create(pthread_trampoline_t trampoline, FAR pthread_t *thread, ptcb->group = NULL; + /* The pid hash slot still holds the only reference: release it + * before the TCB, nxsched_release_tcb() no longer does it. + */ + + if (ptcb->pid) + { + nxsched_releasepid(ptcb->pid); + } + nxsched_release_tcb(ptcb, TCB_FLAG_TTYPE_PTHREAD); return -ret; } diff --git a/sched/pthread/pthread_detach.c b/sched/pthread/pthread_detach.c index 200798c216507..300050ec3a5f1 100644 --- a/sched/pthread/pthread_detach.c +++ b/sched/pthread/pthread_detach.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -106,5 +107,6 @@ int pthread_detach(pthread_t thread) nxrmutex_unlock(&group->tg_mutex); sinfo("Returning %d\n", ret); + nxsched_put_tcb(tcb); return ret; } diff --git a/sched/pthread/pthread_exit.c b/sched/pthread/pthread_exit.c index 18fe92b159b75..260fba16548f3 100644 --- a/sched/pthread/pthread_exit.c +++ b/sched/pthread/pthread_exit.c @@ -36,6 +36,7 @@ #include #include +#include #include #include "sched/sched.h" @@ -68,6 +69,7 @@ void nx_pthread_exit(FAR void *exit_value) #ifndef CONFIG_DISABLE_ALL_SIGNALS sigset_t set; #endif + irqstate_t flags; int status; sinfo("exit_value=%p\n", exit_value); @@ -97,10 +99,31 @@ void nx_pthread_exit(FAR void *exit_value) _exit(EXIT_FAILURE); } + flags = enter_critical_section(); + if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) + { + leave_critical_section(flags); + + /* If the TCB is already in the exiting state, we + * should allow the killing task to execute normally first. + * We stop the execution here. + */ + + for (; ; ) + { + usleep(1000); + } + } + + atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING); + leave_critical_section(flags); + /* Make sure that we are in a critical section with local interrupts. * The IRQ state will be restored when the next task is started. */ + nxsched_releasepid(tcb->pid); + enter_critical_section(); /* Perform common task termination logic. This will get called again later diff --git a/sched/pthread/pthread_join.c b/sched/pthread/pthread_join.c index d8983d5e7cfc2..f69d80b00b470 100644 --- a/sched/pthread/pthread_join.c +++ b/sched/pthread/pthread_join.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -245,6 +246,7 @@ int pthread_join(pthread_t thread, FAR pthread_addr_t *pexit_value) ret = ESRCH; } + nxsched_put_tcb(tcb); goto errout; } @@ -254,6 +256,7 @@ int pthread_join(pthread_t thread, FAR pthread_addr_t *pexit_value) if (tcb == rtcb) { + nxsched_put_tcb(tcb); ret = EDEADLK; goto errout; } @@ -263,6 +266,7 @@ int pthread_join(pthread_t thread, FAR pthread_addr_t *pexit_value) if ((tcb->group != group) || (atomic_read(&tcb->shared_flags) & TCB_FLAG_DETACHED) != 0) { + nxsched_put_tcb(tcb); ret = EINVAL; goto errout; } @@ -280,11 +284,13 @@ int pthread_join(pthread_t thread, FAR pthread_addr_t *pexit_value) if (is_thread_deadlock_for_join(rtcb, tcb)) { sq_rem(&rtcb->join_entry, &tcb->join_queue); + nxsched_put_tcb(tcb); ret = EDEADLK; goto errout; } #endif + nxsched_put_tcb(tcb); nxrmutex_unlock(&group->tg_mutex); /* Take the thread's thread exit semaphore. We will sleep here diff --git a/sched/sched/sched.h b/sched/sched/sched.h index 9432bf0def5f9..7e773717d6100 100644 --- a/sched/sched/sched.h +++ b/sched/sched/sched.h @@ -356,6 +356,17 @@ bool nxsched_merge_pending(void); bool nxsched_reprioritize_rtr(FAR struct tcb_s *tcb, int priority); #endif +/**************************************************************************** + * Name: nxsched_releasepid + * + * Description: + * When a task is destroyed, this function must be called to make its + * process ID available for reuse. + * + ****************************************************************************/ + +void nxsched_releasepid(pid_t pid); + /* Priority inheritance support */ #ifdef CONFIG_PRIORITY_INHERITANCE @@ -510,8 +521,6 @@ bool nxsched_may_control(pid_t pid); /* TCB operations */ -bool nxsched_verify_tcb(FAR struct tcb_s *tcb); - /* Obtain TLS from kernel */ struct tls_info_s; /* Forward declare */ diff --git a/sched/sched/sched_backtrace.c b/sched/sched/sched_backtrace.c index e4a4c3a49d1d7..49c409fb14666 100644 --- a/sched/sched/sched_backtrace.c +++ b/sched/sched/sched_backtrace.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include @@ -91,6 +92,7 @@ static int sched_backtrace_handler(FAR void *cookie) /* There is no TCB with this pid or, if there is, it is not a task. */ leave_critical_section(flags); + nxsched_put_tcb(tcb); return -ESRCH; } @@ -99,6 +101,8 @@ static int sched_backtrace_handler(FAR void *cookie) atomic_and(&tcb->shared_flags, ~TCB_FLAG_CPU_LOCKED); } + nxsched_put_tcb(tcb); + leave_critical_section(flags); arg->stacksize = up_backtrace(tcb, arg->buffer, arg->size, arg->skip); @@ -146,6 +150,7 @@ int sched_backtrace(pid_t tid, FAR void **buffer, int size, int skip) (atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) { + nxsched_put_tcb(tcb); leave_critical_section(flags); return 0; } @@ -156,6 +161,7 @@ int sched_backtrace(pid_t tid, FAR void **buffer, int size, int skip) { struct backtrace_arg_s arg; bool need_restore; + int cpu = tcb->cpu; #ifdef CONFIG_ARCH_ADDRENV FAR void *scratch[BACKTRACE_SCRATCH_DEPTH]; #endif @@ -190,7 +196,7 @@ int sched_backtrace(pid_t tid, FAR void **buffer, int size, int skip) arg.need_restore = need_restore && arg.size == size - ret; - if (nxsched_smp_call_single(tcb->cpu, + if (nxsched_smp_call_single(cpu, sched_backtrace_handler, &arg) < 0) { @@ -225,15 +231,19 @@ int sched_backtrace(pid_t tid, FAR void **buffer, int size, int skip) { arg.size = 0; arg.need_restore = true; - nxsched_smp_call_single(tcb->cpu, sched_backtrace_handler, + nxsched_smp_call_single(cpu, sched_backtrace_handler, &arg); } + + nxsched_put_tcb(tcb); #else arg.need_restore = need_restore; arg.buffer = buffer; arg.size = size; arg.skip = skip; - ret = nxsched_smp_call_single(tcb->cpu, + + nxsched_put_tcb(tcb); + ret = nxsched_smp_call_single(cpu, sched_backtrace_handler, &arg) < 0 ? 0 : arg.stacksize; #endif @@ -242,6 +252,7 @@ int sched_backtrace(pid_t tid, FAR void **buffer, int size, int skip) #endif { ret = up_backtrace(tcb, buffer, size, skip); + nxsched_put_tcb(tcb); } } diff --git a/sched/sched/sched_foreach.c b/sched/sched/sched_foreach.c index 21c5e4bffbd92..b5c280710135d 100644 --- a/sched/sched/sched_foreach.c +++ b/sched/sched/sched_foreach.c @@ -68,7 +68,11 @@ void nxsched_foreach(nxsched_foreach_t handler, FAR void *arg) sched_lock(); for (ndx = 0; ndx < g_npidhash; ndx++) { - /* This test and the function call must be atomic */ + /* This test and the function call must be atomic. The handler + * runs in the critical section and must not block: the reference + * count cannot be taken and dropped here, nxsched_put_tcb() + * posts a semaphore and would allow a context switch. + */ if (g_pidhash[ndx]) { diff --git a/sched/sched/sched_get_stackinfo.c b/sched/sched/sched_get_stackinfo.c index a22698a6d83db..17ef58ae6437f 100644 --- a/sched/sched/sched_get_stackinfo.c +++ b/sched/sched/sched_get_stackinfo.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -59,7 +60,7 @@ int nxsched_get_stackinfo(pid_t pid, FAR struct stackinfo_s *stackinfo) { FAR struct tcb_s *rtcb = this_task(); /* TCB of running task */ - FAR struct tcb_s *qtcb; /* TCB of queried task */ + FAR struct tcb_s *qtcb = NULL; /* TCB of queried task */ int ret = OK; DEBUGASSERT(stackinfo != NULL); @@ -97,7 +98,8 @@ int nxsched_get_stackinfo(pid_t pid, FAR struct stackinfo_s *stackinfo) if (rtcb->group != qtcb->group) { - ret = -EACCES; + nxsched_put_tcb(qtcb); + return -EACCES; } } } @@ -119,5 +121,10 @@ int nxsched_get_stackinfo(pid_t pid, FAR struct stackinfo_s *stackinfo) stackinfo->stack_base_ptr = qtcb->stack_base_ptr; } + if (pid != 0) + { + nxsched_put_tcb(qtcb); + } + return ret; } diff --git a/sched/sched/sched_getaffinity.c b/sched/sched/sched_getaffinity.c index 7b973183baa81..d3fa68aacc084 100644 --- a/sched/sched/sched_getaffinity.c +++ b/sched/sched/sched_getaffinity.c @@ -101,6 +101,11 @@ int nxsched_get_affinity(pid_t pid, size_t cpusetsize, FAR cpu_set_t *mask) ret = OK; } + if (pid != 0) + { + nxsched_put_tcb(tcb); + } + leave_critical_section(flags); return ret; } diff --git a/sched/sched/sched_getparam.c b/sched/sched/sched_getparam.c index 32de0f4d750e7..4f90bfe94524d 100644 --- a/sched/sched/sched_getparam.c +++ b/sched/sched/sched_getparam.c @@ -173,6 +173,7 @@ int nxsched_get_param(pid_t pid, FAR struct sched_param *param) } leave_critical_section(flags); + nxsched_put_tcb(tcb); } } diff --git a/sched/sched/sched_getscheduler.c b/sched/sched/sched_getscheduler.c index 9d20fba8226b2..c42fd0d5b72c6 100644 --- a/sched/sched/sched_getscheduler.c +++ b/sched/sched/sched_getscheduler.c @@ -91,6 +91,11 @@ int nxsched_get_scheduler(pid_t pid) ret = nxsched_get_policy(tcb) >> TCB_FLAG_POLICY_SHIFT; } + if (pid != 0 && tcb != NULL) + { + nxsched_put_tcb(tcb); + } + return ret; } diff --git a/sched/sched/sched_gettcb.c b/sched/sched/sched_gettcb.c index f31ecf4fee48c..11346e97e993e 100644 --- a/sched/sched/sched_gettcb.c +++ b/sched/sched/sched_gettcb.c @@ -40,15 +40,8 @@ * Name: nxsched_get_tcb * * Description: - * Given a task ID, this function will return the a pointer to the - * corresponding TCB (or NULL if there is no such task ID). - * - * NOTE: This function holds a critical section while examining TCB data - * data structures but releases that critical section before returning. - * When it is released, the TCB may become unstable. If the caller - * requires absolute stability while using the TCB, then the caller - * should establish the critical section BEFORE calling this function and - * hold that critical section as long as necessary. + * Given a task ID, obtain a valid TCB and increment the corresponding + * reference count to prevent it from being released. * ****************************************************************************/ @@ -60,10 +53,6 @@ FAR struct tcb_s *nxsched_get_tcb(pid_t pid) flags = enter_critical_section(); - /* Verify whether g_pidhash hash table has already been allocated and - * whether the PID is within range. - */ - if (g_pidhash != NULL && pid >= 0) { /* The test and the return setup should be atomic. This still does @@ -86,9 +75,81 @@ FAR struct tcb_s *nxsched_get_tcb(pid_t pid) } } - leave_critical_section(flags); + if (ret) + { + if (!up_interrupt_context()) + { + /* If we are in the thread context, after obtaining a reference to + * another task, we may not be able to release this reference + * immediately. The purpose of refs is also to prevent the + * situation where this_task is killed and thus unable to release + * the references to other tasks. We need to record the total + * number of references that this_task makes to other tasks. + */ + + atomic_add(&this_task()->refs, 1); + } - /* Return the TCB. */ + atomic_add(&ret->refs, 1); + } + + leave_critical_section(flags); return ret; } + +/**************************************************************************** + * Name: nxsched_put_tcb + * + * Description: + * Drop a reference taken with nxsched_get_tcb(); each successful get + * must be paired with a put. + * + ****************************************************************************/ + +void nxsched_put_tcb(FAR struct tcb_s *tcb) +{ + if (!tcb) + { + return; + } + + DEBUGASSERT(atomic_read(&tcb->refs) > 0); + + /* tcb may in EXIT_PROCESSING */ + + if (atomic_sub(&tcb->refs, 1) == 1) + { + nxsem_post(&tcb->exit_sem); + } + + if (up_interrupt_context()) + { + return; + } + + tcb = this_task(); + + DEBUGASSERT(atomic_read(&tcb->refs) > 0); + + /* this_task may be killed and in KILL_PROCESSING */ + + if (atomic_sub(&tcb->refs, 1) == 1 && + (atomic_read(&tcb->shared_flags) & TCB_FLAG_KILL_PROCESSING)) + { + nxsem_post(&tcb->exit_sem); + + /* If the TCB is already in the exiting state, we + * should allow the exiting task to execute normally first. + * We stop the execution here. + * + * If it continues to run, it may happen that we obtain + * the TCB again and it gets killed. + */ + + for (; ; ) + { + usleep(1000); + } + } +} diff --git a/sched/sched/sched_maycontrol.c b/sched/sched/sched_maycontrol.c index 37a4461440f91..5f4a59d0c6c66 100644 --- a/sched/sched/sched_maycontrol.c +++ b/sched/sched/sched_maycontrol.c @@ -62,5 +62,9 @@ bool nxsched_may_control(pid_t pid) } tcb = nxsched_get_tcb(pid); - return tcb == NULL || tcb->group == nxsched_self()->group; + bool may_control = (tcb == NULL || + tcb->group == nxsched_self()->group); + + nxsched_put_tcb(tcb); + return may_control; } diff --git a/sched/sched/sched_releasetcb.c b/sched/sched/sched_releasetcb.c index d33e36a2403d1..16e72742bc742 100644 --- a/sched/sched/sched_releasetcb.c +++ b/sched/sched/sched_releasetcb.c @@ -54,7 +54,9 @@ void nxsched_releasepid(pid_t pid) { irqstate_t flags = enter_critical_section(); int hash_ndx = PIDHASH(pid); + FAR struct tcb_s *tcb = g_pidhash[hash_ndx]; + DEBUGASSERT(tcb); #ifndef CONFIG_SCHED_CPULOAD_NONE /* Decrement the total CPU load count held by this thread from the * total for all threads. @@ -69,8 +71,17 @@ void nxsched_releasepid(pid_t pid) */ g_pidhash[hash_ndx] = NULL; + DEBUGASSERT(atomic_read(&tcb->refs) > 0); + atomic_sub(&tcb->refs, 1); leave_critical_section(flags); + + /* Wait tcb->refs to be 0 */ + + while (atomic_read(&tcb->refs)) + { + nxsem_wait(&tcb->exit_sem); + } } /**************************************************************************** @@ -115,17 +126,6 @@ int nxsched_release_tcb(FAR struct tcb_s *tcb, uint8_t ttype) timer_deleteall(tcb->pid); #endif - /* Release the task's process ID if one was assigned. PID - * zero is reserved for the IDLE task. The TCB of the IDLE - * task is never release so a value of zero simply means that - * the process ID was never allocated to this TCB. - */ - - if (tcb->pid) - { - nxsched_releasepid(tcb->pid); - } - /* Delete the thread's stack if one has been allocated */ if (tcb->stack_alloc_ptr) @@ -180,6 +180,8 @@ int nxsched_release_tcb(FAR struct tcb_s *tcb, uint8_t ttype) nxtask_resume_vfork(tcb); #endif + nxsem_destroy(&tcb->exit_sem); + /* And, finally, release the TCB itself */ if (tcb->flags & TCB_FLAG_FREE_TCB) diff --git a/sched/sched/sched_roundrobin.c b/sched/sched/sched_roundrobin.c index 64230d952a38d..4fa3e2327f029 100644 --- a/sched/sched/sched_roundrobin.c +++ b/sched/sched/sched_roundrobin.c @@ -76,6 +76,7 @@ static int nxsched_roundrobin_handler(FAR void *cookie) { /* There is no TCB with this pid or, if there is, it is not a task. */ + nxsched_put_tcb(tcb); leave_critical_section(flags); return OK; } @@ -86,6 +87,7 @@ static int nxsched_roundrobin_handler(FAR void *cookie) up_switch_context(this_task(), tcb); } + nxsched_put_tcb(tcb); leave_critical_section(flags); return OK; } diff --git a/sched/sched/sched_rrgetinterval.c b/sched/sched/sched_rrgetinterval.c index a64f50e32f06d..c59a2cc296b6a 100644 --- a/sched/sched/sched_rrgetinterval.c +++ b/sched/sched/sched_rrgetinterval.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -69,7 +70,7 @@ int sched_rr_get_interval(pid_t pid, struct timespec *interval) { - FAR struct tcb_s *rrtcb; + FAR struct tcb_s *rrtcb = NULL; int status = OK; /* If pid is zero, the timeslice for the calling process is written @@ -131,5 +132,10 @@ int sched_rr_get_interval(pid_t pid, struct timespec *interval) status = ERROR; } + if (pid > 0 && rrtcb != NULL) + { + nxsched_put_tcb(rrtcb); + } + return status; } diff --git a/sched/sched/sched_setaffinity.c b/sched/sched/sched_setaffinity.c index 65048114ead0e..198dfd07c4540 100644 --- a/sched/sched/sched_setaffinity.c +++ b/sched/sched/sched_setaffinity.c @@ -150,6 +150,10 @@ int nxsched_set_affinity(pid_t pid, size_t cpusetsize, errout_with_csection: leave_critical_section(flags); + if (pid) + { + nxsched_put_tcb(tcb); + } errout: return ret; diff --git a/sched/sched/sched_setparam.c b/sched/sched/sched_setparam.c index e5e0357fcaab9..a9ce039b19c02 100644 --- a/sched/sched/sched_setparam.c +++ b/sched/sched/sched_setparam.c @@ -192,6 +192,11 @@ int nxsched_set_param(pid_t pid, FAR const struct sched_param *param) ret = nxsched_reprioritize(tcb, param->sched_priority); } + if (tcb != rtcb) + { + nxsched_put_tcb(tcb); + } + sched_unlock(); } else diff --git a/sched/sched/sched_setscheduler.c b/sched/sched/sched_setscheduler.c index c1ffe6f4b4103..78ff68b9af2ad 100644 --- a/sched/sched/sched_setscheduler.c +++ b/sched/sched/sched_setscheduler.c @@ -246,6 +246,11 @@ int nxsched_set_scheduler(pid_t pid, int policy, ret = nxsched_reprioritize(tcb, param->sched_priority); } + if (pid != 0) + { + nxsched_put_tcb(tcb); + } + sched_unlock(); return ret; } diff --git a/sched/sched/sched_suspend.c b/sched/sched/sched_suspend.c index a6b9000224de2..9e14c54a56b0a 100644 --- a/sched/sched/sched_suspend.c +++ b/sched/sched/sched_suspend.c @@ -70,6 +70,7 @@ static int nxsched_suspend_handler(FAR void *cookie) /* There is no TCB with this pid or, if there is, it is not a task. */ leave_critical_section(flags); + nxsched_put_tcb(tcb); return OK; } @@ -84,6 +85,7 @@ static int nxsched_suspend_handler(FAR void *cookie) dq_addlast((FAR dq_entry_t *)tcb, &g_stoppedtasks); leave_critical_section(flags); + nxsched_put_tcb(tcb); return OK; } #endif diff --git a/sched/sched/sched_verifytcb.c b/sched/sched/sched_verifytcb.c index 0cb0902d3a284..56aea34d6fff4 100644 --- a/sched/sched/sched_verifytcb.c +++ b/sched/sched/sched_verifytcb.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -36,46 +37,24 @@ ****************************************************************************/ /**************************************************************************** - * Name: nxsched_verify_tcb + * Name: nxsched_verify_pid * * Description: - * Return true if the tcb refers to an active task; false if it is a stale - * TCB handle. + * Given a task ID, this function will check whether the + * TCB corresponding to the PID exists. * ****************************************************************************/ -bool nxsched_verify_tcb(FAR struct tcb_s *tcb) +bool nxsched_verify_pid(pid_t pid) { - /* Return true if the PID hashes to this TCB. This will catch the case - * where the task associated with the TCB has terminated (note that - * sched_releasedtcb() will nullify the TCB field in that case). The - * following logic will also detect the case where the task associated - * with the TCB has terminated and another task has been started with a - * different TCB but with a PID hashing to the same entry. - * - * NOTE: In the event that the TCB has terminated, the 'tcb' parameter - * will point at either a stale or a re-allocated memory allocation. The - * PID fetched by the use of the bad pointer(tcb->pid) should not cause - * any memory faults because we do at least know that the pointer refers - * to valid memory in the kernel address space and that the hash macro, - * PIDHASH(), will return a valid, in-range index into the g_pidhash[] - * table. - * - * REVISIT: This logic will not, however, catch the case where the task - * originally associated with the TCB has terminated, but a new task was - * started reusing the same memory allocation for its TDB that was freed - * by the terminated task. In this case, a false positive value will be - * returned: The TCB is valid but does not refer to the same task as - * before. This case is not detectable with the limited amount of - * information available. - */ + FAR struct tcb_s *ret; - irqstate_t flags; - bool valid; + ret = nxsched_get_tcb(pid); + if (ret) + { + nxsched_put_tcb(ret); + return true; + } - flags = enter_critical_section(); - valid = tcb == g_pidhash[PIDHASH(tcb->pid)]; - leave_critical_section(flags); - - return valid; + return false; } diff --git a/sched/sched/sched_waitid.c b/sched/sched/sched_waitid.c index 5520df26f51ce..deb368540856e 100644 --- a/sched/sched/sched_waitid.c +++ b/sched/sched/sched_waitid.c @@ -180,7 +180,7 @@ static bool child_running(FAR struct tcb_s *rtcb, idtype_t idtype, pid_t id) if (idtype == P_PID) { - return nxsched_get_tcb(id) != NULL; + return nxsched_verify_pid(id); } #endif @@ -276,11 +276,20 @@ static int check_children(FAR struct tcb_s *rtcb, idtype_t idtype, pid_t id) if (idtype == P_PID) { + bool child; + ctcb = nxsched_get_tcb(id); - if (ctcb == NULL || ctcb->group == NULL || - ctcb->group->tg_ppid != rtcb->group->tg_pid || - (atomic_read(&ctcb->shared_flags) & - TCB_FLAG_EXIT_PROCESSING) != 0) + if (ctcb == NULL) + { + return -ECHILD; + } + + child = ctcb->group != NULL && + ctcb->group->tg_ppid == rtcb->group->tg_pid && + (atomic_read(&ctcb->shared_flags) + & TCB_FLAG_EXIT_PROCESSING) == 0; + nxsched_put_tcb(ctcb); + if (!child) { return -ECHILD; } diff --git a/sched/sched/sched_waitpid.c b/sched/sched/sched_waitpid.c index 3510e21619e9e..984217b16cb77 100644 --- a/sched/sched/sched_waitpid.c +++ b/sched/sched/sched_waitpid.c @@ -70,6 +70,8 @@ void nxsched_reaped(pid_t pid) { atomic_or(&tcb->shared_flags, TCB_FLAG_REAPED); } + + nxsched_put_tcb(tcb); } /**************************************************************************** @@ -238,7 +240,13 @@ pid_t nxsched_waitpid(pid_t pid, FAR int *stat_loc, int options) mystat = true; } - /* Then wait for the task to exit */ + /* Then wait for the task to exit. The reference on ctcb was + * taken to resolve the group; the group waiter count now keeps + * the group alive for the duration of the wait. + */ + + nxsched_put_tcb(ctcb); + ctcb = NULL; if ((options & WNOHANG) != 0) { @@ -288,6 +296,7 @@ pid_t nxsched_waitpid(pid_t pid, FAR int *stat_loc, int options) } } + nxsched_put_tcb(ctcb); leave_critical_section(flags); return ret; diff --git a/sched/semaphore/sem_wait.c b/sched/semaphore/sem_wait.c index 4896ba0ebaf74..0985ad0b5b912 100644 --- a/sched/semaphore/sem_wait.c +++ b/sched/semaphore/sem_wait.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -151,6 +152,7 @@ int nxsem_wait_slow(FAR sem_t *sem) } unlocked = htcb == NULL; + nxsched_put_tcb(htcb); } else { diff --git a/sched/signal/sig_dispatch.c b/sched/signal/sig_dispatch.c index 0c0eaac22ea26..f74d004c6ac7b 100644 --- a/sched/signal/sig_dispatch.c +++ b/sched/signal/sig_dispatch.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -80,6 +81,7 @@ static int sig_handler(FAR void *cookie) /* There is no TCB with this pid or, if there is, it is not a task. */ leave_critical_section(flags); + nxsched_put_tcb(tcb); return -ESRCH; } @@ -94,6 +96,8 @@ static int sig_handler(FAR void *cookie) } leave_critical_section(flags); + nxsched_put_tcb(tcb); + return OK; } #endif @@ -612,6 +616,7 @@ static int nxsig_wake_waiter(pid_t pid, FAR void *arg) } } + nxsched_put_tcb(tcb); return 0; } #endif @@ -1113,6 +1118,7 @@ int nxsig_dispatch(pid_t pid, FAR siginfo_t *info, bool thread, if (stcb != NULL) { ret = nxsig_tcbdispatch(stcb, info, false, source, limit); + nxsched_put_tcb(stcb); } } @@ -1145,6 +1151,7 @@ bool nxsig_source_queued(pid_t pid, FAR const void *source, int signo) flags = enter_critical_section(); tcb = nxsched_get_tcb(pid); group = tcb != NULL ? tcb->group : NULL; + nxsched_put_tcb(tcb); if (group == NULL) { leave_critical_section(flags); diff --git a/sched/signal/sig_kill.c b/sched/signal/sig_kill.c index 7b0a10939c99a..f5d7805fcf9a7 100644 --- a/sched/signal/sig_kill.c +++ b/sched/signal/sig_kill.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -155,6 +156,7 @@ int nxsig_kill_target(pid_t pid) int ret = -ESRCH; int tflags; #ifdef CONFIG_SCHED_CHILD_STATUS + FAR struct tcb_s *ptcb; int ndx; #endif @@ -182,10 +184,10 @@ int nxsig_kill_target(pid_t pid) for (ndx = 0; ndx < g_npidhash && ret < 0; ndx++) { - tcb = g_pidhash[ndx]; - if (tcb != NULL && tcb->group != NULL && - tcb->pid == tcb->group->tg_pid && - group_find_child(tcb->group, pid) != NULL) + ptcb = g_pidhash[ndx]; + if (ptcb != NULL && ptcb->group != NULL && + ptcb->pid == ptcb->group->tg_pid && + group_find_child(ptcb->group, pid) != NULL) { ret = 0; } @@ -193,6 +195,7 @@ int nxsig_kill_target(pid_t pid) #endif leave_critical_section(flags); + nxsched_put_tcb(tcb); return ret; } @@ -238,12 +241,13 @@ int nxsig_kill_target(pid_t pid) int nxsig_kill(pid_t pid, int signo) { + int ret = -EINVAL; + #if !defined(CONFIG_DISABLE_ALL_SIGNALS) && defined(CONFIG_SCHED_HAVE_PARENT) FAR struct tcb_s *rtcb = this_task(); #endif #ifndef CONFIG_DISABLE_ALL_SIGNALS siginfo_t info; - int ret = -EINVAL; #endif int target; diff --git a/sched/signal/sig_notification.c b/sched/signal/sig_notification.c index 063392f448799..844401031d532 100644 --- a/sched/signal/sig_notification.c +++ b/sched/signal/sig_notification.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -119,9 +120,12 @@ int nxsig_event_valid(FAR const struct sigevent *event) target = nxsched_get_tcb(event->sigev_notify_thread_id); if (target == NULL || target->group != nxsched_self()->group) { + nxsched_put_tcb(target); return -EINVAL; } + nxsched_put_tcb(target); + return OK; } diff --git a/sched/signal/sig_tgkill.c b/sched/signal/sig_tgkill.c index 810eaf5a0fc9b..8ab9fd551d6c0 100644 --- a/sched/signal/sig_tgkill.c +++ b/sched/signal/sig_tgkill.c @@ -88,7 +88,10 @@ int nxsig_tgkill(pid_t pid, pid_t tid, int signo) if (signo == 0) { - return (nxsched_get_tcb(tid) != NULL) ? 0 : -ESRCH; + FAR struct tcb_s *stcb = nxsched_get_tcb(tid); + + nxsched_put_tcb(stcb); + return (stcb != NULL) ? 0 : -ESRCH; } #ifdef CONFIG_DISABLE_ALL_SIGNALS diff --git a/sched/task/task_delete.c b/sched/task/task_delete.c index 9ab20921a2245..3d5d488845078 100644 --- a/sched/task/task_delete.c +++ b/sched/task/task_delete.c @@ -108,6 +108,7 @@ int nxtask_delete(pid_t pid) if (((rtcb->flags & TCB_FLAG_TTYPE_MASK) != TCB_FLAG_TTYPE_KERNEL) && ((dtcb->flags & TCB_FLAG_TTYPE_MASK) == TCB_FLAG_TTYPE_KERNEL)) { + nxsched_put_tcb(dtcb); return -EACCES; } @@ -119,6 +120,7 @@ int nxtask_delete(pid_t pid) * don't bother to unlock the TCB since it will be going away. */ + nxsched_put_tcb(dtcb); _exit(EXIT_SUCCESS); } @@ -126,9 +128,12 @@ int nxtask_delete(pid_t pid) if (nxnotify_cancellation(dtcb)) { + nxsched_put_tcb(dtcb); return OK; } + nxsched_put_tcb(dtcb); + /* Otherwise, perform the asynchronous cancellation, letting * nxtask_terminate() do all of the heavy lifting. */ diff --git a/sched/task/task_exithook.c b/sched/task/task_exithook.c index dc38057c4eb51..0ca9b7bc20d84 100644 --- a/sched/task/task_exithook.c +++ b/sched/task/task_exithook.c @@ -388,6 +388,7 @@ static inline void nxtask_signalparent(FAR struct tcb_s *ctcb, int status) */ nxtask_sigchild(ptcb, ctcb, status); + nxsched_put_tcb(ptcb); #endif } #else diff --git a/sched/task/task_fork.c b/sched/task/task_fork.c index 706fb7419e782..38524efc23c11 100644 --- a/sched/task/task_fork.c +++ b/sched/task/task_fork.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -209,7 +210,7 @@ static void fork_restore_parent_env(void) FAR struct tcb_s *nxtask_setup_fork(start_t retaddr, bool vfork) { FAR struct tcb_s *ptcb = this_task(); - FAR struct tcb_s *parent; + FAR struct tcb_s *parent = NULL; FAR struct tcb_s *child; FAR char **argv; size_t stack_size; @@ -264,6 +265,8 @@ FAR struct tcb_s *nxtask_setup_fork(start_t retaddr, bool vfork) nxtask_joininit(child); + nxsem_init(&child->exit_sem, 0, 0); + /* Allocate a new task group with the same privileges as the parent */ ret = group_allocate(child, ttype); @@ -483,6 +486,11 @@ FAR struct tcb_s *nxtask_setup_fork(start_t retaddr, bool vfork) group_initialize(child); sinfo("parent=%p, returning child=%p\n", parent, child); + if (parent != ptcb) + { + nxsched_put_tcb(parent); + } + return child; errout_with_tcb: @@ -499,8 +507,22 @@ FAR struct tcb_s *nxtask_setup_fork(start_t retaddr, bool vfork) } #endif + /* The pid hash slot may still hold the only reference: release it + * before the TCB, nxsched_release_tcb() no longer does it. + */ + + if (child->pid) + { + nxsched_releasepid(child->pid); + } + nxsched_release_tcb((FAR struct tcb_s *)child, ttype); errout: + if (parent != ptcb) + { + nxsched_put_tcb(parent); + } + set_errno(-ret); return NULL; } @@ -661,6 +683,11 @@ void nxtask_abort_fork(FAR struct tcb_s *child, int errcode) /* Release the TCB */ + if (child->pid) + { + nxsched_releasepid(child->pid); + } + nxsched_release_tcb(child, child->flags & TCB_FLAG_TTYPE_MASK); set_errno(errcode); } diff --git a/sched/task/task_getgroup.c b/sched/task/task_getgroup.c index a25a2d754bbbf..041cce0d2b188 100644 --- a/sched/task/task_getgroup.c +++ b/sched/task/task_getgroup.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include @@ -62,7 +63,10 @@ FAR struct task_group_s *task_getgroup(pid_t pid) if (tcb) { - return tcb->group; + struct task_group_s *group = tcb->group; + + nxsched_put_tcb(tcb); + return group; } return NULL; diff --git a/sched/task/task_init.c b/sched/task/task_init.c index 157e07e2dc260..f03b4de021994 100644 --- a/sched/task/task_init.c +++ b/sched/task/task_init.c @@ -174,6 +174,8 @@ int nxtask_init(FAR struct tcb_s *tcb, const char *name, int priority, nxtask_joininit(tcb); #endif + nxsem_init(&tcb->exit_sem, 0, 0); + /* Duplicate the parent tasks environment */ ret = env_dup(tcb->group->tg_info, envp); @@ -300,6 +302,8 @@ int nxtask_init(FAR struct tcb_s *tcb, const char *name, int priority, nxtask_joindestroy(tcb); + nxsem_destroy(&tcb->exit_sem); + group_leave(tcb); sched_trace_end(); @@ -335,5 +339,14 @@ void nxtask_uninit(FAR struct tcb_s *tcb) * itself. */ + /* The pid hash slot still holds the only reference: release it + * before the TCB, nxsched_release_tcb() no longer does it. + */ + + if (tcb->pid) + { + nxsched_releasepid(tcb->pid); + } + nxsched_release_tcb(tcb, tcb->flags & TCB_FLAG_TTYPE_MASK); } diff --git a/sched/task/task_prctl.c b/sched/task/task_prctl.c index 9bdd1ad63c5f1..475407f88a6b2 100644 --- a/sched/task/task_prctl.c +++ b/sched/task/task_prctl.c @@ -79,6 +79,7 @@ int prctl(int option, ...) FAR char *name = va_arg(ap, FAR char *); FAR struct tcb_s *tcb; + irqstate_t flags; int pid = 0; if (option == PR_SET_NAME_EXT || @@ -97,6 +98,8 @@ int prctl(int option, ...) * of pid==0 meaning "this thread") */ + flags = enter_critical_section(); + if (pid == 0) { tcb = this_task(); @@ -112,6 +115,7 @@ int prctl(int option, ...) if (tcb == NULL) { + leave_critical_section(flags); serr("ERROR: Pid does not correspond to a task: %d\n", pid); errcode = ESRCH; goto errout; @@ -123,6 +127,12 @@ int prctl(int option, ...) { serr("ERROR: No name provide\n"); errcode = EFAULT; + leave_critical_section(flags); + if (pid != 0) + { + nxsched_put_tcb(tcb); + } + goto errout; } @@ -145,6 +155,12 @@ int prctl(int option, ...) strlcpy(name, tcb->name, CONFIG_TASK_NAME_SIZE); } + + leave_critical_section(flags); + if (pid != 0) + { + nxsched_put_tcb(tcb); + } } break; #else diff --git a/sched/task/task_reparent.c b/sched/task/task_reparent.c index 9b92c293cd701..4420065b45c53 100644 --- a/sched/task/task_reparent.c +++ b/sched/task/task_reparent.c @@ -96,6 +96,7 @@ int task_reparent(pid_t ppid, pid_t chpid) /* Get the PID of the old parent task's task group (opid) */ opid = chgrp->tg_ppid; + nxsched_put_tcb(tcb); /* Get the old parent task's task group (ogrp) */ @@ -137,6 +138,7 @@ int task_reparent(pid_t ppid, pid_t chpid) pgrp = tcb->group; ppid = pgrp->tg_pid; + nxsched_put_tcb(tcb); } if (!pgrp) @@ -219,9 +221,9 @@ int task_reparent(pid_t ppid, pid_t chpid) #ifdef CONFIG_SCHED_CHILD_STATUS FAR struct child_status_s *child; #endif - FAR struct tcb_s *ptcb; - FAR struct tcb_s *chtcb; - FAR struct tcb_s *otcb; + FAR struct tcb_s *ptcb = NULL; + FAR struct tcb_s *chtcb = NULL; + FAR struct tcb_s *otcb = NULL; pid_t opid; irqstate_t flags; #ifndef CONFIG_SCHED_CHILD_STATUS @@ -347,6 +349,10 @@ int task_reparent(pid_t ppid, pid_t chpid) errout_with_ints: leave_critical_section(flags); + nxsched_put_tcb(ptcb); + nxsched_put_tcb(otcb); + nxsched_put_tcb(chtcb); + return ret; } #endif diff --git a/sched/task/task_restart.c b/sched/task/task_restart.c index d39b4b79f3732..33453cd3d1b09 100644 --- a/sched/task/task_restart.c +++ b/sched/task/task_restart.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -72,6 +73,7 @@ static int restart_handler(FAR void *cookie) /* There is no TCB with this pid or, if there is, it is not a task. */ leave_critical_section(flags); + nxsched_put_tcb(tcb); return -ESRCH; } @@ -84,6 +86,8 @@ static int restart_handler(FAR void *cookie) leave_critical_section(flags); + nxsched_put_tcb(tcb); + return OK; } #endif @@ -187,7 +191,7 @@ static void nxtask_reset_task(FAR struct tcb_s *tcb, bool remove) static int nxtask_restart(pid_t pid) { FAR struct tcb_s *rtcb; - FAR struct tcb_s *tcb; + FAR struct tcb_s *tcb = NULL; irqstate_t flags; int ret; @@ -232,6 +236,7 @@ static int nxtask_restart(pid_t pid) tcb->cpu != this_cpu()) { struct restart_arg_s arg; + int cpu = tcb->cpu; arg.pid = tcb->pid; if (atomic_or(&tcb->shared_flags, TCB_FLAG_CPU_LOCKED) & @@ -244,7 +249,8 @@ static int nxtask_restart(pid_t pid) arg.need_restore = true; } - nxsched_smp_call_single(tcb->cpu, restart_handler, &arg); + nxsched_put_tcb(tcb); + nxsched_smp_call_single(cpu, restart_handler, &arg); tcb = nxsched_get_tcb(pid); if (!tcb || tcb->task_state != TSTATE_TASK_INVALID || @@ -262,7 +268,7 @@ static int nxtask_restart(pid_t pid) /* Activate the task. */ nxtask_activate(tcb); - + nxsched_put_tcb(tcb); return OK; } #endif /* CONFIG_SMP */ @@ -303,9 +309,11 @@ static int nxtask_restart(pid_t pid) /* Activate the task. */ nxtask_activate(tcb); + nxsched_put_tcb(tcb); return OK; errout_with_lock: + nxsched_put_tcb(tcb); leave_critical_section(flags); return ret; } diff --git a/sched/task/task_setup.c b/sched/task/task_setup.c index 000b92872d04d..461c7002be2e6 100644 --- a/sched/task/task_setup.c +++ b/sched/task/task_setup.c @@ -119,6 +119,7 @@ static int nxtask_assign_pid(FAR struct tcb_s *tcb) g_pidhash[hash_ndx] = tcb; tcb->pid = next_pid; + atomic_set(&tcb->refs, 1); g_lastpid = next_pid; leave_critical_section(flags); diff --git a/sched/task/task_spawnparms.c b/sched/task/task_spawnparms.c index 0e5c2db3021ab..69279e3d00f95 100644 --- a/sched/task/task_spawnparms.c +++ b/sched/task/task_spawnparms.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -161,6 +162,7 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) if (tcb) { tcb->sigprocmask = attr->sigmask; + nxsched_put_tcb(tcb); } } #endif @@ -176,6 +178,7 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) { tcb->group->tg_pgid = tcb->group->tg_pid; tcb->group->tg_sid = tcb->group->tg_pid; + nxsched_put_tcb(tcb); } } diff --git a/sched/task/task_terminate.c b/sched/task/task_terminate.c index 724d1d96ed583..c79d41f6ff71a 100644 --- a/sched/task/task_terminate.c +++ b/sched/task/task_terminate.c @@ -49,26 +49,17 @@ * Private Functions ****************************************************************************/ -static int terminat_handler(FAR void *cookie) +static int terminate_handler(FAR void *cookie) { - pid_t pid = (pid_t)(uintptr_t)cookie; - FAR struct tcb_s *tcb; + FAR struct tcb_s *tcb = (FAR struct tcb_s *)(uintptr_t)cookie; irqstate_t flags; - flags = enter_critical_section(); - tcb = nxsched_get_tcb(pid); - - if (!tcb) - { - /* There is no TCB with this pid or, if there is, it is not a task. */ - - leave_critical_section(flags); - return -ESRCH; - } + /* tcb is valid here */ + flags = enter_critical_section(); nxsched_remove_readytorun(tcb); - leave_critical_section(flags); + return OK; } #endif @@ -117,18 +108,23 @@ int nxtask_terminate(pid_t pid) uint8_t task_state; irqstate_t flags; - flags = enter_critical_section(); - /* Find for the TCB associated with matching PID */ dtcb = nxsched_get_tcb(pid); - if (!dtcb || (atomic_or(&dtcb->shared_flags, TCB_FLAG_EXIT_PROCESSING) & - TCB_FLAG_EXIT_PROCESSING) != 0) + if (!dtcb || (atomic_or(&dtcb->shared_flags, + TCB_FLAG_EXIT_PROCESSING) & TCB_FLAG_EXIT_PROCESSING) != 0) { - leave_critical_section(flags); return -ESRCH; } + /* Even if we decrease the reference count here, dtcb won't be released + * elsewhere, because it already has TCB_FLAG_EXIT_PROCESSING. + */ + + nxsched_put_tcb(dtcb); + + flags = enter_critical_section(); + /* Remove dtcb from tasklist, let remove_readtorun() do the job */ task_state = dtcb->task_state; @@ -141,8 +137,8 @@ int nxtask_terminate(pid_t pid) tcb_flags = atomic_or(&dtcb->shared_flags, TCB_FLAG_CPU_LOCKED); - ret = nxsched_smp_call_single(dtcb->cpu, terminat_handler, - (FAR void *)(uintptr_t)pid); + ret = nxsched_smp_call_single(dtcb->cpu, terminate_handler, + (FAR void *)(uintptr_t)dtcb); if (ret < 0) { diff --git a/sched/timer/timer_create.c b/sched/timer/timer_create.c index b5e8c5a2be923..8bbd3278826e9 100644 --- a/sched/timer/timer_create.c +++ b/sched/timer/timer_create.c @@ -133,7 +133,7 @@ static bool timer_cpu_getclockid(FAR clockid_t *clockid) return true; } - return nxsched_get_tcb(pid) != NULL; + return nxsched_verify_pid(pid); } #else # define timer_cpu_getclockid(c) false diff --git a/sched/timer/timer_initialize.c b/sched/timer/timer_initialize.c index f937ad64261ed..b4003ee588705 100644 --- a/sched/timer/timer_initialize.c +++ b/sched/timer/timer_initialize.c @@ -25,6 +25,7 @@ ****************************************************************************/ #include +#include #include #include @@ -226,6 +227,8 @@ FAR struct posix_timer_s *timer_gethandle(timer_t timerid) { timer = NULL; } + + nxsched_put_tcb(owner); } return timer; diff --git a/sched/wqueue/kwork_inherit.c b/sched/wqueue/kwork_inherit.c index a470607200671..6c85aedf68f26 100644 --- a/sched/wqueue/kwork_inherit.c +++ b/sched/wqueue/kwork_inherit.c @@ -72,6 +72,7 @@ static void lpwork_boostworker(pid_t wpid, uint8_t reqprio) if (wtcb->boost_priority != 0) { + nxsched_put_tcb(wtcb); return; } @@ -105,6 +106,8 @@ static void lpwork_boostworker(pid_t wpid, uint8_t reqprio) nxsched_set_priority(wtcb, reqprio); } } + + nxsched_put_tcb(wtcb); } /**************************************************************************** @@ -138,6 +141,7 @@ static void lpwork_restoreworker(pid_t wpid, uint8_t reqprio) if (wtcb->boost_priority != reqprio) { + nxsched_put_tcb(wtcb); return; } @@ -184,6 +188,8 @@ static void lpwork_restoreworker(pid_t wpid, uint8_t reqprio) nxsched_set_priority(wtcb, wpriority); } + + nxsched_put_tcb(wtcb); } /**************************************************************************** diff --git a/sched/wqueue/kwork_thread.c b/sched/wqueue/kwork_thread.c index b5c5f0d49415e..db73319e11af4 100644 --- a/sched/wqueue/kwork_thread.c +++ b/sched/wqueue/kwork_thread.c @@ -946,6 +946,7 @@ int work_queue_priority_wq(FAR struct kwork_wqueue_s *wqueue) { FAR struct kworker_s *worker; FAR struct tcb_s *tcb; + int pri; if (wqueue == NULL) { @@ -963,7 +964,10 @@ int work_queue_priority_wq(FAR struct kwork_wqueue_s *wqueue) return -ESRCH; } - return tcb->sched_priority; + pri = tcb->sched_priority; + nxsched_put_tcb(tcb); + + return pri; } int work_queue_priority(int qid) From cd9795fdf29e2c84856300f7d8e828b473bccee8 Mon Sep 17 00:00:00 2001 From: wangzhi16 Date: Thu, 20 Mar 2025 21:18:36 +0800 Subject: [PATCH 03/15] sched/backtrace: drop the TCB reference after taking the backtrace 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 --- sched/sched/sched_backtrace.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sched/sched/sched_backtrace.c b/sched/sched/sched_backtrace.c index 49c409fb14666..af2490a68afcd 100644 --- a/sched/sched/sched_backtrace.c +++ b/sched/sched/sched_backtrace.c @@ -101,11 +101,10 @@ static int sched_backtrace_handler(FAR void *cookie) atomic_and(&tcb->shared_flags, ~TCB_FLAG_CPU_LOCKED); } - nxsched_put_tcb(tcb); - leave_critical_section(flags); arg->stacksize = up_backtrace(tcb, arg->buffer, arg->size, arg->skip); + nxsched_put_tcb(tcb); return OK; } From 5a1ce5e61dad936392cf11dc0eca6d573ed6b3a7 Mon Sep 17 00:00:00 2001 From: huojianchao Date: Thu, 12 Nov 2026 21:53:44 +0800 Subject: [PATCH 04/15] signal: fix use-after-free of the group signal candidate TCBs 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 Signed-off-by: zhangyuan29 --- sched/group/group_signal.c | 59 ++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 24 deletions(-) diff --git a/sched/group/group_signal.c b/sched/group/group_signal.c index 3be1a19543be2..d29ed360fdb00 100644 --- a/sched/group/group_signal.c +++ b/sched/group/group_signal.c @@ -49,10 +49,10 @@ struct group_signal_s FAR siginfo_t *siginfo; /* Signal to be dispatched */ FAR const void *source; /* The POSIX timer of the signal, or NULL */ bool limit; /* Apply SIGQUEUE_MAX (sigqueue()) */ - FAR struct tcb_s *dtcb; /* Default, valid TCB */ - FAR struct tcb_s *utcb; /* TCB with this signal unblocked */ - FAR struct tcb_s *atcb; /* This TCB was awakened */ - FAR struct tcb_s *ptcb; /* This TCB received the signal */ + pid_t dpid; /* Default, valid pid */ + pid_t upid; /* pid with this signal unblocked */ + pid_t apid; /* This pid was awakened */ + pid_t ppid; /* This pid received the signal */ }; #endif @@ -94,9 +94,9 @@ static int group_signal_handler(pid_t pid, FAR void *arg) * default. */ - if (!info->dtcb) + if (!info->dpid) { - info->dtcb = tcb; + info->dpid = pid; } /* Is the thread waiting for this signal (in this case, the signal is @@ -104,7 +104,7 @@ static int group_signal_handler(pid_t pid, FAR void *arg) */ if (nxsig_ismember(&tcb->sigwaitmask, info->siginfo->si_signo) == 1 && - (!info->atcb || info->siginfo->si_signo == SIGCHLD)) + (!info->apid || info->siginfo->si_signo == SIGCHLD)) { /* Yes.. This means that the task is suspended, waiting for this * signal to occur. Stop looking and use this TCB. The @@ -123,9 +123,9 @@ static int group_signal_handler(pid_t pid, FAR void *arg) /* Limit to one thread */ - info->atcb = tcb; + info->apid = pid; - if (info->ptcb != NULL && info->siginfo->si_signo != SIGCHLD) + if (info->ppid != 0 && info->siginfo->si_signo != SIGCHLD) { ret = 1; /* Terminate the search */ goto errout; @@ -135,15 +135,15 @@ static int group_signal_handler(pid_t pid, FAR void *arg) /* Is this signal unblocked on this thread? */ if ((nxsig_ismember(&tcb->sigprocmask, info->siginfo->si_signo) != 1) && - !info->ptcb && tcb != info->atcb) + !info->ppid && pid != info->apid) { /* Yes.. remember this TCB if we have not encountered any * other threads that have the signal unblocked. */ - if (!info->utcb) + if (!info->upid) { - info->utcb = tcb; + info->upid = pid; } /* Is there also a action associated with the task group? */ @@ -167,8 +167,8 @@ static int group_signal_handler(pid_t pid, FAR void *arg) /* Limit to one thread */ - info->ptcb = tcb; - if (info->atcb != NULL) + info->ppid = pid; + if (info->apid != 0) { ret = 1; /* Terminate the search */ goto errout; @@ -214,6 +214,7 @@ int group_signal(FAR struct task_group_s *group, FAR siginfo_t *siginfo, #ifdef HAVE_GROUP_MEMBERS struct group_signal_s info; FAR struct tcb_s *tcb; + pid_t pid; int ret; DEBUGASSERT(group && siginfo); @@ -221,10 +222,10 @@ int group_signal(FAR struct task_group_s *group, FAR siginfo_t *siginfo, info.siginfo = siginfo; info.source = source; info.limit = limit; - info.dtcb = NULL; /* Default, valid TCB */ - info.utcb = NULL; /* TCB with this signal unblocked */ - info.atcb = NULL; /* This TCB was awakened */ - info.ptcb = NULL; /* This TCB received the signal */ + info.dpid = 0; /* Default, valid pid */ + info.upid = 0; /* pid with this signal unblocked */ + info.apid = 0; /* This pid was awakened */ + info.ppid = 0; /* This pid received the signal */ /* Make sure that pre-emption is disabled to that we signal all of the * members of the group before any of them actually run. (This does @@ -250,11 +251,11 @@ int group_signal(FAR struct task_group_s *group, FAR siginfo_t *siginfo, * signal unblocked, then use that thread. */ - if (info.atcb == NULL && info.ptcb == NULL) + if (info.apid == 0 && info.ppid == 0) { - if (info.utcb) + if (info.upid) { - tcb = info.utcb; + pid = info.upid; } /* Otherwise use the default TCB. There should always be a default @@ -262,9 +263,9 @@ int group_signal(FAR struct task_group_s *group, FAR siginfo_t *siginfo, * signal to a pending state. */ - else if (info.dtcb) + else if (info.dpid) { - tcb = info.dtcb; + pid = info.dpid; } else { @@ -274,7 +275,17 @@ int group_signal(FAR struct task_group_s *group, FAR siginfo_t *siginfo, /* Now deliver the signal to the selected group member */ - ret = nxsig_tcbdispatch(tcb, siginfo, true, source, limit); + tcb = nxsched_get_tcb(pid); + if (tcb) + { + ret = nxsig_tcbdispatch(tcb, siginfo, true, source, limit); + } + else + { + ret = -ESRCH; + } + + nxsched_put_tcb(tcb); } errout: From c78d4ea5e5d35ddd9233c651ae6d45558d7f5369 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Tue, 13 May 2025 18:09:52 +0800 Subject: [PATCH 05/15] sched/tcb: do not count a reference of the running task on itself 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 --- sched/sched/sched_gettcb.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/sched/sched/sched_gettcb.c b/sched/sched/sched_gettcb.c index 11346e97e993e..54ac8e277b205 100644 --- a/sched/sched/sched_gettcb.c +++ b/sched/sched/sched_gettcb.c @@ -75,7 +75,7 @@ FAR struct tcb_s *nxsched_get_tcb(pid_t pid) } } - if (ret) + if (ret && ret != running_task()) { if (!up_interrupt_context()) { @@ -109,7 +109,18 @@ FAR struct tcb_s *nxsched_get_tcb(pid_t pid) void nxsched_put_tcb(FAR struct tcb_s *tcb) { - if (!tcb) + FAR struct tcb_s *rtcb; +#ifdef CONFIG_SMP + irqstate_t flags; + + flags = up_irq_save(); + rtcb = running_task(); + up_irq_restore(flags); +#else + rtcb = running_task(); +#endif + + if (!tcb || tcb == rtcb) { return; } From 85e163cbb09db0347949e427e6aa5a0eda150170 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Thu, 29 May 2025 08:09:40 +0800 Subject: [PATCH 06/15] exit: move the position of nxsched_releasepid backward. 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 Signed-off-by: zhangyuan29 --- sched/pthread/pthread_exit.c | 8 ++++++-- sched/task/exit.c | 14 ++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/sched/pthread/pthread_exit.c b/sched/pthread/pthread_exit.c index 260fba16548f3..f99bb6940dfba 100644 --- a/sched/pthread/pthread_exit.c +++ b/sched/pthread/pthread_exit.c @@ -122,8 +122,6 @@ void nx_pthread_exit(FAR void *exit_value) * The IRQ state will be restored when the next task is started. */ - nxsched_releasepid(tcb->pid); - enter_critical_section(); /* Perform common task termination logic. This will get called again later @@ -140,5 +138,11 @@ void nx_pthread_exit(FAR void *exit_value) nxtask_exithook(tcb, status); + /* In nxtask_exithook, nxmutex_lock is used, and nxmutex_lock depends + * on nxsched_get_tcb. Therefore, we move nxsched_releasepid + * to this position. + */ + + nxsched_releasepid(tcb->pid); up_exit(EXIT_SUCCESS); } diff --git a/sched/task/exit.c b/sched/task/exit.c index 7d20fd1c443c5..2501806d1c46a 100644 --- a/sched/task/exit.c +++ b/sched/task/exit.c @@ -74,12 +74,6 @@ void _exit(int status) #endif - /* Make sure that we are in a critical section with local interrupts. - * The IRQ state will be restored when the next task is started. - */ - - enter_critical_section(); - /* Perform common task termination logic. This will get called again later * through logic kicked off by up_exit(). * @@ -94,7 +88,15 @@ void _exit(int status) atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING); + enter_critical_section(); + nxtask_exithook(tcb, status); + /* In nxtask_exithook, nxmutex_lock is used, and nxmutex_lock depends + * on nxsched_get_tcb. Therefore, we move nxsched_releasepid + * to this position. + */ + + nxsched_releasepid(tcb->pid); up_exit(status); } From a2a1df758e75cac9dc6b8998a8a4ba9bc50ba6ed Mon Sep 17 00:00:00 2001 From: buxiasen Date: Wed, 17 Dec 2025 11:15:51 +0800 Subject: [PATCH 07/15] sched/exit: fix release pid outof critical_section 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 Signed-off-by: zhangyuan29 --- sched/task/task_terminate.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sched/task/task_terminate.c b/sched/task/task_terminate.c index c79d41f6ff71a..8c69eb0bdd316 100644 --- a/sched/task/task_terminate.c +++ b/sched/task/task_terminate.c @@ -170,6 +170,12 @@ int nxtask_terminate(pid_t pid) nxtask_exithook(dtcb, EXIT_SUCCESS); + /* Release the task's PID sequence should align with + * nx_pthread_exit, with in critical_section and after exit hook. + */ + + nxsched_releasepid(pid); + leave_critical_section(flags); /* Since all tasks pass through this function as the final step in their * exit sequence, this is an appropriate place to inform any From 8bad141185120dabe8cb13976d5c95437d42ffbc Mon Sep 17 00:00:00 2001 From: anpeiyun Date: Tue, 13 Oct 2026 11:48:11 +0800 Subject: [PATCH 08/15] sched/signal: do not deliver signals for a thread that is exiting 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 Signed-off-by: zhangyuan29 --- sched/signal/sig_deliver.c | 29 ++++++++++++++++++++++++++++- sched/signal/sig_pending.c | 11 +++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/sched/signal/sig_deliver.c b/sched/signal/sig_deliver.c index 1cfa3739bf72b..30b4f859a5d77 100644 --- a/sched/signal/sig_deliver.c +++ b/sched/signal/sig_deliver.c @@ -65,6 +65,7 @@ void nxsig_deliver(FAR struct tcb_s *stcb) FAR sigq_t *sigq; sigset_t savesigprocmask; sigset_t newsigprocmask; + uint32_t tcbflags; sigset_t tmpset1; sigset_t tmpset2; irqstate_t flags; @@ -73,11 +74,37 @@ void nxsig_deliver(FAR struct tcb_s *stcb) for (; ; ) { + flags = enter_critical_section(); + tcbflags = atomic_read(&stcb->shared_flags); + + /* An exiting thread must not run signal actions: its task group may + * already be released. Unlink the action queue under the lock and + * release it after unlocking, so that the trampoline cannot retry. + */ + + if ((tcbflags & (TCB_FLAG_EXIT_PROCESSING | + TCB_FLAG_KILL_PROCESSING)) != 0) + { + FAR sigq_t *next = (FAR sigq_t *)stcb->sigpendactionq.head; + + sq_init(&stcb->sigpendactionq); + leave_critical_section(flags); + + while (next != NULL) + { + FAR sigq_t *rest = (FAR sigq_t *)next->flink; + + nxsig_release_pendingsigaction(next); + next = rest; + } + + break; + } + /* Test if this task is already handling a signal (we don't permit * nested signals on the same thread). */ - flags = enter_critical_section(); if ((stcb->flags & TCB_FLAG_SIGNAL_ACTION) != 0) { /* Yes.. then we must wait for the signal handler to return */ diff --git a/sched/signal/sig_pending.c b/sched/signal/sig_pending.c index 0b856464db3d1..6fdae9e785363 100644 --- a/sched/signal/sig_pending.c +++ b/sched/signal/sig_pending.c @@ -89,6 +89,17 @@ sigset_t nxsig_pendingset(FAR struct tcb_s *stcb) stcb = this_task(); } + /* An exiting thread may already have lost its task group; its signal + * queues are gone, so report no pending signal and leave the group alone. + */ + + if ((atomic_read(&stcb->shared_flags) & + (TCB_FLAG_EXIT_PROCESSING | TCB_FLAG_KILL_PROCESSING)) != 0) + { + sigemptyset(&sigpendset); + return sigpendset; + } + group = stcb->group; DEBUGASSERT(group); From 636cffa4df643ee805adc5bad25f3f4dafb549b9 Mon Sep 17 00:00:00 2001 From: zhangyuan29 Date: Tue, 24 Nov 2026 18:27:05 +0800 Subject: [PATCH 09/15] sched/tcb: let a killed task drop its TCB references before removal 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 --- include/nuttx/sched.h | 4 +++ sched/pthread/pthread_exit.c | 30 ++++++++++-------- sched/sched/sched_gettcb.c | 41 ++++++++++++++++-------- sched/sched/sched_suspend.c | 10 ++++++ sched/sched/sched_waitid.c | 13 +++++++- sched/task/exit.c | 6 ++++ sched/task/task.h | 1 + sched/task/task_restart.c | 61 ++++++++++++++++++++++++++++++++---- sched/task/task_terminate.c | 52 ++++++++++++++++++++++++++++++ 9 files changed, 185 insertions(+), 33 deletions(-) diff --git a/include/nuttx/sched.h b/include/nuttx/sched.h index 60cbc0d20233b..6e9c9f0666872 100644 --- a/include/nuttx/sched.h +++ b/include/nuttx/sched.h @@ -701,6 +701,10 @@ struct tcb_s atomic_t refs; + /* The total number of references that we hold on other tasks */ + + atomic_t holds; + /* When we exit, we need post this sem. */ sem_t exit_sem; diff --git a/sched/pthread/pthread_exit.c b/sched/pthread/pthread_exit.c index f99bb6940dfba..2e4b7ce91f8a8 100644 --- a/sched/pthread/pthread_exit.c +++ b/sched/pthread/pthread_exit.c @@ -69,15 +69,12 @@ void nx_pthread_exit(FAR void *exit_value) #ifndef CONFIG_DISABLE_ALL_SIGNALS sigset_t set; #endif - irqstate_t flags; int status; sinfo("exit_value=%p\n", exit_value); DEBUGASSERT(tcb != NULL); - atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING); - /* Block any signal actions that would awaken us while were * are performing the JOIN handshake. */ @@ -99,24 +96,31 @@ void nx_pthread_exit(FAR void *exit_value) _exit(EXIT_FAILURE); } - flags = enter_critical_section(); - if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) - { - leave_critical_section(flags); + /* If the TCB is already in the exiting state, we should allow the + * killing task to execute normally first. We stop the execution here. + * The flag is set late, after the join handshake: setting it here + * would refuse the signals that the join handshake still exchanges. + */ - /* If the TCB is already in the exiting state, we - * should allow the killing task to execute normally first. - * We stop the execution here. - */ + /* Set-and-test, like _exit(): if nxtask_terminate() won the + * arbitration in the same window, it tears the thread down and we + * park instead of racing it through the exit path. + */ + if ((atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING) & + TCB_FLAG_EXIT_PROCESSING) != 0) + { for (; ; ) { usleep(1000); } } - atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING); - leave_critical_section(flags); + /* A thread leaving on its own must have dropped every reference it + * took: kernel paths finish before pthread_exit() can be called. + */ + + DEBUGASSERT(atomic_read(&tcb->holds) == 0); /* Make sure that we are in a critical section with local interrupts. * The IRQ state will be restored when the next task is started. diff --git a/sched/sched/sched_gettcb.c b/sched/sched/sched_gettcb.c index 54ac8e277b205..08b4f7fb16e02 100644 --- a/sched/sched/sched_gettcb.c +++ b/sched/sched/sched_gettcb.c @@ -27,6 +27,7 @@ #include #include +#include #include "nuttx/irq.h" @@ -87,7 +88,7 @@ FAR struct tcb_s *nxsched_get_tcb(pid_t pid) * number of references that this_task makes to other tasks. */ - atomic_add(&this_task()->refs, 1); + atomic_add(&this_task()->holds, 1); } atomic_add(&ret->refs, 1); @@ -141,26 +142,40 @@ void nxsched_put_tcb(FAR struct tcb_s *tcb) tcb = this_task(); - DEBUGASSERT(atomic_read(&tcb->refs) > 0); + DEBUGASSERT(atomic_read(&tcb->holds) > 0); + + /* this_task may be killed and in KILL_PROCESSING: nxtask_terminate() + * sets the flag before it reads holds, so order our decrement before + * the flag read. + */ + + bool last = atomic_sub(&tcb->holds, 1) == 1; - /* this_task may be killed and in KILL_PROCESSING */ + SMP_MB(); - if (atomic_sub(&tcb->refs, 1) == 1 && - (atomic_read(&tcb->shared_flags) & TCB_FLAG_KILL_PROCESSING)) + if (last && + (atomic_read(&tcb->shared_flags) & + (TCB_FLAG_KILL_PROCESSING | TCB_FLAG_EXIT_PROCESSING)) != 0) { + /* Wake nxtask_terminate() or nxtask_restart() waiting for the + * references to be dropped. + */ + nxsem_post(&tcb->exit_sem); - /* If the TCB is already in the exiting state, we - * should allow the exiting task to execute normally first. - * We stop the execution here. - * - * If it continues to run, it may happen that we obtain - * the TCB again and it gets killed. + /* A killed task stops here: if it kept running it could take the + * TCB again and be killed again. A restarted task must keep + * running until it is reset. */ - for (; ; ) + if ((atomic_read(&tcb->shared_flags) & + TCB_FLAG_KILL_PROCESSING) != 0) { - usleep(1000); + for (; ; ) + { + usleep(1000); + } } } } + diff --git a/sched/sched/sched_suspend.c b/sched/sched/sched_suspend.c index 9e14c54a56b0a..670d1779f31aa 100644 --- a/sched/sched/sched_suspend.c +++ b/sched/sched/sched_suspend.c @@ -115,6 +115,16 @@ void nxsched_suspend(FAR struct tcb_s *tcb) flags = enter_critical_section(); + /* A task being terminated must not stop: nxtask_terminate() waits for + * it to drop its TCB references. + */ + + if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) + { + leave_critical_section(flags); + return; + } + #ifdef CONFIG_ENABLE_ALL_SIGNALS /* Check if received SIGCONT */ diff --git a/sched/sched/sched_waitid.c b/sched/sched/sched_waitid.c index deb368540856e..c1c2ef4ca01c4 100644 --- a/sched/sched/sched_waitid.c +++ b/sched/sched/sched_waitid.c @@ -128,7 +128,18 @@ static void report_child(FAR struct tcb_s *rtcb, static void child_handler(FAR struct tcb_s *tcb, FAR void *arg) { FAR struct child_search_s *search = arg; - FAR struct task_group_s *group = tcb->group; + FAR struct task_group_s *group; + + /* An exiting task may already have lost its task group; the reference + * nxsched_foreach() holds keeps the TCB alive, not the group. + */ + + if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) + { + return; + } + + group = tcb->group; if (group == NULL || group == search->group || group->tg_ppid != search->group->tg_pid) diff --git a/sched/task/exit.c b/sched/task/exit.c index 2501806d1c46a..8cefe7f783f0b 100644 --- a/sched/task/exit.c +++ b/sched/task/exit.c @@ -88,6 +88,12 @@ void _exit(int status) atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING); + /* A task leaving on its own must have dropped every reference it + * took: kernel paths finish before exit() can be called. + */ + + DEBUGASSERT(atomic_read(&tcb->holds) == 0); + enter_critical_section(); nxtask_exithook(tcb, status); diff --git a/sched/task/task.h b/sched/task/task.h index efdaf519ad5bb..22e6df3bc43aa 100644 --- a/sched/task/task.h +++ b/sched/task/task.h @@ -59,6 +59,7 @@ void nxtask_setup_name(FAR struct tcb_s *tcb, FAR const char *name); int nxtask_exit(void); int nxtask_terminate(pid_t pid); +void nxtask_wait_holds(FAR struct tcb_s *tcb); void nxtask_exithook(FAR struct tcb_s *tcb, int status); void nxtask_recover(FAR struct tcb_s *tcb); diff --git a/sched/task/task_restart.c b/sched/task/task_restart.c index 33453cd3d1b09..d8da83862c4f5 100644 --- a/sched/task/task_restart.c +++ b/sched/task/task_restart.c @@ -67,8 +67,7 @@ static int restart_handler(FAR void *cookie) /* tcb that we want restart */ tcb = nxsched_get_tcb(arg->pid); - if (!tcb || tcb->task_state == TSTATE_TASK_INVALID || - (atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) + if (!tcb || tcb->task_state == TSTATE_TASK_INVALID) { /* There is no TCB with this pid or, if there is, it is not a task. */ @@ -231,6 +230,48 @@ static int nxtask_restart(pid_t pid) goto errout_with_lock; } + if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_EXIT_PROCESSING) != 0) + { + ret = -ESRCH; + goto errout_with_lock; + } + + /* As in nxtask_terminate(), keep others from ending the task and let it + * drop the references it holds before it is reset. + */ + + /* EXIT_PROCESSING only: KILL_PROCESSING would park the target in + * nxsched_put_tcb() at its next put, but a restarted task must keep + * running until it is reset. The references it holds are still dropped + * by the task itself; a task blocked indefinitely between get and put + * delays the restart, as before. A reference taken between + * nxtask_wait_holds() returning and the removal below is lost with + * the discarded context: a known limitation of not parking here. + */ + + /* Set-and-test: if nxtask_terminate() won the arbitration in the + * same window, it owns the teardown and this restart must fail + * instead of resetting a TCB being released. + */ + + if ((atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING) & + TCB_FLAG_EXIT_PROCESSING) != 0) + { + ret = -ESRCH; + goto errout_with_lock; + } + + nxsched_put_tcb(tcb); + leave_critical_section(flags); + nxtask_wait_holds(tcb); + flags = enter_critical_section(); + tcb = nxsched_get_tcb(pid); + if (tcb == NULL) + { + ret = -ESRCH; + goto errout_with_lock; + } + #ifdef CONFIG_SMP if (tcb->task_state == TSTATE_TASK_RUNNING && tcb->cpu != this_cpu()) @@ -253,16 +294,15 @@ static int nxtask_restart(pid_t pid) nxsched_smp_call_single(cpu, restart_handler, &arg); tcb = nxsched_get_tcb(pid); - if (!tcb || tcb->task_state != TSTATE_TASK_INVALID || - (atomic_read(&tcb->shared_flags) & - TCB_FLAG_EXIT_PROCESSING) != 0) + if (!tcb || tcb->task_state != TSTATE_TASK_INVALID) { ret = -ESRCH; - goto errout_with_lock; + goto errout_with_flags; } DEBUGASSERT(tcb->task_state != TSTATE_TASK_RUNNING); nxtask_reset_task(tcb, false); + atomic_and(&tcb->shared_flags, ~TCB_FLAG_EXIT_PROCESSING); leave_critical_section(flags); /* Activate the task. */ @@ -304,6 +344,7 @@ static int nxtask_restart(pid_t pid) #endif nxtask_reset_task(tcb, true); + atomic_and(&tcb->shared_flags, ~TCB_FLAG_EXIT_PROCESSING); leave_critical_section(flags); /* Activate the task. */ @@ -312,6 +353,14 @@ static int nxtask_restart(pid_t pid) nxsched_put_tcb(tcb); return OK; +#ifdef CONFIG_SMP +errout_with_flags: + if (tcb != NULL) + { + atomic_and(&tcb->shared_flags, ~TCB_FLAG_EXIT_PROCESSING); + } + +#endif errout_with_lock: nxsched_put_tcb(tcb); leave_critical_section(flags); diff --git a/sched/task/task_terminate.c b/sched/task/task_terminate.c index 8c69eb0bdd316..346cd5e2e6bb2 100644 --- a/sched/task/task_terminate.c +++ b/sched/task/task_terminate.c @@ -68,6 +68,49 @@ static int terminate_handler(FAR void *cookie) * Public Functions ****************************************************************************/ +/**************************************************************************** + * Name: nxtask_wait_holds + * + * Description: + * Wait until a task marked with TCB_FLAG_KILL_PROCESSING dropped the + * references it holds on other tasks. It drops them only when it runs, + * so it is woken if stopped, and parks in nxsched_put_tcb(). + * + ****************************************************************************/ + +void nxtask_wait_holds(FAR struct tcb_s *tcb) +{ +#ifdef CONFIG_SIG_SIGSTOP_ACTION + irqstate_t flags; +#endif + + SMP_MB(); + +#ifdef CONFIG_SIG_SIGSTOP_ACTION + /* A stopped task never reaches nxsched_put_tcb(): wake it alone. */ + + flags = enter_critical_section(); + if (atomic_read(&tcb->holds) > 0 && + tcb->task_state == TSTATE_TASK_STOPPED) + { + FAR struct tcb_s *rtcb = this_task(); + + nxsched_remove_blocked(tcb); + if (nxsched_add_readytorun(tcb)) + { + up_switch_context(this_task(), rtcb); + } + } + + leave_critical_section(flags); +#endif + + while (atomic_read(&tcb->holds) > 0) + { + nxsem_wait(&tcb->exit_sem); + } +} + /**************************************************************************** * Name: nxtask_terminate * @@ -123,6 +166,15 @@ int nxtask_terminate(pid_t pid) nxsched_put_tcb(dtcb); + /* The flag must be set before nxtask_wait_holds() reads holds: the + * target parks itself at its last nxsched_put_tcb() only when it sees + * it, and a restarted task must keep running, hence the flag only here. + */ + + atomic_or(&dtcb->shared_flags, TCB_FLAG_KILL_PROCESSING); + + nxtask_wait_holds(dtcb); + flags = enter_critical_section(); /* Remove dtcb from tasklist, let remove_readtorun() do the job */ From bf583c5c812abb19578a089e74b0b4fc232fe3f1 Mon Sep 17 00:00:00 2001 From: zhangyuan29 Date: Fri, 13 Nov 2026 22:32:16 +0800 Subject: [PATCH 10/15] sched/tcb: park the dying task without a timer 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 --- sched/pthread/pthread_exit.c | 5 +---- sched/sched/sched.h | 1 + sched/sched/sched_gettcb.c | 35 +++++++++++++++++++++++++++++++---- sched/task/exit.c | 10 +++++++++- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/sched/pthread/pthread_exit.c b/sched/pthread/pthread_exit.c index 2e4b7ce91f8a8..347c843419104 100644 --- a/sched/pthread/pthread_exit.c +++ b/sched/pthread/pthread_exit.c @@ -110,10 +110,7 @@ void nx_pthread_exit(FAR void *exit_value) if ((atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING) & TCB_FLAG_EXIT_PROCESSING) != 0) { - for (; ; ) - { - usleep(1000); - } + nxsched_park_task(tcb); } /* A thread leaving on its own must have dropped every reference it diff --git a/sched/sched/sched.h b/sched/sched/sched.h index 7e773717d6100..72315cdc66fca 100644 --- a/sched/sched/sched.h +++ b/sched/sched/sched.h @@ -338,6 +338,7 @@ bool nxsched_add_readytorun(FAR struct tcb_s *rtrtcb); bool nxsched_remove_readytorun(FAR struct tcb_s *rtrtcb); void nxsched_remove_self(FAR struct tcb_s *rtrtcb); void nxsched_add_blocked(FAR struct tcb_s *btcb, tstate_t task_state); +void nxsched_park_task(FAR struct tcb_s *tcb); void nxsched_remove_blocked(FAR struct tcb_s *btcb); int nxsched_set_priority(FAR struct tcb_s *tcb, int sched_priority); void nxsched_releasepid(pid_t pid); diff --git a/sched/sched/sched_gettcb.c b/sched/sched/sched_gettcb.c index 08b4f7fb16e02..769858b554db5 100644 --- a/sched/sched/sched_gettcb.c +++ b/sched/sched/sched_gettcb.c @@ -27,6 +27,7 @@ #include #include +#include #include #include "nuttx/irq.h" @@ -37,6 +38,35 @@ * Public Functions ****************************************************************************/ +/**************************************************************************** + * Name: nxsched_park_task + * + * Description: + * Stop a task that found itself already inside a termination flow. It + * must not touch its stack again: it removes itself from the ready-to-run + * list, blocks on the signal wait list and switches away for good. The + * termination path already handles a task blocked in TSTATE_WAIT_SIG. + * + ****************************************************************************/ + +void nxsched_park_task(FAR struct tcb_s *tcb) +{ + enter_critical_section(); + +#ifndef CONFIG_DISABLE_ALL_SIGNALS + sigemptyset(&tcb->sigwaitmask); +#endif + + for (; ; ) + { + nxsched_remove_self(tcb); + nxsched_add_blocked(tcb, TSTATE_WAIT_SIG); + up_switch_context(this_task(), tcb); + } + + PANIC(); +} + /**************************************************************************** * Name: nxsched_get_tcb * @@ -171,10 +201,7 @@ void nxsched_put_tcb(FAR struct tcb_s *tcb) if ((atomic_read(&tcb->shared_flags) & TCB_FLAG_KILL_PROCESSING) != 0) { - for (; ; ) - { - usleep(1000); - } + nxsched_park_task(tcb); } } } diff --git a/sched/task/exit.c b/sched/task/exit.c index 8cefe7f783f0b..95568c638c7f4 100644 --- a/sched/task/exit.c +++ b/sched/task/exit.c @@ -86,7 +86,15 @@ void _exit(int status) * once, or does something very naughty. */ - atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING); + /* If the TCB is already in the exiting state, we should allow the + * killing task to execute normally first. We stop the execution here. + */ + + if ((atomic_or(&tcb->shared_flags, TCB_FLAG_EXIT_PROCESSING) & + TCB_FLAG_EXIT_PROCESSING) != 0) + { + nxsched_park_task(tcb); + } /* A task leaving on its own must have dropped every reference it * took: kernel paths finish before exit() can be called. From 7155efd95244360f9b82845db549f866d64d7ba3 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Fri, 14 Mar 2025 08:20:43 +0800 Subject: [PATCH 11/15] sched/sched: drop the critical sections that the TCB reference covers 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 Signed-off-by: zhangyuan29 --- sched/sched/sched_backtrace.c | 6 ------ sched/sched/sched_getaffinity.c | 4 ---- 2 files changed, 10 deletions(-) diff --git a/sched/sched/sched_backtrace.c b/sched/sched/sched_backtrace.c index af2490a68afcd..010c5e00cc482 100644 --- a/sched/sched/sched_backtrace.c +++ b/sched/sched/sched_backtrace.c @@ -80,9 +80,6 @@ static int sched_backtrace_handler(FAR void *cookie) { FAR struct backtrace_arg_s *arg = cookie; FAR struct tcb_s *tcb; - irqstate_t flags; - - flags = enter_critical_section(); tcb = nxsched_get_tcb(arg->pid); @@ -91,7 +88,6 @@ static int sched_backtrace_handler(FAR void *cookie) { /* There is no TCB with this pid or, if there is, it is not a task. */ - leave_critical_section(flags); nxsched_put_tcb(tcb); return -ESRCH; } @@ -101,8 +97,6 @@ static int sched_backtrace_handler(FAR void *cookie) atomic_and(&tcb->shared_flags, ~TCB_FLAG_CPU_LOCKED); } - leave_critical_section(flags); - arg->stacksize = up_backtrace(tcb, arg->buffer, arg->size, arg->skip); nxsched_put_tcb(tcb); diff --git a/sched/sched/sched_getaffinity.c b/sched/sched/sched_getaffinity.c index d3fa68aacc084..0590bf664ee22 100644 --- a/sched/sched/sched_getaffinity.c +++ b/sched/sched/sched_getaffinity.c @@ -71,15 +71,12 @@ int nxsched_get_affinity(pid_t pid, size_t cpusetsize, FAR cpu_set_t *mask) { FAR struct tcb_s *tcb; - irqstate_t flags; int ret; DEBUGASSERT(cpusetsize == sizeof(cpu_set_t) && mask != NULL); /* Verify that the PID corresponds to a real task */ - flags = enter_critical_section(); - if (pid == 0) { tcb = this_task(); @@ -106,7 +103,6 @@ int nxsched_get_affinity(pid_t pid, size_t cpusetsize, FAR cpu_set_t *mask) nxsched_put_tcb(tcb); } - leave_critical_section(flags); return ret; } From 06ae1885ecc5d5fb058dda7136fdab4587e31522 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Mon, 12 May 2025 14:18:49 +0800 Subject: [PATCH 12/15] sched: drop critical sections that the TCB reference or a lock covers 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 Signed-off-by: zhangyuan29 --- sched/irq/irq_procfs.c | 3 --- sched/sched/sched_getparam.c | 4 ++-- sched/sched/sched_lock.c | 3 --- sched/sched/sched_setscheduler.c | 5 ----- sched/task/task_reparent.c | 8 -------- sched/wqueue/kwork_inherit.c | 10 ++++------ 6 files changed, 6 insertions(+), 27 deletions(-) diff --git a/sched/irq/irq_procfs.c b/sched/irq/irq_procfs.c index 207cbee65d98c..3074502e40bd4 100644 --- a/sched/irq/irq_procfs.c +++ b/sched/irq/irq_procfs.c @@ -146,7 +146,6 @@ static int irq_callback(int irq, FAR struct irq_info_s *info, FAR struct irq_file_s *irqfile = (FAR struct irq_file_s *)arg; struct irq_info_s copy; struct timespec delta; - irqstate_t flags; clock_t elapsed; clock_t now; size_t linesize; @@ -159,13 +158,11 @@ static int irq_callback(int irq, FAR struct irq_info_s *info, /* Take a snapshot and reset the counts */ - flags = enter_critical_section(); memcpy(©, info, sizeof(struct irq_info_s)); now = clock_systime_ticks(); info->start = now; info->time = 0; info->count = 0; - leave_critical_section(flags); /* Don't bother if count == 0. * diff --git a/sched/sched/sched_getparam.c b/sched/sched/sched_getparam.c index 4f90bfe94524d..60eb18d9f3e03 100644 --- a/sched/sched/sched_getparam.c +++ b/sched/sched/sched_getparam.c @@ -118,7 +118,9 @@ int nxsched_get_param(pid_t pid, FAR struct sched_param *param) { FAR struct tcb_s *rtcb; FAR struct tcb_s *tcb; +#ifdef CONFIG_SCHED_SPORADIC irqstate_t flags; +#endif int ret = OK; if (param == NULL) @@ -153,7 +155,6 @@ int nxsched_get_param(pid_t pid, FAR struct sched_param *param) { /* Get the TCB associated with this PID */ - flags = enter_critical_section(); tcb = nxsched_get_tcb(pid); if (!tcb) { @@ -172,7 +173,6 @@ int nxsched_get_param(pid_t pid, FAR struct sched_param *param) #endif } - leave_critical_section(flags); nxsched_put_tcb(tcb); } } diff --git a/sched/sched/sched_lock.c b/sched/sched/sched_lock.c index d53fab16816fc..c9683661d6409 100644 --- a/sched/sched/sched_lock.c +++ b/sched/sched/sched_lock.c @@ -86,13 +86,10 @@ void sched_lock(void) { #if (CONFIG_SCHED_CRITMONITOR_MAXTIME_PREEMPTION >= 0) || \ defined(CONFIG_SCHED_INSTRUMENTATION_PREEMPTION) - irqstate_t flags = enter_critical_section_notrace(); - /* Note that we have pre-emption locked */ nxsched_critmon_preemption(rtcb, true, return_address(0)); sched_note_preempt_lock(rtcb); - leave_critical_section_notrace(flags); #endif } } diff --git a/sched/sched/sched_setscheduler.c b/sched/sched/sched_setscheduler.c index 78ff68b9af2ad..20fb8a408a522 100644 --- a/sched/sched/sched_setscheduler.c +++ b/sched/sched/sched_setscheduler.c @@ -136,7 +136,6 @@ int nxsched_set_scheduler(pid_t pid, int policy, FAR const struct sched_param *param) { FAR struct tcb_s *tcb; - irqstate_t flags; int ret = -EINVAL; if (param == NULL) @@ -184,8 +183,6 @@ int nxsched_set_scheduler(pid_t pid, int policy, * while we set up scheduling policy. */ - flags = enter_critical_section(); - switch (policy) { case SCHED_OTHER: @@ -230,8 +227,6 @@ int nxsched_set_scheduler(pid_t pid, int policy, break; #endif } - - leave_critical_section(flags); } } else diff --git a/sched/task/task_reparent.c b/sched/task/task_reparent.c index 4420065b45c53..d7ca1d30ceca1 100644 --- a/sched/task/task_reparent.c +++ b/sched/task/task_reparent.c @@ -225,18 +225,11 @@ int task_reparent(pid_t ppid, pid_t chpid) FAR struct tcb_s *chtcb = NULL; FAR struct tcb_s *otcb = NULL; pid_t opid; - irqstate_t flags; #ifndef CONFIG_SCHED_CHILD_STATUS irqstate_t tgflags; #endif int ret; - /* Disable interrupts so that nothing can change in the relationship of - * the three task: Child, current parent, and new parent. - */ - - flags = enter_critical_section(); - /* Get the child tasks TCB (chtcb) */ chtcb = nxsched_get_tcb(chpid); @@ -348,7 +341,6 @@ int task_reparent(pid_t ppid, pid_t chpid) } errout_with_ints: - leave_critical_section(flags); nxsched_put_tcb(ptcb); nxsched_put_tcb(otcb); nxsched_put_tcb(chtcb); diff --git a/sched/wqueue/kwork_inherit.c b/sched/wqueue/kwork_inherit.c index 6c85aedf68f26..68a2175485a0b 100644 --- a/sched/wqueue/kwork_inherit.c +++ b/sched/wqueue/kwork_inherit.c @@ -214,7 +214,6 @@ static void lpwork_restoreworker(pid_t wpid, uint8_t reqprio) void lpwork_boostpriority(uint8_t reqprio) { - irqstate_t flags; int wndx; /* Clip to the configured maximum priority */ @@ -226,7 +225,7 @@ void lpwork_boostpriority(uint8_t reqprio) /* Prevent context switches until we get the priorities right */ - flags = enter_critical_section(); + sched_lock(); /* Adjust the priority of every worker thread */ @@ -235,7 +234,7 @@ void lpwork_boostpriority(uint8_t reqprio) lpwork_boostworker(g_lpwork.worker[wndx].pid, reqprio); } - leave_critical_section(flags); + sched_unlock(); } /**************************************************************************** @@ -258,7 +257,6 @@ void lpwork_boostpriority(uint8_t reqprio) void lpwork_restorepriority(uint8_t reqprio) { - irqstate_t flags; int wndx; /* Clip to the configured maximum priority */ @@ -270,7 +268,7 @@ void lpwork_restorepriority(uint8_t reqprio) /* Prevent context switches until we get the priorities right */ - flags = enter_critical_section(); + sched_lock(); /* Adjust the priority of every worker thread */ @@ -279,7 +277,7 @@ void lpwork_restorepriority(uint8_t reqprio) lpwork_restoreworker(g_lpwork.worker[wndx].pid, reqprio); } - leave_critical_section(flags); + sched_unlock(); } #endif /* CONFIG_SCHED_WORKQUEUE && CONFIG_SCHED_LPWORK && \ From 2b66c13b9b3f0f3f48f51f1e65d4fa6141264391 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Thu, 25 Jun 2026 15:30:20 +0800 Subject: [PATCH 13/15] sched: skip SETSCHEDULER handling in posix_spawn on FIFO-only builds 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 --- include/spawn.h | 4 +++- libs/libc/spawn/lib_psa_dump.c | 2 ++ sched/task/task_spawnparms.c | 4 ++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/include/spawn.h b/include/spawn.h index cfbac15cd3a9b..54d88fd993d6b 100644 --- a/include/spawn.h +++ b/include/spawn.h @@ -60,7 +60,9 @@ #define POSIX_SPAWN_RESETIDS (1u << 0) /* 1: Reset effective user ID */ #define POSIX_SPAWN_SETPGROUP (1u << 1) /* 1: Set process group */ #define POSIX_SPAWN_SETSCHEDPARAM (1u << 2) /* 1: Set task's priority */ -#define POSIX_SPAWN_SETSCHEDULER (1u << 3) /* 1: Set task's scheduler policy */ +#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) +# define POSIX_SPAWN_SETSCHEDULER (1u << 3) /* 1: Set task's scheduler policy */ +#endif #define POSIX_SPAWN_SETSIGDEF (1u << 4) /* 1: Set default signal actions */ #define POSIX_SPAWN_SETSIGMASK (1u << 5) /* 1: Set sigmask */ #define POSIX_SPAWN_SETSID (1u << 7) /* 1: Create the new session(glibc specific) */ diff --git a/libs/libc/spawn/lib_psa_dump.c b/libs/libc/spawn/lib_psa_dump.c index 63c2ea7baaabf..b62e431f1ffa8 100644 --- a/libs/libc/spawn/lib_psa_dump.c +++ b/libs/libc/spawn/lib_psa_dump.c @@ -86,10 +86,12 @@ void posix_spawnattr_dump(posix_spawnattr_t *attr) _err(" POSIX_SPAWN_SETSCHEDPARAM\n"); } +#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) if ((attr->flags & POSIX_SPAWN_SETSCHEDULER) != 0) { _err(" POSIX_SPAWN_SETSCHEDULER\n"); } +#endif if ((attr->flags & POSIX_SPAWN_SETSIGDEF) != 0) { diff --git a/sched/task/task_spawnparms.c b/sched/task/task_spawnparms.c index 69279e3d00f95..f827a03607803 100644 --- a/sched/task/task_spawnparms.c +++ b/sched/task/task_spawnparms.c @@ -218,7 +218,9 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) * then we will call nxsched_set_scheduler() below. */ +#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) if ((attr->flags & POSIX_SPAWN_SETSCHEDULER) == 0u) +#endif { sinfo("Setting priority=%d for pid=%d\n", param.sched_priority, pid); @@ -228,6 +230,7 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) } } +#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) /* If we are only changing the scheduling policy, then reset * the priority to the default value (the same as this thread) in * preparation for the nxsched_set_scheduler() call below. @@ -268,6 +271,7 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) nxsched_set_param(pid, ¶m) : -EINVAL; #endif } +#endif /* CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) */ return ret; } From f848cc64d110d039d77a24ad2b86d85cec0980a1 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Thu, 25 Jun 2026 19:44:34 +0800 Subject: [PATCH 14/15] sched/spawn: pass tcb to spawn_execattrs() instead of pid 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 Signed-off-by: zhangyuan29 --- binfmt/binfmt_execmodule.c | 2 +- sched/task/spawn.h | 5 +++-- sched/task/task_spawn.c | 2 +- sched/task/task_spawnparms.c | 31 ++++++++++++------------------- 4 files changed, 17 insertions(+), 23 deletions(-) diff --git a/binfmt/binfmt_execmodule.c b/binfmt/binfmt_execmodule.c index c4315af369a24..b73ed3a2bcaf4 100644 --- a/binfmt/binfmt_execmodule.c +++ b/binfmt/binfmt_execmodule.c @@ -413,7 +413,7 @@ int exec_module(FAR struct binary_s *binp, if (attr) { - ret = spawn_execattrs(pid, attr); + ret = spawn_execattrs(tcb, attr); if (ret < 0) { goto errout_with_tcbinit; diff --git a/sched/task/spawn.h b/sched/task/spawn.h index 948e8bcf10ea0..c1036287daa07 100644 --- a/sched/task/spawn.h +++ b/sched/task/spawn.h @@ -43,7 +43,7 @@ * * Input Parameters: * - * pid - The pid of the new task. + * tcb - The TCB of the new task. * attr - The attributes to use * * Returned Value: @@ -58,6 +58,7 @@ * ****************************************************************************/ -int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr); +int spawn_execattrs(FAR struct tcb_s *tcb, + FAR const posix_spawnattr_t *attr); #endif /* __SCHED_TASK_SPAWN_H */ diff --git a/sched/task/task_spawn.c b/sched/task/task_spawn.c index 65052e3fb1261..4f4a435ab51c6 100644 --- a/sched/task/task_spawn.c +++ b/sched/task/task_spawn.c @@ -130,7 +130,7 @@ static int nxtask_spawn_create(FAR const char *name, int priority, if (attr) { - ret = spawn_execattrs(pid, attr); + ret = spawn_execattrs(tcb, attr); if (ret < 0) { goto errout_with_taskinit; diff --git a/sched/task/task_spawnparms.c b/sched/task/task_spawnparms.c index f827a03607803..377cf823e0cb6 100644 --- a/sched/task/task_spawnparms.c +++ b/sched/task/task_spawnparms.c @@ -39,6 +39,7 @@ #include #include "group/group.h" +#include "sched/sched.h" #include "task/spawn.h" #include "task/task.h" @@ -130,7 +131,7 @@ static inline int nxspawn_open(FAR struct tcb_s *tcb, * * Input Parameters: * - * pid - The pid of the new task. + * tcb - The TCB of the new task. * attr - The attributes to use * * Returned Value: @@ -143,9 +144,10 @@ static inline int nxspawn_open(FAR struct tcb_s *tcb, * ****************************************************************************/ -int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) +int spawn_execattrs(FAR struct tcb_s *tcb, FAR const posix_spawnattr_t *attr) { struct sched_param param; + pid_t pid = tcb->pid; int ret = OK; DEBUGASSERT(attr); @@ -157,13 +159,7 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) #ifndef CONFIG_DISABLE_ALL_SIGNALS if ((attr->flags & POSIX_SPAWN_SETSIGMASK) != 0u) { - FAR struct tcb_s *tcb = nxsched_get_tcb(pid); - - if (tcb) - { - tcb->sigprocmask = attr->sigmask; - nxsched_put_tcb(tcb); - } + tcb->sigprocmask = attr->sigmask; } #endif @@ -172,14 +168,8 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) if ((attr->flags & POSIX_SPAWN_SETSID) != 0u) { - FAR struct tcb_s *tcb = nxsched_get_tcb(pid); - - if (tcb != NULL) - { - tcb->group->tg_pgid = tcb->group->tg_pid; - tcb->group->tg_sid = tcb->group->tg_pid; - nxsched_put_tcb(tcb); - } + tcb->group->tg_pgid = tcb->group->tg_pid; + tcb->group->tg_sid = tcb->group->tg_pid; } /* Then it joins a process group, as setpgid(pid, pgroup) in the caller */ @@ -210,6 +200,7 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) if (ret == OK) { +#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) /* Get the priority from the attributes */ param.sched_priority = attr->priority; @@ -218,14 +209,16 @@ int spawn_execattrs(pid_t pid, FAR const posix_spawnattr_t *attr) * then we will call nxsched_set_scheduler() below. */ -#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC) if ((attr->flags & POSIX_SPAWN_SETSCHEDULER) == 0u) #endif { sinfo("Setting priority=%d for pid=%d\n", param.sched_priority, pid); - +#ifdef CONFIG_SCHED_SPORADIC ret = nxsched_set_param(pid, ¶m); +#else + ret = nxsched_set_priority(tcb, attr->priority); +#endif } } } From 4d833a5d6f1d10a16e34b053103e8e8e5f2cc8b6 Mon Sep 17 00:00:00 2001 From: hujun5 Date: Fri, 26 Jun 2026 09:40:43 +0800 Subject: [PATCH 15/15] sched/spawn: read current priority directly instead of nxsched_get_param 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 Signed-off-by: zhangyuan29 --- binfmt/binfmt_loadmodule.c | 16 ++-------------- libs/libc/spawn/lib_psa_init.c | 4 ++++ sched/task/task_spawn.c | 15 ++------------- 3 files changed, 8 insertions(+), 27 deletions(-) diff --git a/binfmt/binfmt_loadmodule.c b/binfmt/binfmt_loadmodule.c index 3cdbe142f10d0..c9fcec469f698 100644 --- a/binfmt/binfmt_loadmodule.c +++ b/binfmt/binfmt_loadmodule.c @@ -64,27 +64,15 @@ static int load_default_priority(FAR struct binary_s *bin) { - struct sched_param param; - int ret; - - /* Get the priority of this thread */ - - ret = nxsched_get_param(0, ¶m); - if (ret < 0) - { - berr("ERROR: nxsched_get_param failed: %d\n", ret); - return ret; - } - /* Save that as the priority of child thread */ - bin->priority = param.sched_priority; + bin->priority = nxsched_self()->sched_priority; if (bin->priority <= 0) { bin->priority = SCHED_PRIORITY_DEFAULT; } - return ret; + return OK; } /**************************************************************************** diff --git a/libs/libc/spawn/lib_psa_init.c b/libs/libc/spawn/lib_psa_init.c index 3139803f7f2ee..d1ed4da7a3959 100644 --- a/libs/libc/spawn/lib_psa_init.c +++ b/libs/libc/spawn/lib_psa_init.c @@ -56,7 +56,9 @@ int posix_spawnattr_init(posix_spawnattr_t *attr) { +#ifdef CONFIG_SCHED_SPORADIC struct sched_param param; +#endif int ret; DEBUGASSERT(attr); @@ -69,11 +71,13 @@ int posix_spawnattr_init(posix_spawnattr_t *attr) /* Set the default priority to the same priority as this task */ +#ifdef CONFIG_SCHED_SPORADIC ret = _SCHED_GETPARAM(0, ¶m); if (ret < 0) { return _SCHED_ERRNO(ret); } +#endif /* attr->priority left at 0: callers that do not set a priority will have * it filled in from the loaded binary (binp->priority) by the binary diff --git a/sched/task/task_spawn.c b/sched/task/task_spawn.c index 4f4a435ab51c6..08de950b0c8d5 100644 --- a/sched/task/task_spawn.c +++ b/sched/task/task_spawn.c @@ -214,17 +214,9 @@ static int nxtask_spawn_exec(FAR pid_t *pidp, FAR const char *name, } else { - struct sched_param param; - /* Set the default priority to the same priority as this task */ - ret = nxsched_get_param(0, ¶m); - if (ret < 0) - { - return ret; - } - - priority = param.sched_priority; + priority = this_task()->sched_priority; stacksize = CONFIG_POSIX_SPAWN_DEFAULT_STACKSIZE; } @@ -237,10 +229,7 @@ static int nxtask_spawn_exec(FAR pid_t *pidp, FAR const char *name, if (priority == 0) { - struct sched_param param; - - nxsched_get_param(0, ¶m); - priority = param.sched_priority; + priority = this_task()->sched_priority; } if (stacksize == 0)