Skip to content

sched: Enable HRTIMER unconditionally, convert wdog/wqueue/tickless interfaces [HRTimer Part I] - #22492

Open
Fix-Point wants to merge 23 commits into
apache:masterfrom
Fix-Point:wdog-hrtimer-experiment
Open

Fix-Point wants to merge 23 commits into
apache:masterfrom
Fix-Point:wdog-hrtimer-experiment

Conversation

@Fix-Point

@Fix-Point Fix-Point commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This series enables the high-resolution timer subsystem (CONFIG_HRTIMER) unconditionally, removes the legacy tick-based watchdog interfaces, and converts the workqueue and watchdog modules to the hrtimer interface. It is the first part of a larger effort to replace the tick-based wdog everywhere with hrtimer; upcoming parts follow the order workqueue → POSIX timer → scheduler → tcb timer → misc.

Changes (in commit order):

  1. sched/hrtimer: Add BMP support — Convert the hrtimer lock, last-expired time, queue and running slot to per-CPU BMP/SMP variables, add hrtimer_initialize() called from nx_start() to initialize the per-CPU queue at runtime, and let the wdog queue initialize through hrtimer_queue_initialize().

  2. hrtimer: introduce hrtimer_is_active() — Add a predicate for "is the timer armed". hrtimer internals must not be accessed directly by users, yet the watchdog upper-half status query needs this question. It is defined from the remaining time reported by hrtimer_gettime(): a non-zero remainder means the timer is pending and has not expired yet, which matches the former wdog func-based test except at the instant of expiration. The gettime implementation clamps a negative remainder to zero, so unused and cancelled timers are reported inactive without wraparound.

  3. sched: Remove conditional compilation for HRTIMER — Remove the CONFIG_HRTIMER conditional compilation so that wdog uses hrtimer unconditionally and the legacy tick-based watchdog code is deleted. sched/Kconfig drops the config HRTIMER switch and the if HRTIMER wrapper (keeping the HRTIMER_LIST/HRTIMER_TREE structure choice and HRTIMER_PRECISION_SHIFT). This is the key step toward enabling HRTIMER by default.

  4. sched/wdog: Fix Coverity CID 3933988 — Wrap the hrtimer_start() return value in wd_timer_start() with DEBUGVERIFY() (MISRA C-2012 Rule 17.7, unchecked return value).

  5. sched/wdog: Inline wdog interfaces with NULL checks — Move NULL pointer checks from the .c files into inline functions in the header, letting the compiler optimize away redundant checks: wd_start_abstick() ↔ wd_start_abstick_internal(), wd_cancel() ↔ wd_cancel_internal() wrappers; inline wd_start() validates the delay range. wd_init() is removed (no caller).

  6. sched/tickless: Remove tick-based alarm/timer interfaces — Delete the up_alarm_tick_start/up_alarm_tick_cancel/up_timer_tick_start/up_timer_tick_cancel wrappers that merely converted ticks to timespec and delegated to the timespec variants; after the hrtimer conversion no in-tree caller uses them (dead code). The NULL check in up_timer_getmask becomes a DEBUGASSERT since the caller always ensures the lower-half is registered.

  7. sched/wqueue: Add hrtimer support for workqueue — Convert the workqueue timer from wdog to hrtimer: the kwork_wqueue_s timer field becomes struct hrtimer_s; work_timer_reset() and the expiration callback use the hrtimer interface; a WQUEUE_MAX_DELAY limit is added (min(WDOG_MAX_DELAY, HRTIMER_MAX_DELAY/NSEC_PER_TICK)). Goal: eliminate the workqueue deadlock completely — the wdog callback runs in interrupt context; when it interleaves with the workqueue thread's mutex-protected operations, the callback/signal-delivery path that holds a lock can deadlock. Switching to hrtimer's synchronous cancellation (hrtimer_cancel_sync) and an independent callback path removes the dependency of the timeout callback on the wdog interrupt-context lock chain, closing that deadlock window.

  8. sched/tickless: Convert watchdog to hrtimer in tickless scheduler — The scheduler event timer becomes an hrtimer: the expiration callback returns the delay to the next event (with a 1 ns floor, so a zero delay still re-arms) and the hrtimer core re-inserts the timer itself. nxsched_process_event() now returns the next delay, and nxsched_timer_start() arms the hrtimer directly.

  9. sched/sched: Fix Coverity CID 3933998 (MISRA C-2012 Rule 9.1) — Zero-initialize the timespec in nxsched_process_timer() so every member has a defined value before it is read.

  10. sched/hrtimer: Extract the hrtimer queue into reusable interfaces — Replace the per-CPU tree/list globals with a struct hrtimer_queue_s instance and out-of-line hrtimer_queue_initialize/first/insert/remove helpers, so the same queue code serves both the hrtimer core and the wdog driver timer.

  11. sched/wdog: Refactor wdog on top of the hrtimer queue — struct wdog_s embeds an hrtimer_s (the user callback is stored in timer.func, the deadline in timer.expired); the ad-hoc wdog list is replaced by a queue instance, wd_gettime() becomes inline, and wd_gettime.c is removed.

  12. sched/wdog: Drop g_wdtimernested, use the hrtimer running slot — The running slot is maintained on all builds, hrtimer_is_referenced() reports whether a CPU holds the timer (running or cancel-marked form), and wd_in_callback() is derived from it; the g_wdtimernested flag is removed.

  13. sched/tickless: Use the hrtimer running slot in the tickless scheduler — sched_in_expiration() is derived from the same hrtimer_is_referenced() helper instead of a private flag.

  14. sched/wdog: read the cancel note fields under the critical section — Read the callback and deadline while the critical section is held so that the scheduler note emitted outside it cannot observe a concurrent change; the note arguments are also swallowed when instrumentation is disabled.

  15. Board configurations — Disable CONFIG_LIBC_TEMPBUFFER in imx93-qsb/rpmsg (the static pool is linked into the ITCM load region; the image fits again), reduce PREALLOC_TIMERS in stm32l476vg-disco/nsh to save 120 bytes of ksram, and enable LTO on lx_cpu/nsh (also dropping the redundant -mpic-register=r9, which otherwise breaks the PIC ELF links under -Werror) and on quickfeather/nsh (together with DEBUG_FULLOPT/-Os, since that config previously built without any -O).

Motivation: hrtimer provides nanosecond resolution and a unified kernel timing path; with CONFIG_HRTIMER off by default most targets only have tick granularity, and wdog/tickless/POSIX timer carry parallel tick/hrtimer implementations. This series makes hrtimer the default path and replaces wdog step by step, in the order workqueue → POSIX timer → scheduler → tcb timer → misc.

Beyond switching the default, this series greatly simplifies the implementation: duplicate tick/timespec conversion wrappers are deleted (up_*_tick_*), the legacy tick-based watchdog path is removed, and NULL checks move into inline functions the compiler can optimize away — fewer moving parts, less code, single timing path. At the same time it improves timer precision and performance: nanosecond-granularity expiration replaces tick-quantized delays, the workqueue no longer round-trips through the wdog interrupt-context lock chain (removing a deadlock window), and the simpler hot paths (inlined NULL checks, direct hrtimer start/cancel) reduce per-timer overhead.

Dependencies: this PR depends on the companion apps PR (testing/ostest: enable hrtimer_test by default).
Depends-On: apache/nuttx-apps#4179

Impact

  • User impact: no directly visible API change; behavior (resolution) improves to nanosecond granularity once hrtimer is active.
  • Build: the CONFIG_HRTIMER switch is removed — configurations that explicitly set CONFIG_HRTIMER=y must drop that line (this PR already removes the references in 3 defconfigs); CONFIG_HRTIMER_LIST/CONFIG_HRTIMER_TREE/CONFIG_HRTIMER_PRECISION_SHIFT are kept. New hrtimer_is_active() API added to include/nuttx/hrtimer.h. Four up_*_tick_* declarations removed from arch.h.
  • Hardware: hrtimer requires a board-level high-resolution clock source (the up_alarm_*/up_timer_* timespec variants); only the tick-wrapper interfaces are removed.
  • Documentation: Documentation/ hrtimer docs are not updated in this part (follow-up parts).
  • Security: none.
  • Compatibility: CONFIG_HRTIMER symbol removed (a stale defconfig line produces a Kconfig unknown-symbol warning, non-blocking, cleanup suggested); wd_init() removed (no callers); the four tick interfaces removed (no callers).
  • Data structures: struct wdog_s now embeds struct hrtimer_s, so its size and layout change for code that allocates it; wd_gettime() is inline (no exported symbol); the wdog callbacks run from the hrtimer core context, and wd_start()/wd_cancel() called from a callback are detected through hrtimer_is_referenced().
  • New helpers: hrtimer_is_active() and hrtimer_is_referenced() in include/nuttx/hrtimer.h (hrtimer_is_referenced() must be called from the critical section).

Testing

Host: Linux x86_64; RISC-V rv64/rv32 QEMU 6.2; toolchains riscv64-unknown-elf-gcc 10.2 / arm-none-eabi-gcc 10.3.1.

Board/Configuration:

  • rv-virt:nsh64 (riscv64, QEMU) + CONFIG_TESTING_OSTEST=y + CONFIG_SCHED_WORKQUEUE=y
  • TICKLESS config: CONFIG_SCHED_TICKLESS=y + CONFIG_SCHED_TICKLESS_ALARM=y + LIMIT_MAX_SLEEP (verifies no dangling references after the tick interface removal)
  • nucleo-c071rb:nsh (STM32C071, Cortex-M0+, 128 KiB flash) — flash footprint comparison

Build: each of the 6 commits passes tools/checkpatch.sh with 0 errors; rv-virt:nsh64 default and TICKLESS configs both build with 0 errors / 0 warnings; wdog/wqueue/tickless objects are actually compiled into the image.

Run/Boot:

# rv-virt:nsh64, QEMU:
$ (sleep 3; printf 'ostest\r'; sleep 200) | timeout 240 qemu-system-riscv64 -semihosting -M virt,aclint=on -cpu rv64 -smp 8 -bios none -kernel nuttx -nographic
...
ostest_main: Exiting with status 0
  • Full ostest round passes, including wdog (hrtimer path), workqueue (HPWORK/LPWORK callbacks 100/100), and POSIX timer cases.
  • Flash footprint on nucleo-c071rb:nsh: baseline 77,440 B vs chain 77,988 B (+548 B ≈ 0.42% of 128 KiB flash) — not significant.

Additional validation after the wdog/tickless rework:

  • rv-virt:smp (rv32, CONFIG_SMP=y, SMP_NCPUS=8, CONFIG_SCHED_TICKLESS=y + SCHED_TICKLESS_ALARM): build 0 errors / 0 warnings; full ostest passes with ostest_main: Exiting with status 0 and no assertion (log kept as ostest-rv-virt-smp-tickless.log).
  • rv-virt:smp non-tickless: build 0/0 and a repeated wdog_test/hrtimer_test loop runs without assertions.
  • imx93-qsb/rpmsg links again: the image previously overflowed the ITCM (528 bytes over); the load image now leaves 352 bytes free.
  • After adding BMP support: rv-virt:smp with tickless (SMP) and quickfeather:nsh (UP, -Os + LTO) build clean, and tools/checkpatch.sh passes on the full series.
  • qemu-armv7a:citest (UP, flat): the full ostest completes and the wqueue tests pass after keeping clock_systime_nsec() as the reference time passed to hrtimer_process() from the tick handler.

Note: the companion apps change that always compiles/runs hrtimer_test lives in the apps PR that this PR depends on; QEMU-vs-real-hardware differences are called out where applicable; configs that download external packages (e.g. qemu-armv7a:full) were not tested due to restricted network in the environment.

Follow-up: flash size reduction

The last commits reduce the image size on configurations that are at the
FLASH limit. They come after the functional conversion and do not change
the timer behavior:

  • libc/misc: move tempbuffer pool from .data to .bss - the pool struct
    had a non-zero initializer, so the 512-byte buffer array was linked
    into .data; tracking used buffers keeps the struct zero-initialized and
    moves it to .bss (512 bytes less .data, measured on imx93-qsb:rpmsg).
  • boards/imx93-qsb/rpmsg: disable the libc temp buffer - the
    applications do not need the global pool; the image now ends 40 bytes
    below the ITCM limit.
  • boards/lx_cpu/nsh: Enable LTO (which also drops the redundant
    -mpic-register=r9) and boards/lx_cpu/nsh: disable the libc temp buffer - the nsh image overflowed the FLASH region by 524 bytes; LTO
    and the smaller libc keep it inside.
  • boards/eoss3/quickfeather: Enable LTO and Enable compiler optimization - the configuration selected no optimization level
    (DEBUG_NOOPT), so the image was built without -O; selecting
    DEBUG_FULLOPT (-Os) with LTO drops .text from 259,924 to
    100,960 bytes.
  • boards/stm32f3/nucleo-f302r8: Disable stack dump on the cansock config - the hrtimer conversion adds a little code and the 64 KiB
    image overflowed by 40 bytes with GCC 13; dropping the stack dump
    frees about 1 KiB, at the cost of the crash register dump.

Note that boards/sam3u-ek:knsh no longer overflows: current master
already enables LTO on that configuration.

@github-actions github-actions Bot added Area: Drivers Drivers issues Size: L The size of the change in this PR is large Board: risc-v Board: simulator Board: tricore labels Nov 27, 2026
@Fix-Point Fix-Point changed the title sched: enable hrtimer by default and convert wdog/wqueue/tickless to hrtimer sched: Enable HRTIMER unconditionally, convert wdog/wqueue interfaces [HRTimer Part I] Nov 27, 2026
@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch from 4f8e9b7 to e9a04f8 Compare November 27, 2026 12:08
@Fix-Point Fix-Point changed the title sched: Enable HRTIMER unconditionally, convert wdog/wqueue interfaces [HRTimer Part I] sched: enable hrtimer by default and convert wdog/wqueue/tickless to hrtimer [HRTimer Part I] Nov 27, 2026
@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch from e9a04f8 to c6d8b60 Compare November 27, 2026 12:14
@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

arduino-mega2560

  • flash: .data +18 B, .text +1,484 B, .trampolines +4 B (+2.2%, 70,248 B / 262,144 B, total: 27% used)
  • sram: .bss +32 B, .data +18 B (+1.8%, 2,853 B / 8,192 B, total: 35% used)

esp32-devkitc

  • ROM: .dram0.data -516 B, .flash.text +552 B (+0.0%, 134,956 B / 4,194,272 B, total: 3% used)
  • dram0_0_seg: .dram0.bss +592 B, .dram0.data -516 B (+0.7%, 10,548 B / 180,736 B, total: 6% used)
  • irom0_0_seg: .flash.text +552 B (+0.5%, 101,124 B / 3,342,304 B, total: 3% used)

hifive1-revb

  • flash: .text +704 B (+0.8%, 87,276 B / 4,194,304 B, total: 2% used)
  • sram: .bss +64 B (+1.7%, 3,924 B / 16,384 B, total: 24% used)

mirtoo

  • kseg0_progmem: .text +1,148 B (+1.8%, 64,696 B / 131,072 B, total: 49% used)
  • kseg1_datamem: .bss +64 B, .sbss +24 B (+3.3%, 2,780 B / 32,256 B, total: 9% used)

mps2-an500-citest

  • flash: .data -520 B, .text +4,096 B (+1.4%, 257,404 B / 4,194,304 B, total: 6% used)
  • sram1: .bss +608 B, .data -520 B (+0.5%, 16,544 B / 16,777,216 B, total: 0% used)

mps2-an500-citest-protected

  • flash: .data -516 B, .text +1,008 B (+0.4%, 123,076 B / 4,194,304 B, total: 3% used)
  • sram1: .bss +600 B, .data -516 B (+1.0%, 8,604 B / 16,777,216 B, total: 0% used)

qemu-armv7a-citest

  • ROM: .data -400 B, .init_section -112 B, .text +4,208 B (+0.7%, 566,224 B / 1,048,576 B, total: 54% used)

qemu-armv7a-citest-knsh

  • ROM: .data -512 B, .init_section -936 B, .text +936 B (-0.3%, 164,760 B / 1,048,576 B, total: 16% used)

qemu-armv8a

  • Code: .rodata +768 B, .text.cancel_test +44 B, .text.cmd_dmesg +16 B, .text.cmd_mkdir +20 B, .text.nsh_catfile -360 B, .text.nx_start +12 B, .text.nxmq_wait_receive +28 B, .text.nxmq_wait_send +28 B, .text.nxsched_abstick_sleep +8 B, .text.nxsched_process_timer +216 B, .text.nxsem_clockwait +12 B, .text.nxsem_tickwait +8 B, .text.profil +12 B, .text.profil_timer_handler +4 B, .text.strtol +92 B, .text.strtoul +32 B, .text.strtoull +24 B, .text.timer_settime +24 B, .text.timer_test +8 B, .text.timer_timeout +12 B, .text.user_main +20 B, .text.wd_timer +32 B, .text.wdog_test_thread -152 B, .text.wdtest_callback_recursive +24 B, .text.wdtest_recursive +28 B, .text.work_loop +20 B, .text.work_qcancel +8 B, .text.work_qqueue +24 B, .text.work_queue_alloc +4 B, .text.work_queue_run -4 B, .text.work_timer_expired +4 B, .text.wqueue_test_entry +288 B (+1.2%, 391,188 B)
  • Data: .bss.g_hpwork -8 B (+0.1%, 78,577 B)

qemu-intel64

  • Code: .text +3,381 B (+0.0%, 8,714,246 B)
  • Data: .bss +576 B, .data -544 B, .rodata +1,312 B (+1.2%, 111,241 B)

rx65n-rsk2mb

  • RAM: .bss +548 B, .data -516 B (+0.5%, 7,092 B / 262,144 B, total: 3% used)
  • ROM: .text +752 B (+0.8%, 95,600 B / 2,097,152 B, total: 5% used)

s698pm-dkit

  • Code: .text +4,192 B (+1.0%, 420,480 B)
  • Data: .bss +576 B, .data -528 B (+0.4%, 12,304 B)

stm32-nucleo-f103rb

  • flash: .text +584 B (+1.7%, 35,104 B / 131,072 B, total: 27% used)
  • sram: .bss +48 B (+1.9%, 2,620 B / 20,480 B, total: 13% used)

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

@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch 2 times, most recently from 7ad382e to dbe29fa Compare November 27, 2026 12:25
Comment thread sched/sched/sched_processtick.c Resolved
Comment thread sched/wdog/wd_start.c Resolved
Comment thread sched/wdog/wdog.h Resolved
Comment thread include/nuttx/wdog.h Resolved
Comment thread include/nuttx/wdog.h Resolved
Comment thread sched/wdog/wd_start.c Resolved
Comment thread sched/wqueue/kwork_queue.c Resolved
Comment thread sched/wqueue/kwork_queue.c Resolved
Comment thread sched/wqueue/kwork_thread.c Resolved
Comment thread sched/wqueue/wqueue.h Resolved
@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch from dbe29fa to 1890f0b Compare November 27, 2026 15:10
@github-actions

Copy link
Copy Markdown

🔗 Cross-repo PR dependencies

The read-only Build run reported the following dependent PR(s) and fetched head SHA(s):

CI run: https://github.com/apache/nuttx/actions/runs/46022589205

@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch 5 times, most recently from 2d928ca to 4506997 Compare November 30, 2026 03:44
@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch from 6f9441d to f82d69f Compare December 1, 2026 13:00
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

🔗 Cross-repo PR dependencies

The read-only Build run reported the following dependent PR(s) and fetched head SHA(s):

CI run: https://github.com/apache/nuttx/actions/runs/46651937542

Fix-Point and others added 2 commits December 2, 2026 09:50
…tion

Convert the hrtimer global variables (g_hrtimer_lock, g_hrtimer_tree,
g_hrtimer_head, g_hrtimer_list, g_hrtimer_last_expired and
g_hrtimer_running) to per-CPU variables with the BMP/SMP macros for SMP
support, and add hrtimer_initialize() called from nx_start() to
initialize the per-CPU queue at runtime.

Co-authored-by: buxiasen <buxiasen@xiaomi.com>
Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
The hrtimer structure content should not be accessed directly by
users, so provide a predicate for the "is the timer armed" question
needed by the watchdog upper half status query.  It is defined by the
remaining time reported by hrtimer_gettime(): a non-zero remainder
means the timer is pending and has not expired yet, which matches the
former wdog func based test except at the instant of expiration.  The
gettime implementation clamps a negative remainder to zero, so unused
and cancelled timers are reported inactive without wraparound.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Fix-Point and others added 19 commits December 2, 2026 10:13
This change removes conditional compilation for CONFIG_HRTIMER, simplifying the wdog code. The legacy tick-based watchdog code is removed, unifying the implementation to use hrtimer. This is part of the effort to enable CONFIG_HRTIMER by default.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Replace the wdog that triggers the scheduler event with an hrtimer:

- g_sched_event becomes an hrtimer_t.
- nxsched_wdog_expiration() becomes nxsched_hrtimer_expiration(), which
  returns the delay to the next scheduler event so that the hrtimer core
  re-arms the timer itself.
- nxsched_process_event() returns the next delay instead of re-arming the
  timer, and nxsched_timer_start() arms the hrtimer with hrtimer_start().

An in-expiration flag lets nxsched_reassess_timer() skip the re-arm when
the callback has already done it.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
In nxsched_process_timer(), the local struct timespec ts is declared
without an initializer.  up_timer_gettime(&ts) is expected to fill it,
but Coverity's MISRA Rule 9.1 check cannot see across the call and flags
clock_time2nsec(&ts) on the next line as reading an object with automatic
storage duration before it has been set.

Zero-initialize ts at declaration so every member has a defined value
before any read.  up_timer_gettime() still overwrites it as before, so
runtime behavior is unchanged.

Coverity CID: 3933998
Checker: MISRA C-2012 Rule 9.1

Co-authored-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: dengwenqi <dengwenqi@xiaomi.com>
Add hrtimer support to workqueue module:
- Add hrtimer to kwork_wqueue_s structure
- Use hrtimer in work_timer_reset
- Add work_timer_expired hrtimer callback

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Remove the up_alarm_tick_start, up_alarm_tick_cancel, up_timer_tick_start
and up_timer_tick_cancel wrappers that merely converted ticks to timespec
and delegated to the timespec variants.  No in-tree caller uses them
after the hrtimer conversion, so they are dead code.

Also replace the NULL check in up_timer_getmask with DEBUGASSERT since
the caller always ensures the lower-half is registered.

This simplifies the arch interface and reduces code memory footprint.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Replace the hrtimer tree/list/head globals (g_hrtimer_tree,
g_hrtimer_list, g_hrtimer_head) with a struct hrtimer_queue_s instance
(g_hrtimer_queue), and move the queue operations
(hrtimer_queue_initialize/first/insert/remove) into out-of-line
functions in hrtimer_queue.c.  The queue owns its tree (or sorted list)
and, in tree mode, the cached earliest node; the empty queue (NULL head)
is a valid state.

The out-of-line functions keep the code size down: the same entry points
serve both the hrtimer expiry loop and, in the next step, the wdog driver
timer.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Wrap the hrtimer_start() call in wd_timer_start() with DEBUGVERIFY()
so the int return value (OK on success, negated errno on failure) is
no longer silently discarded. Coverity flags this as CID 3933988
(Unchecked return value, MISRA C-2012 Rule 17.7).

wd_timer_start() is a void inline used from interrupt-disabled
watchdog scheduling paths and cannot meaningfully propagate an
hrtimer_start() failure to its caller. DEBUGVERIFY() is the canonical
NuttX pattern for this case (see sched/init/nx_start.c,
sched/timer/timer_settime.c, sched/task/task_recover.c): it asserts
that the call did not return a negative errno when
CONFIG_DEBUG_ASSERTIONS is enabled, and reduces to ((void)(f)) in
release builds, leaving generated code unchanged. <assert.h> is
already pulled in transitively via <nuttx/sched.h> in this header.

Coverity CID: 3933988
Type: Unchecked return value (Error handling issues)
File: sched/wdog/wdog.h:123

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: dengwenqi <dengwenqi@xiaomi.com>
Move NULL pointer checks from .c files to inline functions in the
header, allowing the compiler to optimize away redundant checks:
- Rename wd_start_abstick() to wd_start_abstick_internal() and create
  inline wd_start_abstick() wrapper with NULL checks.
- Create inline wd_start() that validates delay range and delegates
  to wd_start_abstick().
- Rename wd_cancel() to wd_cancel_internal() and create inline
  wd_cancel() wrapper with NULL check.
- Simplify wd_start_next() to use ternary expression.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Replace the ad-hoc doubly-linked wdog list (g_wdactivelist) with a
struct hrtimer_queue_s instance (g_wdqueue), reusing the hrtimer queue
infrastructure.

Key changes:

- struct wdog_s now embeds struct hrtimer_s timer only; the user
  callback is stored directly in timer.func and the absolute deadline
  in timer.expired.  WDOG_ISACTIVE checks timer.func.

- wd_start_abstick_internal / wd_cancel_internal mutate g_wdqueue via
  hrtimer_queue_insert/hrtimer_queue_remove and, when the queue head
  changes, re-arm the driver hrtimer (g_wdtimer) through the hrtimer
  API (a no-op inside wd_timer() processing, detected by
  wd_in_callback()).

- wd_timer() processes the wdog queue entirely under
  enter_critical_section(), invoking user callbacks with the critical
  section held; it returns the delay until the next wdog expiration,
  or 0 when the queue is empty.  The g_wdtimernested flag marks
  callback processing in progress for wd_in_callback().

- wd_get_next_expire() reports the queue head; wd_gettime() is now an
  inline built on hrtimer_gettime(), and the standalone wd_gettime.c
  implementation is removed.

- ipfrag uses WDOG_ISACTIVE() instead of peeking at the old func
  member; the wdog scheduler notes keep their argument swallowing.

Note: the absolute-time interfaces (wd_start_abstick_internal and the
deadline arithmetic built on clock_t) produce wrong deadlines once a
32-bit clock_t wraps.  The design assumes clock_t never overflows.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
The running slot (g_hrtimer_running) is now maintained on all builds:
the array and hrtimer_mark_running()/hrtimer_unmark_running() no longer
carry the CONFIG_SMP conditionals, so uniprocessor builds track the slot
too at negligible cost.

Add hrtimer_is_referenced() to check whether a CPU's running slot holds
a timer, in either the running or the cancel-marked form.  The
cancel-marked form only exists on SMP, where hrtimer_cancel_running()
sets it, so the non-SMP variant compares the slot with the timer pointer
directly.  hrtimer_is_running() keeps its CONFIG_SMP guard: outside SMP
the slot always holds the callback's timer while the callback runs, so
the check is a compile-time true.

Derive wd_in_callback() from hrtimer_is_referenced(): while wd_timer()
runs the slot holds g_wdtimer on this CPU, so wd_start()/wd_cancel()
called from a watchdog callback detect the in-progress processing and
skip re-arming the driver hrtimer.  This removes the g_wdtimernested flag
and its set/clear in wd_timer().

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Replace the g_in_sched_expiration flag with hrtimer_is_running(): the
hrtimer core keeps the running slot set to g_sched_event while the
expiration callback runs, so nxsched_reassess_timer() can detect that the
re-arm is already handled without an extra flag.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
wd_cancel_internal() saves the callback and the deadline into local
variables with the critical section held, so the scheduler notes
emitted after leave_critical_section() can still report the cancelled
wdog's func/expired: hrtimer_queue_remove() clears timer.func while the
queue lock is held, and reading it after the unlock would observe the
cleared value.

The empty sched_note_wdog_cancel() form now swallows its arguments so
the call site does not trip over unused-parameter warnings when the
scheduler note instrumentation is compiled out.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
…s ksram

The preallocated POSIX timer pool occupies ksram even when unused; the
nsh config only needs a small number of timers, so reduce the pool
from 4 to 2 entries to save 120 bytes of ksram.

Assisted-by: xiaomi/mimo-v2.6-pro

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
The tempbuffer pool struct carried a non-zero free_bitmap initializer,
which forced the whole struct -- including the 512-byte buffer array --
into .data and consumed that much flash.  Invert the bitmap to
used_bitmap (0 = free, its natural zero value) and drop the initializer
so the struct lands in .bss instead.

On imx93-qsb:rpmsg, which loads .data into a small ITCM, the data load
image ends at 0x0fffe00c instead of 0x0fffe204, and .bss grows by the
same 512 bytes in DTCM.  API and behavior are unchanged.

Co-authored-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
The applications built for this configuration do not need the global
libc temporary buffer; use stack variables instead.  The pool now lives
in .bss, so this saves 512 bytes of DTCM.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
The applications built for this configuration do not need the global
libc temporary buffer; use stack variables instead.  Together with the
LTO build this keeps the image inside the FLASH region.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
The nsh image overflows the FLASH region, so enable link-time
optimization to shrink the linked image.

LTO links the PIC ELF programs (CONFIG_PIC plus the external ELF test
programs) through the compiler driver, and lto1 does not receive -fpic
on that link: it rejects the explicitly passed -mpic-register=r9 as
useless without -fpic, and -Werror turns that into a link failure of
bin/errno and friends.  The option is redundant anyway -- with
-msingle-pic-base on an EABI target GCC already defaults the PIC register
to r9.  The GCC ARM options manual documents this: "For single PIC base
case, the default is 'R9' if target is EABI based or stack-checking is
enabled, otherwise the default is 'R10'."
https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html

Drop it from CELFFLAGS and CXXELFFLAGS; those flags are also handed to
the ELF link through LDELFEXEFLAGS.

[skip-cmake-parity]

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
Enable link-time optimization on the nsh configuration so that code
growth is optimized across translation units while the image stays inside
the small FLASH region.

LTO links the PIC ELF programs through the compiler driver.  The
redundant -mpic-register=r9 that lto1 rejects is already dropped from
CELFFLAGS by the preceding lx_cpu change, so the external ELF test
programs keep linking with -Werror.  r9 is GCC's default PIC register
with -msingle-pic-base on an EABI target.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
The configuration does not select an optimization level, so the Kconfig
choice defaults to DEBUG_NOOPT and the whole image is built without -O.
That also makes the LTO build pointless: at -O0 the link shrinks by only
a few bytes.

Select DEBUG_FULLOPT, which builds with -Os, and keep -g for the debug
symbols.  Together with LTO this drops .text from 259,924 to 100,960
bytes and .data from 488 to 420 bytes, leaving plenty of room in the
256 KiB FLASH region.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
@Fix-Point
Fix-Point force-pushed the wdog-hrtimer-experiment branch from b296e19 to f8e66dd Compare December 2, 2026 02:23
The hrtimer conversion adds a little code and the cansock image no longer
fits in the 64 KiB flash: GCC 13 overflows it by 40 bytes (measured 252
bytes with the local toolchain).  Dropping the stack dump frees about
1 KiB in this configuration, at the cost of the register dump on a crash.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
@Fix-Point
Fix-Point requested a review from raiden00pl as a code owner December 2, 2026 06:16
The hrtimer conversion adds a little code and the 128 KiB image overflows
by 72 bytes with GCC 13.  Dropping the stack dump frees about 1 KiB and
keeps the configuration inside the flash, at the cost of the register
dump on a crash.

Assisted-by: xiaomi/mimo-v2.6-pro
Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>

@jerpelea jerpelea left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please split the pr in logical blocks
sched: convert wdog/wqueue/tickless interfaces
boards: Enable HRTIMER unconditionally

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Arch: arm Issues related to ARM (32-bit) architecture Area: Drivers Drivers issues Board: arm Board: arm64 Board: risc-v Board: simulator Board: tricore Size: XL The size of the change in this PR is very large. Consider breaking down the PR into smaller pieces.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants