Commit graph zephyr/subsys/tracing
Author SHA1 Message Date
Andrii Chmutov
1b18024c4a tracing: ctf: Configurable CTF timestamp function
Enables configurability of CTF timestamp getter to allow synchronization
of different SoCs using shared clock.

Signed-off-by: Andrii Chmutov <achmutov@antmicro.com>
Signed-off-by: Maciej Torhan <mtorhan@antmicro.com>
2026-10-28 22:28:45 -04:00
Mikolaj Klikowicz
11bb2dc414 tracing: ctf: Use packets
Enables usage of multiple CTF streams. Now each event is packed into a
packet which contains stream ID. This increases number of bytes per event
by 4 (2 bytes for packet size and 2 bytes for stream ID).

Signed-off-by: Mikolaj Klikowicz <mklikowicz@antmicro.com>
Signed-off-by: Maciej Torhan <mtorhan@antmicro.com>
2026-10-28 22:28:09 -04:00
Hayden Ball
792a6278eb tracing: usb: keep two transfers in flight
The USB backend copied each chunk into its single bounce buffer, then
blocked the tracing thread until the transfer completed. Nothing could
be drained from the tracing buffer while the bus was busy, so bursts
overflowed it.

Split the bounce buffer into two halves, keeping the same RAM, and let
the buffer pool provide the flow control: allocating blocks only while
both buffers are in flight, and each completion frees its buffer.
Disabling the endpoint completes any queued buffers with -ECONNABORTED,
which also frees them. The largest single transfer halves.

Streaming CTF over USB from an nRF52840 (measured on an NCS-based
tree), dropped events in a 60 s capture fell from 0.88% to 0.21%.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Hayden Ball <hayden@playerdata.com>
2026-10-19 16:25:45 +02:00
Tom Burdick
4b7ed8fd95 tracing: user: declare the RTIO user hook prototypes
The weak sys_trace_rtio_*_user() hooks have no prototypes, so an
out-of-tree implementation with the wrong signature links without any
diagnostic. Declare them next to the GPIO hooks, which are already
listed this way.

Assisted-by: claude:claude-opus-5
Signed-off-by: Tom Burdick <thomas.burdick@infineon.com>
2026-10-16 09:14:58 +02:00
Tom Burdick
f2ba448d1d rtio: Update usage of rtio_sqe_cancel
Updates callers of rtio_sqe_cancel to use the newer opaque handle
version which takes into account the generational allocation of SQEs.
The validation of cancel is now safe in that each SQE being cancelled
must belong to the pool in struct rtio the caller has access to and
knows about. It must also be the correct generation of the SQE so that
recycled or freed SQEs are not incorrectly dereferenced with undefined
behavior.

Adds a coccinelle semantic patch to update callers both in and outside
the tree.

A migration guide was updated to include information about the API
change and the usage of the spatch to help out of tree applications
update to the new call semantics. The spatch likely won't fix all
callers but could save some time.

Assisted-by: claude:claude-opus-5 coccinelle
Signed-off-by: Tom Burdick <thomas.burdick@infineon.com>
2026-10-16 09:14:58 +02:00
Gero Schwäricke
27064e3a25 tracing: sysview: fix thread info swap
StackSize and StackBase were swapped and StackUsage was uninitialized.

While at it, I reduced code duplication.

Signed-off-by: Gero Schwäricke <gero.schwaericke@sevenlab.de>
2026-10-14 08:44:02 +02:00
Anas Nashif
49ed9ec2ad tracing: implement object tracking on top of object cores
Object tracking kept its own intrusive lists of kernel objects, prepended
from the init tracing hooks with a linear duplicate scan and never
removed from. They had the same lifetime flaw as the object core lists:
an object discarded without being unlinked left the list pointing into
dead memory.

Make CONFIG_TRACING_OBJECT_TRACKING select CONFIG_OBJ_CORE and walk the
objects through the object core API instead. The per-object
_obj_track_next field, the _track_list_k_* heads, SYS_PORT_TRACK_NEXT()
and the tracking side of the init tracing macros are removed with the
tracking.h header.

Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-09-29 15:50:16 +02:00
Benjamin Cabé
3484454ac8 scripts: kconfig: hardenconfig: switch to YAML hardening database
Replace scripts/kconfig/hardened.csv with a distributed YAML database.
The CSV format could not carry any explanation for its recommendations,
had no validation (a malformed line was silently dropped), no notion of
profiles, no ownership story, and no way to extend it out of tree.

The database now lives where the code lives: the central
scripts/kconfig/hardening.yaml defines the hardening profiles (plus
rules for top-level Kconfig symbols), and per-subsystem hardening.yaml
fragments next to the relevant Kconfig files carry the rules, so each
rule is reviewed by the maintainers of the code it hardens. Every rule
has a required rationale and optional references, supports exact-value
and integer min/max recommendations (STACK_POINTER_RANDOM is now
'>=100' instead of '==100'), and belongs to a profile: 'base' (memory
protection and inherently insecure features) or 'strict' (extends base
with debug/observability feature removal). The default profile is
'strict', matching the rule set the CSV checked.

hardenconfig is restructured around a serializable HardeningReport
model so results can be consumed programmatically, and gains:

- a Rationale column in the report
- profile selection:
  west build -t hardenconfig -- -DHARDENCONFIG_PROFILE=base
- HARDENCONFIG_SHOW_ALL to also list PASS/NA results
- HARDENCONFIG_STRICT to exit non-zero on failures, for CI use
- HARDENCONFIG_JSON to write machine-readable results, including which
  database file each rule came from
- HARDENCONFIG_EXTRA_SOURCES to layer out-of-tree database files that
  may add profiles/rules and override in-tree ones

The EXPERIMENTAL/DEPRECATED/NOT_SECURE marker symbol detection is
preserved unchanged.

Three CSV entries are intentionally not carried over because they were
redundant: BT_CONN_DISABLE_SECURITY and BT_OOB_DATA_FIXED can only be
enabled together with BT_TESTING, and TIMER_RANDOM_GENERATOR together
with TEST_RANDOM_GENERATOR, all of which the database already
recommends disabling for the same profiles.

Behavioral fix: the CSV's DEBUG_COREDUMP line used '=' instead of ','
and was silently ignored, so CONFIG_DEBUG_COREDUMP was never actually
checked; it now is.

Also add tabulate to requirements-base.txt: hardenconfig has always
imported it, but it was only pulled in via other requirements files.

Assisted-by: Claude:fable-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
2026-09-29 10:40:32 +02:00
Tom Burdick
15cb1c9b27 tracing: add an ITM backend
Adds a tracing backend that writes trace data to an ITM stimulus port
on Cortex-M mainline parts, where a debug probe can capture it over
SWO or parallel trace. Writes poll the stimulus port and drop data if
it stays full, so a slow or absent trace sink cannot stall the core.
A marker word in the ELF tells a host tool ITM tracing is present and
which payload format it carries.

Signed-off-by: Tom Burdick <thomas.burdick@infineon.com>
2026-09-28 07:37:58 -04:00
Artem Voinov
be29d083c0 tracing: ctf: guard socket address arguments against NULL
Add NULL checks for sockaddr and addrlen in four CTF socket
hooks, matching the pattern used by accept_exit and recvfrom_exit.

Fixes #117635

Signed-off-by: Artem Voinov <voinov.artem.job@gmail.com>
2026-09-27 09:09:10 -04:00
Måns Ansgariusson
0bde5ccbeb lib: ring_buffer: drop select/depends on RING_BUFFER
The slim ring buffer API is now header-only and always available and the
tree has already migrated from the _claim/_finish API, so the RING_BUFFER
symbol no longer gates any code.
Remove the now-redundant "select RING_BUFFER" and CONFIG_RING_BUFFER=y
entries across drivers, subsystems, samples and tests.

Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>
2026-09-16 07:29:22 +02:00
Benjamin Cabé
b78bb9ffa0 tracing: place USB class data in ROM
The class API vtable and the descriptor pointer arrays are never
written after initialization, but were missing a const and so ended up
in .data. Add it.

Saves 68 bytes of RAM in samples/subsys/tracing/basic on
nrf52840dk/nrf52840.

Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Assisted-by: Claude:opus-5
2026-09-11 17:29:52 +02:00
Benjamin Cabé
acd6be722f usb: device_next: place per-class constant data in ROM
Add the missing const (and static, where the symbol is file-local) to
the class API vtables and the per-instance arrays of descriptor
pointers, which nothing writes after initialization.

That requires usbd_class_api::get_desc() to return "const void *". The
stack walks the result as "struct usb_desc_header *const *", so the
descriptors stay writable for the bInterfaceNumber and
bEndpointAddress patching done at init. Classes outside subsys/usb
only get the new return type here.

With the previous commit, this saves 86 to 180 bytes of RAM per class
on nrf52840dk/nrf52840, with no flash increase.

Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Assisted-by: Claude:opus-5
2026-09-11 05:24:28 -04:00
Eve Redero
681173c8f6 fix: tracing: ctf: add sleep_ticks tracing
Commit a672a717ca added the sleep_ticks enter/exit trace
enums 0x184 and 0x185 to factorize the sleep functions tracing,
but the metadata was not updated with the matching event classes.
Add them in the metadata.

Assisted-by: opencode:big-pickle
Signed-off-by: Eve Redero <eve.redero@gmail.com>
2026-09-07 10:34:47 +02:00
Måns Ansgariusson
65c22aae8d tracing: refactor tracing_buffer to use new ring_buf api
The prior implementation had its own ring buffer implementation, which
relied on the claim/finish api of the ring_buf implementation.
As the ring_buf implementation is moving towards removing the claim/finish
api, this commit refactors the tracing_buffer to use the ring_buf api
directly, without relying on the trace_buffers abstraction.

Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>
2026-08-27 07:20:28 -07:00
Nicolas Pitre
a672a717ca tracing: give k_sleep_ticks() its own trace point
The sleep trace hooks were attached to k_sleep(), k_msleep() and
k_usleep().  Those are inline wrappers now, and the only function left to
instrument is the k_sleep_ticks() primitive underneath them, so the three
hook families no longer have anything emitting them.  The msleep pair had
in fact been unused for some time already.

Replace all three with one k_thread_sleep_ticks pair reporting the timeout
and the time left to sleep in ticks, and drop what is left behind in each
backend: the CTF events and their top level helpers, the entry in
SYSVIEW_Zephyr.txt, and the user and test hooks.  The new CTF and
SystemView ids are fresh rather than reused, so a recording made by an
older build cannot be misread by a newer decoder.  The retired SystemView
ids stay defined, since out of tree code may refer to them.

The profiling example in the instrumentation documentation named two
symbols that no longer exist, and is updated to the ones that replace
them.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-08-20 08:52:31 +02:00
Anas Nashif
dc159fd9cb tracing: ctf: add syscall tracing
tracing_syscall.h had no CTF branch, so syscalls were untraced under CTF
(only SystemView and the test format hooked them). Add
tracing_ctf_syscall.h, mirroring the SystemView integration: it maps
sys_port_trace_syscall_enter and _exit to CTF events recording the
syscall id (and, on entry, the syscall name as a bounded string). Wire
it in with a CONFIG_TRACING_CTF branch in tracing_syscall.h, plus the
event ids, emitters, trampolines and TSDL metadata.

The header includes <zephyr/types.h> rather than <zephyr/kernel.h>: it
is pulled in very early from the generated syscall dispatch, before the
kernel types are complete.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
cee80e9c22 tracing: ctf: add pm_system tracing
CTF emitted no events for PM system suspend (enter/exit with the tick
budget and chosen power state); the sys_port_trace_pm_system_* hooks
fell through to the no-op fallback, so it was invisible in a CTF trace.

Add CTF coverage for every hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
1e999d0735 tracing: ctf: add pm_device_runtime tracing
CTF emitted no events for the PM device runtime API (get, put,
put_async, enable, disable); the sys_port_trace_pm_device_runtime_*
hooks fell through to the no-op fallback, so it was invisible in a CTF
trace.

Add CTF coverage for every hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
b5135ad87f tracing: ctf: add rtio tracing
CTF emitted no events for rtio (submit, sqe/cqe acquire/release/consume,
cqe submit, txn and chain next, sqe cancel); the sys_port_trace_rtio_*
hooks fell through to the no-op fallback, so it was invisible in a CTF
trace.

Add CTF coverage for every hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
d8d94aaa91 tracing: ctf: add k_pipe tracing
CTF emitted no events for k_pipe (init, reset, close, write and read)
for the current pipe API; the sys_port_trace_k_pipe_* hooks fell through
to the no-op fallback, so it was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

The old-API pipe hooks (get/put/flush/cleanup/alloc_init) have no call
site and are left to the no-op fallback.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
fbca1e9724 tracing: ctf: add k_heap_sys tracing
CTF emitted no events for the system heap
k_malloc/k_calloc/k_aligned_alloc/k_realloc/k_free family; the
sys_port_trace_k_heap_sys_* hooks fell through to the no-op fallback, so
it was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
cc1e7d4bf5 tracing: ctf: add k_heap tracing
CTF emitted no events for k_heap (init, alloc, aligned_alloc, calloc,
realloc and free); the sys_port_trace_k_heap_* hooks fell through to the
no-op fallback, so it was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
ef03bec8a0 tracing: ctf: add k_stack tracing
CTF emitted no events for k_stack (init, alloc_init, cleanup, push and
pop); the sys_port_trace_k_stack_* hooks fell through to the no-op
fallback, so it was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
9fdbb3fc0e tracing: ctf: add k_lifo tracing
CTF emitted no events for k_lifo (init, put and alloc_put, get); the
sys_port_trace_k_lifo_* hooks fell through to the no-op fallback, so it
was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
f0839daa37 tracing: ctf: add k_fifo tracing
CTF emitted no events for k_fifo (init, put and alloc_put, put_list,
put_slist, get, peek head/tail, cancel_wait); the
sys_port_trace_k_fifo_* hooks fell through to the no-op fallback, so it
was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Anas Nashif
f009676994 tracing: ctf: add k_queue tracing
CTF emitted no events for k_queue (init, append/prepend and their alloc
variants, insert, append_list, merge_slist, get, remove, unique_append
and peek); the sys_port_trace_k_queue_* hooks fell through to the no-op
fallback, so it was invisible in a CTF trace.

Add CTF coverage for every live hook: the event ids, ctf_top_* emitters,
sys_trace_* trampolines and prototypes, the sys_port_trace_* macros and
the matching TSDL event definitions in the metadata.

k_queue_insert_blocking has no kernel call site and is left to the no-op
fallback.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-08-03 08:49:29 -04:00
Etienne Carriere
8ad85c9cef tracing: use diamond include for non-local header files
Use #include <> instead of #include "" to include a header file which path
is not relative to the directory path of the file emitting the #include
directive.

This change was made running scripts/check_quoted_includes.py script
proposed in https://github.com/zephyrproject-rtos/zephyr/pull/112135
with the Linux shell command below and manually selecting the applicable
changes:
$ find subsys/tracing/ -type f -exec \
    ./scripts/check_quoted_includes.py -w {} \;

Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
2026-07-31 13:02:25 -04:00
Anas Nashif
945af04840 lib: os: cpu_load: close the idle window at ISR entry
The idle-hook backend closed its idle window from the idle-exit hook that
the architecture runs after the wait instruction. That only works on
architectures which wait with interrupts locked (Arm, RISC-V): the wait
returns without servicing the interrupt, so the exit hook runs before any
ISR.

Architectures that wait with interrupts enabled (x86 "sti; hlt", Xtensa
"waiti 0") let the wake-up ISR run first, and it can reschedule away from
the idle thread. The idle-exit hook is then deferred until the idle thread
is next scheduled, long after idle actually ended, so the busy time in
between is attributed to idle. Measured on qemu_xtensa, a window that was
100% idle reported a load of 1000 per mille instead of 0.

Make closing the window idempotent and also drive it from the ISR entry
hook, sys_trace_isr_enter().
The first interrupt after the CPU went idle is exactly the instant idle
ended, so closing there is accurate; a deferred idle-exit hook then finds
the window already closed and does nothing. Interrupts that did not
interrupt idle only pay one flag test.

Architectures that wait with interrupts locked are unaffected: their
idle-exit hook still closes the window before any ISR runs.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-17 11:55:28 -04:00
Anas Nashif
0997a8c0be lib: os: cpu_load: unify metric and idle-hook modules
The two CPU load modules that previously lived side by side (the
scheduler-runtime-statistics metric in lib/os/cpu_load_metric and the
idle-hook measurement in lib/os/cpu_load) are merged into a single
CONFIG_CPU_LOAD module with a pluggable backend selected through the
CPU_LOAD_BACKEND choice:

- CPU_LOAD_BACKEND_RUNTIME_STATS: scheduler runtime statistics,
  portable and multi-CPU capable (formerly CPU_LOAD_METRIC).
- CPU_LOAD_BACKEND_IDLE_HOOK: architecture idle hooks, low overhead
  with an optional hardware counter, single CPU.

A shared feature layer above the backends provides the current-CPU
getter, the periodic report timer and the threshold callback, so both
backends gain the periodic logging and callback features. The unified
getter pair returns the load in per mille:

  int cpu_load_get(bool reset);                       /* current CPU */
  int cpu_load_get_cpu(unsigned int cpu_id, bool reset);

CONFIG_CPU_LOAD_METRIC and cpu_load_metric_get() are kept as deprecated
compatibility wrappers; the latter returns percent as before. The
<zephyr/sys/cpu_load_metric.h> header now just includes
<zephyr/sys/cpu_load.h>. The tracing backends now gate the idle
accounting on CPU_LOAD_BACKEND_IDLE_HOOK rather than CPU_LOAD, since the
idle hooks only exist for that backend.

The cpu_freq on-demand policy is migrated to cpu_load_get_cpu() and
selects CPU_LOAD together with the new CPU_LOAD_MULTICPU helper to pull
in the runtime-statistics backend.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-17 11:55:28 -04:00
Anas Nashif
58cc81a2c8 lib: os: move cpu_load out of debug and drop tracing dep
The idle-hook based CPU load module lived under subsys/debug, required
CONFIG_TRACING, and exposed its API through <zephyr/debug/cpu_load.h>.
It does not conceptually belong to the debug subsystem, and its only
dependency on tracing was the idle notification hooks, now available
through CONFIG_SYS_IDLE_HOOKS.

Move the module to lib/os/cpu_load with its own CMakeLists and Kconfig,
relocate the public header to <zephyr/sys/cpu_load.h>, and select
SYS_IDLE_HOOKS instead of TRACING. Update all includers (the tracing
backends, samples and tests) to the new header path.

CONFIG_CPU_LOAD now builds and runs without the tracing subsystem.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-17 11:55:28 -04:00
Anas Nashif
25d08114e9 arch: gate idle notification hooks on SYS_IDLE_HOOKS
The architecture idle paths call sys_trace_idle() and
sys_trace_idle_exit() to notify subscribers when the CPU enters and
leaves the idle state. These calls were guarded by CONFIG_TRACING,
which tied idle-time accounting to the tracing subsystem even though
no tracing backend is required to service the hooks.

Introduce a hidden Kconfig symbol, SYS_IDLE_HOOKS, that any subsystem
needing these notifications can select, and have TRACING select it.
Switch the idle-path guards in every architecture and SoC that emits
the hooks from CONFIG_TRACING to CONFIG_SYS_IDLE_HOOKS. Because
TRACING selects the new symbol, existing tracing behaviour is
unchanged; the change only lets non-tracing consumers receive the
hooks.

This is a prerequisite for building the CPU load module without the
tracing subsystem.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-17 11:55:28 -04:00
Georgios Vasilakis
1e2ade68aa tracing: Add existed object check in SYS_TRACK_LIST_PREPEND
The SYS_TRACK_LIST_PREPEND unconditionally prepends an object in
the list without checking if the object is already in the list.

This is problematic and will corrupt the list if an object
is initiallized multiple times.

For example if you define an event with the macro:
K_EVENT_DEFINE(my_event)

and then you also initialize the object in code:
k_event_init(&my_event)

This will corrupt the list. Even though you don't need to run
the k_event_init after you statically define the event it is
not explicitely forbitten either so it should not corrupt
anything.

To fix that I updated the SYS_TRACK_LIST_PREPEND to check
if an object is already in the list and only prepend it
if it does not exist.

Signed-off-by: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
2026-07-14 20:06:56 -04:00
Pieter De Gendt
312b085a2a tracing: ctf: Add SYS_INIT enter/exit events
The kernel already calls sys_trace_sys_init_enter/exit around every
SYS_INIT and device init, but the CTF backend stubbed them out. Implement
them so per-init timing is captured.

Record the device name when the entry is a device, so the event is
self-describing in any CTF reader. Bare SYS_INIT entries have no runtime
name, so the init_fn pointer is recorded instead for offline resolution.
The init level and result are included as well.

Assisted-by: Claude:claude-opus-4.8
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2026-07-13 16:16:52 -05:00
Pieter De Gendt
66bef0f8ed tracing: Configurable init level
The tracing backend initialized at a fixed APPLICATION level. Make the
SYS_INIT level (TRACING_INIT_LEVEL) and priority (TRACING_INIT_PRIORITY)
configurable so tracing can come up earlier and capture more of the boot
sequence.

The earliest level is PRE_KERNEL_2 (sync tracing only — async needs the
kernel for its drainer thread), and it requires a priority above the
system timer (SYSTEM_CLOCK_INIT_PRIORITY) so the cycle counter is live
and event timestamps are valid. The defaults (APPLICATION, priority 0)
preserve the previous behavior.

Assisted-by: Claude:claude-opus-4.8
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2026-07-13 16:16:52 -05:00
Anas Nashif
df2f4b06c6 tracing: serialize the runtime core with a spinlock for SMP safety
Producers put trace packets into a single shared ring buffer under
TRACING_LOCK, which was a bare irq_lock(). irq_lock() only masks
interrupts on the local CPU, so on SMP two producers on different cores
could mutate the ring buffer concurrently and corrupt it - the buffer is
documented as single-producer and relies on the caller to serialize.

Back TRACING_LOCK/TRACING_UNLOCK with a k_spinlock instead. On SMP this
serializes producers across cores; on uniprocessor k_spin_lock()
degrades to the same interrupt-lock, so there is no added cost and
behaviour is unchanged.

Restructuring synchronous mode to emit to the backend outside the lock
was considered but not done: emitting synchronously from ISR context
with a blocking backend inherently keeps interrupts masked for the
transfer (which is why sync mode already requires a low-latency
backend), so it would not remove that property, and the extra
copy/critical-section regresses the high-rate sync UART test.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
4363b7c624 tracing: add a tracing shell
Runtime control of tracing was only possible over the UART host-command
path (CONFIG_TRACING_HANDLE_HOST_CMD). Add an optional "tracing" shell
command, behind CONFIG_TRACING_SHELL, to enable/disable emission, show
the tracing state and the dropped-packet count, and flush the backends.
It reuses tracing_set_enabled(), tracing_packet_drop_count_get() and
tracing_backends_flush() from the core.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
1b396d2a87 tracing: fan trace output out to all registered backends
The core resolved a single backend by name (CONFIG_TRACING_BACKEND_NAME)
into a working_backend pointer and emitted only to it. Backends already
live in an iterable section, so fan every trace packet out to the
configured backend plus any backend registered under a different name.
An out-of-tree module that adds a backend with TRACING_BACKEND_DEFINE()
then receives the same stream with no edits to the core tree; a backend
sharing the configured name (as some tests do to substitute a capture
backend) overrides it, so single-backend behaviour is unchanged.

The common single-backend case stays a direct call - the section is only
walked when a differently named backend exists - to avoid slowing
high-rate synchronous backends.

Also surface what was previously hidden: tracing_packet_drop_count_get()
for the otherwise write-only dropped-packet counter,
tracing_set_enabled() to toggle output at runtime, and an optional
flush() backend op with tracing_backends_flush(). These are used by the
tracing shell in a later commit.

tests/subsys/tracing/tracing_backend_fanout registers a second backend
and checks that it receives data.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
fd451c283d tracing: user: expose kernel-object hooks as weak callbacks
The CONFIG_TRACING_USER backend routed only thread, ISR, idle, sleep,
timer, GPIO and RTIO hooks to overridable __weak sys_trace_*_user()
callbacks; every kernel-object hook was a no-op, so an integrator could
not observe semaphores, mutexes, message queues, etc. without forking
the header.

Widen the backend to the kernel-object hooks (condition variables,
events, mailboxes, memory slabs, message queues, mutexes, polling,
semaphores, the remaining thread hooks and work queues): each
sys_port_trace_k_*() macro now calls a typed sys_trace_k_*() trampoline
that forwards to a __weak sys_trace_k_*_user() callback. The typed
signatures were taken from the CTF backend
(subsys/tracing/ctf/ctf_top.c), which already declares them.

Object types CTF itself does not trace (queue, fifo, lifo, stack, pipe,
heap) and the net/socket hooks are left out for now; they still resolve
to no-ops via the tracing_hooks.h fallback, so this is additive. The
trampoline functions reuse the CTF sys_trace_k_* names without conflict
because tracing_user.c and ctf_top.c are never compiled together.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
541ea15d43 tracing: support out-of-tree tracing formats via Kconfig string
The format selection in <zephyr/tracing/tracing.h> is a hardcoded
not add a tracing format without editing the core tree (Percepio, though
shipped as a module, still relies on a hardcoded include).

Mirror the existing CONFIG_TRACING_BACKEND_NAME pattern for formats: add
a promptless Kconfig string CONFIG_TRACING_FORMAT_HEADER that a module
assigns (default "my_format.h" if TRACING_MY_FORMAT), and pull it in
from tracing.h with a computed #include when no in-tree format is
selected. The format header defines the hooks it records and ends by
including tracing_hooks.h so the rest fall back to no-ops.

Add <zephyr/tracing/tracing_default_hooks.h> providing the default lower
sys_trace_* layer (isr/idle prototypes resolving to the weak no-ops in
tracing_none.c, plus no-op macros for named events and system init) so a
minimal out-of-tree format does not have to reimplement it.

A backend is already pluggable through TRACING_BACKEND_DEFINE(), so
neither a custom format nor a custom backend now requires changes to the
core tree. The new tests/subsys/tracing/tracing_format_module is a
complete worked example and verifies a format supplied purely via
CONFIG_TRACING_FORMAT_HEADER is wired into the kernel hook points.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
f976dfbc05 tracing: test: drop duplicated hook no-ops, use canonical fallback
Include tracing_hooks.h at the end of tracing_test.h, after the test
backend's own hook definitions, and remove the 164 empty no-op
sys_port_trace_* defines that the canonical fallback now supplies. As
with the user backend, tracing_test.h pulls in kernel.h before defining
its hooks, so the fallback is included here at the header's end.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
5093575ef8 tracing: user: drop duplicated hook no-ops, use canonical fallback
Include tracing_hooks.h at the end of tracing_user.h, after the user
backend's own hook definitions, and remove the 293 empty no-op
sys_port_trace_* defines that the canonical fallback now supplies.

tracing_user.h includes kernel.h (which re-enters tracing.h) before it
defines its hooks, so the fallback must be included here, at the end of
the header, rather than from tracing.h - otherwise the re-entrant
include would define the no-ops first and the real definitions below
would redefine them.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
03dd39120d tracing: sysview: drop duplicated hook no-ops, use canonical fallback
Include tracing_hooks.h at the end of tracing_sysview.h, after
SystemView's own hook definitions, and remove the 160 empty no-op
sys_port_trace_* defines that the canonical fallback now supplies. The
filled.

No functional change: every hook SystemView recorded expands as before.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Anas Nashif
7555bd3bf9 tracing: ctf: drop duplicated hook no-ops, use canonical fallback
Include tracing_hooks.h at the end of tracing_ctf.h, after CTF's own
hook definitions, and remove the 130 empty no-op sys_port_trace_*
defines that the canonical fallback now supplies. The #ifndef guards
keep CTF's real definitions; only the gaps are filled, so this header no
longer has to track the full hook list.

No functional change: every hook CTF defined expands exactly as before,
and the previously-undefined hooks now resolve to a no-op instead of
being absent.

Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2026-07-08 18:30:09 -04:00
Nicolas Pitre
465dccef22 timing: rename timing_ns_get() to avoid a benchmark syscall clash
Commit ca3d07f70e ("timing: add timing_timestamp_get() for monotonic
timestamps") added a public timing_timestamp_get() to
<zephyr/timing/timing.h>. The app_kernel and latency_measure benchmarks
already define a local userspace syscall of that name to read the raw
timing counter from user threads, and they include timing.h, so the
declarations now collide:

  error: static declaration of 'timing_timestamp_get' follows non-static
  declaration

Rename the newly added API to timing_ns_get(). Besides resolving the
clash, the name better reflects that it returns a monotonic nanosecond
value, not the raw timing_t counter that the benchmarks' helper returns.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-04 09:06:19 -04:00
Nicolas Pitre
ca3d07f70e timing: add timing_timestamp_get() for monotonic timestamps
timing_counter_get() may be backed by a counter narrower than 64 bits
that wraps. Consumers wanting an absolute time reference rather than the
duration between two readings (the CTF trace timestamp, the
instrumentation timestamp) computed the interval from a fixed zero, which
simply returns the raw counter and so jumps backwards on every wrap.

Add timing_timestamp_get(), which accumulates the interval since its
previous reading into a 64-bit total before converting to nanoseconds, so
the result stays monotonic across wraps. Each interval is non-negative, so
the value is monotonic no matter how often the function is called; it is
also accurate as long as no more than one wrap occurs between consecutive
calls, beyond which it undercounts the elapsed time but still only
advances. The accumulator is not seeded on the first call, so timestamps
are offset by the counter value at that point rather than starting from
zero, just like the previous version did; this only shifts the origin and
avoids a first-call test on every subsequent call. A spinlock keeps the
shared accumulator consistent on SMP, where the callers' irq_lock does
not.

Use it from both consumers, which previously open-coded the zero-based
form. The cost stays on this absolute-timestamp path; consumers that
measure intervals between two explicit readings are unaffected.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-07-03 13:56:44 -04:00
Nicolas Pitre
1e68351a25 kernel: userspace: abort timer before freeing
Re-implementation of the fix originally proposed as PR #109426 on
top of the z_try_abort_timeout() infrastructure.

When a dynamically allocated k_timer's reference count drops to
zero its storage is about to be freed. If the timer's expiration
handler is in flight on another CPU at this moment, it will
dereference the freed memory.

Introduce k_timer_cleanup(): cancels the timeout and waits for any
in-flight handler to complete. Unlike k_timer_stop() it does not
run the user stop_fn nor wake pending threads -- the caller is
about to drop the storage and there is no further consumer. The
retry-on-EAGAIN loop around z_try_abort_timeout() guarantees that
when this returns 0 the handler has fully run; no in-band sentinel
is involved.

unref_check() in kernel/userspace/userspace.c calls
k_timer_cleanup() for K_OBJ_TIMER, guarded by K_OBJ_FLAG_INITIALIZED
(z_waitq_head() on an uninitialized dnode would otherwise read
garbage).

Add sys_port_trace_k_timer_cleanup_{enter,exit} hooks across the
tracing backends (default no-op).

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2026-06-15 18:35:49 -04:00
James Growden
dd804fa33a tracing: uart: build fix
Change break to return in order to compile

Signed-off-by: James Growden <jgrowden@tenstorrent.com>
2026-06-08 21:29:29 -04:00
Anas Nashif
d0b389da9e kernel: remove redundant kernel_structs.h includes
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>
2026-06-02 20:24:14 +02:00
Jinming Zhao
fed96f09c2 tracing: user: Add sleep event tracing support
Sleep events are not traced in the user tracing backend. In addition,
k_sleep() does not go through the pending state, so there is no pend
event either. This leaves a thread switch-out with no context in the
trace, which can be confusing when analyzing scheduler behavior.

Add the missing sleep hooks (k_sleep, k_usleep, k_msleep) to the user
tracing backend and update the sample to demonstrate their output.

Signed-off-by: Jinming Zhao <jinmzhao@qti.qualcomm.com>
2026-05-27 08:34:21 +02:00