Commit graph zephyr/drivers/timer
Author SHA1 Message Date
Nicolas Pitre
586849999d drivers: timer: collapse obsolete announce-range cycle clamp
These drivers clamped the programmed deadline against the smaller of two
limits: the sys_clock_announce() range (INT32_MAX ticks) and the
cycle_diff_t width used for the cycle-to-tick division. The kernel now caps
the requested timeout in ticks (SYS_CLOCK_MAX_WAIT) and keeps the announced
tick count in range, so the announce-range limit is obsolete.

Drop it (CYCLES_MAX_1 and the MIN), leaving only the cycle-width limit. The
1/4 headroom is kept: it covers the *cycle*-domain late report (a delayed
ISR must still see a cycle delta that fits in cycle_diff_t before the
cast), which the kernel's tick-domain slack does not address. With the
announce range gone, CYCLES_MAX no longer depends on CYC_PER_TICK and
becomes a compile-time constant, so the runtime precompute is removed too.
Also drop the now-dead K_TICKS_FOREVER branches (the kernel never passes
it).

No functional change for the timeouts the kernel actually requests.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-01 23:44:31 -04:00
Nicolas Pitre
63ef20093c drivers: timer: gate deep-idle timer stop on SLOPPY_IDLE
These drivers stop or disable the timer when the kernel has no pending
timeout, which is only correct when CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE lets
the uptime skew during idle. That used to be implicit: the kernel only
passed K_TICKS_FOREVER under sloppy idle. The core now always passes a
finite value and signals "no pending deadline" with ticks ==
SYS_CLOCK_MAX_WAIT regardless of the option, so the gate must be made
explicit or a non-sloppy build would stop the timer and lose time.

Test IS_ENABLED(CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE) && ticks ==
SYS_CLOCK_MAX_WAIT before stopping, matching the ite/stm32 drivers already
converted, and drop the now-redundant idle argument from the condition. The
normal path re-enables the timer on the next sys_clock_set_timeout(), so
the stop is safe. nrf_rtc only re-keys its "no pending timeout" far-compare
and sys_busy flag to the sentinel; it does not stop the timer.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-01 23:44:31 -04:00
Nicolas Pitre
11ebcf851a drivers: timer: simplify skip/inverted K_TICKS_FOREVER guards
The kernel no longer passes K_TICKS_FOREVER to sys_clock_set_timeout(), so
the guards that skipped reprogramming (or whose inverted form gated the
normal path) on it are dead.

Unwrap the "program only when not forever" guards (cc23x0_rtc,
cc23x0_systim) and the "idle and not forever" power-management hooks
(esp32, xtensa) since the condition is now always satisfied. Drop the
idle/forever skip-returns (max32_rv32, max32_wut, openrisc). renesas_rx_cmt
and renesas_ra_ulpt tested the forever sentinel alongside INT32_MAX (==
SYS_CLOCK_MAX_WAIT); keep the single SYS_CLOCK_MAX_WAIT "no near deadline"
skip and drop the dead disjunct.

No functional change.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-01 23:44:31 -04:00
Nicolas Pitre
bbf9caf996 drivers: timer: drop dead K_TICKS_FOREVER tick clamps
The kernel core no longer passes K_TICKS_FOREVER to
sys_clock_set_timeout(): next_timeout() always returns a finite value
capped at SYS_CLOCK_MAX_WAIT. The per-driver "map K_TICKS_FOREVER to the
hardware maximum" handling is therefore dead: the requested tick count is
already bounded by the kernel and each of these drivers re-clamps to its
own hardware limit anyway.

Remove the dead K_TICKS_FOREVER mapping from the drivers whose value is
still bounded by a following hardware clamp. mchp_sam_pit64b and
xlnx_psttc, where the ternary was also the only guard before a uint32 cycle
multiply, keep an explicit clamp to their hardware maximum. native_sim,
which has no hardware limit, simply drops the special case.

No functional change.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-01 23:44:31 -04:00
Nicolas Pitre
c33571b372 kernel: timeout: cap the timeout passed to drivers centrally
sys_clock_announce() reports ticks elapsed since the previous announce. The
quantity that must stay in range is therefore the distance of the next
timeout from that announce, not its distance from "now" as next_timeout()
previously bounded. When an early timeout is repeatedly replaced by a later
one, announces are deferred and that distance can exceed the range even
though each set_timeout() delay was in range, which every driver has had to
defend against on its own.

Cap it in the core instead: SYS_CLOCK_MAX_WAIT becomes UINT32_MAX/2 (the
clamp, with the upper half of the range left as slack for a late announce)
and next_timeout() clamps the inter-announce distance to it. Drivers no
longer need to clamp for the announce range and only have to honour their
own cycle-count limits.

The core no longer emits K_TICKS_FOREVER; the reported delay is always
finite, saturating at SYS_CLOCK_MAX_WAIT. Drivers that stop the timer
entirely when idle now key off ticks == SYS_CLOCK_MAX_WAIT under
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE.

z_get_next_timeout_expiry() still reports to the idle and PM paths as a
signed int32_t. It keeps its K_TICKS_FOREVER default and adopts the
next_timeout() value only when that fits, so the unsigned cap can never
surface there as a negative number.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-01 23:44:31 -04:00
Nicolas Pitre
f4a2a27071 kernel: timeout: make the system clock tick interface unsigned
The sys_clock_set_timeout(), sys_clock_announce() and
sys_clock_announce_locked() interfaces carry a number of ticks to be
scheduled or announced. Those ticks have no negative meaning, so a signed
argument is both wasteful and error prone: it invites incorrect handling in
drivers and it halves the range that sys_clock_announce() can represent.

Switch the tick argument of these interfaces, along with the internal
announce_remaining accounting, from int32_t to uint32_t. This is a
mechanical change: driver bodies perform plain arithmetic on the value and
are unaffected by the signedness, and the kernel never passes a negative
tick count. The freed sign bit doubles the representable announce range,
which a later change will use to move the announce range limit out of the
drivers and into the core.

One config is not strictly neutral: under CONFIG_TIMEOUT_64BIT,
K_TICKS_FOREVER is a 64-bit value that an unsigned 32-bit argument can no
longer compare equal to, so the K_TICKS_FOREVER tests in drivers stop
matching there. K_TICKS_FOREVER is a k_ticks_t concept and has no business
in this tick count interface; a follow-up removes it from the driver side
entirely, which closes this gap.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-01 23:44:31 -04:00
Jun Lin
043b965ecf drivers: timer: npcx: fix potential elapsed cycle underflow
Fix a potential underflow bug in npcx_itim_evt_elapsed_cyc32() that
occurs when cyc_evt_timeout is 1. The timer register is programmed with
MAX(cyc_evt_timeout - 1, 1), but the elapsed calculation used
cyc_evt_timeout - cnt2 - 1, causing an off-by-one mismatch.

When cyc_evt_timeout=1:
- Register is set to MAX(0, 1) = 1
- If read before first tick (cnt=1), elapsed = 1 - 1 - 1 = -1
- This underflows to 0xffffffff (~36 hours worth of cycles)

This can trigger a watchdog reset: the massive elapsed value causes
sys_clock_announce() to run all scheduled tasks in a tight loop,
starving the watchdog feeder.

Fix by mirroring the same MAX(cyc_evt_timeout - 1, 1) logic used when
programming the timer, ensuring the elapsed calculation matches the
actual start value.

Signed-off-by: Jun Lin <CHLin56@nuvoton.com>
2026-06-30 18:22:31 -04:00
Etienne Carriere
b0b25c35c9 drivers: use <> to include Zephyr headers instead of ""
Use <> operator to include a Zephyr header file instead of "" that
is intended to local header files, not header files relative to
specifically defined search paths.

This change was made running the sed shell command below:
$ sed -i -E 's/#include "zephyr\/([^"]+)\.h"/#include <zephyr\/\1.h>/g' \
    `grep -rsl "#include \"zephyr/" drivers/`

Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
2026-06-30 06:49:18 -04:00
Anas Nashif
96bbd46fa6 x86: loapic: make interrupt bit operations unsigned
Address MISRA integer essential-type findings in the LOAPIC and HPET
paths by making bitmask constants explicitly unsigned and by using
width-safe shifts/casts in register programming code.

The changes are mechanical and preserve behavior while avoiding signed
intermediate expressions in operations that feed uint32_t register
writes.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-06-26 22:30:03 -04:00
Mika Braunschweig
ee994a9501 driver: timer: ti_dmtimer: set device statically instead at initialization
This assigns the device pointer used for the timer during compile time
instead of assigining it at runtime during initialization. This prevents
overwriting the exception vector on Cortex-R5 cores, if a timer is used
before the kernel initialization finished.

Signed-off-by: Mika Braunschweig <mika.braunschweig@siemens.com>
2026-06-26 13:02:17 -04:00
Holt Sun
671ed7c118 drivers: timer: add NXP STM system timer driver
Add an MCUX STM system timer driver selected through the existing
nxp,stm devicetree node referenced by zephyr,system-timer. The driver
uses the free-running STM counter and channel 0 absolute compare to
implement tickful and tickless sys_clock hooks.

The counter clock is derived at runtime from the STM clock-control
provider and the node prescaler, avoiding a second devicetree
clock-frequency source. The deadline math follows the same
last_elapsed model used by the ARM architectural and RISC-V machine
timer drivers, and uses sys_clock_announce_locked() so the kernel
clock lock is shared.

STM compare channels assert only when CNT matches CMP, so compare
programming uses a read-back/retry loop to ensure the programmed value
is genuinely ahead of the current counter and cannot be missed until
32-bit wraparound.

The STM counter driver skips the instance selected as the system timer,
so enabling both drivers does not reinitialize the same hardware.

Validated with west build -p always -b frdm_mcxe31b
zephyr/tests/kernel/timer/timer_behavior and strict UART capture on
FRDM-MCXE31B; all timer_behavior suites passed. Also built the same
test with CONFIG_COUNTER_MCUX_STM=y to cover the skipped counter
instance path.

Signed-off-by: Holt Sun <holt.sun@nxp.com>
2026-06-26 07:46:02 -04:00
Nicolas Pitre
97fac4b782 kernel: mmu: remove LINKER_USE_PINNED_SECTION and __pinned_* tagging
CONFIG_LINKER_USE_PINNED_SECTION is the second half of the selective
kernel-pinning model removed in issue #108773. With the kernel image
now always resident at boot (previous commit), the __pinned_*
attribute family is a no-op: every page they would have segregated is
already pinned by z_mem_manage_init()'s whole-image loop, so the
tagging contract neither adds safety nor remains maintainable.

Drop it.

Mechanical removals:

* All ~219 in-tree uses of __pinned_text, __pinned_rodata,
  __pinned_data, __pinned_bss, __pinned_noinit, and __pinned_func
  across arch/x86, drivers/interrupt_controller, drivers/timer,
  arch/common, kernel, lib/libc, subsys/portability/posix, tests, and
  the syscall code generator (scripts/build/gen_syscalls.py).

* The assembly aliases PINNED_TEXT/RODATA/DATA/BSS/NOINIT used in
  arch/x86/core/ia32/*.S and drivers/interrupt_controller/
  intc_loapic_spurious.S become plain TEXT/RODATA/DATA/BSS/NOINIT.

* K_KERNEL_PINNED_STACK_DEFINE, K_KERNEL_PINNED_STACK_ARRAY_DEFINE,
  K_KERNEL_PINNED_STACK_ARRAY_DECLARE, K_THREAD_PINNED_STACK_DEFINE,
  and K_THREAD_PINNED_STACK_ARRAY_DEFINE are removed. The few
  in-tree callers (kernel/init.c, arch/arm/core/cortex_a_r/smp.c,
  arch/arm64/core/fatal.c, arch/rx/core/prep_c.c,
  arch/x86/core/prep_c.c, kernel/include/kernel_internal.h,
  tests/bluetooth/hci_uart_async) move to the corresponding
  non-pinned macros.

Machinery removals:

* Kconfig.zephyr drops CONFIG_LINKER_USE_PINNED_SECTION.
  qemu_x86_tiny and qemu_x86_atom_virt drop their =y overrides.

* include/zephyr/linker/section_tags.h drops the __pinned_* macro
  definitions (both arms). __isr collapses to an empty macro since
  its only purpose was to alias __pinned_func.

* include/zephyr/linker/sections.h drops PINNED_TEXT_SECTION_NAME,
  PINNED_BSS_SECTION_NAME, etc. and the bare PINNED_TEXT/RODATA/etc.
  forwarders, plus the _APP_SMEM_PINNED_SECTION_NAME constant.

* include/zephyr/linker/linker-defs.h drops the lnkr_pinned_*
  externs, the _app_smem_pinned_* externs, and the lnkr_is_pinned()
  / lnkr_is_region_pinned() inline helpers.

* include/zephyr/linker/utils.h drops the lnkr_pinned_rodata branch
  in linker_is_in_rodata().

* include/zephyr/linker/app_smem_pinned{,_aligned,_unaligned}.ld
  are deleted; cmake/linker/ld/target_configure.cmake stops
  configuring them.

* boards/qemu/x86/qemu_x86_tiny.ld and
  include/zephyr/arch/x86/ia32/linker.ld drop their pinned-section
  blocks and the now-redundant #ifndef CONFIG_LINKER_USE_PINNED_SECTION
  conditionals throughout the body. The
  LIB_KERNEL_IN_SECT / LIB_ARCH_X86_IN_SECT / LIB_ZEPHYR_IN_SECT /
  LIB_C_IN_SECT / LIB_DRIVERS_IN_SECT / LIB_SUBSYS_LOGGING_IN_SECT /
  LIB_ZEPHYR_OBJECT_FILE_IN_SECT / ZEPHYR_KERNEL_FUNCS_IN_SECT macros
  in qemu_x86_tiny.ld are deleted; they existed only to feed the
  pinned text/rodata/data/bss/noinit sections.

* kernel/mmu.c drops the mark_linker_section_pinned(lnkr_pinned_start,
  ...) call. The mark_linker_section_pinned() helper survives but is
  now gated only on CONFIG_LINKER_USE_BOOT_SECTION.

* arch/common/init.c and include/zephyr/arch/common/init.h drop
  arch_bss_zero_pinned(); arch/x86/core/ia32/crt0.S drops the call
  to it.

* arch/x86/core/userspace.c drops the eager k_mem_page_in() of the
  thread's privileged stack on user-mode entry. With the kernel
  image fully resident the stack is already mapped.

* arch/x86/gen_mmu.py drops map_region("lnkr_pinned") and the
  set_region_perms() calls for lnkr_pinned_text / lnkr_pinned_rodata.

* CMakeLists.txt drops the LINKER_USE_PINNED_SECTION block that
  generated APP_SMEM_PINNED_* variables and the
  pinned_partitions target property feeding gen_app_partitions.py.
  cmake/modules/extensions.cmake removes the PINNED_RODATA /
  PINNED_RAM_SECTIONS / PINNED_DATA_SECTIONS zephyr_linker_sources()
  location keywords and their snippet files.
  scripts/build/gen_app_partitions.py drops --pinoutput /
  --pinpartitions arguments and the pinned-output branch.
  subsys/testsuite/coverage/CMakeLists.txt drops its
  CONFIG_DEMAND_PAGING-conditional fork.

* scripts/build/gen_kobject_list.py drops the
  app_smem_pinned_start / _end fallback for kobject placement
  validation.

* tests/arch/x86/pagetables and tests/kernel/mem_protect/userspace
  drop their lnkr_pinned_text / lnkr_pinned_rodata branches.

* include/zephyr/arch/x86/ia32/arch.h folds IRQSTUBS_TEXT_SECTION
  to the unconditional ".text.irqstubs" form.

* tests/subsys/llext/src/syscalls_ext.c drops a stale comment about
  syscalls landing in .pinned_text.

Targeted retentions:

* arch/x86/core/bootargs.c keeps multiboot_cmdline and efi_bootargs
  in .noinit (was __pinned_noinit, which decayed to __noinit when
  LINKER_USE_PINNED_SECTION was unset). The multiboot and zefi loader
  paths write these buffers before Zephyr's BSS-zero step, so
  zeroing them at boot loses the cmdline.

* arch/x86/core/ia32/fatal.c keeps _df_esf and _df_stack in .noinit.
  They are scratch space written by the double-fault handler and have
  no zero-init requirement; keeping them in .noinit also preserves
  the historical post-noinit alignment that gen_mmu.py relies on
  (z_mapped_size is computed before CMake-injected iterable sections
  are appended to the linker script, so the post-noinit page padding
  is what keeps those sections within the mapped region).

* include/zephyr/arch/x86/ia32/syscall.h and
  include/zephyr/arch/x86/arch.h wrap the per-arch
  arch_syscall_invoke* / arch_is_user_context / arch_k_cycle_get_*
  implementations in @cond INTERNAL_HIDDEN. The public Doxygen
  contract lives on the prototypes in
  include/zephyr/arch/arch_interface.h; the per-arch implementations
  are internal. Without this, removing the __pinned_func attribute
  exposes the implementations to the doxygen-coverage delta check
  as 10 newly-undocumented APIs.

Documentation updates are deferred to a separate commit.

Issue: #108773

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-06-23 09:11:08 -04:00
Albort Xue
b02f480197 drivers: timer: mcux_lptmr: fix WUC wakeup source not configured
The LPTMR system timer driver used WUC_DT_SPEC_INST_GET_OR() which
relies on DT_DRV_COMPAT to resolve the device instance. Since the
system timer obtains its node via DT_CHOSEN(zephyr_system_timer)
rather than the standard device model, DT_DRV_COMPAT is undefined
and the macro silently falls back to the default value {0}. This
leaves wuc.dev as NULL and wuc_enable_wakeup_source_dt() is never
called, so the WUU module wakeup source for LPTMR is not programmed.

On MCXW7xx platforms this means timed wakeup from low-power states
fails: the board enters sleep and never returns.

Use WUC_DT_SPEC_GET_OR(LPTMR_NODE, ...) instead, which resolves
directly from the chosen system-timer node where the wakeup-ctrls
property is defined.

Signed-off-by: Albort Xue <yao.xue@nxp.com>
2026-06-22 17:57:12 +02:00
Felix Wang
9a3132026f drivers: timer: add NXP System Counter (SYS_CTR) timer driver
Add a system clock driver built on top of the NXP System Counter
(SYS_CTR) block, which provides a 56-bit free-running counter and two
compare frames capable of generating maskable interrupts.

The driver is a free-running counter paired with an absolute compare
register. Compare frame 0 is used for the system timer, leaving frame
1 available for other consumers. The instance is selected via the
zephyr,system-timer chosen property.

Signed-off-by: Felix Wang <fei.wang_3@nxp.com>
2026-06-19 11:09:36 +02:00
Anas Nashif
ea1fbf3588 driver: fix various typos
Fixed various typos under drivers/

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-06-17 10:12:27 -04:00
Peter Mitsis
794134a5ab drivers: timer: simplify intel_adsp_timer
Simplifies the sys_clock_set_timeout() calculation used to determine
the next correct cycle at which to trigger the timer interrupt. There
is no risk that number of cycles we are adding will exceed MAX_CYCLES.

--

Furthermore, should the current cycle count match the 'last_count',
it prevents the timer from firing one tick too early. That firing
would not lead to miscount of ticks, nor mis-execution of handlers.
However it could lead to one extra timer interrupt being processed
unnecessarily.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2026-06-16 23:16:20 +02:00
Nicolas Pitre
860bbbcbdb drivers: timer: nrf_rtc_timer: switch to absolute tick-aligned deadlines
sys_clock_set_timeout() computed the compare value as

    cyc = ticks * CYC_PER_TICK + unannounced;
    cyc = DIV_ROUND_UP(cyc, CYC_PER_TICK) * CYC_PER_TICK;
    target = last_count + cyc;

The DIV_ROUND_UP forces the fire onto the next tick boundary *after*
the requested point, but the driver never subtracts the unannounced
sub-tick offset back out. When the caller arms partway through a tick
(the common case), the timer therefore fires one tick later than the
kernel asked for -- k_timer_start(K_TICKS(N), ...) ends up firing at
roughly N+2 ticks instead of N+1.

Adopt the absolute tick-aligned deadline pattern already proven in
arm_arch_timer.c and riscv_machine_timer.c:

  - Track last_elapsed: the tick count the kernel last observed via
    sys_clock_elapsed(). Reset to 0 in the handler at announce.
  - sys_clock_set_timeout() computes the target as
      target = last_count + (last_elapsed + ticks) * CYC_PER_TICK
    and clamps the cycle delta from last_count at MAX_CYCLES so the
    24-bit compare register is satisfied relative to the current
    counter.
  - The handler reads the current counter (not the scheduled expire
    time) to compute dticks, advancing last_count to the actual tick
    boundary just past now in one shot. This subsumes the previous
    "wrap protection" branch: a large unannounced delta naturally
    produces a target in the past, compare_set forces an immediate
    IRQ, and the handler catches up in a single invocation.
  - sys_clock_elapsed() records the delta in last_elapsed.

A v1 of this change (commit 67a29d7f98 ("drivers: timer:
nrf_rtc_timer: switch to absolute tick-aligned deadlines"), since
reverted) kept a separate "if unannounced >= COUNTER_HALF_SPAN,
target = last_count" branch. That broke the handler invariant:
dticks evaluated to zero, last_count never advanced, and the ISR
re-pended in an infinite loop once the counter naturally crossed
COUNTER_HALF_SPAN (~4m17s on nrf52). The structural change above
removes the need for any such recovery branch.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-06-16 17:44:04 +02:00
Nicolas Pitre
b02731645b drivers: timer: leon_gptimer: convert to a tickless driver
The driver drove subtimer 0 as a fixed periodic source whose ISR always
called sys_clock_announce(1), and sys_clock_elapsed() returned 0. Two
consequences:

- A periodic interrupt serviced more than one tick period late dropped
  the missed ticks (announce(1) cannot catch up), so uptime fell behind
  real time.

- With elapsed() pinned at 0, k_uptime_ticks() advanced only at tick
  interrupts, so it lagged real time by a variable 0..1 tick. At a fine
  tick rate this made tick-quantized measurements (e.g. the time-slice
  tests) come up a tick short.

The hardware already exposes what a proper driver needs: subtimer 1 runs
as a free-running 1 MHz up-counter. Use it as the definitive time base
and make the driver tickless:

- sys_clock_elapsed() reports whole ticks since the last announce, read
  from the free-running counter.
- sys_clock_set_timeout() computes an absolute tick-aligned deadline
  (announced + (last_elapsed + ticks) periods) and programs it as a
  one-shot relative delay on subtimer 0, since GPTIMER has no absolute
  compare register.
- The ISR derives the elapsed tick count from the free-running counter
  and announces all of it, so a late or coalesced interrupt no longer
  drops ticks.

When CONFIG_TICKLESS_KERNEL=n the driver keeps subtimer 0 periodic and
announces from the same free-running base, so the non-tickless path is
preserved. select TICKLESS_CAPABLE accordingly.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-06-12 00:24:48 +02:00
Holt Sun
699c4a5ec8 drivers: timer: default mcux lptmr from chosen
Make the MCUX LPTMR system timer follow the devicetree
zephyr,system-timer chosen node again. The symbol still depends on the
chosen node being enabled and compatible with nxp,lptmr, so the driver
is only selected when DTS names an LPTMR as the system timer.

This keeps devicetree as the source of truth for the selected system
timer and avoids builds where DTS points at LPTMR but Kconfig silently
keeps SysTick.

Validated with configure-only builds for FRDM-MCXW70, FRDM-MCXW71,
FRDM-MCXW72, TWR-KE18F, FRDM-MCXC444, and i.MX95 M7. Also ran
FRDM-MCXW72 hello_world and FRDM-MCXC444 power_mgmt_soc on hardware.

Signed-off-by: Holt Sun <holt.sun@nxp.com>
2026-06-11 09:11:26 +02:00
Etienne Carriere
bdb16a8b51 drivers: timer: stm32: Use kernel log level for radio timer
Use CONFIG_KERNEL_LOG_LEVEL in STM32 radio timer driver to rely on kernel
log level instead of the default generic log level configuration.

Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
2026-06-10 14:55:40 -04:00
Etienne Carriere
cd21ca2db6 drivers: timer: stm32_lptim: use DT_NODE_HAS_PROP() instead of DT_PROP()
Replace DT_NODE_HAS_PROP() instead DT_PROP() to test presence of
st,timeout property since it's more consistent. The DT property min value
is 1 hence testing against value 0 makes no sense.

Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
2026-06-08 13:55:00 +02:00
Sylvio Alves
40e13d301b drivers: timer: esp32: enable systimer on esp32p4
Add SOC_SERIES_ESP32P4 to the dependency list of the Espressif
systimer driver so it is selected by default and provides the
sys_clock_elapsed implementation the kernel needs.

Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
2026-06-03 18:27:15 -04:00
Amneesh Singh
9969745801 drivers: update interrupt handling to use "flags" instead of "sense"
Update all drivers to use "flags" instead of "sense" when accessing
interrupt properties from device tree. This aligns with the updated
interrupt controller bindings that now consistently use "flags" as
the cell name for the IRQ type field.

Signed-off-by: Amneesh Singh <amneesh@ti.com>
2026-06-01 12:38:26 -04:00
Shreyas Shankar
d2a8500223 drivers: timer: ti_rtitimer: Add initial support for TI RTI Timer
Add support for using RTI hardware as system timer:

- Add headers, driver code, Kconfig, and bindings for TI RTI Timer
- Make changes in CMakeLists.txt and Kconfig to support ti_rti_timer
- Add documentation and usage instructions in bindings file.

NOTE: Each RTI has 2 Counter blocks, 4 Counter Compare blocks.
This driver assumes that Counter block 0, Compare block 0 of
chosen RTI instance are used as RTI Timer.

Signed-off-by: Shreyas Shankar <s-shankar@ti.com>
2026-05-31 13:39:47 +02:00
Romain Jayles
22fafcfaee drivers: stm32_lptim_timer: check DIEROK on all the relevant socs
Others socs series also have a DIEROK flag to check.
The stm32_lptim_timer has been modificated accordingly

Signed-off-by: Romain Jayles <romain.jayles@st.com>
2026-05-29 22:08:20 +02:00
Jonathan Elliot Peace
3f9ceb7135 drivers: timer: arm_arch: allow custom interrupt controller
The arm_arch_timer driver only uses the architecture-level
IRQ_CONNECT/irq_enable abstractions, both of which dispatch through
arch_irq_*() and therefore work whether the underlying interrupt
controller is a GIC or a SoC-supplied custom controller. The latter
is selected via CONFIG_ARM_CUSTOM_INTERRUPT_CONTROLLER, in which
case the arm64 arch layer maps the calls to the SoC-provided
z_soc_irq_* hooks.

The "depends on GIC" predates custom-intc support landing in arm64
and is artificially restrictive. Relax it so non-GIC arm64 SoCs can
reuse the canonical timer driver instead of cloning it.

The driver itself is unchanged.

Signed-off-by: Jonathan Elliot Peace <jep@alphabetiq.com>
2026-05-27 21:32:13 -04:00
Mathieu Choplain
2b84616e19 drivers: timer: move the LPM_COMPANION_COUNTER hooks to common code
The implementation of the "system timer low-power companion interface"
when CONFIG_SYSTEM_TIMER_LPM_COMPANION_COUNTER is selected is generic,
but was done in the Cortex-M SysTick driver for historical reasons.

Move the implementation to a common source file included in the build
when CONFIG_SYSTEM_TIMER_LPM_COMPANION_COUNTER is selected. This cleans
up the Cortex-M SysTick driver and allows other system timer drivers to
benefit from the code.

Signed-off-by: Mathieu Choplain <mathieu.choplain-ext@st.com>
2026-05-27 21:31:46 -04:00
Nicolas Pitre
6485341c59 drivers: timer: cortex_m_systick: migrate to sys_clock_lock()
Replace the driver-private spinlock with the unified timer lock API
introduced by commit 32b1399669 ("kernel/timeout: introduce
sys_clock_lock() and sys_clock_announce_locked()"), following the
pattern already applied to other SMP-capable timer drivers.

No in-tree board enables CONFIG_SMP on a Cortex-M, so the specific
two-CPU race that motivated that commit does not apply here. The
same two-lock window is still reachable in UP, though: a nested IRQ
handler that uses time facilities can fire between sys_clock_isr()'s
update of the hardware baseline (cycle_count, announced_cycles,
under the driver-private lock) and the sys_clock_announce() call
that advances curr_tick (under the kernel's timeout_lock), see the
two halves of "now" out of sync, and observe time going backwards
from one call to the next. Putting the hardware cycle baseline and
curr_tick under a single lock closes that window the same way it
does on SMP.

As a direct consequence, sys_clock_set_timeout() and
sys_clock_elapsed() no longer need to acquire anything -- the caller
already holds the kernel timeout lock across both the driver call
and the following sys_clock_announce(). The driver is now consistent
with the convention used by all the other timer drivers.

sys_clock_cycle_get_32() / sys_clock_cycle_get_64() /
sys_clock_idle_exit() / z_sys_clock_hw_cycles_per_sec_update() are
called from contexts that do not hold the kernel's timeout lock, so
they acquire it via sys_clock_lock() themselves.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-05-27 21:29:35 -04:00
Nicolas Pitre
bd7a21126e drivers: timer: cortex_m_systick: use absolute-cycle deadlines
Rework sys_clock_set_timeout() along the same lines as the RISC-V
machine timer (drivers/timer/riscv_machine_timer.c) and ARM generic
timer (drivers/timer/arm_arch_timer.c) drivers: compute the absolute
cycle target for the next fire and program SysTick for the delta to
it, rather than reconstructing a tick-aligned fire point on every
call through the old "-1, round up to tick boundary, subtract
unannounced" dance.

The core of the computation shrinks from:

    delay = ticks * CYC_PER_TICK;
    delay += unannounced;
    delay = DIV_ROUND_UP(delay, CYC_PER_TICK) * CYC_PER_TICK;
    delay -= unannounced;
    delay = MAX(delay, MIN_DELAY);
    if (delay > MAX_CYCLES) { last_load = MAX_CYCLES; }
    else                     { last_load = delay; }

into:

    int64_t want  = ((uint64_t)last_elapsed + ticks) * CYC_PER_TICK;
    int64_t delta = want - unannounced;
    cycles = CLAMP(delta, MIN_DELAY, MAX_CYCLES);
    SysTick->LOAD = cycles - 1;

No tick-boundary realignment and no DIV_ROUND_UP round-trip. The
64-bit intermediate absorbs arbitrarily large 'ticks' without
overflowing the 32-bit cycle product. The division-by-CYC_PER_TICK
that lived in the hot path is gone (divisions by non-constant
divisors are costly even on 32 bits, so avoiding them where we can
is worthwhile).

Concretely:

* Track last_elapsed -- the tick count most recently returned to the
  kernel via sys_clock_elapsed() -- and use it as the "now" reference
  when computing the deadline. sys_clock_isr() resets last_elapsed
  to 0 on every announce.

* The pre-clamp on 'ticks' and the MAX_TICKS derivation are gone:
  the clamp applies to the computed cycle count (the quantity the
  hardware LOAD register actually constrains), and MAX_CYCLES is
  the 24-bit COUNTER_MAX directly.

* Explicitly clear SCB->ICSR PENDSTCLR on every reprogram. Writing
  SysTick->VAL = 0 clears CTRL.COUNTFLAG but leaves any pending
  SysTick exception from the old schedule armed in ICSR. Without this
  explicit clear, a wrap that fired between sys_clock_elapsed() and
  the LOAD/VAL reset would still trigger the ISR once interrupts are
  re-enabled, with the ISR then reading the new LOAD/VAL and
  mis-accounting the elapsed time. Matches the pattern already used
  in the LPM RESET_BY_LPM path.

The elapsed() helper, overflow_cyc bookkeeping, LPM companion paths,
runtime frequency update, 64-bit cycle counter variant, the val1/val2
drift-compensation dance around the LOAD/VAL write, and the
non-tickless fallback are untouched. The wire-level behaviour is
identical in the normal case; the only observable behaviour change
is the PENDSTCLR write, which closes a latent race that could delay
a stale ISR by one LOAD worth of cycles.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-05-27 21:29:35 -04:00
Zhiyuan Tang
95f28b3ccf drivers: timer: cortex_m_systick: add zephyr,min-timeout-cycles property
Add support for configuring the minimum timer delay via the Devicetree
property 'zephyr,min-timeout-cycles'. This is particularly useful for
platforms using low-frequency clock sources (e.g., 32.768 kHz).

The driver's default MIN_DELAY is MAX(1024, CYC_PER_TICK / 16). On a
system with a 32.768 kHz clock and CONFIG_SYS_CLOCK_TICKS_PER_SEC=1000,
CYC_PER_TICK is 32. This results in a MIN_DELAY of 1024 cycles, which
translates to a ~31 ms minimum timeout. This granularity is too
coarse for tickless operation and causes failures in tests that expect
sub-10ms precision.

This change allows boards to override this limit, enabling finer timing
resolution while maintaining the existing default for backward
compatibility.

Signed-off-by: Zhiyuan Tang <zhiyuan_tang@realsil.com.cn>
2026-05-27 21:28:04 -04:00
Amneesh Singh
f96fe2a675 timer: ti_dmtimer: allow configuring timer clock source
Allow configuring the clock source for TI's dmtimer using syscon driver for
MMR writes. The new property "clksel" takes offset and value to select
the mux configuration.

This is required since there are no clock parent APIs in the clock
controller subsystem as of now.

Signed-off-by: Amneesh Singh <amneesh@ti.com>
2026-05-27 21:27:24 -04:00
Henrik Brix Andersen
cdb5827599 drivers: timer: stm32: lptim: select CONFIG_RESET
Select CONFIG_RESET as the STM32 Low Power Timer (LPTIM) driver depends on
it.

Signed-off-by: Henrik Brix Andersen <henrik@brixandersen.dk>
2026-05-26 15:26:26 +02:00
Alberto Escolar Piedras
c2c6a2da39 Revert "drivers: timer: nrf_rtc_timer: switch to absolute tick-aligned deadlines"
This reverts commit 67a29d7f98.

After this commit a BT testcase
tests/bsim/bluetooth/ll/throughput/tests_scripts/\
gatt_write_no_phy_update.sh
started failing, where the RTC1 interrupt fires
in an infinite loop after 4m:17s.

This is blocking all BT related PRs.
Let's revert this commit while the issue is debugged to unblock
development.

Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
2026-05-18 10:45:57 +02:00
Davide Di Lello
58f192e773 drivers: infineon: Update copyright for Infineon
Update structure of the copyright

Signed-off-by: Davide Di Lello <Davide.Dilello@Infineon.com>
2026-05-15 23:27:34 +02:00
Nicolas Pitre
67a29d7f98 drivers: timer: nrf_rtc_timer: switch to absolute tick-aligned deadlines
sys_clock_set_timeout() computed the compare value as

    cyc = ticks * CYC_PER_TICK + unannounced;
    cyc = DIV_ROUND_UP(cyc, CYC_PER_TICK) * CYC_PER_TICK;
    target = last_count + cyc;

The DIV_ROUND_UP forces the fire onto the next tick boundary *after*
the requested point, but the driver never subtracts the unannounced
sub-tick offset back out. When the caller arms partway through a tick
(the common case), the timer therefore fires one tick later than the
kernel asked for -- k_timer_start(K_TICKS(N), ...) ends up firing at
roughly N+2 ticks instead of N+1. This is what GoranWall observed on
nrf52840dk: the new tests/kernel/timer/timer_behavior ramp test fails
on specific delay values.

Compute the target directly as

    target = last_count + (last_elapsed + ticks) * CYC_PER_TICK

where last_elapsed is the tick count the kernel last observed via
sys_clock_elapsed(), and last_count is tick-aligned by construction.
The fire lands at exactly (last_elapsed + ticks) ticks past the last
announce, regardless of when within a tick the caller armed.

Track last_elapsed in sys_clock_elapsed() and reset it in
sys_clock_timeout_handler() at announce. The COUNTER_HALF_SPAN
wrap-protection check is preserved. Clamp on ticks alone since the
24-bit compare register limit is relative to the current counter,
and target - now = ticks * CYC_PER_TICK - sub_tick.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-05-15 10:46:00 +02:00
Holt Sun
6e98d8e160 drivers: timer: fix MCUX LPTMR wrap accounting
Some MCUX LPTMR instances expose counters narrower than 32 bits.

Raw uint32_t subtraction in tickless mode can treat a 16-bit

hardware wrap as a 32-bit wrap.

Compute elapsed time and compare distances in the hardware counter

domain with COUNTER_MAX.

Signed-off-by: Holt Sun <holt.sun@nxp.com>
2026-05-14 12:04:12 +02:00
Felix Wang
3824308e58 drivers: timer: mcux_lptmr: fix long-term tick drift in tickless mode
Previously announced_cycles was set directly to the current counter
value, which includes sub-tick remainder cycles from ISR latency.
Over time these remainders accumulate, causing the announced tick
boundary to drift away from the true tick grid.

Advance announced_cycles in whole-tick increments instead, so that
the sub-tick fraction is naturally absorbed by the next interval
rather than compounding across interrupts.

Signed-off-by: Felix Wang <fei.wang_3@nxp.com>
2026-05-13 10:35:38 +02:00
Davide Di Lello
82741b2614 drivers: infineon: Update copyright for Infineon
Update structure of the copyright

Signed-off-by: Davide Di Lello <Davide.Dilello@Infineon.com>
2026-05-12 22:19:02 +02:00
Adam Kondraciuk
98395af2b2 drivers: timer: nrf_grtc_timer: Add Kconfig options for uninit behavior
Add Kconfig options to control whether the GRTC timer is stopped
and/or cleared when the driver is uninitialized (e.g. when
sys_clock_disable() is called).

Signed-off-by: Adam Kondraciuk <adam.kondraciuk@nordicsemi.no>
2026-05-08 06:45:11 -05:00
Holt Sun
0c4382ae5e drivers: timer: keep mcux_lptmr policy explicit
Selecting MCUX_LPTMR_TIMER directly from
/chosen/zephyr,system-timer broadens the default behavior for
any SoC DTSI that now sets the chosen node. KE1xF only
intends to use LPTMR under PM, while MCX-W7xx and i.MX95 M7
still require their SoC-specific selection rules.

Keep the generic Kconfig selection policy implicit and retain
the SoC-specific enablement rules in the MCX-W7xx and i.MX95
M7 defconfigs.

This keeps the chosen-based instance selection while avoiding
unintended system timer changes outside the narrow fix scope.

Signed-off-by: Holt Sun <holt.sun@nxp.com>
2026-05-05 15:59:14 +01:00
Nicolas Pitre
75bef580e9 drivers: timer: arm_arch_timer: fix truncation in arch_busy_wait
The custom arm_arch_timer arch_busy_wait() computed the wait duration as:

    cycles_to_wait = sys_clock_hw_cycles_per_sec() / USEC_PER_SEC *
                     (uint64_t)usec_to_wait;

Integer division applied first. When the timer frequency is not an
integer multiple of USEC_PER_SEC (e.g. 62.5 MHz on Cortex-A53), the
fractional cycles-per-microsecond are silently dropped, making every
call to k_busy_wait() return short by up to 0.8% of the requested
duration -- breaking the API contract that busy_wait() is guaranteed
to wait at least the requested number of microseconds.

Replace the open-coded conversion with k_us_to_cyc_ceil64(), which
multiplies first and rounds up, so the resulting cycle count always
covers at least the requested microseconds.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-05-04 21:55:33 +02:00
Alexios Lyrakis
1cf1de81a1 arch: riscv: add Supervisor-mode (S-mode) support
Introduce CONFIG_RISCV_S_MODE to select Supervisor-mode execution.
Add depends on !RISCV_S_MODE to RISCV_PMP since PMP CSRs are
inaccessible from S-mode.

Add an M-mode SBI shim (reset.S + sbi.S) that configures exception
delegation, PMP, and counter access before dropping to S-mode via mret.
The shim handles SBI_SET_TIMER ecalls from S-mode and forwards MTIP to
STIP so the supervisor timer driver works without a full SBI firmware.

Introduce privilege-level abstractions in isr.S (RV_CAUSE, RV_EPC,
RV_STATUS, RV_TVAL, etc.) and update all runtime code that previously
accessed M-mode-only CSRs (mcause, mtval, mstatus, mie, mip) to use the
S-mode equivalents when CONFIG_RISCV_S_MODE is set.

ARCH_EXCEPT in kernel context uses ebreak (cause=3, Breakpoint) instead
of a direct z_riscv_fatal_error() call.  In S-mode, ecall (cause=9) is
kept in M-mode for SBI and never reaches the S-mode exception handler;
a direct call with NULL esf caused the stack unwinder to crash into an
infinite fault loop.  ebreak is delegated to S-mode by our medeleg
configuration; isr.S treats ebreak with t0=RV_ECALL_RUNTIME_EXCEPT the
same way M-mode treats ecall-based ARCH_EXCEPT.

Signed-off-by: Alexios Lyrakis <alexios.lyrakis@gmail.com>
2026-05-04 14:54:52 +02:00
Nicolas Pitre
603fa4818e drivers: timer: assert sys_clock lock held where required
Add sys_clock_is_locked(), the analog of z_spin_is_locked() for the
timer lock exposed via sys_clock_lock(). Use it to assert lock
ownership in sys_clock_set_timeout() and sys_clock_elapsed() of the
six timer drivers that were migrated to sys_clock_lock() and
consequently no longer acquire anything internally in those callbacks
(arm_arch_timer, riscv_machine_timer, xtensa_sys_timer, hpet,
apic_tsc, intel_adsp_timer).

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-05-01 11:18:04 -05:00
Ren Chen
124062c965 drivers: timer: it51xxx: add kconfig to select count-up in combination mode
For next-generation it51xxx series, external timers switch
from count-up to count-down when combination mode is enabled.

This change introduces Kconfig option to allow selecting
count-up mode according to hardware design.

Signed-off-by: Ren Chen <Ren.Chen@ite.com.tw>
2026-04-28 15:22:59 +02:00
Albort Xue
8e51e2eb10 driver: timer: mcux_lptmr: add wakeup source support
Add support for configuring the LPTMR as a wakeup source by integrating
with the WUC (Wakeup Controller) subsystem.

Signed-off-by: Albort Xue <yao.xue@nxp.com>
2026-04-28 15:21:15 +02:00
Nicolas Pitre
7e02a6847e drivers: timer: arm_arch: use WFxT in arch_busy_wait()
Use the WFET (Wait For Event with Timeout) instruction, introduced in
Armv8.8-A (FEAT_WFxT), to let the CPU enter a low-power state during
arch_busy_wait() instead of spinning on the counter.

The availability of WFxT is detected at runtime by reading
ID_AA64ISAR2_EL1. When the feature is absent, the existing polling
loop is used as before.

Also fix the cycles_to_wait computation to use 64-bit multiplication
to avoid truncation with large usec_to_wait values.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-04-14 22:31:36 -04:00
Raffael Rostagno
80ee819be5 drivers: systimer: xtensa: Fix ISR/idle_exit concurrency
IDLE exit is programmed to happen shortly before systimer
programmed wake-up event happens. If the interrupt from
the timer happens before, idle_exit() does not run, as
timeout_idle flag is cleared at the ISR. Fix condition for
both systimer (ESP32) and xtensa drivers.

Signed-off-by: Raffael Rostagno <raffael.rostagno@espressif.com>
2026-04-08 07:40:46 -04:00
Nicolas Pitre
7735bf3bb8 drivers: timer: intel_adsp_timer: use sys_clock_lock() to fix SMP race
Migrate intel_adsp_timer to the unified timer lock API. Replace the
driver-private spinlock with sys_clock_lock()/sys_clock_announce_locked().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-04-07 11:40:49 -05:00
Nicolas Pitre
8ee79c2dd3 drivers: timer: apic_tsc: use sys_clock_lock() to fix SMP race
Migrate apic_tsc to the unified timer lock API. Replace the
driver-private spinlock with sys_clock_lock()/sys_clock_announce_locked().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-04-07 11:40:49 -05:00
Nicolas Pitre
59d4ffeea6 drivers: timer: hpet: use sys_clock_lock() to fix SMP race
Migrate hpet to the unified timer lock API. Replace the driver-private
spinlock with sys_clock_lock()/sys_clock_announce_locked().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-04-07 11:40:49 -05:00