Commit graph

1698 commits

Author SHA1 Message Date
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
Paul Sokolovsky
6c5a08899a posix: fs: ZFD_IOCTL_CLOSE: Be sure to call posix_fs_free_obj()
To make sure that entry in fs.c:desc_array[] is freed. Note that
freeing an entry in fdtable is handled by generic implementation
of close().

Fixes: #17231

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-27 10:34:54 -04:00
Andrew Boie
aed767a98c libc: newlib: make sbrk() thread-safe
Concurrent use of this function could lead to corruption.
Use a sys_sem to synchronize access.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-08-22 07:38:56 -05:00
Paul Sokolovsky
5b3df8a180 posix: pthread_create: Ignore retval of pthread_mutex_init() calls
pthread_mutex_init() just redirects to Zephyr kernel primitive, for
initializing structure fields. So, use the knowledge that it can't
fail (for as long as structure pointer is initialized, and here it's
from pre-allocated array), and ignore return value of
pthread_mutex_init()

Coverity-CID: 203542
Fixes: #18371

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-21 07:26:59 -05:00
Peter Bigot
96c1b05125 lib/newlib: revert treatment of libc files as system includes
The solution from #14312 of using -isystem to prioritize the position of
the libc directory bypasses the effect of -ffreestanding with respect to
libc symbols expected to be present in a non-hosted environment.

Further, it breaks C++ with the ARM Embedded toolchain as the system
fails to find the right file with #include_next.

Use a more fine-grained solution that explicitly includes the underlying
newlib header required for <inttypes.h> support before moving on to
include the next available one, whether system or non-system.

Closes #17564

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-08-20 12:51:16 -05:00
Peter Bigot
849df51666 lib/libc: rearrange for standard use of extern "C"
Consistently place C++ use of extern "C" after all include directives,
within the negative branch of _ASMLANGUAGE if used.

Background from issue #17997:

Declarations that use C linkage should be placed within extern "C"
so the language linkage is correct when the header is included by
a C++ compiler.

Similarly #include directives should be outside the extern "C" to
ensure the language-specific default linkage is applied to any
declarations provided by the included header.

See: https://en.cppreference.com/w/cpp/language/language_linkage
Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-08-19 23:36:59 +02:00
Peter Bigot
b6dafeb612 include/lvgl: rearrange for standard use of extern "C"
Consistently place C++ use of extern "C" after all include directives,
within the negative branch of _ASMLANGUAGE if used.

Background from issue #17997:

Declarations that use C linkage should be placed within extern "C"
so the language linkage is correct when the header is included by
a C++ compiler.

Similarly #include directives should be outside the extern "C" to
ensure the language-specific default linkage is applied to any
declarations provided by the included header.

See: https://en.cppreference.com/w/cpp/language/language_linkage
Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-08-13 18:00:31 +02:00
Jan Van Winkel
55c3585f18 gui: Corrected paths in Zephyr to LVGL FS mapping
Corrected path handling between zephyr and LVGL FS API

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-08-09 07:35:38 -05:00
Jan Van Winkel
fa27e583a1 gui: Disable LVGL features by default
Removed 'default y' from LVGL Kconfig files to disable features by
default

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-08-09 07:35:38 -05:00
Jan Van Winkel
6bbd4cbaa3 gui: Add support for lvgl API version 6
Added support for lvgl API version 6

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-08-09 07:35:38 -05:00
Peter A. Bigot
ef4cd6a1ab lib/libc/minimal: Refined handle duplicate time definitions
Follow the approach of newlib to use a file sys/_types.h to specify the
underlying type for POSIX/libc types that must be provided in multiple
headers.  The identifier for this type is in the reserved namespace.

Use this type rather than a specific standard type in all headers that
need to provide the type under its public name.

Remove the inclusion of <sys/types.h> from headers that should not bring
in all symbols present in that header, replacing it with the standard
boilerplate to expose the specific symbols that are required.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-08-09 00:43:09 -07:00
Kumar Gala
daf9f11024 lib/libc/min: Handle duplicate time definitions
time_t and suseconds_t are defined in time.h and sys/types.h.  Handle
the duplication by adding ifdef protection around them similar to what
is being done for other types.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-08-09 00:43:09 -07:00
Paul Sokolovsky
f0d483aaa6 lib: posix: Switch to use zephyr_interface_library_named cmake directive
Similar to how other sub-libraries are defined in Zephyr tree, e.g.
"fs", "lgvl", etc. This is supposed to help with the need to
explicitly add posix include path to each and every application using
POSIX subsys.

Fixes: #15627

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-08 14:31:35 +02:00
Paul Sokolovsky
7d2df83b51 libc: minimal: Add headers as system includes
This is consistent with how newlib headers are treated, and will
have effect of ninlibc headers to be further down in the include
order. This is important, because some POSIX subsys headers
override those of libc. Without this change, we can't streamline
POSIX build config using zephyr_interface_library_named() cmake
directive, because includes will be in wrong order.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-08 14:31:35 +02:00
Paul Sokolovsky
ff6432edad lib: posix: Use "posix_subsys" as the CMake lib for the subsystem.
Historically, it used to be "PTHREAD", which is no longer true, as
POSIX subsys offers much more functionality than just Pthreads. Use
detailed name, like "posix_subsys", to avoid possible confusion with
ARCH_POSIX-related matters.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-08-08 14:31:35 +02:00
Nicolas Pitre
1f4b5ddd0f riscv32: rename to riscv
With the upcoming riscv64 support, it is best to use "riscv" as the
subdirectory name and common symbols as riscv32 and riscv64 support
code is almost identical. Then later decide whether 32-bit or 64-bit
compilation is wanted.

Redirects for the web documentation are also included.

Then zephyrbot complained about this:

"
New files added that are not covered in CODEOWNERS:

dts/riscv/microsemi-miv.dtsi
dts/riscv/riscv32-fe310.dtsi

Please add one or more entries in the CODEOWNERS file to cover
those files
"

So I assigned them to those who created them. Feel free to readjust
as necessary.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-08-02 13:54:48 -07:00
Peter A. Bigot
8420f43b86 libc: minimal: add strspn and strcspn support
These functions are useful for determining prefixes, as with file system
paths.  They are required by littlefs.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-07-31 09:22:49 -07:00
Peter A. Bigot
b8af1a6a4e libc/minimal: fix reproducibility of gmtime
struct tm has fields that were not being set by the implementation,
causing the test to fail when the uninitialized values were compared
with a static initialized result.  Zero the structure before filling it.

Closes #17794

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-07-31 11:48:18 +03:00
Paul Sokolovsky
6b90a02bb4 libc: minimal: time.h: Don't (re)define struct timespec.
By the latest convention, libc's define struct timespec in
sys/_timespec.h. This is consistent with Newlib and ensures
about errors due to redefinitions.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-07-25 13:50:58 -04:00
Paul Sokolovsky
b7bb48eeac posix: unistd.h: open() doesn't belong here
Per POSIX, open() is defined in <fcntl.h>. fcntl.h in turn comes from
the underlying libc, either newlib, or minimal libc.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-07-25 13:50:58 -04:00
Paul Sokolovsky
1347bf9b48 posix: mqueue.h: Move O_CREAT and friends to fcntl.h
That's the header which is supposed to define them, there was even
FIXME on that in mqueue.h.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-07-25 13:50:58 -04:00
Paul Sokolovsky
3a4553913e posix: struct timespec: Move definition to sys/_timespec.h
POSIX subsys defines struct timespec in <time.h> (as POSIX public
API requires), but newlib defines in in sys/_timespec.h, which
inevitably leads to inclusion order and redifinition conflicts.
Follow newlib way and define it in single place, sys/_timespec.h,
which belongs to libc namespace. Thus, we move current definition
to minimal libc, and will use either minlibc's or newlib's
definition, instead of trying to redefine it.

This is similar to the introduction of sys/_timeval.h done earlier.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-07-25 13:50:58 -04:00
Paul Sokolovsky
3693f85805 posix: Move sys/stat.h to minimal libc
Newlib libc already provides sys/stat.h, so trying to have sys/stat.h
on the level of POSIX subsys inevitable leads to include order and
definition conflicts. Instead (as most of other sys/* includes)
should come from the underlying libc.

While moving, made unrelated change of removing #include <kernel.h>,
to accommodate the change reviewers.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-07-25 13:50:58 -04:00
Wentong Wu
715369350d lib: os: add sys_sem data type
For systems with userspace, the sys_sem exist in user memory working
as counter semaphore for user mode thread. The implemention of sys_sem
is based on k_futex. And the majority of the synchronization operations
are performed in user mode to reduce the calling of system call.
And for systems without userspace enabled, sys_sem behaves like k_sem.

Fixes: #15139.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-07-24 10:12:25 -07:00
Andrew Boie
39425eaada assert: generate oops if invoked from usermode
User mode isn't allowed to generate a panic and this would
lead to a confusing privilege violation exception.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-20 08:29:39 -04:00
Peter A. Bigot
9d25b671bc sys: timeutil: add module
Add a generic API to provide the inverse operation for gmtime and as a
home for future generic time-related functions that are not in POSIX.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-07-17 14:04:44 +02:00
Peter A. Bigot
3e8df8b369 libc: minimal: provide gmtime implementation
Implement the conversion from UNIX time to broken-down civil time per
the gmtime() and gmtime_r() functions.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-07-17 14:04:44 +02:00
Peter A. Bigot
acc1703241 libc: minimal: provide types in time.h
Provide definitions for a subset of the standard time types that must be
provided by this file, in anticipation of supporting civil time in
Zephyr.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-07-17 14:04:44 +02:00
Nicolas Pitre
629bd85612 mempool: significant reduction of memory waste
The mempool allocator implementation recursively breaks a memory block
into 4 sub-blocks until it minimally fits the requested memory size.

The size of each sub-blocks is rounded up to the next word boundary to
preserve word alignment on the returned memory, and this is a problem.

Let's consider max_sz = 2072 and n_max = 1. That's our level 0.

At level 1, we get one level-0 block split in 4 sub-blocks whose size
is WB_UP(2072 / 4) = 520. However 4 * 520 = 2080 so we must discard the
4th sub-block since it doesn't fit inside our 2072-byte parent block.

We're down to 3 * 520 = 1560 bytes of usable memory.
Our memory usage efficiency is now 1560 / 2072 = 75%.

At level 2, we get 3 level-1 blocks, and each of them may be split
in 4 sub-blocks whose size is WB_UP(520 / 4) = 132. But 4 * 132 = 528
so the 4th sub-block has to be discarded again.

We're down to 9 * 132 = 1188 bytes of usable memory.
Our memory usage efficiency is now 1188 / 2072 = 57%.

At level 3, we get 9 level-2 blocks, each split into WB_UP(132 / 4)
= 36 bytes. Again 4 * 36 = 144 so the 4th sub-block is discarded.

We're down to 27 * 36 = 972 bytes of usable memory.
Our memory usage efficiency is now 972 / 2072 = 47%.

What should be done instead, is to round _down_ sub-block sizes
not _up_. This way, sub-blocks still align to word boundaries, and
they always fit within their parent block as the total size may
no longer exceed the initial size.

Using the same max_sz = 2072 would yield a memory usage efficiency of
99% at level 3, so let's demo a worst case 2044 instead.

Level 1: 4 sub-blocks of WB_DN(2044 / 4) = 508 bytes.
We're down to 4 * 508 = 2032 bytes of usable memory.
Our memory usage efficiency is now 2032 / 2044 = 99%.

Level 2: 4 * 4 sub-blocks of WB_DN(508 / 4) = 124 bytes.
We're down to 16 * 124 = 1984 bytes of usable memory.
Our memory usage efficiency is now 1984 / 2044 = 97%.

Level 3: 16 * 4 sub-blocks of WB_DN(124 / 4) = 28 bytes.
We're down to 64 * 28 = 1792 bytes of usable memory.
Our memory usage efficiency is now 1792 / 2044 = 88%.

Conclusion: if max_sz is a power of 2 then we get 100% efficiency at
all levens in both cases. But if not, then the rounding-up method has
a far worse degradation curve than the rounding-down method, wasting
more than 50% of memory in some cases.

So let's round sub-block sizes down rather than up, and remove
block_fits() which purpose was to identify sub-blocks that didn't
fit within their parent block and is now useless.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-16 14:21:21 -07:00
Nicolas Pitre
8e11970378 realloc(): struct sys_mem_pool_block is word aligned
Since commit 39cd2ebef7 ("malloc: make sure returned memory is
properly aligned") the size of struct sys_mem_pool_block size is
rounded up to the next word boundary.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-16 14:42:37 +02:00
Joakim Andersson
7a93e948a9 kernel: lib: Add convert functions for hex strings and binary arrays
Move duplicate hex2bin and add bin2hex function so that application can
use the functions and avoid code duplication.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2019-07-16 12:44:18 +02:00
Nicolas Pitre
3c0cc08657 prf.c: handle denormals properly
Denormals need to be normalized to be displayed properly.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
53169743d2 prf.c: properly format INF/NAN/zero with prefix
The space or plus prefix must appear when requested even with INF and
NAN. And no zero-padding in that case.

Also, 0.0 and -0.0  are distinct values. It is necessary to display
the minus sign with a negative zero.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
90ec5360be prf.c: fix wrong results with %g conversion
The precision parameter to the %g conversion indicates the maximum
number of significant digits and not the number of digits to appear
after the radix character. Here's a few examples this patch fixes:

                                expected        before
----------------------------------------------------------
printf("%.3g", 150.12)          150             150.12
printf("%.2g", 150.1)           1.5e+02         150.1
printf("%#.3g", 150.)           150.            150.000
printf("%#.2g", 15e-5)          0.00015         0.00
printf("%#.4g", 1505e-7)        0.0001505       0.0002
printf("%#.4g", 1505e-8)        1.505e-05       1.5050e-05

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
132a286c39 prf.c: fix display of float exponent >= 100
The code accounts only for 2 exponent digits even though the exponent
may grow up to 308. Before this change, printf("%g", 1e300) would
produce "1e+N0".

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
f286eda6f0 prf.c: remove arbitrary large stack buffer usage
The on-stack work buffer occupies 201 bytes by default. Now that we've
made the code able to cope with virtually unlimited width and precision
values, we can reduce stack usage to its strict minimum i.e. 25 bytes.

This allows for some additional sprintf tests exercizing wide results.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
d28434b4fa prf.c: remove buffer limitation on precision and padding for floats
Even if the code used to limit the precision to the on-stack buffer
size, it was still possible to do:

    printf("%f", 1.0e300);

which would overflow the stack and crash the program. Let fix this issue
and remove the precision limitation by recording the number of zeroes to
insert while converting the value and generating those zeroes only
when outputting the data.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
7c7f107885 prf.c: remove buffer limitation on field width and padding for integers
Zero-padding of integers took place in the on-stack buffer before
justification. Let's perform that padding on the fly while sending
out data instead.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
33312cfd98 prf.c: remove buffer limitation on field width and string copy
The z_prf() function currently allocates a 200-byte buffer on the
stack to copy strings into, and then perform left/right alignment
and padding. Not only this is a pretty large chunk of stack usage,
but this imposes limitations on field width and string length. Also
the string is copied not only once but _thrice_ making this code
less than optimal.

Let's rework the code to get rid of both the field width limit and
string length limit, as well as the two extra memory copy instances.

While at it, let's fixes printf("%08s", "abcd") which used to
produce "0000abcd".

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
4ad2a8f990 prf.c: don't be silent with unknown conversion specifiers
Mimic the glibc behavior when encountering an unknown conversion
specifier rather than silently skipping it.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
ab59209ea6 prf.c: abstract output method call
This makes for nicer code by avoiding repetitions of the same pattern.
Changes to come will make more use of it.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
e1d8c1f8ca prf.c: implement the "hh" length modifier
For completeness.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
e9b1cc5f31 prf.c: code and style cleanup
Some cleanups before further changes:

- Remove dead leftover from the "case 's'" code.

- Remove needless parents and casts.

- Remove "register" qualifier as it is ignored. The compiler knows
  better these days.

- Adjust tabs assuming standard 8-columns tab spacing.

- Make multi-line comments start with "/*" on a line of its own.

- Make the format string const to match  prototypes in other files.

- Declare boolean variable and parameters as bool.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-14 23:07:44 -04:00
Nicolas Pitre
ff7e4e69c8 realloc(): fix possible memory leak
If size is equal to zero, and ptr is not NULL, then the call must be
equivalent to free(ptr).

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-12 14:08:02 -07:00
Nicolas Pitre
ffab197928 libc: fix memchr() prototype
The standard memchr() uses an int for its second argument.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-10 13:42:31 -07:00
Timo Teräs
55dc481a15 libc: add strnlen implementation
This is standard function and useful for application writers.

Signed-off-by: Timo Teräs <timo.teras@iki.fi>
2019-07-10 13:41:20 -07:00
Jukka Rissanen
b889120ca7 Revert "libc: types: Remove wrong definition"
This reverts commit 2a63e342f4.

This needs to be reverted as otherwise the type of ssize_t will be
"unsigned long" which is not correct.

    (gdb) ptype ssize_t
    type = unsigned long

For example this check would fail in that case

    ssize_t foo(void)
    {
        return -1;
    }
    ...
    if (foo() < 0) {
        printk("This is never called\n");
    }

Fixes #17378

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2019-07-09 21:55:05 +03:00
Jan Van Winkel
18ef131c80 gui: Move lvgl into a zephyr module
Removed lvgl sources from CMakefile.txt and only keep zephyr glue
logic.

Further added lvgl module to west.yml.

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-07-06 07:58:44 -04:00
Nicolas Pitre
1b359e6426 limits.h: streamline value definitions
Compilers (at least gcc and clang) already provide max value definitions
for basic types. It makes sense to rely on them to properly support
both 32-bit and 64-bit builds.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-05 10:05:37 -04:00
Nicolas Pitre
39cd2ebef7 malloc: make sure returned memory is properly aligned
The accounting data stored at the beginning of a memory block used by
malloc must push the returned memory address to a word boundary. This
is already the case on 32-bit systems, but not on 64-bit systems where
e.g. struct k_mem_block_id still has a size of 4.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-03 14:17:29 -07:00
Andy Ross
ee4c23cc1f CMSIS v2: Work around time unit confusion
The current CMSIS v2 implementation is clearly assuming that timeout
arguments being passed to e.g. osDelay() are in units of Zephyr ticks,
not milliseconds as specified by ARM or (inconsistently) assumed by
our test code.

Most tests work with the ~100 Hz default tick rate, but they tend to
fail on precision issues at higher tick rates.  Force the CMSIS v2
applications to be 1000 Hz for now as a workaround, and detect the
mismatch as a build failure.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-07-02 22:52:29 -04:00
Nicolas Pitre
fc4ca923bb mempool: fully use the inline free block bitmap on 64-bit targets
The "bits" field in struct sys_mem_pool_lvl is unioned with a pointer.
That leaves more space for inline free bits on 64-bit targets.
Let's declare it as an array and adjust its size based on the pointer
size. On 32-bit targets the generated code remains identical.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-02 19:41:20 -07:00
Nicolas Pitre
cf974371fb mempool: make alignment/rounding 64-bit compatible
Minimum alignment and rounding must be done on a word boundary. Let's
replace _ALIGN4() with WB_UP() which is equivalent on 32-bit targets,
and 64-bit aware.

Also enforce a minimal alignment on the memory pool. This is making
a difference mostly on64-bit targets where the widely used 4-byte
alignment is not sufficient.

The _ALIGN4() macro has no users left so it is removed.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-02 19:41:20 -07:00
Andrew Boie
d045bd7673 lib: os: exclude z_arch_printk_char_out()
This function doesn't do anything, and only exists so that
it can be overridden later, exclude from coverage reports.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-28 20:04:29 -07:00
Andrew Boie
05212e823f lib: os: fix vsnprintk coverage
vsnprintk() was uncovered. Simply adjust snprintk() to use
it, instead of duplicating logic.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-28 20:04:29 -07:00
Anas Nashif
5b0aa794b2 cleanup: include/: move misc/reboot.h to power/reboot.h
move misc/reboot.h to power/reboot.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
efb8df5366 cleanup: include/: move misc/stack.h to debug/stack.h
move misc/stack.h to debug/stack.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
a2fd7d70ec cleanup: include/: move misc/util.h to sys/util.h
move misc/util.h to sys/util.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
d222553931 cleanup: include/: move misc/speculation.h to sys/speculation.h
move misc/speculation.h to sys/speculation.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
536dd5a71f cleanup: include/: move misc/slist.h to sys/slist.h
move misc/slist.h to sys/slist.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
1859244b64 cleanup: include/: move misc/rb.h to sys/rb.h
move misc/rb.h to sys/rb.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
9ab2a56751 cleanup: include/: move misc/printk.h to sys/printk.h
move misc/printk.h to sys/printk.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
0c9e280547 cleanup: include/: move misc/mutex.h to sys/mutex.h
move misc/mutex.h to sys/mutex.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
08ee8b09ba cleanup: include/: move misc/mempool.h to sys/mempool.h
move misc/mempool.h to sys/mempool.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
1ed300b318 cleanup: include/: move misc/mempool_base.h to sys/mempool_base.h
move misc/mempool_base.h to sys/mempool_base.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
6ecadb03ab cleanup: include/: move misc/math_extras.h to sys/math_extras.h
move misc/math_extras.h to sys/math_extras.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
447311ec3e cleanup: include/: move misc/libc-hooks.h to sys/libc-hooks.h
move misc/libc-hooks.h to sys/libc-hooks.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
8be9f5de03 cleanup: include/: move misc/fdtable.h to sys/fdtable.h
move misc/fdtable.h to sys/fdtable.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
896b8d3c50 cleanup: include/: move misc/errno_private.h to sys/errno_private.h
move misc/errno_private.h to sys/errno_private.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
5eb90ec169 cleanup: include/: move misc/__assert.h to sys/__assert.h
move misc/__assert.h to sys/__assert.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
7435e5e089 cleanup: include/: move ring_buffer.h to sys/ring_buffer.h
move ring_buffer.h to sys/ring_buffer.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
9e35d53d1f cleanup: include/: move display.h to drivers/display.h
move display.h to drivers/display.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
f901e26de9 cleanup: include/: move hwinfo.h to drivers/hwinfo.h
move hwinfo.h to drivers/hwinfo.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
fe051a9055 cleanup: include/: move flash.h to drivers/flash.h
move flash.h to drivers/flash.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
0abdacf3a4 cleanup: include/: move json.h to data/json.h
move json.h to data/json.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
4e48e87fd2 cleanup: include/: move crc.h to sys/crc.h
move crc.h to sys/crc.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
bd977d06f8 cleanup: include/: move base64.h to sys/base64.h
move base64.h to sys/base64.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
e1e05a2eac cleanup: include/: move atomic.h to sys/atomic.h
move atomic.h to sys/atomic.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif
656f4dfdac cleanup: include/: move fs.h to fs/fs.h
move fs.h to fs/fs.h and
create a shim for backward-compatibility.

No functional changes to the headers.
A warning in the shim can be controlled with CONFIG_COMPAT_INCLUDES.

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Daniel Leung
1c5fa6a128 cmake: use sdk-ng built toolchain for x86_64
This adds the necessary bits to utilize the x86_64 toolchain
built by sdk-ng for x86_64 when toolchain variant is either
zephyr or xtools. This allows decoupling the builds from
the host toolchain.

Newlib is also available with this toolchain so remove
the Kconfig restriction on CONFIG_NEWLIB_LIBC.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2019-06-27 16:08:32 -04:00
Flavio Ceolin
2a63e342f4 libc: types: Remove wrong definition
types.h was wrongly defining unsigned as signed and following
undefining it. This definition was not being used anywhere though.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-06-27 07:17:04 -04:00
Ioannis Glaropoulos
ff07fc7f0a lib: libc: fix alignment of HEAP base address for ARM
In ARM builds with support for user mode, i.e. with
CONFIG_USERSPACE=y, we need to align the beginning
of the heap space, to respect the ARM MPU region
alignment requirements.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-06-26 09:11:45 -04:00
Ioannis Glaropoulos
53ec19c3cc lib: libc: newlib: define USED_RAM_END_ADDR only where it is needed
USED_RAM_END_ADDR is not used when Kconfig option
CONFIG_NEWLIB_LIBC_ALIGNED_HEAP_SIZE is defined,
therefore, we do not need to define the macro in
that specific case.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-06-26 09:11:45 -04:00
Nicolas Pitre
f32330b22c stdint.h: streamline type definitions
Compilers (at least gcc and clang) already provide definitions to
create standard types and their range. For example, __INT16_TYPE__ is
normally defined as a short to be used with the int16_t typedef, and
__INT16_MAX__ is defined as 32767. So it makes sense to rely on them
rather than hardcoding our own, especially for the fast types where
the compiler itself knows what basic type is best.

Using compiler provided definitions makes even more sense when dealing
with 64-bit targets where some types such as intptr_t and size_t must
have a different size and range. Those definitions are then adjusted
by the compiler directly.

However there are two cases for which we should override those
definitions:

* The __INT32_TYPE__ definition on 32-bit targets vary between an int
  and a long int depending on the architecture and configuration.
  Notably, all compilers shipped with the Zephyr SDK, except for the
  i586-zephyr-elfiamcu variant, define __INT32_TYPE__ to a long int.
  Whereas, all Linux configurations for gcc, both 32-bit and 64-bit,
  always define __INT32_TYPE__ as an int. Having variability here is
  not welcome as pointers to a long int and to an int are not deemed
  compatible by the compiler, and printing an int32_t defined with a
  long using %d makes the compiler to complain, even if they're the
  same size on 32-bit targets. Given that an int is always 32 bits
  on all targets we might care about, and given that Zephyr hardcoded
  int32_t to an int before, then we just redefine __INT32_TYPE__ and
  derrivatives to an int to keep the peace in the code.

* The confusion also exists with __INTPTR_TYPE__. Looking again at the
  Zephyr SDK, it is defined as an int, even even when __INT32_TYPE__ is
  initially a long int. One notable exception is i586-zephyr-elf where
  __INTPTR_TYPE__ is a long int even when using -m32. On 64-bit targets
  this is always a long int. So let's redefine __INTPTR_TYPE__ to always
  be a long int on Zephyr which simplifies the code, works for both
  32-bit and 64-bit targets, and mimics what the Linux kernel does.
  Only a few print format strings needed adjustment.

In those two cases, there is a safeguard to ensure the type we're
enforcing has the right size and fail the build otherwise.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-25 23:29:22 -04:00
Nicolas Pitre
d4b60d691c malloc: no longer need to round mempool's max_sz
Since commit 465b2cf31b this value is rounded at compile time instead.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-25 23:24:53 -04:00
Nicolas Pitre
1140bd090c mempool: properly use the inline free block bitmap
The free block bitmap uses either extra memory specified by a pointer
in struct sys_mem_pool_lvl or the space occupied by that pointer
directly if the bitmap length is small enough to fit it.

But the test is wrong. the inline bitmap should be used if the number
of required bits is smaller or _equal_ to the pointer size. Not doing so
would wrongly bounce the free block bitmap to extra memory when the
number of blocks is exactly 32, which is in disagreement with
Z_MPOOL_LBIT_WORDS() that correctly returns 0 in that case.

In theory that mean that this bug would causes an overflow of the free
block bitmap whenever one level has exactly 32 blocks. But right now
there is a separate bug fixed separately that over-sizes the extra block
bitmap mitigating this bug.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-25 23:24:05 -04:00
Andy Ross
d0490fe9f9 lib/os/mempool: Fix corruption case with block splitting
The block_fits() predicate was borked.  It would check that a block
fits within the bounds of the whole heap.  But that's not enough:
because of alignment changes between levels the sub-blocks may be
adjusted forward.  It needs to fit inside the PARENT block that it was
split from.

What could happen at runtime is that the last subblocks of a
misaligned parent block would overlap memory from subsequent blocks,
or even run off the end of the heap.  That's bad.

Change the API of block_fits() a little so it can extract the parent
region and do this properly.

Fixes #15279.  Passes test introduced in #16728 to demonstrate what
seems like the same issue.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-06-25 18:51:08 -07:00
Nicolas Pitre
465b2cf31b mempool: fix corruption of the free block bitmap and beyond
In z_sys_mem_pool_block_alloc() the size of the first level block
allocation is rounded up to the next 4-bite boundary. This means one
or more of the trailing blocks could overlap the free block bitmap.

Let's consider this code from kernel.h:

  #define K_MEM_POOL_DEFINE(name, minsz, maxsz, nmax, align) \
       char __aligned(align) _mpool_buf_##name[_ALIGN4(maxsz * nmax) \
                              + _MPOOL_BITS_SIZE(maxsz, minsz, nmax)]; \

The static pool allocation rounds up the product of maxsz and nmax not
size of individual blocks. If we have, say maxsz = 10 and nmax = 20,
the result of _ALIGN4(10 * 20) is 200. That's the offset at which the
free block bitmap will be located.

However, because z_sys_mem_pool_block_alloc() does this:

        lsizes[0] = _ALIGN4(p->max_sz);

Individual level 0 blocks will have a size of 12 not 10. That means
the 17th block will extend up to offset 204, 18th block up to 216, 19th
block to 228, and 20th block to 240. So 4 out of the 20 blocks are
overflowing the static pool area and 3 of them are even located
completely outside of it.

In this example, we have only 20 blocks that can't be split so there is
no extra free block bitmap allocation beyond the bitmap embedded in the
sys_mem_pool_lvl structure. This means that memory corruption will
happen in whatever data is located alongside the _mpool_buf_##name
array. But even with, say, 40 blocks, or larger blocks, the extra bitmap
size would be small compared to the extent of the overflow, and it would
get corrupted too of course.

And the data corruption will happen even without allocating any memory
since z_sys_mem_pool_base_init() stores free_list pointer nodes into
those blocks, which in turn may get corrupted if that other data is
later modified instead.

Fixing this issue is simple: rounding on the static pool allocation is
"misparenthesized". Let's turn

	_ALIGN4(maxsz * nmax)

into

	_ALIGN4(maxsz) * nmax

But that's not sufficient.

In z_sys_mem_pool_base_init() we have:

        size_t buflen = p->n_max * p->max_sz, sz = p->max_sz;
        u32_t *bits = (u32_t *)((u8_t *)p->buf + buflen);

Considering the same parameters as above, here we're locating the extra
free block bitmap at offset `buflen` which is 20 * 10 = 200, again below
the reach of the last 4 memory blocks. If the number of blocks gets past
the size of the embedded bitmap, it will overlap memory blocks.

Also, the block_ptr() call used here to initialize the free block linked
list uses unrounded p->max_sz, meaning that it is initially not locating
dlist nodes within the same block boundaries as what is expected from
z_sys_mem_pool_block_alloc(). This opens the possibility for allocated
adjacent blocks to overwrite dlist nodes, leading to random crashes in
the future.

So a complete fix must round up p->max_sz here too.

Given that runtime usage of max_sz should always be rounded up, it is
then preferable to round it up once at compile time instead and avoid
further mistakes of that sort. The existing _ALIGN4() usage on p->max_sz
at run time are then redundant.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-24 12:10:09 -07:00
Anas Nashif
f2cb20c772 docs: fix misspelling across the tree
Found a few annoying typos and figured I better run script and
fix anything it can find, here are the results...

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-19 15:34:13 -05:00
David B. Kinder
2aebc980e2 doc: fix Kconfig misspellings
Fix misspellings in Kconfig files missed during regular reviews.

Signed-off-by: David B. Kinder <david.b.kinder@intel.com>
2019-06-18 15:07:52 -04:00
Andrew Boie
db84a76379 lib: os: remove dead code
If multithreading is disabled, thread_entry() never runs
since we cannot create threads; the non-multithreading case
was simply dead code.

Indicate to code coverage that CODE_UNREACHABLE should be
skipped.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-18 09:08:01 -04:00
Nicolas Pitre
c47bf1fa5e prf.c: implement the ll length modifiers
This allows for printing long long values. Because the code size
increase may be significant, this is made optional on 32-bit targets.
On 64-bit targets this doesn't change the code much as longs and
long longs are the same size so it is always enabled in that case.

The test on MAXFLD has to be adjusted accordingly. Yet, its minimum
value wasn't large enough to store a full-scale octal value, so this
is fixed as well.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-17 10:58:09 -07:00
Nicolas Pitre
2b32059a61 printk: make it 64-bit compatible
On 64-bit systems the most notable difference is due to longs and
pointers being 64-bit wide. Therefore there must be a distinction
between ints and longs. Similar to the prf.c case, this patch properly
implements the h, hh, l, ll and z length modifiers as well as some small
cleanups.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-17 10:28:44 -07:00
Nicolas Pitre
a6891e0313 prf.c: make it 64-bit compatible
On 64-bit systems the most notable difference is due to longs and
pointers being 64-bit wide. Therefore there must be a distinction
between ints and longs.

This patch:

- Make support functions take a long rather than an int as this can
  carry both longs and ints just fine.

- Use unsigned values in _to_x() to cover the full unsigned range
  and avoid sign-extending big values. Negative values are already
  converted to unsigned after printing the minus sign. This also makes
  division and modulus operations slightly faster.

- Remove excessive casts around va_arg() and use proper types with it.

- Implement the l and z length modifiers as they're significant on
  64-bit targets. While at it, throw in the z modifier as well.
  Since they all come down to 32-bit values on 32-bit targets, the
  added code should get optimized away as duplicate by the compiler
  in that case.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-13 12:55:17 -07:00
Nicolas Pitre
03170c040c string.c: make it 64-bit compatible
Casting a pointer to an int produces warnings with 64-bit targets.
Furthermore, an int is not always the optimal memory element that
can be copied in that case.

Let's use uintptr_t to cast pointers to integers for alignment
determination purposes, and mem_word_t to denote the optimal memory
"word" that can be copied on the platform.

The mem_word_t definition is equivalent to uintptr_t by default.
However, some 32-bit targets such as ARM platforms with the LDRD/STRD
instructions could benefit from word_t being an uint64_t.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-07 13:19:51 -07:00
Nicolas Pitre
eeb2e67f2b time_t: define using a fixed-width type
Make sure type_t and suseconds_t keep the same size on 32-bit and
64-bit targets.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-06 14:22:09 -07:00
Anas Nashif
4c32258606 style: add braces around if/while statements
Per guidelines, all statements should have braces around them. We do not
have a CI check for this, so a few went in unnoticed.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-06 15:20:21 +02:00
Nicolas Pitre
4323d381e7 json: make it 64-bit compatible
The struct json_obj_descr definition allocates only 2 bits for type
alignment. Instead of using them literally minus 1 to encode 1, 2, or 4,
let's store the alignment's shift value instead so that 1, 2, 4 or 8 can
be encoded with the same 2 bits to accommodate 64-bit builds.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-05 07:47:41 -04:00
Christian Tavares
543de09357 lib: updatehub: add support ipv6
This extends the UpdateHub library code to allow the
use of IPV6 for communication.

Signed-off-by: Christian Tavares <christian.tavares@ossystems.com.br>
2019-06-05 00:20:37 +02:00
Christian Tavares
c5d74eccda lib: updatehub: add suport a CoAPS/DTLS
This extends the UpdateHub library code to allow the
use of CoAPS/DTLS for communication.

Refs: #13039.

Signed-off-by: Christian Tavares <christian.tavares@ossystems.com.br>
2019-06-05 00:20:37 +02:00
Christian Tavares
297ac3765f lib: updatehub: Add UpdateHub.io support
UpdateHub is an enterprise-grade solution which makes simple to
remotely update all your embedded devices in the field. It
handles all aspects related to sending Firmware Over-the-Air(FOTA)
updates with maximum security and efficiency, while you focus in
adding value to your product.

Signed-off-by: Christian Tavares <christian.tavares@ossystems.com.br>
Signed-off-by: Otavio Salvador <otavio@ossystems.com.br>
2019-06-05 00:20:37 +02:00
Jan Van Winkel
539d16fca8 gui: Corrected RGB888 pointer in LVGL write function
Corrected buffer pointer in LVGL zephyr_vdb_write function for
converting RGBA8888 to RGB888 pixel format.

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-05-30 09:33:07 -04:00
Paul Sokolovsky
af529d1158 libc: minimal: Implement exit()/_exit() functions.
Behavior is similar to newlib version: print "exit" message and go
into infinite loop.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-05-23 09:27:59 -04:00
Ulf Magnusson
927012dd7f lvgl: kconfig: Remove menu and use a 'menuconfig' symbol
The 'Graphical user interface' menu currently contains just the
'LittlevGL Support' symbol and its indented children.

To remove one menu level, remove the 'Graphical user interface' menu,
rename the symbol to 'LittlevGL GUI library' (consistent with e.g.
'Logging' and 'Bluetooth'), and turn it into a 'menuconfig' symbol.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-05-21 14:19:20 -05:00
Alexander Mihajlovic
f19787bb84 posix: Fix calculation of clock base in clock_settime
Previous version calculated rt_clock_base incorrectly by subtracting
clock_gettime from the specified time. Effectively the following
formula was used.

    rt_clock_base := new_time - clock_gettime()

This is clearly incorrect when we consider what should happen if we
call clock_settime with the result of clock_gettime. It ought to be
approximately a no-op, but instead we end up zeroing the clock.

    rt_clock_base := clock_gettime() - clock_gettime() = 0

This patch fixes clock_settime by instead using k_uptime_get to
calculate rt_clock_base, like so:

    rt_clock_base := new_time - k_uptime_get()

Trying the earlier thought experiment we get:

    rt_clock_base := clock_gettime() - k_uptime_get()

Using the definition of clock_gettime this expands to:

    rt_clock_base := (rt_clock_base + k_uptime_get()) - k_uptime_get()

The two k_uptime_get() terms cancel out, leaving:

    rt_clock_base := rt_clock_base

I.e. the no-op that we expect when calling clock_settime with
the result of clock_gettime.

Note: The bug is only observable when rt_clock_base is non-zero.
So when clock_settime is called for the first time, it will appear
to work correctly since rt_clock_base is initialized to 0.

Signed-off-by: Alexander Mihajlovic <alexander.mihajlovic@endian.se>
2019-05-21 08:24:59 -04:00
Benoit Leforestier
472ea92e79 Build: Build with newlib-nano c library
Add an option for building with newlib-nano library.
The newlib-nano library for ARM embedded processors is a part of the
GNU Tools for ARM Embedded Processors.
Add mem_alloc tests with newlib nano.

Signed-off-by: Benoit Leforestier <benoit.leforestier@gmail.com>
2019-05-15 10:46:44 -05:00
Jakob Olesen
c8708d9bf3 misc: Replace uses of __builtin_*_overflow() with <misc/math_extras.h>.
Use the new math_extras functions instead of calling builtins directly.

Change a few local variables to size_t after checking that all uses of
the variable actually expects a size_t.

Signed-off-by: Jakob Olesen <jolesen@fb.com>
2019-05-14 19:53:30 -05:00
Wentong Wu
6922d93d8e lib/posix: correct the meaning of CONFIG_MAX_PTHREAD_COUNT
Current code implement CONFIG_MAX_PTHREAD_COUNT as the maximum number
of POSIX threads that can ever be created, rather than the maximum
number of active POSIX threads. Use pthread_state of struct posix_thread
to track the state of posix thread in posix_thread_pool so that we can
reuse the unused posix thread.

Fixes #15516.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-05-11 08:24:36 -04:00
Paul Sokolovsky
81fa697f32 posix: Move gettimeofday declaration to <sys/time.h>
According to POSIX, that's the header which defines this function.
Similarly, nothing in POSIX indicates that <time.h> should have
access to struct timeval, so it's removed (it's made accessible
to <sys/time.h> via <sys/_timeval.h> introduced earlier).

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-05-07 22:18:09 -04:00
Paul Sokolovsky
c896f87d5d libc: minimal: Introduce sys/_timeval.h
This is implementation-level header which defines struct timeval, and
intended to be included by headers which need this structure. This
implementation scheme is compatible with Newlib, and thus provides a
step to use minlibc vs Newlib interchangeably.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-05-07 22:18:09 -04:00
Paul Sokolovsky
d79d3eb725 libc: minimal: Define time_t and suseconds_t
According to POSIX, these types should be defined by sys/types.h.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-05-07 22:18:09 -04:00
Andrew Boie
7153a2eec5 lib: cmsis_v1: set stack size larger if coverage
Use some large value, coverage targets have lots of RAM.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-02 15:42:33 -04:00
Andrew Boie
8502a2ea73 lib: cmsis_v2: increase stack sizes if coverage
Set to 4096, coverage targets have lots of RAM.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-02 15:42:33 -04:00
Andrew Boie
16317c1a9f lib: cmsis_v2: set default dynamic stack size
Set to same default as regular stacks. This doesn't use
any extra memory until CMSIS_V2_THREAD_DYNAMIC_MAX_COUNT
is set. 0 is not a valid default if that is set.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-02 15:42:33 -04:00
Andrew Boie
b8c560a439 newlib: fix user mode calls to _sbrk
Depending on configuration, this value could end up as
a variable and not an array symbol, causing a crash if
newlib decides to call _sbrk on behalf of a user thread,
which needs to perform arithmetic on it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-02 07:25:19 -04:00
Balaji Kulkarni
a25dce964b libc: minimal: Add bsearch function
This function implements generic binary-search.

Fixes #15159

Signed-off-by: Balaji Kulkarni <balaji.kulkarni92@gmail.com>
2019-04-25 20:39:36 -07:00
Tomasz Gorochowik
1afa9d0e5d libc: minimal: fix realloc function
Excerpt from the manual:

  If ptr is NULL, then the call is equivalent to malloc(size) [...]

Without this commit, such calls end with a BUS FAULT.

Signed-off-by: Tomasz Gorochowik <tgorochowik@antmicro.com>
2019-04-19 16:17:14 -04:00
Anas Nashif
3ae52624ff license: cleanup: add SPDX Apache-2.0 license identifier
Update the files which contain no license information with the
'Apache-2.0' SPDX license identifier.  Many source files in the tree are
missing licensing information, which makes it harder for compliance
tools to determine the correct license.

By default all files without license information are under the default
license of Zephyr, which is Apache version 2.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-04-07 08:45:22 -04:00
Patrik Flykt
4aa48833d8 subsystems: Rename reserved function names
Rename reserved function names in the subsys/ subdirectory except
for static _mod_pub_set and _mod_unbind functions in bluetooth mesh
cfg_srv.c which clash with the similarly named global functions.

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-04-03 17:31:00 -04:00
Andrew Boie
c8aee7b413 sys_mem_pool: use sys_mutex
Permission management no longer necessary, the former
parameter for the mutex is now simply ignored.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-04-03 13:47:45 -04:00
Andrew Boie
f0835674a3 lib: os: add sys_mutex data type
For systems without userspace enabled, these work the same
as a k_mutex.

For systems with userspace, the sys_mutex may exist in user
memory. It is still tracked as a kernel object, but has an
underlying k_mutex that is looked up in the kernel object
table.

Future enhancements will optimize sys_mutex to not require
syscalls for uncontended sys_mutexes, using atomic ops
instead.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-04-03 13:47:45 -04:00
Pawel Dunaj
2189d9b56d lib: mempool: Alloc and break must happen atomically
This fixes a regression caused by 41e90630d.

Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
2019-04-03 12:36:36 -04:00
Patrik Flykt
21358baa72 all: Update unsigend 'U' suffix due to multiplication
As the multiplication rule is updated, new unsigned suffixes
are added in the code.

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-03-28 17:15:58 -05:00
Patrik Flykt
24d71431e9 all: Add 'U' suffix when using unsigned variables
Add a 'U' suffix to values when computing and comparing against
unsigned variables.

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-03-28 17:15:58 -05:00
Flavio Ceolin
c2b25151cb lib: printk: Make if/iterations evaluate boolean operands
MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 22:06:45 -04:00
Flavio Ceolin
44fc55e209 lib: crc16_sw: Add missing U to unsigned constants
Add U to unsigned integer constants to avoid implicit cast.

MISRA-C rule 10.1

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 22:06:45 -04:00
Flavio Ceolin
ce696e9aa2 lib: rb: Make operands have an appropriate essential type
MISRA-C 8.10.2 defines essential operand types and how to handle them
through rules 10.1 .. 10.5. This commit adds an U to unsigned constants
to avoid implicit casts and make if/while statements evaluate a boolean
to avoid other types being casted to boolean.

MISRA-C rules 10.1, 10.2 and 10.3

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 22:06:45 -04:00
Flavio Ceolin
9d5936c04f lib: posix: fs: Fix access invalid memory
fs_dirent.name is MAX_FILE_NAME + 1 bytes long, not PATH_MAX. Just
fixing it to avoid access invalid memory.

Coverity CID: 186037

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-23 09:52:51 -05:00
Vincent Wan
3609e261bb net: sockets: move fcntl back to socket_offload.c
We are reverting the changes in commit
55b3f05932 given build errors are seen
when fcntl.h is included, as it declares fcntl() as a non-static
function. The same function cannot be declared as both static and
non-static.

Instead, we avoid redefining fcntl() in lib/os/fdtable.c specifically
for case of the SimpleLink family, til we have support for the new
socket_op_vtable.

Signed-off-by: Vincent Wan <vincent.wan@linaro.org>
2019-03-20 11:36:18 -05:00
Pawel Dunaj
41e90630d7 lib: mempool: Synchronize level checks
Do not perform early level usage check. This can lead to situation
where block is seen as available on level when it was taken from
the other context.

Fixes: #14504

Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
2019-03-19 13:38:46 -05:00
Pawel Dunaj
2c7d68009a lib: mempool: Return error if no block found
Return -ENOMEM if no block is available on any level.

Fixes: #14504

Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
2019-03-19 13:38:46 -05:00
Krzysztof Chruscinski
9502b8b80b lib: os: ring_buffer: Fix not handled return value
Some function return values were not handled. Added assert in case
those functions return error. It is possible only if same ring buffer
instance is used without any protection from multiple contexts.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2019-03-14 08:40:18 +01:00
Ulf Magnusson
53376394b7 kconfig: Remove blank lines at the beginning/end of files
Maybe this is some "just in case" thing that got copied around. There's
no need to have a blank line at the beginning or end of Kconfig files.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-03-13 07:29:42 -05:00
Kumar Gala
7aa8e43add libc: newlib: Cleanup/fix setting of system include paths
When we build with newlib we don't set -nostdinc.  In that case make
sure that we leave it to the toolchain to set the system include paths.

The one exception to leaving to the toolchain to set the system include
paths is the path to the newlib headers.  Since we build
with -ffreestanding we need to make sure the newlib header path is the
before the toolchain headers. Otherwise the toolchain's 'freestanding'
headers get picked up and that causes issues (for example getting PRI*64
defined properly from inttypes.h due to __STDC_HOSTED__ being '0').

For newlib we accomplish this by having the only system header specified
by zephyr_system_include_directories() being just the newlib headers.

Note: for minlibc we leave things alone as things just happen to work as
the -I include of the libc headers takes precedence over -isystem so we
get the libc headers over the toolchain ones.  For the newlib case it
appears that setting both -I and -isystem for the same dir causes the
-I to be ignored.

Fixes #14310

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-03-13 06:50:23 -05:00
Maureen Helm
f8c4808d96 boards: mimxrt10{50,60}_evk: Set lvgl defaults in board defconfigs
Configure lvgl defaults for imx rt boards in their respective board
defconfigs rather than the lvgl sample application.

Signed-off-by: Maureen Helm <maureen.helm@nxp.com>
2019-03-13 06:02:42 -05:00
Kumar Gala
276f766317 libc: rename _zephyr_fputc to zephyr_fputc
For some reason we missed _zephyr_fputc in commit
4344e27c26.  Rename _zephyr_fputc to just
zephyr_fputc and fixup associated code to build.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-03-12 13:59:06 -05:00
Kumar Gala
c82f23cada libc: Fix fwrite function name
Commit 4344e27c26 changed the reserved
function names, but got the naming wrong for fwrite.  Just use the
name zephyr_fwrite everywhere.

Fixes #14275

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-03-12 13:59:06 -05:00
Patrik Flykt
4344e27c26 all: Update reserved function names
Update reserved function names starting with one underscore, replacing
them as follows:
   '_k_' with 'z_'
   '_K_' with 'Z_'
   '_handler_' with 'z_handl_'
   '_Cstart' with 'z_cstart'
   '_Swap' with 'z_swap'

This renaming is done on both global and those static function names
in kernel/include and include/. Other static function names in kernel/
are renamed by removing the leading underscore. Other function names
not starting with any prefix listed above are renamed starting with
a 'z_' or 'Z_' prefix.

Function names starting with two or three leading underscores are not
automatcally renamed since these names will collide with the variants
with two or three leading underscores.

Various generator scripts have also been updated as well as perf,
linker and usb files. These are
   drivers/serial/uart_handlers.c
   include/linker/kobject-text.ld
   kernel/include/syscall_handler.h
   scripts/gen_kobject_list.py
   scripts/gen_syscall_header.py

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-03-11 13:48:42 -04:00
Andrew Boie
7416457b87 lib: fdtable: safely bounds check file descriptors
Prevent speculative attacks with out-of-bounds fd
values.

Won't affect code generation for systems that don't
enable CONFIG_BOUNDS_CHECK_BYPASS_MITIGATION.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-11 09:54:04 -07:00
Dennis Wildmark
ce4b282717 lib: cmsis_rtos_v2: changed printformat that produced warnings
Changed the print format for unsigned 32-bit variables that produced
warnings when compiled with newlib instead of the standard C library.
Chose to replace %d with PRIu32 because the latter is more portable
and adapts to the types of the standard C libraries.
Tested with and without newlib, and with sanitycheck.

Signed-off-by: Dennis Wildmark <dennis.wildmark@assaabloy.com>
2019-03-11 11:02:20 -05:00
Ulf Magnusson
da704c453f kconfig: lvgl: Remove redundant LVGL dep.
Appears within an 'if LVGL'.

'if FOO' is just shorthand for adding 'depends on FOO' to each item
within the 'if'. Dependencies on menus work similarly. There are no
"conditional includes" in Kconfig, so 'if FOO' has no special meaning
around a source. Conditional includes wouldn't be possible, because an
if condition could include (directly or indirectly) forward references
to symbols not defined yet.

Tip: When adding a symbol, check its dependencies in the menuconfig
('ninja menuconfig', then / to jump to the symbol). The menuconfig also
shows how the file with the symbol got included, so if you see
duplicated dependencies, it's easy to hunt down where they come from.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-03-09 09:48:25 -05:00
Filip Brozovic
fb3d9744cc lvgl: lvgl_color_1: add support for horizontally tiled displays
Enable displays which do not have SCREEN_INFO_MONO_VTILED set to work
with LittlevGL

Signed-off-by: Filip Brozovic <fbrozovic@gmail.com>
2019-03-07 07:18:50 -05:00
Patrik Flykt
e8f6ea2c8c lib/os: Remove case ranges from printk
Remove case ranges from printk in order to clean up GNUisms
and make the code standards compliant.

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-03-06 17:44:04 -05:00
Anas Nashif
3caea8c81e libc: minimal: add prototype of rand()
Add prototype of rand() that can be defined in tests.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-03-04 17:32:08 -08:00
Andrew Boie
7707060959 userspace: get rid of app section placeholders
We used to leave byte-long placeholder symbols to ensure
that empty application memory sections did not cause
build errors that were very difficult to understand.

Now we use some relatively portable inline assembly to
generate a symbol, but don't take up any extra space.

The malloc and libc partitions are now only instantiated
if there is some data to put in them.

Fixes: #13923

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-04 08:05:16 -08:00
Tim Sørensen (TIMS)
630af8a65f misc: assert_post_action: Added __weak keyword.
Added __weak keyword to to support overriding assert_post_action().
This allows system designers to change/augment the assert behaviour,
i.e. add logging to persistant storage of program counter, line
number etc, and/or change reboot behaviour.

Signed-off-by: Tim Sørensen (TIMS) <tims@oticon.com>
2019-03-02 12:26:21 -05:00
Charles E. Youse
3522e05f76 posix/pthreads: fix pthread_barrier_wait() behavior to match Posix
Exactly one caller of pthread_barrier_wait() should receive a return
value of PTHREAD_BARRIER_SERIAL_WAIT; all others should receive zero
(or an error code). Added a test to match.

Fixes: #9953

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-03-02 03:40:06 +01:00
Flavio Ceolin
1556fce845 libc: ctype: Fix operations between signed and unsigned types
MISRA-C says that char type should not be used in arithmetically as the
data doesn't represent numbers.

MISRA-C rules 10.1 and 10.2

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-01 09:22:24 +01:00
Andy Ross
85d895c60e lib/os: Remove recursion from mempool and rbtree
MISRA rules (see #11425) forbid recursive algorithms.  In the case of
rb_walk(), it's not actually used anywhere but a test right now, so we
can simply disable the API when CONFIG_MISRA_SANE is defined.  Mempool
had a (IMHO, fairly clever) tail recursive loop in bfree_recombine()
which can be trivially transformed into an only slightly uglier
iterative version.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-28 10:06:35 -08:00
Andy Ross
fe04adf99b lib/os: Conditionally eliminate alloca/VLA usage
MISRA rules (see #9892) forbid alloca() and family, even though those
features can be valuable performance and memory size optimizations
useful to Zephyr.

Introduce a MISRA_SANE kconfig, which when true enables a gcc error
condition whenever a variable length array is used.

When enabled, the mempool code will use a theoretical-maximum array
size on the stack instead of one tailored to the current pool
configuration.

The rbtree code will do similarly, but because the theoretical maximum
is quite a bit larger (236 bytes on 32 bit platforms) the array is
placed into struct rbtree instead so it can live in static data (and
also so I don't have to go and retune all the test stack sizes!).
Current code only uses at most two of these (one in the scheduler when
SCHED_SCALABLE is selected, and one for dynamic kernel objects when
USERSPACE and DYNAMIC_OBJECTS are set).

This tunable is false by default, but is selected in a single test (a
subcase of tests/kernel/common) for coverage.  Note that the I2C and
SPI subsystems contain uncorrected VLAs, so a few platforms need to be
blacklisted with a filter.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-28 10:06:35 -08:00
Paul Sokolovsky
d01f75be7e lib: os: fdtable: Add underscore aliases for read/write/close/lseek
These get references by newlib builds in other toolchains, e.g.
gnuarmemb, and lack of them breaks linking. Tested that
tests/posix/fs and tests/posix/common actually work with these
changes.

Fixes: #13906

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-02-28 08:45:13 -06:00
Ulf Magnusson
9aab5cef96 kconfig: Remove redundant 'default n' properties
Some more were added since the cleanup pass in June 2018. See e.g.
commit 2d50da70a1 ("drivers: ipm: Kconfig: Remove redundant 'default n'
properties") for a motivation. It also avoids people wondering whether
or not they need to put in 'default n'.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-02-27 09:25:22 +01:00
Rajavardhan Gundi
60186eba8c lib: cmsis_rtos_v2: kernel: Fix a coverity issue
Fixes an issue corresponding to CID: 190641

Fixes #12292.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2019-02-27 09:23:56 +01:00
Paul Sokolovsky
4bcd560985 lib: fdtable: Update for zephyr_write() rename
_impl__zephyr_write() was renamed to _impl__zephyr_write_stdout().
This wasn't caught by CI because we didn't have POSIX tests build
for newlib, but now we have.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-02-26 14:56:58 -06:00
Paul Sokolovsky
b5639c4ee2 libc: newlib: Rename adhoc read/write implementation for stdin/stdout
In case newlib is enabled, but POSIX subsys isn't, there're adhoc
implementations of read() and write() which work only with adhoc
stdin/stdout emulation layer. These are backed by system calls named
like "read" and "write". Rename all these functions and syscalls to
explicitly mention stdin/stdout in the names, to free namespace
for the implementation of generic read/write syscalls which will
integrate with POSIX fdtable.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2019-02-26 11:36:33 -06:00
Andrew Boie
feab37096b libc: fix CONFIG_STDOUT_CONSOLE semantics
The intent of this Kconfig is to allow libc stdout
functions like printf() to send their output to the
active console driver instead of discarding it.

This somehow evolved into preferring to use
printf() instead of printk() for all test case output
if enabled. Libc printf() implementation for both
minimal libc and newlib use considerably more stack
space than printk(), with nothing gained by using
them.

Remove all instances where we are conditionally
sending test case output based on this config, enable
it by default, and adjust a few tests that disabled
this because they were blowing stack.

printk() and vprintk() now work as expected for
unit_testing targets, they are just wrappers for
host printf().

Fixes: #13701

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-26 08:00:33 -06:00
Anas Nashif
59841c9c67 libc: do not enable newlib on x86_64
Also, for now x86_64 does not support newlib, so do not enable newlib
for this arch until we have a solution.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-02-24 17:48:10 -05:00
Kumar Gala
6cc5722a61 lib: posix: Fix compile error with mqueue.h
With newer newlib we get a build error with mqueue.h realted to mode_t.
Let's just let newlib define mode_t and have minimal libc also define
it in sys/types.h.  So we remove the duplicated definition in
posix/unistd.h.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-02-23 11:42:31 -06:00
Andrew Boie
4ce652e4b2 userspace: remove APP_SHARED_MEM Kconfig
This is an integral part of userspace and cannot be used
on its own. Fold into the main userspace configuration.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-23 07:43:55 -05:00
Andrew Boie
17ce822ed9 app_shmem: create generic libc partition
We need a generic name for the partition containing
essential C library globals. We're going to need to
add the stack canary guard to this area so user mode
can read it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-22 18:50:43 -05:00
Kumar Gala
e96d02984c lib: posix: Fix compile issue with newer newlib
Both SDK 0.10.0-beta2 and the ARM gcc 2018q2 run into a build issue with
newlib and conflict definitions of mode_t type.

First we need to add some ifdef protection if mode_t is already defined
and set _MODE_T_DECLARED if we are the first to define it.

Secondarily, we rename include/posix/sys/types.h to
include/posix/posix_types.h so that we aren't getting a name collusion
with the system sys/types.h and that we can easily and clearily include
it (which we need to do to pull in the info from newlib).

Fixes: #12224

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-02-22 11:55:01 -06:00
Kumar Gala
b730fa4ccb posix_lib: Disable support on native posix arch
For now we are disabling support for POSIX lib on native posix arch.  We
need to cleanup and support POSIX lib cleanly for hardware targets.
Once that is working properly we can look to support the feature on
native posix arch.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-02-22 11:55:01 -06:00
Anas Nashif
04743c9a79 posix: rename priority in sched_param struct
Priority member in the sched_param struct should be named
sched_priority.

Fixes #13470

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-02-19 11:24:45 -05:00
Carlos Stuart
75f77db432 include: misc: util.h: Rename min/max to MIN/MAX
There are issues using lowercase min and max macros when compiling a C++
application with a third-party toolchain such as GNU ARM Embedded when
using some STL headers i.e. <chrono>.

This is because there are actual C++ functions called min and max
defined in some of the STL headers and these macros interfere with them.
By changing the macros to UPPERCASE, which is consistent with almost all
other pre-processor macros this naming conflict is avoided.

All files that use these macros have been updated.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-14 22:16:03 -05:00
Andy Ross
ec554f44d9 kernel: Split reschdule & pend into irq/spin lock versions
Just like with _Swap(), we need two variants of these utilities which
can atomically release a lock and context switch.  The naming shifts
(for byte count reasons) to _reschedule/_pend_curr, and both have an
_irqlock variant which takes the traditional locking.

Just refactoring.  No logic changes.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Carlos Stuart
f5f450eeee lib: cmsis_rtos_v2: Join and detach support
Implements osThreadJoin and osThreadDetach.

This implementation uses a semaphore to signal when a thread is
exiting so any join operations are signalled to continue. It supports
multiple join operations on a single thread, and ensures joins are
aborted if a thread is detached.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-08 11:59:38 -05:00
Jan Van Winkel
d5b71ca756 gui: Corrected typo in object realign Kconfig option
Corrected typo in lv_conf.h for object realign Kconfig option.

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-02-08 09:35:18 -06:00
Andrew Boie
41f6011c36 userspace: remove APPLICATION_MEMORY feature
This was never a long-term solution, more of a gross hack
to get test cases working until we could figure out a good
end-to-end solution for memory domains that generated
appropriate linker sections. Now that we have this with
the app shared memory feature, and have converted all tests
to remove it, delete this feature.

To date all userspace APIs have been tagged as 'experimental'
which sidesteps deprecation policies.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-08 07:04:30 -05:00
Andrew Boie
4b4f773484 libc: set up memory partitions
* Newlib now defines a special z_newlib_partition containing
  all globals relevant to newlib. Most of these are in libc.a
  with a heap tracking variable in newlib's hooks.

* Both C libraries now expose a k_mem_partition containing the
  bounds of the malloc heap arena. Threads that want to use
  libc malloc() will need to add this to their memory domain.

* z_newlib_get_heap_bounds has been removed, in favor of the
  memory partition for the heap arena

* ztest now includes the C library partitions in its memory
  domain.

* The mem_alloc test now runs in user mode to prove that this
  all works for both C libraries.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-08 07:04:30 -05:00
Carlos Stuart
655d3cc2b0 lib: cmsis_rtos_v2: Default thread prioity
If an unitialized/zeroed optional attribute was passed to osThreadNew
the priority would be osThreadNone i.e. uninitialized. This causes an
ASSERT to be hit as the priority isn't valid (it is not between
osPriorityIdle and osPriorityISR).

The fix checks the passed in priority is not osPriorityNone and assigns
osPriorityNormal. This is the correct CMSIS behaviour.

The ASSERT will still be hit if the priority is invalid (<0).

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Carlos Stuart
d47178bc95 lib: cmsis_rtos_v2: Default name if name is NULL
Fixed an issue whereby if an attribute structure was passed into a CMSIS
RTOS v2 'new' function with an invalid address i.e. NULL assigned to the
name (char*) member the memcpy at the end of each new function
would cause a segmentation fault i.e. read from an invalid
address.

This has been fixed by checking if the name is NULL and using the
default name from the init struct if it is. This is the same name
that would be used if not passing in the optional attr function
argument.

Changed the memcpy to strncpy to ensure that the copy does not read
beyond the end of the source string and changed the length from 16 to 15
(by means of a `sizeof(...)-1`) of the destination buffer to ensure that
it will always be nul-terminated.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Carlos Stuart
d4eb2c9014 lib: cmsis_rtos_v2: Dynamic thread stacks
Implemented dynamic thread stacks for CMSIS threads by declaring an
array of default sized thread stacks. Allocation cannot be done on the
heap as some architectures require strict alignment for stacks so the
macro must be used to define the stack to ensure most compatibility.

Added a Kconfig variable to limit the number of dynamic threads on the
system (they also count towards total CMSIS thread count). This is so a
developer can have fine grained control over how many dynamic threads
can be allocated because all their stacks must be allocated up front so
could use a lot of memory needlessly if oversubscribed. The default
value is 0 which effectively disabled dynamic threads but also reduces
the memory impact to almost none.

Fixed an assert bug where thread_num was being tested against the
maximum allowed CMSIS threads - it previous checked for less than or
equal which actually (due to when the increment happens) allowed there
to be one more thread. The check now correctly uses less than and only
allowed up to the defined maximum.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Carlos Stuart
48320433e9 lib: cmsis_rtos_v2: Dynamic memory pools
Implemented dynamic allocation of memory pools in a similar to manner to
what was already implemented for message queues. Added all the same
checks on size vs. maximum allowed and current heap.

Added an additional Kconfig variable to define the maximum size of a
dynamically allocated memory pool.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Carlos Stuart
17db516069 lib: cmsis_rtos_v2: Message queue checks
Added some additional checks when creating a message queue to ensure the
size of the queue does not exceed the size of the buffer passed in via
the optional attributes.

Added a new Kconfig option to limit the maximum size of a message queue
dynamically allocated on the heap.

Added a check to ensure the heap is at least large enough to hold a
maximum size dynamically allocated queue.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Carlos Stuart
07a1a60df2 lib: cmsis_rtos_v2: Additional Kconfig dependency
Added Kconfig dependency that NUM_PREEMPT_PRIORITIES must be at least
osPriorityISR (56). This was enforced by a build assert message but not
decribed in the Kconfig.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Carlos Stuart
ccf51e2f50 lib: cmsis_rtos_v2: Uncrustify source files
Ran uncrustify on all library source files to ensure a compliant base to
work from.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-06 10:20:17 -05:00
Jan Van Winkel
edfd41f6de gui: Upstep LittlevGL to version 5.3
Upstep LittlevGL to version 5.3

Signed-off-by: Jan Van Winkel <vanwinkeljan@gmail.com>
2019-02-04 15:32:29 -05:00
Alberto Escolar Piedras
c2699dd52d misc: assert_post_action: Treat POSIX arch like others
After #12732, 6904501173
asserts call k_panic.

Before this, the POSIX arch had its own hack in the
__ASSERT_POST implementation to terminate the process instead
of spining forever.

But the POSIX arch does implement k_panic properly, so there
is no need anymore for this hack.
=> Remove the special treatment for POSIX ARCH

Signed-off-by: Alberto Escolar Piedras <alpi@oticon.com>
2019-02-03 10:28:51 -08:00
Krzysztof Chruscinski
6904501173 misc: Add k_panic on assert
Replaced forever loop in assert with call to a function.
In post_assert_action() function, k_panic is called.

Forever loop was preventing logs to be printed and had behavior
ependent on the context (low prioriy thread - system continue to
ork, irq - system is blocked).

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2019-02-02 15:58:33 -08:00
Dominik Rekawek
499feaf50e lib: posix: fix build break due to size comparsion
In limits.h PATH_MAX is defined to same value as in nffs

Signed-off-by: Dominik Rekawek <dominik@itetech.pl>
2019-02-01 23:41:09 -05:00
Kumar Gala
f75ddb8dc7 gui: Fix typo in Kconfig option
CONFIG_ isn't used inside Kconfig files.  Remove use.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-02-01 19:01:16 -05:00
Anas Nashif
b832a1e264 printk: move into lib/os
Last file under misc/. Put it alongside other support functions in
lib/os.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-01-22 07:45:22 -05:00
Anas Nashif
db92e5c66e lib: flatten all loose components into one lib
lib/ was starting to get messy and inconsitent. Files being either
dumped in the root or in sub-directories without a clear plan.
Move all library components into one single folder and call it 'os'.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-01-22 07:45:22 -05:00
Niranjhana N
81ec05548d lib: posix: fix a wrong type in mqueue.c
mq_maxmsg and mq_msgsize are defined to be of
type long in POSIX standard. So use long for
variables that hold its value in mq_open().

Signed-off-by: Niranjhana N <niranjhana.n@intel.com>
2019-01-15 17:48:34 -05:00
Andy Ross
b69d0da82d arch/x86_64: New architecture added
This patch adds a x86_64 architecture and qemu_x86_64 board to Zephyr.
Only the basic architecture support needed to run 64 bit code is
added; no drivers are added, though a low-level console exists and is
wired to printk().

The support is built on top of a "X86 underkernel" layer, which can be
built in isolation as a unit test on a Linux host.

Limitations:

+ Right now the SDK lacks an x86_64 toolchain.  The build will fall
  back to a host toolchain if it finds no cross compiler defined,
  which is tested to work on gcc 8.2.1 right now.

+ No x87/SSE/AVX usage is allowed.  This is a stronger limitation than
  other architectures where the instructions work from one thread even
  if the context switch code doesn't support it.  We are passing
  -no-sse to prevent gcc from automatically generating SSE
  instructions for non-floating-point purposes, which has the side
  effect of changing the ABI.  Future work to handle the FPU registers
  will need to be combined with an "application" ABI distinct from the
  kernel one (or just to require USERSPACE).

+ Paging is enabled (it has to be in long mode), but is a 1:1 mapping
  of all memory.  No MMU/USERSPACE support yet.

+ We are building with -mno-red-zone for stack size reasons, but this
  is a valuable optimization.  Enabling it requires automatic stack
  switching, which requires a TSS, which means it has to happen after
  MMU support.

+ The OS runs in 64 bit mode, but for compatibility reasons is
  compiled to the 32 bit "X32" ABI.  So while the full 64 bit
  registers and instruction set are available, C pointers are 32 bits
  long and Zephyr is constrained to run in the bottom 4G of memory.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-11 15:18:52 -05:00
Jan Van Winkel
cbfcae7a1f gui: Added glue logic for LittlevGL GUI library
Added glue logic to interface Zephyr with LittlevGL GUI library

This includes:
 * KConfig options for all lvgl options
 * Kernel & user space memory management
 * Zephyr to lvgl FS call mapping
 * Color space conversion function

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-01-07 16:05:35 -05:00
Flavio Ceolin
0c4bb833de lib: posix: Make statements evaluate boolean expressions
MISRA-C requires that the if statement has essentially Boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-01-07 08:52:07 -05:00
Flavio Ceolin
76b3518ce6 kernel: Make statements evaluate boolean expressions
MISRA-C requires that the if statement has essentially Boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-01-07 08:52:07 -05:00
Alistair Francis
41dfc4d478 libc: riscv: Fix the RISC-V ifdef
Following the standard GCC RISC-V convetion use __riscv for the RISC-V
specific define:
41d6b10e96/gcc/config/riscv/riscv-c.c (L37)

Signed-off-by: Alistair Francis <alistair.francis@wdc.com>
2019-01-03 18:15:53 -05:00
Yannis Damigos
33f1951c9d crc: Move crc7 into CRC single header
Move crc7 into CRC single header

Signed-off-by: Yannis Damigos <giannis.damigos@gmail.com>
2018-12-30 16:24:10 -05:00
bbafc36b1c lib: add crc7.
Used as a checksum on command messages when talking with MMC cards.

Implemented using the unwound bytewise implementation from
https://en.wikipedia.org/wiki/Computation_of_cyclic_redundancy_checks
which is a good mix of size and speed.

The API and naming matches lib/crc7.c in Linux.

Signed-off-by: Michael Hope <mlhx@google.com>
2018-12-30 16:24:10 -05:00
Andy Ross
0d4954fafc lib/cmsis_rtos_v2: Fix overflow in osKernelGetInfo()
If any of the Zephyr version numbers went beyond 99, the "%2d" printf
specifiers would expand to fit and the string would run over the
memory on the stack used for os_str[].

Recent GCC versions (remember native_posix and x86_64 use the host
compiler) were actually detecting this and correctly issuing a warning
(but only if the 3-digit char value would overflow the actual array
size!), which was breaking sanitycheck for me on Fedora 28 and Ubuntu
18.04 build hosts.  Pretty impresive warning.

As it happens this was wasteful anyway; we were spending bytes on the
stack (and in rodata to store the constant which, and the cycles
needed to copy it into place on the stack where it would be
overwritten immediately) when we could just snprintf() directly into
the buffer the user gave us.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-12-26 09:41:41 -05:00
Rajavardhan Gundi
41aa164c85 lib/cmsis_rtos_v2: Implement support for Thread Flags APIs
Thread Flags are used to trigger execution states between threads.
These APIs provide functionalities like set, clear and wait.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
fa499b353d lib/cmsis_rtos_v2: Implement support for Event Flag APIs
Events are used to trigger execution states between threads.
These APIs provide functionalities like event set, clear and
wait.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
27f4cd2356 lib/cmsis_rtos_v2: Implement support for Message Queue APIs
These APIs provide message queue functionality like create,
put and get.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
e5c848878a lib/cmsis_rtos_v2: Implement support for mempool APIs
These APIs allow creating, allocating and freeing of mempools.

Note: "Mempool" in CMSIS actually means memslabs in Zephyr.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
b39f6268c1 lib/cmsis_rtos_v2: Implement support for semaphore APIs
These APIs allow creating, acquiring, releasing and deleting
of semaphores.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
19b57ce2e8 lib/cmsis_rtos_v2: Implement support for mutex APIs
These APIs allow creating, acquiring, releasing and deleting
the mutexes.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
0285c69a3a lib/cmsis_rtos_v2: Implement support for timer APIs
These APIs provide the support of virtual timers. All timers
can be started, restarted, or stopped. Timers can be configured
as one-shot or periodic.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
7d499e3471 lib/cmsis_rtos_v2: Implement support for generic wait APIs
APIs to introduce wait i.e osDelay and osDelayUntil are defined
here. They are analogous to k_sleep in the kernel.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00
Rajavardhan Gundi
e3fe0cafab lib/cmsis_rtos_v2: Implement support for Kernel APIs
Implement support for Kernel management APIs like
osKernelInitialize, osKernelGetTickCount, osKernelGetSysTimerCount
etc.

Signed-off-by: Rajavardhan Gundi <rajavardhan.gundi@intel.com>
2018-12-20 12:23:22 +01:00