Commit graph

1698 commits

Author SHA1 Message Date
Chris Friedt
afae448ff2 posix: pthread: take care with pthread cond resources
Previously, `pthread_cond_init()` could not actually fail, and
destroying condition variables was a no-op, and it was missing
in `pthread_exit()`.

However, with the change of `pthread_cond_t` to `uint32_t`, and
since those are embedded inside of `struct posix_thread` for the
time being, the pthread code needs to keep track that it is
relinquishes used condition variables when a thread completes.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-19 14:16:38 +09:00
Chris Friedt
1777a33558 lib: posix: internal: use a more generic INIT mask and inlines
Previously `PTHREAD_MUTEX_MASK_INIT` was used to mark a
`pthread_mutex_t` as initialized.

The same needs to be done for `pthread_cond_t` and likely others.

Rather than copy-pasting that and a number of inlines that
duplicate the same functionality, simply make it more generic.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-19 14:16:38 +09:00
Chris Friedt
b0b4c9c3f1 posix: mutex: abstract pthread_mutex_t as uint32_t
Consistent with the change of `pthread_t` from
`struct posix_thread` to `uint32_t`, we can now also abstract
`pthread_mutex_t` as `uint32_t` and separate `struct posix_mutex`
as an implementation detail, hidden from POSIX API consumers.

This change deprecates `PTHREAD_MUTEX_DEFINE()` in favour of the
(standardized) `PTHREAD_MUTEX_INITIALIZER`.

This change introduces `CONFIG_MAX_PTHREAD_MUTEX_COUNT`.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-15 05:56:31 +09:00
Chris Friedt
6042acc1a9 posix: pthread: take care with pthread mutex resources
Previously, `pthread_mutex_init()` could not actually fail, and
destroying mutexes was a no-op, so it was missing in a couple of
places.

However, with the change of `pthread_mutex_t` to `uint32_t`, and
since those are embedded inside of `struct posix_thread` for the
time being, the pthread code needs to keep track that it is
relinquishes used mutex resources when a thread completes.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-15 05:56:31 +09:00
Chris Friedt
39b8b3ac8a posix: pthread_create: use spinlock for pthread_pool_lock
The `pthread_create()` function is not a cancellation point and
iterating over / mutating `posix_thread_pool` is not a blocking
operation, so use a spinlock for the internal `pthread_pool_lock`.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-08 16:10:26 -05:00
Chris Friedt
660a7db3f2 posix: pthread: use spinlock instead of mutex for cancel lock
The cancel lock will not block so a mutex is overkill.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-08 13:30:02 -05:00
Chris Friedt
4bae4f426f include: posix: move pthread impl detail to posix_internal.h
The `struct pthread` and `enum pthread_state` are actually
implementation details specific to Zephyr.

Let's limit the scope where that level of detail is visible.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-07 09:09:11 -05:00
Chris Friedt
2812f61e4e posix: pthread_once: use k_mutex for pthread_key_lock
In the interest of reducing any layering concerns,
avoid using POSIX locking primitives where necessary.

Note: it is not safe to use a spinlock here, as the
callback function to `pthread_once()` may itself be
a cancellation point.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-07 09:04:01 -05:00
Chris Friedt
ad5c3a1ae3 posix: pthread: remove duplicate assignment
The `thread` pointer variable is already assigned within the loop
above.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-07 10:16:09 +00:00
Keith Packard
d8d81c4a09 libc/picolibc: Remove unused POSIX-ish hooks
While reviewing the dependency between Picolibc POSIX APIs and Zephyr, I
found that the picolibc libc-hooks code copied a bunch of functions from
the newlib version which weren't needed. This required replacing a few
calls to the (now removed) '_write' hook with printk instead.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-11-02 06:49:32 -04:00
Chris Friedt
ce054404a2 posix: use uint32_t instead of void* for pthread_t
Several other widely-used pthread implementations
abstract `pthread_t` as `uint32_t`. The benefit
there is that we avoid passing around a pointer to
an internal structure (implementation detail).

Additionally, this removes the alias from `k_tid_t`
to `pthread_t` inside of `struct pthread_mutex`.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-11-02 15:39:44 +09:00
Kumar Gala
9be0914885 lib: os: p4wq: Convert CONFIG_MP_NUM_CPUS handling
Move runtime checks to use arch_num_cpus().  This is to allow
runtime determination of the number of CPUs in the future.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2022-10-31 17:08:34 +01:00
Chris Friedt
f5cfeae152 posix: pthread: remove duplicate assignment in pthread_exit
The `self->retval` field was assigned twice.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2022-10-31 16:58:47 +01:00
Keith Packard
25c378461e libc/picolibc: Set __LINUX_ERRNO_EXTENSIONS__ for picolibc
This makes sure extra errno values from Linux that Zephyr uses are
available.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-10-31 17:17:42 +09:00
Daniel Leung
cf23b312c3 lib: picolib: put stdio variables into libc partition
This adds the necessary modifier to the stdin/stdout/stderr
variables in picolib, and putting into the z_libc_partition.
This allows userspace applications to utilize these variables
for console I/O.

Fixes #51343

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-10-20 09:59:42 +02:00
Daniel Leung
6ee7294ac2 lib: picolib: move static to be the first modifier
Compliance check complains about static not being the first
modifier. So move them so there are no more complains
in the future.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-10-20 09:59:42 +02:00
Stephanos Ioannidis
28b22b276a lib: libc: newlib: Make newlib nano variant optional
The newlib nano variant is currently enabled by default when
`CONFIG_NEWLIB_LIBC=y` and the selected toolchain-architecture
combination includes the newlib nano variant support, even if
`CONFIG_NEWLIB_LIBC_NANO` is not selected by the user.

When `CONFIG_NEWLIB_LIBC=y`, this results in the newlib nano variant
being selected for some architectures (e.g. ARC, ARM and RISC-V), while
the full variant is selected for the rest of the architectures.

The above behaviour is problematic because there exist functional
differences between the newlib full and nano variants (e.g. C99 format
modifiers such as `hh`, `ll`, `z`, `j` and `t` are not available in the
newlib nano variant), and this effectively leads to different level of
C standard support across different architectures when
`CONFIG_NEWLIB_LIBC=y`.

This commit fixes this problem by making the `CONFIG_NEWLIB_LIBC_NANO`
not `default y` and requiring its user to explicitly set this symbol to
`y` when they want to use the newlib nano variant.

Signed-off-by: Stephanos Ioannidis <stephanos.ioannidis@nordicsemi.no>
2022-10-19 16:02:51 +02:00
Anas Nashif
a5bd666f4e lib: notify: build sys-notify conditionally.
Add a new Kconfig and build this code conditionally, so we do not end up
with this file being built for each zephyr app.

Partial fix for #50654

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-10-03 10:18:15 +02:00
Anas Nashif
a81b322828 lib: onoff: add a config for on-off and build conditionally
Do not build this service unconditionally.

Partial fix of #50654

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-10-03 10:18:15 +02:00
Piotr Pryga
e2e06a74c3 libc: minimal: Add C11 aligned_alloc
Extend capabilities of a minimal libc to support C11 capability
to allocate memory with requested alignment.

Signed-off-by: Piotr Pryga <piotr.pryga@nordicsemi.no>
2022-10-03 10:13:25 +02:00
Stephanos Ioannidis
175cc385c4 lib: picolibc: Use smaller default heap size
The picolibc heap size configuration (`CONFIG_PICOLIBC_HEAP_SIZE`) is
used to set the statically allocated malloc heap size when userspace is
enabled.

The current default heap size of 1048576 bytes (MMU) and 65536 bytes
(MPU) is too large for most platforms that Zephyr supports and may
result in the picolibc tests being filtered out due to the increased
memory footprint of the compiled image (i.e. SRAM overflow).

This commit updates the default picolibc heap size to a more reasonable
16384 bytes for MMU platforms and 1024 bytes for MPU platforms.

Signed-off-by: Stephanos Ioannidis <stephanos.ioannidis@nordicsemi.no>
2022-09-30 13:52:24 +00:00
Chris Friedt
0217c3952a posix: conditionally compile perror pthread_common and nanosleep
Previously, these files were compiled unconditionally.

Partial fix for #50654

Signed-off-by: Chris Friedt <cfriedt@fb.com>
2022-09-28 14:06:55 +00:00
Jiafei Pan
d486bd3cfe lib: libc: newlib: make sure retargetable locking is enabled in toolchain
Add build assert to make sure _RETARGETABLE_LOCKING is enabled in
toolchain, When _RETARGETABLE_LOCKING is enabled, "_LOCK_T" is "__lock"
pointer type, otherwise "_LOCK_T" is "int" type, so there will be the
following compile warnings when toolchain doesn't enable
_RETARGETABLE_LOCKING:

zephyr/lib/libc/newlib/libc-hooks.c:416:13: warning: cast to pointer from
integer of different size [-Wint-to-pointer-cast]
  416 |  k_sem_take((struct k_sem *)lock, K_FOREVER);
      |             ^
zephyr/lib/libc/newlib/libc-hooks.c: In function '__retarget_lock_acquire
_recursive':
zephyr/lib/libc/newlib/libc-hooks.c:423:15: warning: cast to pointer from
integer of different size [-Wint-to-pointer-cast]
  423 |  k_mutex_lock((struct k_mutex *)lock, K_FOREVER);
      |               ^
...

Signed-off-by: Jiafei Pan <Jiafei.Pan@nxp.com>
2022-09-21 08:59:24 +00:00
Seppo Takalo
c93b4cf307 libc: newlib: Call gettimeofday() also when CONFIG_POSIX_CLOCK
When CONFIG_POSIX_CLOCK is enabled, we should have implementation
of gettimeofday() and therefore time(NULL) should return correct
time, instead of -1.

Signed-off-by: Seppo Takalo <seppo.takalo@nordicsemi.no>
2022-09-20 08:19:23 +00:00
Krzysztof Chruscinski
a7224830ce lib: os: cbprintf: Mechanism for detecting %p in static package
Static packaging is using only argument types to build a package. There
is one case where analysing argument type only is not enough to
determine package content. That is %p with (unsigned) char pointer vs
%s. In case of %s a string might need to be appended to the package
and in case of %p it must be avoided. Format string analysis is required
to distinguish those two cases.
In order to speed up the runtime inspection, additional information is
added to a static package. That is index of the string argument (where
first argument has index 0). This information allows quick format string
inspection where nth format specifier is found and checked if it is a
pointer format specifier.
Inspection algorithm is added to cbprintf_package_convert() and if %p
is found then data for that argument is discarded. Additionally, log
warning is printed with suggestion to cast pointer argument to void *
to avoid confusion. It is desired to get rid of this ambiguity because
there are going to be logging configurations where strings are stripped
from a binary and runtime inspection cannot be performed.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-09-19 10:14:23 +00:00
Gerard Marull-Paretas
79e6b0e0f6 includes: prefer <zephyr/kernel.h> over <zephyr/zephyr.h>
As of today <zephyr/zephyr.h> is 100% equivalent to <zephyr/kernel.h>.
This patch proposes to then include <zephyr/kernel.h> instead of
<zephyr/zephyr.h> since it is more clear that you are including the
Kernel APIs and (probably) nothing else. <zephyr/zephyr.h> sounds like a
catch-all header that may be confusing. Most applications need to
include a bunch of other things to compile, e.g. driver headers or
subsystem headers like BT, logging, etc.

The idea of a catch-all header in Zephyr is probably not feasible
anyway. Reason is that Zephyr is not a library, like it could be for
example `libpython`. Zephyr provides many utilities nowadays: a kernel,
drivers, subsystems, etc and things will likely grow. A catch-all header
would be massive, difficult to keep up-to-date. It is also likely that
an application will only build a small subset. Note that subsystem-level
headers may use a catch-all approach to make things easier, though.

NOTE: This patch is **NOT** removing the header, just removing its usage
in-tree. I'd advocate for its deprecation (add a #warning on it), but I
understand many people will have concerns.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-09-05 16:31:47 +02:00
Christopher Friedt
a5ee862ff0 posix: clock: make tz non-const in gettimeofday
This `tz` field is not const in the spec.

Signed-off-by: Christopher Friedt <cfriedt@fb.com>
2022-09-03 04:00:37 -04:00
Krzysztof Chruscinski
bb74b4f028 lib: os: cbprintf: Renamed flags used for conversion function
At some point, package copy function was extended and renamed
to cbprintf_package_convert. However, flags used by this
function were not renamed and used contained COPY idiom.
Deprecating flags with COPY and replacing them with flags
with CONVERT idiom to match function which is utilizing them.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-08-26 12:52:08 +02:00
Krzysztof Chruscinski
7303ac135d lib: os: spsc_pbuf: Minor code cleanup
Minor cleanup in allocation function. Using define instead of
sizeof(uint32_t) to better explain the purpose. Adding few
comments.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-08-24 17:48:50 +00:00
Krzysztof Chruscinski
6928c4a546 lib: os: spsc_pbuf: Fix race condition
Allocator is adding padding in 2 steps. First padding mark is written
to the buffer and then write index is reset to 0. Consumer may interrupt
this operation (another thread or core) and fail since it was only checking
padding marker and that alone was enough to consume the padding. If that
happen before write index got updated, buffer reading become corrupted.
Fixing it by adding write index check when padding is found.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-08-24 17:48:50 +00:00
Krzysztof Chruscinski
4b5ff413f5 lib: os: spsc_pbuf: Fix miscalculation in the allocation
Wrong value was used for free space calculation. Updating test which
previously was hiding this bug.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-08-24 17:48:50 +00:00
Andrei Emeltchenko
6f831d542a posix: getopt: Set variable only if used
Only assign dash_prefix when PRINT_ERROR true.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-08-19 12:07:45 +02:00
Andy Ross
02b23f3733 arch/posix: Add MemorySanitizer support
Wire this up the same way ASAN works.  Right now it's support only by
recent clang versions (not gcc), and only in 64 bit mode.  But it's
capable of detecting uninitialized data reads, which ASAN is not.

This support is wired into the sys_heap (and thus k_heap/k_malloc)
layers, allowing detection of heap misuse like use-after-free.  Note
that there is one false negative lurking: due to complexity, in the
case where a sys_heap_realloc() call is able to shrink memory in
place, the now-unused suffix is not marked uninitialized immediately,
making it impossible to detect use-after-free of those particular
bytes.  But the system will recover cleanly the next time the memory
gets allocated.

Also no attempt was made to integrate this handling into the newlib or
picolibc allocators, though that should hopefully be possible via
similar means.

Signed-off-by: Andy Ross <andyross@google.com>
2022-08-19 08:30:01 +02:00
Stephanos Ioannidis
e918783af1 lib: libc: minimal: Define off_t as intptr_t
The `off_t` type, which is specified by the POSIX standard as a signed
integer type representing file sizes, was defined as `long` or `int`
depending on the target architecture without a clear explanation on why
it was defined as such.

While the POSIX standard does not specify the size requirement of the
`off_t` type, it generally corresponds to the size of a pointer in
practice, mainly because the optimal file handling size is closely tied
to the native pointer size.

For this reason, this commit removes the per-architecture `off_t`
definition and defines it as `intptr_t` such that its size always
matches the native pointer size.

Note that the toolchain-defined `__INTPTR_TYPE__` macro is used instead
of the `intptr_t` typedef as per the common convention used in the C
standard library headers.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-08-19 02:47:50 +09:00
Daniel Leung
7dc20978e3 lib: os: cbprintf: fix typo exteral -> external
The cbprintf formatter cbvprintf_exteral_formatter_func has a typo
in it with a missing 'n'. So add it.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-08-17 08:08:46 +00:00
Evgeniy Paltsev
a8a4fec2b1 teslibct: don't allow picolib tests for ARC MWDT toolchain
Currently picolib isn't compatible with ARC MWDT toolchain,
so don't try to build picolib tests in case of ARC MWDT toolchain
usage.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2022-08-16 08:23:22 +00:00
Keith Packard
8865d4d7db picolibc: Don't select TLS without toolchain support
If the architecture has TLS support, but the toolchain doesn't, then
don't enable Zephyr TLS support when selecting picolibc.

Closes: #47275.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-08-11 12:20:20 +02:00
Keith Packard
f0216a2619 libc/picolibc: Place malloc heap in noinit section if possible
When the heap is of a fixed size and there isn't a special malloc partition
in use, place the heap in uninitialized memory so that the application
doesn't spend time at startup erasing it. Picolibc malloc always clears
memory before returning it to applications, so this change will not be
visible to applications.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-08-11 12:20:05 +02:00
Enjia Mai
e696de1f31 lib: os: disable PRINTK_SYNC while using EFI console as log backend
There is a spinlock used in the EFI console code for printing
one line string. It already made the log output being in order
under multi-cores, so it doesn't need a printk sync spinlock
again. Disable it while using EFI console as a log backend.

Fixes #47512.

Signed-off-by: Enjia Mai <enjia.mai@intel.com>
2022-08-11 12:17:24 +02:00
Krzysztof Chruscinski
09b41829a8 lib: os: spsc_pbuf: Fix free space calculation
Fixing bug in free space calculation which was assuming 1 byte
padding and not 32 bit word padding. Bug could result in the
data corruption in certain scenario.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-08-02 08:13:31 -04:00
Flavio Ceolin
dfa71ca332 lib: os: Fix warning on XCC
xcc compiler complains about how fdtable variable is initialized:
"""
warning: missing braces around initialize
"""

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2022-07-25 17:07:11 -04:00
Krzysztof Chruscinski
b6dcdb17f9 lib: os: spsc_pbuf: Improve data cache configuration
Use CONFIG_DCACHE_LINE_SIZE to determine distance between
fields modified by different cores.
Add option which specifies what is the data cache line
of the remote core. Maximum from local and remote cache
line sizes is used as distance and alignement.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-07-18 12:21:16 -04:00
Tomislav Milkovic
0fe2c1fe90 everywhere: Fix legacy include paths
Any project with Kconfig option CONFIG_LEGACY_INCLUDE_PATH set to n
couldn't be built because some files were missing zephyr/ prefix in
includes
Re-run the migrate_includes.py script to fix all legacy include paths

Signed-off-by: Tomislav Milkovic <milkovic@byte-lab.com>
2022-07-18 16:16:47 +00:00
Marcin Szkudlinski
e4d11fe177 lib: mem_blocks: add a usage test for a block
add a sys_mem_blocks_is_region_free procedure to test
if the block in question is free or taken

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
Signed-off-by: Tomasz Leman <tomasz.m.leman@intel.com>
2022-07-14 10:44:18 +02:00
Peter Mitsis
3b7818b2d2 lib/os: use generic mem stats structure for heap
Since the retrieved heap memory statistics are identical to those of
the retrieved mem_block statistics, it makes sense to use a single
generic-named structure for both instead of two identical structures
with different names.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-07-12 13:59:26 +00:00
Peter Mitsis
d061366f54 lib/os: add statistics tracking to mem_blocks
Both the current and maximum number of allocations in a given memory
blocked are tracked (and can be queried) when the
CONFIG_SYS_MEM_BLOCKS_RUNTIME_STATS Kconfig option is selected.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-07-12 13:59:26 +00:00
Christopher Friedt
da0398d198 posix: pthread: consider PTHREAD_EXITED state in pthread_create
If a thread is joined using `pthread_join()`, then the
internal state would be set to `PTHREAD_EXITED`.

Previously, `pthread_create()` would only consider pthreads
with internal state `PTHREAD_TERMINATED` as candidates for new
threads. However, that causes a descriptor leak.

We should be able to reuse a single thread an infinite number
of times.

Here, we also consider threads with internal state
`PTHREAD_EXITED` as candiates in `pthread_create()`.

Fixes #47609

Signed-off-by: Christopher Friedt <cfriedt@fb.com>
2022-07-12 10:16:02 +02:00
Anas Nashif
4f65bf6412 scripts: move gen_strerror_table.py to scripts/build
Move scripts needed by the build system and not designed to be run
individually or standalone into the build subfolder.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-07-12 10:03:45 +02:00
Alexander Dengg
21aa4a9a86 lib: open-amp: support resource table on C++ applications
In C++ applications, methods which are meant to be implemented in C
should be wrapped in a `extern "C"` scope at the point of declaration.
This enables the correct symbol table mangling, which fixes current
linker errors in C++.

Signed-off-by: Alexander Dengg <dornbirndevelops@gmail.com>
2022-07-06 10:56:01 -05:00
Anas Nashif
65337bc7eb lib: add mising braces to single line if statements
Following zephyr's style guideline, all if statements, including single
line statements shall have braces.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-07-06 11:00:45 -04:00
Stephanos Ioannidis
b8d4a31abd lib: libc: picolibc: Initialise libc heap during POST_KERNEL phase
This commit changes the invocation of the picolibc malloc heap
initialisation function such that it is executed during the POST_KERNEL
phase instead of the APPLICATION phase.

This is necessary in order to ensure that the application
initialisation functions (i.e. the functions called during the
APPLICATIION phase) can make use of the libc heap.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-07-06 10:46:39 +02:00
Stephanos Ioannidis
43e1c28a25 lib: libc: newlib: Initialise libc heap during POST_KERNEL phase
This commit changes the invocation of the newlib malloc heap
initialisation function such that it is executed during the POST_KERNEL
phase instead of the APPLICATION phase.

This is necessary in order to ensure that the application
initialisation functions (i.e. the functions called during the
APPLICATIION phase) can make use of the libc heap.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-07-06 10:46:39 +02:00
Stephanos Ioannidis
db0748c462 lib: libc: minimal: Initialise libc heap during POST_KERNEL phase
This commit changes the invocation of the minimal libc malloc
initialisation function such that it is executed during the POST_KERNEL
phase instead of the APPLICATION phase.

This is necessary in order to ensure that the application
initialisation functions (i.e. the functions called during the
APPLICATIION phase) can make use of the libc heap.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-07-06 10:46:39 +02:00
Christopher Friedt
b391993d1b lib: posix: add perror() implementation
Add a trivial implementation of `perror()`.

Fixes #46100

Signed-off-by: Christopher Friedt <cfriedt@fb.com>
2022-07-04 22:53:36 +02:00
Christopher Friedt
4cc443705d libc: minimal: add strerror and strerror_r function
Add simple strerror() and strerror_r() implementations.

Fixes #46099

Signed-off-by: Christopher Friedt <cfriedt@fb.com>
2022-07-04 22:53:36 +02:00
Emil Gydesen
de4b564754 zephyr: Fix n=0 for utf8_lcpy
The function used an assert if n was 0. Instead
of using an assert, the function will now just
not do anything. The documentation has also
been updated to reflect this.

The reasoning for this is that the strlcpy function
this (sort of) implements for utf8 works the same way.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2022-07-04 15:49:22 +02:00
Abramo Bagnara
8521b43546 coding guidelines: comply with MISRA C:2012 Rule 21.13
MISRA C:2012 Rule 21.13 (Any value passed to a function in <ctype.h>
shall be representable as an unsigned char or be the value EOF).

Functions in <ctype.h> have undefined behavior if they are called with
any other value. Callers affected by this change are not prepared to
handle EOF anyway. The addition of these casts avoids the issue
and does not result in any performance penalty.

Signed-off-by: Abramo Bagnara <abramo.bagnara@bugseng.com>
Signed-off-by: Simon Hein <SHein@baumer.com>
2022-06-30 17:34:28 -04:00
Abramo Bagnara
795500bbe3 coding guidelines: comply with MISRA C:2012 Rule 9.3
MISRA C:2012 Rule 9.3 (Arrays shall not be partially initialized.)

Systematically use `{0}' to specify full 0 initialization
(not `{}', not `{0U}').

Signed-off-by: Abramo Bagnara <abramo.bagnara@bugseng.com>
Signed-off-by: Simon Hein <SHein@baumer.com>
2022-06-30 17:34:05 -04:00
Keith Packard
bc234fb1af libc/picolibc: Rework malloc arena setup
Picolibc inherited its malloc arena configuration from newlib instead of
from minimal libc. This ended up making it a bit too fragile to run the
full set of zephyr tests. In particular:

 * Z_MALLOC_PARTITION_EXISTS would get set when not used

 * Setting an arena size depended on a bunch of other values, including
   whether the system had an MMU or MPU, and whether the MPU required
   power-of-two alignment or not.

This patch cleans things up so that there is a single heap size specifier,
PICOLIBC_HEAP_SIZE.

 * If PICOLIBC_HEAP_SIZE is positive, this sets the size of the heap. On
   MMU systems, picolibc will only use the remaining memory if that's
   smaller.

 * If PICOLIBC_HEAP_SIZE is zero, then there is no heap available and
   malloc will always fail. This also disables Z_MALLOC_PARTITION_EXISTS.

 * If PICOLIBC_HEAP_SIZE is negative, then picolibc uses all remaining
   memory for the malloc heap.

The defaults are designed to allow tests to work without requiring
additional settings.

 * For MMU enabled systems, the default value is 1048576. It would be nice
   to have this use 'all available memory', but that's difficult to manage
   as the API which returns free memory (k_mem_free_get) doesn't take into
   account the amount of free virtual address space.

 * For MPU enabled systems which require power-of-two aligned MPU regions,
   the default value is 64kB.

 * For other systems, the default value is -1, indicating that all
   available memory be used for the malloc arena.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-30 10:33:24 +02:00
Krzysztof Chruscinski
715ae32501 lib: os: spsc_pbuf: Add option to get maximum utilization
Add option to track maximum utilization of the packet buffer.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-30 10:30:49 +02:00
Krzysztof Chruscinski
fa055f743f lib: os: spsc_pbuf: Extend API with zero copy model
Added functions which allow to use zero copy model for handling
data within the packet buffer.

Additionally, added handling of cache by adding option to keep rd_idx
in different cache line than wr_idx and data.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-30 10:30:49 +02:00
Keith Packard
866f1cb9b0 lib/cbprintf: Disable tagged arguments with picolibc
Picolibc doesn't have the non-standard printf support required for tagged
arguments in cbprintf. Disable this and use the format string parsing code
instead.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-29 10:29:13 +02:00
Keith Packard
2d20faab47 lib/os: Replace cbvprintf and printfcb family when using picolibc
Picolibc already provides the functionality offered by cbprintf, so
there's no reason to use the larger and less functional version included
in zephyr.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-27 12:47:25 +02:00
Keith Packard
d90fa562b2 lib/printk: Use picolibc's vfprintf instead of cbvprintf
When using picolibc, change vprintk to use picolibc's vfprintf instead of
cbvprintf.

Building samples/hello-world for qemu-cortex-m3.

old:

Memory region         Used Size  Region Size  %age Used
           FLASH:        9056 B       256 KB      3.45%
            SRAM:        3960 B        64 KB      6.04%
        IDT_LIST:          0 GB         2 KB      0.00%

new:

Memory region         Used Size  Region Size  %age Used
           FLASH:        7900 B       256 KB      3.01%
            SRAM:        3960 B        64 KB      6.04%
        IDT_LIST:          0 GB         2 KB      0.00%

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-24 20:30:03 +02:00
Keith Packard
d465dbba6d lib/printk: Removed unused 'count' field in printk context
There's no use of the 'count' field of the context, so remove it. Because
that's the only member of struct out_context, remove the whole struct.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-24 20:30:03 +02:00
Keith Packard
ecee708e4b lib/printk: Use picolibc's snprintf/vsnprintf for snprintk/vsnprintk
Replace wrapper functions that use cbprintf with direct calls to picolibc
stdio functions.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-24 20:30:03 +02:00
Christopher Friedt
9d433c89a2 lib: posix: semaphore: use consistent timebase in sem_timedwait
In the Zephyr implementation, `sem_timedwait()` uses a
potentially wildly different timebase for comparison via
`k_uptime_get()` (uptime in ms).

The standard specifies `CLOCK_REALTIME`. However, the real-time
clock can be modified to an arbitrary value via clock_settime()
and there is no guarantee that it will always reflect uptime.

This change ensures that `sem_timedwait()` uses a more
consistent timebase for comparison.

Fixes #46807

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2022-06-24 20:12:05 +02:00
Andrei Emeltchenko
edc98394b1 lib: os: Remove unneeded assignment
Remove assignment since it is duplicated at the end of do-while
loop.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-23 15:43:59 -05:00
Keith Packard
0984aedf68 libc/picolibc: When !TLS, use zephyr errno
For targets without thread local storage, we need to use the builtin
per-thread errno support provided by Zephyr as the multi-thread errno
support provided in picolibc relies on TLS.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-23 09:16:32 +02:00
Abramo Bagnara
d1d5acd2cd coding guidelines: comply with MISRA C:2012 Rule 8.2
MISRA C:2012 Rule 8.2 (Function types shall be in prototype form with
named parameters.)

Added missing parameter names.

Signed-off-by: Abramo Bagnara <abramo.bagnara@bugseng.com>
2022-06-22 17:17:39 -04:00
Keith Packard
d0c75f3b96 lib/libc: Add picolibc support (aarch32, aarch64 and RISC-V) [v21]
Picolibc is a fork of newlib designed and tested on embedded systems. It
offers a smaller memory footprint (both ROM and RAM), and native TLS
support, which uses the Zephyr TLS support.

By default, the full printf version is included in the executable, which
includes exact floating point and long long input and output. A
configuration option has been added to switch to the integer-only
version (which also omits long long support).

Here are some size comparisons using qemu-cortex-m3 and this application
(parameters passed to printf to avoid GCC optimizing it into puts):

void main(void)
{
    printf("Hello World! %s %d\n", CONFIG_BOARD, 12);
}

                       FLASH    SRAM
    minimal             8696    3952
    picolibc int        7600    3960
    picolibc float     12304    3960
    newlib-nano int    11696    4128
    newlib-nano float  30516    4496
    newlib             34800    6112

---

v2:
	Include picolibc-tls.ld

v3:
	Document usage in guides/c_library.rst and
	getting_started/toolchain_other_x_compilers.rst

v4:
	Lost the lib/libc/picolibc directory somehow!

v5:
	Add PICOLIBC_ALIGNED_HEAP_SIZE configuration option.
	Delete PICOLIBC_SEMIHOST option support code

v6:
	Don't allocate static RAM for TLS values; TLS
	values only need to be allocated for each thread.

v7:
	Use arm coprocessor for TLS pointer storage where supported for
	compatibility with the -mtp=cp15 compiler option (or when the
	target cpu type selects this option)

	Add a bunch of tests

	Round TLS segment up to stack alignment so that overall stack
	remains correctly aligned

	Add aarch64 support

	Rebase to upstream head

v8:
	Share NEWLIB, NEWLIB_NANO and PICOLIBC library configuration
	variables in a single LIBC_PARTITIONS variable instead of
	having separate PICOLIBC_PART and NEWLIB_PART variables.

v9:
	Update docs to reference pending sdk-ng support for picolibc

v10:
	Support memory protection by creating a partition for
	picolibc shared data and any pre-defined picolibc heap.

v11:
	Fix formatting in arch/arm/core/aarch64/switch.S

v12:
	Remove TLS support from this patch now that TLS is upstream
	Require THREAD_LOCAL_STORAGE when using PICOLIBC for architectures
	that support it.

v13:
	Merge errno changes as they're only needed for picolibc.
	Adapt cmake changes suggested by Torsten Tejlmand Rasmussen

v14:
	Update to picolibc 1.7 and newer (new stdin/stdout/stderr ABI)

v15:
	Respond to comments from dcpleung:
	* switch kernel/errno to use CONFIG_LIBC_ERRNO instead of
          CONFIG_PICOLIBC
	* Add comment to test/lib/sprintf as to why the %n test
	  was disabled for picolibc.

v16:
	Switch picolibc to a module built with Zephyr. This eliminates
	toolchain dependencies and allows compiler settings for Zephyr
	to also be applied to picolibc.

v17:
	Provide Zephyr-specific 'abort' implementation.
	Support systems with MMU

v18:
	Allow use of toolchain picolibc version.

v19:
	Use zephyr/ for zephyr headers

v20:
	Add locking
	Use explicit commit for picolibc module

v21:
	Create PICOLIBC_SUPPORTED config param. Set on arc, arm, arm64,
	mips and riscv architectures.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-22 13:15:55 +02:00
Kai Vehmanen
7f6b762a73 lib/os: winstream: properly include string.h for memcpy
If system memcpy() is used, assert.h must be included. Fixes
a build warning on undeclared use of memcpy.

Signed-off-by: Kai Vehmanen <kai.vehmanen@linux.intel.com>
2022-06-21 14:02:13 -04:00
Abramo Bagnara
ada9ca4c93 coding guidelines: comply with MISRA C:2012 Rule 7.2
MISRA C:2012 Rule 7.2 (A `u' or `U' suffix shall be applied to all
integer constants that are represented in an unsigned type)

Added missing `U' suffixes in constants that are involved in the
analyzed build, plus a few more not to introduce inconsistencies
with respect to nearby constants that are either unused in the
build (but implicitly unsigned) or are used and are immediately
converted to unsigned.

Signed-off-by: Abramo Bagnara <abramo.bagnara@bugseng.com>
2022-06-14 13:36:14 -04:00
Keith Packard
11267a30a1 lib/os/cbprintf: Use signed char for %hhd format
The cast to narrow for %hhd support must be 'signed char' instead of 'char'
to support targets where 'char' is unsigned, as on riscv.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-09 11:32:58 +02:00
Krzysztof Chruscinski
0829610bbc lib: os: spsc_pbuf: Add option to use cache
Add flags option to init call and a flag to use cache.
Add Kconfig choice to pick how to approach cache. Cache can be
enforced in all spsc_pbuf instances, disable in all, or runtime selected
based on configuration flag. Option is added to allow memory footprint
savings.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-07 19:04:35 +02:00
Krzysztof Chruscinski
2f189e39a5 lib: os: Rename icmsg_buf to spsc_pbuf
Move icmsg_buf to lib/os and rename to spsc_pbuf (Single Producer
Single Consumer Packet Buffer). It is a generic module and initially
was created as internal module for ipc service.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-07 19:04:35 +02:00
Daniel Leung
aff6e8b2f7 lib: os: cbprint: enable tagged arguments for packaging
This adds some bits to support tagged arguments to be used for
packaging. If enabled, the packaging function no longer looks at
the format strings to determine the types of arguments, but
instead, each argument is tagged with a type by preceding it
with another argument as type (integer). This allows the format
strings to be removed from the final binary to conserve space.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-06-08 00:15:55 +09:00
Andrei Emeltchenko
29128bfa02 lib: mpsc_pbuf: Fix compilation unused-but-set-variable warning
Use ARG_UNUSED() to fix compilation warnings.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-06 22:47:11 +02:00
Andrei Emeltchenko
3cf5c3c33c lib: ring_buf: Make code consistent
Make code easier to read by using the same name for error code.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-06 22:46:43 +02:00
Andrei Emeltchenko
e63eedce51 lib: ring_buf: Fix unused-but-set compilation warnings
For the error codes used only in __ASSERT() statements fix compilation
warnings like:

...
warning: variable 'err' set but not used [-Wunused-but-set-variable]
        int err;
            ^
...

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-06 22:46:43 +02:00
Andrei Emeltchenko
14b6f491cb lib: bitarray: Remove dead statement
Remove dead code since we go out of the loop after break statement.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-06 22:46:37 +02:00
Juha Heiskanen
ec1c85b385 lib: os: Extend Json library API and type update
New Types:
* Added support for Generic Numeric type (float, 64-bit)
* Added support for Opaque string type.
* Added support parse Array data in object for seprate array parsing
New API for Json Array parsing Object 1 by 1:
* json_arr_separate_object_parse_init() init array parse
* json_arr_separate_parse_object() Parsing 1 Json Object
Rename token and lexer structures and publish those.

Signed-off-by: Juha Heiskanen <juha.heiskanen@nordicsemi.no>
2022-06-06 12:06:43 +02:00
Andrei Emeltchenko
c62a380843 lib: os: Fix unused variable set warning
Fixes following warning during compilation with llvm:

...
lib/os/mpsc_pbuf.c:428:8: warning: variable 'wrap' set but not used
  [-Wunused-but-set-variable]
        bool wrap;
             ^
1 warning generated.
...

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-05 14:49:45 +02:00
Andrei Emeltchenko
0c934e22d1 lib: rb: Remove unneeded statement
Remove unneeded statement since it is done in the beginning of the
loop.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-05 14:49:37 +02:00
Andrei Emeltchenko
3074b5808e libc: sqrtf: Remove dead assignment
Remove dead assignment from sqrtf().

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2022-06-05 14:49:31 +02:00
Stephanos Ioannidis
eb710039c0 libc: minimal: Fix gmtime() userspace support
The gmtime() function returns a global result variable, and this
variable must be placed in the `z_libc_partition` when userspace is
enabled.

Since gmtime() makes use of a global variable and this results in a
footprint increase, this commit makes the time functions optional by
introducing `CONFIG_MINIMAL_LIBC_TIME` Kconfig and making them only
available when this option is enabled.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-06-01 11:03:38 +02:00
Stephanos Ioannidis
2bcb713371 libc: Define Z_LIBC_DATA macro globally
This commit globally defines the `Z_LIBC_DATA` macro, which is used to
place variables into the libc memory partition, so that it can be
re-used.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-06-01 11:03:38 +02:00
Stephanos Ioannidis
4735e10630 libc: minimal: Introduce CONFIG_MINIMAL_LIBC_NON_REENTRANT_FUNCTIONS
This commit introduces a new configuration called
`CONFIG_MINIMAL_LIBC_NON_REENTRANT_FUNCTIONS`, which enables the
traditional non-reentrant (i.e. not thread-safe) version of the C
standard library functions such as rand() and gmtime() when the
respective configs are enabled.

The non-reentrant functions make use of the globals and require an
additional memory partition (MPU region), which is scarce on low-end
devices, when CONFIG_USERSPACE=y.

The purpose of this option is to classify the MPU resource intensive
functions as a separate category and only enable them when there is a
demand for such.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-06-01 11:03:38 +02:00
Stephanos Ioannidis
b290926a99 libc: minimal: Add reentrant rand_r function
This commit adds the `rand_r` function, which is a reentrant (i.e.
thread-safe) version of the `rand` function, such that a thread-safe
variant is always available.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-06-01 11:03:38 +02:00
Stephanos Ioannidis
d755050a14 libc: minimal: Add PRIxMAX macros for [u]intmax_t
This commit adds the missing `PRIxMAX` macros for the C99 `intmax_t`
and `uintmax_t` types:

  PRIdMAX, PRIiMAX, PRIoMAX, PRIuMAX, PRIxMAX, PRIXMAX

Note that the `PRIxMAX` macros specify the `ll` size modifier because
the type of the `intmax_t` for the minimal libc is defined as that of
the `int64_t`, which is always overridden to `long long int` by
`zephyr_stdint.h`; for more details, refer to the GitHub PR #29876,
which deliberately introduced this scheme.

In the future, this scheme will need to be reworked such that the
minimal libc `stdint.h` defines `intmax_t` as `__INTMAX_TYPE__`, and
the `inttypes.h` resolves the corresponding format specifier.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-26 17:38:50 +02:00
Stephanos Ioannidis
c3f80aa844 libc: minimal: Add PRIx{FAST,LEAST}N macros
This commit adds the missing `PRIx{FAST,LEAST}N` C99 integer type
format macros that correspond to the C99 integer types overridden in
the `zephyr_stdint.h` header:

  PRIdFAST8, PRIdFAST16, PRIdFAST32, PRIdFAST64
  PRIdLEAST8, PRIdLEAST16, PRIdLEAST32, PRIdLEAST64

  PRIiFAST8, PRIiFAST16, PRIiFAST32, PRIiFAST64
  PRIiLEAST8, PRIiLEAST16, PRIiLEAST32, PRIiLEAST64

  PRIoFAST8, PRIoFAST16, PRIoFAST32, PRIoFAST64
  PRIoLEAST8, PRIoLEAST16, PRIoLEAST32, PRIoLEAST64

  PRIuFAST8, PRIuFAST16, PRIuFAST32, PRIuFAST64
  PRIuLEAST8, PRIuLEAST16, PRIuLEAST32, PRIuLEAST64

  PRIxFAST8, PRIxFAST16, PRIxFAST32, PRIxFAST64
  PRIxLEAST8, PRIxLEAST16, PRIxLEAST32, PRIxLEAST64

  PRIXFAST8, PRIXFAST16, PRIXFAST32, PRIXFAST64
  PRIXLEAST8, PRIXLEAST16, PRIXLEAST32, PRIXLEAST64

Note that these macros will eventually need to be defined according to
the toolchain-specified types when the `zephyr_stdint.h` hack is
removed in the future; refer to the the GitHub issue #46032 for more
details.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-26 17:38:50 +02:00
Stephanos Ioannidis
c2db0c5a86 libc: minimal: Add strstr implementation
This commit adds the strstr function implementation that is licensed
BSD-3-Clause, which is an OSI-approved license, with the modifications
necessary for adoption into the Zephyr minimal C library.

Note that this implementation is based on the size optimised version of
the newlib strcasestr function.

Origin: Newlib
License: BSD 3-Clause
URL: git://sourceware.org/git/newlib-cygwin.git
Commit: 9087163804df8af6dc2ec1f675a2341c25f7795f
Purpose: strstr function support in the minimal C library

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
8c086d5791 libc: minimal: Remove incompatibly licensed strstr function
This commit removes the strstr function implementation that is
licensed BSD-4-Clause-UC, which is not an OSI-approved license.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
c96f15ecf3 libc: minimal: Add strtoull implementation
This commit adds the strtoull function implementation that is licensed
BSD-3-Clause, which is an OSI-approved license, with the modifications
necessary for adoption into the Zephyr minimal C library.

Origin: Newlib
License: BSD 3-Clause
URL: git://sourceware.org/git/newlib-cygwin.git
Commit: 9042d0ce65533a26fc3264206db5828d5692332c
Purpose: strtoull function support in the minimal C library

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
c6b75cd4cd libc: minimal: Remove incompatibly licensed strtoull function
This commit removes the strtoull function implementation that is
licensed BSD-4-Clause-UC, which is not an OSI-approved license.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
25b903cec1 libc: minimal: Add strtoll implementation
This commit adds the strtoll function implementation that is licensed
BSD-3-Clause, which is an OSI-approved license, with the modifications
necessary for adoption into the Zephyr minimal C library.

Origin: Newlib
License: BSD 3-Clause
URL: git://sourceware.org/git/newlib-cygwin.git
Commit: 9042d0ce65533a26fc3264206db5828d5692332c
Purpose: strtoll function support in the minimal C library

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
570ed08221 libc: minimal: Remove incompatibly licensed strtoll function
This commit removes the strtoll function implementation that is
licensed BSD-4-Clause-UC, which is not an OSI-approved license.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
4c78607618 libc: minimal: Add strtoul implementation
This commit adds the strtoul function implementation that is licensed
BSD-3-Clause, which is an OSI-approved license, with the modifications
necessary for adoption into the Zephyr minimal C library.

Origin: Newlib
License: BSD 3-Clause
URL: git://sourceware.org/git/newlib-cygwin.git
Commit: 9042d0ce65533a26fc3264206db5828d5692332c
Purpose: strtoul function support in the minimal C library

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
b6b1edbf91 libc: minimal: Remove incompatibly licensed strtoul function
This commit removes the strtoul function implementation that is
licensed BSD-4-Clause-UC, which is not an OSI-approved license.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
f1563751b3 libc: minimal: Add strtol implementation
This commit adds the strtol function implementation that is licensed
BSD-3-Clause, which is an OSI-approved license, with the modifications
necessary for adoption into the Zephyr minimal C library.

Origin: Newlib
License: BSD 3-Clause
URL: git://sourceware.org/git/newlib-cygwin.git
Commit: 9042d0ce65533a26fc3264206db5828d5692332c
Purpose: strtol function support in the minimal C library

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Stephanos Ioannidis
35caf38ce7 libc: minimal: Remove incompatibly licensed strtol function
This commit removes the strtol function implementation that is
licensed BSD-4-Clause-UC, which is not an OSI-approved license.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-05-25 14:52:29 +02:00
Tomislav Milkovic
3df84e6d55 lib: smf: fix include
Change include to angle brackets
Add zephyr/ prefix to include

Signed-off-by: Tomislav Milkovic <milkovic@byte-lab.com>
2022-05-25 11:14:18 +09:00
Anas Nashif
e5471a253e p4wq: register log module with default log level
Set default log level while registering p4wq as a log module.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-05-17 20:39:25 -04:00
Keith Packard
05946ed9b2 lib/libc/minimal: Move sqrt/sqrtf from samples
The lmp90100_evb sample included an implementation of double sqrt, and the
on_off_level_lighting_vnd_app sample included an implementation of float
sqrtf. Move that code into minimal libc instead of requiring applications
to hand-roll their own version.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-05-14 08:49:36 +09:00
Rico Ganahl
5cf1193902 lib/posix/fs: fix end-of-dir in readdir
POSIX readdir should return NULL if end of dir is reached and
leave errno untouched.

Signed-off-by: Rico Ganahl <rico.ganahl@bytesatwork.ch>
2022-05-13 11:10:04 -07:00
Matt Campbell
2d937f0683 lib: os: mpsc_pbuf: null check notify_drop callback
Allow the user of a mpsc_pbuf to not use the notify_drop callback by
setting it to NULL.

signed-off-by: Matt Campbell <matt@silvertree.io>
2022-05-10 18:32:26 +02:00
Gerard Marull-Paretas
cbd31d720b lib: migrate includes to <zephyr/...>
In order to bring consistency in-tree, migrate all lib code to the new
prefix <zephyr/...>. Note that the conversion has been scripted, refer
to zephyrproject-rtos#45388 for more details.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-05-06 19:58:09 +02:00
Krzysztof Chruscinski
4b4c5bfcee lib: os: cbprintf: Fix variable assignment
When in_len is 0 then length is calculated from the package and
assignment was missing.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-05-05 14:29:26 -05:00
Krzysztof Chruscinski
07322b85c9 lib: os: cbprintf: Add function for converting package
Extend package copying functionality by adding function for converting
a package. Function gets callback+context pair and converted package
is part by part passed to that callback. Contrary to typical sprintf
callback which works on chars, callback works with buffers.

Existing cbprintf_package_copy function is implemented as static
inline and uses new cbprintf_package_convert API.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-05-04 18:56:55 -04:00
Guennadi Liakhovetski
462bd8abc2 sparse: fix all errors
sparse complains about cbprintf incompatible callback type and
incorrect size of struct __va_list. Add exceptions to silence those
errors.

Signed-off-by: Guennadi Liakhovetski <guennadi.liakhovetski@linux.intel.com>
2022-04-28 08:54:21 -04:00
Carlo Caione
1dcea253d2 shared_multi_heap: Rework framework
Entirely rework the shared_multi_heap framework. Refer to the
documentation for more information.

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2022-04-21 13:15:26 +02:00
Flavio Ceolin
bb98bd6d11 libc: newlib: Fix declare a type conflict
Fix a variable declaration type conflict:

libc-hooks.c:92:16: error: conflicting types for '_heap_sentry'
   92 |   extern void *_heap_sentry;
soc.h:78:13: note: previous declaration of '_heap_sentry' was here

Fixes #44926

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2022-04-18 14:42:19 -05:00
Rico Ganahl
f2affbd973 os: lib: bin2hex: fix memory overwrite
Destination buffer size could be too small by one,
but null termination is still written. This could cause an
overwrite in contiguous memory without notice.

Signed-off-by: Rico Ganahl <rico.ganahl@bytesatwork.ch>
2022-04-13 13:43:53 -07:00
Damian Krolik
5f5410a0cc sys: heap: support maximum allocated bytes statistic
Besides the current allocated/free bytes, keep track of
the maximum allocated bytes to help determine the heap
size requirements. Also, provide a function to reset
the statistic.

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2022-04-13 13:27:28 -07:00
Christopher Friedt
7c583bbf8f lib: posix: support for pthread_attr_setstacksize
Support pthread_attr_setstacksize(3).

See https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_attr_getstacksize.html

Fixes #44722

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2022-04-12 22:02:04 +09:00
Yuval Peress
53ef68d459 include: Prefix includes to use a scope
Move include paths and add new target_include_directories to support
backwards compatibility:
* /include -> /include/zephyr
  example: <irq.h> -> <zephyr/irq.h>

Issue #41543

Signed-off-by: Yuval Peress <peress@google.com>
2022-04-08 19:03:32 +02:00
Marcin Szkudlinski
68a5059ff3 os/lib: change all NULL checking in mem_blocks.c to asserts
Some problems, as passing NULL when a context in expected,
always reflect to bugs. Such problems cannot be handled
in runtime. So the desired action is system panic.

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-04-05 14:29:33 -04:00
Marcin Szkudlinski
05e16411fb os/lib: change all NULL checking in bitarray.c to asserts
Some problems, as passing NULL when a context in expected,
always reflect to bugs. Such problems cannot be handled
in runtime. So the desired action is system panic.

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-04-05 14:29:33 -04:00
Marcin Szkudlinski
033dbae787 lib/mem_blocks: add allocation for contiguous memory blocks
Added allocation and freeing of a contiguous memory blocks

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-04-05 14:29:33 -04:00
Marcin Szkudlinski
297321a9e1 lib/os: sys_mem_blocks_get added
memory block should allow not only allocate memory but also
getting an arbitrary chosen part of memory.
Mixing of allocate and get, however possible, may be dangerous
because alloc may get any of memory. So be careful.

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-04-05 14:29:33 -04:00
Marcin Szkudlinski
e25a7c4611 lib/mem_blocks: change internal alloc_one to alloc_blocks
As preparation for memory blocks to support continuous memory blocks
modify bitmap operation wrappers to support multiple bits alloc/free

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-04-05 14:29:33 -04:00
Marcin Szkudlinski
6c6a16d3b9 lib: bitarray: sys_bitarray_test_and_set_region added
a method to check and set/clear a chosen region in a bitmap
if not previously set/cleared in a single atomic operation.
Useful for keeping track of resources usage, like memory banks

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-04-05 14:29:33 -04:00
Jaxson Han
0e1ff84fe7 posix: Fix pthread_once has incorrect behavior
As described in
https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_once.html.
The behavior of pthread_once() is undefined if once_control has
automatic storage duration or is not initialized by PTHREAD_ONCE_INIT

However, in Zephyr, the implementation is incorrect. If the init value
is PTHREAD_ONCE_INIT, the program will never run the init_func.

Signed-off-by: Jaxson Han <jaxson.han@arm.com>
2022-04-05 10:38:30 -07:00
Krzysztof Chruscinski
35593ce1e9 lib: posix: clock: Prevent early overflows
Algorithm was converting uptime to nanoseconds which can easily
lead to overflows. Changed algorithm to use milliseconds and
nanoseconds for remainder only.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-04-01 09:37:41 +02:00
Krzysztof Chruscinski
a33f7de86a lib: os: cbprintf: Add CBPRINTF_PACKAGE_COPY_KEEP_RO_STR flag
Add flag to copy function which indicates that read-only
string locations shall be kept in the output package.

Updated cbprintf_package test to pass.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-03-29 23:03:35 -04:00
Krzysztof Chruscinski
6d98a1cc7e debug: Revert ASSERT options dependency
f4df23c9 added dependency on ASSERT to some options prefixed
with ASSERT_ assuming that they are no used elsewhere. Turned
out that there are subsystem specific assert macros (e.g. BT_ASSERT)
which relies on those options. Removing the dependency.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-03-29 12:29:55 -07:00
Gerhard Jörges
4fd24a4341 libc: minimal: Add strtoll() and strtoull()
- strtoll() and strtoull() are copies of strtol() and strtoul() with
  types changed to long long instead of long.
- added tests
- added documentation
- removed stubs from civetweb sample

Signed-off-by: Gerhard Jörges <joerges@metratec.com>
2022-03-24 11:03:06 +01:00
Matthias Fend
fc4055852e lib: open-amp: add support for an empty resource table
This allows a resource table to be included even if neither virtIO nor the
RAM console are used.

Signed-off-by: Matthias Fend <matthias.fend@emfend.at>
2022-03-24 10:41:39 +01:00
Nazar Kazakov
f483b1bc4c everywhere: fix typos
Fix a lot of typos

Signed-off-by: Nazar Kazakov <nazar.kazakov.work@gmail.com>
2022-03-18 13:24:08 -04:00
Krzysztof Chruscinski
786647bdcf lib: os: assert: Avoid including printk.h in __assert.h
Create wrapper for printk to avoid including printk.h in __assert.h.
__assert.h is used everywhere thus should not have dependency to
printk.h.

Cleanup assert Kconfig options.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-03-16 10:27:20 +01:00
Nazar Kazakov
9713f0d47c everywhere: fix typos
Fix a lot of typos

Signed-off-by: Nazar Kazakov <nazar.kazakov.work@gmail.com>
2022-03-14 20:22:24 -04:00
Krzysztof Chruscinski
c917e6c2ce lib: os: cbprintf: Extend API to support new packaging modes
Added new flags to packaging API:
- CBPRINTF_PACKAGE_ADD_RO_STR_IDXS - when set, read-only string
  locations are appended to the package
- CBPRINTF_PACKAGE_ADD_RW_STR_IDXS - when set, read-write string
  locations are appended to the package (instead of appending actual
  strings)
- CBPRINTF_PACKAGE_FIRST_RO_STR_CNT(n) - indicate that n first strings
  are known to be read only. Ignored in runtime packaging.

Add function for copying packages with optional appending strings.

Changed CBPRINTF_MUST_RUNTIME_PACKAGE to use same flags as packaging.

Aligned logging and test to those changes.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-03-14 11:16:14 +01:00
Marcin Szkudlinski
2597b787d8 lib/os: Add sys_multi_heap_get_heap function for multi_heap
Sometimes there's a need to perform special operations on a heap
for a specified block. I.e. release virtual memory mapping,
power off memory bank etc.
The added procedure gets a pointer to a proper heap with metadata
for a given address.

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-03-11 13:56:05 -05:00
Marcin Szkudlinski
2a0ee8c920 lib/os: Add metadata to heap in multi_heap
When operating on different kinds of heaps sometimes there's a need to
perform special operations on heap, poweroff memory bank when releasing
memory etc. Therefore some additional data may be required.
Metadata is a point to keep such data.

Signed-off-by: Marcin Szkudlinski <marcin.szkudlinski@intel.com>
2022-03-11 13:56:05 -05:00
Gerard Marull-Paretas
dffaf5375c kconfig: tweak Kconfig prompts
Tweak some Kconfig prompts after the removal of "Enable...".

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-03-09 15:35:54 +01:00
Gerard Marull-Paretas
95fb0ded6b kconfig: remove Enable from boolean prompts
According to Kconfig guidelines, boolean prompts must not start with
"Enable...". The following command has been used to automate the changes
in this patch:

sed -i "s/bool \"[Ee]nables\? \(\w\)/bool \"\U\1/g" **/Kconfig*

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-03-09 15:35:54 +01:00
Carles Cufi
66c9a8e0f9 lib: libc: minimal: Add macros for fast and least min/max values
The minimal C library already supports the fast and least types via
typedefs, but the corresponding min and max macros were missing. Add
those so that we are compatible with software using them.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2022-03-09 13:40:58 +01:00
Danny Oerndrup
845a200c1b libc: minimal: qsort remove callback cast in call of qsort_r
Remove the cast of the two parameter compare function used by qsort, to
the three parameter callback function used by qsort_r, in order to
ensure compatibility with other toolchains, even those off-tree.

Fixes #42870

Signed-off-by: Danny Oerndrup <daor@demant.com>
2022-03-09 06:11:40 -05:00
Daniel Leung
dc22617478 linker: add a utility func to check if an addr is in RO section
This adds a utility function to check if an address is within
read only section. This is extracted from logging subsys so
use the new func in logging. The one is cbprintf_packaged is
also replaced.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-02-28 10:53:02 +01:00
Nicolas Pitre
eee5b8e563 ring_buffer: make finish methods final
Make it possible to "finish" with fewer bytes than what was "claimed".

This was possible before on the get side, but the put side was
cummulative wrt finish. The revamp made it cummulative on both sides.
Turns out that existing users rely on the opposite behavior which is
more logical and useful. So make both sides that way.

Adjust documentation, test case and users accordingly.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2022-02-28 10:52:41 +01:00
Nicolas Pitre
81dbc9dbbf ring_buffer: make the normal "raw" byte mode first
The item mode is really a specialization of the byte mode. And in-tree
usage shows the byte mode is prominent. It feels more natural if the
byte mode is presented first with the item mode second. Swap the code
and documentation order accordingly. No code change.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2022-02-24 14:49:00 -08:00
Nicolas Pitre
099850e916 ring_buffer: the great simplification
This code is rather hairy. When I look at it I don't like the way it
stares back at me.

First, the rewind business looks fishy. It has to die.

And we don't have to rely on modulus either. Not even for non-power-of-2
buffers. Let's kill that distinction too and make all sizes always
"high performance".

The code is now entirely relying only on simple ALU operations (add,
sub and compare).

The key assumption: 32-bit values do wrap around after max range has
been reached. No saturation. All architectures supported by Zephyr
do that.

Some stats:

lib/os/ring_buffer.c: 62 insertions(+), 124 deletions(-)

ring_buffer.c.obj       before   after    diff
----------------------------------------------
frdm_k64f                 1224    1136     -88
m2gl025_miv               2485    2079    -406
mps2_an385                1228    1132     -96
mps2_an521                1228    1132     -96
native_posix              1546    1496     -50
native_posix_64           1598    1595      -3
nsim_hs_mpuv6             1252    1192     -60
nsim_hs_smp               1252    1192     -60
nsim_sem                  1252    1192     -60
qemu_arc_em               1324    1192    -132
qemu_arc_hs6x             1824    1620    -204
qemu_arc_hs               1252    1192     -60
qemu_cortex_a53_smp       2154    1888    -266
qemu_cortex_a53           2154    1888    -266
qemu_cortex_a9            1938    1792    -146

Before (qemu_cortex_a53):
START - test_ringbuffer_performance
1 byte put-get, avg cycles: 52
4 byte put-get, avg cycles: 47
1 byte put claim-finish, avg cycles: 39
5 byte put claim-finish, avg cycles: 41
5 byte get claim-finish, avg cycles: 52
 PASS - test_ringbuffer_performance in 0.8 seconds

After (qemu_cortex_a53):
START - test_ringbuffer_performance
1 byte put-get, avg cycles: 34
4 byte put-get, avg cycles: 41
1 byte put claim-finish, avg cycles: 27
5 byte put claim-finish, avg cycles: 29
5 byte get claim-finish, avg cycles: 29
 PASS - test_ringbuffer_performance in 0.4 seconds

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2022-02-24 14:49:00 -08:00
Nicolas Pitre
c2543320d8 ring_buffer: rationalize the item-based put and get methods
Conceptually, ring_buf_item_put() and ring_buf_item_get() are specialized
versions of ring_buf_put() and ring_buf_get(). Make it so to rationalize
the code to open the way for more optimizations.

This means we need specialized wrappers on top of ring_buf_init()
accordingly, given that the core machinery is now common and byte based.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2022-02-24 14:49:00 -08:00
Daniel Leung
660d30e870 sys: bitarray: remove set but unused variable
The mismatch_mask in match_region() is set but never actually
being used. So remove it as Clang complains.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-02-24 08:38:38 -06:00
Bartosz Golaszewski
6c190292c0 lvgl: move the lvgl glue out of the zephyr tree
Start using the upstream Kconfig from LVGL and move the glue code out
of the zephyr tree and put it under lvgl/zephyr/ in modules.

Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Bartosz Golaszewski
1244a89a21 lvgl: bump version to v8.1.0
This updates the lvgl in-tree glue code to work with version v8.1.0 and
bumps the west manifest accordingly.

The following are the most significant changes:
- The logging callback has changes in lvgl and no longer provides the
  caller with an integer log level code. We now need to parse the log
  string's prefix to determine the level.
- Several Kconfig options (mostly for default values of various settings)
  have been removed because these values are no longer configurable in
  lvgl.
- The library no longer performs a deep copy of the display and input
  device driver structs, so these must no longer be allocated on the
  stack in the init func.

Other than that it's mostly about renaming of various structures and
functions and adjusting the calls if function's signatures have changed.

This patch allows all in-tree users to work correctly but it's likely
it doesn't support all new widgets and layouts added in lvgl v8. These
however can be added gradually once this is upstream.

Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Bartosz Golaszewski
1e80d5a954 lvgl: provide lvgl_realloc()
In order to support lvgl v8, we need to provide a realloc() implementation
in our custom sys_heap allocator. This uses sys_heap_realloc() internally
and exposes traditional realloc() semantics.

Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Bartosz Golaszewski
b7dbe1a51e lvgl: add locking for the sys heap
The sys_heap layer doesn't provide any locking mechanism. Add a spin_lock
around the calls to sys_heap functions.

Suggested-by: Nicolas Pitre <npitre@baylibre.com>
Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Bartosz Golaszewski
b2f1bbed88 lvgl: mem: align the memory used for the private sys heap
Improve efficiency by introducing the 8-byte alignment of the private
heap.

Suggested-by: Nicolas Pitre <npitre@baylibre.com>
Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Bartosz Golaszewski
595131c2d0 lvgl: kill LVGL_MEM_POOL_HEAP_KERNEL and LVGL_MEM_POOL_KERNEL
Current lvgl code allows to use the kernel heap for dynamic memory
allocation. The k_heap API doesn't however provide k_realloc() which
will be needed in order to update lvgl to v8. Nico suggested there's
no good reason for lvgl to use k_heap and it should stick to either
the libc's allocator or depend on its own private sys_heap.

The alternative would be to extend the k_heap API to provide k_realloc()
but this may be tricky for several reasons and for now there would
be a single user anyway.

This removes the choice of using k_heap for lvgl and renames the user
pool to SYS_HEAP in Kconfig and makes it the default option.

The prj.conf for the lvgl sample is modifed to specify the number of
memory pool blocks instead of the total size as the default block
size is 2048 and it results in the same size of memory.

Suggested-by: Nicolas Pitre <npitre@baylibre.com>
Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Bartosz Golaszewski
e467088faa lvgl: take opacity into account
The callback used for the 32-bit color depth has a slight problem, it
doesn't take opacity into account. Correctly mix the colors by using
lv_color_mix().

Suggested-by: Gabor Kiss-Vamosi <kisvegabor@gmail.com>
Signed-off-by: Bartosz Golaszewski <bartosz.golaszewski@huawei.com>
2022-02-24 11:51:33 +01:00
Krzysztof Chruscinski
5c8cc1aa8f lib: os: mpsc_pbuf: Add usage tracking
Add API to fetch current buffer usage. Add option to track
maximum buffer usage and API to fetch that value.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-02-21 20:41:17 -05:00
Daniel Nejezchleb
b68bdf20cf lib/os: fdtable: add locking to posix api
Added locking to posix read(), write(), close()
for additional protection.

In read() missing lock would create uneven calls to locking
mechanism in sockets.c after k_condvar_wait().
That results in socket lock not ever being unlocked

Signed-off-by: Daniel Nejezchleb <dnejezchleb@hwg.cz>
2022-02-10 10:59:03 +01:00
Christopher Friedt
07c00fff25 pthread: cond: fix pthread_cond_wait always returning ETIMEDOUT
It was noted that `pthread_cond_wait()` would always return
ETIMEDOUT, even when successful (and no timeout should ever
occur with `K_FOREVER`).

The z_sched_wake() / z_sched_wake_all() / z_sched_wait() API
are used here with a swap return value of 0 to indicate
success.

Fixes #41284

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2022-02-09 22:16:45 -05:00
Krzysztof Chruscinski
c2666c3138 lib: os: cbprintf: Use rodata section on sparc
Use rodata region markers to detect if string is read only on
sparc. It was previously disabled but now can be used.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-02-08 09:41:37 -05:00
Carles Cufi
7f6524949a lib: os: crc: Rework the crc16() implementation
As described in #42403, there was an issue with the existing crc16_ansi()
implementation, since it was not calculating the CRC-16-ANSI (aka
CRC-16-MODBUS). This is because the  existing crc16() function only
supported non-reflected input and output (and the CRC-16-ANSI requires
reflection on both) and also it did not seem to support correctly inial
seeds different from 0x0000 (and, again, the CRC-16-ANSI requires 0xffff
as an initial seed).

This commit replaces the existing crc16() with a functional pair,
crc16() and crc16_reflect(), that also work with any poly, any initial seed
and allow to select whether reflection is performed.
It also adapts crc16_ansi() so that it actually returns the correct CRC.

Fixes #42403.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2022-02-04 12:33:22 -05:00
Daniel Leung
e2f109456c lib/os: cbprintf_packaged: add ability to use external formatter
This adds to the cbprintf_packaged library to allow external
formatters to be used by the way of callback. This will allow
logging backends to use their own formatter for output if
needed.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-02-04 11:14:55 +01:00
Krzysztof Chruscinski
a40ca6fd1c logging: printk: Fix LOG_PRINTK for v2
Fixed a dependency from printk.h to logging headers which in
certain configurations could lead to circular dependencies.
Cleaned up printk.c to call z_log_vprintk from vprintk.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-01-27 10:02:21 +01:00
Krzysztof Chruscinski
09fef8e7d2 lib: os: printk: Minor refactoring
Refactoring to remove code redundancy caused by splitted
handling based on USERSPACE enabled.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-01-27 10:02:21 +01:00
Binu Jacob
5fa5658ef7 libc: newlibc: Fix recursive gettimeofday() calls on non-Posix systems
Calling gettimeofday() from _gettimeofday() in a non-Posix build
environment can result in a recursive call loop, causing a stack
overflow. Modify _gettimeofday() to return -1 for non-posix systems
(the previous behaviour that was added in #22508).

Fixes #41095

Signed-off-by: Binu Jacob <bjj@planetinnovation.com.au>
2022-01-21 15:27:45 -05:00
Nicolas Pitre
019a1e13f4 cbprintf_packaged: code cleanups
- Abstract buffer offset computation for better code clarity.

- Rework the logic around rw/ro strings to simplify the logic and
  to guard against overflows even when only computing the needed buffer
  size.

- Use modulus to simplify alignment tests (generated assembly is
  the same).

- Avoid CBPRINTF_ prefixes for local macro names

- Better pointer types to reduce cast usage.

- Add more comments.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2022-01-20 08:21:33 -05:00
Antony Pavlov
0369998e61 arch: add MIPS architecture support
MIPS (Microprocessor without Interlocked Pipelined Stages) is a
instruction set architecture (ISA) developed by MIPS Computer
Systems, now MIPS Technologies.

This commit provides MIPS architecture support to Zephyr. It is
compatible with the MIPS32 Release 1 specification.

Signed-off-by: Antony Pavlov <antonynpavlov@gmail.com>
2022-01-19 13:48:21 -05:00
Andy Ross
528bef2d22 lib/os: Add sys_winstream lockless shared memory byte stream IPC
It's not uncommon to have Zephyr running in environments where it
shares a memory bus with a foreign/non-Zephyr system (both the older
Intel Quark and cAVS audio DSP systems share this property).  In those
circumstances, it would be nice to have a utility that allows an
arbitrary-sized chunk of that memory to be used as a unidirectional
buffered byte stream without requiring complicated driver support.
sys_winstream is one such abstraction.

This code is lockless, it makes no synchronization demands of the OS
or hardware beyond memory ordering[1].  It implements a simple
file/socket-style read/write API.  It produces small code and is high
performance (e.g. a read or write on Xtensa is about 60 cycles plus
one per byte copied).  It's bidirectional, with no internal Zephyr
dependencies (allowing it to be easily ported to the foreign system).
And it's quite a bit simpler (especially for the reader) than the
older cAVS trace protocol it's designed to replace.

[1] Which means that right now it won't work reliably on arm64 until
we add a memory barrier framework to Zephyr!  See notes in the code;
the locations for the barriers are present, but there's no utility to
call.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2022-01-13 14:01:23 -05:00
Daniel Leung
3feec54acf lib: os: remove @return doc for void functions
For functions returning nothing, there is no need to document
with @return, as Doxgen complains about "documented empty
return type of ...".

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-12 16:02:16 -05:00
Krzysztof Chruscinski
4433953e34 lib: os: ring_buffer: Fix issues in rewinding
Two issues were found:
- subtracting rewinding value from head could result in negative value
- calling ring_buf_put_claim after tail got rewinded but before head
got rewinded resulted in error.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-01-11 18:19:44 -05:00
Daniel Leung
f3856d0b47 lib: os: mem_blocks: add alloc/free event notifications
This adds event notification for mem_blocks using the new
heap listener interface.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-11 16:10:53 -05:00
Daniel Leung
d8f97caac2 lib: os: mem_blocks: add memory blocks allocator groups
This adds similar ability of sys_multi_heap to the memory blocks
allocator, where a choice function can be used to select
which allocator (of a group) is used for memory block allocation.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-11 16:10:53 -05:00
Daniel Leung
8308f3f4d5 lib: os: introduce memory blocks allocator
This introduces yet another memory blocks allocator where:

() All memory blocks have a single fixed size.

() Multiple blocks can be allocated or freed at the same time.

() A group of blocks allocated together may not be contiguous.
   This is useful for operations such as scatter-gather DMA
   transfers.

() Bookkeeping of allocated blocks is done outside of
   the associated buffer (unlike memory slab). This allows
   the buffer to reside in memory regions where these can be
   powered down to conserve energy.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-11 16:10:53 -05:00
Daniel Leung
5604b98f21 lib: os: group heap related kconfigs under a menu
This groups the heap related kconfigs under a menu
so they are under a group (!).

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-11 16:10:53 -05:00
Emil Gydesen
43b827c562 zephyr: Add UTF8 kconfig to conditionally compile utf8.c
Add the kconfig option so that the utf8.c file can be
conditionally compile, and only for the applications
that need it.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2022-01-11 11:50:15 +01:00
Emil Gydesen
baf48fbe2e zephyr: Add UTF-8 truncating strlcpy variant
Add a function to copy a UTF-8 encoded string that
ensure correct truncation of the string if the source
is larger than the destination, as well as ensuring that
the resulting destination string is NULL-terminated.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2022-01-11 11:50:15 +01:00
Emil Gydesen
5cb72d2193 zephyr: Add function to properly truncate UTF-8 strings
Add a function that can properly truncate UTF-8 strings
without leaving unterminated started characters,
as UTF-8 characters can be 1-4 bytes long.

Signed-off-by: Emil Gydesen <emil.gydesen@nordicsemi.no>
2022-01-11 11:50:15 +01:00
Daniel Leung
bbe03935f6 lib: os/heap: fix bytes freed calculation for heap listener
This fixes an issue of how the number of bytes freed is calculated
for the heap listener.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-10 21:27:28 -05:00
Daniel Leung
f6e2705719 sys: heap: add support for heap listener
This adds notification in the heap code to emit events for
heap listeners.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-10 10:28:04 -05:00
Daniel Leung
071db26f6c lib: os: CONFIG_HEAP_LISTENER to be hidden
This changes CONFIG_HEAP_LISTENER to be a hidden kconfig so that
the actual heap implementation can select it to enable
notifications. Each heap implementations will have their own
kconfigs to enable heap listener functionality so that app
can be built to only listen to certain heap implementations.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-10 10:28:04 -05:00
Daniel Leung
ae415272c1 sys: heap_listener: extend to cover more events
This extends the heap_listener to cover more events,
specifically, allocation, free and realloc.

Note that typedef are used so the callback can be
documented.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-10 10:28:04 -05:00
Daniel Leung
39d17a180a sys: heap_listener: resize_cb to also take heap ID
Add a parameter to the resize callback to also take the heap ID.
This allows a single callback to be used for multiple heaps if
so desired.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-01-10 10:28:04 -05:00
Eduardo Montoya
b2ca577256 libc: add stddef.h to the minimal libc
It is required for using `size_t`.

Signed-off-by: Eduardo Montoya <eduardo.montoya@nordicsemi.no>
2022-01-07 12:48:27 -05:00
Krzysztof Chruscinski
bd8cc594d9 lib: os: mpsc_pbuf: Add const to mpsc_pbuf_free argument
Added const qualifier to argument in a function.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-01-07 18:47:19 +01:00
Jakub Rzeszutko
d4559f53fa lib: getopt: rework and extend getopt library
Getopt has been rework in this way that calling it does not require
extra state parameter and its execution is thread safe.
Global parameters describing the state of the getopt function have been
made available to ensure full API compatibility in using this library.
However, referencing these global variables directly is not thread
safe. In order to get the state of the getopt function for the thread
that is currently using it, call: getopt_state_get();

Extended the library with getopt_long and getopt_long_only functions.

Moved getopt libary from utils to posix.

Signed-off-by: Jakub Rzeszutko <jakub.rzeszutko@nordicsemi.no>
2022-01-06 21:26:59 +01:00
Patric Karlström
20b3d180d1 posix: Make clock_settime/gettime REALTIME thread-safe
Fixes #23419

Signed-off-by: Patric Karlström <pakar@imperialnet.org>
2021-12-21 11:49:51 +01:00
Damian Krolik
3aedda9852 lib: os: add heap event listener
* add generic heap event listener module that can be used
  for notifying an application of heap-related events
* use the listener module in newlib libc hooks
* add a unit test

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
2021-12-18 07:49:15 -05:00
Nicolas Pitre
40a94d2451 lib/os/heap: use BIT() and BIT_MASK() on bit fields
This is a clean way to make MISRA happy.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-12-13 17:16:07 -05:00
Jeremy Bettis
1e0a36c655 build: Remove unused functions
Removed unused functions, or moved inside #ifdefs.

This allows using -Werror=unused-function on the clang compiler. Tested
by building the ChromeOS EC on all supported platforms with
-Werror=unused-functions.

Signed-off-by: Jeremy Bettis <jbettis@google.com>
2021-12-13 15:49:08 -05:00
Johann Fischer
5228211060 lib: lvgl: obtain LVGL_DISPLAY_DEV_NAME from devicetree
It is not possible completely remove options like
LVGL_DISPLAY_DEV_NAME without heavy reworking of LVGL support
because lvgl_init needs the name of the device, and
LVGL_*_RES_MAX options to define internal buffers.

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
2021-12-10 12:47:30 +01:00
Gerard Marull-Paretas
78dc8ce338 drivers: timer: improve sys_timer_disable usage
- Remove the weak symbol definition
- Notify about the capability of disabling via a selected Kconfig option
  (CONFIG_SYSTEM_TIMER_HAS_DISABLE_SUPPORT)
- Provide a dummy inline function when the functionality is not
  available

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-12-04 07:34:53 -05:00
Ramiro Merello
b1c350dbfe json: Fix rule 5.7 violations (Tag name should be unique)
Fixed 5.7 rules errors due to:
- struct token token updated to struct token tok
- struct lexer lexer updated to struct lexer lex

Signed-off-by: Ramiro Merello <rmerello@itba.edu.ar>
2021-12-01 12:21:19 -05:00
Markus Fuchs
c6bc548b73 json: Add top-level array decoding support
The library supports encoding JSON objects and arrays as well as
parsing JSON objects. Introduce a new function json_arr_parse() adding
support for parsing top-level JSON arrays.

Signed-off-by: Markus Fuchs <markus.fuchs@ch.sauter-bc.com>
2021-12-01 12:21:19 -05:00
Nicolas Pitre
5aeb809374 lib/os/heap-validate: code cleanup
Remove code duplication, use common code idiom, etc.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-11-15 11:03:57 -05:00
Nicolas Pitre
f13387d8d2 lib/os/heap: fix a type
Rationale in commit b1eefc0c26 ("lib/os/heap: straighten up our type
usage").

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-11-15 11:03:57 -05:00
Chen Peng1
28f834c914 sys_heap: add check for sys_heap_runtime_stats_get API
add operations to check sys_heap_runtime_stats_get API
in existing sys_heap_validate function.

Signed-off-by: Chen Peng1 <peng1.chen@intel.com>
2021-11-11 16:21:43 -05:00
Chen Peng1
a71cd8790f heap: add functions to get heap runtime statistics
add functions to get the sys_heap runtime statistics,
include total free bytes, total allocated bytes.

Signed-off-by: Chen Peng1 <peng1.chen@intel.com>
2021-11-11 16:21:43 -05:00
Christopher Friedt
bd83df1552 libc: minimal: add qsort to the minimal libc
This change implements qsort() for the minimal libc via Heapsort.

Heapsort time complexity is O(n log(n)) in the best, average,
and worst cases. It is O(1) in space complexity (i.e. sorts
in-place) and is iterative rather than recursive. Heapsort is
not stable (i.e. does not preserve order of identical elements).

On cortex-m0, this implementation occupies ~240 bytes.

Fixes #28896

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2021-11-10 07:00:36 -05:00
Bradley Bolen
6336cb26d8 libc: minimal: Use new ZRESTRICT macro
This lets the toolchain header files determine how to use "restrict"
instead of having that decision down in the minimal libc library.

Signed-off-by: Bradley Bolen <bbolen@lexmark.com>
2021-11-05 13:29:31 +01:00
Sam Hurst
c4cdbc6062 lib: smf: Remove unused variables
In function smf_execute_ancestor_exit_actions, variables
"tmp_state" and "target_parent" are set but not used.

Twister passed:
twister -T tests/lib/smf/

Signed-off-by: Sam Hurst <sbh1187@gmail.com>
2021-10-26 17:53:32 -04:00
Nicolas Pitre
46db2b491d lib/os/heap: option for optimizing for one heap size on 32-bit systems
The "small" heap is is way sufficient for most 32-bit systems.

Let's provide the option to have only one type of heap allowing for
smaller and faster heap code due to not having a bunch of runtime
conditionals based on the heap size.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-10-17 07:34:51 -04:00
Carlo Caione
43cb00df08 multi_heap: Introduce shared multi-heap memory pool manager
The shared multi-heap memory pool manager uses the multi-heap allocator
to manage a set of reserved memory regions with different capabilities /
attributes (cacheable, non-cacheable, etc...) defined in the DT.

The user can request allocation from the shared pool specifying the
capability / attribute of interest for the memory (cacheable /
non-cacheable memory, etc...)

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2021-10-12 07:44:46 -04:00
Andy Ross
cf0c5e2a1c lib/os: Add sys_heap_usable_size()
Add a simple internal block size predicate to expose the internal
memory region reserved for an allocation.  The immediate use case is
cache-incoherent systems wanting to do an invalidate of freed memory,
but it might be useful for apps doing e.g. string processing to better
optimize size changes, etc...

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2021-10-06 20:20:31 -04:00
Sam Hurst
cb4785542e lib: smf: Add State Machine Framework
Add an application agnostic State Machine Framework library to
Zephyr that provides an easy way for developers to integrate
state machines into their application.

Twister passed:
twister -T tests/lib/smf/

Signed-off-by: Sam Hurst <sbh1187@gmail.com>
2021-10-04 20:33:11 -04:00
Andy Ross
85e96ff3ca lib/os: Add sys_multi_heap utility
This is a simple wrapper allowing multiple sys_heap regions to be
unified under a single allocation API.  Sometimes apps need the
ability to share multiple discontiguous regions in a single "heap", or
to have memory of different "types" be allocated heuristically based
on usage (e.g. cacheability, latency, power...).  This allows a
user-specified function to select the underlying memory to use for
each application.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2021-10-01 20:38:35 -04:00
Carles Cufi
38f6fd05bf libc: minimal: Add an implementation of iscntrl()
Implement the iscntrl() function, which returns whether a character is a
control one or not.

Ref: https://en.cppreference.com/w/c/string/byte/iscntrl

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2021-10-01 11:37:38 +02:00
Ramiro Merello
28da82c0e1 json: Changes enum name of square brackets from list to array
Marked JSON_TOK_LIST_ as deprecated in favor of JSON_TOK_ARRAY_

Signed-off-by: Ramiro Merello <rmerello@itba.edu.ar>
2021-09-28 19:52:10 -04:00
Krzysztof Chruscinski
ba60c94b48 lib: os: mpsc_pbuf: Add const qualifier to API calls
Add const qualifier where it was missing. Updating
relevant code.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-09-28 06:15:39 -04:00
Stephanos Ioannidis
04e67e2593 Revert "lib: newlib: Add workaround for #38258"
The commit 9bd1483afeb18f4225ec7b0340b0d4e20efb7d01 was added as a
workaround for the Xtensa initial malloc failure bug.

This bug has been fixed in the Zephyr SDK 0.13.1 release and therefore
this workaround is no longer needed.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-09-24 07:35:40 -04:00
Yang XiaoHua
5a65fc0557 libc: minimal: Add math macro definition
When the sof module code was build, it was found that
PI was not defined in the minimal library.
Here are some mathematical constant definitions to avoid build errors.

Signed-off-by: Yang XiaoHua <yangxiaohuamail@gmail.com>
2021-09-22 06:16:31 -04:00
Ryan McClelland
deef96d70c lib: timeutil: fix implicit conversions from float to double
C implicit promotion rules will want to make floats into doubles very
easily. Zephyr build will generate warnings when this flag,
`-Wdouble-promotion`, is enabled with GCC

Signed-off-by: Ryan McClelland <ryanmcclelland@fb.com>
2021-09-20 19:47:57 -04:00
Stephanos Ioannidis
92f0f706f7 lib: libc: Drop z_ prefix from stdio syscalls
This commit removes the `z_` prefix from the stdio syscall functions
(`z_zephyr_write_stdout` and `z_zephyr_read_stdin`) since it is
redundant and does not align with the convention used by the equivalent
minimal libc syscall functions (e.g. `zephyr_fputc` and
`zephyr_fwrite`).

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-09-11 04:47:01 -04:00
Stephanos Ioannidis
86b8cf1f06 lib: libc: arcmwdt: Fix userspace write() and read() mishap
The newlib `write()` and `read()` functions must call the
`z_zephyr_write_stdout()` and `z_zephyr_read_stdin()` syscall functions
in order to function properly in a user mode context.

The existing incorrect implementation was copied off the newlib hooks
implementation, which was corrected in the previous commit.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-09-11 04:47:01 -04:00
Stephanos Ioannidis
eab7ae922a lib: libc: newlib: Fix userspace write() and read() mishap
The commit 4344e27c26 changed the syscall
function invocation in the `write()` and `read()` functions to the
direct syscall implementation function invocation by mistake.

The newlib `write()` and `read()` functions must call the
`z_zephyr_write_stdout()` and `z_zephyr_read_stdin()` syscall functions
in order to function properly in a user mode context.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-09-11 04:47:01 -04:00
Dylan Hung
f0ea22b538 libc/minimal: locate the memory pool for malloc() to .bss
When CONFIG_USERSPACE is turned off, the POOL_SECTION will be located in
.data section.  This will increase the target binary size.  Since the
memory pool is for malloc() use and it doesn't need for initial values,
locate it in the .bss section to reduce binary size.

Signed-off-by: Dylan Hung <dylan_hung@aspeedtech.com>
Change-Id: Iee52ac06a48414c083518c79775fe31334eab674
2021-09-10 10:59:25 -04:00
Evgeniy Paltsev
c5eeb0f4eb ARC: MWDT: add locking interface implementation
ARC MWDT libraries require to implement locking interface
otherwise not all of functionality is guarantee to be
thread-safe.

So, let's implement locking interface.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-09-07 11:31:37 -04:00
Evgeniy Paltsev
4e0f7ea540 posix: pthread: replace irq_lock with spinlock
We shouldn't use swapping with an interrupt lock held
as it works incorrectly on SMP platforms.

Fix that by replacing irq_lock with spinlock for pthread
subsystem.

NOTE: we fix that in a simple way with single spinlock
for mutex / cond_var / barrier. That could be improved
later (i.e. split it for several spinlocks).

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-09-03 12:20:19 -04:00
Nicolas Pitre
5a384b9ea8 lib/os/cbprintf_nano.c: avoid sign extension on unsigned formats
There might be a sign extension when a long is promoted to
int_value_type and the former type is smaller than the later.
This produces the wrong output if the specified format is unsigned.

Let's avoid this problem by handling signed and unsigned cases
explicitly. When the type already matches int_value_type then the
compiler is smart enough to recognize the redundancy and removes
unneeded duplications automatically, meaning that the code will stay
small when code size matters.

A similar issue also existed in the restricted %llu case.
The fix is the same as above.

Those fixes exposed wrong results in the printk.c test with %llx
so fix that as well.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-09-02 19:37:06 -04:00
Stephanos Ioannidis
2208844f17 lib: newlib: Add workaround for #38258
For the Xtensa platforms (e.g. qemu_xtensa), the first `malloc` call
may fail if the newlib heap base address is such that the first `sbrk`
call returns a 4096-byte aligned address.

Here we add a workaround for Xtensa that allocates and immediately
frees a 16-byte memory block during initialisation so that all
subsequent `malloc` calls succeed.

This commit needs to be reverted once the issue #38258 is fixed.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-09-02 10:58:15 -05:00
Evgeniy Paltsev
9f948a84f7 ARC: MWDT: libc: add _exit support
Default weak _exit implementation from ARC MWDT libs
calls _exit_halt from startup libs. As we are going to
get rid of startup libs usage let's implement _exit
stub.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-09-01 17:08:32 -04:00
Torsten Rasmussen
16e848b57c armclang: threading_weak.c source file added for armclang
The stub file threading_weak.c has been added containing weak stub
implementation of threading related kernel functions.

The file is needed for armlink.

When linking with armlink the linker will resolve undefined symbols for
all undefined functions even if those functions the reference the
undefined symbol is never actually called.

This file provides weak stub implementations that are compiled when
CONFIG_MULTITHREADING=n to ensure proper linking.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-08-30 08:54:23 -04:00
Torsten Rasmussen
36bb00d1f5 armclang: ARM Compiler C library support
Support for ARM Compiler C library.

This commit add support for the ARM Compiler C libary in:
- Kconfig
- libc/armstdc

A new Kconfig symbol is added to allow a toolchain to specify if they
support linking with the minimal C library.
Also the CMake variable `TOOLCHAIN_HAS_NEWLIB` is exported to Kconfig
so that CONFIG_NEWLIB_LIBS can only be enabled if the toolchain has
newlib.

The armclang toolchain selects the CMake scatter file generator and
disables support for the LD linker template which is not supported by
armlink.

For the ARM Compiler C library, a corresponding lib/libc/armstc/ folder
with a minimal implementation to work with the ARM Compiler C library
is added.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-08-30 08:54:23 -04:00
Torsten Rasmussen
c6aded2dcb linker: align _image_rodata and _image_rom start/end/size linker symbols
Cleanup and preparation commit for linker script generator.

Zephyr linker scripts provides start and end symbols for each larger
areas in the linker script.

The symbols _image_rom_start and _image_rom_end corresponds to the group
ROMABLE_REGION defined in the ld linker scripts.

The symbols _image_rodata_start and _image_rodata_end is not placed as
independent group but covers common-rom.ld, thread-local-storage.ld,
kobject-rom.ld and snippets-rodata.ld.

This commit align those names and prepares for generation of groups in
linker scripts.

The symbols describing the ROMABLE_REGION will be renamed to:
_image_rom_start -> __rom_region_start
_image_rom_end   -> __rom_region_end

The rodata will also use the group symbol notation as:
_image_rodata_start -> __rodata_region_start
_image_rodata_end   -> __rodata_region_end

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-08-28 08:48:03 -04:00
Maksim Masalski
e02c7bd466 libc: types: suppress deviation
Suppress violation, because it is a deliberated deviation.
Noticed, that my previous PR #36420 comments were not correctly
detected by a static analysis tool. Only the first one item
"MISRAC2012-RULE_20_4-a" was detected and suppressed.

Change comment style, so each item will be suppressed.
Comment style defined in PR #36911 as the most suitable
for the analysis tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-08-24 07:23:02 -04:00
Krzysztof Chruscinski
58942f3f13 lib: os: ring_buffer: Fix race condition
Ring buffer claims that no synchronization is needed
when there is a single producer and single consumer.
However, recent changes have broken that promise since
indexes rewind mechanism was modifing head and tail
when consuming. Patch fixes that by spliting rewinding
of indexes so that producer rewinds tail only and
consumer rewinds head.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-08-17 19:52:08 +02:00
Michael Zimmermann
5e7ef8be5a json: fix parsing first array-array element
Previously, the first element inside the array-array didn't contain the
decoded data.

Signed-off-by: Michael Zimmermann <sigmaepsilon92@gmail.com>
2021-08-16 15:11:20 -04:00
Evgeniy Paltsev
b84a0fe9c3 ARC: MWDT: LIB: implement _istty hook
Implement _istty hook as it is required for proper setup of
STDIN/STDOUT/STDERR buffering.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-08-13 13:43:19 -05:00
Evgeniy Paltsev
ab130333db ARC: MWDT: LIB: implement ___errno hook
Implement ___errno so ARC MWDT libc can use proper (Zephyr) errno

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-08-13 13:43:19 -05:00
Evgeniy Paltsev
64ff64a48f ARC: MWDT: workaround missing file IO related defines
ARC MWDT libc misses some file IO related defines, let's
add them in ARC MWDT libc compatibility layer.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-08-13 13:43:19 -05:00
Evgeniy Paltsev
a5788ff12d ARC: LIB: MWDT: add stdout hooks, timespec header
ARC MWDT toolchain misses stdout hooks implementation and
itimerspec structure in timespec header. Let's add them in
arcmwdt compatibility layer.

The implementation was inspired by libc-hooks.c for NEWLIB.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-08-13 13:43:19 -05:00
Evgeniy Paltsev
e479d9aea0 ARC: LIB: add ARC MWDT libc support
ARC MWDT toolchain doesn't provide newlib, let's add support
of ARC MWDT libc to Zephyr

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-08-13 13:43:19 -05:00
Christoph Thurnheer
ef97121d74 lib: os: add gcc noreturn attribute for sys_reboot
sys_reboot doesn't return so mark it with noreturn

Signed-off-by: Christoph Thurnheer <c.thurnheer@gmx.ch>
2021-08-13 07:32:51 -04:00
Fabio Baltieri
f88a420d69 toolchain: migrate iterable sections calls to the external API
This migrates all the current iterable section usages to the external
API, dropping the "Z_" prefix:

Z_ITERABLE_SECTION_ROM
Z_ITERABLE_SECTION_ROM_GC_ALLOWED
Z_ITERABLE_SECTION_RAM
Z_ITERABLE_SECTION_RAM_GC_ALLOWED
Z_STRUCT_SECTION_ITERABLE
Z_STRUCT_SECTION_ITERABLE_ALTERNATE
Z_STRUCT_SECTION_FOREACH

Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
2021-08-12 17:47:04 -04:00
Stephanos Ioannidis
43b8002b14 lib: newlib: Add retargetable locking implementation
This commit adds the newlib retargetable locking interface function
implementations in order to make newlib functions thread safe.

The newlib retargetable locking interface is internally called by the
standard C library functions provided by newlib to synchronise access
to the internal shared resources.

By default, the retargetable locking interface functions defined within
the newlib library are no-op. When multi-threading is enabled (i.e.
`CONFIG_MULTITHREADING=y`), the Zephyr-side retargetable locking
interface implementations override the default newlib implementation
and provide locking mechanism.

The retargetable locking interface may be called with either a static
(`__lock__...`) or a dynamic lock.

The static locks are statically allocated and initialised immediately
after kernel initialisation by `newlib_locks_prepare`.

The dynamic locks are allocated and de-allocated through the
`__retargetable_lock_init[_recursive]` and
`__retarget_lock_close_[recurisve]` functions as necessary by the
newlib functions. These locks are allocated in the newlib heap using
the `malloc` function when userspace is not enabled -- this is safe
because the internal multi-threaded malloc lock implementations
(`__malloc_lock` and `__malloc_unlock`) call the retargetable locking
interface with a static lock (`__lock__malloc_recursive_mutex`). When
userspace is enabled, the dynamic locks are allocated and freed through
`k_object_alloc` and `k_object_release`.

Note that the lock implementations used here are `k_mutex` and `k_sem`
instead of `sys_mutex` and `sys_sem` because the Zephyr kernel does not
currently support dynamic allocation of the latter. These locks should
be updated to use `sys_mutex` and `sys_sem` when the Zephyr becomes
capable of dynamically allocating them in the future.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-08-09 08:51:24 -05:00
Jordan Yates
2c1f184d02 lib: timeutil: fix conversion drift
Fix conversion drifts for large deltas by only applying float
operations when the skew requires it. This helps because not all
integers are representable as floats, so large integers are
neccessarily quantised when performing float operations.

When required, floating-point operations are now performed on doubles
instead of floats.

Fixes #37263.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-08-08 08:18:23 -04:00
Andrew Boie
f07df42d49 kernel: make k_current_get() work without syscall
We cache the current thread ID in a thread-local variable
at thread entry, and have k_current_get() return that,
eliminating system call overhead for this API.

DL: changed _current to use z_current_get() as it is
    being used during boot where TLS is not available.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2021-07-30 20:16:47 -04:00
Christopher Friedt
0ca511a49e sys: ring_buffer: ring_buf_peek() and ring_buf_size_get()
Add ring_buf_size_get() to get the number of bytes currently available
in the ring buffer.

Add ring_buf_peek() to read data from the head of a ring buffer without
removal.

Fixes #37145

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2021-07-28 07:32:28 -04:00
Krzysztof Chruscinski
5d80cbae59 lib: os: cbprintf: Add support for conversion to fsc package
Added support for conversion from a standard package which contains
pointers to read only strings to fully self-contained (fsc) package.
Fsc package contains all strings associated with the package thus
access to read only strings is not needed to format a string.

In order to allow conversion to fsc package, standard package must
contain locations of all string pointers within the package. Appending
that information is optional and is controlled by flags parameter
which was added to packaging API. If option flag is set then
package contains header, arguments, locations of read only strings and
transient strings (each prefixed with string argument location).
Package header has been extended with field which contains number of
read only string locations.

A function for conversion to fsc package has been added
(cbprintf_fsc_package()).

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-07-27 14:50:45 +02:00
Maksim Masalski
52a4ba26ce lib: os: cast to the same size composite expression
In file crc16_sw.c essential type of LHS operand (16 bit) is wider than
essential type of composite expression in RHS operand (8 bit).
In crc32c_sw.c and crc32_sw.c Essential type of LHS operand (32 bit) is
wider than essential type of composite expression in RHS operand (8 bit)

Found as a coding guideline violation (MISRA R10.7) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-07-23 15:53:30 -04:00
Krzysztof Chruscinski
69d2cc4735 lib: os: cbprintf: Add dependency to cbprintf Kconfig
Prevent CONFIG_CBPRINTF_STATIC_PACKAGE_CHECK_ALIGNMENT when LOG_PRINTK.
Prevent use of assert in cbprintf header when printk is redirected
to logging. Enabling it would lead to circular header includes and
compilation failure.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-07-21 07:46:39 -04:00
Yasushi SHOJI
b2fde24c4c libc: minimal: Add rand() and srand()
rand() and srand() are pseudo-random number generator functions
defined in ISO C. This implementation uses the Linear Congruential
Generator (LCG) algorithm with the following parameters, which are the
same as used in GNU Libc "TYPE_0" algorithm.

  Modulus 2^31
  Multiplier 1103515245
  Increment 12345
  Output Bits 30..0

Note that the default algorithm used by GNU Libc is not TYPE_0, and
TYPE_0 should be selected first by an initstate() call as shown below.

All global variables in a C library must be routed to a memory
partition in order to be used by user-mode applications when
CONFIG_USERSPACE is enabled.  Thus, srand_seed is marked as
such. z_libc_partition is originally used by the Newlib C library but
it's generic enough to be used by either the minimal libc or the
newlib.

All other functions in the Minimal C library, however, don't require
global variables/states.  Unconditionally using z_libc_partition with
the minimal libc might be a problem for applications utilizing many
custom memory partitions on platforms with a limited number of MPU
regions (eg. Cortex M0/M3). This commit introduces a kconfig option
CONFIG_MINIMAL_LIBC_RAND so that applications can enable the
functions if needed.  The option is disabled by default.

Because this commit _does_ implement rand() and srand(), our coding
guideline check on GitHub Action finds it as a violation.

    Error: lib/libc/minimal/include/stdlib.h:45:WARNING: Violation to
    rule 21.2 (Should not used a reserved identifier) - srand

But this is false positive.

The following is a simple test program for LCG with GNU Libc.

  #include <stdio.h>
  #include <stdlib.h>

  int main()
  {
          static char state[8];

          /* Switch GLIBC to use LCG/TYPE_0 generator type. */
          initstate(0, state, sizeof(state));

          srand(1);  /* Or any other value. */
          printf("%d\n", rand());
          printf("%d\n", rand());

          return 0;
  }

See initstate(3p) for more detail about how to use LCG in GLIBC.

Signed-off-by: Yasushi SHOJI <yashi@spacecubics.com>
2021-07-20 13:32:36 -04:00
5d55730cf6 libc: minimal: add size optimized string functions
The current implementations of memcpy and memset are optimized for
performance and use a word based loop before the byte based loop.

Add a config option that skips the word based loop. This saves 120
bytes on the Cortex-M0+ which is worthwhile on small apps like a
bootloader.

Enable by default if SIZE_OPTIMIZATIONS is set.

Signed-off-by: Michael Hope <mlhx@google.com>
2021-07-06 07:40:38 -04:00
Maksim Masalski
8535a01d92 libc: types: add a comment to the "wrong definition" code
Add an explanation comment, so no one in the future
will try to change that part of the code.
Add parasoft tags to suppress a violation in static analysis tool

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-06-24 09:29:39 +02:00
Yasushi SHOJI
fedab40576 lib: os: heap-validate: Fix wrong chunkid returned by max_chunkid()
With 64 bytes heap and 1 byte allocation on a big heap, we get:

  0   1   2   3   4   5   6   7
| h | h | b | b | c | 1 | s | f |

where
  - h: chunk0 header
  - b: buckets in chunk0
  - c: chunk header for the first allocation
  - 1: chunk mem
  - s: solo free header
  - f: end marker / footer

max_chunkid() was returning h->end_chunk - min_chunk_size(h), which is
5 because min_chunk_size() on a big heap is 2.  This works if you
don't have the solo free header at 6 and the heap is like:

  0   1   2   3   4   5   6
| h | h | b | b | c | 1 | f |

max_chunkid() in this case gives you 6 - 2 = 4, which is the right
chunkid for the last chunk header.

This commit replaces max_chunkid() with h->end_chunk and "<=" (less
than or equal to) with "<" (less than), so that it always compares
against the end maker chunkid, but the code won't touch the end maker
itself.

Signed-off-by: Yasushi SHOJI <yashi@spacecubics.com>
2021-06-23 06:18:44 -04:00
Kumar Gala
932bc399ba lib: os: Removed deprecated Kconfig PRINTK64 symbol
The symbol have been deprecated for 2 releases so remove the code
associated with it.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2021-06-11 16:35:19 -05:00
Anas Nashif
9143f4fd8c fdtable: remove remains of switch
a switch was converted to an if statement and still had a default,
something went really wrong here.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-06-05 10:38:04 -04:00
Maksim Masalski
9eab89ff20 lib: replace one case switch with if operator
Current "switch" operator with one case replace with the "if"
operator, because every switch statement shall have at least
two case-clauses.

Found as a coding guideline violation (MISRA R16.1) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-06-04 16:22:38 -05:00
Maksim Masalski
a61edd480d lib: add default labels and comments to switch statements
According to the Zephyr Coding Guideline all switch statements
shall be well-formed.
Added a default labels to switch-clauses without them.
Added comments to the empty default cases.

Found as a coding guideline violation (MISRA R16.1) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-06-04 16:22:23 -05:00
Maksim Masalski
3960d413db lib: os: add braces to 'if' statements
An 'if' (expression) construct shall be followed by a compound
statement.
Add braces to improve readability and maintainability.

Found as a coding guideline violation (MISRA R15.6) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-06-04 16:20:44 -05:00
Maksim Masalski
78ba2ec830 coding guidelines: add to function prototypes form named parameters
Function types shall be in prototype form with named parameters

Found as a coding guideline violation (MISRA R8.2) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-06-04 16:20:06 -05:00
Stephanos Ioannidis
182417f32f lib: newlib: Add minimum required heap size config
This commit adds a new `CONFIG_NEWLIB_MIN_REQUIRED_HEAP_SIZE` config
that allows user to specify the minimum required heap size for the
newlib heap, and makes `malloc_prepare` validate that the memory space
available for the newlib heap is greater than this value.

The default minimum required heap size values were empiricially
determined, so as to allow the basic standard C functions such as
`printf` and `scanf` to work properly.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-06-02 08:50:45 -05:00
Aurelien Jarno
9fdd3f2bac lib: newlib: fix _gettimeofday hook
The time() function works correctly with the minimal libc, but always
returns -1 with the newlib libc. This is due to the _gettimeofday hook
being implemented that way.

Fix that by calling gettimeofday in the _gettimeofday hook instead of
returning -1.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2021-05-28 11:37:19 -05:00
Maksim Masalski
9867ac2a40 posix: pthread_exit: check for null before dereferencing
In a primitive SYS_SLIST_FOR_EACH_NODE check for null was
after dereferencing. Place check for null of the "thread_spec_data"
before its dereferencing.

Found as a coding guideline violation (MISRA R4.1) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-05-27 09:07:57 -05:00
Maksim Masalski
7711435347 lib: remove redundant check for null
Statement "cont = dropped_item != NULL" first checks if "dropped_item"
returns null or not null, then assigns to "cont".
If "dropped_item" is null then "cont = 0",
if "dropped_item" is not null then "cont = 1".

As a result in line below no need to check "dropped_item" again
It is enough to check state of the "cont" variable,
to be sure what returned "dropped_item".

Found as a coding guideline violation (MISRA R4.1) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-05-26 08:29:20 -05:00
Maksim Masalski
f18b728a4c heap: create unique variable name
In code is a variable "chunksz_t chunksz" that has the same name as
function "chunksz_t chunksz()" in the one heap.h file.
Create unique variable name to avoid misreading in the future.

Found as a coding guideline violation (MISRA R5.9) by static
coding scanning tool.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-05-25 19:06:06 -04:00
Watson Zeng
79fb3b7ccc libc: minimal: mwdt: define __INT*_C() and __UINT*_C()
Our minimal C library makes an alias of UINT*_C() to
be __UINT*_C() and INT*_C() to __INT*_C(). However,
in mwdt, these are not defined by default, so define
them ourselves. We have similar fix for xcc: #31962

Signed-off-by: Watson Zeng <zhiwei@synopsys.com>
2021-05-25 12:55:48 -05:00
Andy Ross
d37370301c k_heap: Clamp to a minimum heap size
The K_HEAP_DEFINE macro would allow users to specify heaps that are
too small, leading to potential corruption events (though at least
there were __ASSERTs that would catch this at runtime if enabled).

It would be nice to put the logic to compute this value into the heap
code, but that isn't available in kernel.h (and we don't want to pull
it in as this header is already WAY to thick).  So instead we just
hand-compute and document the choice.  We can address bitrot problems
with a test.

(Tweaks to heap size asserts and correct size bounds from Nicolas Pitre)

Fixes #33009

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2021-05-20 17:52:21 -04:00
Anas Nashif
1e74ddd709 kernel: remove dead workq code
work_q.c is not being built or used, it was replaced by user_work.c
which now has k_work_user_queue_start.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-05-18 11:21:27 -05:00
Carles Cufi
14b358a252 libc: minimal: Add EOVERFLOW
Add the EOVERFLOW error number, which is already in use by some of
Zephyr's modules.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2021-05-17 09:11:15 -04:00
Carles Cufi
1e26e08a92 libc: minimal: Add doxygen formatting to errno.h
Format the file so it can be processed by Doxygen.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2021-05-17 09:11:15 -04:00
Carles Cufi
165def7ea6 libc: minimal: Align errno.h values with newlib
In order to be able to document the error codes with Doxygen and
Breathe, start by aligning the macro values to those provided by newlib
in include/sys/errno.h:

https://github.com/zephyrproject-rtos/newlib-cygwin/blob/zephyr-newlib-4.1.0/newlib/libc/include/sys/errno.h

Also get rid of the (unused and untrue) ERRMAX definition.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2021-05-17 09:11:15 -04:00
Stephanos Ioannidis
1ff6664e98 lib: newlib: Remove internal _sbrk lock
This commit removes the lock inside the newlib internal `_sbrk`
function, which is called by `malloc` when additional heap memory is
needed.

This lock is no longer required because any calls to the `malloc`
function are synchronised by the `__malloc_lock` and `__malloc_unlock`
functions.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-05-13 07:30:43 -05:00
Stephanos Ioannidis
b0e690ac1e lib: newlib: Add malloc lock
This commit adds a lock implementation for the newlib heap memory
management functions (`malloc` and `free`).

The `__malloc_lock` and `__malloc_unlock` functions are called by the
newlib `malloc` and `free` functions to synchronise access to the heap
region.

Without this lock, making use of the `malloc` and `free` functions from
multiple threads will result in the corruption of the heap region.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2021-05-13 07:30:43 -05:00
Maksim Masalski
dbfa5a04de coding guidelines 11.9: fix literal zero as the null-ptr-constant
File has next violations:
MISRA 11_9_a
Use NULL instead of literal zero (0) as the null-pointer-constant
MISRA 11_9_b
Literal zero (0) shall not be used as the null-pointer-constant

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2021-05-12 21:51:40 -04:00
Maksim Masalski
136c9424c5 coding guidelines 10.4: casting operands to have same types
File zephyr/lib/os/cbprintf_nano.c had operands with different types.
It caused Rule 10.4 violation.
Both operands of an operator in which the usual arithmetic conversions
are performed shall have the same essential type category.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>

coding guidelines 10.4: casting operands to have same types

File zephyr/lib/os/cbprintf_nano.c had operands with different types.
It caused Rule 10.4 violation.
Both operands of an operator in which the usual arithmetic conversions
are performed shall have the same essential type category.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>

removed cast to int
2021-05-08 12:32:15 +02:00
Evgeniy Paltsev
6afe7c5fd2 ARC: prepare for building for ARCv3 HS6x
Do basic preparations for building code for ARCv3 HS6x
* add ISA_ARCV3 and CPU_HS6X config options
* add off_t type support for __ARC64__
* use elf64-littlearc format for linking
* use arc64 mcpu for CPU_HS6X

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2021-05-07 14:55:49 -05:00
Daniel Leung
ff407fb922 sys: introduce bit arrays
This introduces bit arrays as a new data type. This is different
than sys_bitfield as it is working on raw arrays of 32-bit
data. The bit arrays encode additional data inside the struct
to avoid going beyond the declared number of bits, and also
provides locking.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2021-05-07 13:36:22 -04:00
Krzysztof Chruscinski
edc3c87c72 lib: os: mpsc_buf: Allow dropping of skip packets in no overwrite
Previously, when no overwrite mode was used and there was no space
no packet was dropped. However, it should be allowed to drop skip
packet that may be added as padding at the end of the buffer.
Extended dropping scheme to drop skip packets in no overwrite mode.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-05-06 15:40:05 +02:00
Krzysztof Chruscinski
7825487334 lib: os: mpsc_pbuf: Add guard for oversized allocation
Added early return from mpsc_pbuf_alloc when requested size
exceed the buffer capacity. Previously, in that case buffer
was falling into endless loop.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-05-06 15:40:05 +02:00
Guennadi Liakhovetski
91d90df2a7 p4wq: add support for per-CPU, per-queue and delayed threads
Currently P4WQ supports queues with sets of user-provided
worked threads of arbitrary numbers. These threads are started
immediately upon initialisation.

This patch adds support for 3 more thread implementation options:

1. queue per thread. It adds a K_P4WQ_ARRAY_DEFINE() macro which
   initialises an array of queues and threads of the same number.
   These threads are then uniquely assigned to respective queues.
2. delayed start. With this option threads aren't started
   immediately upon queue initialisation. Instead a new function
   k_p4wq_enable_static_thread() has to be called to enable those
   threads individually.
3. queue per CPU. With this option the user can assign CPU masks
   to threads when calling k_p4wq_enable_static_thread().
   Otherwise the cpu_mask parameter to that function is ignored.
   Currently enabling this option implies option 2 above. Also so
   far to enable queues per CPU the user has to use
   K_P4WQ_ARRAY_DEFINE(), which means this option also implies 1
   above, but both these restrictions can be relaxed in the
   future if required.

Signed-off-by: Guennadi Liakhovetski <guennadi.liakhovetski@linux.intel.com>
2021-05-03 17:13:01 -04:00
Guennadi Liakhovetski
56610bdafb p4wq: fix races when handling work items
Work items in P4WQ currently belong to the user before submission
and after exit from the handler, therefore, unless the handler
re-submits the item, accessing it in p4wq_loop() in such cases
is racy. To fix this we re-define work item ownership. Now the
item belongs to the P4WQ core until the user calls
k_p4wq_wait(). If the work item has its .sync flag set, the
function will sleep until the handler completes processing the
work item or until the timeout expires. If .sync isn't set and
the handler hasn't processed the item yet, the function returns
-EBUSY.

Signed-off-by: Guennadi Liakhovetski <guennadi.liakhovetski@linux.intel.com>
2021-05-03 17:13:01 -04:00
Guennadi Liakhovetski
a4b88193cc p4wq: fix initialisation with SMP disabled
When SMP is disabled, the SMP initialisation level is
undefined, therefore a different level must be used.

Signed-off-by: Guennadi Liakhovetski <guennadi.liakhovetski@linux.intel.com>
2021-05-03 17:13:01 -04:00
Daniel Leung
143a18b36b lib: os: assign sys_notify callback default to NULL...
...instead of numeric zero.

Current usage violates MISRA rule 11.9.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2021-04-29 07:16:37 -04:00
Jennifer Williams
b773ec1675 lib: os: cbprintf_complete: fix typo in cbvprintf width comment
This commit fixes a subtle typo - width instead of with.

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2021-04-29 07:14:39 -04:00
Gerard Marull-Paretas
a7e4ae5976 lib: os: reboot: misc cleanup
Remove redundant includes and out-of-date comment.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-04-28 20:34:00 -04:00
Gerard Marull-Paretas
f163bdb280 power: move reboot functionality to os lib
Reboot functionality has nothing to do with PM, so move it out to the
subsys/os folder.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2021-04-28 20:34:00 -04:00
Jennifer Williams
be5a3777ca lib: os: add final else where missing in onoff, p4wq, sem
onoff, p4wq, and sem had several places missing final else
statement in the if else if construct. This commit adds
else {} to comply with coding guideline 15.7.

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2021-04-28 20:28:19 -04:00
Jennifer Williams
9517b87d35 lib: os: add final else where missing in heap*
heap* had several places missing final else statement in the
if else if construct. This commit adds else {} to comply with
coding guideline 15.7.

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2021-04-28 20:28:19 -04:00
Jennifer Williams
254dfd4aba lib: os: add final else where missing in cbprintf_*
cbprintf_* had several places missing final elsestatement in the
if else if construct. This commit adds else {} to comply with
coding guideline 15.7.

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2021-04-28 20:28:19 -04:00
Daniel Leung
2c6da987cd lib/os: cbprintf_packaged: simplify rodata check
NIOS2 is using _image_rodata_start/_end in its linker script
to mark the boundaries of rodata. So they no loner need
special treatment.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2021-04-28 22:25:42 +02:00
Anas Nashif
b8312fab4c Revert "lib: os: various places fix missing final else"
This reverts commit 163b7f0d82.

This is causing test failures, see #34624

Fixes #34624

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-04-27 22:42:00 -04:00
Jennifer Williams
163b7f0d82 lib: os: various places fix missing final else
The lib/os/ had several places missing final else
statement in the if else if construct. This commit adds
else {} or simple refactor to comply with coding guideline 15.7.
- cbprintf_complete.c
- cbprintf_nano.c
- heap-validate.c
- heap.c
- onoff.c
- p4wq.c
- sem.c

Also resolves the checkpatch issue of comments should align * on
each line.

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2021-04-27 17:31:59 -04:00
Krzysztof Chruscinski
45baec2d5b lib: gui: lvgl: Fix logging macro usage
Logging macro is expecting a constant value.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-22 15:29:15 -05:00
Flavio Ceolin
3e38d5efad lib: rb: Fix violations to rule 12.1
Missing explicit parentheses on sub-expressions

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-04-20 15:50:49 -04:00
Flavio Ceolin
f83c004319 lib: rb: Fix violations to rule 14.4
get_child does not return an essentially boolean type, so it has to be
properly checked against a pointer.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-04-20 15:50:49 -04:00
Flavio Ceolin
81b5b030d5 lib: rb: Fix violation to rule 10.3
get_color return enum rb_color. Use this type to avoid
implicit conversion to int.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-04-20 15:50:49 -04:00
Flavio Ceolin
188bb6e160 lib: rb: Use types that indicate size and signedness
Fixes violations related with essential type model.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-04-20 15:50:49 -04:00
Anas Nashif
a15f32f58c portability: move cmsis APIs to subsys/portability
Move cmsis OS apis under subsystem/portability. Those are not libraries
and only serve to provide a level of abstraction using the CMSIS OS APIs
to existing Zephyr interfaces.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-04-20 08:45:05 -04:00
Krzysztof Chruscinski
f1bb20f6b4 logging: Adapt logger to support both versions
Adapted to be able to switch between v1 and v2.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-19 10:59:23 -04:00
Krzysztof Chruscinski
345d12e8e0 tests: lib: Add test for mpsc_pbuf
Added suite for multiple producer, single consumer packet buffer.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-19 10:59:23 -04:00
Krzysztof Chruscinski
1fd71ca043 lib: os: mpsc_pbuf: Add optional debug features
Added optional debug prints. Logging cannot be used because
mpsc pbuf is used by the logging.

Added option to clear packet memory after allocation. Option is
enabled in Kconfig.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-19 10:59:23 -04:00
Krzysztof Chruscinski
3a765f4384 lib: os: Add mpsc (multiple producer, single consumer) packet buffer
Added module for storing variable length packets in a ring buffer.
Implementation assumes multiple producing contexts and single consumer.

API provides zero copy functionality with alloc, commit, claim, free
scheme.

Additionally, there are functions optimized for storing single word
packets and packets consisting of a word and a pointer. Buffer can work
in two modes: saturation or overwriting the oldest packets when buffer
has no space to allocate for a new buffer.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-04-19 10:59:23 -04:00
Jukka Rissanen
dde03c6770 net: socket: Add locking to prevent concurrent access
The BSD API calls were not thread safe. Add locking to fix this.

Fixes #27032

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2021-04-15 07:16:51 -05:00
Jennifer Williams
efc78b5b46 lib: os: fix heap_print_info missing final else in construct
The if ... else if ... construct was missing the final else.
This commit refactors it to comply with coding guideline 15.7.
The logic is to check if used or free, and do not increment
for the reserved chunks (first/last) in the heap.

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2021-04-14 09:20:20 -04:00
Jordan Yates
a4afedb02a sys: ring_buffer: allow NULL data buffers
Allow NULL data buffers to be provided to `ring_buf_get` and
`ring_buf_item_get`, in which case data will be discarded instead of
copied out to the user.

Fixes #33488.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2021-04-09 13:19:30 +02:00
Anas Nashif
0ec3774bde userspace: rename _is_user_context -> k_is_user_context
This functions is being called across the tree, no reason why it should
not be a public API.

The current usage violates a few MISRA rules.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-04-01 05:34:17 -04:00
David Leach
dca4397e08 subsys/cmsis_v1: Fix unitialized struct coverity error
Fixes #33060

Signed-off-by: David Leach <david.leach@nxp.com>
2021-04-01 04:52:10 -04:00
Carlo Caione
3539c2fbb3 arm/arm64: Make ARM64 a standalone architecture
Split ARM and ARM64 architectures.

Details:

- CONFIG_ARM64 is decoupled from CONFIG_ARM (not a subset anymore)
- Arch and include AArch64 files are in a dedicated directory
  (arch/arm64 and include/arch/arm64)
- AArch64 boards and SoC are moved to soc/arm64 and boards/arm64
- AArch64-specific DTS files are moved to dts/arm64
- The A72 support for the bcm_vk/viper board is moved in the
  boards/bcm_vk/viper directory

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2021-03-31 10:34:33 -05:00
Nicolas Pitre
7b6a4da206 libc/minimal: assorted fixes to malloc() and friends
- When malloc() is called with a size of 0 we should not set errno
  to ENOMEM as there is no actual allocation failure in that case.
  This duplicates the realloc() behavior.

- Put unlock_ret assignments on separate lines, otherwise gcc complains
  about unused variables when the tests on it are disabled.

- There NULL return added in 952970d6cb are completely pointless.
  First, there is no reason for sys_mutex_unlock() to fail, and even
  if it did, those returns would be blatent memory leaks. Remove them.
  No one should blindly modify code just to make static code
  analysers happy.

- Replace all CHECKIF() by explicit assertion statements to uniformize
  those checks and drop the NULL returns entirely. We can't return
  anything in the free() case, and there are no runtime conditions
  for sys_mutex_lock() to sometimes succeed and sometimes fail anyway.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-31 08:05:37 -04:00
Artur Lipowski
3b269bb033 lib: cmsis_rtos_v2: Fix timing and logic for osEventFlagsWait.
Consistently use ticks for timing purposes.
Fix retry logic.
Check flags when osFlagsWaitAll is not set.

Fixes #31103

Signed-off-by: Artur Lipowski <Artur.Lipowski@hidglobal.com>
2021-03-29 13:52:12 -04:00
Krzysztof Chruscinski
65474d8d67 lib: os: cbprintf: Improvements for sparc
Unified define used for handling sparc case in static and
runtime packaging. Reworked macro for storing argument in
static packaging.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-03-29 14:08:41 +02:00
Krzysztof Chruscinski
c26e08a51f lib: os: cbprintf: Add alignment offset to packaging
Added parameter to CBPRINTF_STATIC_PACKAGE which indicates buffer
alignment offset compared to CBPRINTF_PACKAGE_ALIGNMENT. When offset
is set to 0, macro assumes that input buffer is aligned to
CBPRINTF_PACKAGE_ALIGNMENT. When offset is positive, macro assumes
that buffer address is shifted by given number of bytes to
CBPRINTF_PACKAGE_ALIGNMENT alignment.

Extended cbprintf_package to use len argument as alignment offset
indicator when calculating length only (package pointer is null).

Features are not available for xtensa platform which seems to
require 16 byte alignment from the package. It is only an assumption
due to lack of the documentation and may be fixed in the future.

Feature allows to avoid unnecessary padding when package is part of
a message and preceeded by a header of a known size. For example,
message header on 32 bit architecture has 12 bytes, long doubles are
not used so cbprintf requires 8 byte alignment. Without alignment
offset indicator, package containing just a string with one argument
would need 4 byte padding after the header and 4 byte padding after
the package. Message would be 32 bytes long. With alignment offset
indication both paddings are not needed and message is only 24 bytes
long.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-03-29 14:08:41 +02:00
Anas Nashif
f5a1be80cd libc: strncat: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
841d6f3ba6 libc: malloc: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
05d7d32122 posix: timer: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
7c8d932e65 libc: gmtime_r: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
8415c94ab1 libc: printf/..: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
27af48417e libc: snprintf/..: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
0576a3d0e6 libc: fputs/puts: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Anas Nashif
4f52519c7e libc: strtol/strtoul: match implementation to declaration
The identifiers used in the declaration and definition of a function
shall be identical [MISRAC2012-RULE_8_3-b]

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-29 07:52:42 -04:00
Flavio Ceolin
9fd4ea91b7 coccinelle: Remove extra semicolon
coccicheck --mode=patch --cocci=semicolon.cocci

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2021-03-25 11:35:30 -05:00
Anas Nashif
52775ff263 kernel: rename reserved 'exp' symbol
This symbol is reserved and usage of reserved symbols violates the
coding guidelines. (MISRA 21.2)

NAME
       exp, expf, expl - base-e exponential function

SYNOPSIS
       #include <math.h>

       double exp(double x);

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-25 07:28:37 -04:00
Anas Nashif
1b6933d231 kernel: heap: rename 'free' and 'alloc'
This symbol is reserved and usage of reserved symbols violates the
coding guidelines. (MISRA 21.2)

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-25 07:28:37 -04:00
Anas Nashif
21d3225317 kernel: heap: rename resereved 'rewind'
This symbol is reserved and usage of reserved symbols violates the
coding guidelines. (MISRA 21.2)

NAME
   fgetpos, fseek, fsetpos, ftell, rewind - reposition a stream

SYNOPSIS
   #include <stdio.h>

   void rewind(FILE *stream);

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-25 07:28:37 -04:00
Anas Nashif
581214524a ring_buffer: rename resereved 'rewind' symbol
This symbol is reserved and usage of reserved symbols violates the
coding guidelines. (MISRA 21.2)

NAME
       fgetpos, fseek, fsetpos, ftell, rewind - reposition a stream

SYNOPSIS
       #include <stdio.h>

       void rewind(FILE *stream);

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-25 07:28:37 -04:00
Guðni Már Gilbert
952970d6cb lib: libc: minimal: add check on returned value
Fix #32938 [Coverity CID :219508] "Unchecked return value in
lib/libc/minimal/source/stdlib/malloc.c"

The Coverity complains about sys_mutex_lock() which returns 0 if
locked. I added also the same check on returned value for
sys_mutex_unlock() which returns 0 if unlocked.

Signed-off-by: Guðni Már Gilbert <gudni.m.g@gmail.com>
2021-03-23 12:13:00 +01:00
Anas Nashif
0ac3073d20 fdtable: fdtable: do not use tag name fd_entry
Do not reuse tag name (misra rule 5.7).

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-22 19:48:14 -04:00
Anas Nashif
5c90ceb105 clock: rename z_tick_get_32 -> sys_clock_tick_get_32
Do not use z_ for internal APIs, z_ is for private APIs within one
subsystem only.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-03-19 11:22:17 -04:00
Marcin Niestroj
064c6ef830 libc: minimal: implement time() API
Implement time() API by using clock_gettime(CLOCK_REALTIME, ...).

Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
2021-03-19 09:56:53 -04:00
Nicolas Pitre
b1eefc0c26 lib/os/heap: straighten up our type usage
The size_t usage, especially in struct z_heap_bucket made the heap
header almost 2x bigger than it needs to be on 64-bit systems.
This prompted me to clean up our type usage to make the code more
efficient and easier to understand. From now on:

- chunkid_t is for absolute chunk position measured in chunk units
- chunksz_t is for chunk sizes measured in chunk units
- size_t is for buffer sizes measured in bytes

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-18 19:33:39 -04:00
Nicolas Pitre
e919bb2d16 lib/os/heap: abstract conversion from chunk size to usable bytes
This is the reverse of bytes_to_chunksz().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-18 19:33:39 -04:00
Nicolas Pitre
f4e1611692 lib/os/heap: no need to over-mask
bmask already represents the intersection of h->avail_buckets and
wanted buckets.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-18 19:33:39 -04:00
Nicolas Pitre
a54e101a1e lib/os/heap: rename struct z_heap.len to struct z_heap.end_chunk
The end marker chunk was represented by the len field of struct z_heap.
It is now renamed to end_chunk to make it more obvious what it is.

And while at it...

Given that it is used in size_too_big() to cap the allocation size
already, we no longer need to test the bucket index against the
biggest index possible derived from end_chunk in alloc_chunk(). The
corresponding bucket_idx() call is relatively expensive on some
architectures so avoiding it (turning it into a CHECK() instead) is
a good thing.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-18 19:33:39 -04:00
Nicolas Pitre
e8910f629d lib/os/heap: document the reason behind the header field ordering
This is not obvious why the order is important when only looking at
the header file.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-18 19:33:39 -04:00
Nicolas Pitre
f2fd0e8bb6 lib/os/heap: make printed heap info more useful
Turn sys_heap_dump() into sys_heap_print_info() to better reflect
what it actually does, and improve the information being printed.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-03-16 16:06:53 +01:00
Ningx Zhao
7874052df2 lib/rbtree: Remove dead case in rb_remove()
This "else" clause was dead code, in a valid
tree it's not possible to have a node and
its child both be red.
Fix issue #33239.

Signed-off-by: Ningx Zhao <ningx.zhao@intel.com>
2021-03-13 06:49:08 -05:00
Krzysztof Chruscinski
9966d85c0a lib: os: cbprintf: Add alignment check to cbprintf_package
Added validation of alignment to cbprintf_package. Error is returned if
input buffer is not aligned to the largest argument.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-03-11 09:54:39 +01:00
Krzysztof Chruscinski
47a565367e lib: os: cbprintf: Add static packaging
Extend cbprintf with static packaging.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2021-03-11 09:54:39 +01:00
Guðni Már Gilbert
94f88e502f lib: os: Simplify z_impl_z_sys_mutex_kernel_unlock
Remove one redundant if() statement already included
with k_mutex_unlock()

Signed-off-by: Guðni Már Gilbert <gudni.m.g@gmail.com>
2021-03-10 05:42:06 -05:00
Nicolas Pitre
14e5e98822 lib: cbprintf: add support for deferred formatting
In applications like logging the call site where arguments to
formatting are available may not be suitable for performing the
formatting, e.g. when the output operation can sleep.  Add API that
supports capturing data that may be transient into a buffer that can
be saved, and API that then produces the output later using the
packaged arguments.

[ Documentation and commit log from Peter Bigot. ]

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-05 09:29:35 +01:00
Spoorthy Priya Yerabolu
6d10db3ed6 Coding guideline: Fixing code violations for 21.13 Rule
Any value passed to a function in <ctype.h> shall be
representable as an unsigned char or be the value EOF.

So changed type of variable to unsigned char.

Signed-off-by: Spoorthy Priya Yerabolu <spoorthy.priya.yerabolu@intel.com>
2021-03-05 10:53:13 +03:00
Peter Bigot
b706a5e999 kernel: remove old work queue implementation
Now that the old API has been reimplemented with the new API remove
the old implementation and its tests.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-03 20:06:00 -05:00
Peter Bigot
4e3b92609b kernel: provide functional equivalent to old userspace work queue API
The new API cannot be used from userspace because it is not merely a
wrapper around existing userspace-capable objects (threads and
queues), but instead requires much more complex and lower-level access
to memory that can't be touched from userspace.  The vast majority of
work queue users are operating from privileged mode, so there's little
motivation to go through the pain and complexity of converting all
functions to system calls.

Copy the necessary pieces of the existing userspace work queue API out
and expose them with new names and types:

* k_work_handler_t becomes k_work_user_handler_t
* k_work becomes k_work_user
* k_work_q becomes k_work_user_q

etc.  Because the replacement API cannot use the same types new API
names are also introduced to make it more clear that the userspace
work queue API is a separate functionality.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-03 20:06:00 -05:00
Peter Bigot
44539ed645 kernel: select work queue implementation
Attempts to reimplement the existing work API using a new work
implementation failed, primarily due to heavy use of whitebox testing
in validating the original API.  Add a temporary Kconfig that will
select between the two implementations so we can use the same
identifiers but select which implementation they reference.

This commit just adds the selection infrastructure and uses it to
conditionalize the existing implementation in anticipation of the new
one in the next commit.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-03-03 20:06:00 -05:00
James Harris
c7bb423f3e kernel: fix race conditions with z_ready_thread
Several internal APIs wrote thread attributes (return value, mainly)
_after_ calling `z_ready_thread`. This is unsafe, at least in SMP,
because another core could have already picked up and run the thread.

Fixes #32800.

Signed-off-by: James Harris <james.harris@intel.com>
2021-03-03 13:54:47 -05:00
Rajavardhan Gundi
4269ecd2bc lib: os: Introduce support for CRC32C algorithm
This introduces the support for CRC32C (Castagnoli) algorithm.
The generator polynomial used is 0x1EDC6F41UL.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2021-03-02 14:08:30 +01:00
Jakub Rzeszutko
ddb07f57ec lib: add freebsd getopt library
This library is going to be used by the shell module. Some shell users
are not satisfied with subcommands alone and need to use the options
for commands as well.

Signed-off-by: Jakub Rzeszutko <jakub.rzeszutko@nordicsemi.no>
2021-03-01 09:50:32 -05:00
Jakub Rzeszutko
72dd5a5c68 lib: move fnmatch to lib/util
We expect to have more libraries with incopatible license. There must
be a common place for such software. It seems that lib/util is good
place for that.

Signed-off-by: Jakub Rzeszutko <jakub.rzeszutko@nordicsemi.no>
2021-03-01 09:50:32 -05:00
Nicolas Pitre
fb73ac392c lib/os/cbprintf_nano.c: several improvements
This makes cbprintf_nano.c much closer to the standard printf and
therefore more useful. The following are now implemented:

- right justification for everything (only for numbers previously)
- precision value for numbers, chars and strings
- width/precision passed as arguments with *
- "unlimited" padding length
- lower/uppercase hex output
- the #, + and ' ' flags are supported

And the code was heavily reworked to reduce its size as much as
possible to mitigate the size growth. Still, the binary resulting
from cbprintf_nano.c is now between 10% and 20% bigger depending on
the architecture. This is still far smaller than cbprintf_complete.c
which remains about twice as big on average even without FP support.

Many unit tests that were skipped with CONFIG_CBPRINTF_NANO are now
enabled, and a few more were added for good measure.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-23 19:39:59 +01:00
Nicolas Pitre
7a91cf0176 Revert "lib/os/heap: introduce option to force big heap mode"
This reverts commit b6b6d39bb6.

With both commit 4690b8d5ec ("libc/minimal: fix malloc() allocated
memory alignment") and commit c822e0abbd ("libc/minimal: fix
realloc() allocated memory alignment") in place, there is no longer
a need for enforcing the big heap mode on every allocations.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-19 07:32:22 -05:00
Andy Ross
9a594a0c1a lib/p4wq: Fix race with completed work items
Work items can be legally resubmitted from within their own handler.
Currently the p4wq detects this case by checking their thread field to
see if it's been set to NULL.  But that's a race, because if the item
was NOT resubmitted then it no longer belongs to the queue and may
have been freed or reused or otherwise clobbered legally by user code.

Instead, steal a single bit in the thread struct for this purpose.
This patch adds a K_CALLBACK_STATE bit in user_options and documents
it in such a way (as being intended for "callback manager" utilities)
that it can't be used recursively or otherwise collide.

Fixes #32052

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2021-02-14 18:17:28 -05:00
Anas Nashif
5d1c535fc8 license: add missing SPDX headers
Add SPDX header to files with existing license.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-02-11 08:05:16 -05:00
Nicolas Pitre
e539bb1979 libc/minimal: restore proper locking for malloc() and friends
Commit 40016a6a92 ("libc/minimal: Use a sys_heap for the malloc
implementation") replaced sys_mem_pool_alloc() with sys_heap_alloc().
The problem is that those aren't equivalent. While the former did
guard against concurrent usage, the later doesn't.

Add the same locking around sys_heap_alloc() that used to be implicit
with sys_mem_pool_alloc().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-08 12:40:16 -05:00
Andrzej Puzdrowski
68a5ec3cb2 lib/gui/lvgl: Add fs_dir_t type variable initialization …
The commit adds initialization of fs_dir_t variables in preparation
for fs_opendir function change that will require fs_dir_t object, passed
to the function, to be initialized before first usage.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
2021-02-05 07:32:20 -05:00
Andrzej Puzdrowski
8339da6da6 lib/posix/fs: Add fs_dir_t type variable initialization
The commit adds initialization of fs_dir_t variables in preparation
for fs_opendir function change that will require fs_dir_t object, passed
to the function, to be initialized before first usage.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
2021-02-05 07:32:20 -05:00
Nicolas Pitre
47de5a0591 libc/minimal: fix realloc() failure case
It is said that the C17 realloc() behavior is to return the original
pointer on error and that's what is implemented here. This may be
confused with a successful realloc() and nobody else does that.

Instead, a failed realloc() should return NULL, leave the original
memory intact and set errno to ENOMEM. This is the behavior described
by all the following references:

Linux/glibc:
https://man7.org/linux/man-pages/man3/malloc.3.html

NetBSD
https://man.netbsd.org/realloc.3

Microsoft
https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/realloc

Mac OS X
https://developer.apple.com/library/archive/documentation/System/\
Conceptual/ManPages_iPhoneOS/man3/reallocf.3.html

Open Group Base Specifications Issue 6
https://pubs.opengroup.org/onlinepubs/009604599/functions/realloc.html

PTC MKS Toolkit
https://www.mkssoftware.com/docs/man3/realloc.3.asp

Let's get in line with the most common behavior.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-02 19:08:24 -05:00
Nicolas Pitre
593997046b lib/os/heap: fix out-of-bounds usage of memcpy() in sys_heap_realloc()
The sys_heap_realloc() code falls back to allocating new memory
and copying the existing data over when it cannot adjust the size
in place. However the size of the data to copy should be the old
size and not the new size if we're extending the allocation.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-02 19:08:24 -05:00
Nicolas Pitre
c822e0abbd libc/minimal: fix realloc() allocated memory alignment
The definition for realloc() says that it should return a pointer
to the allocated memory which is suitably aligned for any built-in
type.

Turn sys_heap_realloc() into a sys_heap_aligned_realloc() and use it
with __alignof__(z_max_align_t) to implement realloc() with proper
memory alignment for any platform.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-02 19:08:24 -05:00
Nicolas Pitre
4690b8d5ec libc/minimal: fix malloc() allocated memory alignment
The definition for malloc() says that it should return a pointer
to the allocated memory which is suitably aligned for any built-in
type. This requirement was lost in commit 0c15627cc1 ("lib: Remove
sys_mem_pool implementation") where the entire memory pool used to
have an explicit alignment of 16.

Fix this by allocating memory with sys_heap_aligned_alloc() using
__alignof__(z_max_align_t) which will automatically get the needed
alignment on each platform.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-02-02 19:08:24 -05:00
Dominik Ermel
ba3b1ba3d5 posix: Add fs_file_t type variable initializations
The commit adds initializations of fs_file_t variables in preparation
for fs_open function change that will require fs_file_t object, passed
to the function, to be initialized before first usage.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
2021-01-29 08:04:51 -05:00
Peter Bigot
10180af38d lib: cbprintf: avoid referencing distinct union fields in a statement
An assignment from one multi-word union field to another was not safe
from corruption.  Copy the value out to a local value before storing it
to the preferred union field.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-27 16:45:38 -05:00
Peter Bigot
8528e45897 lib: cbprintf: add libc f/printf substitutes
This allows applications that may not use minimal libc avoid the cost
of a second printf-like formatting infrastructure by using printfcb()
instead of printf() for output.  It also helps make sure that the
formatting support (e.g. floats) is consistent between user-directed
output and the logging infrastructure.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-27 13:34:06 -05:00
Peter Bigot
98747abf9c libc: minimal: add putchar
Provide putc and putchar wrappers around fputc.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-27 13:34:06 -05:00
Klaus H. Sorensen
4e7b5769bd lib: crc32_sw: 4 bit at a time implementation
Calculate crc32 4 bits at a time. The return value of the calculation is
identical to the previous 1 bit at a time implementation.

Results in a speed up of a factor 3 at the cost of using 64 bytes of
flash for a crc table.

Calculating crc32 of 128kB of flash on a 120MHz Kinetis MKE16F512
Cortex-M4 takes 99ms using the 1 bit at a time implementation, and 30ms
using the 4 bits at a time implementation.

The crc32 routine is used by subsys/canbus/canopen/canopen_program.c to
calculate crc of flash images.

Signed-off-by: Klaus H. Sorensen <khso@vestas.com>
2021-01-24 14:24:48 -05:00
Martin Åberg
b6b6d39bb6 lib/os/heap: introduce option to force big heap mode
This option allows forcing big heap mode. Useful on for getting 8-byte
aligned blocks on 32-bit machines.

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2021-01-24 10:11:11 -05:00
Martin Åberg
180ce491ad libc/minimal: reallocarray() in terms of realloc()
reallocarray() is defined in terms of realloc(). From OpenBSD manual
pages:
    "Designed for safe allocation of arrays, the reallocarray()
    function is similar to realloc() except it operates on nmemb
    members of size size and checks for integer overflow in the
    calculation nmemb * size."

The return value of sys_heap_realloc() is not compatible with that
of realloc().

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2021-01-24 10:11:11 -05:00
Andrew Boie
e2b62b8abb newlib: clamp max heap size on MMU systems
Previously, newlib claimed all free physical memory in the
system.

Now, the kernel manages this, allowing for memory to be
used via k_mem_map() calls.

Establish an upper bound to how much newlib will try to
claim on system startup, instead of trying to take all
of it, allowing other parts of the system to also map
anonymous memory.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2021-01-23 19:47:23 -05:00
Andrew Boie
b01177156f newlib: memory-map the heap, cleanups
We now draw heap memory from an anonymous memory mapping
instead of a hard-coded region past the kernel image,
which is no longer mapped by default.

Some readability cleanups were made to a particuarly
horrible set of nested ifdefs. A few types were adjusted.

sbrk()'s count argument is an intptr_t, not an int.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2021-01-23 19:47:23 -05:00
Nicholas Lowell
ce480e8577 posix: clock: nanosecond resolution
directly convert ticks to nsecs in the clock_* posix
functions which will provide the best resolution the
system allows

Signed-off-by: Nicholas Lowell <nlowell@lexmark.com>
2021-01-22 12:37:58 -05:00
Nicolas Pitre
a2011d8af9 z_heap_aligned_alloc(): avoid memory wastage
The strategy used in z_heap_aligned_alloc() was to allocate an extra
align-sized memory block for storing a pointer to the memory heap.
This is wasteful in terms of memory usage when alignment is larger
than a pointer width. A loop is needed to find the initial memory
start when freeing it which isn't optimal either.

Instead, let's have sys_heap_aligned_alloc() rewind a pointer after
it is aligned to make just enough room for storing our heap reference.
This way the heap reference is always located immediately before the
aligned memory and any unused memory is returned to the heap.

The rewind and alignment values may coincide in which case only
the alignment is necessary anyway.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-01-22 10:04:43 -05:00
Anas Nashif
ee599d88c3 Revert "newlib: memory-map the heap, cleanups"
This reverts commit bf91269738.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-01-22 08:39:45 -05:00
Anas Nashif
808303c5f4 Revert "newlib: clamp max heap size on MMU systems"
This reverts commit e966244de2.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2021-01-22 08:39:45 -05:00
Andrew Boie
e966244de2 newlib: clamp max heap size on MMU systems
Previously, newlib claimed all free physical memory in the
system.

Now, the kernel manages this, allowing for memory to be
used via k_mem_map() calls.

Establish an upper bound to how much newlib will try to
claim on system startup, instead of trying to take all
of it, allowing other parts of the system to also map
anonymous memory.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2021-01-21 16:47:00 -05:00
Andrew Boie
bf91269738 newlib: memory-map the heap, cleanups
We now draw heap memory from an anonymous memory mapping
instead of a hard-coded region past the kernel image,
which is no longer mapped by default.

Some readability cleanups were made to a particuarly
horrible set of nested ifdefs. A few types were adjusted.

sbrk()'s count argument is an intptr_t, not an int.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2021-01-21 16:47:00 -05:00
Peter Bigot
ee7c9f7fe8 libc: minimal: add INTn_C macros to stdint.h
Macros like INT64_C(x) convert x to a constant integral expression,
i.e. one that can be used in preprocessor code.  Implement wrappers
that use the GNUC intrinsics to perform the translation.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-21 14:50:01 -05:00
Rohit Gujarathi
f023df581f drivers: display: Added support for restricted update.
Added support for restricted updating of monochrome
displays.

Signed-off-by: Rohit Gujarathi <gujju.rohit@gmail.com>
2021-01-21 17:26:37 +01:00
Peter A. Bigot
f6d7595d4e lib/timeutil: add utilities to manage local/reference clock alignment
Provide data structures to capture a timestamp in two different
clocks, monitor the drift between those clocks, and using a base
instant with estimated drift convert between the clocks.

This provides the core technology to convert between system uptime and
an external continuous time scale like TAI (UTC without applying leap
seconds).

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2021-01-20 16:38:56 -05:00
Nicolas Pitre
f436315e02 lib/os/heap: guard against arithmetic overflows
Let's do it upfront only once for each entry point and dispense
with overflow checks later to keep the code simple.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-01-20 14:15:44 -05:00
Torsten Rasmussen
da3726006b cmake: newlib linking flags -lc and -lgcc circular dependency
Fixes: #28650

Linking with newlib now defines the following linker flags as:
```
${CMAKE_C_LINKER_WRAPPER_FLAG}${CMAKE_LINK_LIBRARY_FLAG}c
${CMAKE_C_LINKER_WRAPPER_FLAG}${CMAKE_LINK_LIBRARY_FLAG}gcc
c
```

This is needed because when linking with newlib on aarch64, then libgcc
has a link dependency to libc (strchr), but libc also has dependencies
to libgcc.

CMake is capable of handling circular link dependencies for CMake
defined static libraries, which can be further controlled using
`LINK_INTERFACE_MULTIPLICITY`.

However, libc and libgcc are not regular CMake libraries, and is seen as
linker flags by CMake, and thus symbol de-duplications will be
performed.

CMake link options cannot be used, as that will place those libs first
on the linker invocation. -Wl,--start-group is problematic as the
placement of -lc and -lgcc is not guaranteed in case later libraries are
also using -lc / -libbgcc as interface linker flags.

Thus, we resort to use
`${CMAKE_C_LINKER_WRAPPER_FLAG}${CMAKE_LINK_LIBRARY_FLAG}`
as this ensures the uniqueness and thus avoids symbol de-duplication
which means libc will be followed by libgcc, which is finally followed
by libc again.

It would have been possible to use `-lc` directly, but there is a risk
that an externally library is also adding `-lc` and thus de-duplication
and re-arrangement of this flag happens. This risk is in theory also
existing with this fix, but the long nature of this link flag with using
`${CMAKE_C_LINKER_WRAPPER_FLAG}` would likely indicate a similar fix and
thus those libraries will stay in order.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2021-01-20 09:25:38 -05:00
Eugeniy Paltsev
74c4d5ae2a libc: minimal: stdout: fix fputs return value
The 'fputs' has flaw in the implementation. It almost always
returns 'EOF' even if completed successfully.
This happens because we compare 'fwrite' return value which is
"number of members successfully written" (which is 1 in current
implementation) to the total string size:

----------------------------->8-----------------------
int fputs(const char *_MLIBC_RESTRICT string,
          FILE *_MLIBC_RESTRICT stream)
{
	int len = strlen(string);
	int ret;

	ret = fwrite(string, len, 1, stream);

	return len == ret ? 0 : EOF;
}
----------------------------->8-----------------------

In result 'fputs' return 'EOF' in case of string length bigger
than 1.

There are several fixes possible, and one of the fixes is to
swap number of items (1) with size (string length) when we
are calling 'fwrite'. The only difference will be that
'fwrite' will return actual numbers of bytes written which
can be compared with the string length.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
2021-01-19 23:03:12 -05:00
Ningx Zhao
36d83a5156 tests: ringbuffer: code coverage improvements
Add double macros to remove the __week function
when calculating coverage.

Signed-off-by: Ningx Zhao <ningx.zhao@intel.com>
2021-01-18 23:12:47 -05:00
Nicolas Pitre
7a22a4bdf6 heap: clean up some size related issues
First, the maximum heap size must fit in 31 bits worth of chunks
because the internal 32-bit field holding the size is shared with
the `used` bit.

Then the mention of a 256-byte block in the doc is no longer
relevant. That pertained to the previous allocator implementation.

And ditto for the HEAP_MEM_POOL_MIN_SIZE kconfig option.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-01-15 12:08:20 -05:00
Andy Ross
d2eadfa162 lib/os: P4 Work Queue: Pooled Parallel Preemptible Priority-based
This adds a somewhat special purpose IPC mechanism.  It's intended for
applications which have a "work queue" like architecture of discrete
callback items, but which need the ability to schedule those items
independently in separate threads across multiple CPUs.  So P4 Work
items:

1. Can run at any Zephyr scheduler priority and with any deadline
   (this feature assumes EDF scheduling is enabled)

2. Can be submitted at any time and from any context, including being
   resubmitted from within their own handler.

3. Will preempt any lower priority work as soon as they are runnable,
   according to the standard rules of Zephyr priority scheduling.

4. Run from a pool of worker threads that can be allocated efficiently
   (i.e. you need as many as the number of CPUs plus the number of
   preempted in-progress items, but no more).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2021-01-15 11:35:50 -05:00
Peter Bigot
6297c667c5 lib: os: cbprintf: correct arg extraction of wide characters
The l length modifier can apply to the c format specifier; in that
case the expected value is of type wint_t.  Minimal libc doesn't
define wint_t, and it is complex to do so correctly (must add
<wchar.h>, and use a lot of conditional tricks).

wint_t can differ from wchar_t in rank when wchar_t undergoes default
integral promotion, which it does on xtensa (wchar_t is unsigned
short).  So we can use wchar_t as an approximation, except in va_arg
where we need to use a wider type: int covers this case.

Note that we still don't format wide characters, but we do want to
consume the correct amount of data for a default-promoted extended
character.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 14:02:06 +01:00
Peter Bigot
8eda19a898 lib: os: cbprintf: correctly handle signed vs unsigned char
Whether char is signed or unsigned is toolchain and target specific.
Rather than assume it's signed (which is true for x86, but not for
ARM), do the right thing based on whether the minimum representable
value is less than zero.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 14:02:06 +01:00
Peter Bigot
b036afba5a lib: cbprintf: document length modifiers
It may not be clear that the length modifiers reference native C types
with specific ranks.  Document the core type for each modifier.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 14:02:06 +01:00
Peter Bigot
d12a99588b lib: cbprintf: remove cbprintf_arglen
This function was designed to support the logging infrastructure's
need to copy values from va_list structures.  It did not meet that
need, since some values need to be changed based on additional data
that is only available when the complete format specification is
examined.  Remove the function as unnecessary.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 14:02:06 +01:00
Peter Bigot
0bc01822a2 lib: cbprintf: improve coverage
Providing a literal width or precision that exceeds the non-negative
range of int does not appear to be rejected by the standard, but it
does produce a build diagnostic so we can't test it.  Switch to an
equivalent form that doesn't affect line coverage.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-07 14:02:06 +01:00
Peter Bigot
9d14f72593 lib: libc: minimal: remove outdated comment
The referenced functions may not have been implemented back in 2015,
but they are now.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2021-01-04 20:39:16 -05:00
Nicolas Pitre
36f075847c lib/os/heap: always assert the align value argument
Just like commit 0ae04f01b6 ("lib/os/heap: make some checks more
assertive") we shouldn't validate the externally provided align
argument only when CONFIG_SYS_HEAP_VALIDATE is set.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-01-04 16:57:47 -08:00
Nicolas Pitre
aeda6ccdd8 lib/os/heap: fix realloc issues
If the new size amounts to the same number of chunks then:

- If right-chunk is used then we needlessly allocate new memory and
  copy data over.

- If right-chunk is free then we attempt to split it with a zero size
  which corrupts the prev/next list.

Make sure this case is properly handled and add a test for it.

While at it, let's simplify the code somewhat as well.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2021-01-04 11:12:05 -05:00
Nicolas Pitre
16fa1cf844 lib/os/heap: add missing realloc semantics
Need to handle those cases where a NULL pointer and/or 0 size
is provided.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-12-18 14:07:09 -05:00
Peter Bigot
53762239c1 lib: cbprintf: fix mishandling of precision string output
If a precision flag is included for s formatting that bounds the
maximum output length, so we need to use strnlen rather than strlen to
get the amount of data to emit.  With that flag we can't expect there
to be a terminating NUL following the text to print.

Also fix handling of an empty precision, which should behave as if a
precision of zero was provided.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-12-18 08:23:24 -05:00
Nicolas Pitre
cf6fb4dea2 lib: cbprintf: float conversion optimization and documentation
While documenting the float conversion code, I found there was room
for some optimization. In doing so I added test cases to cover edge
cases e.g. making sure proper rounding is applied and that no loss
of precision was introduced. Compiled code should be smaller and
faster.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-12-08 14:09:15 -05:00
Andy Ross
fcd392f6ce kernel: subsys: lib: drivers: Use k_heap instead of z_mem_pool wrappers
Use the core k_heap API pervasively within our tree instead of the
z_mem_pool wrapper that provided compatibility with the older mempool
implementation.

Almost all of this is straightforward swapping of one alloc/free call
for another.  In a few cases where code was holding onto an old-style
"mem_block" a local compatibility struct with a single field has been
swapped in to keep the invasiveness of the changes down.

Note that not all the relevant changes in this patch have in-tree test
coverage, though I validated that it all builds.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross
0c15627cc1 lib: Remove sys_mem_pool implementation
This has been replaced by sys_heap now and all dependencies are gone.
Remove.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross
40016a6a92 libc/minimal: Use a sys_heap for the malloc implementation
The older sys_mem_pool is going away and being replaced by a new
allocator.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross
40c1b55cc2 lib/os/heap: Add sys_heap_realloc()
Add an optimized realloc() implementation that can successfully expand
allocations in place if there exists enough free memory after the
supplied block.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross
6bc6a67b0e lib/gui/lvgl: Use a sys_heap and not a sys_mem_pool
The sys_mem_pool allocator is a legacy thing.  Use the standard heap
to reduce code size.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross
6965cf526d kernel: Deprecate k_mem_pool APIs
Mark all k_mem_pool APIs deprecated for future code.  Remaining
internal usage now uses equivalent "z_mem_pool" symbols instead.

Fixes #24358

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Nicolas Pitre
9dcd76a650 lib/os/heap: minimize initial overallocation in the aligned case
The biggest required padding is equal to `align - chunk_header_bytes`
and not `align - 1` given that the header already contributes to the
padding.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-11-30 14:50:07 -05:00
Krzysztof Chruscinski
3ed8083dc1 kernel: Cleanup logger setup in kernel files
Most of kernel files where declaring os module without providing
log level. Because of that default log level was used instead of
CONFIG_KERNEL_LOG_LEVEL.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2020-11-27 09:56:34 -05:00
Peter Bigot
c1b0cf8ec6 lib: cbprintf: work around LLVM code generation bug
LLVM building for qemu_x86 appears to have an optimization bug where a
union that is assigned to hold values read from va_args() is inferred
to be a constant value, so is placed in ROM with an all-zero content.

Prevent this by packing the conversion state and the value union into
a single container structure that's stack allocated.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-19 12:37:33 +01:00
Robin-Charles Guihéneuf
f0250d5c71 lvgl: kscan: Only process prev state if it has been updated
When no message was get from kscan_msgq queue, the prev state
(x/y point) was processed as a new state. During process its
coordinates could be inverted or modified, depending on the
LVGL_POINTER_KSCAN_SWAP_XY, LVGL_POINTER_KSCAN_INVERT_X,
LVGL_POINTER_KSCAN_INVERT_Y or display orientation configuration.
In these cases, it could cause wrong input data.

Signed-off-by: Robin-Charles Guihéneuf <robin-charles@hotmail.fr>
2020-11-19 12:36:31 +01:00
Anas Nashif
43989ca675 libc: add labs() and llabs()
Add support for abs with additional integer types.

This is needed to make LLVM quiet and stop warning about abs being used
with int64_t and such.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-11-19 08:41:56 +01:00
Peter Bigot
a9e2b10a86 lib: cbprintf: ignore l length modifier on float values
%lf is specified to be the same as %f, and should not be marked as
 invalid.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-17 17:49:22 -05:00
Marcin Niestroj
0d946b712b libc: minimal: print stderr just like stdout
So far data that went to stderr was simply dropped in case of minimal
libc. In case of newlib stderr was treated same like stdout
(e.g. fprintf(stderr, ...) was equivalent to fprintf(stdout, ...).

Extend filter on stream pointer to allow both stdout and stderr to pass
data to stdout hook (which is Zephyr console backend in most cases).

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-11-17 12:29:19 -08:00
Peter Bigot
607b390ba4 lib: cbprintf: fix pointer justification and padding
Although flags with pointers are not defined behavior, there is a
desire to have them work, so add a test and fix the complete
implementation so it passes.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-17 11:34:25 +01:00
Nicolas Pitre
d583af7707 lib/os/cbprintf_nano.c: simplifications and enhancements
Simplify the code to increase readability, and fix right-padding
for %p.

Also, the compiled code is smaller with those changes applied.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-11-17 11:34:25 +01:00
Martin Åberg
9feb799762 lib: cbprintf: improved %p specifier handling
This fixes an issue where the %p specifier always generated "(nil)"
on SPARC. The failing test cases were:
 tests/lib/sprintf/libraries.libc.sprintf
 tests/kernel/common/kernel.common.misra
 tests/kernel/common/kernel.common.tls
 tests/kernel/common/kernel.common

The exact logic behind the issue has not been fully analyzed, but
it can be observed that this commit eliminates one occurrence of
undefined behavior. (Only allowed to read the last union field written.)

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-13 14:53:55 -08:00
Martin Åberg
73b7dde833 cmsis: align buffer containing struct k_timer
The slab cmis_timer_slab is used to allocate objects of the type
"struct timer_obj", so it should be defined to use the compile-time
alignment requirement of "struct timer_obj", rather than 4.

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-13 14:53:55 -08:00
Martin Åberg
6f4bcf7933 libc: minimal: Add SPARC support
This commit defines the off_t type for SPARC.

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-13 14:53:55 -08:00
Martin Åberg
6d126e7481 lib/posix: SPARC newlib has unsigned short mode_t
This commit eliminates a compilation error by passing int to va_arg
rather than mode_t on SPARC.

Newlib sys/_types.h defines mode_t for SPARC as:
  typedef unsigned short __mode_t;

GCC 10.2.0 gave the following error message and suggested solution:

mqueue.c: In function 'mq_open':
mqueue.c:61:21: error: 'mode_t' {aka 'short unsigned int'} is promoted
 to 'int' when passed through '...' [-Werror]
   61 |   mode = va_arg(va, mode_t);
      |                     ^
mqueue.c:61:21: note: (so you should pass 'int' not 'mode_t' {aka 'short
unsigned int'} to 'va_arg')

Signed-off-by: Martin Åberg <martin.aberg@gaisler.com>
2020-11-13 14:53:55 -08:00
Peter Bigot
bb99422c8a lib/os: replace z_vprintk with cbprintf
Using the same implementation as the rest of Zephyr reduces code size.

Update options and expected results for formatting test.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-13 06:38:01 -05:00
Peter Bigot
18851d8ef9 libc/minimal: remove z_prf
All in-tree uses have been replaced by cbprintf, and the API was
private so there should be no out-of-tree users.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-13 06:38:01 -05:00
Peter Bigot
7cf9a8c102 libc: switch to cbprintf as basis for printf functionality
The minimal libc provided by Zephyr can use the Zephyr system
implementation rather than have its own implementation.

When combined with CBPRINTF_NANO some sprintf tests must be
skipped as they assume a more capable libc.  Add an overlay
that supports testing this non-default combination.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-13 06:38:01 -05:00
Peter Bigot
33103828dc lib: add cbprintf capability
This commit adds a C99 stdio value formatter capability where
generated text is emitted through a callback.  This allows generation
of arbitrarily long output without a buffer, functionality that is
core to printk, logging, and other system and application needs.

The formatter supports most C99 specifications, excluding:
* %Lf long double conversion
* wide character output

Kconfig options allow disabling features like floating-point
conversion if they are not necessary.  By default most conversions are
enabled.

The original z_vprintk() implementation is adapted to meet the
interface requirements of cbvprintf, and made available as an opt-in
feature for space-constrained applications that do not need full
formatting support.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-13 06:38:01 -05:00
Peter Bigot
abb3a28c94 Revert "shell: support floating point output with newlib"
This reverts commit e812ee6c21.

This is the initial step towards replacing the core Zephyr formatting
infrastructure with a common functionally-complete solution.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-13 06:38:01 -05:00
Peter Bigot
74fd3a8143 libc: minimal: add maximum integer typedefs
Use 64-bit as the maximum integer size.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-11-13 06:38:01 -05:00
Krzysztof Chruscinski
1e46bb3bb5 lib: os: ring_buffer: Allow using full buffer capacity
Previously, ring buffer had capacity of provided buffer size - 1. This
trick was used to distinguish between empty and full states. It had one
drawback: ring buffer could not be used as a pool of equal sized buffers
(using ring_buf_put_claim and ring_buf_get_claim).
Reworked internals to use non wrapping head and tail. Since they are
non wrapping, there is no issue with distinguishing between empty and
full. Since this appraoch would be vulnerable to wrapping on 32 bit
boundary, added a mechanism which periodically reduces all indexes to
avoid 32 bit wrapping.

After this rework, buffer has one byte more capacity. Simple test shows
slight performance improvement.

Updated tests to reflect increased capacity and added test to check if
it is possible to continuesly allocated 2 buffers of half ring buffer
size.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2020-11-11 13:17:49 +01:00
Andrew Boie
a29b31d800 libc: newlib: fix virtual memory arena size
The calculations need to be from the RAM base virtual
address and not the physical address.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-11-09 20:19:13 -05:00
Nicolas Pitre
a5c53d255c lib/os/prf.c: let the compiler optimize _ldiv5() on 64-bit architectures
The compiler doesn't need help here.

For example, gcc creates this on Aarch64:

_ldiv5:
        ldr     x1, [x0]
        mov     x2, -3689348814741910324
        movk    x2, 0xcccd, lsl 0
        add     x1, x1, 2
        umulh   x1, x1, x2
        lsr     x1, x1, 2
        str     x1, [x0]
        ret

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-11-09 13:23:25 -08:00
Nicolas Pitre
822dfbd012 lib/os/prf.c: alternate implementation for _ldiv5()
The _ldiv5() is an optimized divide-by-5 function that is smaller and
faster than the generic libgcc implementation.

Yet it can be made even smaller and faster with this replacement
implementation based on a reciprocal multiplication plus some tricks.

For example, here's the assembly from the original code on ARM:

_ldiv5:
        ldr     r3, [r0]
        movw    ip, #52429
        ldr     r1, [r0, #4]
        movt    ip, 52428
        adds    r3, r3, #2
        push    {r4, r5, r6, r7, lr}
        mov     lr, #0
        adc     r1, r1, lr
        adds    r2, lr, lr
        umull   r7, r6, ip, r1
        lsr     r6, r6, #2
        adc     r7, r6, r6
        adds    r2, r2, r2
        adc     r7, r7, r7
        adds    r2, r2, lr
        adc     r7, r7, r6
        subs    r3, r3, r2
        sbc     r7, r1, r7
        lsr     r2, r3, #3
        orr     r2, r2, r7, lsl #29
        umull   r2, r1, ip, r2
        lsr     r2, r1, #2
        lsr     r7, r1, #31
        lsl     r1, r2, #3
        adds    r4, lr, r1
        adc     r5, r6, r7
        adds    r2, r1, r1
        adds    r2, r2, r2
        adds    r2, r2, r1
        subs    r2, r3, r2
        umull   r3, r2, ip, r2
        lsr     r2, r2, #2
        adds    r4, r4, r2
        adc     r5, r5, #0
        strd    r4, [r0]
        pop     {r4, r5, r6, r7, pc}

And here's the resulting assembly with this commit applied:

_ldiv5:
        push    {r4, r5, r6, r7}
        movw    r4, #13107
        ldr     r6, [r0]
        movt    r4, 13107
        ldr     r1, [r0, #4]
        mov     r3, #0
        umull   r6, r7, r6, r4
        add     r2, r4, r4, lsl #1
        umull   r4, r5, r1, r4
        adds    r1, r6, r2
        adc     r2, r7, r2
        adds    ip, r6, r4
        adc     r1, r7, r5
        adds    r2, ip, r2
        adc     r2, r1, r3
        adds    r2, r4, r2
        adc     r3, r5, r3
        strd    r2, [r0]
        pop     {r4, r5, r6, r7}
        bx      lr

So we're down to 20 instructions from 36 initially, with only 2 umull
instructions instead of 3, and slightly smaller stack footprint.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-11-09 13:23:25 -08:00
Jan Van Winkel
7c8ef52648 lib: gui: lvgl: update to v7.6.1
Update LVGL to minor release 7.6.1

resolves: #29050

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2020-11-01 10:51:00 -05:00
Paul Sokolovsky
565228516c libc: minimal: Implement abort().
abort() is an important runtime function, oftentimes used to signal
abnormal execution conditions in generic applications. Worse, they
may be used under such circumstances in e.g. compiler support
libraries, in which case lack of implementation of this function
will lead to link error.

Fixes: #29541

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2020-10-28 17:02:16 +01:00
Daniel Leung
97db4ac0ca libc: add hidden option CONFIG_NEED_LIBC_MEM_PARTITION
The z_libc_partition was only enabled when newlib is being used,
and/or stack canaries are needed. This adds a hidden option
where this partition can be enabled if needed, regardless of
whether newlib is used or stack canaries are needed.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-10-24 10:52:00 -07:00
Nicolas Pitre
c227fe7b80 lib/os/heap: Correct aligned_alloc sizing for small heaps
The code that made aligned_alloc work with the 4-byte heap headers was
requesting a block of the correctly padded size, and correctly
aligning the output buffer within that memory, but it was using the
UNALIGNED chunk size for the buffer as the final size of the block
with splitting off the unused suffix.  So the final chunk in the
buffer was could be incorrectly returned to the heap and reused,
leading to overlap.

Compute the chunk size of the output buffer based on the
already-aligned output pointer instead.

Initial investigation and fix from Andy Ross <andrew.j.ross@intel.com>.
I reworked his fix, created a test case, and stolen his commit log.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-10-23 12:52:04 -04:00
Maksim Masalski
da3e834d58 lib: posix: unchecked return value while taking semaphore
Fixing of the false-positive Coveiry issue.
Stop Coverity from worrying about this case.

Signed-off-by: Maksim Masalski <maksim.masalski@intel.com>
2020-10-21 06:26:11 -05:00
Kumar Gala
cae988c697 lib: posix: eventfd: Fix use of 'struct k_spinlock_key'
Code should be using k_spinlock_key_t and not 'struct k_spinlock_key'.
With recent change to redefine struct k_spinlock_key we see this code
break because it wasn't using the correct type.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-10-07 08:11:25 -04:00
Arnaud Mouiche
7673baed84 libc: newlib: Avoid all files to be opened in line buffer mode
Default buffer mode is setup by fopen depending on isatty value.
Expect only 0, 1 & 2 to be tty for CONFIG_POSIX_API cases.

This way regular files are opened in block buffering mode (instead
of line buffering mode) which really speed up fread/fwrite
operations on FS.

Signed-off-by: Arnaud Mouiche <arnaud.mouiche@invoxia.com>
2020-10-05 09:59:38 -07:00
Arnaud Mouiche
fd9766c961 posix: fix missing _open for fopen support
Using fopen() in application failed to build when configured with
	CONFIG_NEWLIB_LIBC=y
	CONFIG_POSIX_API=y

Signed-off-by: Arnaud Mouiche <arnaud.mouiche@invoxia.com>
2020-10-05 09:59:38 -07:00
Xavier Chapron
824f423e54 misc: Replace assert include and calls by sys/__assert.h equivalent
Replace all calls to the assert macro that comes from libc by calls to
__ASSERT_NO_MSG(). This is usefull as the former might be different
depending on the libc used and the later can be customized to reduce
flash footprint.

Signed-off-by: Xavier Chapron <xavier.chapron@stimio.fr>
2020-10-02 11:42:40 +02:00
Rafał Kuźnia
5ead7e7b3b lib: posix: eventfd: general eventfd improvements
The eventfd implementation suffers from various shortcomings
and it is not thread safe.

This commit addresses the following aspects of eventfd:
* make read() and write() atomic in respect to each other
* POLLIN after creating eventfd with initval != 0 shall be set
* blocking and nonblocking modes shall have the same effect on poll()
* add support for POLLOUT

Signed-off-by: Rafał Kuźnia <rafal.kuznia@nordicsemi.no>
2020-10-02 11:34:19 +02:00
Christopher Friedt
3cdf718d5b lib: posix: nanosleep: round up to the nearest microsecond
We must round up to the nearest microsecond in order to fulfill the
nanosleep(2) API requirement of sleeping for *at least* that many
nanoseconds.

The only platform with an upper-bound check right now is Nordic.

Fixes #28483

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-10-02 11:31:43 +02:00
Aastha Grover
83b9f69755 code-guideline: Fixing code violation 10.4 Rule
Both operands of an operator in the arithmetic conversions
performed shall have the same essential type category.

Changes are related to converting the integer constants to the
unsigned integer constants

Signed-off-by: Aastha Grover <aastha.grover@intel.com>
2020-10-01 17:13:29 -04:00
Gerard Marull-Paretas
faf7736b14 lib: gui: lvgl: fix touch point rotation equations
When rotation is 90 or 270 degrees X and Y resolution values will also
be swapped, so we need to take that into account.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-09-24 13:50:25 -05:00
Lauren Murphy
25f9b643c7 lib: os: mempool: Fix unused return values from sys_mutex_lock calls
Fixes Coverity issues 210682 and 210686.

Fixes #25983
Fixes #25984

Signed-off-by: Lauren Murphy <lauren.murphy@intel.com>
2020-09-18 18:02:37 -04:00
Kumar Gala
59f76a291c lib: cmsis_rtos_v2: Handle possible zero length array
Change how we handle the case of
CONFIG_CMSIS_V2_THREAD_DYNAMIC_MAX_COUNT=0 so that we don't create
a zero length array.  Instead we can just ifdef out the code associated
with handling a dynamic stack allocation.

Fixes #28397

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-09-18 10:13:58 -05:00
Gerard Marull-Paretas
e8459719d8 lib: gui: lvgl: match kscan rotation with the display
Kscan coordinates are transformed in case display is rotated so that
frames of reference are aligned.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-09-16 12:02:52 +02:00
Gerard Marull-Paretas
b28ec03f0e lib: gui: lvgl: add support for kscan axes swap and inversion
Add new Kconfig options to allow kscan axes swap and inversion. These
options are useful to align display and touch frame of reference. If a
touch API is ever introduced these options could be moved there.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-09-16 12:02:52 +02:00
Grzegorz Kostka
cccb1908ac lib: fdtable: fix z_free_fd multiple calls fd leak
Multiple calls of z_free_fd against fd with refcount equal 0 are causing
descriptor table entry leak by decrementing refcount below 0.
This patch prevents decrementing refcount below zero.

Signed-off-by: Grzegorz Kostka <grzegorz@mobility.cloud>
2020-09-10 16:04:36 -05:00
Peter Bigot
6c910c021e lib: os: printk: fix printing unsigned 32-bit integers
The vararg extraction for unmodified integers always used int, which
sign extends when assigned to the printk_val_t.  Avoid the sign
extension for unsigned values.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-09-10 11:46:56 -05:00
Peter Bigot
b3f0c3b4d7 lib: os: prf: correct use of istype functions
Character class functions from ctype.h may be implemented as macros
where the argument is used to index an array of class flags.  Using a
char value as an index produces diagnostics in some toolchains.
Explicitly cast the parameter to the type required by the API.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-09-03 21:53:09 +02:00
Peter Bigot
e812ee6c21 shell: support floating point output with newlib
shell_fprintf requires that formatted output be emitted with a
putchar()-like output function.  Newlib does not provide such a
capability.  Zephyr provides two solutions: z_prf() which is part of
minimal libc and handles floating point formatting, and z_vprintk()
which is core and does not support floating point.

Move z_prf() out of minimal libc into the core lib area, and use it
unconditionally in the shell.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-09-03 21:53:09 +02:00
Flavio Ceolin
03d70b2ca3 lib: hex: Remove constant expression
Part of an else expression was constant, just removing it.

Code guideline rule 14.3

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-09-02 13:45:50 -04:00
Flavio Ceolin
1396e89e6c os: work_q: Use NULL instead of 0
Code guideline rule 11.9 says to use macro NULL for null pointers.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-09-02 13:45:50 -04:00
Tomasz Bursztyka
e18fcbba5a device: Const-ify all device driver instance pointers
Now that device_api attribute is unmodified at runtime, as well as all
the other attributes, it is possible to switch all device driver
instance to be constant.

A coccinelle rule is used for this:

@r_const_dev_1
  disable optional_qualifier
@
@@
-struct device *
+const struct device *

@r_const_dev_2
 disable optional_qualifier
@
@@
-struct device * const
+const struct device *

Fixes #27399

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-09-02 13:48:13 +02:00
Vincent Wan
0e436ed72a lib: fdtable: fix reference counting in z_reserve_fd()
The new fd entry should be reserved by incrementing its reference count
in z_reserve_fd() instead of z_finalize_fd() in order to avoid having
the same one being returned in a concurrent call. If for some reason
the fd is not finalized after z_reserve_fd() is called, it can be
freed via z_free_fd(), which would decrement the reference count.

Fixes #27721

Signed-off-by: Vincent Wan <vwan@ti.com>
2020-08-27 11:42:19 +03:00
Gerard Marull-Paretas
7538f0212f lib: gui: lvgl: improve cmake formatting
Improve the format of the CMakeLists.txt file.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-08-26 15:32:59 -05:00
Gerard Marull-Paretas
b3847e80c4 lib: gui: lvgl: sort objects
LVGL objects have been alphabetically sorted. The aim of this change is
to help locating objects as well as keeping track of them.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-08-26 15:32:59 -05:00
Gerard Marull-Paretas
948a692252 lib: gui: lvgl: split Kconfig settings
LVGL Kconfig settings have been splitted into more granular units in
order to improve readability and maintenance.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-08-26 15:32:59 -05:00
Gerard Marull-Paretas
4f86a9a2d5 lib: gui: lvgl: align all Kconfig object names
Align all Kconfig option names with LVGL names. The followed rule:
LV_(.*) -> CONFIG_LVGL_(.*).

Also replaced LVGL boolean configuration entries using if/else/endif
with direct IS_ENABLED macro.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-08-26 15:32:59 -05:00
Flavio Ceolin
0aaae4a039 guideline: Make explicit fallthrough cases
-Wimplicit-fallthrough=2 requires a fallthrough comment or a compiler
to tells gcc that this happens intentionally.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-08-24 20:28:47 -04:00
Anas Nashif
b4cd1c1a53 lib: mempool: alloc_bit_is_set is used only with asserts
Put it behind an ifdef CONFIG_ASSERT to make clang happy.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-08-19 06:57:40 -04:00
Siddharth Chandrasekaran
0637595ec5 libc: add strtok_r implementation
This is a standard function and useful for applications.

Signed-off-by: Siddharth Chandrasekaran <siddharth@embedjournal.com>
2020-08-18 09:19:58 -07:00
Jukka Rissanen
2ed6b6a8ed lib: fdtable: Add callback for close() calls
Do not route close() calls via ioctl() as that is error prone
and quite pointless. Instead create a callback for close() in
fdtable and use it directly.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-14 09:47:51 -07:00
Peter A. Bigot
13f96d439e sys: onoff: support clients using synchronous transitions
The on-off manager infrastructure is designed to robust asynchronous
transition between binary states where multiple clients may be
initiating a transition from any context.  The actual transition is
performed using a manager that tracks the current state and pending
operations.  Requests are initiated by passing a reference to an
onoff_client object that holds client state including the notification
mechanism.

This API may be used in subsystems where the transitions for a
particular driver are always synchronous and isr-ok, e.g. setting a
SoC-controlled GPIO.  In this situation the full on-off manager
infrastructure is wasteful.  All we need is a record of the service
state: off, active count, or error.

Add a data structure and an API that can be used to replace the onoff
manager functionality in a situation where all transitions are isr-ok
and synchronous while retaining compatible behavior from the client
perspective.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2020-08-14 17:53:39 +02:00
Yuguo Zou
1672e51d51 lib: fix compile error for ARC arch
macro Z_ARC_MPU_SIZE_ALIGN is no longer exist, so change it accordingly

Signed-off-by: Yuguo Zou <yuguo.zou@synopsys.com>
2020-08-12 09:22:37 +02:00
Jan Pohanka
9e462469b4 lib: posix: Fix priority validity check in pthread_setschedparam
New priority value check was faultly done on zephyr priority instead
of posix one.

Signed-off-by: Jan Pohanka <xhpohanka@gmail.com>
2020-08-11 07:46:06 -04:00
Jukka Rissanen
8b578bdceb lib: os: Add refcounting to fdtable entries
Use proper refcounting instead of magic value in obj field
when checking whether the fd is still in use. This will make
sure that if fd is shared between two threads, we do not
release it too soon.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-08-10 14:56:08 -07:00
Torsten Rasmussen
bb3946666f cmake: fix include directories to work with out-of-tree arch
Include directories for ${ARCH} is not specified correctly.
Several places in Zephyr, the include directories are specified as:
${ZEPHYR_BASE}/arch/${ARCH}/include
the correct line is:
${ARCH_DIR}/${ARCH}/include
to correctly support out of tree archs.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2020-08-05 08:06:07 -04:00
Gerson Fernando Budke
29544a1ceb updatehub: Move from lib to subsys:mgmt folder
Zephyr introduced subsys/mgmt folder for MCU management. Move UpdateHub
to this newly and dedicated space.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-08-03 16:33:06 +02:00
Carles Cufi
244f826e3c cmake: remove _if_kconfig() functions
This set of functions seem to be there just because of historical
reasons, stemming from Kbuild. They are non-obvious and prone to errors,
so remove them in favor of the `_ifdef()` ones with an explicit
`CONFIG_` condition.

Script used:

git grep -l _if_kconfig | xargs sed -E -i
"s/_if_kconfig\(\s*(\w*)/_ifdef(CONFIG_\U\1\E \1/g"

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-08-01 12:35:20 +02:00
Dominik Ermel
49ab2099f3 lib/posix: Add support for open flags to open(...)
The fs_open flags has been changed to accept open flags, which requires
changes to open(...) to support the new flags.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
2020-07-30 16:33:18 +02:00
Dominik Ermel
deb1694c3c posix: Extend open() function signature with ellipsis
The commit changes signature of open function from:
  int open(const char *name, int flags)
to
  int open(const char *name, int flags, ...)

Currently existing two argument invocations should not require any
rework.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
2020-07-30 16:33:18 +02:00
Dominik Ermel
47ab70e34c gui: Add open flags argument to fs_open invocation
Now fs_open supports open flags and the lvgl_fs code requires update.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
2020-07-30 16:33:18 +02:00
Gerson Fernando Budke
897a177232 lib: updatehub: Fix getaddrinfo resource leak
Add missing freeaddrinfo to fix memory leak.

Fixes #26994.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-07-30 10:29:21 -04:00
Gerson Fernando Budke
32bafacc31 lib: updatehub: Add flash_img_init return value check
The flash_img_int return value is not checked for fail conditions.
This can result on useless download attempts once image will not
be properly recorded. Add return value check and on error execute
default treatment.

Fixes #26992.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-07-30 12:24:48 +02:00
Gerson Fernando Budke
8683b47b17 lib: updatehub: Fix out-of-bounds access
The struct pollfd context variable is not proper initialized and index
is out-of-bounds. Adjusts index to be inside scope boundary.

Fixes #26993.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-07-30 12:24:48 +02:00
Gerard Marull-Paretas
5df0ad3194 lib: gui: lvgl: update to v7.0.2
Update LVGL to version 7.0.2. Notable changes in v7 include:

- New drawing system (note that it uses much more ROM than previous
  versions)
- New style system
- Some objects have been renamed (current changes do not align yet
  Zephyr Kconfig settings with LVGL)
- New fonts with more sizes (e.g. Montserrat, replacing Roboto)
- Theme changes (most have been removed, default is now Material)

Note that constant defaults have been aligned with LVGL.

Signed-off-by: Gerard Marull-Paretas <gerard@teslabs.com>
2020-07-27 15:06:22 +02:00
Vincent Wan
b3d5af0e9d lib: fdtable: Remove workaround for SimpleLink for fcntl
Given socket offloading is now implemented under the fd's vtable, we can
directly use the default fcntl implementation.

Signed-off-by: Vincent Wan <vwan@ti.com>
2020-07-27 13:28:06 +02:00
Daniel Leung
4fc1444823 lib: os/heap: timeout: avoid identifier collisions
MISRA-C Rule 5.3 states that identifiers in inner scope should
not hide identifiers in outer scope.

In the function sys_heap_alloc(), the variable "chunksz"
collide with function named chunksz(). So rename those variable.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-07-25 21:26:15 -04:00
David Leach
2abdc19ceb libc: newlib: libc-hooks: Fix Coverity warning
Suppress the coverity warning on using the semaphore as
this semaphore is used and freed only in this function.

Fixes: #18960

Signed-off-by: David Leach <david.leach@nxp.com>
2020-07-24 21:51:14 -04:00
Pete Skeggs
3835b0bd1c lib/os/work_q: sanity check work_q handler prior to calling it
Just as NULL pointers should not be dereferenced, they should
not be called either.

Fixes 26723

Signed-off-by: Pete Skeggs <peter.skeggs@nordicsemi.no>
2020-07-24 12:07:17 +02:00
Andrew Boie
bb0c6dbf62 libc: newlib: remove impossible ifdef
This whole code block is ifdef'ed around
CONFIG_NEWLIB_LIBC_ALIGNED_HEAP_SIZE being NOT defined,
remove as this can never be true.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-23 11:01:42 +02:00
Andrew Boie
ca1154d85a libc: newlib: simplfy malloc arena defn
We've come a long way since this was written to implement
generic ram bounds definitions and MPU capabilities,
use them here.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-23 11:01:42 +02:00
Jan Van Winkel
1130dc9f90 gui: Set actual display size when using static buffers
Set actual display size, obtained via the display driver, when using
static rendering buffers. If the actual screen size is not set an
out-of-bound write could occur in case the maximum resolution settings
for LVGL are larger than the actual screen resolution.

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2020-07-21 15:12:05 +02:00
Marcin Niestroj
063dd51dc7 lib: posix: eventfd: fix read/poll after multiple writes
So far semaphore was used with possible values in range 0 to
UINT32_MAX. Each write resulted in semaphore increment. As an example
after two writes and single read eventfd counter was correctly zeroed,
but semaphore counter was not. This means that poll() signalled at this
stage POLLIN (semaphore counter was > 0), but it clearly should
not (eventfd counter == 0). Blocking version of read() was also
returning immediately, returning 0 as previous eventfd counter.

Change read_sem to be a binary semaphore, which counter represents
eventfd counter being zero (when semaphore counter == 0) or
non-zero (when semaphore counter == 1). Try to take the semaphore in
eventfd read() and decrement eventfd counter when semaphore was ready.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-07-20 16:21:37 +02:00
Christopher Friedt
d0629e3c4e libc: malloc: log an error when malloc is called and arena size is 0
Previously, if the arena size was zero, malloc would always fail.
However, the log message was only visible if debug messages were
enabled. Logging an error will hopefully make it more obvious that
CONFIG_MINIMAL_LIBC_MALLOC_ARENA_SIZE should be >= if the minimal
libc and malloc are both used.

Fixes #26720

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-07-20 12:48:33 +02:00
Nicolas Pitre
6014e5f441 lib/os/heap: remove big_heap restriction for aligned allocations
After commit 8a6b02b5bf ("lib/os/heap: some code simplification in
sys_heap_aligned_alloc()") it is no longer required to have a "big"
heap for aligned allocations to work on 32-bit targets. While the
natural alignment for returned memory has an offset of 4 within a chunk
unit due to the smaller header size, returning to a chunkid from a
memory pointer with an offset of 8 will fall back onto the proper chunk
number once the 4 is substracted and then divided by 8.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-07-14 19:35:52 -04:00
Nicolas Pitre
e9ff53fa2a lib/os/heap: optimize chunk splitting
The code is doing a split in split_alloc(), adding the leftover to the
free list, then splitting the suffix away in sys_heap_aligned_alloc(),
removing the former leftover from the free list, combining it with the
suffix and finally adding the combined chunk back to the free list.

Instead, let's have each allocator do their own splitting only once by
moving the split_alloc() processing upstream rather than downstream.
This also allows for the "used" flag to be set only once at the end
rather than being overwritten along the way.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-07-14 19:35:52 -04:00
Nicolas Pitre
9b538e4079 lib/os/heap: make "solo free headers" into first-class citizens
Instead of limiting the excess split-off to sufficiently large chunks
in split_alloc(), let's allow normal allocations to create "solo free
headers" just like with aligned allocations. There is no point leaving
them in the allocated chunk if the user didn't ask for it. Doing so
makes them eligible for merging at the next opportunity and potentially
reusable sooner.

Also make the validation code aware of them.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-07-14 19:35:52 -04:00
Nicolas Pitre
130963ad2f lib/os/heap: add an additional validation criteria
One fundamental validation criteria is to never have consecutive free
chunks. If that ever happens we failed to merge them. That means a free
chunk must always be surrounded by used chunks.

It is a pain to extend valid_chunk() with new rules as it is.
So a VALIDATE() macro is introduced to make things easier to work with.
It also allows for isolating each test, possibly making VALIDATE() into
__ASSERT() to determine exactly which test is tripping when debugging.

Finally, because of that new validation rule, sys_heap_validate() must
be modified so not to use valid_chunk() while it is flipping all the
"used" flags. So let's run valid_chunk() up front before alterating
chunk headers.

Now sys_heap_validate() has become justifiably more expensive and a few
emulated targets are about to bust the tests/lib/heap test timeout. So
bump the timeout as well.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-07-14 19:35:52 -04:00
Nicolas Pitre
9b617755d2 lib/os/heap: code cleanup
This makes the code cleaner wrt bucket_idx() usage on chunks for which
solo_free_header() is true. In such case the bucket_idx() computation
is useless, and potentially undefined anyway.

In the same vain, move the clearing of the used flag out of
free_chunks() as only one of its callers actually needs that.
Makes free_chunks singular as there is only one chunk (potentially
spanning multiple chunk units) to free.

Also some cosmetic changes for better code uniformity.

No functional changes.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-07-14 19:35:52 -04:00
Dominik Ermel
5a40ff1ac5 posix/fs: Fix POSIX lseek to return position upon completion
Bring standard behaviour to lseek, where new file position is returned
on success.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
2020-07-04 07:46:51 -04:00
Andy Ross
3f9ad86b1d kernel/printk: Make it synchronous
Currently printk isn't synchronized except at the byte output level,
leading to interleaving of messages on SMP systems that try to log
simultaneously.  This is actually fairly amusing, and actually helpful
occasionally to validate inter-CPU contention down to the "few cycles"
level.

Still, when you're printing data you need to read, you need to be able
to read it.  Put a spinlock around each buffered line.  This has to
happen in a few places, as there are three different code paths taken
for !USERSPACE, syscall, and user mode.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-06-27 08:14:58 -04:00
Nicolas Pitre
ae597c07b6 printk: print %p properly on 32-bit targets
The width for %p on 32-bit targets should be 8 regardless of
CONFIG_PRINTK64. Adjust the test accordingly.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-27 00:03:58 -04:00
Nicolas Pitre
64af35049c lib/os/heap: debugging facility to dump the heap structure to the cconsole
It is linked in only when used, so handy to always have it around for
analysis purposes.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-26 11:41:43 -07:00
Nicolas Pitre
0ae04f01b6 lib/os/heap: make some checks more assertive
Some checks in sys_heap_init() depend on the externally provided size
parameter. If the check fails, this would be a bug outside of the heap
code and therefore should be flagged despite the value of
CONFIG_SYS_HEAP_VALIDATE.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-25 17:43:13 -07:00
Andy Ross
973487fdad lib/os: Rework/shrink printk conversions, add 64 bit support
Add support for 64 bit conversions in a uniformly expressable way by
printing values backwards into a buffer on the stack first.  This
allows all operations to work on the low bits of the value and so the
code doesn't need to care (beyond the size of that buffer) about the
word size.  This trick also doesn't care about the specifics of the
base value, so in the process this unifies the decimal and hex printk
conversion code to a single function.

This comes at a mild cost in CPU cycles to the decimal converter and
somewhat higher cost to hex (because it's now doing a full div/mod
operation instead of shifting and masking).  And stack usage has grown
by a few words to hold the temporary.  But the benefits in code size
are substantial (e.g. ~250 bytes of .text on arm32).

Note that this also contains a change to tests/kernel/common to
address what appears to have been a bug in the original converters.
The printk test uses a format string that looks like "%-4x%-2p" and
feeds it the literal arguments "0xABCDEF" and "(char *)42".
Now... clearly both those results are going to overflow the 4 and
2-byte field sizes, so there shouldn't be any whitespace between these
fields.  But the test was written to expect two spaces, inexplicably
(yes, I checked: POSIX-compatible printf implementations don't have
those spaces either).

The new code is definitely doing the right thing, so fix the test
instead.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-06-24 13:43:40 -07:00
Nicolas Pitre
8a6b02b5bf lib/os/heap: some code simplification in sys_heap_aligned_alloc()
It is clearer to apply the alignment in the memory address space
rather than the chunk space.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-24 11:53:50 -07:00
Gerson Fernando Budke
3add3d7b60 lib: updatehub: Add download block check
The current CoAP implementation not perform any checks including
duplicated packets. This add block sequency verification and a
timer to ensures that slow networks works apropriately.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-06-23 19:22:31 +02:00
Gerson Fernando Budke
092b962350 lib: updatehub: Kconfig: Add coap block size option
Allow select max CoAP block size for exchange data using coap protocol.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-06-23 19:22:31 +02:00
Gerson Fernando Budke
6c4c12d531 lib: updatehub: Kconfig: Add coap max retry option
The current implementation uses a fixed value for max retries. That
value could be good for an wired network like Ethernet. However,
wireless network can suffer with higher packet collision, low reception
signal etc. This refacts the variable to be defined at Kconfig. This
way max retries can be adjust conform the current media.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-06-23 19:22:31 +02:00
Gerson Fernando Budke
a7c63d8818 lib: updatehub: Init metadata variable
Init metadata variable to a defined state.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-06-23 19:22:31 +02:00
Gerson Fernando Budke
d16517e575 lib: updatehub: Init hints variable
The hints variable is used without a defined state. This fill the struct
with zeros to set variable at a well known state.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-06-23 19:22:31 +02:00
Gerson Fernando Budke
9a43250667 lib: updatehub: Add log level
Current log only prints default log level. Add LOG_LEVEL at updatehub
to switch between log variations based on CONFIG_UPDATEHUB_LOG_LEVEL.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-06-23 19:22:31 +02:00
Andy Ross
ed258e9c6f lib/os/heap: Add sys_heap_aligned_alloc()
Add support for a C11-style aligned_alloc() in the heap
implementation.  This is properly optimized, in the sense that unused
prefix/suffix data around the chosen allocation is returned to the
heap and made available for general allocation.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-06-22 14:54:04 -04:00
Andy Ross
1f29dd3251 lib/os/heap: General refactoring
Miscellaneous refactoring and simplification.  No behavioral changes:

Make split_alloc() take and return chunk IDs and not memory pointers,
leaving the conversion between memory/chunks the job of the higher
level sys_heap_alloc() API.  This cleans up the internals for code
that wants to do allocation but has its own ideas about what to do
with the resulting chunks.

Add split_chunks() and merge_chunks() utilities to own the linear/size
pointers and have split_alloc() and free_chunks() use them instead of
doing the list management directly.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-06-22 14:54:04 -04:00
Nicolas Pitre
ad59e923e9 sys_heap: reduce the size of struct z_heap_bucket by half
This struct is taking up most of the heap's constant footprint overhead.
We can easily get rid of the list_size member as it is mostly used to
determine if the list is empty, and that can be determined through
other means.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
74fbca412a sys_heap: perform cheap overflow detection on freed memory
Make the LEFT_SIZE field first and SIZE_AND_USED field last (for an
allocated chunk) so they sit right next to the allocated memory. The
current chunk's SIZE_AND_USED field points to the next (right) chunk,
and from there the LEFT_SIZE field should point back to the current
chunk. Many trivial memory overflows should trip that test.

One way to make this test more robust could involve xor'ing the values
within respective accessor pairs. But at least the fact that the size
value is shifted by one bit already prevent fooling the test with a
same-byte corruption.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
cb3d460a2c sys_heap: simplify some complex checks
Avoid redundancy and bucket_idx() usage when possible.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
d1125d21d4 sys_heap: remove need for last_chunk()
We already have chunk #0 containing our struct z_heap and marked as
used. We can add a partial chunk at the very end that is also marked
as used. By doing so there is no longer a need for checking heap
boundaries at run time when merging/splitting chunks meaning fewer
conditionals in the code's hot path.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
6d827fa080 sys_heap: introduce min_chunk_size()
With this we can remove magic constants, especially those used with
big_heap().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
e553161b8e sys_heap: optimize struct z_heap
It is possible to remove a few fields from struct z_heap, removing
some runtime indirections by doing so:

- The buf pointer is actually the same as the struct z_heap pointer
  itself. So let's simply create chunk_buf() that perform a type
  conversion. That type is also chunk_unit_t now rather than u64_t so
  it can be defined based on CHUNK_UNIT.

- Replace the struct z_heap_bucket pointer by a zero-sized array at the
  end of struct z_heap.

- Make chunk #0 into an actual chunk with its own header. This allows
  for removing the chunk0 field and streamlining the code. This way
  h->chunk0 becomes right_chunk(h, 0). This sets the table for further
  simplifications to come.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
e2b64777e5 sys_heap: optimize usage of size and used flags
By storing the used flag in the LSB, it is no longer necessary to have
a size_mask variable to locate that flag. This produces smaller and
faster code.

Replace the validation check in chunk_set() to base it on the storage
type.

Also clarify the semantics of set_chunk_size() which allows for clearing
the used flag bit unconditionally which simplifies the code further.

The idea of moving the used flag bit into the LEFT_SIZE field was
raised. It turns out that this isn't as beneficial as it may seem
because the used bit is set only once i.e. when the memory is handed off
to a user and the size field becomes frozen at that point. Modifications
on the leftward chunk may still occur and extra instructions to preserve
that bit would be necessary if it were moved there.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
54950aca01 sys_heap: provide more chunk_fields accessors
Let's provide accessors for getting and setting every field to make the
chunk header layout abstracted away from the main code. Those are:

SIZE_AND_USED: chunk_used(), chunk_size(), set_chunk_used() and
chunk_size().

LEFT_SIZE: left_chunk() and set_left_chunk_size().

FREE_PREV: prev_free_chunk() and set_prev_free_chunk().

FREE_NEXT: next_free_chunk() and set_next_free_chunk().

To be consistent, the former chunk_set_used() is now set_chunk_used().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Nicolas Pitre
f97eca26e6 sys_heap: some cleanups to make the code clearer
First, some renames to make accessors more explicit:

  size() --> chunk_size()
  used() --> chunk_used()
  free_prev() --> prev_free_chunk()
  free_next() --> next_free_chunk()

Then, the return type of chunk_size() is changed from chunkid_t to
size_t, and chunk_used() from chunkid_t to bool.

The left_size() accessor is used only once and can be easily substituted
by left_chunk(), so it is removed.

And in free_list_add() the variable b is renamed to bi so to be
consistent with usage in sys_heap_alloc().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2020-06-21 19:25:35 +02:00
Markus Fuchs
2f9b0d419b json: Add top-level array encoding support
The library supports the declaration of JSON arrays as both nested and
top-level elements. However, as the provided encoding functions
json_obj_encode() and json_obj_encode_buf() interpret all input
structures as objects, top-level arrays are encoded as

{"<field_name>":[{...},...,{...}]}

instead of

[{...},...,{...}].

Add new functions json_arr_encode() and json_arr_encode_buf() that
enable top-level JSON array encoding.

Signed-off-by: Markus Fuchs <markus.fuchs@de.sauter-bc.com>
2020-06-19 18:21:27 +02:00
Paul Sokolovsky
5f05d6598f libc: newlib: libc-hooks: Provide our own implementation of __chk_fail()
The version as shipped in Newlib itself is coded a bit sloppily for an
embedded environment. We thus want to override it (and make it weak, to
allow user apps to override it in turn, if needed). The desired
properties of the implementation are:

1. It should call _write() (Newlib implementation calls write()).
2. It should be minimal (Newlib implementation allocates message
on the stack, i.e. misses "static const").

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2020-06-17 17:06:47 +02:00
Marcin Niestroj
385abc7740 lib: posix: eventfd: support build with !POSIX_API
Just change include path to support build with CONFIG_POSIX_API=n.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-06-15 16:52:29 +02:00
Christopher Friedt
8bcf005084 lib: posix: nanosleep
This change adds support for nanosleep(2) documented at
https://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

N.B: Currently, this provides no better resolution than
k_busy_wait()

Fixes #25554

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-06-12 17:02:03 +02:00
Marcin Niestroj
1502b9a648 lib: posix: eventfd: move intialization out of search loop
Search for unused eventfd object and just remember its instance in loop
body. Initialize object later, to make it distinct from "search
phase". This change is basically an improvement for readability.

Signed-off-by: Marcin Niestroj <m.niestroj@grinn-global.com>
2020-06-10 17:19:19 +03:00
Kumar Gala
a1b77fd589 zephyr: replace zephyr integer types with C99 types
git grep -l 'u\(8\|16\|32\|64\)_t' | \
		xargs sed -i "s/u\(8\|16\|32\|64\)_t/uint\1_t/g"
	git grep -l 's\(8\|16\|32\|64\)_t' | \
		xargs sed -i "s/s\(8\|16\|32\|64\)_t/int\1_t/g"

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-06-08 08:23:57 -05:00
Andrew Boie
87480cd4fb fdtable: init fd context objects
Anytime a file descriptor context object is updated, we need to
reset its access permissions and initialization state. This
is the most centralized place to do it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Tahir Akram
ba88c99677 lib: updatehub: Fix bus fault
Fix variable-size string copy patch that introduced a runtime bug that
causes a bus fault.

Fixes #24853.

Signed-off-by: Tahir Akram <mtahirbutt@hotmail.com>
Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-05-26 14:37:54 +02:00
Gerson Fernando Budke
284e841bf4 lib: updatehub: Fix compile warning
Based on the current platform a warning can raise becase of missing
string.h include file.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-05-18 11:12:31 +02:00
Gerson Fernando Budke
c35cad52f5 lib: updatehub: Add missing include for FLASH_AREA
The conversion from DT_FLASH_AREA to FLASH_AREA macros don't add the
storage flash_map.h include file.

Fixes: #25332

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-05-18 11:12:31 +02:00
Kumar Gala
ff579a3af3 flash: Convert DT_FLASH_AREA to FLASH_AREA macros
Convert with a combo of scripts and by hand fixups:

git grep -l DT_FLASH_AREA_.*_ID | \
 xargs sed -i -r 's/DT_FLASH_AREA_(.*)_ID/FLASH_AREA_ID(\L\1)/'

git grep -l DT_FLASH_AREA_.*_OFFSET | \
 xargs sed -i -r 's/DT_FLASH_AREA_(.*)_OFFSET/FLASH_AREA_OFFSET(\L\1)/'

git grep -l DT_FLASH_AREA_.*_SIZE | \
 xargs sed -i -r 's/DT_FLASH_AREA_(.*)_SIZE/FLASH_AREA_SIZE(\L\1)/'

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-05-13 21:22:53 +02:00
Gerson Fernando Budke
4980a13fc4 lib: updatehub: Update to new timeout api
Update to new timeout api. Without this change UpdateHub don't build
anymore.

Fixes: #25230

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-05-12 20:17:38 +02:00
Paul Sokolovsky
0b634793cc lib: posix: Update to new timeout API
Mostly trivial search-and-replace, except for pthread_rwlock.c, where
we need spread timeout over 2 semaphore operations.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2020-05-08 17:31:45 +02:00
Andy Ross
7e3d43b558 lib/cmsis_rtos_v2: Update to newer timeout API
Mostly simple.  Note that the CMSIS RTOS2 API specifies timeout values
in system ticks instead of milliseconds, so the conversions here are
able to elide a conversion that the original code had to do.  That's a
good thing, but does mean that in practice runtime behavior will not
be 1:1 identical.

Also note that the switch away from legacy timeouts involved a change
to 64 bit timeouts by default, which pushed
tests/portability/cmsis_rtos_v2 over the limit on qemu_xtensa.
Unfortunately CMSIS stacks have a fixed limit we can't increase, so I
turned off 64 bit timeouts (CMSIS apps won't need them by definition
anyway -- their API is 32 bit).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-05-06 06:05:03 -04:00
Andy Ross
1003ab806c subsys/cmsis_v1: Port to new timeout API
No complexity here.  The CMSIS API was always in milliseconds, needs
nothing but a few wrapper macros for kernel timeout arguments.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-05-06 06:05:03 -04:00
David Brown
69e8a7b657 updatehub: Require peer verification with DTLS
DTLS without peer verification offers no security whatsoever (and is
arguably worse than not using DTLS in the first place).

Change the verification option to require this peer verification.  To
use this, it may be necessary to install and use a root certificate.

Signed-off-by: David Brown <david.brown@linaro.org>
2020-05-05 13:40:12 -05:00
Kumar Gala
be97e40683 soc: nios2: Cleanup linker scripts to use new DTS macros
Move defines for _RAM_ADDR, _RAM_SIZE, _ROM_ADDR, and _ROM_ADDR into
the linker.ld and thus remove dts_fixup.h.  We rework to use
DT_REG_ADDR and DT_REG_SIZE on DT_CHOSEN(zephyr_sram) and
DT_CHOSEN(zephyr_flash).

Also fixup use of _RAM_ADDR/_RAM_SIZE in newlib/libc-hooks.c.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-04-30 20:59:13 -05:00
Kumar Gala
a45ea3806f x86: Rework rework x86 related code to use new DTS macros
Replace DT_PHYS_RAM_ADDR and DT_RAM_SIZE with DT_REG_ADDR/DT_REG_SIZE
for the DT_CHOSEN(zephyr_sram) node.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-04-30 08:37:18 -05:00
Peter Bigot
a09f6ad54c json: fix buffer overrun in encoding helper
The bounds check failed to account for the additional space required
for the terminating NUL after the encoded value was written.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-04-28 15:06:45 -04:00
Tobias Svehagen
ca872a44c1 lib: posix: Add support for eventfd
This implements a file descriptor used for event notification that
behaves like the eventfd in Linux.

The eventfd supports nonblocking operation by setting the EFD_NONBLOCK
flag and semaphore operation by settings the EFD_SEMAPHORE flag.

The major use case for this is when using poll() and the sockets that
you poll are dynamic. When a new socket needs to be added to the poll,
there must be some way to wake the thread and update the pollfds before
calling poll again. One way to solve it is to have a timeout set in the
poll call and only update the pollfds during a timeout but that is not
a very nice solution. By instead including an eventfd in the pollfds,
it is possible to wake the polling thread by simply writing to the
eventfd.

Signed-off-by: Tobias Svehagen <tobias.svehagen@gmail.com>
2020-04-28 09:57:41 +03:00
Peter Bigot
14e2ca4f16 sys: onoff: redesign to meet changed needs
The previous architecture proved unable to support user expectations,
so the API has been rebuilt from first principles.  Backward
compatibility cannot be maintained for this change.

Key changes include:

* Formerly the service-provided transition functions were allowed to
  sleep, and the manager took care to not invoke them from ISR
  context, instead returning an error if unable to initiate a
  transition.  In the new architecture transition functions are
  required to work regardless of calling context: it is the service's
  responsibility to guarantee the transition will proceed even if it
  needs to be transferred to a thread.  This eliminates state machine
  complexities related to calling context.
* Constants identifying the visible state of the manager are exposed
  to clients through both notification callbacks and a new monitor API
  that allows clients to be notified of all state changes.
* Formerly the release operation was async, and would be delayed for the
  last release to ensure a client would exist to be notified of any
  failures.  It is now synchronous.
* Formerly the cancel operation would fail on the last client associated
  with a transition.  The cancel operation is now synchronous.
* A helper function is provided to safely synchronously release a
  request regardless of whether it has completed or is in progress,
  satisfying the use case underlying #22974.
* The user-data parameter to asynchronous notification callbacks has
  been removed as user data can be retrieved from the CONTAINER_OF
  the client data.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-04-22 16:52:47 +02:00
Julien D'Ascenzio
e689277dd5 lib: posix: clock: Turn clock_gettime into system call
Fix thread fault, on user mode, when reading variable rt_clock_base.
For the moment, clock_settime is left without system call:
we don't want to expose clock_settime without figuring out access
control

Signed-off-by: Julien D'Ascenzio <julien.dascenzio@paratronic.fr>
2020-04-17 08:08:37 -04:00
Gerson Fernando Budke
894dcbbf15 lib: updatehub: Improve probe security
Improve buffer overflow security on probe_cb. This ensures that socket
buffer have fixed lenght and content received by COAP fills properly on
metadata buffer. After that, ensures that metadata content is a valid
string with length lower than metadata size.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-04-17 10:09:56 +03:00
Gerson Fernando Budke
6238e52062 lib: updatehub: Refact to use bin2hex
Use bin2hex instead inline conversion.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-04-17 10:09:56 +03:00
Gerson Fernando Budke
0801aef3fb lib: updatehub: Fix variable-size string copy
A malformed JSON payload that is received from an UpdateHub server
may trigger memory corruption in the Zephyr OS. This could result
in a denial of service in the best case, or code execution in the
worst case.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
2020-04-17 10:09:56 +03:00
Andy Ross
aa4227754c lib/os: Add sys_heap, a new/simpler/faster memory allocator
The existing mem_pool implementation has been an endless source of
frustration.  It's had alignment bugs, it's had racy behavior.  It's
never been particularly fast.  It's outrageously complicated to
configure statically.  And while its fragmentation resistance and
overhead on small blocks is good, it's space efficiencey has always
been very poor due to the four-way buddy scheme.

This patch introduces sys_heap.  It's a more or less conventional
segregated fit allocator with power-of-two buckets.  It doesn't expose
its level structure to the user at all, simply taking an arbitrarily
aligned pointer to memory.  It stores all metadata inside the heap
region.  It allocates and frees by simple pointer and not block ID.
Static initialization is trivial, and runtime initialization is only a
few cycles to format and add one block to a list header.

It has excellent space efficiency.  Chunks can be split arbitrarily in
8 byte units.  Overhead is only four bytes per allocated chunk (eight
bytes for heaps >256kb or on 64 bit systems), plus a log2-sized array
of 2-word bucket headers.  No coarse alignment restrictions on blocks,
they can be split and merged (in units of 8 bytes) arbitrarily.

It has good fragmentation resistance.  Freed blocks are always
immediately merged with adjacent free blocks.  Allocations are
attempted from a sample of the smallest bucket that might fit, falling
back rapidly to the smallest block guaranteed to fit.  Split memory
remaining in the chunk is always returned immediately to the heap for
other allocation.

It has excellent performance with firmly bounded runtime.  All
operations are constant time (though there is a search of the smallest
bucket that has a compile-time-configurable upper bound, setting this
to extreme values results in an effectively linear search of the
list), objectively fast (about a hundred instructions) and amenable to
locked operation.  No more need for fragile lock relaxation trickery.

It also contains an extensive validation and stress test framework,
something that was sorely lacking in the previous implementation.

Note that sys_heap is not a compatible API with sys_mem_pool and
k_mem_pool.  Partial wrappers for those (now-) legacy APIs will appear
later and a deprecation strategy needs to be chosen.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-14 10:05:55 -07:00
Peter Bigot
8bd676ed38 sys: onoff: generalize and shorten API
The original API was misnamed, as the intent was to provide a manager
that decoupled state management from the service that needed to be
turned on or off.  Update all the names, shortening them where
appropriate removing unncessary internal components like _service.

Also remove some API that misled developers into believing that onoff
managers are normally expected to be exposed directly to consumers.
While this is a use case, in most situations there are service or
client-specific actions that need to be coupled to transition events.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-04-06 16:41:41 +02:00
Peter Bigot
fadd98aad2 sys: add generic asynchronous notification infrastructure
k_poll() for a signal is often desired for notification of completion
of asynchronous operations, but there are APIs where it may be
necessary to invoke "asynchronous" operations from contexts where
sleep is disallowed, or before the kernel has been initialized.
Extract the general notification solution from the on-off service into
a utility that can be used for other APIs.

Also move documentation out to a resource management section.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-04-06 16:41:41 +02:00
Krzysztof Chruscinski
e2ca46c329 sys: onoff: Move transition functions out of service struct
Extracted transition functions from onoff structure to external one
which allows to keep them in flash.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2020-04-06 16:41:41 +02:00
Joakim Andersson
4ebfafe7ce lib: os: fix signed and unsigend comparison warnings
Fix instances of:
warning: comparison between signed and unsigned integer expressions
[-Wsign-compare]

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2020-04-03 18:06:59 -04:00
Arnaud Pouliquen
25ec73986b lib: open-amp: add helper to add resource table in project
The resource table is needed by the Linux kernel OS
for a rpmsg generic support, but is also recognised by OpenAMP.
This table allows to add trace based on the RAM console
and to support rpmsg protocol.

Signed-off-by: Arnaud Pouliquen <arnaud.pouliquen@st.com>
2020-04-01 09:21:15 -05:00
Andy Ross
7832738ae9 kernel/timeout: Make timeout arguments an opaque type
Add a k_timeout_t type, and use it everywhere that kernel API
functions were accepting a millisecond timeout argument.  Instead of
forcing milliseconds everywhere (which are often not integrally
representable as system ticks), do the conversion to ticks at the
point where the timeout is created.  This avoids an extra unit
conversion in some application code, and allows us to express the
timeout in units other than milliseconds to achieve greater precision.

The existing K_MSEC() et. al. macros now return initializers for a
k_timeout_t.

The K_NO_WAIT and K_FOREVER constants have now become k_timeout_t
values, which means they cannot be operated on as integers.
Applications which have their own APIs that need to inspect these
vs. user-provided timeouts can now use a K_TIMEOUT_EQ() predicate to
test for equality.

Timer drivers, which receive an integer tick count in ther
z_clock_set_timeout() functions, now use the integer-valued
K_TICKS_FOREVER constant instead of K_FOREVER.

For the initial release, to preserve source compatibility, a
CONFIG_LEGACY_TIMEOUT_API kconfig is provided.  When true, the
k_timeout_t will remain a compatible 32 bit value that will work with
any legacy Zephyr application.

Some subsystems present timeout (or timeout-like) values to their own
users as APIs that would re-use the kernel's own constants and
conventions.  These will require some minor design work to adapt to
the new scheme (in most cases just using k_timeout_t directly in their
own API), and they have not been changed in this patch, instead
selecting CONFIG_LEGACY_TIMEOUT_API via kconfig.  These subsystems
include: CAN Bus, the Microbit display driver, I2S, LoRa modem
drivers, the UART Async API, Video hardware drivers, the console
subsystem, and the network buffer abstraction.

k_sleep() now takes a k_timeout_t argument, with a k_msleep() variant
provided that works identically to the original API.

Most of the changes here are just type/configuration management and
documentation, but there are logic changes in mempool, where a loop
that used a timeout numerically has been reworked using a new
z_timeout_end_calc() predicate.  Also in queue.c, a (when POLL was
enabled) a similar loop was needlessly used to try to retry the
k_poll() call after a spurious failure.  But k_poll() does not fail
spuriously, so the loop was removed.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-03-31 19:40:47 -04:00
Andy Ross
32bb2395c2 timeout: Fix up API usage
Kernel timeouts have always been a 32 bit integer despite the
existence of generation macros, and existing code has been
inconsistent about using them.  Upcoming commits are going to make the
timeout arguments opaque, so fix things up to be rigorously correct.
Changes include:

+ Adding a K_TIMEOUT_EQ() macro for code that needs to compare timeout
  values for equality (e.g. with K_FOREVER or K_NO_WAIT).

+ Adding a k_msleep() synonym for k_sleep() which can continue to take
  integral arguments as k_sleep() moves away to timeout arguments.

+ Pervasively using the K_MSEC(), K_SECONDS(), et. al. macros to
  generate timeout arguments.

+ Removing the usage of K_NO_WAIT as the final argument to
  K_THREAD_DEFINE().  This is just a count of milliseconds and we need
  to use a zero.

This patch include no logic changes and should not affect generated
code at all.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-03-31 19:40:47 -04:00
Oleg Zhurakivskyy
b1e1f64d14 global: Replace BUILD_ASSERT_MSG() with BUILD_ASSERT()
Replace all occurences of BUILD_ASSERT_MSG() with BUILD_ASSERT()
as a result of merging BUILD_ASSERT() and BUILD_ASSERT_MSG().

Signed-off-by: Oleg Zhurakivskyy <oleg.zhurakivskyy@intel.com>
2020-03-31 07:18:06 +02:00
Gerson Fernando Budke
d1e2d345fb lib: updatehub: Add missing do upgrade request call
After a success image download, UpdateHub needs inform MCUboot that
must test new image and then, on success, commit this new image. This
add missing upgrade request call step and fixes the upgarde flow.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2020-03-30 16:54:29 +03:00
Gerson Fernando Budke
1128eab3f2 lib: updatehub: Fix download block error
The current version aborts update when found last transfer block. Now,
system checks only at end of coap block transfer total size and install
if download is ok.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2020-03-30 16:54:29 +03:00
Gerson Fernando Budke
1fe1b0eec6 lib: updatehub: Extract sha256 final method
Extract finish sha256 calc method.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2020-03-30 16:54:29 +03:00
Gerson Fernando Budke
5f5919a900 lib: updatehub: Fix buffer sizes
The MAX_PAYLOAD_SIZE must reflect the size of COAP_BLOCK_x. This is
necessary becase BLOCK size represents max payload size. The current
value create inconsistencies for coap lib. The same way,
MAX_DOWNLOAD_DATA must allocate sufficient space for MAX_PAYLOAD_SIZE
plus all space for coap header etc.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2020-03-30 16:54:29 +03:00
Gerson Fernando Budke
92f9cd9f85 lib: updatehub: Fix build warnings
Fix all build warnings.

Signed-off-by: Gerson Fernando Budke <gerson.budke@ossystems.com.br>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2020-03-30 16:54:29 +03:00
Måns Ansgariusson
2f323e65b2 lib: cmsis_rtos: Fix Periodic timer
This commit changes the behaviour of the CMSIS-RTOS periodic timers to
have an initial timeout equal to the periodic timeout instead of
executing the callback function directly when calling the
osTimerStart(...); function.

This behavioural change is according to the CMSIS-RTOS specification.

Signed-off-by: Måns Ansgariusson <Mans.Ansgariusson@AssaAbloy.com>
2020-03-25 09:37:59 -04:00
Carles Cufi
d212bc4d60 ext: lib: Move fnmatch to lib/
Since we already have similarly licensed 3-clause BSD files in the tree,
and in particular in our minimal libc, move the fnmatch functionality
from ext/ to lib/.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-03-20 22:56:19 -04:00
Carles Cufi
4b37a8f3a4 Revert "global: Replace BUILD_ASSERT_MSG() with BUILD_ASSERT()"
This reverts commit 8739517107.

Pull Request #23437 was merged by mistake with an invalid manifest.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-03-19 18:45:13 +01:00
Oleg Zhurakivskyy
8739517107 global: Replace BUILD_ASSERT_MSG() with BUILD_ASSERT()
Replace all occurences of BUILD_ASSERT_MSG() with BUILD_ASSERT()
as a result of merging BUILD_ASSERT() and BUILD_ASSERT_MSG().

Signed-off-by: Oleg Zhurakivskyy <oleg.zhurakivskyy@intel.com>
2020-03-19 15:47:53 +01:00
Julien D'Ascenzio
1128c65ab0 lib: posix: fix ARG_UNUSED check on clock_getrtc
The ARG_UNUSED should be on tz, not tv

Signed-off-by: Julien D'Ascenzio <julien.dascenzio@paratronic.fr>
2020-03-18 12:28:43 -04:00
Andrew Boie
2dc2ecfb60 kernel: rename struct _k_object
Private type, internal to the kernel, not directly associated
with any k_object_* APIs. Is the return value of z_object_find().
Rename to struct z_object.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-17 20:11:27 +02:00
Andrew Boie
f2734ab022 kernel: use a union for kobject data values
Rather than stuffing various values in a uintptr_t based on
type using casts, use a union for this instead.

No functional difference, but the semantics of the data member
are now much clearer to the casual observer since it is now
formally defined by this union.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-17 20:11:27 +02:00
Nicholas Lowell
17b19eb810 pthread: add setname/getname glibc extensions
Adding the ability to set and get pthread names by defining
some non-standard extension functions that were first
introduced by Glibc.

Similar to zephyr thread naming, these allow for thread
tracking and debugging even when using the more portable
posix API.

Though Glibc was the originator, the current POSIX functions
have return codes based on Oracle's adopted spec, so these
functions follow suit.  The Oracle and Glibc function
prototypes match.

Signed-off-by: Nicholas Lowell <nlowell@lexmark.com>
2020-03-10 15:15:34 +02:00
Flavio Ceolin
9e45c67679 lib: posix: Fix undefined reference to clock_gettime()
timespec_to_timeoutms calls clock_gettime that requires
CONFIG_POSIX_CLOCK. ifdef this function to avoid undefined reference.

Fixes #20137

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-03-10 14:57:16 +02:00
Jukka Rissanen
9d4fbb2912 crc: Add crc8 implementation and tests
Add crc8 implementation and unit tests for it.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-03-10 12:53:53 +02:00
Nick Ward
1e503b5ca7 lib: posix: clock: Fix nanosecond rollover logic
It was out by one count.

Signed-off-by: Nick Ward <nix.ward@gmail.com>
2020-02-15 23:09:43 +03:00
Ulf Magnusson
eddd98f811 kconfig: Replace some single-symbol 'if's with 'depends on'
I think people might be reading differences into 'if' and 'depends on'
that aren't there, like maybe 'if' being needed to "hide" a symbol,
while 'depends on' just adds a dependency.

There are no differences between 'if' and 'depends on'. 'if' is just a
shorthand for 'depends on'. They work the same when it comes to creating
implicit menus too.

The way symbols get "hidden" is through their dependencies not being
satisfied ('if'/'depends on' get copied up as a dependency on the
prompt).

Since 'if' and 'depends on' are the same, an 'if' with just a single
symbol in it can be replaced with a 'depends on'. IMO, it's best to
avoid 'if' there as a style choice too, because it confuses people into
thinking there's deep Kconfig magic going on that requires 'if'.

Going for 'depends on' can also remove some nested 'if's, which
generates nicer symbol information and docs, because nested 'if's really
are so simple/dumb that they just add the dependencies from both 'if's
to all symbols within.

Replace a bunch of single-symbol 'if's with 'depends on' to despam the
Kconfig files a bit and make it clearer how things work. Also do some
other minor related dependency refactoring.

The replacement isn't complete. Will fix up the rest later. Splitting it
a bit to make it more manageable.

(Everything above is true for choices, menus, and comments as well.)

Detected by tweaking the Kconfiglib parsing code. It's impossible to
detect after parsing, because 'if' turns into 'depends on'.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2020-02-08 08:32:42 -05:00
Andrew Boie
efc5fe07a2 kernel: overhaul unused stack measurement
The existing stack_analyze APIs had some problems:

1. Not properly namespaced
2. Accepted the stack object as a parameter, yet the stack object
   does not contain the necessary information to get the associated
   buffer region, the thread object is needed for this
3. Caused a crash on certain platforms that do not allow inspection
   of unused stack space for the currently running thread
4. No user mode access
5. Separately passed in thread name

We deprecate these functions and add a new API
k_thread_stack_space_get() which addresses all of these issues.

A helper API log_stack_usage() also added which resembles
STACK_ANALYZE() in functionality.

Fixes: #17852

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-02-08 10:02:35 +02:00
Kumar Gala
4fb265657d libc: newlibc: Implement dummy _gettimeofday to link
With the change in SDK 0.11.1 to newlib to remove
-DMISSING_SYSCALL_NAMES we now need to implement a version of
_gettimeofday.  Previously with pre SDK 0.11.1 we had a recursive mess
of _gettimeofday_r -> gettimeofday -> _gettimeofday_r.  (which are all
implemented in newlib and thus we didn't get a link error).

With SDK 0.11.1 we have: _gettimeofday_r -> _gettimeofday.  And we
should provide a version of _gettimeofday.

Fixes #22484

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-02-05 20:47:41 +01:00
Kumar Gala
c8696293a9 libc: fix build issue with posix fs APIs on xtensa
On xtensa we always need to implement the reentrant fs syscall
functions.  So remove the #ifndef CONFIG_POSIX_API protection around
them and add needed externs.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-02-04 20:59:52 +02:00
Kumar Gala
9897c3b0dd libc: Move xtensa reentrant syscall impl to common libc-hooks
The xcc specific reentrant syscall implementations are actually useful
for xtensa in general.  So move that code from being specific to
intel_s1000 / xcc into generic newlib/libc-hooks.c.  This is in prep
for the Zephyr SDK dropping -DMISSING_SYSCALL_NAMES which will make
its version of newlib on xtensa match behavior with xcc.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-02-03 14:57:10 -06:00
Maureen Helm
514b5861c3 gui: Add support for lvgl touch input device
Adds support for an optional lvgl touch input device using the zephyr
keyboard scan interface. This can be used with the ft5336 touch panel
driver, which returns single touch coordinates through the kscan
driver callback.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-02-01 08:50:16 -05:00
Kumar Gala
6317c82f06 toolchain: Have Kconfig NEWLIB_LIBC_NANO depend on toolchain support
Introduce HAS_NEWLIB_LIBC_NANO Kconfig option that the toolchain
specific Kconfig (gnuarmemb & zephyr 0.11) can select to convey that the
feature is supported.

This removes the need to if protect the NEWLIB_LIBC_NANO Kconfig with:

    if "$(ZEPHYR_TOOLCHAIN_VARIANT)" = "gnuarmemb"

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-01-29 12:22:31 -06:00
Peter A. Bigot
1964bf08bb lib: os: onoff: add API for on-off service request and release management
There are various situations where it's necessary to support turning
devices on or off at runtime, includin power rails, clocks, other
peripherals, and binary device power management.  The complexity of
properly managing multiple consumers of a device in a multithreaded
system suggests that a shared implementation is desirable.  This
commit provides an API that supports managing on-off resources.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2020-01-29 14:08:46 +01:00
Ulf Magnusson
a094cafecc gui: kconfig: Fix broken refs to LVGL_OBJ_PRELOAD_DEF_ANIMATION_*
The CONFIG_ prefixes were missing.

Found with a work-in-progress scripts/kconfig/lint.py check.

These are defined in lib/gui/lvgl/Kconfig.objects.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2020-01-25 08:15:17 -05:00
Maureen Helm
ff1cd6e10c gui: Add BGR565 pixel format support to lvgl
Adds support for the BGR565 pixel format to lvgl. This fixes the lvgl
sample for mimxrt10{50,60,64}_evk boards, which were broken when the
mcux elcdif display driver was modified in commit
9041b0f119 to return the BGR565 pixel
format instead of RGB565.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2020-01-22 08:55:16 +01:00
Robert Lubos
665d195f3a net: sockets: tls: Add missing symbols for a few options
`TLS_PEER_VERIFY` and `TLS_DTLS_ROLE` options accept specific values,
yet no symbols were defined for them. In result, magic numbers were used
in several places, making the code less readable.

Fix this issue, by adding the missing symbols to the `socket.h` header,
and using them in places where related socket options are set.

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2020-01-20 09:58:23 +02:00
Joakim Andersson
27bbfb66b4 assert: Completely remove file info and condition expression
Completely remove the file info and condition expression from the
the print statement if they are not enabled. This saves a little code
space which adds up when there are many assert calls.

In bluetooth shell test this saves around 4.5k bytes.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2020-01-13 13:59:55 +01:00
Andrew Boie
d76ae46c0c lib: os: make snprintk fns generally available
The intention of disabling CONFIG_PRINTK is that all
invocations of it will compile to nothing, saving a lot
of runtime overhead and footprint since all the format
strings are completely dropped; instances of printk()
and related functions are no-ops.

However, some subsystems need snprintk() for string
processing, since the snprintf() implementations in even
minimal C library are too costly in text footprint or
stack usage for some applications. This processing is
required for the application to even function.

This patch continues to have disabling  CONFIG_PRINTK to
cause the non snprintk functions to become no-ops, but
now we always compile the necessary bits for snprintk(),
relying on gc-sections to discard them if unused.

z_vprintk() is now unconditionally defined in the header
since it is not tied to any particular output sink and
is intended for users who know exactly what they are
doing (it's in zephyr private scope).

Relates to: #21564

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-01-03 10:13:30 +01:00
Pavlo Hamov
03baef9975 libc: syscall: make aliases WEAK by default
make all syscall functions overridable

Signed-off-by: Pavlo Hamov <pavlo_hamov@jabil.com>
2019-12-17 10:35:20 -08:00
Andrew Boie
c5e3688583 lib: os: don't cast mutex pointers to u32_t
Just use the correct data type.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-12-12 14:48:42 -08:00
Josh Gao
c0026346a3 libc: permit users to supply their own malloc.
Severely memory constrained systems with known allocation patterns can
benefit from providing their own implementation of malloc with
specifically tuned bucket sizes. Provide a switch to allow users to
replace the default malloc implementation with their own.

Signed-off-by: Josh Gao <josh@jmgao.dev>
2019-12-12 10:49:52 -06:00
Ulf Magnusson
984bfae831 global: Remove leading/trailing blank lines in files
Remove leading/trailing blank lines in .c, .h, .py, .rst, .yml, and
.yaml files.

Will avoid failures with the new CI test in
https://github.com/zephyrproject-rtos/ci-tools/pull/112, though it only
checks changed files.

Move the 'target-notes' target in boards/xtensa/odroid_go/doc/index.rst
to get rid of the trailing blank line there. It was probably misplaced.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-12-11 19:17:27 +01:00
Jan Van Winkel
a1e336e7af gui: Added support for LVGL v6.1
Added support for new features in LVGL v6.1

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-12-09 15:07:28 -06:00
Andrew Boie
e794da070a lib: os: uncrustify sem.c
Also fix a spelling error.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-18 13:52:15 +01:00
Andy Ross
8892406c1d kernel/sys_clock.h: Deprecate and convert uses of old conversions
Mark the old time conversion APIs deprecated, leave compatibility
macros in place, and replace all usage with the new API.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-11-08 11:08:58 +01:00
Andrew Boie
4f77c2ad53 kernel: rename z_arch_ to arch_
Promote the private z_arch_* namespace, which specifies
the interface between the core kernel and the
architecture code, to a new top-level namespace named
arch_*.

This allows our documentation generation to create
online documentation for this set of interfaces,
and this set of interfaces is worth treating in a
more formal way anyway.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-07 15:21:46 -08:00
Andrew Boie
ec3aafbf78 printk: print pointers on 64-bit properly
Needs a min-width of 16, not 8, for 64-bit.
Some indentation oddities fixed.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-06 17:50:34 -08:00
Stephanos Ioannidis
2d7460482d headers: Refactor kernel and arch headers.
This commit refactors kernel and arch headers to establish a boundary
between private and public interface headers.

The refactoring strategy used in this commit is detailed in the issue

This commit introduces the following major changes:

1. Establish a clear boundary between private and public headers by
  removing "kernel/include" and "arch/*/include" from the global
  include paths. Ideally, only kernel/ and arch/*/ source files should
  reference the headers in these directories. If these headers must be
  used by a component, these include paths shall be manually added to
  the CMakeLists.txt file of the component. This is intended to
  discourage applications from including private kernel and arch
  headers either knowingly and unknowingly.

  - kernel/include/ (PRIVATE)
    This directory contains the private headers that provide private
   kernel definitions which should not be visible outside the kernel
   and arch source code. All public kernel definitions must be added
   to an appropriate header located under include/.

  - arch/*/include/ (PRIVATE)
    This directory contains the private headers that provide private
   architecture-specific definitions which should not be visible
   outside the arch and kernel source code. All public architecture-
   specific definitions must be added to an appropriate header located
   under include/arch/*/.

  - include/ AND include/sys/ (PUBLIC)
    This directory contains the public headers that provide public
   kernel definitions which can be referenced by both kernel and
   application code.

  - include/arch/*/ (PUBLIC)
    This directory contains the public headers that provide public
   architecture-specific definitions which can be referenced by both
   kernel and application code.

2. Split arch_interface.h into "kernel-to-arch interface" and "public
  arch interface" divisions.

  - kernel/include/kernel_arch_interface.h
    * provides private "kernel-to-arch interface" definition.
    * includes arch/*/include/kernel_arch_func.h to ensure that the
     interface function implementations are always available.
    * includes sys/arch_interface.h so that public arch interface
     definitions are automatically included when including this file.

  - arch/*/include/kernel_arch_func.h
    * provides architecture-specific "kernel-to-arch interface"
     implementation.
    * only the functions that will be used in kernel and arch source
     files are defined here.

  - include/sys/arch_interface.h
    * provides "public arch interface" definition.
    * includes include/arch/arch_inlines.h to ensure that the
     architecture-specific public inline interface function
     implementations are always available.

  - include/arch/arch_inlines.h
    * includes architecture-specific arch_inlines.h in
     include/arch/*/arch_inline.h.

  - include/arch/*/arch_inline.h
    * provides architecture-specific "public arch interface" inline
     function implementation.
    * supersedes include/sys/arch_inline.h.

3. Refactor kernel and the existing architecture implementations.

  - Remove circular dependency of kernel and arch headers. The
   following general rules should be observed:

    * Never include any private headers from public headers
    * Never include kernel_internal.h in kernel_arch_data.h
    * Always include kernel_arch_data.h from kernel_arch_func.h
    * Never include kernel.h from kernel_struct.h either directly or
     indirectly. Only add the kernel structures that must be referenced
     from public arch headers in this file.

  - Relocate syscall_handler.h to include/ so it can be used in the
   public code. This is necessary because many user-mode public codes
   reference the functions defined in this header.

  - Relocate kernel_arch_thread.h to include/arch/*/thread.h. This is
   necessary to provide architecture-specific thread definition for
   'struct k_thread' in kernel.h.

  - Remove any private header dependencies from public headers using
   the following methods:

    * If dependency is not required, simply omit
    * If dependency is required,
      - Relocate a portion of the required dependencies from the
       private header to an appropriate public header OR
      - Relocate the required private header to make it public.

This commit supersedes #20047, addresses #19666, and fixes #3056.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2019-11-06 16:07:32 -08:00
Nicolas Pitre
132b2b8c99 mempool: trap on double-free instances
A double-free could cause very hard to find bugs when using the mempool
allocator as the same memory would end up being allocated twice
afterwards.

Now that bits in the block bitmap are cleared only when actually freeing
a block, we may simply ensure those bits are still set before clearing
them, effectively catching most double-free cases.

The alloc_bit_is_set() function is made static inline so that when
assertion checks are disabled the compiler won't complain about unused
code.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-11-06 21:42:42 +01:00
Ulf Magnusson
39f2281c89 kconfig: Change some '#Comment' comments to '# Comment'
For consistency. Newly-introduced stuff.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-04 17:31:27 -05:00
Ulf Magnusson
bd6e04411e kconfig: Clean up header comments and make them consistent
Use this short header style in all Kconfig files:

    # <description>

    # <copyright>
    # <license>

    ...

Also change all <description>s from

    # Kconfig[.extension] - Foo-related options

to just

    # Foo-related options

It's clear enough that it's about Kconfig.

The <description> cleanup was done with this command, along with some
manual cleanup (big letter at the start, etc.)

    git ls-files '*Kconfig*' | \
        xargs sed -i -E '1 s/#\s*Kconfig[\w.-]*\s*-\s*/# /'

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-04 17:31:27 -05:00
Ulf Magnusson
8cb26d19c6 libc: kconfig: Have MINIMAL_LIBC depend on !REQUIRES_FULL_LIBC
This prevents MINIMAL_LIBC from being selected by the user (in the
menuconfig or in a configuration file) when REQUIRES_FULL_LIBC is y.
'default' on a choice only determines the default selection, not what
symbols can be selected.

It's helpful to think of Kconfig in terms of someone going into the
menuconfig and making changes.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-02 00:31:57 +01:00
Ulf Magnusson
975de21858 kconfig: Global whitespace/consistency cleanup
Clean up space errors and use a consistent style throughout the Kconfig
files. This makes reading the Kconfig files more distraction-free, helps
with grepping, and encourages the same style getting copied around
everywhere (meaning another pass hopefully won't be needed).

Go for the most common style:

 - Indent properties with a single tab, including for choices.

   Properties on choices work exactly the same syntactically as
   properties on symbols, so not sure how the no-indentation thing
   happened.

 - Indent help texts with a tab followed by two spaces

 - Put a space between 'config' and the symbol name, not a tab. This
   also helps when grepping for definitions.

 - Do '# A comment' instead of '#A comment'

I tweaked Kconfiglib a bit to find most of the stuff.

Some help texts were reflowed to 79 columns with 'gq' in Vim as well,
though not all, because I was afraid I'd accidentally mess up
formatting.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-01 15:53:23 +01:00
Jan Van Winkel
9555f82d28 libc: Use select REQUIRES_FULL_LIBC instead of select NEWLIB_LIBC
Changed select NEWLIB_LIBC to select REQUIRES_FULL_LIBC

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-11-01 14:18:36 +01:00
Jan Van Winkel
0e59f6846f libc: Changed dependencies of NEWLIB_C into !MINIMAL_LIBC
Changed Kconfig dependencies of NEWLIB_C into !MINIMAL_LIBC

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-11-01 14:18:36 +01:00
Jan Van Winkel
c1f865b412 libc: Added Kconfig choice to select C library
Added Kconfig choice to select C library implementation

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-11-01 14:18:36 +01:00
Anas Nashif
8d22fd9263 updatehub: move header to library
Not a top-level zephyr core API and tied to third party environment, so
move it to where the code is in lib/updatehub.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-10-25 18:20:20 -04:00
Daniel Leung
b7eb04b300 x86: consolidate x86_64 architecture, SoC and boards
There are two set of code supporting x86_64: x86_64 using x32 ABI,
and x86 long mode, and this consolidates both into one x86_64
architecture and SoC supporting truly 64-bit mode.

() Removes the x86_64:x32 architecture and SoC, and replaces
   them with the existing x86 long mode arch and SoC.
() Replace qemu_x86_64 with qemu_x86_long as qemu_x86_64.
() Updates samples and tests to remove reference to
   qemu_x86_long.
() Renames CONFIG_X86_LONGMODE to CONFIG_X86_64.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2019-10-25 17:57:55 -04:00
Ulf Magnusson
41a0e762ed lib: cmsis_v1: kconfig: Remove unused CMSIS_MAX_THREAD_COUNT symbol
Added in commit ccd1c21824 ("lib/cmsis_rtos_v1: Implement support for
thread APIs"), then never used.

Found with a script.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-10-22 23:02:16 -04:00
Ulf Magnusson
01aa3117ac gui: lvgl: Fix broken CONFIG_LVGL_OBJ_WINDOW check
Was impossible to enable due to a typo. Fix it.

Found with a script (LVGL_OBJ_WINDOW was unused besides
being enabled in tests/lib/gui/lvgl/prj.conf).

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-10-22 11:09:51 +02:00
Peter Bigot
66c8756956 coccinelle: standardize kernel API timeout arguments
Re-run with updated script to detect missed cases.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-10-04 16:23:57 -04:00
Nicolas Pitre
bb7c2e82b1 mempool: remove redundant bit set/clear within loops
When small blocks are recombined to create a single block at a shallower
level, it is sufficient to remove those blocks from the free list. There
is no need to mark those small blocks as allocated in the bitmap.

This, in turn, removes the need to mark small blocks back as unallocated
when splitting up a big blocks as they'll already be so marked.
Only the first small block needs to be marked allocated and the
remaining blocks only need to be added to the free list.

This makes the code smaller and more efficient, especially since those
removed bit manipulations were located within loops.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-10-04 13:42:59 -04:00
Nicolas Pitre
1b193e9ece mempool: reverse free bit semantic
This turns the free-bit flag into an alloc-bit flag effectively
reversing its semantic. This is to make further changes more natural
and easier to understand.

No need to clear the alloc bits at init time as they're located in .bss
and all clear already.

The code remains functionally equivalent after this change.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-10-04 13:42:59 -04:00
Peter Bigot
ab91eef23b coccinelle: standardize kernel API timeout arguments
Use the int_literal_to_timeout Coccinelle script to convert literal
integer arguments for kernel API timeout parameters to the standard
timeout value representations.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-10-03 11:55:44 -07:00
Andrew Boie
fe031611fd kernel: rename main/idle thread/stacks
The main and idle threads, and their associated stacks,
were being referenced in various parts of the kernel
with no central definition. Expose these in kernel_internal.h
and namespace with z_ appropriately.

The main and idle threads were being defined statically,
with another variable exposed to contain their pointer
value. This wastes a bit of memory and isn't accessible
to user threads anyway, just expose the actual thread
objects.

Redundance MAIN_STACK_SIZE and IDLE_STACK_SIZE defines
in init.c removed, just use the Kconfigs they derive
from.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie
4ad9f687df kernel: rename thread return value functions
z_set_thread_return_value is part of the core kernel -> arch
interface and has been renamed to z_arch_thread_return_value_set.

z_set_thread_return_value_with_data renamed to
z_thread_return_value_set_with_data for consistency.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Nicolas Pitre
2129937d3d realloc(): move mempool internal knowledge out of generic lib code
The realloc function was a bit too intimate with the mempool accounting.
Abstract that knowledge away and move it where it belongs.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-09-30 10:57:24 -07:00
Anas Nashif
50d5e37b8a tests: move util test to be unit tests
Move to a unit test, no need to build this for every platform we have.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-09-27 15:23:26 -04:00
Kumar Gala
4cbe5c0961 lib/libc/min: Introduce simple math.h
Introduce math.h to get definitions of float_t and double_t.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-09-27 04:30:07 -07:00
Sebastian Bøe
8610b84d55 cmake: don't link interface libraries with zephyr_interface
Stop linking interface libraries against zephyr_interface. This is
cargo cult code that in practice does nothing.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2019-09-26 05:50:46 -07:00
Paul Sokolovsky
0173d86e6f lib: posix, minlibc: struct itimerspec is defined by sys/timespec.h
Newlib has it defined in sys/timespec.h, and thus per the established
conventions, everything else relies on it being there. Specifically,
minimal libc acquires sys/timespec.h with a similar definition, and
POSIX headers rely on that header. Still with a workaround for old
Newlib version as used by Xtensa (but all infrastructure for that is
already there; actually, this patch removes duplicate similar-infra,
which apparently didn't work as expected by now, so now we have a
single workaround, not 2 different once).

To emphasize a point, now there 2 headers:

sys/_timespec.h, defining struct timespec, and
sys/timespec.h, defining struct itimerspec

That's how Newlib has it, and what we faithfully embrace and follow,
because otherwise, there will be header conflicts depending on
various libc and POSIX subsys options.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-09-25 20:56:29 -07:00
Paul Sokolovsky
0dcee73fe1 lib: posix: Kconfig: Allow to enable individual components
Allow to enable individual POSIX components, like Pthreads.
CONFIG_POSIX_API now just enables all of individual POSIX components,
and sets up environment suitable to easily port POSIX applications to
Zephyr.

Fixes: #12965

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-09-25 20:56:29 -07:00
Kim Sekkelund
0450263393 Bluetooth: Host: Remove printk dependency from settings
Some modules use snprintk to format the settings keys. Unfortunately
snprintk is tied with printk which is very large for some embedded
systems.
To be able to have settings enabled without also enabling printk
support, change creation of settings key strings to use bin2hex, strlen
and strcpy instead.
A utility function to make decimal presentation of a byte value is
added as u8_to_dec in lib/os/dec.c
Add new Kconfig setting BT_SETTINGS_USE_PRINTK

Signed-off-by: Kim Sekkelund <ksek@oticon.com>
2019-09-25 17:36:39 +02:00
Peter A. Bigot
55ace13c32 lib/timeutil: avoid implementation-defined behavior
The algorithm for converting broken-down civil time to seconds in the
POSIX epoch time scale would produce undefined behavior on a toolchain
that uses a 32-bit time_t in cases where the referenced time could not
be represented exactly.

However, there are use cases in Zephyr for civil time conversions
outside the 32-bit representable range of 1901-12-13T20:45:52Z through
2038-01-19T03:14:07Z inclusive.

Add new API that specifically returns a 64-bit signed seconds count, and
revise the existing API to detect out-of-range values and convert them
to a diagnosible error.

Closes #18465

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-09-19 20:49:51 -04:00
Peter A. Bigot
cc1594a59a lib/timeutil: support const correctness for pointer parameter
timeutil_timegm() does not modify the passed structure, so it should
indicate that in the signature (even though the GNU extension does not).

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-09-19 20:49:51 -04:00
Peter Bigot
dfd26dbbeb libc/minimal/assert: conditionalize static_assert macro
static_assert was not added to C until C11.  Zephyr builds default to
C99.  To preserve compatibility with newlib avoid defining the
macro at standard levels where it did not exist.

Relates to #17738 and #11754.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-09-19 09:37:42 -05:00
Andy Ross
643701aaf8 kernel: syscalls: Whitespace fixups
The semi-automated API changes weren't checkpatch aware.  Fix up
whitespace warnings that snuck into the previous patches.  Really this
should be squashed, but that's somewhat difficult given the structure
of the series.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Andy Ross
346cce31d8 kernel: Port remaining buildable syscalls to new API
These calls are buildable on common sanitycheck platforms, but are not
invoked at runtime in any tests accessible to CI.  The changes are
mostly mechanical, so the risk is low, but this commit is separated
from the main API change to allow for more careful review.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Andy Ross
6564974bae userspace: Support for split 64 bit arguments
System call arguments, at the arch layer, are single words.  So
passing wider values requires splitting them into two registers at
call time.  This gets even more complicated for values (e.g
k_timeout_t) that may have different sizes depending on configuration.
This patch adds a feature to gen_syscalls.py to detect functions with
wide arguments and automatically generates code to split/unsplit them.

Unfortunately the current scheme of Z_SYSCALL_DECLARE_* macros won't
work with functions like this, because for N arguments (our current
maximum N is 10) there are 2^N possible configurations of argument
widths.  So this generates the complete functions for each handler and
wrapper, effectively doing in python what was originally done in the
preprocessor.

Another complexity is that traditional the z_hdlr_*() function for a
system call has taken the raw list of word arguments, which does not
work when some of those arguments must be 64 bit types.  So instead of
using a single Z_SYSCALL_HANDLER macro, this splits the job of
z_hdlr_*() into two steps: An automatically-generated unmarshalling
function, z_mrsh_*(), which then calls a user-supplied verification
function z_vrfy_*().  The verification function is typesafe, and is a
simple C function with exactly the same argument and return signature
as the syscall impl function.  It is also not responsible for
validating the pointers to the extra parameter array or a wide return
value, that code gets automatically generated.

This commit includes new vrfy/msrh handling for all syscalls invoked
during CI runs.  Future commits will port the less testable code.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Kumar Gala
749ca106a0 libc: Make libc-nano default for ARM toolchain if newlib
The ARM embedded toolchain has 2 newlib based libc build variants, one
that utilizes the "nano" configuration which is more in line with the
Zephyr SDK.  Make the "nano" cfg the default if newlib is enabled to
match closer how the Zephyr SDK behaves.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-08-28 10:59:29 -05:00
Paul Sokolovsky
0906671a7b posix: pthread: pthread_mutex_timedlock should accept absolute deadline
It was coded as if it accepts relative timeout. Normative reference:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_timedlock.html

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-27 17:50:48 -04:00
Paul Sokolovsky
68c7dc6b96 posix: pthread: pthread_cond_timedwait should accept absolute deadline
Instead, it was coded as if it accepted a relative timeout. Normative
reference:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html

Fixes: #17812

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-27 17:50:48 -04:00