Commit graph

468 commits

Author SHA1 Message Date
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
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
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
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
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
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
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
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
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
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 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
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
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 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
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
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
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
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
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
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
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
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 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
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
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
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
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
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
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
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
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
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
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
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 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 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
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
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
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
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
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 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 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
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
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
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
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 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
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
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
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 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
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 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 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 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 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 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
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
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 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
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
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