The `cbprintf_cb` callback function taken by `cbvprintf()` may return a
negative number to indicate an I/O error. The `str_out()` function can
never error (it just copies the input to a buffer), but it always returns
its input. For regular ASCII input, this is merely nonsense; however, when
writing out a character with its MSB set (e.g., UTF-8-encoded text), the
character is sign-extended, and the function returns a negative number.
This is interpreted as an error by `outs()` (in `cbprintf_complete.c`), and
so printing concludes after a single character.
For example, prior to this change, the assertion in this snippet fails:
char buf[16];
int len = snprintfcb(buf, sizeof(buf), "\xED\xA0\xBD\xED\xB1\x8D");
assert(len == 6);
Signed-off-by: Samuel Coleman <samuel.coleman@rbr-global.com>
the boot banner is printed at the end of
the init process with
``SYS_INIT(boot_banner, APPLICATION, 0);``
we don't need the early console for it.
When CONFIG_EARLY_CONSOLE is enabled,
the console will init with PRE_KERNEL_1, otherwise
with POST_KERNEL. Both are before APPLICATION.
For compatibility `EARLY_CONSOLE` will now be enabled by default,
as it was selected by the boot banner before, that is also
enabled by default.
Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
Added option CONFIG_LOG_PRINTK_STATIC which redirects printk's to
logging macro which creates message during compilation by examining
argument types using _Generic keyword. When this option is enabled
printk format string is not accessed in runtime so it can be removed
(e.g. in dictionary based logging). When this option is enabled printk
is much faster. Option is implied when dictionary based logging is
enabled.
The only condition that must be met to use build time message creation
macros is that format string is a string literal and not a variable.
That is the case for printk because it is using __printf_like gcc
extension to validate that.
Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
Similarly to the existing CONFIG_ZVFS_OPEN_ADD_SIZE_* mechanism used to
size the file descriptor table, allow subsystems to declare their eventfd
count requirements via CONFIG_ZVFS_EVENTFD_ADD_SIZE_* Kconfig options.
These are summed up at build time and compared against
CONFIG_ZVFS_EVENTFD_MAX, with the larger of the two values used to size
the eventfd table, exposed as the ZVFS_EVENTFD_SIZE compile definition.
A new CONFIG_ZVFS_EVENTFD_IGNORE_MIN option allows to override the
calculated requirement and use CONFIG_ZVFS_EVENTFD_MAX as-is.
As each eventfd also consumes a file descriptor, the resulting eventfd
count is now reserved in the file descriptor table as well, replacing the
former CONFIG_ZVFS_OPEN_ADD_SIZE_EVENTFD option which only accounted for
CONFIG_ZVFS_EVENTFD_MAX.
The WPA supplicant requirement is moved from a CONFIG_ZVFS_EVENTFD_MAX
default into a dedicated
CONFIG_ZVFS_EVENTFD_ADD_SIZE_WIFI_NM_WPA_SUPPLICANT option.
Assisted-by: Cursor:Claude Opus 4.8
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Replace z_unpend_first_thread() with z_unpend_first_thread_locked() and
migrate every caller across the kernel. The old function dropped the
scheduler spinlock before returning, exposing a race window between
its caller's "arch_thread_return_value_set + z_ready_thread" pair and
a still-in-flight timeout handler that could ready the thread first --
the woken thread might then run on another CPU and see an uninitialized
swap_retval. Pre-1b8c7a3 the dticks-cancel check made the handler bail;
here we fix it cleanly by requiring the caller to hold _sched_spinlock
across the entire wake, so the handler is blocked for the duration and
runs as a no-op afterwards.
z_unpend_first_thread_locked() requires the caller to be inside a
locked region and must be paired with z_sched_ready_locked() (and
whatever return-value setup is needed) under the same lock acquisition.
Sites migrated:
Simple "set retval [+ swap_data] and ready" callers use the existing
z_sched_wake() convenience wrapper, refactored to use the new
helper internally:
sem (give, reset), mem_slab (free), stack (push),
condvar (signal, broadcast), msgq (purge),
queue (cancel_wait, queue_insert, append_list),
futex (wake).
Sites that need additional setup on the woken thread use
LOCK_SCHED_SPINLOCK + z_unpend_first_thread_locked() + custom wake:
mutex (unlock -- needs the thread reference to track new owner),
msgq put / get (needs memcpy into the receiver's swap_data
buffer before the return value is set).
The dticks-cancel check in z_thread_timeout() is left in place; it is
no longer load-bearing once z_abort_thread_timeout() has no callers,
and is removed in the next commit.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
When CONFIG_POSIX_DEVICE_IO and CONFIG_PICOLIBC are enabled,
stdinout_write_vmeth will return 0, causing the write function to
busy-wait forever on file descriptor 1 (stdout).
This change makes the function work with Picolibc, so we can use
write with file descriptor 1 to output data to the stdout_hook of
picolibc.
Signed-off-by: Marco Casaroli <marco.casaroli@gmail.com>
Since commit 37717b229f ("sys: util: rename Z_MIN Z_MAX Z_CLAMP to min
max and clamp"), <zephyr/sys/util.h> unconditionally defines function-
like macros named `min`, `max`, and `clamp` in the global namespace (in
C mode). util.h gets pulled in transitively by very broad headers,
including the POSIX layer's <pthread.h>, so any third-party C code that
uses these names as ordinary identifiers (e.g. XNNPACK's static `clamp`
helper and its public `clamp` struct field) fails to build as soon as
<pthread.h> is included.
Following the approach used by Linux, move the lowercase `min`, `max`,
`min3`, `max3`, and `clamp` macros (and their helpers) into a new
<zephyr/sys/minmax.h> header that has to be included explicitly by
source files that want them. util.h keeps the uppercase MIN/MAX/CLAMP,
so most code is unaffected; only the (much smaller) set of files that
actually use the lowercase variants needs to pick up the new include.
Fixes#107853.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
the boot banner is printed at the end of
the init process with
``SYS_INIT(boot_banner, APPLICATION, 0);``
we don't need the early console for it.
When CONFIG_EARLY_CONSOLE is enabled,
the console will init with PRE_KERNEL_1, otherwise
with POST_KERNEL. Both are before APPLICATION.
Signed-off-by: Fin Maaß <f.maass@vogl-electronic.com>
When cbvprintf_package() packages a %s argument, append_string()
eventually calls strlen(str) on the pointer. If the caller passed
NULL to %s, strlen() dereferences address 0. On MMU-less targets
this is undefined behavior; on TF-M targets the SPU fields a read
at address 0 as SECURE_FAULT, which aborts the whole image.
Passing NULL to %s is a caller bug. However, deferred/packaged
logging captures the argument now and dereferences it later,
disconnecting the crash site from the offending call site and
making triage significantly harder. Substitute "(null)" in place
of a NULL string, matching the behavior of glibc's printf family,
so the buggy caller shows up in the log output rather than the
log infrastructure crashing.
Signed-off-by: Diego Solano <diegosolano@gmail.com>
The CONFIG_NET_SOCKETS_POLL_MAX Kconfig option was deprecated in
Zephyr 4.0.0, remove it and any leftover in-tree option use.
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Introduces K_MEM_SLAB_DEFINE_TYPE() and K_MEM_SLAB_DEFINE_STATIC_TYPE()
helpers to allow the user to declare slabs for types without having to
manually ensure the alignment is correct.
Manual slab alignment was very error-prone and this change fixes several
instances of misalignment that would be trapped by the undefined
behavior sanitizer when running on 64-bit targets.
Signed-off-by: Egill Sigurdur <egill@egill.xyz>
This moves the atomic_c.c from kernel to lib/os as atomic
functions are not exactly kernel features.
This also moves all the atomic kconfigs from kernel to lib/os
as the atomic headers are already under include/zephyr/sys/.
Signed-off-by: Daniel Leung <daniel.leung@intel.com>
This moves boot arguments from kernel into the lib/os.
This is not strictly a kernel function so this change provides
a separation between core kernel functionalities and others.
Signed-off-by: Daniel Leung <daniel.leung@intel.com>
Boot banner is not exactly a kernel feature. It is more like
an OS feature so moving it into lib/os.
Signed-off-by: Daniel Leung <daniel.leung@intel.com>
The cbprintf_cb typedef used an empty parameter list () which in C23
is equivalent to (void), making it incompatible with any callback
function that takes parameters.
Fix by giving cbprintf_cb a proper prototype (int c, void *ctx),
removing the now-redundant cbprintf_cb_local typedef, and adding
explicit (cbprintf_cb) casts at call sites where the callback has a
different signature (fputc, sprintf_out).
Signed-off-by: Shuai Ma <Shuai.MA@cn.bosch.com>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>