Commit graph

359 commits

Author SHA1 Message Date
Tim Pambor
9ab0c1b183 sys: timeutil: Fix warning in timespec_is_valid
Cast NSEC_PER_SEC to long to resolve a compiler warning about comparison
between signed and unsigned integer expression.

Signed-off-by: Tim Pambor <tim.pambor@codewrights.de>
2025-06-18 17:49:56 -04:00
Benjamin Cabé
f899ff2475 include: util: fix doxygen comment for utf8_trunc
Properly format code block

Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
2025-06-17 16:09:06 +02:00
Sayooj K Karun
cd7c78e92e lib: min_heap: Add min-heap data structure
Introduce a binary min-heap implementation as a generic data structure
for use in kernel and application code. A min-heap always maintains
the smallest element at the root, making insertion and removal of the
minimum element efficient (O(log n)).

The API allows both static and dynamic initialization, supports custom
comparators.

Signed-off-by: Sayooj K Karun <sayooj@aerlync.com>
2025-06-07 13:29:24 +01:00
Luca Arato
ab0218ed7e sys: Remove static modifier
Remove static struct modifier from SPSC_DECLARE macro.
This solves a warning emitted when compiling for native_sim.

Signed-off-by: Luca Arato <luca.arato@secomind.com>
2025-06-06 08:43:03 +02:00
Anas Nashif
6559c7f554 sys: slist/sflist: remove stray FIXME
The FIXME asking a question that is not valid anymore, remove the FIXME.

Fixes #90764

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-06-05 09:34:55 +02:00
Chris Friedt
13e827fe1b sys: timeutil: add missing copyright for recent changes
Add copyright for changes that were included with #90060.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-05-27 06:51:38 +02:00
Chris Friedt
d3ec91674a sys: timeutil: check for 32-bit time_t to avoid warning (part 2)
Same error had to be fixed in the branch where optimizations were done.

This is probably a good example of where using `if (IS_ENABLED()) ...`
is a better choice than using `#ifdef`. Because the compiler would have
caught this error last time as well.

Anyway, same problem - different line(s)!

A warning was propogated to error when building for
native_sim/native.

```
timeutil.h:682:17: error: result of comparison of constant \
  -9223372036854775808 with expression of type '__time_t' (aka 'long') \
  is always false [-Werror,-Wtautological-constant-out-of-range-compare]
timeutil.h:680:17: error: result of comparison of constant \
  -9223372036854775808 with expression of type '__time_t' (aka 'long') \
  is always false [-Werror,-Wtautological-constant-out-of-range-compare]
```

This is due to the issue described in #90029.

Add workarounds for `timespec_to_timeout()` and `timespec_negate()`
until 90029 is resolved.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-05-23 14:04:53 +02:00
Chris Friedt
d61a7a80ad sys: timeutil: check for 32-bit time_t to avoid warning
A warning was propogated to error when building for
native_sim/native.

```
timeutil.h:519:17: error: result of comparison of constant \
  -9223372036854775808 with expression of type '__time_t' (aka 'long') \
  is always false [-Werror,-Wtautological-constant-out-of-range-compare]
```

This is due to the issue described in #90029.

Add workarounds for `timespec_to_timeout()` and `timespec_negate()`
until 90029 is resolved.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-05-23 09:36:41 +02:00
Chris Friedt
21b8bd1ba1 sys: timeutil: add utility functions for struct timespec
Add a number of utility functions for manipulating struct timespec.

* timespec_add()
* timespec_compare()
* timespec_equal()
* timespec_is_valid()
* timespec_negate()
* timespec_normalize()
* timespec_sub()
* timespec_from_timeout()
* timespec_to_timeout()

If the `__builtin_add_overflow()` function is available, then the
API is mostly branchless, which should provide decent performance on
systems with an instruction cache and branch prediction. Otherwise,
manually written alternatives exist that are also perhaps more
readable.

The two functions at the end convert time durations between
representation as `struct timespec` and `k_timeout_t`.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-05-22 23:57:17 +02:00
Chris Friedt
246c65bfe9 timeutil: correct position of doxygen end-group comment
swap the relative position of the __cplusplus closing
bracket and the doxygen end-group comment.

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2025-05-22 23:57:17 +02:00
Anas Nashif
2aacbcaab5 style: add missing curly braces in if/while/for statements.
Add missing curly braces in if/while/for statements.

This is a style guideline we have that was not enforced in CI. All
issues fixed here were detected by sonarqube SCA.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-05-17 14:10:33 +02:00
Daniel Nicoletti
9bbccf39cb include: zephyr: sys: Fix uuid.h usage in C++ code
In uuid.h the function uuid_generate_v5 had a 'namespace'
parameter which is a reserved C++ keywork.
Renamed to 'ns'.

Signed-off-by: Daniel Nicoletti <dantti12@gmail.com>
2025-05-06 02:36:15 +02:00
Pieter De Gendt
1a64977b1f sys: dlist: Add const qualifier to immutable API functions
Allow passing structs with sys_dlist_t members as const without
discarding qualifiers if the API is used without modifying it.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2025-05-01 08:54:04 -04:00
Pieter De Gendt
dde8067d4a sys: slist/sflist: Add const qualifier to immutable API functions
Allow passing structs with sys_slist_t/sys_sflist_t members as const
without discarding qualifiers if the API is used without modifying it.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
2025-05-01 08:54:04 -04:00
Andrej Butok
0b3e9abbff sys: ring_buffer: fix possible ring_buf_put_claim/get_claim wrong size
- The issue is caused by the MIN() macro, which expands to
  (a)<(b)?(a):(b), where ring_buf_space_get()/ring_buf_size_get()
  is used as 'b' and is evaluated twice. The issue occurs when
  the (a)<(b) condition evaluates such that (b) is selected,
  but the value of (b) changes between evaluations, resulting
  in a possibly larger value than (a).
- Fixes the potential incorrect behavior by storing the result
  of ring_buf_space_get()/ring_buf_size_get() in a variable
  before using it in the MIN macro.

Signed-off-by: Andrej Butok <andrey.butok@nxp.com>
2025-04-26 11:14:44 -04:00
Anas Nashif
a97881fd63 doc: doxygen: move usermode mutex/sem under usermode group
Move usermode mutex/semaphore under the usermode group.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-04-18 17:46:50 +02:00
Anas Nashif
3dc7291115 doc: doxygen: move notify/onoff to os_services
Those are no kernel permitives and belong under os services.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2025-04-18 17:46:50 +02:00
Théo Battrel
2158f4897d include: util: Add util_eq and util_memeq
`util_eq` compare two memory areas and their length. It returns true if
they are equal, else false.

`util_memeq` the first n bytes of two memory areas. It returns true if
they are equal, else false.

Signed-off-by: Théo Battrel <theo.battrel@nordicsemi.no>
2025-04-14 16:06:38 +02:00
JP Hutchins
fe6366b804 lib: crc: add CRC-32K/4.2
This adds the best HD=4 CRC32 polynomial. The discovery
is the result of research by Philip Koopman of Carnegie
Mellon University, and is well documented at
https://users.ece.cmu.edu/~koopman/crc/.

The user is given the option of trading 1024B of RAM to
improve the execution speed. The unit tests are parameterized
with this KConfig option.

Signed-off-by: JP Hutchins <jp@intercreate.io>
2025-04-14 09:49:02 +02:00
Simone Orru
bb39048cc2 uuid: Add UUID utilities
Add UUID generation and parsing utilities compliant
with RFC9562.

Signed-off-by: Simone Orru <simone.orru@secomind.com>
2025-04-14 09:47:26 +02:00
Hein Wessels
7d56d6a0b0 lib: os: cbprintf: add initializer for xtensa padding
Hush the compiler warning for missing initializer when compiling
for both Xtensa and C++.

Signed-off-by: Hein Wessels <heinwessels93@gmail.com>
2025-04-07 11:22:21 +02:00
Nicolas Pitre
11021cdd4f kernel: sys_heap: decouple realloc from aligned_realloc
When sys_heap_realloc() is expressed in terms of sys_heap_aligned_realloc()
it invokes a longer aligned allocation code path with an extra runtime
overhead even though no alignment is necessary.

Let's reference and invoke the aligned allocation code path only when an
actual aligned allocation is requested. This opens the possibility for
the linker to garbage-collect the aligning code otherwise.

Improve realloc documentation while at it.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-04-01 22:13:04 +02:00
Nicolas Pitre
9da06456f2 kernel: kheap: decouple simple alloc from aligned_alloc
When k_heap_alloc() is expressed in terms of k_heap_aligned_alloc()
it invokes a longer aligned allocation code path with an extra runtime
overhead even though no alignment is necessary.

Let's reference and invoke the aligned allocation code path only when an
actual aligned allocation is requested. This opens the possibility for
the linker to garbage-collect the aligning code otherwise.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-04-01 22:13:04 +02:00
Anisetti Avinash Krishna
139211772c include: zephyr: sys: time_units: Make z_clock_hw_cycles_per_sec unsigned
Convert z_clock_hw_cycles_per_sec to unsigned int to increase
supported frequency range.

Signed-off-by: Anisetti Avinash Krishna <anisetti.avinash.krishna@intel.com>
2025-03-28 12:21:07 +01:00
Anisetti Avinash Krishna
98dba7da7c include: zephyr: sys: time_units: Type cast SYS_CLOCK_HW_CYCLES_PER_SEC
Type case CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC to uint32_t
while defining sys_clock_hw_cycles_per_sec_runtime_get()
to extend the range of frequency to 0xffffffff.

Signed-off-by: Anisetti Avinash Krishna <anisetti.avinash.krishna@intel.com>
2025-03-28 12:21:07 +01:00
Krzysztof Chruściński
1ac19d3e98 sys: cbprintf: logging: Fix opaque struct pointer warning
Use compiler trick to allow operations with all types of arguments.
Previous solution was using arg+0 with suppressing compiler warning
about pointer arithmetic operations but it was not covering for
opaque struct pointers.

Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
2025-03-25 11:00:42 +01:00
Tom Hughes
15411747e7 everywhere: Use correct macro for gcc-specific warnings
Many warnings were disabled for all compilers, even though they are
gcc-specific warnings. Now that clang has -Wunknown-warning-option
enabled, this can cause compilation failures when building with clang
toolchains.

Use TOOLCHAIN_DISABLE_GCC_WARNING for all gcc-specific macros.

https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
https://clang.llvm.org/docs/DiagnosticsReference.html

Fixes: #84138

Signed-off-by: Tom Hughes <tomhughes@chromium.org>
2025-03-20 21:57:47 +01:00
Tom Hughes
11d70c61e5 everywhere: Replace diagnostic pragmas with TOOLCHAIN_* macros
The TOOLCHAIN_DISABLE_WARNING/TOOLCHAIN_ENABLE_WARNING macros are easier
to read and compiler agnostic.

Signed-off-by: Tom Hughes <tomhughes@chromium.org>
2025-03-20 21:57:47 +01:00
Anisetti Avinash Krishna
15a45e6fa8 include: zephyr: sys: time_units: Fix precision bug in z_tmcvt_32
Fixing the precedence of the cast in z_tmcvt_int_div_32 and
z_tmcvt_int_mul_32 functions so the final result is of type
uint32_t.

Fixes #87226

Signed-off-by: Anisetti Avinash Krishna <anisetti.avinash.krishna@intel.com>
2025-03-19 20:27:26 +01:00
Emil Gydesen
351805435c Revert "include: util: Add generic function to count bits set in a value"
This reverts commit d05de070db.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2025-03-18 16:39:47 +01:00
Emil Gydesen
d05de070db include: util: Add generic function to count bits set in a value
Adds a generic function that will count the number of bits set in
a value.

It uses POPCOUNT (e.g. __builtin_popcount for GCC) if available,
or else it will use Brian Kernighan’s Algorithm to count bits.

POPCOUNT will likely always support unsigned ints, but the function
was implemented to use it with uint8_t for the sake of simplicity
and compatibility with Brian Kernighan’s Algorithm.

A generic solution was chosen rather than a macro/function per
type (e.g. uint8_t, uint16_t, etc.) as that is easier to maintain
and also supports array types (e.g. counting the number of bits
in 128 or 256 octet arrays).

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2025-03-17 21:03:56 -04:00
Evgenii Kosenko
03f41eb40b include: sys: sys_heap: fix ifdef guards
Ifdef guard of CONFIG_SYS_HEAP_RUNTIME_STATS prevents using IS_ENABLED
macro, preferred way of guarding code. This commit fixes that by
removing ifdef macro.

Signed-off-by: Evgenii Kosenko <Evgenii.Kosenko@silabs.com>
2025-03-15 00:35:50 +01:00
Evgenii Kosenko
a133ef8f19 include: sys: sys_heap: fix doc generation
Documentation comments describes sys_heap_runtime_stats_get function to
have stats_t argument, hoever function has stats. The commit fixes typo
introduces in a71cd8790f

Signed-off-by: Evgenii Kosenko <Evgenii.Kosenko@silabs.com>
2025-03-15 00:35:50 +01:00
Nicolas Pitre
c7467f0c65 ring_buffer: constify some arguments
Functions that don't modify content should have pointers to it marked
const.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-03-11 08:59:05 +01:00
Nicolas Pitre
e1eead3925 ring_buffer: shrink size of struct ring_buf
Make struct ring_buf 12 bytes smaller by default. This comes with a 32KB
buffer size limit which covers almost all cases. The previous limit of
2GB can be restored with CONFIG_RING_BUFFER_LARGE=y.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-03-11 08:59:05 +01:00
Tom Hughes
a9b76dcb1b include: Re-enable warning
This warning no longer seems to be triggering, so we shouldn't disable
it.

Signed-off-by: Tom Hughes <tomhughes@chromium.org>
2025-02-19 18:51:34 +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
Joel Holdsworth
52a1db1cf3 kernel: Fixed init_delay initialization on older GCC versions
Within the K_THREAD_DEFINE macro, a nested set of macros is expanded to
populate the values of a global _static_thread_data structure.

The K_THREAD_DEFINE macro expands to statements including the
Z_THREAD_COMMON_DEFINE macro, which expands to statements including the
Z_THREAD_INITIALIZER macro, which expands to an initialization expression
of a _static_thread_data struct. The init_delay member of that struct is
then initialized with the Z_THREAD_INIT_DELAY_INITIALIZER macro, which
expands to an expression including the SYS_TIMEOUT_MS macro which
converts a number of milliseconds to a number of ticks.

For example, take the following macro:

    K_THREAD_DEFINE(
        thread_X,
        STACKSIZE,
        thread_X_entry_point, NULL, NULL, NULL,
        PRIORITY,
        0,
        0);

In abbreviated form, it expands as follows:

    typedef struct {
        int ticks;
    } k_timeout_t;

    struct _static_thread_data {
        /* ... */
        k_timeout_t init_delay;
    };

    struct _static_thread_data _k_thread_data_thread_X = {
        /* ... */
        .init_delay = (k_timeout_t){ .ticks = 0 }
    };

However, in GCC versions before 5.1, the code fails to compile with the
error "initializer element is not constant", when compiled with the
following options:

    gcc -std=gnu99 -c test.c

In the above code, the error can be corrected by replacing...

    .init_delay = (k_timeout_t){ .ticks = 0 }

...with...

    .init_delay = { .ticks = 0 }

...i.e. removing initialization with a compound literal.

In order to achieve this, this patch reworks the system of macros.

The Z_TIMEOUT_TICKS(t) macro is refactored into Z_TIMEOUT_TICKS_INIT(t)
which defines the initializer part: { .ticks = t }, and Z_TIMEOUT_TICKS(t)
which is defined as ((k_timeout_t) Z_TIMEOUT_TICKS_INIT(t)) .

For symmetry, Z_TIMEOUT_NO_WAIT_INIT is split out of Z_TIMEOUT_NO_WAIT.

Similarly, SYS_TIMEOUT_MS_INIT(ms) is split out of SYS_TIMEOUT_MS(ms) so
that the Z_THREAD_INIT_DELAY_INITIALIZER(ms) macro can use
SYS_TIMEOUT_MS_INIT(ms) which expands Z_TIMEOUT_TICKS_INIT(t) to initialize
init_delay without using a compound literal.

Signed-off-by: Joel Holdsworth <jholdsworth@nvidia.com>
2025-01-27 13:24:52 +01:00
Nicolas Pitre
3075a7d906 ring_buffer: factorize almost identical code
Factorize almost identical code. May even improve performance due to
CPU cache locality.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2025-01-25 01:40:03 +01:00
Ivan Pankratov
257d9d45ba kernel: sys_heap: stats: save heap pointers to an array during init
To request heap statistics, a pointer to a heap structure is required.
This is straightforward for a user-defined heap. However, such a pointer
is not known for heaps created by other components or libraries, like
libc. Therefore, it is not possible to calculate the total heap memory.

The proposed solution is to use an array of pointers, which is filled in
on every sys_heap_init() call. One can then iterate through it to sum up
the total memory allocated for all heaps.

The array size is configurable. The default array size is zero,
which means the feature is disabled. Any other integer greater then zero
defines the array size and enables the feature.

A list of pointers instead of an array could be another approach,
but it requeres a heap, which is not always available.

Signed-off-by: Ivan Pankratov <ivan.pankratov@silabs.com>
2025-01-23 16:37:33 +01:00
Måns Ansgariusson
c8a2a080ac kernel: Rewrite k_pipe_* API
The `k_pipe_*` API has been reworked to provide a more consistent and
intuitive interface. The new API aims to provide a simple to use byte
stream interface that is more in line with the POSIX pipe API.
The previous API has been deprecated and will be removed in a future
release.

Signed-off-by: Måns Ansgariusson <Mansgariusson@gmail.com>
2025-01-17 19:43:44 +01:00
Joakim Andersson
6a3f885408 sys: byteorder: Add endian-specific buffer convert and copy functions
Add endian specific buffer convert and copy functions.
This is helpful when you want to convert arbitrary data lengths
but only swapping byte order when needed.

Signed-off-by: Joakim Andersson <joerchan@gmail.com>
2025-01-17 13:56:33 +01:00
Patryk Duda
22d3173a61 include: zephyr: sys: Introduce IS_BIT_SET() macro
This macro is defined in a few places which leads to macro redefinition
error e.g. when compiling prometheus network sample for NPCX boards.

Provide one definition of IS_BIT_SET() in util_macro.h to fix the
problem.

Signed-off-by: Patryk Duda <patrykd@google.com>
2025-01-10 14:48:13 +01:00
Peter Mitsis
472c71d3f4 kernel: Add method to dequeue from a dlist
Dequeuing from a doubly linked list is similar to removing an item
except that it does not re-initialize the dequeued node.

This comes in handy when sorting a doubly linked list (where the
node gets removed and re-added). In that circumstance, re-initializing
the node is required. Furthermore, the compiler does not always
'understand' this. Thus, when performance is critical, dequeuing
may be preferred to removing.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2025-01-07 18:24:09 +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
Yanir Levin
d1f8e1f823 include: sys: util: Fix LOG2CEIL macro
LOG2CEIL(1) results in undefined behaviour,
as LOG2CEIL(1) expands to __builtin_clz(0),
which is undefined according to GCC docs.

Signed-off-by: Yanir Levin <yanir10@gmail.com>
2024-12-18 01:00:45 +01:00
Krzysztof Chruściński
78ba5cd61a sys: util: Extend IS_EQ to support unsigned literals
Extend IS_EQ to include unsigned integer literals like 0U.

Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
2024-12-13 20:04:33 +01:00
Trung Hieu Le
64ce567f5d include: zephyr: sys: util: Add type check for macro DIV_ROUND_CLOSEST
Add type check to avoid comparing unsigned values with 0 which is always
true or false and can cause coverity issue.

Signed-off-by: Trung Hieu Le <trunghieu.le@nxp.com>
2024-12-05 19:59:07 -05:00
Chris Friedt
9504034733 sys: util: use BITS_PER_BYTE macro instead of the magic number 8
Obviously, everyone knows that there are 8 bits per byte, so
there isn't a lot of magic happening, per se, but it's also
helpful to clearly denote where the magic number 8 is referring
to the number of bits in a byte.

Occasionally, 8 will refer to a field size or offset in a
structure, MMR, or word. Occasionally, the number 8 will refer
to the number of bytes in a 64-bit value (which should probably
be replaced with `sizeof(uint64_t)`).

For converting bits to bytes, or vice-versa, let's use
`BITS_PER_BYTE` for clarity (or other appropriate `BITS_PER_*`
macros).

Signed-off-by: Chris Friedt <cfriedt@tenstorrent.com>
2024-11-16 15:22:35 -05:00
Meir Komet
5595f66851 multi_heap: introduce support for realloc()
Add support for realloc (and realloc_aligned) into the multi heap lib,
where the buffer sent in will either be reused (maybe shrinked),
or enlarged by allocating on any of the matching heaps of the multi heap.

Signed-off-by: Meir Komet <mskomet1@gmail.com>
2024-11-16 14:02:07 -05:00