When the device fails to resume, get_sync_locked() returns with the
power domain still claimed. Release it, as pm_device_runtime_get()
does for devices that are not ISR-safe.
Signed-off-by: Adrien Lessard <adrien.lessard@rbr-global.com>
pm_system_resume() clears z_cpus_pm_state[id] before the system_suspend
exit hook reads it, so every successful suspend was traced as
PM_STATE_ACTIVE. Latch the state before entering it and report that.
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Assisted-by: Claude:opus-5.5
Mark the early system timer resume prompt as experimental and remove
redundant resume-ordering notes from the PM documentation.
Use CMake's LINKER syntax for the timer idle-exit wrapper. Restrict
the two timer-order tests to GNU ld or LLD toolchains, and explain
why they require SysTick without an LPM companion.
Keep both PM resume sequences unchanged.
All five power management configurations were built and run on
qemu_cortex_m3 with the GNU toolchain; all 48 tests passed.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
Restore the legacy system PM resume sequence by default: resume
system-managed devices, run SoC exit post-ops, notify state exit,
and perform system timer idle-exit accounting.
Keep the sequence introduced by #118977 behind the default-off
PM_EARLY_SYSTEM_TIMER_RESUME option, which selects EXPERIMENTAL.
Platforms enabling it must validate SoC and timer dependencies and
timeout callbacks that can run before devices have resumed. The
legacy sequence retains its stopped-timer busy-wait limitation.
Leave STM32 LPTIM unchanged and document both resume sequences. Add
QEMU tests for exact resume ordering, IRQ masking, and timer progress
during device resume.
All 48 tests across five QEMU configurations pass. Build STM32U5
STOP3 and STM32WBA S2RAM. Validate both sequences on FRDM-MCXN947
for ten S2RAM cycles each, including busy-waits in experimental
device resume callbacks. STM32 runtime validation remains pending.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
pm_policy_next_event_ticks() and pm_policy_next_custom_ticks() both
report int64_t tick counts, but pm_system_suspend() stored them in
int32_t locals and ticks_expiring_sooner() took int32_t parameters. An
event further out than INT32_MAX ticks therefore truncated, and could
truncate negative: at a 32768 Hz tick rate that is only ~18.2 hours
(INT32_MAX / 32768 = 65536 s) of lead time.
A negative value then either trips the __ASSERT() guards in
ticks_expiring_sooner() or, in a build without assertions, wins the
MIN() and discards the real kernel deadline. In the latter case
pm_policy_next_state() receives a negative tick count, which the
default policy compares against an unsigned min_residency_ticks, so the
loop never breaks and the deepest state is selected while a much nearer
wakeup is still pending.
Widen ticks_expiring_sooner() to int64_t and clamp its result to the
[-1, SYS_CLOCK_MAX_WAIT] range that pm_policy_next_state() accepts, so
the policy hook keeps its int32_t tick parameter while a far future
event can no longer wrap negative and be read as "nothing pending".
kernel/idle.c already relies on the same upper bound when it narrows
z_get_next_timeout_expiry() into _kernel.idle.
Detect "nothing pending" by testing the sign rather than by comparing
against K_TICKS_FOREVER. K_TICKS_FOREVER is ((k_ticks_t)-1) and
k_ticks_t is uint32_t when CONFIG_TIMEOUT_64BIT=n, so at int64_t width
that sentinel promotes to 4294967295 and never compares equal to the -1
the callers actually pass. The same asymmetry is already documented on
SYS_CLOCK_IDLE_FOREVER.
The mismatch dates back to commit 59779ebe4b ("pm: policy: event: use
uptime ticks"), which widened pm_policy_next_event_ticks() to int64_t
without updating its caller.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
pm_system_resume() ran the resume sweep, and with it every driver's resume
handler, before sys_clock_idle_exit(). A driver is entitled to delay in
that handler -- a reference that has to settle, a converter that has to
recalibrate -- and k_busy_wait() reads the system timer, which
sys_clock_idle_enter() is free to have stopped. With
CONFIG_SYSTEM_TIMER_RESET_BY_LPM, which every SoC whose low-power states
gate the core clock has to set, it is stopped and its count is meaningless,
so the read never advances and the wait never ends: the system hangs on the
way out of a state it entered correctly.
Move the timer restart, and the SoC's own exit hook it depends on, ahead of
the sweep. Nothing between them touches a device, and the timer is what
everything after them relies on, so it belongs first. The hook's own
documentation described the order it used to run in; correct it.
This moves more than the restart. sys_clock_idle_exit() also hands the
kernel the ticks the sleep covered, and an announce runs the timeouts that
came due right there in the idle thread, so those handlers now run ahead of
the devices. A SoC selecting CONFIG_PM_STATE_SET_IRQ_UNLOCKED had its wake
ISR in that window already and sees no change; on the ones that keep
interrupts locked across resume the window was empty until now.
What can run there is bounded. Interrupts are still locked and this is the
idle thread, so only the handler body itself executes: one that readies a
thread does not get that thread scheduled until the idle path unlocks, and
by then the devices are back. That leaves a k_timer expiry function
touching a device directly, which is worth trading against a hang that is
certain.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
put_sync_locked() released a claimed power domain by calling itself on the
domain device. The domain's usage count, state and flags are updated there
while only the child's spinlock is held, never the domain's own, so on SMP
two children suspending at the same time race on the domain they share.
get_sync_locked() claims the domain with pm_device_runtime_get(), which
does take that lock. Do the same on the put side and call
pm_device_runtime_put(). The domain still has to be ISR-safe, otherwise the
semaphore back end would be entered with a spinlock held, so the nesting
stays spinlock over spinlock, as on the get side.
put_sync_locked() is now only reached from the two public put functions,
which already test PM_DEVICE_FLAG_RUNTIME_ENABLED, so drop its own check.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
pm_device_runtime_get() tests PM_DEVICE_FLAG_RUNTIME_ENABLED in the public
function; the put side tested it in both back ends instead, in
runtime_suspend() and in put_sync_locked().
Succeeding when runtime PM is not enabled is documented behaviour of
pm_device_runtime_put() and pm_device_runtime_put_async(), so test the flag
there, next to the tracing entry point, like the get side does.
runtime_suspend() is only reached from those two functions, so its check is
now redundant and is removed. put_sync_locked() also recurses into itself
to release the power domain, which does not go through the public API, so
it keeps its check.
Behaviour is unchanged; the ISR-safe path stops taking a spinlock just to
find out it has nothing to do.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
struct pm_state_constraints::count is a size_t, but
pm_policy_state_constraints_get(), pm_policy_state_constraints_put()
and pm_state_in_constraints() walked it with an int index, comparing a
signed and an unsigned value on every iteration.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
pm_device_runtime_get() traces its entry and then takes two early
returns without a matching exit event: when runtime PM is not enabled
for the device, and when k_sem_take() fails. Backends that map these
hooks onto paired calls, such as SystemView's
RecordFunc()/RecordEndCall(), skew their call depth on both paths.
Route both through the existing `end` label. It is placed after the
unlock block, so the semaphore that was never taken is not given back.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
pm_system_suspend() traces its entry unconditionally, but the early
return taken when no power state is active leaves without a matching
exit event. Backends that map these hooks onto paired calls, such as
SystemView's RecordFunc()/RecordEndCall(), permanently skew their call
depth every time that path is hit.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
shell_strtoul() only assigns to *err when parsing fails; on success it
leaves the variable untouched. cmd_cpu_lock() and cmd_cpu_idle()
declared it uninitialized and then tested `err < 0`, reading an
indeterminate value and potentially failing a perfectly valid command.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
Both `cpu lock` and `cpu unlock` were registered with two mandatory and
one optional argument. The shell accepts any argc in
[mandatory, mandatory + optional], so `cpu lock standby` (argc == 2) is
let through, but both handlers unconditionally parse argv[2] and read
past the arguments the shell actually populated.
The substate is documented as required in the command help, so declare
it as mandatory instead of optional.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
Fix a race condition that leads to a device being in `STATE_ACTIVE`
while its power domain is not enabled. The race occurs when an
asynchronous put is running and a `get` request arrives.
Assisted-by: GPT-5.5
Signed-off-by: Jordan Yates <jordan@embeint.com>
Use the autogenerated `DT_COMPAT_ZEPHYR_POWER_STATE` variable in Kconfig
of the PM subsystem instead of declaring a variable manually.
Signed-off-by: Mathieu Choplain <mathieu.choplain-ext@st.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>
K_SPINLOCK() expands to a for loop, so the compiler cannot prove the
guarded block always executes and warns that ret is used uninitialized
on return from runtime_usage_put():
subsys/pm/device_runtime.c:116:16: warning: 'ret' may be used
uninitialized [-Wmaybe-uninitialized]
Both branches inside the block assign ret, so this is a false positive.
Initialize ret at declaration, matching runtime_usage_put_fast() which
already initializes its return value for the same reason.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
The get/put fast paths update pm->base.usage under the global runtime
PM spinlock, but the slow paths update the same non-atomic counter
while holding only the per-device semaphore. A pm_device_runtime_get()
call from an ISR can then interleave with the last-user
pm_device_runtime_put() read-modify-write running in a thread: the
fast path sees usage == 1 with the device active, increments the
counter and returns 0, and the interrupted thread overwrites the
counter with 0 and suspends the device. The ISR ends up holding a
runtime PM reference on a suspended device and the usage count is
permanently off by one.
Serialize all usage read-modify-write sequences of the non-ISR-safe
paths through the global spinlock: the unbalanced check, decrement and
last-user decision in runtime_suspend(), the suspend failure restores,
the slow-path get increment and the resume failure decrement. State
keeps being written under the per-device semaphore: every transition
away from the active state happens with usage == 0, which is now
visible under the spinlock, so the fast-path "usage > 0 and state
active" check cannot claim a reference on a device that is about to be
suspended. The ISR-safe paths already serialize everything under the
per-device spinlock and are unchanged. The counter updates are
factored into small runtime_usage_*() helpers so that every
read-modify-write visibly goes through the same lock.
The race window was confirmed on qemu_x86 by disassembly (the usage
load and store are split across a branch, so the timer IRQ can be
delivered in between) and reproduced deterministically with the stress
test added in the following commit, which fails without this fix and
passes with it.
Fixes the race left open by commit 46e5ba3732 ("pm: device_runtime:
Fix managing the device from multiple contexts").
Signed-off-by: Holt Sun <holt.sun@nxp.com>
Header file include/zephyr/sys_clock.h is deprecated and will be removed
someday. Update the whole file tree to include zephyr/sys/clock.h
straight instead of zephyr/sys_clock.h.
This change was made running the sed shell command below:
$ sed -i 's/zephyr\/sys_clock\.h/zephyr\/sys\/clock\.h/' \
`grep -rsl "zephyr/sys_clock\.h" subsys/pm/`
Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
The idle argument of sys_clock_set_timeout() carries a distinct signal:
the CPU is entering low-power idle, here is its wakeup. Only the PM and
SoC power paths produce it (the timeout core always passes false), and
only a few drivers act on it to hand off to a low-power wakeup timer.
Introduce a dedicated sys_clock_idle_enter() hook for that, so the two
idle==true callers (subsys/pm and soc/nxp/rw) call it instead of
sys_clock_set_timeout(). Its weak default just programs the wakeup via
sys_clock_set_timeout(), so a driver with no low-power handling needs
nothing.
The five drivers that acted on idle (cortex_m_systick, esp32, xtensa,
mcux_os, stm32_lptim) move that handling into their own
sys_clock_idle_enter(), keeping their exact behaviour. Where the idle
path was self-contained it moves wholesale (cortex_m_systick, mcux_os,
stm32_lptim); where it shares the timeout programming, idle_enter()
calls set_timeout() first and then does its idle work (esp32), or shares
a small private helper (xtensa). set_timeout() keeps its now-unused idle
argument for the moment; nobody passes idle==true to it any more, which
lets the next change drop the argument entirely.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
The device-lock policy references no pm_device_* API; enum pm_state and
the constraint helpers come from <zephyr/pm/state.h>. Remove the unused
<zephyr/pm/device.h> include.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
All output in the PM shell goes through shell_print()/shell_error()
from <zephyr/shell/shell.h>; no stdio symbols are used. Remove the
unused <stdio.h> include.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
pm.c uses no string/memory functions (<string.h>), registers no SYS_INIT
handler (<zephyr/init.h>), and calls no pm_device_runtime_* API
(<zephyr/pm/device_runtime.h>). Remove these three unused includes.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
Replace the opt-in locked marker with a legacy unlocked marker. With
this, SoC PM hooks use the locked IRQ contract by default, and only
legacy SoCs that still unmask interrupts from PM hooks select
PM_STATE_SET_IRQ_UNLOCKED.
Drop the old locked marker selections from already migrated NXP SoCs and
update the PM test expectation accordingly.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
Use behavior-first wording in the PM API notes when describing the
locked-resume contract. This keeps the durable text focused on the
case where system PM keeps interrupts locked across resume, while
keeping CONFIG_PM_STATE_SET_IRQ_LOCKED as the current selector.
Shorten duplicated zero-latency interrupt details in the system PM
page and Kconfig help by referring readers to the ZLI documentation.
Also keep the ARM IRQ comment focused on the PM-wake-safe contract.
No behavior change. Validated with git diff --check.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
The locked-resume ordering guarantee covers only interrupts that
arch_irq_lock() can mask. On Cortex-M Mainline that lock is a BASEPRI
threshold, so zero-latency interrupts (IRQ_ZERO_LATENCY) run above it
and are outside that ordering.
Document that a zero-latency ISR used with PM must be PM-wake-safe, or
that its interrupt source must be masked or disabled while the system
state does not allow the ISR to execute.
No behavior change. Validated with git diff --check.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
kernel.h implies kernel_structs.h via kernel_includes.h, making
explicit inclusion of kernel_structs.h unnecessary whenever kernel.h
is already included in the same translation unit.
Remove the redundant includes across arch, boards, drivers, kernel,
lib, samples, subsys, and tests trees.
in include/zephyr/kernel_structs.h:
* 2. kernel.h shall imply kernel_structs.h, such that it shall not be
* necessary to include kernel_structs.h explicitly when kernel.h is
* included.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Add early exist to the suspend function if suspending client is
not the last one. It fixes the case where user calls put function
from the thread context and it gets interrupted by the device
interrupt where another asynchronous put is called. In that case,
in the interrupt context the call will return error as semaphore
cannot be taken and reference counting gets broken. By adding
an early exit if context is not the last one, we ensure that only
last client executes suspending procedure.
Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
Keep the original architecture IRQ key owned by idle across a
successful system PM transition.
Add architecture hooks and the PM_STATE_SET_IRQ_LOCKED migration
contract for SoCs that keep PM hooks from unmasking interrupts.
Signed-off-by: Holt Sun <holt.sun@nxp.com>
When `pm_device_runtime_put*()` is called on a device whose usage
count is already zero, `runtime_suspend()` emits "Unbalanced suspend"
at warning level. The message does not include the device name,
so on a system with many runtime-managed devices the warning gives
no hint which call site to fix.
Add `dev->name` to the log message, matching the style of the
neighbouring debug logs in the file.
Signed-off-by: Petr Hlineny <development@hlineny.cz>
sys_clock_set_timeout() and sys_clock_elapsed() are now documented
as requiring the system clock lock to be held by the caller. Wrap
the calls in subsys/pm/pm.c, soc/nxp/rw/power.c and the kernel
shell thread list command with sys_clock_lock()/sys_clock_unlock().
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Power managed devices should be able to return -EBUSY at
pm_action() (driver) calls without generating error log messages.
Suppress such error messages to allow the driver to decide at
sleep time if it still is unable to suspend, without generating
log noise.
Signed-off-by: Raffael Rostagno <raffael.rostagno@espressif.com>
Introduce enum pm_device_deps_region to replace the magic number
used when iterating through device dependency array regions in
power_domain_add_or_remove().
Signed-off-by: Yongxu Wang <yongxu.wang@nxp.com>
Add error logging in pm_resume_devices() to report when a device
fails to resume. This improves debuggability by making resume
failures visible in the system log.
Signed-off-by: Yongxu Wang <yongxu.wang@nxp.com>
Only define variable for enabled CPU Core to fix the following building
warning in case of any CPU Core is not enabled but with "cpu-power-states"
dts node property:
zephyr/subsys/pm/state.c:15:43: warning: 'pmstates_DT_N_S_cpus_S_cpu_0'
defined but not used [-Wunused-const-variable=]
Signed-off-by: Jiafei Pan <Jiafei.Pan@nxp.com>
Only set state to ACTIVE after RESUME succeeds, if it fails,
keep SUSPENDED STATE and attach an error code.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
It turns out that power_domain_add_or_remove() when add==true only
looks for DEVICE_HANDLE_NULL empty slots to write to, and never checks
"whether this dev_handle is already in the supported handles or not".
The result is: repeated adds may insert duplicate entries; or when
there are no empty slots, even though it's "already in the domain",
it returns -ENOSPC (which conflicts with the documented semantics).
This commit adds a check: when add==true and rv[i] == dev_handle is
found, it returns -EALREADY and avoids duplicate insertion.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
The comment definition for pm_policy_latency_request_add
states: states that exceed the given latency are unavailable.
However, the implementation in pm_policy_latency_update_locked
does not use the greater-than operator, so according to the
semantics, it should be changed to > to be consistent.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
The comment for the API pm_policy_latency_changed_subscribe
states: "NULL to disable", but the function implementation
directly saves and subscribes to this node, and subsequently
calls it directly without null checking when changes occur.
This actually poses a risk of calling a null function pointer.
This commit fixes this issue to make the function implementation
consistent with the API description.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
Use ARRAY_SIZE macro to determine the size of the pm_constraints
array instead of DT_PROP_LEN. Because a practical issue is that
'zephyr, disabling-power-states' may contain multiple power states,
but one of the power states is in a disabled status. In this case,
the size obtained by DT_PROP_LEN is larger than the actual size.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
1. Updated event-related API docs to fix wording and clarify
semantics ("earliest/soonest event", ticks vs cycles).
2. Improve the event implementation to prevent list corruption on misuse:
- pm_policy_event_register() is now idempotent: re-registering
the same evt updates its time instead of appending a duplicate node.
- pm_policy_event_update() / pm_policy_event_unregister() become clean
no-ops if evt is not currently registered.
- Kept a basic evt != NULL assertion.
Signed-off-by: Zhaoxiang Jin <Zhaoxiang.Jin_1@nxp.com>
The "@funcprops" Doxygen alias was originally introduced to list all
the function properties that apply to a given function (e.g. isr_ok,
etc.) in the form of a bullet list. However, since commit a258ab32d1
that is no longer the case and all the properties are rendered as
qualifiers (https://www.doxygen.nl/manual/commands.html#cmdqualifier)
and therefore no longer need to be grouped in a separate list.
This commit also ensure all aliases for the actual qualifiers use
`@qualifier` notation instead of `\qualifier` to be consistent with
our Doxygen guidelines.
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
next_event should not be global. This can cause
linkage conflicts if another file defines a symbol
with the same name.
Signed-off-by: Flavio Ceolin <flavio@hubblenetwork.com>
Add an optional power policy hook to provide custom "next event"
ticks during pm_system_suspend(), in addition to the existing
kernel ticks and policy event list.
This hook enables applications and SoC-specific code to derive
the next wake-up time directly from proprietary or
hardware-specific data structures (e.g. hardware registers,
binary-only modules, complex schedulers) that are not
practical to convert into the standard PM policy event list.
The feature is gated by CONFIG_PM_CUSTOM_TICKS_HOOK and is fully
backwards compatible when disabled.
Signed-off-by: Alessandro Manganaro <alessandro.manganaro@st.com>
In pm_system_suspend there is a possible invalid type promotion
in sys_clock_set_timeout(MAX(0, ticks - exit_latency_ticks), true);
ticks is int32_t and exit_latency_ticks is uint32_t consequently
ticks is promoted to uint32_t resulting in a possible underflow and
setting a wrong value in sys_clock_set_timeout().
Fixes#100005
Coverity CID: 535628
Signed-off-by: Flavio Ceolin <flavio@hubblenetwork.com>