Commit graph

558 commits

Author SHA1 Message Date
Roman Bakshansky
5c8e33bed1 lib: os: cbprintf: fix -wsign-compare warning
Replace ternary operator with if-else to avoid mixing signed and unsigned
types in the conditional expression. This eliminates the compiler warning
while preserving the original logic.

Fixes #104581

Signed-off-by: Roman Bakshansky <bakshansky@protonmail.com>
2026-03-11 20:48:34 -04:00
Adrian Warecki
fab9ced9dc logging: sensing: tests: Add missing compiler barriers
Add missing memory barriers after branching on k_is_user_context() to
prevent reordering possible of privileged memory access.

Signed-off-by: Adrian Warecki <adrian.warecki@intel.com>
2026-03-06 11:37:00 +00:00
Alberto Escolar Piedras
28c6f4d8d5 zvfs: Use own macros and remove include
Use the zvfs macros in the code of the module itself, instead of using
the versions from the POSIX API, and remove the header that defined those
as it is not needed anymore.

Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
2026-02-26 21:25:31 +00:00
Pete Johanson
dabb43615a spsc_pbuf: Move to new barrier_sync_synchronize() API
Move to the new barrier_sync_synchronize() wrapper API.

Signed-off-by: Pete Johanson <pete.johanson@analog.com>
2026-02-25 18:47:53 +01:00
Krzysztof Chruściński
4cdc5844ba lib: os: cbprintf: Add option to use default alignment for rv32e
Add option to use default alignment when building a cbprintf package
on riscv (rv32e). It is useful in case when cbprintf packages are not
formatted on rv32e but on another core. There is such case on nrf54h20
where log messages are formatted by the ARM Cortex M33 core (cpuapp)
and without this option 64 bit arguments are incorrectly formatted.

Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
2026-02-19 12:53:43 +01:00
Chris Friedt
351a12d921 lib: os: do not include posix sys/types.h header
There is no need to pull in POSIX types in either of the modified files,
so remove the `<sys/types.h>` inclusion.

Signed-off-by: Chris Friedt <chris@fr4.co>
2026-02-13 09:47:38 -06:00
Jamie McCrae
d94ed7b316 lib: os: Fix ZVFS leaking without being enabled
Fixes this define leaking into all application source files when
the feature is not even enabled

Co-authored-by: Chris Friedt <cfriedt@tenstorrent.com>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
2026-01-09 14:23:25 -06:00
Marco Casaroli
a78db0f8a9 posix: eventfd: ignore k_condvar_broadcast result
k_condvar_broadcast does not error. It returns the number of
woken threads on success. We should not assert any value.

Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
2026-01-08 08:31:56 -05:00
Marco Casaroli
aa607f9b0a posix: eventfd: fix deadlock with POSIX API
When eventfd is used through read(2) and write(2), the mutex is
already locked from the fdtable implementation. So we remove the
usage of the mutex from the zvfs_eventfd_*_op functions, as it is
already managed by fdtable.

However, when zvfs_eventfd_{read,write} are used, no fdtable layer
is used and we shuld call the _op function with the mutex locked
(the same behavior as with fdtable), so these functions should
manage the mutex. We add it there.

Fixes #99234

Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
2026-01-08 08:31:56 -05:00
Samuel Coleman
3332a97295 lib: cbprintf: perform length calculation dry-run.
C99 § 7.19.6.5 defines `snprintf`. According to ¶ 2:

> If `n` is zero, nothing is written, and `s` may be a null pointer.

And according to § 7.19.6.12 ¶ 2:

> The `vsnprintf` function is equivalent to `snprintf` (...)

However, prior to this change, `vsnprintfcb` (and indirectly, `snprintfcb`)
unconditionally null-terminates the output buffer.

This fixes #48394, which was auto-closed without actually being fixed.

Co-authored-by: Adrien Lessard <adrien.lessard@rbr-global.com>
Signed-off-by: Samuel Coleman <samuel.coleman@rbr-global.com>
2026-01-07 10:20:22 +01:00
Chris Friedt
3c855aeddd zvfs: eventfd: count eventfd file descriptors for fdtable size
Previously, eventfd file descriptors were not being counted against the
required size for the global file descriptor table, which would result
in the function `eventfd()` (and `zvfs_eventfd()`) failing due to
insufficient resources.

Signed-off-by: Chris Friedt <chris@fr4.co>
2026-01-06 19:14:47 +00:00
Bjarki Arge Andreasen
66dbe436bd lib: os: poweroff: Disable ZLIs before poweroff
We currently only disable "normal" IRQs with irq_lock(). This is not
sufficient if ZLIs are enabled, as even though they are supposed to
be "above" the kernel, they must not interrupt the poweroff procedure.

Signed-off-by: Bjarki Arge Andreasen <bjarki.andreasen@nordicsemi.no>
2025-12-14 11:14:45 +00:00
Bjarki Arge Andreasen
7c72e3cc42 lib: os: reboot: Disable ZLIs before reboot
We currently only disable "normal" IRQs with irq_lock(). This is not
sufficient if ZLIs are enabled, as even though they are supposed to
be "above" the kernel, they must not interrupt the reboot procedure.

Signed-off-by: Bjarki Arge Andreasen <bjarki.andreasen@nordicsemi.no>
2025-12-14 11:14:45 +00:00
Peter van der Perk
819955b52c kernel: thread: mark return undefined in z_thread_entry using DWARF
Add DWARF hint to handle z_thread_entry correctly
in debuggers. This function starts a new thread and never returns.
Use `.cfi_undefined` so DWARF-based unwinding does not rely on return.
Without this, unwinding may follow a bogus return address, leading to
invalid memory reads and potential bus faults during backtrace.

Signed-off-by: Peter van der Perk <peter.vanderperk@nxp.com>
2025-11-20 08:59:42 -05:00
Fei Wang
8af60c6239 lib: os: mpsc_pbuf: fix potential semaphore wait forever
One thread calls mpsc_pbuf_alloc to produce data, which invokes
add_skip_item and steps into k_sem_take.

Another thread calls mpsc_pbuf_claim to consume data. In this condition,
mpsc_pbuf_claim has only small remaining space and needs to call rd_idx_inc
to reserve space, but there is still no data available.

The consumer should call k_sem_give to wake mpsc_pbuf_alloc again,
so the producer can allocate space and continue producing data.

Without this wake-up, the producer thread may wait forever in
k_sem_take, leading to a deadlock situation.

Signed-off-by: Fei Wang <fei.wang@jaguarmicro.com>
2025-11-19 15:56:39 -05:00
Jakub Klimczak
3c4277391a zvfs: Remove test for static initialization of stdin, stdout, stderr
This removes a function that created a new mutex and conditional variable
and used memcpy() to compare them with ones in a given fdtable entry.
Since those struct members are initialized statically, this test doesn't
serve much of a purpose anymore. Moreover, padding bytes inside structs
are technically not required to be zero, so these memcpy() calls caused
SonarQube to complain.

Signed-off-by: Jakub Klimczak <jklimczak@internships.antmicro.com>
2025-11-18 08:12:19 -05:00
Jakub Klimczak
f16f3f641e zvfs: Move fdtable into ZVFS
The file descriptor table is used in every area that expects to work on
files through descriptor indices. It can only be operated on through
functions whose names indicate a relationship with ZVFS (`zvfs_*fd*`).
The integer file descriptor mechanism shouldn't be separate from ZVFS.
This will make cooperation between different file access APIs much
simpler. This commit also makes preparations for the fdtable becoming
optional.

Signed-off-by: Jakub Klimczak <jklimczak@internships.antmicro.com>
2025-11-18 08:12:19 -05:00
Jakub Klimczak
735f0d7363 zvfs: Move file operations from POSIX into ZVFS
This commit moves all operations on single files into ZVFS and makes the
POSIX subsystem call into ZVFS to perform them. It was necessary to define
a `struct zvfs_stat` to avoid a dependency cycle. Functions used
internally for file i/o operations are publicised since they won't require
any changes between various subsystems. This allows ZVFS to actually
fulfill its purpose of facilitating cooperation of different file APIs.

Signed-off-by: Jakub Klimczak <jklimczak@internships.antmicro.com>
2025-11-18 08:12:19 -05:00
Anas Nashif
4e9a4e385a cpu_load: rename conflicting API
We have two places defining cpu_load_get() and trying to the same thing,
one is a core kernel feature supported on all architecture, the other is
part of debug, requires tracing and supported only on a subset of
architectures. Both deliver different results and accuracy.

While we figure our how to merge those into one API and with the
advanatges of both, rename the API so there is no confusion about what
is being used.

Fixes #97845

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-11-07 10:27:50 +02:00
Anas Nashif
303af992e5 style: fix 'if (' usage in cmake files
Replace with 'if(' and 'else(' per the cmake style guidelines.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-10-29 11:44:13 +02:00
Fabio Baltieri
700a1a5a28 lib, kernel: use single evaluation min/max/clamp
Replace all in-function instances of MIN/MAX/CLAMP with the single
evaluation version min/max/clamp.

There's probably no race conditions in these files, but the single
evaluation ones save a couple of instructions each so they should save
few code bytes and potentially perform better, so they should be
preferred in general.

Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
2025-10-24 01:10:40 +03:00
Anas Nashif
24e094ef5e lib: move cpu_load into lib/os
Move cpu_load to lib/os, as this functionality on its own does not
justify being a subsystem on its own.

Fixes #95498

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-10-22 09:02:38 +02:00
Jukka Rissanen
1cfdf7c8d1 lib: Introduce a way to set minimum file descriptors count
Instead of user trying to figure out what is the amount of file /
socket descriptors in the system, let the various subsystems etc.
specify their need using a Kconfig option. The build system will
then add these smaller values together and set a suitable file
descriptor count in the system.

This works the same way as the heap size calculation introduced
in commit 3fbf12487c

Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2025-10-21 17:22:03 +03:00
Anas Nashif
f22a0afc74 testsuite: coverage: Support semihosting
Use semihosting to collect coverage data instead of dumping data to
serial console.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-10-14 17:32:46 -04:00
Chaitanya Tata
19449e4396 wifi: treewide: Adjust defaults for dual mode usage
In case STA + AP mode is enabled, then adjust the defaults to accomodate
the second interface.

Signed-off-by: Chaitanya Tata <Chaitanya.Tata@nordicsemi.no>
2025-09-19 08:27:55 -04:00
Alberto Escolar Piedras
1d6da40624 lib: os: clock: Fix possibly unitialized variable warning
When building with high optimization level, the compiler thinks
duration may be used initialized and warns as much.

Let's initialize this variable always to ensure it does not happen
and with it pacify the compiler.

Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
2025-09-13 09:37:19 +02:00
Chris Friedt
4ff059395b sys: timeutil: compute the remainder in timespec to timeout conversion
Since it's possible that rounding up might not always be the right thing
to do in every situation, in order to allow the application to make more
informed decisions, we created a modified timespec_to_timeout() that also
returns the remainder (or difference) between the requested time to
convert and resulting k_timeout_t. The difference is expressed as a
timespec object.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-09-02 15:53:54 +02:00
Clay Wynn
40e91b4242 os: add __weak to to assert_print to allow customization
System designers may want to change the behavior of assert_print, such as
storing the message off into retained RAM and instantly rebooting. Adding
__weak allows customatization

Signed-off-by: Clay Wynn <cwynn@meta.com>
2025-08-29 22:57:52 -04:00
Mohamed Moawad
4b90816982 posix: Map CLOCK_REALTIME and CLOCK_MONOTONIC to Zephyr clock IDs
Some toolchains may define CLOCK_REALTIME and
CLOCK_MONOTONIC in their libc headers
with values that differ from Zephyr's internal
SYS_CLOCK_REALTIME and SYS_CLOCK_MONOTONIC.

To ensure consistent behavior across all boards and
toolchains, Introduce a helper function to map
CLOCK_REALTIME and CLOCK_MONOTONIC to Zephyr's internal
clock IDs (SYS_CLOCK_REALTIME and SYS_CLOCK_MONOTONIC).

This prevents mismatched clock IDs being passed to
the kernel, avoiding invalid clockid errors when using
functions like clock_gettime().

Signed-off-by: Mohamed Moawad <moawad@synopsys.com>
2025-07-19 13:43:21 -04:00
Chris Friedt
9e5e294ea4 lib: os: clock: fix for CID 529870
Fix for CID 529870, where Coverity found an issue where `timespec.tv_sec`
is never greater than `UINT64_MAX / NSEC_PER_SEC` (18446744073).

This is naturally true when `time_t` is only 32-bit, which is actually
never the case for any Zephyr platform aside from `native_sim/native/32`.

When `time_t` is a signed 64-bit value, at some point in the future, but
maybe not in our lifetimes, `timespec.tv_sec` could exceed 18446744073,
since `INT64_MAX > UINT64_MAX / NSEC_PER_SEC`.

We should not see coverity issues errors like this in the future, once we
have a consistent `time_t` representation across all Zephyr platforms.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-07-11 08:21:46 -10:00
Robert Lubos
c7757b982c lib: os: zvfs: select: Fix warning about bitshifting signed value
This was caught by UBSAN:

  zvfs_select.c:70:2: runtime error: left shift of 1 by 31 places
  cannot be represented in type 'int'

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2025-07-04 13:16:32 -05:00
Jukka Rissanen
410afbaf19 lib: zvfs: Add default eventfd count for hostap
hostap needs more eventfd to function so set a proper default value.

Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2025-06-27 10:56:49 +02:00
Chris Friedt
a3e934f12c sys: clock: additional sys_clock api calls
Additional entries for the sys_clock API, comprised of:

* sys_clock_gettime()
* sys_clock_settime()
* sys_clock_nanosleep()

along with the constants

* SYS_CLOCK_REALTIME
* SYS_CLOCK_MONOTONIC
* SYS_TIMER_ABSTIME

The primary motivation for this API is so that libc and other
libraries have a familiar-enough API to reach to when POSIX
is not available, since POSIX is optional in Zephyr.

By adding this API to lib/os, we also eliminate dependency cycles
between libc and posix, as lib/os is a mutual dependency.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-06-24 14:18:52 +02:00
Anas Nashif
d4a2b7dc57 lib: os: cbprintf_complete: add missing break statement
Add missing break in switch statement.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-06-18 17:48:03 -04:00
Tim Pambor
3b90ed6122 lib: os: Fix function signature of str_out
Update the str_out function signature to match the expected
cbprintf_cb_local type:
typedef int (*cbprintf_cb_local)(int c, void *ctx);

Signed-off-by: Tim Pambor <tim.pambor@codewrights.de>
2025-06-18 17:45:06 -04:00
Alberto Escolar Piedras
ca5b7506e8 lib/os/fdtable: Remove ifdef on NATIVE_POSIX
This board does not exist anymore, so this is just dead code at this
point.

Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
2025-03-12 02:27:36 +01:00
Damian Krolik
73802412a8 lib: os: mpsc_pbuf: take spinlock in utilization getters
Two public functions do not take the spinlock even though
they access mutable, non-atomic members of the buffer:
- mpsc_pbuf_get_utilization()
- mpsc_pbuf_get_max_utilization()

Take the spinlock to avoid possible data races.

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2025-02-18 13:30:29 +01:00
Luis Ubieda
ec45b29ea3 p4wq: Add Kconfig to perform early init on threads
In order to make them functional for devices during init. Default
behavior is to keep late initialization, as before.

Signed-off-by: Luis Ubieda <luisf@croxel.com>
2025-02-18 05:32:58 +01:00
Florian Weber
093b29fdb5 lib: os: p4wq: add done handler
Add an optional handler to the p4wq to give the submitting code
(e.g. rtio workq) a possibility execute code after the work was
succesfully executed.

Signed-off-by: Florian Weber <Florian.Weber@live.de>
2025-02-12 16:03:17 +01:00
Krzysztof Chruściński
3e52109590 lib: os: mpsc_pbuf: Fix infinite loop during allocation
It was possible that allocation was continuously attempting to find
space. It could happen if allocation interrupted consuming a packet
(which is marked as busy) and there is not enough space to allocate
requested packet but there would be if busy packet was freed.
Algorithm in that case was continuously going through the buffer
in search for packets that can be dropped to find space for the
new packet.

Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
2025-01-29 17:55:56 +01:00
Pisit Sawangvonganan
e3a4a16594 lib: fix typo in multiple directories
Utilize a code spell-checking tool to scan for and correct spelling errors
in various files within the `lib` directory.

Signed-off-by: Pisit Sawangvonganan <pisit@ndrsolution.com>
2025-01-28 00:06:18 +01:00
Nicolas Pitre
46aa6717ff Revert "arch: deprecate _current"
Mostly a revert of commit b1def7145f ("arch: deprecate `_current`").

This commit was part of PR #80716 whose initial purpose was about providing
an architecture specific optimization for _current. The actual deprecation
was sneaked in later on without proper discussion.

The Zephyr core always used _current before and that was fine. It is quite
prevalent as well and the alternative is proving rather verbose.
Furthermore, as a concept, the "current thread" is not something that is
necessarily architecture specific. Therefore the primary abstraction
should not carry the arch_ prefix.

Hence this revert.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-01-10 07:49:08 +01:00
Yong Cong Sin
1a578eb72c lib: os: mpsc_pbuf: do not wait when spinlock is held
Check if the spinlock is held before attempting to wait by
taking the semaphore, as that would cause a context switch which
isn't allowed and will trigger an assertion error when
`CONFIG_SPIN_VALIDATE` is enabled.

Logging in spinlock-held context when the log buffer is full can lead
to an infinite assertion error loop, as the logging subsys attempts to
allocate buffer when there's none available, it will try to wait for
one and thus triggers the assertion error, the error message will be
printed through the logging sybsys but there's no buffer available,
so it will try to wait for one and triggers another assertion error..
This loop just goes on and on forever, and nothing gets printed to
the terminal.

Added a test to validate the fix.

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
Signed-off-by: Maxim Adelman <imax@meta.com>
2025-01-06 06:53:52 +01:00
Chris Friedt
68c0ff4e85 posix: fcntl.h: define constants in terms of zvfs constants
Define fcntl.h constants in terms of zvfs constants.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-01-05 09:58:54 +01:00
Chris Friedt
e08cc508e1 os: fdtable: set offset to zero with newly reserved fd's
Previously, if a file object is was re-used, it could
inherit the offset field of the previously closed file object,
making reading from the beginning of the file impossible
until the offset was manually zero'ed.

The offset should *always* be zero when a file is ready to be
used.

The issue really only presents itself when implementing a
vtable backend.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-01-05 09:58:19 +01:00
Chris Friedt
2a2806bb40 os: fdtable: restore errno if optional locking ioctl fails
The `zvfs_finalize_typed_fd()` function notifies some backends
via `ioctl()` with `ZFD_IOCTL_SET_LOCK`. However, support for
this method and functionality is optional.

In backends that do not support locking, this benign failure can
set `errno` to 95 (`EOPNOTSUPP`) in many circumstances where a
change in `errno` (indicating some kind of failure) is not
appropriate.

Prevent errno poisoning by backing-up and restoring `errno`.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-01-05 09:57:49 +01:00
Kai Vehmanen
4b49d7cb23 lib: os: p4wq: fix K_P4WQ_DELAYED_START mode
When the PRESTART thread state was removed, this changed the semantics
of k_thread_start() when thread was created with a K_FOREVER timeout,
suspended and then started with k_thread_start().

This sequence is used in p4wq to implement K_P4WQ_DELAYED_START
(which again is needed by K_P4WQ_USER_CPU_MASK).

With PRESTART removed, the following sequence:
  z_mark_thread_as_not_suspended(thread);
  k_thread_start(thread);

.. no longer starts the thread. As a result, p4wq users like SOF
multicore configurations, hit errors as p4wq threads never start.

Fix the implementation by removing the calls to change thread
suspended state explicitly, but rather rely on the new
k_thread_create() and k_thread_start() semantics.

Fixes: 7cdf40541b ("kernel/sched: Eliminate PRESTART thread state")
Signed-off-by: Kai Vehmanen <kai.vehmanen@linux.intel.com>
2024-12-04 22:26:38 -05:00
Yong Cong Sin
b1def7145f arch: deprecate _current
`_current` is now functionally equals to `arch_curr_thread()`, remove
its usage in-tree and deprecate it instead of removing it outright,
as it has been with us since forever.

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
Signed-off-by: Yong Cong Sin <yongcong.sin@gmail.com>
2024-11-23 20:12:24 -05:00
Jukka Rissanen
04d8b7c595 net: sockets: Cleanup socket properly if POSIX API is enabled
The sock_obj_core_dealloc() was not called if close() is called
instead of zsock_close(). This happens if POSIX API is enabled.

Fix this by calling zvfs_close() from zsock_close() and then
pass the socket number to zsock_close_ctx() so that the cleanup
can be done properly.

Reported-by: Andreas Ålgård <aal@ixys.no>
Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2024-11-08 15:56:39 -06:00
Krzysztof Chruściński
3bf54a9e85 lib: os: cbprintf_packaged: Fix cbprintf_package_convert
When conversion is done in two steps (output length calculation
followed by the actual conversion), it was failing when helper
array for holding calculated string length from the first
conversion run was shorter than number of strings that were
supposed to be appended to the package. Fix by taking into
account strl_len to determine if length can be taken from the
array or need to be calculated again.

Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
2024-11-01 09:56:03 -05:00