Add support for the AMD/Xilinx AXI Timer as a Zephyr system
clock driver for soft-core CPUs such as MicroBlaze and
MicroBlaze V.
The driver targets the common dual 32-bit timer configuration
where timer1 is used as a free-running clock source and
timer0 is used as a clock event source.
Timer1 operates as an up-counter with auto-reload enabled.
Timer0 supports both periodic and one-shot operation and is
used to implement tickful and tickless kernel modes
respectively.
Signed-off-by: Alp Sayin <alpsayin@gmail.com>
Signed-off-by: Michal Simek <michal.simek@amd.com>
Signed-off-by: Satya Sri <satyasri.katru@amd.com>
Convert the native_sim_timer system-timer driver to the generic tickless
timer core. The core takes over the tick accounting, and what is left here
is the cycle-domain primitives for this hardware, for a COMPARE_ORDERED
backend.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Drop the hand-rolled tick accounting for the generic core. CMT1 keeps
free-running as the cycle source and CMT0 keeps raising the tick
interrupt. What goes away is everything between them: the announce
baseline, the cycle-to-tick division in three places, the deadline
arithmetic and the private spinlock.
This is a RELOAD backend rather than a compare one, because the compare
register belongs to a different counter than the cycle source. The core's
absolute deadlines live in CMT1's domain, which says nothing about CMT0's
CMCOR, so what CMT0 can be given is a relative delay. CMT0 exists only to
raise the interrupt, nothing reads its count, so the arming primitive
restarts it and CMCOR becomes exactly the delay the core asked for.
Two CMCOR pathologies in the old sys_clock_set_timeout() go with it. It
special-cased the maximal tick value by declining to reprogram at all,
which left whatever period was already loaded in place forever, and it
could compute a CMCOR of zero, which matches on every count. The core
neither special-cases a tick value nor programs a reload below
TIMER_CORE_ALARM_MIN_CYCLES, set here to two so CMCOR never lands on a
just-cleared CMCNT.
CMT1's software extension stays, so the core is given 32 bits rather than
the raw 16. One CMT1 period is 10.9 ms at 6 MHz and a masked delta
aliases past that, so a k_busy_wait() holding interrupts for longer would
see the cycle counter go backwards and uptime stop. That is poor practice
on the caller's part, but it has to keep working for well over a second.
Folding the wrap in on each read is what keeps the extension alive while
no ISR can run, and it makes the read stateful, hence
TIMER_CORE_COUNTER_NONATOMIC. A wrap is still only caught if something
reads within the period, which the arming bound and any busy-wait loop
both ensure. The arm range stays 16 bits, all CMT0's CMCOR holds.
Tested on qemu_rx/r5f562n8, kernel and arch suites, and build-tested on
rsk_rx130@512kb/r5f51308axfp.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Replace direct NVIC_SetPendingIRQ()/NVIC_ClearPendingIRQ()/
NVIC_EnableIRQ() calls with the portable k_irq_set_pending()/
k_irq_clear_pending()/irq_enable() equivalents. The Smartbond DA1469x
is a plain-NVIC Cortex-M33, so the pending-state capabilities are
always available where this code builds.
Assisted-by: Claude:claude-opus-5
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Replace direct NVIC_SetPendingIRQ()/NVIC_ClearPendingIRQ() calls with
k_irq_set_pending()/k_irq_clear_pending().
Assisted-by: Claude:claude-opus-5
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Replace the direct NVIC_ClearPendingIRQ() call with
k_irq_clear_pending().
Assisted-by: Claude:claude-opus-5
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
TIMER_CORE_MAX_UNANNOUNCED_CYCLES was the smaller of two unrelated
limits: what the counter can still resolve, and what the alarm can
express. The tick clamp divides by it, so where a tick is longer than the
alarm can hold, it comes out zero and the arm path collapses:
span = 0 /* clamped */
want = 0 * CYC_PER_TICK = 0
rel = (want > done) ? want - done : 0 /* 0 */
rel < ALARM_MIN /* floored */
set_reload(ALARM_MIN)
On frdm_mcxn947 at 150 MHz with CONFIG_SYS_CLOCK_TICKS_PER_SEC=1 a tick
is 150000000 cycles against a 24-bit SysTick reload of 16777215, so the
driver arms 1499 cycles, the 10 us floor, and interrupts 78000 times a
second announcing nothing. Asking for one tick a second then costs more
interrupts than any other tick rate.
Only the counter's reach bounds how much unannounced time may accumulate.
The alarm's reach bounds a single arm. Split them:
MAX_UNANNOUNCED_CYCLES = COUNTER_SAFE_SPAN
MAX_ARM_CYCLES = MIN(COUNTER_SAFE_SPAN, ALARM_MAX_CYCLES)
The tick clamp uses the first, so a tick always fits, and each arm is
capped at the second. That board now spans 14 ticks and arms 16777215
cycles at a time, nine interrupts to cross one tick, which is what the
driver already did for a timeout longer than its reload.
The cap is guarded on the two bounds differing, so it folds away where
the alarm covers the whole span and the span clamp has already bounded
the value.
Fixes: #117169
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Remove remaining uses of the internal __ASSERT_ON macro. Let __ASSERT()
handle disabled assertions, mark assert-only values as unused where needed,
and use CONFIG_ASSERT for assertion-only state.
Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>
The deep-sleep counter (1kHz RTC) used on platform RW61x stops at
zero and does not track PM3 exit recovery time. This causes two
issues:
1. After PM3 exit, the kernel sees unaccounted time remaining
and enters a parasitic PM2 to fill the gap. Fix by adding
the exit-latency back to the compensated sleep time in the
OS timer driver (mcux_os_timer.c).
2. On counter overflow re-entry into PM3, the PM policy
exit-latency subtraction is not applied since re-entry
bypasses the PM framework. Fix by adjusting the RTC wakeup
count in the SoC power re-arm loop (soc/nxp/rw/power.c).
Signed-off-by: Jacob Wienecke <jacob.wienecke@nxp.com>
The free-running 64-bit system counter with its absolute compare
register is a COMPARE_ORDERED backend. The driver keeps
timer_driver_cycle_get() (the counter) and timer_driver_set_compare()
(set the comparator and unmask), and the core takes over the tick
accounting, the deadline math, the range clamp and the announce.
smp_timer_init() primes the per-CPU comparator through
timer_core_smp_prime().
The driver's own cyc_per_tick cache goes: with
CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME the core precomputes the
value in timer_core_init().
The ISR keeps its hardware specifics: the Cortex-A9 erratum 740657
spurious-interrupt handling, and masking the level-asserted compare in
tickless mode, which the core's rearm unmasks again.
Declaring the counter's 64-bit width with TIMER_CORE_COUNTER_WIDTH
removes the driver's CONFIG_GDBSTUB-only widening of the cycle diff,
which existed only because the width was not stated.
timer_api and context pass on qemu_cortex_a53, UP and SMP.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A down-counter reloaded from LDCNT that interrupts at zero and does not
free-run, so a RELOAD backend. The counter the core reads is synthesized,
the reloads consumed so far plus what the one in flight has counted down,
and it is declared 28 bits wide like the hardware. That read touches
state the ISR and the reload path also write, so
TIMER_CORE_COUNTER_NONATOMIC has the core serialise the public getters.
The core takes over the tick accounting: last_announcement and the
announced-tick arithmetic go, along with sys_clock_set_timeout(),
sys_clock_elapsed() and sys_clock_cycle_get_32(). The driver is left with
folding the consumed reload into the synthesized count, in the ISR and
again when a new reload replaces one in flight.
Two oddities in the replaced code are worth recording. The ISR reloaded
RTMR_COUNTER_MAX * CYCLES_PER_TICK, a product that overflows 32 bits and
wraps to an arbitrary value, where the intent was simply to keep counting
until the next deadline; it now reloads the counter's maximum.
sys_clock_elapsed() took the absolute value of a difference that it
computed backwards, so an announce arriving between the two reads turned
into elapsed time counted forwards; the core computes it once, from the
counter.
sys_clock_cycle_get_32() now counts over the full 32-bit space, where the
driver's own masked it to the counter's 28 bits. The sleep compensation
masked the difference of two readings to match, which would truncate a
sleep past 0x0fffffff cycles, so that mask goes.
Stopping the timer moves to sys_clock_idle_enter(K_TICKS_FOREVER), where
the CPU is on its way to sleep and sys_clock_idle_exit() is guaranteed to
restart it. The magic tick value that used to request it could arrive
with the CPU still running.
Build-tested on rts5912_evb, tickless and tickful, with and without
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A free-running counter and a compare register that matches on equality, so
a value written after the counter has passed it is missed for a whole
counter period: a COMPARE_EXACT backend. The core writes the comparator
through its verify loop, which is what the driver's MIN_DELAY floor existed
for, and the counter's own width is declared so the core masks deltas at
the real wrap rather than at a register boundary.
The core takes over the tick accounting. announced_cycles, counter_delta()
and the round-up-to-the-next-tick arithmetic go with it, along with
sys_clock_set_timeout(), sys_clock_elapsed() and the driver's own
CYCLES_PER_TICK. The ISR is left with the flag clear and the announce.
The counter is now free-running in both modes. It used to reset on match
for a ticked kernel, which an absolute compare cannot express, and that
also retired the private cycles accumulator the tickful cycle counter was
built from: the counter itself now carries that, and the core emits
sys_clock_cycle_get_32().
sys_clock_no_timeout() takes over the sloppy-idle case that keyed off a
magic tick value. It masks the wakeup and leaves the counter running, so
the cycle getters keep working. Under a ticked kernel it does nothing: the
interrupt it would mask is the periodic tick.
Build-tested on frdm_mcxw71, tickless and tickful, with and without
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
hwtimer_enable(period) sets the next tick interrupt at now + period, so
it is a reload register and this is a RELOAD backend. The cycle counter
is nsi_hws_get_time(), microseconds since boot, so arming is a plain
forward of what the core computes.
Tickful keeps the period semantics: the driver arms once at init and the
model raises every subsequent tick on its own, which is what the core
expects of a RELOAD driver there. Tickless re-anchors on every announce.
last_tick_time, the ISR elapsed computation, sys_clock_set_timeout(),
sys_clock_elapsed() and both cycle getters move into the core. The ISR is
left with the announce.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
On SoCs that power off the OS Timer in deep low-power states, the driver
can now delegate low-power timekeeping to the generic system-timer
low-power companion framework (CONFIG_SYSTEM_TIMER_LPM_COMPANION_*).
Select SYSTEM_TIMER_HAS_LPM_COMPANION_SUPPORT and add a new
"handoff-power-states" devicetree property: when entering one of the listed
states the driver arms the companion counter chosen via
/chosen/zephyr,system-timer-companion and recovers the elapsed time on
wakeup.
The legacy deep-sleep-counter path is unchanged; boards on it do not set
handoff-power-states and keep handing off in PM_STATE_STANDBY as before.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
TIMER_CORE_MAX_UNANNOUNCED_CYCLES is the smaller of what the counter can
resolve and what the alarm register holds, and those two bound different
things. Outrunning the counter leaves the masked delta ambiguous, which
no amount of re-arming recovers. Outrunning the alarm only means the
deadline takes more than one arm to reach.
Asserting on the pair therefore rejects configurations that keep time
correctly, such as the kernel benchmarks at one tick per second on a
25 MHz SysTick: a tick is 25000000 cycles against a 24-bit LOAD, yet
sits well inside the counter's span. Assert on the counter alone.
The arm path still clamps to the pair, so no alarm is programmed out of
range. A tick past the alarm's reach costs extra interrupts, as it did
before the assert existed.
Assisted-by: Claude:opus-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
The tick-versus-span BUILD_ASSERT sits in the branch where cycles per
tick is a macro, but that branch also covers
CONFIG_SYSTEM_CLOCK_HW_CYCLES_PER_SEC_RUNTIME_UPDATE, whose rate is a
function call. The assertion expression is then not constant and the
build fails, as it does for sample.cpu_freq.thermal_cap on frdm_mcxn236.
Emit it only where TIMER_CORE_CHECK_CYC_PER_TICK_AT_INIT is unset, the
same guard the neighbouring cycles-per-tick != 0 assert already uses.
timer_core_init() runs the check at run time for the remaining cases.
Assisted-by: Claude:opus-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
The core describes timer_driver_cycle_get() and the arming primitives as
static inline, which reads as a requirement. It is not one: they have a
single call site each, and the compiler folds them in at -Os without the
keyword. Checked on kit_psc3m5_evk, where neither
timer_driver_set_reload() nor the lptimer_delay() it calls leaves a
symbol behind.
Thirteen of the drivers converted so far declare the arming primitive
plain static already, the split falling by size rather than by intent, so
say static and leave inline to whoever writes the driver.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
TIMER_CORE_MAX_SPAN_TICKS is how many whole ticks the core may arm ahead:
the smaller of what the counter can resolve and what the alarm register
can hold, divided by the cycles in a tick. Nothing checked that it comes
out at least one.
Where it does not, the arm path clamps every request to zero ticks and
the minimum-delay floor rearms a couple of cycles out, over and over,
while each announce is worth no ticks at all. Time stops advancing and
the system wedges, which is a poor way to learn that a 16-bit counter
cannot span a tick at the configured rate.
Assert it instead. Both terms are build constants in the common case, so
that is a BUILD_ASSERT naming the two ways out; the runtime-rate cases
already have an init-time check for the companion condition and get this
one alongside it.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The PIT driver (d8e551cee2) includes the deprecated
zephyr/sys_clock.h header, which since 5b2fd0761d emits a
deprecation warning. With -Werror=cpp in CI this fails the build of
every configuration for the sama5d27 boards, which are the only
users of this driver.
Include zephyr/sys/clock.h instead, which is where the sys_clock
API lives since the headers were merged in c08544a87b.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
In lptimer_delay, we reset the MCWDT counters using the PDL-recommended
210us. On some devices during CPU-intensive processes, this is slightly
too short for the counter to reset, causing the following
ASSERT(counter = 0) to rarely trigger.
Adding a WAITFOR prior to the assert to offer up to 100us for MCWDT to
finish resetting. Using a WAITFOR instead of upping the ResetCounters
delay so this extra wait is optional and only used when necessary.
Assisted-by: Claude:claude-opus-4.6
Signed-off-by: Zayne Stites <Zayne.Stites@infineon.com>
Drop the hand-rolled tick accounting for the generic core. The driver is
left with the cycle-domain primitives: read TTCR, write TTMR, acknowledge
the match.
TTMR matches only TTCR[27:0] == TP, so a target written at or behind the
count is missed until the 28-bit count wraps, 13.4 s at 20 MHz. That is
the COMPARE_EXACT backend, and the core writes the register through its
verify loop. set_compare_safe(), cyc_diff() and the MIN_DELAY floor go
away with it, as does the driver's own spinlock: the core takes the
system clock lock.
qemu_or1k joins the sloppy-idle test variant.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Convert the RISC-V supervisor timer to system_timer_generic.h. The
"time" CSR with the SBI set-timer deadline is a COMPARE_ORDERED backend:
the driver keeps timer_driver_cycle_get() (stime) and
timer_driver_set_compare() (sbi_set_timer), and the core takes over the
tick accounting, the deadline math, the range clamp and the announce.
smp_timer_init() primes the timer through timer_core_smp_prime(). The
counter is 64 bits wide on a 32-bit build as well, so the driver states
that width instead of taking the core's native-register default.
This also drops the driver's private spinlock: it now runs under the
kernel timer lock via the core's sys_clock_lock() / announce_locked(),
which is the intended locking for a system-timer driver.
timer_api and context pass on qemu_riscv64/qemu_virt_riscv64/smode
(supervisor timer under OpenSBI).
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
STIP is level sensitive and stays asserted until the SBI timer call
clears it. The ISR never made that call, relying on
sys_clock_set_timeout() being reached after the announce to move the
deadline forward.
That holds only as long as something does call it. On SMP each hart has
its own deadline, but sys_clock_announce_locked() returns early on all
but the announcing one, so the rest return from the ISR with the
interrupt still pending and take it again immediately. Nothing
guarantees a new deadline is armed on UP either: with no timeout pending
the kernel may legitimately choose not to.
Ask for an infinite expiry on entry, which the SBI spec defines as
clearing the pending interrupt without scheduling another, so the
interrupt fires once for the deadline it was armed with. The arming path
overwrites it in the normal case.
Fixes: #115442
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The systimer is a free-running counter plus a one-shot alarm, so a
COMPARE_ORDERED backend. The driver keeps the counter read and the alarm
write, now timer_driver_cycle_get() and timer_driver_set_compare(), and
the core takes over the tick accounting: last_count, the elapsed-ticks
helper, the tick-aligned deadline computation with its round-up and the
range clamp all go.
The unit counter is 52 bits wide, so the driver states that width and the
core masks its deltas at the counter's true wrap.
The driver's own cycle getters go. Both were guarded against a read after
sys_clock_disable() deinitialized the HAL; that guard now lives in
timer_driver_cycle_get(), which the core's getters go through, and the
arming primitive carries it too. It reports the counter value sampled at
disable rather than zero, so a read landing after it holds the elapsed
span instead of stepping the counter backwards.
MIN_DELAY goes. Every SoC this driver builds for defines
SYSTIMER_LL_ALARM_MISS_COMPENSATE, which is the peripheral raising an
alarm armed at or behind the counter rather than losing it, so a target
that is close or already passed needs no push forward. Espressif's own
systimer_hal_set_alarm_target() writes the target bare on those parts and
keeps a write-and-recheck loop only for the ones without the bit, none of
which this driver covers. Dropping the floor also takes a counter read
off every arm, which on this HAL is a snapshot request, a spin on the
valid bit and a triple read.
The low-power handoff moves from the idle argument of
sys_clock_set_timeout() to sys_clock_idle_enter(), which arms the wakeup
through the core and then hands over to the LPM hook.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Add driver for PIT (Periodic Interval Timer), only supports tickful
kernel mode (CONFIG_TICKLESS_KERNEL=n).
Signed-off-by: Tony Han <tony.han@microchip.com>
Convert the Xtensa CCOUNT/CCOMPARE timer to system_timer_generic.h.
CCOMPARE fires only on CCOUNT == CCOMPARE, so an already-past target is
missed until CCOUNT wraps: that is the COMPARE_EXACT backend, whose
verify loop replaces the minimum-delay bump the driver applied by hand.
The driver keeps timer_driver_cycle_get() (CCOUNT) and
timer_driver_set_compare() (CCOMPARE), and the core takes over the tick
accounting: the last_count baseline, the tickful re-arm and the
sys_clock_elapsed()/set_timeout() tick math all go. smp_timer_init()
primes the per-CPU timer through timer_core_smp_prime().
ccount() still adds the low-power compensation offset, so the cycle count
and every announced delta pick it up. The Espressif LPM hook
(CONFIG_XTENSA_TIMER_LPM_TIMER_HOOK) moves to sys_clock_idle_enter() and
folds the missed cycles into that offset; the non-low-power idle path
drops to the weak sys_clock_idle_enter() default, which arms through
sys_clock_set_timeout().
The low-power exit hands its recovered span to the core directly rather
than folding it into the counter for the announce to find. CCOUNT is 32
bits, so a sleep can outrun what the masked delta resolves, which at
240 MHz is under nine seconds. The compensation still takes the same
span, so the counter stays in step and what CCOUNT did see is left for
the next announce.
kernel.timer.sloppy_idle gains qemu_xtensa/dc233c: with nothing pending
the core arms the longest interval it allows, so the time base keeps
running.
timer_api, context, sleep and tickless pass on qemu_xtensa/dc233c.
Build-verified on esp32 with the LPM hook (CONFIG_PM=y) and with SMP.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Writing CCOMPARE is what clears the pending timer interrupt. The ISR
never wrote it in tickless mode, relying on sys_clock_set_timeout()
being reached after the announce to do so.
That holds only as long as something does call it. On SMP each CPU has
its own CCOMPARE, but sys_clock_announce_locked() returns early on all
but the announcing one, so the rest return from the ISR with the
interrupt still pending and take it again immediately. Nothing
guarantees a new deadline is armed on UP either: with no timeout pending
the kernel may legitimately choose not to.
Write a compare one behind the current count on entry. That clears the
interrupt, and since the match is on equality it also puts the next one a
whole counter period away, which is as far as a 32-bit comparator
reaches. The arming path overwrites it in the normal case.
Split the raw CCOUNT read out of ccount() so the ISR can form that value
without the low-power compensation the cycle domain carries.
Fixes: #115442
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Convert the MIPS CP0 timer to system_timer_generic.h. The CP0 Count
counter with its Compare register is a COMPARE backend, and the first
converted driver whose counter actually wraps during operation: on
32-bit MIPS TIMER_CORE_COUNTER_WIDTH defaults to the native 32 bits, so
the core masks every delta at the 2^32 boundary.
Compare raises the interrupt only on Count == Compare, so an
already-past target is missed until Count wraps all the way around. That
is the COMPARE_EXACT backend: the core writes the register through its
verify loop, replacing the driver's own bump-and-retry and its MIN_DELAY
floor in both set_timeout and the ISR. Writing Compare also clears the
interrupt.
The core now owns the tick accounting and the locking, so the driver's
private spinlock is gone. This also fixes a slow drift: the driver
resynced its baseline to the raw count each ISR and discarded the
sub-tick remainder, where the core keeps the baseline tick-aligned.
timer_api and context pass on qemu_malta, which joins the sloppy-idle
timer_api variant.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A down-counter reloaded from the preload register that interrupts at zero
and does not free-run, so a RELOAD backend. The counter the core reads is
synthesized, the reloads consumed so far plus what the one in flight has
counted down, declared 28 bits wide like the hardware. That read touches
state the ISR and the reload path also write, so the core is told the read
is not atomic and serialises the public getters, as the driver's own getter
did.
The core takes over the tick accounting, which removes the split between
the tickless and ticked builds: last_announcement, two ISR variants, two
sys_clock_elapsed() variants and the deadline computation all collapse into
one ISR that accounts the consumed reload and announces, plus a reload
primitive that folds in what a replaced reload had counted.
The same overflow as in the Realtek driver was here too: the tickless ISR
reloaded MAX_TICKS * CYCLES_PER_TICK, which is TIMER_MAX rounded down and
then multiplied again, wrapping past the counter's 28 bits. It now reloads
the counter's maximum. sys_clock_elapsed() likewise took the absolute value
of a difference computed backwards; the core computes it once, from the
counter.
sys_clock_idle_enter() takes over stopping the timer, the one place it is
safe: the CPU is on its way to sleep, so nothing is left to read a
synthesized count that stops with it, and sys_clock_idle_exit() starts it
again. The magic tick value that used to request it could arrive with the
CPU still running, outside any locked section.
Build-tested on mec172xevb_assy6906, tickless and tickful, with and without
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The counter and the alarm are two different timers here, which the core
keeps apart. The cycle domain is the free-running 32-bit timer, counting
down from 0xffffffff and read back inverted; the wakeup is a separate
24-bit event timer, a one-shot countdown. That makes it a RELOAD backend
whose range is bounded by the event timer rather than by the counter. Both
select the same clock, so the core's cycles are the event timer's without
conversion.
The core takes over the tick accounting: last_announced_hw_cnt, last_ticks
and last_elapsed go, and with them the deadline computation and the clamp
that turned a tick count into an event-timer count. What is left is the
register sequence in timer_driver_set_reload() and an ISR that
acknowledges, re-arms the one-shot event timer for a ticked kernel, and
announces. sys_clock_set_timeout(), sys_clock_elapsed() and
sys_clock_cycle_get_32() come from the core, the last in the same domain
the driver reported. HW_CNT_PER_SYS_TICK and EVEN_TIMER_MAX_CNT_SYS_TICK
go with them, the one cycles-per-tick user left, the one-tick event timer
a ticked kernel starts at init, reading TIMER_CORE_CYC_PER_TICK instead.
IDLE_BLOCK_TIMER_TICKS spelled the same microsecond-to-cycle division out
by hand and becomes k_us_to_cyc_ceil32().
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE used to leave the event timer disabled
once the timeout queue drained. The core arms the longest span the event
timer can hold instead; sys_clock_no_timeout() is not implemented.
Build-tested on it8xxx2_evb, tickless and tickful, with and without
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The counter and the alarm are two different timers here, which the core
keeps apart. The cycle domain is the free-running 32-bit timer, counting
down from 0xffffffff and read back inverted; the wakeup is a separate
24-bit event timer, a one-shot countdown. That makes it a RELOAD backend
whose range is bounded by the event timer rather than by the counter. Both
select the same clock, so the core's cycles are the event timer's without
conversion.
The core takes over the tick accounting: last_announced_hw_cnt, last_ticks
and last_elapsed go, and with them the deadline computation and the clamp
that turned a tick count into an event-timer count. What is left is the
register sequence in timer_driver_set_reload() and an ISR that
acknowledges, re-arms the one-shot event timer for a ticked kernel, and
announces. sys_clock_set_timeout(), sys_clock_elapsed() and
sys_clock_cycle_get_32() come from the core, the last in the same domain
the driver reported. HW_CNT_PER_SYS_TICK and EVEN_TIMER_MAX_CNT_SYS_TICK
go with them, the one cycles-per-tick user left, the one-tick event timer
a ticked kernel starts at init, reading TIMER_CORE_CYC_PER_TICK instead.
The ticked path announced MS_TO_COUNT(HW_CYCLES_PER_SEC, 1) ticks per
interrupt, a cycle count where a tick count was wanted, so a ticked kernel
on this driver ran its uptime fast by that factor. The core announces what
the counter says.
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE used to leave the event timer disabled
once the timeout queue drained. The core arms the longest span the event
timer can hold instead; sys_clock_no_timeout() is not implemented.
Build-tested on it51xxx_evb, tickless and tickful, with and without
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The free-running 64-bit TSC with an absolute deadline (the TSC_DEADLINE
MSR, or the local APIC timer ICR in one-shot mode as the fallback) is a
COMPARE_ORDERED backend. The driver keeps timer_driver_cycle_get()
(rdtsc) and timer_driver_set_compare() (set_trigger), and the core takes
over the tick accounting, the deadline math, the range clamp and the
announce. The last_cycle baseline and the sys_clock_elapsed() /
sys_clock_set_timeout() tick math go, the ISR reduces to an announce,
and smp_timer_init() keeps copying CPU0's LVT to each secondary.
The TSC is 64 bits wide even on a 32-bit build, so the driver states
that width; the old code divided its deltas at the native register
width.
The deadline arm range narrows from the driver's former three-quarter
span to the core's default half span, which reserves the upper half as
IRQ-latency headroom so a late announce of a maximum-length arm still
yields an in-range delta.
The set_timeout() guard that pinned a deadline to UINT64_MAX when the
computed deadline wrapped the 64-bit TSC goes; the core's range clamp
bounds the arm instead.
Built on qemu_x86_64 and qemu_x86 with the TSC deadline comparator, and
on qemu_x86_64 with the APIC_TIMER_TSC ICR fallback.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
SysTick is an auto-reload 24-bit down-counter, so a RELOAD backend. The
driver keeps its hardware-specific parts, the synthesized cycle count
with COUNTFLAG-based wrap detection and the LOAD reprogram with its
drift compensation. The core takes over the tick accounting:
announced_cycles and last_elapsed go, along with the deadline-to-reload
conversion, the range clamp and the announce. The 24-bit LOAD caps the
arm range, and the existing min_delay becomes the reload floor.
The driver carries no cycles-per-tick of its own. The reload floor is
already a cycle count, so the only remaining use for that value is the
one-tick LOAD at init and on the low-power restart, which reads the
core's TIMER_CORE_CYC_PER_TICK. The "tickless does nothing" pragma goes
too, the core build-asserting a non-zero cycles-per-tick.
The synthesized count is 32 bits whatever
CONFIG_CORTEX_M_SYSTICK_64BIT_CYCLE_COUNTER says. That option used to
widen it to 64, putting 64-bit arithmetic on every path to serve one: a
low-power sleep can outrun a 32-bit count, and routing it through the
counter was the only way to announce it. sys_clock_idle_exit() hands
that span to the core directly instead, advancing the counter across it
so the two stay in step, so only that path pays for the wider math. The
option is left advertising sys_clock_cycle_get_64() to the rest of the
system, which is all it was ever about.
The counter is no longer stopped when the timeout queue drains. That is
what CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE did here, and it froze
k_cycle_get_32() under a running thread. The core arms the longest
reload the hardware can hold instead, and the stop moves to
sys_clock_idle_enter(K_TICKS_FOREVER), where the CPU is on its way to
sleep and sys_clock_idle_exit() is guaranteed to restart it.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The RTC is a free-running counter that z_nrf_rtc_timer_read() extends to
64 bits in software, plus an absolute compare, so a COMPARE_ORDERED
backend: compare_set() raises the interrupt straight away for a target the
counter has already passed, and the core's single write is enough. The
counter width is declared as the extended one, 64 bits, while the arm
range stays the driver's own MAX_CYCLES, half the 24-bit counter span,
because that bound comes from the compare register rather than from the
count the core reads.
The core takes over the tick accounting. last_count, last_elapsed and the
cycle-to-tick math go with it, and so do sys_clock_set_timeout(),
sys_clock_elapsed() and sys_clock_cycle_get_32(), which the core emits.
What is left of the timeout handler is the anchor update and the announce.
sys_clock_no_timeout() stays. It does something the arming path cannot:
release sys_busy, which keeps z_nrf_rtc_timer_trigger_overflow() out of
the way while a deadline is pending. The core's default would park the
compare the same distance out but leave that flag set. This also replaces
the old magic tick value in sys_clock_set_timeout(), where a timeout
further out than the announce range arrived as that same value and was
indistinguishable from having none.
Not reprogramming at all in the hook would be the natural improvement, the
compare already in place covering the counter wrap, but that is a
behaviour change and is left for the driver's maintainers.
timer_api, context and sleep pass on nrf52_bsim, which runs this driver
against a model of the RTC, and timer_api passes on nrf5340bsim,
including the sloppy-idle variant. Also build-tested on nrf52840dk,
nrf5340dk and nrf9160dk.
The tickful configuration fails on nrf52_bsim, as it does on upstream
main, so that is not a regression from this change.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Header file include/zephyr/sys_clock.h is deprecated since commit
84fbdcb06d ("include: zephyr: Deprecate include/zephyr/sys_clock.h")
and will be removed someday. Update Zephyr file tree to include
include/zephyr/sys/clock.h instead.
Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
Add support for tracking heavy sleep duration on the RTS5912/RTS5915
using the low-frequency RTMR (RTOS Timer) 32KHz clock domain.
- Expose rts5912_clock_capture_low_freq_timer(),
rts5912_clock_compensate_system_timer(), and
rts5912_clock_get_sleep_ticks() in soc_clock.h.
- Capture timer reading prior to WFI in rts5912_heavy_sleep() and
accumulate elapsed sleep cycles upon wake-up after clock restoration.
Signed-off-by: Keith Short <keithshort@google.com>
Assisted-by: Antigravity:gemini-1.5-pro
When the RTOS timer (RTMR) expires and reaches 0, the hardware sets the
interrupt status bit (RTOSTMR_INTSTS_STS_Msk). If rtmr_get_counter() is
called while interrupts are locked (or before rtmr_isr() clears INTSTS),
counter == 0 is sampled.
Previously, rtmr_get_counter() unconditionally replaced counter == 0
with previous_cnt (assuming 0 meant an unlatched restart). This caused
sys_clock_cycle_get_32() to compute previous_cnt - cur_cnt = 0 elapsed
cycles, leading to a backward jump in the cycle count.
Fix this by checking !(RTMR_REG->INTSTS & RTOSTMR_INTSTS_STS_Msk) so
that a genuine 0 count from an expired timer is preserved until the ISR
runs.
Without this fix, the new test_timer_monotonic_irq_locked fails. With
this fix, test_timer_monotonic_irq_locked passes.
Also verified no regressions on the rts5912_evb board:
* kernel.tickless.concept
* kernel.poll.minimallibc
* kernel.poll
* kernel.timer.monotonic
* kernel.timer.timepoints
Signed-off-by: Keith Short <keithshort@google.com>
Assisted-by: Antigravity:gemini-1.5-pro
The ti_dmtimer driver used to use the first enabled compatible timer
instead of honoring the chosen zephyr,system-timer property. This has been
fixed.
Signed-off-by: Mika Braunschweig <mika.braunschweig@siemens.com>
Drop the hand-rolled tick accounting for the generic core. The driver is
left with the cycle-domain primitives: read the counter, write the
comparator, acknowledge the interrupt.
The comparator matches only on equality, so this is the COMPARE_EXACT
backend. The write-then-verify loop that kept an already-past target
from being lost for a whole counter period moves to the core, which now
does it for every exact-match driver, so
hpet_timer_comparator_set_safe() goes away and timer_driver_set_compare()
is a plain register write. The QEMU SMP workaround for a counter that
reads backwards becomes TIMER_CORE_COUNTER_NONMONOTONIC.
sys_clock_no_timeout() parks the comparator out of reach in a single
register write. The counter keeps running, as that hook requires.
Stopping it belongs in sys_clock_idle_enter(), and only when this CPU is
the only one, because the HPET counter is shared.
qemu_x86 joins the sloppy-idle test variant.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
A driver that recovers elapsed time from somewhere other than its
counter, a low-power companion that kept time while the counter was
stopped, can have a span to announce that outruns what the counter's
width expresses. Reaching that through timer_core_announce_from() means
routing it via the counter, which forces the counter itself to be wide
enough for the sleep rather than for the hardware.
Let such a driver hand the span over directly instead, in cycles, which
is the unit it already works in and the one every other driver-facing
primitive takes. The arithmetic is 64-bit whatever the counter's width,
since that span is exactly what the width cannot cover, and it is kept
separate from timer_core_announce_from() so only the recovery path pays
for it.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The arming path computed its deadline in 64 bits whatever the counter's
width. On a 32-bit target that is synthesized from 32-bit halves: each
add needs its carry recovered with a compare, each shift is a pair plus
an or, and each constant costs twice the instructions. It showed
in the generated code, on openrisc worst of all.
The width was never needed. last_cycle is last_tick * CYC_PER_TICK
exactly, an invariant timer_core_init() establishes and the announce and
the rescale maintain, so
(last_tick + last_elapsed + ticks) * CYC
= last_cycle + (last_elapsed + ticks) * CYC
and the clamp, which subtracts last_cycle straight back off, is on that
relative span alone. The absolute deadline was carried through a
multiply and a subtract only to be cancelled. Forming the span directly
keeps the calculation inside the counter's width.
Three bounds make the narrow types safe, none of them a latency budget:
- The span is clamped in the tick domain before the multiply, so
span * CYC <= MAX_UNANNOUNCED <= COUNTER_MASK by construction. The
comparison that clamps it forms no wide sum either.
- The announce multiplies a tick count obtained by dividing an
already-masked delta, so dticks * CYC <= delta <= COUNTER_MASK. The
round trip cannot grow.
- Init divides a counter read, itself inside the width, and
multiplies it back.
last_cycle and last_tick stay 64 bits. They carry the count past the
counter's wrap, which is what sys_clock_cycle_get_64() reports.
The reload arm gains two simplifications from the same clamp. Capping
the span up front subsumes the clamp against the remaining budget, that
one being rel <= MAX - done, which is just want <= MAX. And the signed
cast goes: only the sign of want - done matters, and its magnitude when
positive, so saturating at zero stands in for every negative value and a
starved ISR still lands on the ALARM_MIN_CYCLES floor.
Counters as wide as the baseline keep the absolute form, having nothing
to narrow to and paying for the new shape without the saving.
One behavioural difference: clamping in the tick domain rounds the
ceiling down to a whole tick, so the longest arm the core programs may
be up to one tick shorter, and is tick-aligned where it was not.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The core already holds a full-width baseline, so it can answer
sys_clock_cycle_get_32() and sys_clock_cycle_get_64() itself and the
driver no longer has to. Both are emitted unconditionally: the baseline
is 64 bits whatever the counter's width, so the 64-bit answer is always
available, and the linker drops it where nothing calls it. A driver that
has to scale the raw count itself suppresses either one with
TIMER_CORE_HAVE_CYCLE_GET_32 or _64.
Whether the platform also advertises the 64-bit counter through
CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER stays a per-driver decision. That
option says the read is cheap, or at least no dearer than a 32-bit one,
so nothing is gained by preferring the narrower getter: it holds where
the core locks for both, and not where it locks only for the 64-bit one.
The 32-bit getter stays lock-free on an atomic counter: it extends from
the baseline's low word, and pairing one baseline read with one counter
read gives the true position whatever an announce does in between. That
matters because it is on the thread-usage timestamp hot path. The lock
is taken only where the read cannot be trusted, either because the
driver synthesizes the count from state the ISR also touches
(TIMER_CORE_COUNTER_NONATOMIC) or because the full 64-bit baseline is
not a single load on a 32-bit CPU.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
TIMER_CORE_BACKEND_RELOAD covers hardware that fires after a relative
delay rather than at an absolute value: down-counters and
compare-match-reset periodics. It is assumed to auto-reload, so a
non-tickless kernel leaves it alone after init and the driver owns the
period.
Programming a reload restarts the counter, which the absolute backends
never have to think about, and that costs two guards the compare path
does not need. timer_core_arm() remembers the tick-aligned deadline it
armed and does nothing while that deadline has not moved, since the
kernel re-evaluates its earliest timeout on every add and abort and
back-to-back calls usually land on the same tick boundary. And a reload
floored at TIMER_CORE_ALARM_MIN_CYCLES is left to expire rather than
rewritten, or a set_timeout() stream arriving faster than the floor
would push the fire point out for as long as the stream lasts and
freeze announced time.
The relative delay is clamped against the budget left before the baseline
would fall TIMER_CORE_ALARM_MAX_CYCLES behind, not against that value
alone, which keeps the same invariant the compare path gets from clamping
its absolute deadline.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
TIMER_CORE_BACKEND_COMPARE_EXACT is the same hardware shape as
COMPARE_ORDERED, but the match is on equality only, so a deadline
written after the counter has passed it is lost for a whole counter
period. hpet and mips_cp0_timer work this way.
The core writes such a comparator through a verify loop that re-reads
the counter and pushes the target out, doubling the push, until it is
genuinely ahead. That is a generalisation of what hpet already does
privately, and it is what lets such a driver drop the minimum-delay
floor it would otherwise need: the floor exists to keep a deadline far
enough ahead to be caught, and the loop establishes that directly
rather than by guessing a constant.
Both flavours are reached through one core-side timer_core_set_compare(),
so neither the arming path nor the SMP bring-up branches on which is in
use.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Every tickless system-timer driver reimplements the same tick
accounting by hand: the cycle-to-tick division, the announce baseline
(last_cycle/last_tick/last_elapsed), the tick-aligned deadline
computation and the range clamp. The logic is identical across the
free-running-compare drivers (arm_arch_timer, riscv_machine_timer,
hpet, ...) down to the copied overflow-guard constant, and the small
divergences between the hand-rolled copies are a recurring source of
timer bugs.
Add system_timer_generic.h, an implementation header a driver includes
to get that accounting for free. It emits the tick-facing contract the
kernel calls (sys_clock_set_timeout(), sys_clock_elapsed()) and owns
the baseline state, so the driver is left with only cycle-domain
primitives: read the counter, arm the comparator, acknowledge the
interrupt. The emitted sys_clock_set_timeout() ignores the deprecated
idle argument; a converted driver gets the idle handoff through
sys_clock_idle_enter().
The header is included, not linked: the driver defines its constants
and static-inline primitives first, so the core inlines and
constant-folds against them (the per-tick divide becomes a
multiply-shift) on a plain -Os build with no LTO. Because the header
defines the global sys_clock_* symbols, a build that pulls in two
system timers fails at link time, which is the correct outcome. It
lives beside the drivers rather than under include/, as it is private
to them.
This commit covers one hardware shape,
TIMER_CORE_BACKEND_COMPARE_ORDERED: a free-running counter and an
absolute comparator whose match is an ordered comparison, so a deadline
already in the past fires immediately. arm_arch_timer and
riscv_machine_timer work this way. The commits that follow add the other
shapes and the cycle counter getters. The header documents the primitives
a driver provides and the knobs it may set.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Entering idle is signalled to the driver through the idle argument of
sys_clock_set_timeout(), which every driver has to carry whether or not
it has anything to hand off. Give the transition its own interface.
Add a weak sys_clock_idle_enter() hook, called by the power management
path when the CPU is about to be put to sleep. A driver that can
reconfigure for low power, hand over to a wakeup timer, or stop its
clock does so there; one that cannot needs no implementation at all.
The default forwards to sys_clock_set_timeout() with the deprecated idle
argument set to true, so a driver keying on that argument keeps working
until it migrates. Recovery is sys_clock_idle_exit(), as before.
The decision in pm_system_suspend() mirrors the one reprogram_next()
makes for a running system. Nothing to wake up for, with the uptime
allowed to drift, is handed over as SYS_CLOCK_IDLE_FOREVER so a driver
can stop its clock knowing sys_clock_idle_exit() will follow; anything
else is a wakeup deadline, adjusted for the exit latency as before.
The hook is issued on every suspend. The idle argument it replaces only
reached the driver when the exit latency was non-zero, so a platform
declaring none left a driver no way to learn the CPU was going to sleep,
which is when a handoff to a low-power wakeup timer has to happen. Where
the deadline needs no adjusting the driver is simply asked for the one it
already has.
That condition arrives in its own value rather than as K_TICKS_FOREVER,
which is unusable in an unsigned tick count: it is (int64_t)-1 with
CONFIG_TIMEOUT_64BIT and UINT32_MAX without it, so a driver comparing
against it would be testing two different things depending on the
configuration. SYS_CLOCK_IDLE_FOREVER sits above SYS_CLOCK_MAX_WAIT, the
longest wait the kernel ever asks for, so it cannot alias a deadline.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
An empty timeout list normally still gets the driver a wakeup request.
That is a synthetic timeout: nothing is waiting for it, it is there to
keep the announce baseline moving so uptime stays correct.
CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE is the permission to skip it, which is
why an empty list only becomes visible to a driver when that option is
set, and today it becomes visible as a tick value the driver has to
recognise rather than as a condition of its own.
Add a weak sys_clock_no_timeout() hook, called in place of
sys_clock_set_timeout() when the list is empty and sloppy idle allows the
uptime to drift. Its default asks sys_clock_set_timeout() for UINT32_MAX
ticks, which is what K_TICKS_FOREVER is in the unsigned tick domain this
interface now uses, so an out-of-tree driver that has not migrated still
sees the "no deadline" value it always did. What gets deprecated is the
special meaning, not the call.
next_timeout() no longer decides sloppy idle, so its empty-list and
far-timeout arms collapse into one capped budget. The far-timeout arm no
longer stops a tick short of the cap either: it only did so to stay
distinguishable from the empty case, which now travels out of band.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>