Commit graph

3242 commits

Author SHA1 Message Date
Abhishek Mishra
db6ab892a2 fs/binfmt: close symlink TOCTOU and harden setuid/setgid exec hygiene
Some checks are pending
Build Documentation / build-html (push) Waiting to run
MemBrowse Memory Report / changes-filter (push) Waiting to run
MemBrowse Memory Report / load-targets (push) Waiting to run
MemBrowse Memory Report / identical (push) Blocked by required conditions
MemBrowse Memory Report / analyze (push) Blocked by required conditions
Perform pseudo-filesystem permission checks inside inode_reserve() and
inode_remove() while the inode tree lock is held, and hold that lock across
pseudorename mutations so symlink swaps cannot bypass directory checks.
Hold a read lock around pseudo-fs open permission checks.

On setuid/setgid exec, update saved set-IDs, mark the task group secure,
sanitize dangerous environment variables, clear debug/dumpable flags, and
add issetugid(), secure_getenv(), and PR_SET/GET_DUMPABLE support.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-08-01 15:32:03 -03:00
yushuailong
8cec1d01db sched/sched: Fix uninitialized sporadic params returned by nxsched_get_param()
Some checks are pending
MemBrowse Memory Report / changes-filter (push) Waiting to run
MemBrowse Memory Report / load-targets (push) Waiting to run
MemBrowse Memory Report / identical (push) Blocked by required conditions
MemBrowse Memory Report / analyze (push) Blocked by required conditions
When querying the calling task itself (pid == 0 or the caller's own
pid), nxsched_get_param() only filled in sched_priority and never
touched the SCHED_SPORADIC related members (sched_ss_low_priority,
sched_ss_max_repl, sched_ss_repl_period and sched_ss_init_budget).
With CONFIG_SCHED_SPORADIC enabled, the caller received uninitialized
stack garbage in these fields, and a task running under the sporadic
policy could not retrieve its own sporadic parameters.

Fix this by factoring the sporadic parameter fill-in into a common
helper nxsched_get_sporadic_param() shared by both the self-query and
the lookup paths, so both paths now return identical information.

The self-query path keeps its original fast-path behavior: no TCB
lookup and a lock-free read of sched_priority.  Only the read of the
sporadic state is wrapped in a critical section, because tcb->sporadic
may be freed concurrently, e.g. by sched_setscheduler() from another
CPU switching the task away from SCHED_SPORADIC.

Signed-off-by: yushuailong <yyyusl@qq.com>
2026-08-01 11:19:50 +08:00
Abhishek Mishra
4c62271654 sched/group: add getresuid, getresgid, setreuid, and setregid
Implement POSIX real/effective/saved credential getters and paired
setters in the task group layer, with libc stubs and syscalls.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-07-30 09:48:10 +08:00
Alan Carvalho de Assis
c027e7c3e4 tools: fix stale archive members surviving a Kconfig-driven CSRCS change
During the Toybox port to NuttX, Claude noticed that changes in the
menuconfig weren't taking affect. This issue exists for a long time on
NuttX, in fact BayLibre's presentation from 2017 make jokes about our
building system not been reliable:
https://www.youtube.com/watch?v=XUJK2htXxKw&t=320s

Stale archive members from $(AR)'s additive-only behavior can linger
after Kconfig toggles change which files provide a symbol, causing dead
weight or "multiple definition" link errors on incremental builds.
Fixed by splitting ARCHIVE into two macros: ARCHIVE keeps the original
additive behavior for apps/libapps.a, which many independent
subdirectories contribute to across a build, while the new
ARCHIVE_REBUILD deletes then archives for the far more common case
of a single Makefile building its own self-contained $(OBJS)
- all 39 such call sites now use it.

Assisted-By: Claude Sonnet 5
Signed-off-by: Alan C. Assis <acassis@gmail.com>
2026-07-28 21:26:03 -03:00
yushuailong
3b3380ca01 sched/sched_critmonitor: remove duplicate preemption start block
The `to->preemp_start = current` assignment when `to->lockcount > 0`
was executed twice under CONFIG_SCHED_CRITMONITOR_MAXTIME_PREEMPTION,
once in the main preemption block and again after the csection block.
Remove the redundant duplicate.

Signed-off-by: yushuailong <yyyusl@qq.com>
2026-07-28 16:04:50 +08:00
Marco Casaroli
6c1feb7839 sched/addrenv: do not dereference a NULL address environment
A task does not necessarily own an address environment.  tcb->addrenv_own is
set only by addrenv_attach(), which is reached only from addrenv_allocate();
a kernel thread never allocates one, and in a protected build nothing does --
there is a single address space for the whole system and the architecture's
up_addrenv_*() are stubs.  addrenv_own is then NULL for every task, always.

That a task may have no address environment is already an expected state.
addrenv_switch() returns OK when tcb->addrenv_curr is NULL and addrenv_drop()
returns early, and every caller of addrenv_select() checks addrenv_own != NULL
before calling in:  nxsched_get_stateinfo(), nxtask_argvstr(), proc_groupenv()
and the arm, arm64, risc-v and tricore up_check_tcbstack().

addrenv_take() and addrenv_give() are the only two that dereference
unconditionally.  addrenv_join() calls addrenv_take(ptcb->addrenv_own) without
a check, so pthread_create() faults on &((struct addrenv_s *)NULL)->refs
whenever the calling task has no address environment.  With
CONFIG_DEBUG_ASSERTIONS off the same access silently corrupts low memory
instead.

Handle NULL in both, the way the rest of the file already does.
addrenv_give() returns a non-zero count for the NULL case so that callers
never conclude an absent address environment has become unreferenced and
should be destroyed.

Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 10:14:44 +08:00
liang.huang
fd0dd8c597 sched/backtrace: fix cross-CPU buffer access under addrenv
The remote CPU's IPI handler wrote into the caller's buffer directly,
which may not be reachable from the target CPU's address environment
under CONFIG_ARCH_ADDRENV.

Signed-off-by: liang.huang <liang.huang@houmo.ai>
2026-07-20 21:01:28 -03:00
liang.huang
059176fe64 sched: avoid dumping raw memory at address 0 for tasks without kstack
dump_stacks() only checked kernelstack_sp != 0 || force, so for tasks
with no kernel stack (e.g. idle, kernelstack_base == 0) the force path
passed base 0 to dump_stackinfo() and dumped raw memory from address 0,
triggering a secondary fault that truncated the panic log.  Guard with
kernelstack_base != 0.

Signed-off-by: liang.huang <liang.huang@houmo.ai>
2026-07-20 20:57:45 -03:00
anjiahao
745a6e53a4 spawn: allow zero stacksize/priority to use binary loader defaults
posix_spawnattr_init() no longer pre-fills attr->stacksize and
attr->priority (it leaves them zero, as memset already does).  When a
caller does not set them, the binary loader supplies them from the
loaded ELF (binp->stacksize / binp->priority, parsed from the nx_*
symbols), and nxtask_spawn_exec() falls back to the parent priority and
CONFIG_POSIX_SPAWN_DEFAULT_STACKSIZE for the posix_spawn() function-task
path.

This lets an application's stack size and priority embedded as ELF
symbols actually drive the spawned task, instead of being overridden by
the spawnattr defaults.

Signed-off-by: anjiahao <anjiahao@xiaomi.com>
2026-07-15 12:24:44 -03:00
raiden00pl
30c5040547 drivers/timers, sched/clock: use file_get/file_put
fs_getfilep()/fs_putfilep() were renamed to file_get()/file_put().

The PTP clock paths still used the old names, breaking the PTP_CLOCK build.

Signed-off-by: raiden00pl <raiden00@railab.me>
2026-07-11 17:22:07 -04:00
raiden00pl
1369a2875d sched/misc/coredump.c: guard tcb->name in coredump
coredump_dump_tcb() copied tcb->name unconditionally, but the tcb_s name
member only exists when CONFIG_TASK_NAME_SIZE > 0

Signed-off-by: raiden00pl <raiden00@railab.me>
2026-07-10 05:04:13 +08:00
Xiang Xiao
9e141acab3 !include/fcntl.h: align open flags with Linux values
Align the NuttX open(2) flag constants with the Linux asm-generic
values so that the FUSE wire protocol and other cross-platform
interfaces work without conversion.

All code that used '(flags & O_RDONLY)' as a bitmask check (always 0
now that O_RDONLY=0) has been updated to use '(flags & O_ACCMODE)'
comparisons.

The NUTTX_O_* constants in include/nuttx/fs/hostfs.h are updated to
match, and the sim hostfs open flag mapping is fixed.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-30 13:43:44 +08:00
Xiang Xiao
6161c73639 include/fcntl.h: remove O_RDOK/O_WROK aliases
O_RDOK and O_WROK are non-standard aliases for O_RDONLY and O_WRONLY
respectively.  Having two names for the same flag creates confusion,
especially when aligning the flag values with Linux.  Remove the
aliases and replace all uses with the standard O_RDONLY/O_WRONLY.

No functional change — O_RDOK was defined as O_RDONLY and O_WROK as
O_WRONLY, so the replacement is a pure text substitution.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-28 09:10:11 -03:00
Jukka Laitinen
7f8f800e63 arch, sched/signal: Fix compilation with ENABLE_PARTIAL_SIGNALS=y
Correct build errors when CONFIG_ENABLE_ALL_SIGNALS is not defined

- sched makefiles: Move pending-signal helpers from the ENABLE_ALL_SIGNALS-only
  list to the !DISABLE_ALL_SIGNALS list so signal dispatch is available in
  PARTIAL builds sched: make SIG_PREALLOC_ACTIONS, SIG_ALLOC_ACTIONS and
  SIG_DEFAULT depend on ENABLE_ALL_SIGNALS
- sched: fix ifdefs around pending-signal queue access and signal-mask for
  PARTIAL/DISABLE modes
- arch: gate SYS_signal_handler / _return calls and SYSCALL_LOOKUP(signal)
  with ENABLE_ALL_SIGNALS

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-16 17:07:32 +08:00
Kerogit
689ed188c6 sched/clock/clock_delay: added config flag to remove weak up_udelay
While attempting to create architecture-specific implementation
of up_udelay, it was discovered that the overriding function is not
included in the final binary, the weak implementation was used instead.

Further investigation and experimentation showed that the linker
only overrides the weak implementation with the custom one if
the custom one is present in a .c source file that contains at least
one other function that is called from somewhere. Some additional
testing revealed that at least one other already present up_udelay
override (rv32m1-vega:nsh) is affected by this.

In a short mailing list discussion it was determined that this
is a likely result of using static libraries during the build process
and it was suggested to introduce configuration option that will
exclude weak implementations of the function from the build altogether.
This patch does that.

This patch does not enable this configuration option for any existing
board/chip because doing so would change its behaviour and needs
to be tested by users of the hardware.

Also changed is the static assertion in sched/clock/clock_delay.c
to not prevent building the code when architecture declares that
it does not use BOARD_LOOPSPERMSEC to determine required loop count.
BOARD_LOOPSPERMSEC is made undefined in such case.

Patch was tested by building breadxavr:nsh (identical binary by SHA256),
rv32m1-vega:nsh (identical text section) and rv-virt:nsh (text section
differs because of different ordering of functions in the binary, ostest
passed though.)

Signed-off-by: Kerogit <kr.git@kerogit.eu>
2026-06-12 09:55:11 -04:00
Abhishek Mishra
d487c46a29 Documentation/sched: Add POSIX user identity transition docs
Adds comprehensive documentation for the POSIX three-tier user identity
model (real, effective, saved-set IDs) enabled by CONFIG_SCHED_USER_IDENTITY.

* Updates sched/Kconfig with detailed help text explaining the config.
* Adds user_identity.rst to formally document credential inheritance
  and the privilege transition rules for setuid(), seteuid(), setgid(),
  and setegid().
* Updates tasks_vs_threads.rst to list credentials as a shared task
  group resource.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-06-12 08:13:23 +08:00
Abhishek Mishra
14661fdba0 sched/group: implement POSIX saved-set-UID/GID semantics
Adds tg_suid and tg_sgid fields to task_group_s to complete the
POSIX three-field identity model (real, effective, saved-set).

Updates group_inherit_identity() to propagate the new fields from
parent to child task group on task creation.

Fixes setuid(), setgid(), seteuid(), and setegid() to implement
correct POSIX privilege transition logic:
- Root (euid==0): may set any value; all three IDs updated by setuid/setgid
- Non-root: may only set effective ID to real or saved value; else EPERM

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-06-12 08:13:23 +08:00
Jukka Laitinen
64b6bbb0c0 sched/Kconfig: Fix ETC_ROMFS dependency
When using FS_CROMFS for etc, user typically don't need FS_ROMFS,
they are completely separate filesystems. But both ETC_ROMFS and
ETC_CROMFS are needed, the first one selects that the ETC needs
to be mounted from ROM based filesystem, and ETC_CROMFS just specifies
that the backing filesystem is actually the CROMFS.

Iow; make ETC_ROMFS depend on FS_ROMFS || FS_CROMFS, so that the
user can drop FS_ROMFS when only FS_CROMFS is needed.

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-10 01:23:08 +08:00
Jukka Laitinen
40bbf67bd3 sched/misc/assert: Add CONFIG_SCHED_DUMP_TASKS and CONFIG_SCHED_DUMP_STACK
Add more refined options for sched/misc/assert to control how verbose
crash dumps are printed out:

- SCHED_DUMP_TASKS
- SCHED_DUMP_STACK

These default to y unless DEFAULT_SMALL is defined. The options can
be undefined to save flash space on a small system.

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-09 08:04:54 -04:00
Jukka Laitinen
5844ff5abb sched/misc/assert: Small flash-saving fixes
- Use shared string for "stack pointer out of range" to avoid duplicate in flash
- Re-use already calculated stack_used instead of calling up_check_tcbstack again

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-09 08:04:54 -04:00
Xiang Xiao
9ff99c6d0f !nuttx: drop redundant casts on tv_sec/tv_nsec and fix printf formats
Now that time_t is unconditionally 64-bit (signed int64_t) and the
struct timespec fields tv_sec / tv_nsec are wide enough on their own,
the explicit (uint64_t)/(int64_t)/(int) casts that used to guard the
multiplications and subtractions in *_us / *_ms / *_ns helpers are no
longer needed.  Drop them to keep the timekeeping math readable and
consistent with the previous sclock_t/time_t cleanup.

In the same spirit, this commit also:

* Normalises the printf-style format specifiers and casts used to
  print tv_sec / tv_nsec / tv_usec values across arch/, drivers/,
  fs/, sched/ and libs/.  The prior code was a mix of
  "%d"/"%u"/"%ld"/"%lu"/"%lld"/PRIu32/PRIu64 with matching
  (int)/(unsigned long)/(long long)/PRIu* casts; some formats
  truncated time_t on 32-bit hosts, others mismatched signedness or
  width.  Replace all such cases with the portable POSIX-recommended
  forms:

    - tv_sec  (time_t,       signed, impl-defined width) -> %jd  + (intmax_t)
    - tv_nsec (long,         signed)                     -> %ld  (no cast)
    - tv_usec (suseconds_t / long)                       -> %ld  (no cast)

  Add #include <stdint.h> where required.

* Drops a few stale `(FAR const time_t *)&ts.tv_sec` casts and
  related `(FAR struct tm *)` / `(const time_t *)` casts in
  gmtime_r() / localtime_r() / gmtime() callers; ts.tv_sec is plain
  time_t now and the casts only obscured the type.

* Fixes one overflow in fs/procfs/fs_procfscritmon.c where
  all_time.tv_sec * 1000000 could overflow on 32-bit time_t before
  being multiplied again; cast to uint64_t at the start.

No behavioural change.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
c47b1e2c5b !sys/types.h: change time_t and clock_t to int64_t to align with other OSes
POSIX leaves the signedness of time_t and clock_t unspecified, but
mainstream implementations (Linux glibc/musl, the BSDs, macOS, RTEMS,
Zephyr's POSIX layer, Windows _time64) expose time_t as signed 64-bit.
NuttX has historically used uint64_t only because it was tied to the
CONFIG_SYSTEM_TIME64 knob; with that gone, switch:

  time_t   : uint64_t  -> int64_t
  clock_t  : uint64_t  -> int64_t
  CLOCK_MAX: UINT64_MAX -> INT64_MAX

This lets (time_t)-1 sentinels, negative tick deltas, and host-side
headers behave as on every other POSIX system without source churn.

Headers updated:
  - include/sys/types.h, include/limits.h, include/nuttx/clock.h
  - include/nuttx/fs/hostfs.h (nuttx_time_t alias)
  - include/nuttx/{mqueue.h,wdog.h,wqueue.h,timers/clkcnt.h}

Because clock_t is now signed 64-bit, the NuttX-internal sclock_t
alias becomes redundant: every sclock_t/SCLOCK_MAX use is folded
back to clock_t/CLOCK_MAX (notably in sched/wdog, sched/mqueue,
sched/sched, sched/clock, sched/timer, libs/libc/time, fs/vfs and
the drivers/arch consumers below).

Tick/period constants (NSEC_PER_SEC, USEC_PER_SEC, MSEC_PER_SEC,
SEC_PER_MIN, ...) in include/nuttx/clock.h are retyped from "long"
literals to INT64_C(...) so that 64-bit arithmetic no longer
depends on the host's long width.

Strip now-redundant (time_t)/(clock_t)/(unsigned long) casts and
unsigned-only branches across the tree:
  - arch RTC / oneshot / tickless lowerhalfs:
      arm: cxd56xx, efm32, imxrt, lc823450, max326xx, sam34, sama5,
           samd5e5, samv7, stm32, stm32f7, stm32h7, stm32l4, stm32wb,
           xmc4
      mips: pic32mz       sparc: bm3803       x86_64: intel64
      risc-v/xtensa: espressif (esp_i2c[_slave], esp_rtc,
           esp32c3{_i2c,_rtc,_wifi_adapter}, esp32{,s2,s3}_*),
           mpfs_perf
  - drivers: audio/tone, input/aw86225, power/pm/{activity,
           stability}_governor, rpmsg/rpmsg_ping,
           timers/{ds3231,mcp794xx,pcf85263,rx8010},
           wireless/ieee80211/bcm43xxx, wireless/spirit/spirit_spi
  - core: fs/vfs/{fs_poll,fs_timerfd}, mm/iob/iob_alloc,
          libs/libc/{netdb/lib_dnscache,time/{lib_calendar2utc,
          lib_time}}, net/icmp/icmp_pmtu, net/icmpv6/icmpv6_pmtu,
          net/ipfrag, net/tcp/{tcp.h,tcp_timer},
          net/utils/net_snoop, net/mld/mld_query (drop the now-dead
          mld_mrc2mrd helper since signed math handles it directly),
          sched/clock/{clock,clock_initialize},
          sched/sched/{sched_profil,sched_setparam,sched_setscheduler},
          sched/pthread/pthread_create,
          sched/wdog/{wd_gettime,wd_start,wdog.h},
          sched/timer/timer_gettime, sched/mqueue/*

Flip the few in-tree printf format strings that assumed an
unsigned 64-bit tv_sec:
  * drivers/rpmsg/rpmsg_ping.c                       PRIu64 -> PRId64
  * arch/xtensa/src/esp32{,s2,s3}/esp32*_oneshot_lowerhalf.c
                                          PRIu32 (already wrong) -> PRId64

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
c6654b1106 !sched/clock: remove CONFIG_SYSTEM_TIME64 and always use 64-bit time
The 32-bit system clock has a limited range (~497 days) and the
configuration knob is no longer worth the complexity given that
practically every modern target already enables it.  Make 64-bit
time_t/clock_t/sclock_t/nuttx_time_t the only supported flavor.

Specifically:
  - Drop the SYSTEM_TIME64 Kconfig option and its dependent
    PERF_OVERFLOW_CORRECTION/HRTIMER guards in sched/Kconfig.
  - Remove every #ifdef CONFIG_SYSTEM_TIME64 branch in headers
    (include/{sys/types.h,limits.h,inttypes.h,nuttx/clock.h,
    nuttx/fs/hostfs.h}) and core code paths
    (sched/clock/clock.h, drivers/power/pm/pm_procfs.c,
    drivers/rpmsg/rpmsg_ping.c, fs/procfs/fs_procfsuptime.c,
    libs/libc/wqueue/work_usrthread.c,
    arch/avr/src/avrdx/avrdx_timerisr_tickless_alarm.c).
  - Strip CONFIG_SYSTEM_TIME64=y from every board defconfig.
  - Update Documentation/guides/rust.rst accordingly.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
c32b683085 !compiler: drop CONFIG_HAVE_LONG_LONG and require long long support
Every compiler supported by NuttX provides the "long long" types,
so the CONFIG_HAVE_LONG_LONG indirection is no longer useful.
Remove the option from include/nuttx/compiler.h and treat
"long long" as unconditionally available across the OS.

In addition to deleting the guard itself, this commit unconditionally
enables the long-long flavored helpers that used to be gated behind
it:

  - libs/libc/fixedmath: drop the soft-emulated b32/ub32 routines
    in lib_fixedmath.c (-261 lines) and trim the matching
    prototypes, Make.defs and CMakeLists.txt entries; keep only
    the long-long backed implementations.
  - include/sys/endian.h, include/strings.h, libs/libc/string
    /lib_ffsll.c, lib_flsll.c: always expose the 64-bit byte-swap
    and ffsll/flsll variants.
  - libs/libm/libm/lib_llround{,f,l}.c: drop the empty stubs.
  - libs/libc/stdlib (atoll, llabs, lldiv, strtoll/ull, rand48,
    strtold), libs/libc/stream (libvsprintf, libvscanf,
    libbsprintf, ultoa_invert), libs/libc/misc (crc64, crc64emac),
    libs/libc/inttypes/strtoimax, libs/libc/lzf, libs/libc/libc.csv,
    libs/libc/string (memset, vikmemcpy): remove the
    #ifdef CONFIG_HAVE_LONG_LONG branches.
  - include/{stddef.h,stdlib.h,fixedmath.h,sys/epoll.h,cxx/cstdlib,
    nuttx/audio/audio.h,nuttx/crc64.h,nuttx/lib/math.h,
    nuttx/lib/math32.h,nuttx/lib/stdbit.h}: same guard cleanup.
  - drivers/note/note_driver.c, fs/spiffs/src/spiffs.h,
    sched/irq/irq_procfs.c: drop their local guards as well.
  - Documentation/applications/netutils/ntpclient/index.rst:
    refresh the documentation snippet.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
9a84223c1e sched/clock: Remove TIMER_MASK32 from clock.h
since it isn't used anymore

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
wangyongrong
f20f9ff19e sched/group: skip group_release for kernel thread group
When CONFIG_DISABLE_PTHREAD=y, HAVE_GROUP_MEMBERS is undefined and
group_leave() unconditionally calls group_release() for every exiting
thread. This destroys the shared g_kthread_group resources (mutex,
fdlist, task_info) while other kernel threads are still using them,
causing use-after-free crashes.

Fix by checking TCB_FLAG_TTYPE_KERNEL in group_leave() before calling
group_release(), so the entire release path is skipped for kernel
threads. This is safe because g_kthread_group is statically allocated
and its lifetime is the entire system.

Signed-off-by: wangyongrong <wangyongrong@xiaomi.com>
2026-05-08 13:44:51 +08:00
Matteo Golin
48db502daf !boards: Remove NSH_ARCHINIT and board_app_initialize
BREAKING: In an effort to simplify NuttX initialization, NSH_ARCHINIT is
removed. board_app_initialize is also removed. BOARD_LATE_INITIALIZE now
performs all board initialization logic, and is by default enabled. All
references to these symbols are removed. BOARDIOC_INIT remains, but will
result in -ENOTTY when called. It is to be removed in a later commit.

Quick fix: Boards relying on NSH_ARCHINIT should now enable
CONFIG_BOARD_LATE_INITIALIZE instead. If the application needs
fine-grained control over board initialization from userspace, the logic
performed by BOARDIOC_INIT may be copied to the board_finalinitialize
function and used instead via BOARDIOC_FINALINIT. All
board_app_initialize logic provided by NuttX is now moved to
board_late_initialize, and the same should be done for out-of-tree
boards.

Signed-off-by: Matteo Golin <matteo.golin@gmail.com>
2026-05-02 18:36:46 +08:00
Michal Lenc
7dc6be8f08 clock_settime: don't block when up_rtc_settime is called
Setting the current time in RTC may be a blocking operation (driver
needs to wait for oscillator stabilization after reset and so on).
This may cause the unwanted effect of clock_settime blocking the
code execution for a considerable amount of time.

The solution is to plan a low priority work that takes care
of setting the time in RTC and let clock_settime continue. We don't
have to check if the work is available, just cancel it if there
is a new time set request.

This is used only if CONFIG_SCHED_LPWORK is enabled.

Signed-off-by: Michal Lenc <michallenc@seznam.cz>
2026-04-28 15:15:05 -04:00
zhanxiaoqi
786b315947 fs/inode: add optional manual FD backtrace control via task group flag
When CONFIG_FS_BACKTRACE is enabled, collecting a stack trace for every
new file descriptor adds overhead to fast path operations like open(),
dup(), and socket().

This patch adds a new configuration option CONFIG_FS_BACKTRACE_DEFAULT.
When enabled (default behavior), the GROUP_FLAG_FD_BACKTRACE flag is
automatically set during group allocation, causing backtrace to be
captured for all tasks globally, preserving the original diagnostic
capability.

When disabled, backtrace capture is zero-cost by default and must be
explicitly enabled per task group using GROUP_FLAG_FD_BACKTRACE.

Signed-off-by: zhanxiaoqi <zhanxiaoqi@bytedance.com>
2026-04-28 09:53:27 +02:00
Arjav Patel
f51052d780 sched/docs: Align ETC ROMFS text with tmpfs-first /tmp mount.
Update ETC_ROMFS help text and NSH/ROMFS guides to describe the
/tmp mount behavior as tmpfs-first with FAT RAMDISK fallback when
CONFIG_FS_TMPFS is not enabled.

Signed-off-by: Arjav Patel <arjav1528@gmail.com>
2026-04-23 10:26:21 -03:00
zhanxiaoqi
29114efb41 sched/misc: Optimize thread saving order in coredump for easier gdb debug
When GDB opens a coredump file, it first selects a "current thread",
and the bt command by default only performs backtracing on this current
thread. When there is no dedicated "crash thread marker" for this current
thread in NuttX's coredump.elf, it usually degenerates to
"the first thread parsed in the core file".

Signed-off-by: zhanxiaoqi <zhanxiaoqi@bytedance.com>
2026-04-14 19:33:14 +08:00
Piyush Patle
0dccc8ba21 include/debug.h: Move to include/nuttx/debug.h
debug.h is a NuttX-specific, non-POSIX header. Placing it in the
top-level include/ directory creates naming conflicts with external
projects that define their own debug.h.
This commit moves the canonical header to include/nuttx/debug.h,
following the NuttX convention for non-POSIX/non-standard headers,
and updates all in-tree references.

A backward-compatibility shim is left at include/debug.h that
emits a deprecation #warning and re-includes <nuttx/debug.h>,
allowing out-of-tree code to continue building while migrating.

Signed-off-by: Piyush Patle <piyushpatle228@gmail.com>
2026-04-07 07:50:06 -03:00
Shunchao Hu
5f6e1e2d7e sched/semaphore: check unmasked pending signals before blocking.
A signal can arrive before sem_wait transitions the task
to TSTATE_WAIT_SEM. In that window, the wait cannot yet
be aborted by sem_wait_irq(). If sem_wait then blocks
without re-checking unmasked pending signals, it can
sleep indefinitely and miss the interrupt.

Check for unmasked pending signals before touching the
semaphore count and return -EINTR if one is already pending.

Signed-off-by: Shunchao Hu <ankohuu@gmail.com>
2026-04-07 09:50:02 +08:00
raiden00pl
d72bb349f4 sched/group_foreachchild.c: fix warning
fix compilation warning:

   group/group_foreachchild.c:85:10: warning: 'ret' may be used uninitialized [-Wmaybe-uninitialized]
   85 |   return ret;
      |          ^~~
   group/group_foreachchild.c:67:7: note: 'ret' was declared here
   67 |   int ret;

Signed-off-by: raiden00pl <raiden00@railab.me>
2026-03-24 10:56:23 -03:00
Huang Qi
e3eeaefd6d style: Fix "the the" typo across the codebase.
Fix 269 occurrences of duplicate "the" word typo found in 209 files
across source code, header files, and configuration.

Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
2026-03-23 11:07:49 +01:00
chao an
d5b02b6954 sched/critmon: Fix CPU load stats incorrect when using SCHED_CPULOAD_CRITMONITOR
Fix the abnormal CPU usage statistics issue caused by missing update
of run_start timestamp in the target task (to) TCB when the CPU load
counting mode is SCHED_CPULOAD_CRITMONITOR.

Before this fix, the to->run_start was not set when switching context,
leading to incorrect CPU usage calculation (e.g., Idle_Task showed 52.9%
CPU usage instead of 100%, and running tasks had wrong non-zero values).
After fixing, the CPU statistics return to normal: Idle_Task correctly
shows 100% usage, and non-running tasks show 0% as expected.

Enable:
+CONFIG_SCHED_CPULOAD_CRITMONITOR=y
+CONFIG_SCHED_CRITMONITOR=y

Before:
nsh> ps
  TID   PID  PPID PRI POLICY   TYPE    NPX STATE    EVENT     SIGMASK            STACK    CPU COMMAND
    0     0     0   0 FIFO     Kthread   - Ready              0000000000000000 0069584 52.9% Idle_Task
    1     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067456  0.0% sim_loop_wq 0x7b4417a003f0 0x7b4417a00470
    2     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067464 17.6% hpwork 0x4014dba0 0x4014dc20
    3     3     0 100 FIFO     Task      - Running            0000000000000000 0067496 36.8% nsh_main

After:
nsh> ps
  TID   PID  PPID PRI POLICY   TYPE    NPX STATE    EVENT     SIGMASK            STACK    CPU COMMAND
    0     0     0   0 FIFO     Kthread   - Ready              0000000000000000 0069584 100.0% Idle_Task
    1     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067456  0.0% sim_loop_wq 0x7646932003f0 0x764693200470
    2     0     0 224 FIFO     Kthread   - Waiting  Semaphore 0000000000000000 0067464  0.0% hpwork 0x4014dba0 0x4014dc20
    3     3     0 100 FIFO     Task      - Running            0000000000000000 0067496  0.0% nsh_main

This issue was introduced by PR #17075, where the run_start update for the
target task was omitted in the SCHED_CPULOAD_CRITMONITOR branch.

Signed-off-by: chao an <anchao.archer@bytedance.com>
2026-03-03 11:54:20 -05:00
chao an
d8b4d53444 sched/tickless: Fix CLOCK_MONOTONIC always 0 by updating sched ticks
Fix the issue where clock_gettime(CLOCK_MONOTONIC) always returns 0 in
tickless mode, caused by the scheduler tick counter (g_system_ticks) not
being updated with the actual timer ticks.

1. Add clock_update_sched_ticks() function to sched/clock/clock_sched_ticks.c:
  a. This function directly sets the system tick counter to a specific value
     (vs incrementing in clock_increase_sched_ticks), with full documentation
     matching the existing code style.
  b. Uses seqlock to ensure thread-safe access to g_system_ticks.

2. Call clock_update_sched_ticks() in nxsched_process_timer() (sched_processtickless.c):

  a. Syncs the scheduler tick counter with the actual timer ticks retrieved via up_timer_gettick().

With this fix, g_system_ticks is properly updated in tickless mode,
and clock_gettime(CLOCK_MONOTONIC) returns the correct non-zero monotonic time.

Signed-off-by: chao an <anchao.archer@bytedance.com>
2026-03-03 11:01:02 -05:00
chenzhaoxiang
635f64ebb8 sched/misc: fix potential out-of-bounds access in coredump stack emission
The elf_emit_tcb_stack() function in coredump.c was calculating the stackbuffer length
and emitting the stack data without validating whether thecalculated buffer range
(buf + len) exceeds the actual bounds of the TCB'sstack memory region (stack_base_ptr + adj_stack_size).

This could lead to out-of-bounds memory access when the calculated stacklength is larger
than the available stack space, potentially causing memorycorruption, crashes, or incorrect
core dump generation.

This fix adds a bounds check:
1. Compares the end of the intended stack buffer (buf + len) against the
   upper limit of the TCB's stack (stack_base_ptr + adj_stack_size).
2. If the buffer would exceed the stack bounds, truncates the length to fit
   within the valid stack memory range.

The change ensures safe memory access during core dump generation,preventing out-of-bounds
reads and improving the robustness of the coredumpfeature.

Signed-off-by: chao an <anchao.archer@bytedance.com>
2026-02-27 17:52:34 +08:00
chenzhaoxiang
0d12f82074 sched/misc: fix incorrect mutex holder retrieval in assert backtrace
The dump_lockholder() function in assert.c was directly accessing themutex->holder
member variable to print the mutex holder's thread ID inthe backtrace log. This is
incorrect because the holder field is aprivate implementation detail of the mutex structure,
and the properAPI nxmutex_get_holder() should be used to retrieve the holder ID.

Using the public API ensures consistency with mutex state management,avoids potential issues
with future changes to the mutex structure'sinternal layout, and adheres to the kernel's
encapsulation principles.

This fix corrects the log output to show the accurate mutex holder IDwhen assertion failures
related to mutex locks occur, improving thedebuggability of lock-related issues.

Signed-off-by: chao an <anchao.archer@bytedance.com>
2026-02-27 09:24:55 +08:00
chenzhaoxiang
14fb39a6cd sched/misc: fix incomplete data emission in coredump elf_emit function
The elf_emit() function in coredump.c was only checking for negative returnvalues
from lib_stream_puts() to detect write failures. However, lib_stream_puts()can return 0
to indicate that no bytes were written (e.g., due to stream full,end-of-file, or other
non-error conditions that prevent data writing).

This oversight meant that cases where lib_stream_puts() returned 0 would bypassthe error handling,
leading to incomplete data emission in the core dump withoutany failure indication.
The loop would continue attempting to write the remainingdata, resulting in partial or corrupted core dump files.

This fix modifies the condition from ret < 0 to ret <= 0 to:

1. Catch both error conditions (negative return values) and zero-byte writes.
2. Immediately break the write loop and propagate the failure, ensuring the core
   dump process correctly aborts when data cannot be written.

This change improves the reliability of core dump generation by ensuring allfailed or
incomplete write attempts are properly handled, preventing corruptedcore dump files.

Signed-off-by: chao an <anchao.archer@bytedance.com>
2026-02-26 14:44:16 +01:00
wangchengdong
9c80011c53 sched/signal: update nxsig_clockwait() to support disable all signals
Update nxsig_clockwait() to handle the case where all signals functions
are disabled.

Signed-off-by: Chengdong Wang <wangchengdong@lixiang.com>
2026-02-26 20:03:05 +08:00
wangchengdong
8514e9978f sched/signal: move nxsig_clockwait implementation to a separate file
Move the implementation of nxsig_clockwait() into a separate file
to decouple it from nxsig_timedwait().

Signed-off-by: Chengdong Wang <wangchengdong@lixiang.com>
2026-02-26 20:03:05 +08:00
wangchengdong
23d48da4bd sched/sched: add nxsched_abstick_sleep()
Add nxsched_abstick_sleep() and make nxsched_ticksleep()
a wrapper around it.

Signed-off-by: Chengdong Wang <wangchengdong@lixiang.com>
2026-02-26 17:04:47 +08:00
Matteo Golin
2d768c294e arch/delays: Invalid default value for BOARD_LOOPSPERMSEC
Changes the default value for CONFIG_BOARD_LOOPSPERMSEC to -1, which is
invalid. All boards that forget to configure this value will encounter a
static assertion at compile time, enforcing that configurations
upstreamed to NuttX have calibrated values for correct delay timings.

Boards which implement ALARM_ARCH or TIMER_ARCH do not rely on the
busy-loop delay implementation and thus only have a run-time check to
ensure proper delay-timings (in the case where delays are used before
the alarm/timer driver is registered).

Some boards already in the NuttX upstream do not have calibrated values,
but there are no users who currently own the board to submit a
calibrated value for the configurations to use. In this scenario, the
value is temporarily set to 0 and a warning is displayed so that users
of these boards are informed of the calibration process.

Signed-off-by: Matteo Golin <matteo.golin@gmail.com>
2026-02-25 15:00:03 -03:00
wangchengdong
629a9d4ace sched/sched: fix typos and remove unused declarations in sched.h
This patch removes unnecessary and unimplemented function declarations in sched.h, fixing typos and cleaning up the header file.

Signed-off-by: Chengdong Wang <wangchengdong@lixiang.com>
2026-02-25 12:38:13 -05:00
wangchengdong
ae1731210d sched/clock: fix CLOCK_BOOTTIME and CLOCK_MONOTONIC handling
The current implementation retrieves time from the same source for both
CLOCK_BOOTTIME and CLOCK_MONOTONIC, which is incorrect. CLOCK_BOOTTIME
includes time spent in system suspend, whereas CLOCK_MONOTONIC does not.

This patch fixes the incorrect clock source handling and ensures the
two clocks are distinguished properly.

Signed-off-by: Chengdong Wang <wangchengdong@lixiang.com>
2026-02-25 16:15:23 +08:00
SPRESENSE
72b67832ea Makefile: Remove make depend files by make distclean
Intermediate files of make depend like .ddc and .dds may remain
when make is interrupted. Remove them using make distclean.

Signed-off-by: SPRESENSE <41312067+SPRESENSE@users.noreply.github.com>
2026-02-16 16:27:57 +01:00
Tiago Medicci Serrano
9cf7d80bab sched/mqueue: Enable receiving messages on an interrupt handler
The internal implementation of `file_mq_receive` did not allow
receiving a message from an interrupt handler. Although it is not
possible to wait for a message in an interrupt context, it is
perfectly possible to retrieve already-existing messages from the
message queue. This commit modifies file_mq_timedreceive_internal
to enable checking the message list and, if no messages exist, it
returns immediately. This enables receiving any existing messages
in an interrupt context.

Signed-off-by: Tiago Medicci Serrano <tiago.medicci@espressif.com>
2026-02-11 13:10:31 -05:00
hujun5
82a218cbf3 sched_waitpid.c: HIS_metric_violation: CCM
This commit refactors nxsched_waitpid() by extracting the core waiting logic
into a separate waittcb() helper function. This change significantly reduces
the cyclomatic complexity of the main function while preserving all original
functionality and improving code maintainability with better separation of
concerns between initialization and wait handling logic.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
2026-02-04 03:04:44 +08:00
hujun5
5abba4f655 sched_waitpid.c: HIS_metric_violation(HIS_GOTO)
This commit eliminates the goto statement in nxsched_waitpid() function to
improve code quality metrics compliance. The control flow has been restructured
using nested if-else statements to achieve identical functionality while
maintaining MISRA/HIS coding standard compliance and improving code readability.

Signed-off-by: hujun5 <hujun5@xiaomi.com>
2026-02-04 03:04:44 +08:00