Commit graph

2956 commits

Author SHA1 Message Date
Anas Nashif 684b8fcdd0 syscall: Z_SYSCALL_VERIFY_MSG -> K_SYSCALL_VERIFY_MSG
Rename macros and do not use Z_ for internal APIs.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-11-03 11:46:52 +01:00
Anas Nashif 4e396174ce kernel: move syscall_handler.h to internal include directory
Move the syscall_handler.h header, used internally only to a dedicated
internal folder that should not be used outside of Zephyr.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-11-03 11:46:52 +01:00
Anas Nashif a6b490073e kernel: object: rename z_object -> k_object
Do not use z_ for internal structures and rename to k_object instead.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-11-03 11:46:52 +01:00
Anas Nashif c91cad735a kernel: object: rename z_object_init to k_object_init
Do not use z_ for internal API and rename to k_object_init.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-11-03 11:46:52 +01:00
Anas Nashif c54fb959e3 kernel: objects: rename z_dynamic_object_aligned_create
Do not use z_ for internal APIs and rename function.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-11-03 11:46:52 +01:00
Flavio Ceolin 6e02f02464 kernel: Fix k_thread_name_get signature
k_thread_name_get has inconsistent signature. In the function
declaration it uses k_tid_t but in the implementation it is using
struct k_thread *. Change the implementation to use k_tid_t.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-30 17:34:45 -04:00
Flavio Ceolin a36c016dff kernel: mmu: Fix possible null de-reference
virt_page_phys_get can be called with phy parameter NULL when
the intention is just checking if a virtual address is mapped.

This function is generally overwritten by a an arch API that checks if
phys is null before using it but this default implementation doesn't.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-30 09:23:23 -04:00
Jukka Rissanen 83c875adab hostap: Move the relevant config options away from hostap
Moving the Zephyr specific config options from
modules/hostap/Kconfig to corresponding Kconfig where the
option is specified.

Signed-off-by: Jukka Rissanen <jukka.rissanen@nordicsemi.no>
2023-10-26 09:48:47 +02:00
Daniel Leung 88b05b3b91 kernel: disable THREAD_USERSPACE_LOCAL_DATA if LIBC_ERRNO
Thread userspace local data is to be used with storing errno per
thread without thread local storage support. However, if the C
library has native errno support, there is no need to enable
thread userspace local data to store errno per thread. Therefore,
amend the default for CONFIG_THREAD_USERSPACE_LOCAL_DATA so that
it is not enabled if the C library has native errno support.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-10-24 20:23:11 -04:00
Pedro Sousa 4207f4add8 kernel: timer: Fix race condition in k_timer_start
The documentation suggests that k_timer_start can be invoked from ISR
and preemptive contexts, however, an assertion failure occurs if one
k_timer_start call preempts another for the same timer instance. This
commit mitigates the issue by implementing a spinlock throughout the
k_timer_start function, ensuring thread-safety.

Fixes: #62908

Signed-off-by: Pedro Sousa <sousapedro596@gmail.com>
2023-10-23 12:10:06 +02:00
Daniel Leung 943e434559 mm: introduce CONFIG_KERNEL_VM_USE_CUSTOM_MEM_RANGE_CHECK
Sometimes the generic address range checker is not adequate
(think Xtensa cached/uncached pointers). This provides a way
to implement custom memory range checkers for those
situations. When enabled, sys_mm_is_phys_addr_in_range()
and sys_mm_is_virt_addr_in_range() must be implemented.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-10-20 15:08:34 +02:00
Flavio Ceolin 991ff6f48b kernel: init: Build constant in early random generator
Use a Kconfig symbol for initial state in the early
random number generator.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-13 10:03:53 +03:00
Flavio Ceolin 6c0fad2888 kernel: Fixes for z_early_rand_get
The early random get function was making many wrong assumptions
about random subsys and entropy drivers. First, it was assuming
that entropy_get_entropy() would be ISR safe, that is not right,
the driver has an ISR safe callback and if it is not implemented
or not working it is not ok using the other callback.
Second, the fallback to the random subsys is even more problematic
since they can use kernel services to protect internal states and be
thread-safe.

Another incorrect thing in this function was the guard around it.
It was needed by features like stack randomization and stack canaries,
and not when those conditions were match. Just remove it and in case
it is not needed the linker will take care of it.

The drawback of this change is that in the absence of an entropy
generator with support to be called from ISR the randomness is very
weak.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-13 10:03:53 +03:00
Flavio Ceolin 974e336140 kernel: random: Make z_early_rand_get a weak symbol
Allow targets come up with their own early random generator
since the default can be NOT so random due constraints.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-13 10:03:53 +03:00
Flavio Ceolin f9c7a5e6fb kernel: random: Rename early random get function
Rename z_early_boot_rand_get with z_early_rand_get to get consistent
with other early functions.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-13 10:03:53 +03:00
Peter Mitsis e9987aabbc kernel: Remove legacy mem block from mailbox
Memory blocks are a legacy feature and are to be removed from
mailboxes.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-10-13 09:56:02 +03:00
Keith Packard 362d8906a6 kernel: Support platforms with runtime timer freq for thread init_delay
Platforms that determine their basic timer frequency at runtime instead of
build time cannot compute thread initialization timeouts during
compilation.

Switch back to storing the init_delay value in milliseconds and perform the
conversion to a k_timeout_t at runtime.

Signed-off-by: Keith Packard <keithp@keithp.com>
2023-10-12 20:39:20 +03:00
Keith Packard eb024b655f libc: Control Z_LIBC_PARTITION_EXISTS from Kconfig
Instead of adding every possible subsystem which places variables in the C
library memory partition in libc-hooks.h, place those conditions in the
related Kconfig files and simplify the libc-hooks.h to just looking at
CONFIG_NEED_LIBC_MEM_PARTITION.

Signed-off-by: Keith Packard <keithp@keithp.com>
2023-10-10 23:39:40 +03:00
Flavio Ceolin e7bd10ae71 random: Rename random header
rand32.h does not make much sense, since the random subsystem
provides more APIs than just getting a random 32 bits value.

Rename it to random.h and get consistently with other
subsystems.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-10 14:23:50 +03:00
Daniel Leung 2c2d53c7e5 kernel: remove deprecate wording on arch_kernel_init()
The wording on deprecating arch_kernel_init() in favor of prep_c()
has never been materialized. Various architectures are using it to
perform initialization. So remove the wording.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-10-09 10:15:49 +02:00
Daniel Leung dd6a7eb77d kernel: demand_paging: add doc to enum arch_page_location
This adds doc to enum arch_page_location.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-10-09 10:15:49 +02:00
Daniel Leung 77dc74136c kernel: tls: fix doc on arch_tls_stack_setup()
There was a typo there so fix it.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-10-09 10:15:49 +02:00
Yong Cong Sin 0cd135920a kernel: work: check handler when submit to queue
Assert that the handler of a work is not NULL when submitting
it to the queue. This allows early detection of the
code that is submitting a non-NULL work with NULL handler to
the work queue (where it happens), rather than right before the
work item get executed in the queue (when it happens).

Signed-off-by: Yong Cong Sin <ycsin@meta.com>
2023-10-05 13:43:07 +01:00
Flavio Ceolin fee22dae40 kconfig: Deprecate CONFIG_MP_NUM_CPUS
Mark CONFIG_MP_NUM_CPUS deprecated and point to
CONFIG_MP_MAX_NUM_CPUS.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-03 17:45:53 +01:00
Flavio Ceolin 15aa3acaf6 kconfig: Remove MP_NUM_CPUS usage
Zephyr's code base uses MP_MAX_NUM_CPUS to
know how many cores exists in the target. It is
also expected that both symbols MP_MAX_NUM_CPUS
and MP_NUM_CPUS have the same value, so lets
just use MP_MAX_NUM_CPUS and simplify it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-10-03 17:45:53 +01:00
Anas Nashif a1c7bfbc63 kernel: remove unused z_init_thread_base from kernel.h
This API is internal and not used in any way in kernel.h, so move it
back to where it is needed.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-30 18:43:28 +02:00
Anas Nashif e19f21cb27 kernel: move z_is_thread_essential out of public kernel header
This is a private API to the kernel, so move out of kernel.h

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-30 18:43:28 +02:00
Anas Nashif f0c7fbf0f1 kernel: move sched_priq.h to internal/ folder
This header is internal to the kernel and shall not be included directly.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-30 18:43:28 +02:00
Peter Mitsis e6f1090553 kernel: Integrate object core statistics
Integrates object core statistics framework into the following
kernel objects:
  sys_mem_blocks, k_mem_slab
  threads, _cpu, z_kernel

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-30 08:04:14 +03:00
Peter Mitsis 1d5d674e0d kernel: Add initial k_obj_core_stats infrastructure
Adds the infrastructure to integrate statistics into
the object core.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-30 08:04:14 +03:00
Peter Mitsis 6df8efe354 kernel: Integrate object cores into kernel
Integrates object cores into the following kernel structures
   sys_mem_blocks, k_mem_slab
   _cpu, z_kernel
   k_thread, k_timer
   k_condvar, k_event, k_mutex, k_sem
   k_mbox, k_msgq, k_pipe, k_fifo, k_lifo, k_stack

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-30 08:04:14 +03:00
Peter Mitsis 55db86e512 kernel: Add initial obj_core infrastructure
Adds the initial object core infrastructure.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-30 08:04:14 +03:00
Peter Mitsis 9bedfd82a2 kernel: Refactor CPU usage
Refactors CPU usage (thread runtime stats) to make it easier to
integrate with the object core statistics framework.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-30 08:04:14 +03:00
Peter Mitsis 2f003e59e4 kernel: Re-factor k_mem_slab definition
Rearranges the k_mem_slab fields so that information that describes
how much of the memory slab is used is co-located. This will allow
easier of its statistics into the object core statistics reporting
framework.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-30 08:04:14 +03:00
Flavio Ceolin 121d051c9a kernel: fatal: Remove redundant function
We don't need re-implement a function to get the current cpu.
Simply use _current_cpu that even contains additional sanity checks.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-09-29 13:05:13 +02:00
Flavio Ceolin 711c17182f kernel: s/k_current_get/_current
Running inside kernel we can use _current instead of
k_current_get that can lead to additional function call
checks.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-09-29 13:05:13 +02:00
Daniel Leung d47b1c05f3 kernel: userspace: add k_object_is_valid()
This adds a function k_object_is_valid() to check if a kernel
object exists, of certain type, and has been initialized.
This replaces the same (or very similar) code that has been
copied from kernel into the network subsystem.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-09-28 17:28:43 -04:00
Daniel Leung 0a50ff366e kernel: rename z_current_get() to k_sched_current_thread_query()
The original idea of z_current_get() was to be the counterpart
of k_current_get() when thread local variable for current has
not been initialized if TLS is enabled, otherwise they are
the same function. Now since z_current_get() is being used
outside of core kernel, rename it under kernel namespace so
other subsystem can conceptually use them too.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-09-28 16:15:46 +02:00
Keith Packard 41e8b44619 kernel: Make thread 'init_delay' k_timeout_t rather than int msecs
Storing this value in milliseconds rather than using k_timeout_t requires
the system to perform division at runtime to convert types. This pulls in
the 64-bit soft division code on platforms without hardware for this.

Perform the conversion at build time instead by using the runtime time
directly.

The init_delay field was moved within the _static_thread_data structure to
avoid introducing a hole for alignment on 32-bit systems when using 64-bit
timeouts.

Use SYS_TIMEOUT_MS instead of K_MSEC so that the initial delay can be set
to forever.

Signed-off-by: Keith Packard <keithp@keithp.com>
2023-09-28 16:15:27 +02:00
Benjamin Cabé a46f1b9c33 kernel: Fix unused-parameter warnings
Add missing ARG_UNUSED where needed.

Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
2023-09-28 16:14:39 +02:00
Evgeniy Paltsev 54e0731666 kernel: SMP: allow more than 5 CPU cores
Previously we limit maximum number of CPU cores to 5, now be
bumping this restriction so we can use 12 cores.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2023-09-25 09:49:50 +02:00
Nikolay Agishev baeda6ada0 ARC: fix dynamic thread stack allocation
ACR use the same logic for dynamic thread stacks allocation as ARM.
This fixup reuses ARM code.

Signed-off-by: Nikolay Agishev <agishev@synopsys.com>
2023-09-25 09:49:36 +02:00
Ambroise Vincent 995eeda266 kernel: poll: Lock all calls to signal_poll_event
The signal_poll_event function was previously called without the poll
lock held. This created a race condition between a thread calling k_poll
to wait for an event and another thread signalling for this same event.
This resulted in the waiting thread to stay pending and the handle to it
getting removed from the notifyq, meaning it couldn't get woken up
again.

Signed-off-by: Ambroise Vincent <ambroise.vincent@arm.com>
2023-09-18 15:41:23 -04:00
Anas Nashif 8dc2746c0e kernel: z_handle_obj_poll_events is internal not kernel.h material
This internal kernel API is misplaced in a public kernel header. Just
make it available to the code using it in the kernel.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-17 07:59:30 -04:00
Peter Mitsis c7255cf374 kernel: Remove references to _EXPIRED
The _EXPIRED macro is no longer necessary. It is a relic of an older
timeout processing algorithm from several years ago.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-09-15 19:16:20 -04:00
Anas Nashif fcf50ed6e7 kernel: move timeout_q.h to kernel/include
This is a private kernel header with private kernel APIs, it should not
be exposed in the public zephyr include directory.

Once sample remains to be fixed (metairq_dispatch), which currently uses
private APIs from that header, it should not be the case.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-12 12:55:36 -04:00
Anas Nashif 8634c3b444 kernel: move wait_q.h header to be internal
This header does not expose any public APIs, so move it under
kernel/include and change files including it.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2023-09-12 12:55:36 -04:00
Fabio Baltieri a477bddc59 kernel: dynamic: add missing assert argument
Add a missing assert argument, fixes:

zephyrproject/zephyr/kernel/dynamic.c: In function 'dyn_cb':
zephyrproject/zephyr/include/zephyr/sys/__assert.h:44:52: warning:
	format '%p' expects a matching 'void *' argument [-Wformat=]

That started to break the build since:

d7846de548 assert: check format arguments for correctness

Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
2023-09-06 18:34:58 +02:00
Carles Cufi 76e4cd9dc4 kernel: mem_slab: Add assert to k_mem_slab_free()
Add an assert to ensure the pointer provided by the user points to one
of the available blocks in the slab.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2023-09-03 18:20:59 -04:00
Carles Cufi 8c748fd005 kernel: Modify the signature of k_mem_slab_free()
Modify the signature of the k_mem_slab_free() function with a new one,
replacing the old void **mem with void *mem as a parameter.

The following function:
void k_mem_slab_free(struct k_mem_slab *slab, void **mem);

has the wrong signature. mem is only used as a regular pointer, so there
is no need to use a double-pointer. The correct signature should be:
void k_mem_slab_free(struct k_mem_slab *slab, void *mem);

The issue with the current signature, although functional, is that it is
extremely confusing. I myself, a veteran Zephyr developer, was confused
by this parameter when looking at it recently.

All in-tree uses of the function have been adapted.

Fixes #61888.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2023-09-03 18:20:59 -04:00
Florian Grandel cc4d1bd374 kernel: sched: optimize for Meta IRQs == coop prios
Combining Meta IRQs with cooperative threads requires extra care to
return to pre-empted cooperative threads when returning from a Meta IRQ.
This is only needed when there are cooperative threads that are not also
Meta IRQs. This PR saves some space & time when the number of Meta IRQs
is equal to the number of available cooperative threads.

Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
2023-08-28 20:15:44 +02:00
Alberto Escolar Piedras 9eeb78d86d COVERAGE: Fix COVERAGE_GCOV dependencies
CONFIG_COVERAGE has been incorrectly used to
change other kconfig options (stack sizes, etc)
code defaults, as well as some samples behaviour,
which should not have dependend on it.

Instead those should have depended on COVERAGE_GCOV,
which, being the one which adds special code and
temporary RAM storage for embedded targets,
require changes to many features.

When building for the native targets, all this was
unnecessary.

=> Fix the dependency.

Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
2023-08-24 15:36:31 +02:00
Andrei Emeltchenko 9551f2708b kernel: timeout: Remove unneeded assignment
Fix warnings with value stored never read.

Signed-off-by: Andrei Emeltchenko <andrei.emeltchenko@intel.com>
2023-08-22 10:46:41 +01:00
Daniel Leung e38fc6de8a cmake: enable -Wshadow partially for in-tree code
This enables -Wshadow to warn about shadow variables on
in tree code under arch/, boards/, drivers/, kernel/,
lib/, soc/, and subsys/.

Note that this does not enable it globally because
out-of-tree modules will probably take some time to fix
(or not at all depending on the project), and it would be
great to avoid introduction of any new shadow variables
in the meantime.

Also note that this tries to be done in a minimally
invasive way so it is easy to revert when we enable
-Wshadow globally. Source files under modules/, samples/
and tests/ are currently excluded because there does not
seem to be a trivial way to add -Wshadow there without
going through all CMakeLists.txt to add the option
(as there are 1000+ files to change).

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-08-22 11:39:58 +02:00
Jamie McCrae 77a00f1352 kernel: banner: Allow for customising version
This allows for further (out of tree) customisation of the boot
banner version string when devices boot.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
2023-08-21 10:09:46 +02:00
Grant Ramsay 45701e696a kernel: sched: Disable FPU context when thread ends
When `CONFIG_FPU_SHARING` is enabled each `k_thread` struct has a saved
floating point context (`saved_fp_context`). During a context switch, the
current FPU owner's (`_current_cpu->arch.fpu_owner`) registers are saved
to its `saved_fp_context`, and the destination threads FPU registers are
loaded from its `saved_fp_context`.

When a thread ends, it does not release ownership of the FPU
(`_current_cpu->arch.fpu_owner`). This is problematic if the `k_thread`
struct was allocated on the stack. The next context switch will save the
FPU registers into `k_thread -> saved_fp_context` which may now be out of
scope. This will likely (but not always) result in a crash.

Adding `arch_float_disable(thread);` when a thread ends disables
preservation of floating point context information, fixing this issue

Signed-off-by: Grant Ramsay <gramsay@enphaseenergy.com>
2023-08-16 17:05:25 +02:00
Daniel Leung b8e0de2ad0 kernel: mmu: fix bitmap set and clear under direct map
When CONFIG_KERNEL_DIRECT_MAP enabled, the region to be mapped
or unmapped can be outside of the virtual memory space, wholly
within it, or overlap partially. Additional processing is
needed to make sure we only manipulate the bits within
the bitmap, in other words, only the pages represented by
the bitmap.

Fixes #59549

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-08-15 16:30:55 -04:00
Daniel Leung 9c0ff33e04 kernel: rename shadow variables
Renames	shadow variables found by -Wshadow.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-08-10 08:14:12 +00:00
Flavio Ceolin d16c5b9048 kernel: canaries: Allow using TLS to store it
Add new option to use thread local storage for stack
canaries. This makes harder to find the canaries location
and value. This is made optional because there is
a performance and size penalty when using it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-08-08 19:08:04 -04:00
Chaitanya Tata 5c7c099891 kernel: Add support to override banner
This is useful for Zephyr customers to put their custom banners.

Signed-off-by: Chaitanya Tata <Chaitanya.Tata@nordicsemi.no>
2023-08-03 18:05:00 -04:00
Vadim Shakirov 73944c6157 kernel/sched: fix thread selection when ABORTING + PENDING
In commit d537267f, the check on thread abortion was moved from next_up
to z_get_next_switch_handle. However, next_up is also called from
z_swap_next_thread, so the check on thread abortion is now missing there.
This sometimes caused the thread to be stuck in ABORTING + PENDING state
during the test_smp_switch_torture in test/kernel/smp

To avoid such cases in the future, it is worth leaving the check in next_up

Signed-off-by: Vadim Shakirov <vadim.shakirov@syntacore.com>
2023-08-01 11:59:42 +02:00
Peter Mitsis bd5839ec9e kernel: Fix wrap-around check in kernel/mmu.h
Fixes the buffer wrap-around check so that it will not be ignored
by the GNU C compiler.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-08-01 09:51:33 +02:00
Nicolas Pitre 77b7eb1199 kernel/kheap: move to timepoint API
Remove sys_clock_timeout_end_calc() usage.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-07-25 09:12:26 +02:00
Nicolas Pitre 52e2f83185 kernel/timeout: introduce the timepoint API
This is meant as a substitute for sys_clock_timeout_end_calc()

Current sys_clock_timeout_end_calc() usage opens up many bug
possibilities due to the actual timeout evaluation's open-coded nature.

Issue ##50611 is one example.

- Some users store the returned value in a signed variable, others in
  an unsigned one, making the comparison with UINT64_MAX (corresponding
  to K_FOREVER) wrong in the signed case.

- Some users compute the difference and store that in a signed variable
  to compare against 0 which still doesn't work with K_FOREVER. And when
  this difference is used as a timeout argument then the K_FOREVER
  nature of the timeout is lost.

- Some users complexify their code by special-casing K_NO_WAIT and
  K_FOREVER inline which is bad for both code readability and binary
  size.

Let's introduce a better abstraction to deal with absolute timepoints
with an opaque type to be used with a well-defined API.
The word "timeout" was avoided in the naming on purpose as the timeout
namespace is quite crowded already and it is preferable to make a
distinction between relative time periods (timeouts) and absolute time
values (timepoints).

A few stacks are also adjusted as they were too tight on X86.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-07-25 09:12:26 +02:00
Christopher Friedt d7119b889f kernel: dynamic: declare dynamic stubs when disabled
With some of the recent work to disable unnecessary system
calls, there is a scenario where `z_impl_k_thread_stack_free()`
is not defined and an undefined symbol error occurs.

Safety was very concerned that dynamic thread stack code might
touch other code that does not malloc, so add a separate file
for the stack alloc and free stubs.

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-07-24 12:59:43 -04:00
Christopher Friedt dcdebb616a kernel: dynamic: remove unnecessary size assignment
Previously, the kernel stack size was adjusted for no apparent
reason.

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-07-24 12:59:43 -04:00
Flavio Ceolin ed8355ad3f kernel: userspace: Fix memory leak
Fix memory leak on dynamic object allocation.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-20 16:10:32 +00:00
Flavio Ceolin cbbe6d2ab7 kernel: userspace: Simplify dinamyc objects
There is not need to have two types to represent dynamic objects.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-20 16:10:32 +00:00
Nicolas Pitre 13a6c45452 kernel: crude k_busy_wait() implementation
This allows for builds with CONFIG_SYS_CLOCK_EXISTS=n in which case
busy waits are achieved with a crude CPU loop. If ever accuracy is
needed even with such a configuration then implementing arch_busy_wait()
should be considered.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-07-19 21:42:41 -04:00
Nicolas Pitre b157031468 kernel: split k_busy_wait() out of timeout.c
This will allow for builds with CONFIG_SYS_CLOCK_EXISTS=n. For now this
is only the code move.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-07-19 21:42:41 -04:00
Flavio Ceolin 2b1106a407 kernel: userspace: Use only list for dynamic objs
Since the rbtree is using as list because we no longer
can assume that the object pointer is the address of the
data field in the dynamic object struct, lets just use
the already existent dlist for tracking dynamic kernel
objects.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-17 16:56:01 -04:00
Flavio Ceolin 4feb182f12 kernel: dynamic: Fix stack allocation logic
Fix the preference allocation logic. If pool is preferred but POOL_SIZE
is 0 or pool allocation fails, it fallbacks to heap allocation if it
is enabled.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-17 16:56:01 -04:00
Flavio Ceolin 3b7e0b672e kernel: userspace: Dynamic thread stack object
Add support for dynamic thread stack objects. A new container
for this kernel object was added to avoid its alignment constraint
to all dynamic objects.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-17 16:56:01 -04:00
Flavio Ceolin fc6d9eeb3e kernel: dynamic: Support usermode thread stack
Allocate kernel object for userspace thread stack.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-17 16:56:01 -04:00
Flavio Ceolin 67e66e4807 kernel: userspace: Add k_object_alloc_size
Add a new API to dynamically allocate kernel objects that allow
passing an arbitrary size. This new API allows to allocate dynamic
thread stack.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-07-17 16:56:01 -04:00
Christopher Friedt 7b1b2576ac kernel: support dynamic thread stack allocation
Add support for dynamic thread stack allocation

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
2023-07-13 17:16:32 -04:00
Florian Grandel e256b7d244 kernel: spinlock: LOCKED -> K_SPINLOCK
Let the kernel use the new K_SPINLOCK macro and remove the alias.

Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
2023-07-10 09:27:21 +02:00
Florian Grandel 816d09c453 kernel: spinlock: expose LOCKED macro as public API
While the LOCKED pattern is universally useful it can be misused. This
change therefore exposes the LOCKED pattern with extensive usage
documentation to reduce the risk of abuse or unintended deadlock.

Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
2023-07-10 09:27:21 +02:00
Jordan Yates 4ce1f03aa9 kernel: event modification functions return previous value
Update the return value of functions that modify the internal event
state from `void` to `uint32_t`, so that calling code can determine
whether the event was already in a given state, or if the call modified
it.

This simplifies the usage of `struct k_event` as an alternative to
`atomic_t` that users can block on.

Implements #57216

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2023-07-07 09:24:25 +02:00
Florian Grandel 5fa5534afc doc: kernel: clocks: define "current time"
Scheduling relative timeouts from within timer callbacks (=sys clock ISR
context) differs from scheduling relative timeouts from an application
context.

This change documents and explains the rationale of this distinction.

Signed-off-by: Florian Grandel <fgrandel@code-for-humans.de>
2023-06-30 16:07:26 +02:00
Evgeniy Paltsev 16b8191be0 SMP: fix build failure if SMP=y and SYS_CLOCK_EXISTS=n
Fix build failure for the SMP configurations without sysclock.

Signed-off-by: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
Signed-off-by: Evgeniy Paltsev <PaltsevEvgeniy@gmail.com>
2023-06-22 06:17:27 -04:00
Gerard Marull-Paretas 48b201cc53 device: make device dependencies optional
Device dependencies are not always required, so make them optional via
CONFIG_DEVICE_DEPS. When enabled, the gen_device_deps script will run so
that dependencies are collected and part of the final image. Related
APIs will be also made available. Since device dependencies are used in
just a few places (power domains), disable the feature by default. When
not enabled, a second linking pass will not be required.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-06-21 09:32:05 +02:00
Gerard Marull-Paretas 1ebd76ed51 pm: add prompt to DEVICE_DEPS_DYNAMIC
The option can now be set by projects. This change will also allow to
make it dependent on a future CONFIG_DEVICE_DEPS option.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-06-21 09:32:05 +02:00
Gerard Marull-Paretas 319fbe57e1 device: s/HAS_DYNAMIC_DEVICE_HANDLES/DEVICE_DEPS_DYMAMIC
Rename the Kconfig option to be in line with recent renamings in device
handles/dependencies.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-06-21 09:32:05 +02:00
Gerard Marull-Paretas 5982d83e2a device: s/struct device.handles/struct device.deps
Rename struct device `handles` member to `deps`, in line with previous
renamings in the device API.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-06-21 09:32:05 +02:00
Daniel Leung b93ccd22c7 kernel: syscalls: use zephyr_syscall_header
This adds a few line use zephyr_syscall_header() to include
headers containing syscall function prototypes.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-06-17 07:57:45 -04:00
Flavio Ceolin 4f29930e4c pm: Fix cpus active count
Only set a cpu as active (on pm subsystem) when the cpu is effectively
initialized. We cannot assume on pm subsystem that all cpus were
initialized since when the option CONFIG_SMP_BOOT_DELAY is used cpus are
initialized on demand by the application.

Note that once cpus are properly initialized the subystem is able to track
their status.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-06-01 10:05:31 +02:00
Andy Ross a08e23f68e kernel/sched: Fix SMP must-wait-for-switch conditions in abort/join
As discovered by Carlo Caione, the k_thread_join code had a case where
it detected it had been called on a thread already marked _THREAD_DEAD
and exited early.  That's not sufficient.  The thread state is mutated
from the thread itself on its exit path.  It may still be running!

Just like the code in z_swap(), we need to spin waiting on the other
CPU to write the switch handle before knowing it's safe to return,
otherwise the calling context might (and did) do something like
immediately k_thread_create() a new thread in the "dead" thread's
struct while it was still running on the other core.

There was also a similar case in k_thread_abort() which had the same
issue: it needs to spin waiting on the other CPU to kill the thread
via the same mechanism.

Fixes #58116

Originally-by: Carlo Caione <ccaione@baylibre.com>
Signed-off-by: Andy Ross <andyross@google.com>
2023-05-26 17:09:35 -04:00
Andy Ross c3046f417a kernel/sched: Use new barrier and spin APIs
The switch_handle field in the thread struct is used as an atomic flag
between CPUs in SMP, and has been known for a long time to technically
require memory barriers for correct operation.  We have an API for
that now, so put them in:

* The code immediately before arch_switch() needs a write barrier to
  ensure that thread state written by the scheduler is seen to happen
  before the outgoing thread is flagged with a valid switch handle.

* The loop in z_sched_switch_spin() needs a read barrier at the end,
  to make sure the calling context doesn't load state from before the
  other CPU stored the switch handle.

Also, that same spot in switch_spin was spinning with interrupts held,
which means it needs a call to arch_spin_relax() to avoid a FPU state
deadlock on some architectures.

Signed-off-by: Andy Ross <andyross@google.com>
2023-05-26 17:09:35 -04:00
Andy Ross b89e427bd6 kernel/sched: Rename/redocument wait_for_switch() -> z_sched_switch_spin()
This trick turns out also to be needed by the abort/join code.
Promote it to a more formal-looking internal API and clean up the
documentation to (hopefully) clarify the exact behavior and better
explain the need.

This is one of the more... enchanted bits of the scheduler, and while
the trick is IMHO pretty clean, it remains a big SMP footgun.

Signed-off-by: Andy Ross <andyross@google.com>
2023-05-26 17:09:35 -04:00
Hou Zhiqiang 41520e8b5b kernel: mmu: add direct-map support in z_phys_map()
Many RTOS applications assume the virtual and physical address
is 1:1 mapping, so add the 1:1 mapping support in z_phys_map()
to easy adapt these applications.

Signed-off-by: Hou Zhiqiang <Zhiqiang.Hou@nxp.com>
2023-05-26 13:50:35 -04:00
Nicolas Pitre e2d0d1a801 kernel: allow for arch specific processing within busy loops
Give architectures that need it the ability to perform special checks
while e.g. waiting for a spinlock to become available.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-05-25 08:25:11 +00:00
Carlo Caione 74a942e673 barriers: Introduce barrier operations
Introduce a new API for barrier operations starting with a general
skeleton and the implementation for barrier_data_memory_fence_full().

Select a built-in or an arch-based implementation according to new
Kconfig symbols CONFIG_BARRIER_OPERATIONS_BUILTIN and
CONFIG_BARRIER_OPERATIONS_ARCH.

The built-in implementation falls back on the compiler built-in
function using __ATOMIC_SEQ_CST as it is done for the atomic APIs
already.

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2023-05-24 13:13:57 -04:00
Flavio Ceolin df4be07b26 kernel: mmu: Fix Xtensa memory alignment issue
z_page_frame can't be packed on Xtensa due memory alignment
constraints. When this is struct is packed it is 5 bytes long it will
cause an memory alignment problem on Xtensa.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-05-23 08:54:29 +02:00
Nicolas Pitre c1afa5c85e kernel/atomic_c.c: prevent usage in SMP configs
The C version of atomic_cas() uses k_smp_lock() ... which uses
atomic_cas().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-05-23 08:53:39 +02:00
Gerard Marull-Paretas dacb3dbfeb iterable_sections: move to specific header
Until now iterable sections APIs have been part of the toolchain
(common) headers. They are not strictly related to a toolchain, they
just rely on linker providing support for sections. Most files relied on
indirect includes to access the API, now, it is included as needed.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-05-22 10:42:30 +02:00
Andy Ross d537267fc3 kernel/sched: Fix thread selection misordering with aborted threads
When a running thread gets aborted asynchronously (this only happens
in SMP contexts, obviously) it gets flagged "aborting", but the actual
abort needs to happen in the thread's own context.  For convenience,
this was done in the next_up() routine that selects the next thread to
run at interrupt exit time.

But this check was being done AFTER the next candidate thread was
selected from the run queue.  Thread abort can wake up threads blocked
in k_thread_join(), and therefore these weren't seen as runable
threads, even if they should have been.

Executive summary: if you killed a thread running on another CPU, and
there was another thread joined to the killed thread that should have
run on that CPU, it wouldn't (until it received an interrupt or
otherwise reached a schedule point).

Move the abort check above the run queue inspection and into the
end-of-interrupt processing in z_get_next_switch_handle() (so it's
actually a mild performance boost as it's no longer part of the
cooperative context switch path).  Simple fix, subtle bug.

Fixes #58040

Signed-off-by: Andy Ross <andyross@google.com>
2023-05-22 08:06:49 +00:00
Qipeng Zha fa973d1b7b kernel: pin _kernel variable in case of paging
Exception handler(arch/x86/core/ia32/excstub.S) may access
_kernel variable, it will lead to failure when enabled paging,
so make this critical variable pinned.

Signed-off-by: Qipeng Zha <qipeng.zha@intel.com>
2023-05-16 11:41:11 -04:00
Jaroslaw Stelter 9c0dd7e3be intel_adsp: ace20_lnl: Change LNL core count to 5
The ACE 2.0 LNL platform has 5 HIFI4 cores. Change number
of cores to enable 5th core on the platform.

Signed-off-by: Jaroslaw Stelter <Jaroslaw.Stelter@intel.com>
2023-05-15 08:00:11 -04:00
Armin Brauns 0bc342fbbd kernel: fix buffer overflow from incorrect K_MSGQ_DEFINE definition
Without these parentheses, specifying a q_max_msgs of e.g.
`MY_DEFAULT_QUEUESIZE+1` would result in a buffer of size
(1 element + MY_DEFAULT_QUEUESIZE bytes).

This would then lead to an unbounded buffer overflow because the queue
never reaches the exact (offset by MY_DEFAULT_QUEUESIZE bytes)
`buffer_end` and just keeps writing.

Additionally, add asserts to make sure this can't happen again.

Signed-off-by: Armin Brauns <armin.brauns@embedded-solutions.at>
2023-05-12 13:39:10 -04:00
Gerard Marull-Paretas d0e58ad0a6 device: use iterable sections
Use iterable sections to handle devices list. This simplifies devices
implementation by using standard APIs.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-05-12 12:01:10 +02:00
Kumar Gala 96a90550c4 kernel: idle: fix build error on arm-clang
When building sample.minimal.mt-no-preempt-no-timers.arm on arm-clang
we get a link error as z_pm_save_idle_exit expects sys_clock_idle_exit
to be defined.

However the sample sets CONFIG_SYS_CLOCK_EXISTS=n so
sys_clock_idle_exit() will not be defined by any driver.  So add proper
ifdef protection in z_pm_save_idle_exit to fix this.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2023-05-02 15:01:24 -05:00
Peter Mitsis f444fcafdb kernel: Minor k_sem_give() performance enhancement
When a semaphore is given and there is no thread waiting
for it, do not unconditionally perform a reschedule.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-04-28 10:09:46 +02:00
Gerard Marull-Paretas 4d06166623 device: allow NULL init function
Some devices do not need to perform any initialization, so allow the
init function to be NULL. In this case, the initialization code will
just mark the device as initialized, i.e. ready.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-04-19 10:00:25 +02:00
Peter Mitsis e1aa1396d8 kernel: Remove unused absolute symbols
Removes unused absolute symbols that are defined via the
GEN_ABSOLUTE_SYM() macro in the kernel directory.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-04-18 10:51:28 -04:00
Keith Packard 0b90fd5adf samples, tests, boards: Switch main return type from void to int
As both C and C++ standards require applications running under an OS to
return 'int', adapt that for Zephyr to align with those standard. This also
eliminates errors when building with clang when not using -ffreestanding,
and reduces the need for compiler flags to silence warnings for both clang
and gcc.

Most of these changes were automated using coccinelle with the following
script:

@@
@@
- void
+ int
main(...) {
	...
-	return;
+	return 0;
	...
}

Approximately 40 files had to be edited by hand as coccinelle was unable to
fix them.

Signed-off-by: Keith Packard <keithp@keithp.com>
2023-04-14 07:49:41 +09:00
Keith Packard fc076f5a1d kernel: Switch main return type from void to int
As both C and C++ standards require applications running under an OS to
return 'int', adapt that for Zephyr to align with those standard. This also
eliminates errors when building with clang when not using -ffreestanding,
and reduces the need for compiler flags to silence warnings for both clang
and gcc

Signed-off-by: Keith Packard <keithp@keithp.com>
2023-04-14 07:49:41 +09:00
Gerard Marull-Paretas 4863c5f05b sys/util: extend usage of DIV_ROUND_UP
Many areas of Zephyr divide and round up without using the DIV_ROUND_UP
macro. Make use of it, so that we make use of a tested system macro and
at the same time we make code more readable.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-04-12 16:42:29 +02:00
Gerard Marull-Paretas a5fd0d184a init: remove the need for a dummy device pointer in SYS_INIT functions
The init infrastructure, found in `init.h`, is currently used by:

- `SYS_INIT`: to call functions before `main`
- `DEVICE_*`: to initialize devices

They are all sorted according to an initialization level + a priority.
`SYS_INIT` calls are really orthogonal to devices, however, the required
function signature requires a `const struct device *dev` as a first
argument. The only reason for that is because the same init machinery is
used by devices, so we have something like:

```c
struct init_entry {
	int (*init)(const struct device *dev);
	/* only set by DEVICE_*, otherwise NULL */
	const struct device *dev;
}
```

As a result, we end up with such weird/ugly pattern:

```c
static int my_init(const struct device *dev)
{
	/* always NULL! add ARG_UNUSED to avoid compiler warning */
	ARG_UNUSED(dev);
	...
}
```

This is really a result of poor internals isolation. This patch proposes
a to make init entries more flexible so that they can accept sytem
initialization calls like this:

```c
static int my_init(void)
{
	...
}
```

This is achieved using a union:

```c
union init_function {
	/* for SYS_INIT, used when init_entry.dev == NULL */
	int (*sys)(void);
	/* for DEVICE*, used when init_entry.dev != NULL */
	int (*dev)(const struct device *dev);
};

struct init_entry {
	/* stores init function (either for SYS_INIT or DEVICE*)
	union init_function init_fn;
	/* stores device pointer for DEVICE*, NULL for SYS_INIT. Allows
	 * to know which union entry to call.
	 */
	const struct device *dev;
}
```

This solution **does not increase ROM usage**, and allows to offer clean
public APIs for both SYS_INIT and DEVICE*. Note that however, init
machinery keeps a coupling with devices.

**NOTE**: This is a breaking change! All `SYS_INIT` functions will need
to be converted to the new signature. See the script offered in the
following commit.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

init: convert SYS_INIT functions to the new signature

Conversion scripted using scripts/utils/migrate_sys_init.py.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

manifest: update projects for SYS_INIT changes

Update modules with updated SYS_INIT calls:

- hal_ti
- lvgl
- sof
- TraceRecorderSource

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

tests: devicetree: devices: adjust test

Adjust test according to the recently introduced SYS_INIT
infrastructure.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>

tests: kernel: threads: adjust SYS_INIT call

Adjust to the new signature: int (*init_fn)(void);

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2023-04-12 14:28:07 +00:00
Kumar Gala 0722b6f74f smp: Add BUILD_ASSERT to make sure Kconfig values are the same
Add check to ensure that CONFIG_MP_NUM_CPUS and CONFIG_MP_MAX_NUM_CPUS
are set the same.  This will at least cause a build issue for out of
tree users.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2023-04-07 13:13:23 +02:00
Nicolas Pitre 524ac8a29a sched: don't call k_sched_time_slice_set() during early init
All we really want here is to set default parameters. However
k_sched_time_slice_set() also calls z_reset_time_slice(_current)
which expects `_current` to be fully initialized.

Simply initialize `slice_ticks` and `slice_max_prio` with default values
directly. Unfortunately the compiler isn't smart enough to expand
k_ms_to_ticks_ceil32(CONFIG_TIMESLICE_SIZE) to a constant expression
at build time so we must do the conversion by hand (and it shouldn't
overflow due to the nature of the value).

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-04-03 19:16:48 -04:00
Nicolas Pitre 405611dc9e sched: remove restriction on single-tick time slices
Slice expirations are now based on the same timeout mechanism as
regular timers which have been recently fixed and proven to work with
single-tick periods.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-04-03 19:16:48 -04:00
Nicolas Pitre 907eea07f2 z_sched_init: don't use arch_num_cpus()
The reason for arch_num_cpus() is to be able to dynamically adapt to
the actual number of available CPUs at run time.

In the z_sched_init() case, it is not the number of active CPUs that
we need but rather the total number of potential CPUs, and that is
represented by CONFIG_MP_MAX_NUM_CPUS not arch_num_cpus().

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-04-03 12:36:30 -04:00
Jordan Yates db3d51bb7d pm: device_runtime: add zephyr,pm-device-runtime-auto
Add the `zephyr,pm-device-runtime-auto` flag to `pm.yaml` and
`struct pm_device`.

This flag is intended to signify to the boot system that device runtime
PM should be automatically enabled on the device after the init function
has run.

Only run `pm_device_runtime_auto_enable` function on a device if
initialisation succeeded. This prevents actions being run on devices
that are not ready.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2023-03-29 12:21:13 -04:00
Nicolas Pitre 5879d2d6c1 sched: minor time slicing cleanup
Make sliceable() the actual condition for a sliceable thread. Avoid
creating a slice timeout for non sliceable threads. Always reset
slice_expired even if the next thread is not sliceable. Fold
slice_expired_locked() into z_time_slice() to avoid the hidden
unlock/lock. Change `curr` to `thread` as this is not necessarily
the current thread (yet) being set. Make variables static.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-03-16 09:16:59 +01:00
Aastha Grover 877fc3d508 kernel: events: fix waitq timeout race condition
Updates events to prevent a timeout from corrupting the list of
threads that needs to be waken up.

Signed-off-by: Aastha Grover <aastha.grover@intel.com>
2023-03-09 09:22:21 +01:00
Aastha Grover 5537776898 kernel: Add z_sched_wake_thread API
This API wakes up a given thread and is also called from
z_thread_timeout()

Signed-off-by: Aastha Grover <aastha.grover@intel.com>
2023-03-09 09:22:21 +01:00
Aastha Grover a2dccf1283 kernel: events: fix walking the waitq race condition
Fixes race condition for k_event_post_internal() in an
SMP environment while walking the waitq. Uses z_sched_waitq_walk()
to safely walk the waitq by using a sched_spinlock.
It should be noted that since walking the wait queue is an
operation of indeterminant length, there exists the possibility
that the sched_spinlock (which is a highly used and contended-for
lock) may be locked for an indeterminant amount of time. However,
it is expected that few threads will be waiting on any given kernel
event object, which should ameliorate this risk.

Fixes #54317

Signed-off-by: Aastha Grover <aastha.grover@intel.com>
2023-03-09 09:22:21 +01:00
Andy Ross c5c3ad95de kernel/sched: Close hole with cross-core timeslice expirations
Moving timeslice events to timeouts isn't quite enough on SMP, as it's
still possible for systems that don't broadcast their timer interrupts
to end up handling an expiration for a foreign CPU.  There, we need an
IPI, and a symmetric call to z_time_slice() (which is itempotent and
fast) in the IPI ISR.

Signed-off-by: Andy Ross <andyross@google.com>
2023-03-09 09:21:12 +01:00
Andy Ross f3afd5a4c9 kernel/sched: Use kernel timeouts for timeslice expirations
Rework the fragile and ad-hoc computation of timeslice expirations
into per-CPU struct _timeout objects with regular callbacks.  The
expiration callbacks themselves simply set a per-cpu flag (they might
run on any CPU), which gets checked at the end of the timer ISR on
every CPU.

This simplifies logic and removes a bunch of code.  It also fixes at
least three bugs:

1. As @npitre discovered: On SMP, the number of ticks announced on any
given CPU is going to be a subset of all expired ticks.  This broke
the accounting of timeslice ticks, and effectively meant that
timeslicing only worked on SMP on systems where one CPU could hog all
the announcements, and only on that CPU.

2. The bootstrap path to arm the timer driver after setting the first
timeout in an empty list couldn't take into account
sys_clock_elapsed() ticks, as it didn't know whether it was being
called underneath an existing announce loop.  Now this code is no
longer responsible for knowing anything about time slicing at all.

3. Also on SMP, there was a case where two CPUs timeslicing
simultaneously could stomp on each others' timeouts in
z_set_timeout_expiry(), as neither had a way of knowing what the
other's state was.  CPUs could miss their own expiration and have to
wait for the slice expiration on the other CPU.  Now, timeouts are
global objects with simple expiration times, and there's no need for
that function at all.

Signed-off-by: Andy Ross <andyross@google.com>
2023-03-09 09:21:12 +01:00
Peter Mitsis a06f9ac418 kernel: Remove unused derived offset symbols
Some of the offset symbols that are derived from the macro
GEN_OFFSET_SYM() are not used anywhere in the Zephyr codebase.
Remove them as part of a cleanup effort.

Instances of an associated GEN_OFFSET_SYM() have also been
removed when the resulting macro is no longer referenced.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-22 16:01:32 +01:00
Peter Mitsis fa23eb49b3 kernel: Remove unused generated offset symbols
Some of the offset symbols generated via the macro GEN_OFFSET_SYM()
are not used anywhere in the Zephyr codebase. Remove them as part of
a cleanup effort.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-22 16:01:32 +01:00
Nicolas Pitre 6a51a10dec kernel/timer: fix period argument clamp handling
Commit 3e729b2b1c ("kernel/timer: Correctly clamp period argument")
increased the lower limit to 1 so that it wouldn't conflict with a
K_NO_WAIT. But in doing so it enforced a minimum period of 2 ticks.
And the subtraction must obviously be avoided if the period is zero, etc.

Instead of doing this masquerade in k_timer_start(), let's move the
subtraction and clamping in z_timer_expiration_handler() right before
registering a new timeout. It makes the code cleaner, and then it is
possible to have single-tick periods again.

Whith this, timer_jitter_drift in tests/kernel/timer/timer_behavior does
pass with any CONFIG_SYS_CLOCK_TICKS_PER_SEC value, even when the tick
period is equal or larger than the specified timer period for the test
which failed the test before.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2023-02-20 09:52:53 +01:00
Andy Ross d00f9b594b kernel/work: Fix race under with delayed work item cancellation
The call to unschedule_locked() would return true ("successfully
unscheduled") even in the case where the underlying z_abort_timeout()
failed (because the callback was already unpended and
in-progress/complete/about-to-be-run, remember that timeout callbacks
are unsynchronized), leading to state bugs and races against the
callback behavior.

Correctly detect that case and propagate the error to the caller.

Fixes #51872

Signed-off-by: Andy Ross <andyross@google.com>
2023-02-11 12:14:16 +09:00
Peter Mitsis 1b49cd2551 kernel: pipes: ISRs use a private pipe descriptor
Fixes sporadic data access violations that were occuring when pipes
were being used from an ISR. The ISR was incorrectly using the pipe
descriptor belonging to the interrupted thread. This led to corrupted
pipe meta-data. The solution proposed here is to perform a run-time
check and if use a pipe descriptor on the ISR's stack if called from
an ISR.

For additional information, see:
   https://github.com/zephyrproject-rtos/zephyr/issues/52812

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-11 06:45:13 +09:00
Peter Mitsis 59cb96e802 kernel: pipes: Add spin lock/unlock barrier pair
Adds a spin lock/unlock barrier pair after a pipe thread wakes.
After the list of waiting threads is generated, it is possible for
threads on that list to timeout and be removed from the wait queue.
However, since that list was generated before the timeout occurred,
the timed-out thread must wait until the copying is done (the
pipe's spin-lock has been released).

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-11 06:45:13 +09:00
Peter Mitsis 31dfd84fd5 kernel: pipes: Change method of unpending waiters
By the time the working list of readers/writers is processed, it is
possible that waiting reader/writer being processed had timed out
and is no longer on the wait queue. As such, we can not blindly
wake the next thread as that next thread might not be the thread we
had just been processing.

To address this, the calls to z_sched_wake() have been replaced
with z_unpend_thread() and z_ready_thread() so that a specific
thread can be safely targeted for waking.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-11 06:45:13 +09:00
Peter Mitsis 0037712e68 kernel: pipes: use wait queue walker to build list
Uses the new z_sched_waitq_walk() routine to walk the pipe's wait
queue to build a list of waiting threads that will be used for
the data transfer.

This method is preferred over the previous as it ensures that
wait queue is safely traversed.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-11 06:45:13 +09:00
Peter Mitsis ca58339e16 kernel: Add routine to walk a wait queue
Adds a routine to safely walk a specified wait queue and invoke a
custom callback function on each waiting thread.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-02-11 06:45:13 +09:00
Andrzej Głąbek e60af79268 kernel: timer: Eliminate a race condition in expiration handling
When a timer is restarted from a high priority interrupt, it may
happen that the timer is re-added to the timeout list right after
it is removed from that list prior to execution of its expiration
handler but before that execution actually occurs. This leads to
an assertion failure reported for `z_add_timeout()` because then
that function, called from `z_timer_expiration_handler()` for
periodic timers, turns out to be adding a timeout that is already
added to the timeout list.
This commit detects such situation in `z_timer_expiration_handler()`
and makes that function exit immediately when that occurs (as the
timer was restared, its expiration handler should not be executed).

Signed-off-by: Andrzej Głąbek <andrzej.glabek@nordicsemi.no>
2023-02-08 10:17:56 +01:00
romain pelletant 14bcc859ca kernel: k_msgq: add peek at function
Make message queue able to peek data at the specified index.
Related to issue #53360

Signed-off-by: romain pelletant <romainp@kickmaker.net>
2023-01-26 10:00:29 +00:00
Daniel Leung 256db60ebf kernel: mark z_cstart to not have stack protector
Most of the time, z_cstart() is running on an arbitrary region
of memory as stack, where the necessary stack setup has not been
performed. This prevents stack protection to work correctly,
as the stack canary has not been populated. So mark z_cstart()
to have no stack protection at all inside the function to avoid
raising exception during boot.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2023-01-24 13:04:45 -05:00
Stephanos Ioannidis 4a64bfe351 treewide: Use CONFIG_CPP instead of CONFIG_CPLUSPLUS
This commit updates all in-tree code to use `CONFIG_CPP` instead of
`CONFIG_CPLUSPLUS`, which is now deprecated.

Signed-off-by: Stephanos Ioannidis <stephanos.ioannidis@nordicsemi.no>
2023-01-13 17:42:55 -05:00
Flavio Ceolin 080464c7c4 kernel: banner: Remove unnecessary header
sys/util.h is not needed.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-01-09 12:07:28 -05:00
Flavio Ceolin 2757e711e1 kernel: sched: Remove possible deadcode
Put z_priq_dumb_add inside a ifdef guard to avoid deadcode.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2023-01-09 12:07:28 -05:00
Peter Mitsis 42db096d28 kernel: resolve static analysis false positives
At least one static analysis tool is flagging a potential NULL
derefence in sys_clock_announce()'s tick processing loop where the
routine 'first()' is concerned. In practice, this does not occur as
...

  1. The code in question is protected by a spinlock.
  2. 'first()' does not change the contents of anything.

The code has consequently been tweaked to prevent similar such false
positives in the future.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2023-01-05 18:23:04 +00:00
Chris Friedt 4108e14740 ztest: provide sys_clock_tick_set syscall
Accurate timekeeping is something that is often taken for granted.

However, reliability of timekeeping code is critical for most core
and subsystem code. Furthermore, Many higher-level timekeeping
utilities in Zephyr work off of ticks but there is no way to modify
ticks directly which would require either unnecessary delays in
test code or non-ideal compromises in test coverage.

Since timekeeping is so critical, there should be as few barriers
to testing timekeeping code as possible, while preserving
integrity of the kernel's public interface.

With this, we expose `sys_clock_tick_set()` as a system call only
when `CONFIG_ZTEST` is set, declared within the ztest framework.

Signed-off-by: Chris Friedt <cfriedt@meta.com>
2023-01-04 21:12:58 +01:00
Jaxson Han bba9fc9853 kernel: Kconfig: Increase the main stack size for ARM when TEST
The following testcases fail with qemu_cortex_r5 caused by main stack
overflow.
tests/kernel/workq/work_queue/kernel.workqueue
tests/ztest/base/testing.ztest.base.verbose_0_userspace

The main stack size is 512 for qemu_cortex_r5(a Cortex-A/R aarch32
platform) with CONFIG_ZTEST=y. The Cortex-M platforms are already set to
1024. Likely 512 will fail for most aarch32 platforms soon.

Fix the issue by increasing the CONFIG_MAIN_STACK_SIZE to 1024.
Also, remove 'default 1024 if TEST_ARM_CORTEX_M' since Cortex-M is no
longer an exception of default 1024.

Signed-off-by: Jaxson Han <jaxson.han@arm.com>
2022-12-09 21:59:10 +09:00
Martin Jäger caba2ad616 kernel: events: add function to clear events
Shortcut making it easier to clear events than with k_event_set_masked.

Signed-off-by: Martin Jäger <martin@libre.solar>
2022-12-02 09:50:42 -05:00
Martin Jäger 58ece9d503 kernel: events: fix doc typo and remove empty lines
event_wait_all waits for *all* of the specified events, as the name
suggests.

Signed-off-by: Martin Jäger <martin@libre.solar>
2022-12-02 09:50:42 -05:00
Gerard Marull-Paretas 737d799660 kernel: sched: fix ticks logging
- Logging supports printing 64-bit values now. Cast to unsigned long and
  use %lu all times.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-11-29 09:52:04 +01:00
Daniel Leung 100eacca07 kernel: mmu: fix potential running out of virtual memory space
In z_phys_unmap(), the call to virt_region_free() is not using
aligned virtual address and space. This can result in freeing
smaller region that allocated given that inputs to z_phys_unmap()
may not be aligned. So use the already calculated aligned
virtual address and size as input to virt_region_free().

Note that the assertion and if-block in virt_region_free() to
check whether the to-be-unmapped region is within the virtual
memory region needs to be trimmed by one byte at the end.
The assertion and if-block are checking against the region
end address but (start + size) is just one byte over the end.
So subtract one.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2022-11-17 15:56:04 +00:00
Stephanos Ioannidis fa5fd41b61 kernel: Add C++ main() support
The C++ standard requires the main() function to have the return type
of 'int' and does not allow the main() to be defined with the 'void'
return type. Moreover, GCC goes as far as to emit a hard error when the
'::main()' has the return type of `void`.

This commit introduces an option to instruct the Zephyr kernel to call
the 'int main(void)' instead of the 'void main(void)' in case a Zephyr
application defines main() in a C++ source file.

Signed-off-by: Stephanos Ioannidis <stephanos.ioannidis@nordicsemi.no>
2022-11-05 16:41:45 +09:00
Kumar Gala 4f458ba8de kernel: Convert away from CONFIG_MP_NUM_CPUS
Move runtime code to use arch_num_cpus() instead of CONFIG_MP_NUM_CPUS
and use CONFIG_MP_MAX_NUM_CPUS for ifdef and BUILD_ASSERT macros.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2022-10-31 17:09:14 +01:00
Jordan Yates d1d20c08cd kernel: banner: cleanup #ifdef's
Cleanup the mess of duplicate function definitions, unnecessary
variables and duplicate strings. All banner strings are now constant in
ROM. Also fixes a double space between the end of the version string and
the trailing `***` when there is no boot delay.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2022-10-28 18:38:06 -04:00
Jordan Yates 635f8951e1 kernel: boot: add BOOT_DELAY dependency
The BOOT_DELAY option does nothing in code if MULTITHREADING is not
enabled. Move the dependency to Kconfig instead.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2022-10-28 18:38:06 -04:00
Kumar Gala a1195ae39b smp: Move for loops to use arch_num_cpus instead of CONFIG_MP_NUM_CPUS
Change for loops of the form:

for (i = 0; i < CONFIG_MP_NUM_CPUS; i++)
   ...

to

unsigned int num_cpus = arch_num_cpus();
for (i = 0; i < num_cpus; i++)
   ...

We do the call outside of the for loop so that it only happens once,
rather than on every iteration.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2022-10-21 13:14:58 +02:00
Kumar Gala 6393a7ce5c smp: Kconfig: Move to using MP_MAX_NUM_CPUS
Continue to phase out MP_NUM_CPUS, change Kconfig to be
MP_MAX_NUM_CPUS and make MP_MAX_NUM_CPUS the main Kconfig symbol.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2022-10-20 22:04:10 +09:00
Keith Packard 95cec04c7c kernel: When TLS, skip switched_out tracing hook from dummy thread
The dummy thread doesn't include a TLS area, so any thread local variables
will fail to work if used in the switched_out tracing hook. Skip the hook
in this case, as it's not really accurate anyways; the dummy thread is
only used to set context for the initial switch for each core.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-10-19 16:00:00 +02:00
Krzysztof Chruscinski bf39f545e3 kernel: thread: Add casting to pointers in the log message
Using char pointers for %p should be avoided in log messages. It will
cause issues in configurations where logging strings are removed from
the binary and they are not inspected when cbprintf packages from
logging string are built. In that case any char pointers are treated as
strings and copied into the pacakge body.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-10-18 14:13:19 +02:00
Kumar Gala c778eb2a56 smp: Move arrays to use CONFIG_MP_MAX_NUM_CPUS
Move to use CONFIG_MP_MAX_NUM_CPUS for array size declarations instead
of CONFIG_MP_NUM_CPUS.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2022-10-17 14:40:12 +09:00
Kumar Gala 2530ba5750 arch: smp: Allow for number of cpus to be determined at runtime
Introduce a Kconfig (MP_MAX_NUM_CPUS) and an api arch_num_cpus() to
allow for systems that might determine the number of CPUs available to
Zephyr at runtime.

CONFIG_MP_MAX_NUM_CPUS is intented to be use for any array initialization
and such that need to occur at build time.  For most systems
arch_num_cpus() will just report the value of CONFIG_MP_MAX_NUM_CPUS.

The intent is to phase out CONFIG_NP_NUM_CPUS.

Signed-off-by: Kumar Gala <kumar.gala@intel.com>
2022-10-13 16:02:19 +09:00
Francois Ramu e01bee5bcc kernel: idle: fix -Werror=misleading-indentation
Warnings being treated as errors when building :
Error this 'for' clause does not guard...
[-Werror=misleading-indentation]

Signed-off-by: Francois Ramu <francois.ramu@st.com>
2022-10-12 18:43:15 +02:00
Gerard Marull-Paretas 495245a971 init: remove _SYS_INIT_LEVEL* definitions
The _SYS_INIT_LEVEL* definitions were used to indicate the index entry
into the levels array defined in init.c (z_sys_init_run_level). init.c
uses this information internally, so there is no point in exposing this
in a public header. It has been replaced with an enum inside init.c. The
device shell was re-using the same defines to index its own array. This
is a fragile design, the shell needs to be responsible of its own data
indexing. A similar situation happened with some unit tests.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-10-12 18:49:12 +09:00
Gerard Marull-Paretas 831239300f kernel: move z_sys_init_run_level to init.c
The function in charge of calling all init function was defined in
device.c, had a public prototype and was just used in init.c. Since this
is really an internal function tied to Kernel init code, move it to
init.c and make it static, there's no need to expose it publicly.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-10-12 18:49:12 +09:00
Gerard Marull-Paretas e42f58ec94 init: s/ARCH/EARLY, call it just before arch kernel init
The `ARCH` init level was added to solve a specific problem, call init
code (SYS_INIT/devices) before `z_cstart` in the `intel_adsp` platform.
The documentation claims it runs before `z_cstart`, but this is only
true if the SoC/arch takes care of calling:

```c
z_sys_init_run_level(_SYS_INIT_LEVEL_ARCH);
```

Which is only true for `intel_adsp` nowadays. So in practice, we now
have a platform specific init level. This patch proposes to do things in
a slightly different way. First, level name is renamed to `EARLY`, to
emphasize it runs in the early stage of the boot process. Then, it is
handled by the Kernel (inside `z_cstart()` before calling
`arch_kernel_init()`). This means that any platform can now use this
level. For `intel_adsp`, there should be no changes, other than
`gcov_static_init()` will be called before (I assume this will allow to
obtain coverage for code called in EARLY?).

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-10-12 17:16:27 +09:00
Andy Ross c32f376e99 kernel/sched: Fix SMP race on pend
For historical reasons[1] suspending threads would release the
scheduler lock between pend() (which places the current thread onto a
wait queue) and z_swap() (which effects the context swtich).  This
process happens with the caller's lock held, so local interrupts are
masked.  But on SMP this opens a tiny race where another CPU could
grab the pended thread and switch to it while we were still executing
on its stack!

Fix this by elevating the "lock swap" code that already exists in the
(portable/switch-based) z_swap() code one level so that it happens in
z_pend_curr() also.  Now we hold the scheduler lock between pend and
the final context switch.

Note that this technique can't work for the older z_swap_irqlock()
implementation, which exists to vestigially support a few bits of arch
code (mostly direct interrupts) that don't work on SMP anyway.
Address with an assert to prevent future misuse.

[1] z_swap() is a historical API implemented in per-arch assembly for
    older architectures (like ARM32!).  It was designed to be called
    with what at the time was a global IRQ lock, so it doesn't
    understand the idea of a separate scheduler lock.  When we finally
    get all archictures on arch_switch() this design can be cleaned up
    quite a bit.

Signed-off-by: Andy Ross <andyross@google.com>
2022-10-11 12:16:38 -04:00
Gerard Marull-Paretas 27845886a1 kernel: device: add missing kobject.h include
The module references a function declared in kobject.h.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-10-11 18:05:17 +02:00
Anas Nashif e8395351e6 kernel: init: introduce a new init level: ARCH
We have cases where some devices needs to be initialized very early and
before c_start is call, i.e. to setup very early console or to setup
memory. Traditionally this would be hardcoded as part of the soc layer
and not using device model or the init levels.

This patch adds a new level ARCH, which will be called in early
architecture code and before we jump to the kernel code.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-10-11 08:28:25 -04:00
Jay Shoen b4734d5397 kernel: kheap: fix k_heap_aligned_alloc handling of K_FOREVER
k_heap_aligned_alloc was not handling K_FOREVER timeout
correctly due to unsigned return value. Added explicit
K_FOREVER handling of end time.

Fixes #50611.

Signed-off-by: Jay Shoen <jay.shoen@perceive.io>
2022-09-29 10:39:12 -05:00
Nicolas Pitre 1f362a81f1 riscv: fix crash resulting from touching the initial stack's guard area
The interrupt stack is used as the system stack during kernel
initialization while IRQs are not yet enabled. The sp register is
set to z_interrupt_stacks + CONFIG_ISR_STACK_SIZE.

CONFIG_ISR_STACK_SIZE only represents the desired usable stack size.
This does not take into account the added guard area. Result is a stack
whose pointer is much closer to the trigger zone than expected when
CONFIG_PMP_STACK_GUARD=y, and the SMP configuration in particular pushes
it over the edge during many CI test cases.

Worse: during early init we're not quite ready to handle exceptions
yet and complete havoc ensues with no meaningful debugging output.

Make sure the early assembly code locates the actual top of the stack
by generating a constant with its true size.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2022-09-28 07:53:56 +00:00
Tom Burdick 9c0bf4b071 kernel: Obtain current cpu inside of locks for thread usage
Obtaining the CPU outside of the spin locks on SMP would
result in an assert failing on __ASSERT(!z_smp_mobile())
which makes sense as the current cpu may change.

Signed-off-by: Tom Burdick <thomas.burdick@intel.com>
2022-09-26 07:55:33 +00:00
Andy Ross 0ca7150f90 kernel/idle: Fix !SCHED_IPI_SUPPORTED
The requirement for k_yield() to handle "yielding" in the idle thread
was removed a while back, but it missed a spot where we'd try to yield
in the fallback loop on bringup platforms that lack an IPI.  This now
crashes, because yield now unconditionally tries to reschedule the
current thread, which doesn't work for idle threads that don't live in
the run queue.

Just make it a busy loop calling swap(), even simpler.

Fixes #50119

Signed-off-by: Andy Ross <andyross@google.com>
2022-09-19 09:19:02 +02:00
Kai Vehmanen e81ccef613 kernel/sched: fix condition for CPU mask set
When building with CONFIG_SCHED_CPU_MASK_PIN_ONLY=y, CPU mask
is fixed and cannot be changed while thread is running.

The current code asserts if thread state is anything but PREPARED.

We do however have interface like k_work_queue_start() where a thread is
started as part of the queue start. To allow user to set the pinned CPU
for the work queue thread, it needs to be possible to suspend the
thread, set the mask, and then call k_thread_resume(). This seems to be
a valid sequence, so relax the assert check to reflect this.

Signed-off-by: Kai Vehmanen <kai.vehmanen@linux.intel.com>
2022-09-09 16:13:35 -04:00
Anas Nashif 6a9540a773 tracing: ctf: add timer support
Add k_timer tracing to CTF and other formats.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-08-31 16:04:01 -04:00
Jeremy Herbert 379ca18a93 kernel: allow k_poll to wait on pipes
k_poll does not currently allow polling on pipes. This adds support
for doing so on buffered pipes.

Signed-off-by: Jeremy Herbert <jeremy.006@gmail.com>
2022-08-24 17:49:20 +00:00
Carlo Caione 4806e1087e cache: Fix cache API calling from userspace
When a cache API function is called from userspace, this results on
ARM64 in an OOPS (bad syscall error). This is due to at least two
different factors:

- the location of the cache handlers is preventing the linker to
  actually find the handlers
- specifically for ARM64 and ARC some cache handling functions are not
  implemented (when userspace is not used the compiler simply optimizes
  out these calls)

Fix the problem by:

- moving the userspace cache handlers to a their logical and proper
  location (in the drivers directory)
- adding the missing handlers for ARM64 and ARC

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2022-08-23 10:14:17 +02:00
Gerard Marull-Paretas a202341958 devices: constify device pointers initialized at compile time
Many device pointers are initialized at compile and never changed. This
means that the device pointer can be constified (immutable).

Automated using:

```
perl -i -pe 's/const struct device \*(?!const)(.*)= DEVICE/const struct
device *const $1= DEVICE/g' **/*.c
```

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-08-22 17:08:26 +02:00
Andy Ross 5722da71ce kernel: Skip bss clear on native_posix
There's no point to doing this when the host OS clears all memory at
mapping time.  And as it turns out, the __bss_end symbol it was
relying on actually comes from the host toolchain's linker, not our
own linker scripts (making it semi-dangerous to rely on).  And it's
not present in clang/lld output anyway.

Signed-off-by: Andy Ross <andyross@google.com>
2022-08-19 08:30:01 +02:00
Peter Mitsis f86027ffb7 kernel: pipes: rewrite pipes implementation
This new implementation of pipes has a number of advantages over the
previous.
  1. The schedule locking is eliminated both making it safer for SMP
     and allowing for pipes to be used from ISR context.
  2. The code used to be structured to have separate code for copying
     to/from a wating thread's buffer and the pipe buffer. This had
     unnecessary duplication that has been replaced with a simpler
     scatter-gather copy model.
  3. The manner in which the "working list" is generated has also been
     simplified. It no longer tries to use the thread's queuing node.
     Instead, the k_pipe_desc structure (whose instances are on the
     part of the k_thread structure) has been extended to contain
     additional fields including a node for use with a linked list. As
     this impacts the k_thread structure, pipes are now configurable
     in the kernel via CONFIG_PIPES.

Fixes #47061

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-08-17 19:31:25 +02:00
Qi Yang 89c4a074dc kernel: mutex: fix races when lock timeout
Say threadA holds a mutex and threadB tries
to lock it with a timeout, a race would occur
if threadA unlock that mutex after threadB
got unpended by sys_clock and before it gets
scheduled and calls k_spin_lock.

This patch fixes this issue by checking the
mutex's status again after k_spin_lock calls.

Fixes #48056

Signed-off-by: Qi Yang <qi.yang@cmind-semi.com>
2022-08-12 17:40:20 +02:00
Hu Zhenyu 57487622f5 kernel: Init the base.slice_ticks for dummy_thread
Fixes #46324
Set dummy_thread->base.slice_ticks to 0 when
CONFIG_TIMESLICE_PER_THREAD is set. To avoid
_current_cpu->slice_ticks be a big number.

Signed-off-by: Hu Zhenyu <zhenyu.hu@intel.com>
2022-08-04 19:44:24 -04:00
Peter Mitsis 71ef669ea4 kernel: Fixes sys_clock_tick_get()
Fixes an issue in sys_clock_tick_get() that could lead to drift in
a k_timer handler. The handler is invoked in the timer ISR as a
callback in sys_tick_announce().
  1. The handler invokes k_uptime_ticks().
  2. k_uptime_ticks() invokes sys_clock_tick_get().
  3. sys_clock_tick_get() must call elapsed() and not
     sys_clock_elapsed() as we do not want to count any
     unannounced ticks that may have elapsed while
     processing the timer ISR.

Fixes #46378

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-08-04 05:32:11 -04:00
Peter Mitsis 3e2f30a7ef kernel: fix race condition in sys_clock_announce()
Updates sys_clock_announce() such that the <announce_remaining> update
calculation is done after the callback. This prevents another core from
entering the timeout processing loop before the first core leaves it.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-08-03 17:43:04 -04:00
Anas Nashif 13714a6742 kernel: clock: fix SYS_CLOCK_EXISTS help
SYS_CLOCK_EXISTS help was describing the 'do not exist' case and is
confusing.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-08-02 13:57:17 -04:00
Andrew Jackson e183671808 kernel: Add k_event_set_masked primitive
There is no easy way to clear event bits without
the potential for a race to exist between producer(s)
and consumer(s). The result of this race is that events
can be lost through the various resetting mechanisms
available (flag to k_event_wait(), or k_event_set()).

Add k_event_set_masked() which permits bits to be set or cleared.
This allows consumers to clear just the bits that they have read
without (accidentally) discarding any new bits.

Update unit tests to verify the functionality.

Partly Fixes #46117.

Signed-off-by: Andrew Jackson <andrew.jackson@amd.com>
2022-07-25 15:24:32 -04:00
Andrew Jackson e7e827a0d2 kernel: Use mask rather than boolean to update events
Although there is nothing wrong with the existing code,
it doesn't permit individual bits to be set (or cleared).
This makes further changes slightly awkward.

Use a mask to restrict the bits set in an event.

Signed-off-by: Andrew Jackson <andrew.jackson@amd.com>
2022-07-25 15:24:32 -04:00
Simon Hein 02cfbfea51 kernel: comply to coding guidelines MISRA C:2012 Rule 14.4
MISRA C:2012 Rule 14.4 (The controlling expression of an if statement
and the controlling expression of an iteration-statement shall have
essentially Boolean type.)

Use `bool' instead of `int' to represent Boolean values.
Use `do { ... } while (false)' instead of `do { ... } while (0)'.
Use comparisons with zero instead of implicitly testing integers.

This commit is a subset of the original commit:
5d02614e34a86b549c7707d3d9f0984bc3a5f22a

Signed-off-by: Simon Hein <SHein@baumer.com>
2022-07-21 06:16:16 -04:00
Johann Fischer 3c971307dc arch/kernel/soc/samples: use unsigned int for irq_lock()
irq_lock() returns an unsigned integer key.
Generated by spatch using semantic patch
scripts/coccinelle/irq_lock.cocci

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
2022-07-14 14:37:13 -05:00
Peter Mitsis 1244065abc kernel: Extend slabs memory usage stats
Adds memory usage runtime stats routines that parallel those used
by both the heap and mem_blocks. This helps maintain some level of
of consistency across the different memory types.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-07-12 13:59:26 +00:00
Anas Nashif efbadbb677 scripts: move gen_kobject_list.py to scripts/build/gen_kobject_list.py
Move scripts needed by the build system and not designed to be run
individually or standalone into the build subfolder.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2022-07-12 10:03:45 +02:00
Jordan Yates 6f41d52734 kernel: switch to SYS_INIT_NAMED
Update the two locations that use two `SYS_INIT` macros with the same
initilisation functions to use `SYS_INIT_NAMED`.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2022-07-06 10:44:35 +02:00
Enjia Mai 89a9eab652 drivers: console: add a minimal EFI console driver to support printf
Add a minimal EFI console driver to support printf, this console driver
only supports console output. Otherwise the printf will not work.

Signed-off-by: Enjia Mai <enjia.mai@intel.com>
2022-07-05 16:52:32 -04:00
Abramo Bagnara ad8778d019 coding guidelines: comply with MISRA C:2012 Rule 4.1
MISRA C:2012 Rule 4.1 (Octal and hexadecimal escape sequences shall be
terminated.)

Use string literal concatenation to properly terminate hexadecimal
escape sequences.

Signed-off-by: Abramo Bagnara <abramo.bagnara@bugseng.com>
Signed-off-by: Simon Hein <SHein@baumer.com>
2022-06-30 19:51:59 -04:00
Lauren Murphy 318e6db239 debug: coredump: add xtensa intel adsp, support toolchains
Adds compatibility with Intel ADSP GDB from Zephyr SDK and
from Cadence toolchain to coredump_gdbserver.py.

Adds CAVS 15-25 (APL) register definitions. Implements
handle_register_single_read_packet to serve ADSP GDB
p packets.

Prevents BSA from changing between stack dump printout
and coredump by taking lock. Observed to be necessary for
accurate results on slower simulated platforms.

Signed-off-by: Lauren Murphy <lauren.murphy@intel.com>
2022-06-23 15:44:45 -04:00
Krzysztof Chruscinski 041f0e5379 all: logging: Remove log_strdup function
Logging v1 has been removed and log_strdup wrapper function is no
longer needed. Removing the function and its use in the tree.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2022-06-23 13:42:23 +02:00
Stephanos Ioannidis 360f810704 kernel: Migrate to K_KERNEL_PINNED_STACK_ARRAY_DECLARE
This commit updates all deprecated `K_KERNEL_PINNED_STACK_ARRAY_EXTERN`
macro usages to use the `K_KERNEL_PINNED_STACK_ARRAY_DECLARE` macro
instead.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2022-06-20 10:25:52 +02:00
Gerard Marull-Paretas afffc1006f kernel: remove redundant <zephyr/zephyr.h> includes
Files including <zephyr/kernel.h> do not have to include
<zephyr/zephyr.h>, a shim to <zephyr/kernel.h>.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-06-15 09:13:11 +02:00
David Palchak b4a7f0f2ca linker: ensure global constructors only run once
Rename the symbols used to denote the locations of the global
constructor lists and modify the Zephyr start-up code accordingly.
On POSIX systems this ensures that the native libc init code won't
find any constructors to run before Zephyr loads.

Fixes #39347, #36858

Signed-off-by: David Palchak <palchak@google.com>
2022-06-09 11:33:36 +02:00
Keith Packard 275b40ef25 kernel: Allow non-zephyr toolchains to advertise TLS support
Use a new environment variable,
ZEPHYR_TOOLCHAIN_SUPPORTS_THREAD_LOCAL_STORAGE, to set the value for
TOOLCHAIN_SUPPORTS_THREAD_LOCAL_STORAGE instead of setting it to 'n' for
all non-Zephyr toolchains. In particular, the Debian arm-none-eabi
toolchain has TLS support and with this option, can be used to build
Zephyr with thread local variables.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-06-05 14:29:12 +02:00
Andy Ross fb613594c7 kernel/sched: Panic on aborting essential threads
Documentation specifies that aborting/terminating/exiting essential
threads is a system panic condition, but we didn't actually implement
that and allowed it as for other threads. At least one app wants to
exploit this documented behavior as a "watchdog" kind of condition,
and that seems reasonable.  Do what we say we're supposed to do.

This also includes a small fix to a test, which seemed like it was
written to exercise exactly this condition.  Except that it failed to
detect whether or not a system fatal error was actually signaled and
was (incorrectly) indicating "success".  Check that we actually enter
the handler.

Fixes #45545

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2022-05-20 12:34:30 +02:00
Peter Mitsis 976e4087ec kernel: Fix gathering of runtime thread stats
The function k_thread_runtime_stats_all_get() now populates the
current_cycles field in the thread runtime stats structure.

Resets the number of cycles in the CPU's current usage window once
the idle thread is scheduled.

Fixes the average_cycles calcuation.

Signed-off-by: Peter Mitsis <peter.mitsis@intel.com>
2022-05-13 10:19:53 -05:00
Keith Packard 4fc00cae7a kernel: Allow Zephyr to use libc's internal errno
For a library which already provides a multi-thread aware errno, use
that instead of creating our own internal value.

Signed-off-by: Keith Packard <keithp@keithp.com>
2022-05-12 19:06:48 -04:00
Lucas Dietrich 9a848b3ad4 kernel: workq: Add internal function z_work_submit_to_queue()
This adds the internal function z_work_submit_to_queue(), which
submits the work item to the queue but doesn't force the thread to yield,
compared to the public function k_work_submit_to_queue().

When called from poll.c in the context of k_work_poll events, it ensures
that the thread does not yield in the context of the spinlock of object
that became available.

Fixes #45267

Signed-off-by: Lucas Dietrich <ld.adecy@gmail.com>
2022-05-10 18:39:51 +02:00
Gerard Marull-Paretas cffefc818d kernel: migrate includes to <zephyr/...>
In order to bring consistency in-tree, migrate all kernel code to the
new prefix <zephyr/...>. Note that the conversion has been scripted,
refer to zephyrproject-rtos#45388 for more details.

Signed-off-by: Gerard Marull-Paretas <gerard.marull@nordicsemi.no>
2022-05-09 09:26:20 +02:00
Jordan Yates 1ef647f396 kernel: add k_can_yield helper function
Implements a function that application and driver code can use to check
whether it is valid to yield (or block) in the current context. This
check is required for functions that can feasibly be run from multiple
contexts. The primary intended use case is power management transition
functions, which can be run by application code explicitly or
automatically in the idle thread by system PM.

Signed-off-by: Jordan Yates <jordan.yates@data61.csiro.au>
2022-05-06 11:33:10 +02:00
Bradley Bolen 88ba97fea4 arch: arm: aarch32: cortex_a_r: Add shared FPU support
This adds lazy floating point context switching.  On svc/irq entrance,
the VFP is disabled and a pointer to the exception stack frame is saved
away.  If the esf pointer is still valid on exception exit, then no
other context used the VFP so the context is still valid and nothing
needs to be restored.  If the esf pointer is NULL on exception exit,
then some other context used the VFP and the floating point context is
restored from the esf.

The undefined instruction handler is responsible for saving away the
floating point context if needed.  If the handler is in the first
irq/svc context and the current thread uses the VFP, then the float
context needs to be saved.  Also, if the handler is in a nested context
and the previous context was using the FVP, save the float context.

Signed-off-by: Bradley Bolen <bbolen@lexmark.com>
2022-05-05 12:03:27 +09:00
Flavio Ceolin 551038e748 kernel: sched: Change cpu pin only for not executing threads
Do not allow changing the CPU which a thread is pinned when it is
already being executed. This allows further optimizations in some
platforms with incoherent memory since we can safely assume that the
thread will run in the same CPU and avoid invalidate / flush the
cache during context switches.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2022-05-04 13:46:48 -04:00
Andy Ross 7a59cebf12 kernel/k_timer: Robustify vs. late interrupts
The k_timer utility was written to assume that the kernel timeout
handler would never be delayed by more than a tick, so it can naively
reschedule the next interrupt with a simple delay.

Unfortunately real platforms have glitchy hardware and high tick
rates, and on intel_adsp we're seeing this promise being broken in
some circumstances.

It's probably not a good idea to try to plumb the timer driver
interface up into the IPC layer to do this correction, but thankfully
the existing absolute timeout API provides the tools we need (though
it does require that CONFIG_TIMEOUT_64BIT be enabled).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2022-05-04 09:55:46 -05:00
Andy Ross b4e9ef0691 kernel/sched: Defer IPI sending to schedule points
The original design intent with arch_sched_ipi() was that
interprocessor interrupts were fast and easily sent, so to reduce
latency the scheduler should notify other CPUs synchronously when
scheduler state changes.

This tends to result in "storms" of IPIs in some use cases, though.
For example, SOF will enumerate over all cores doing a k_sem_give() to
notify a worker thread pinned to each, each call causing a separate
IPI.  Add to that the fact that unlike x86's IO-APIC, the intel_adsp
architecture has targeted/non-broadcast IPIs that need to be repeated
for each core, and suddenly we have an O(N^2) scaling problem in the
number of CPUs.

Instead, batch the "pending" IPIs and send them only at known
scheduling points (end-of-interrupt and swap).  This semantically
matches the locations where application code will "expect" to see
other threads run, so arguably is a better choice anyway.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2022-05-02 10:23:13 -05:00