Commit graph

2970 commits

Author SHA1 Message Date
Andy Ross 3c2c1d85b0 kernel: Remove z_mem_pool wrapper internals
These implemented a k_mem_pool in terms of the now universal k_heap
utility.  That's no longer necessary now that the k_mem_pool API has
been removed.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross c844bd87b3 kernel: Remove legacy mem_pool usage
The mailbox and msgq utilities had API variants that could pass old
mem_pool blocks through the data structure.  That API is being
deprected (and the features were obscure), so remove the internal
support.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross c770cab1a3 kernel: Make thread resource pools into sys_heaps
The k_mem_pool allocator is no more, and the z_mem_pool compatibility
API is going away.  The internal allocator should be a k_heap always.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross 9413922625 kernel/k_malloc: Decouple k_malloc/k_free from mem_pool
These were implemented in terms of the mem_pool/block API directly
(for complicated reasons, the pointers returned from this API may have
been allocated from allocators other than the single system heap).
Have them use a k_heap instead.

Requires a tweak to one test which had hard-coded an assumption about
the header size.

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

Fixes #24358

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Andy Ross 8a6aee9cac kernel: Make the "heap" backend to mem_pool default
Remove the MEM_POOL_HEAP_BACKEND kconfig, treating it as true always.
Now the legacy mem_pool cannot be enabled and all usage uses the
k_heap/sys_heap backend.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-12-07 21:50:14 -05:00
Kamil Lazowski 303fca9f2a kernel: mem_slab: Optimize mem_slab_free
Changed algorithm of checking for pending thread in mem_slab.
Check for pending thread now is done only if there is
no memory left.

Signed-off-by: Kamil Lazowski <Kamil.Lazowski@nordicsemi.no>
2020-12-07 11:36:48 +01:00
Flavio Ceolin 9a16097fd8 kernel: sched: Change variable name in z_tick_sleep
Change a variable name to avoid confusion between time and ticks.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-12-04 23:05:57 -05:00
Flavio Ceolin 7a815d5d99 kernel: sched: Use k_ticks_t in z_tick_sleep
z_tick_sleep was using int32_t what could cause a possible overflow
when converting from k_ticks_t.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-12-04 23:05:57 -05:00
Katsuhiro Suzuki 8453a73ede kernel: init: activate FPU for main thread
This patch activates FPU feature for main thread if FPU related
configs (FPU, FPU_SHARING) are enabled.

Signed-off-by: Katsuhiro Suzuki <katsuhiro@katsuster.net>
2020-12-04 23:05:08 -05:00
Andrew Boie 3f7ae0d749 x86: increase default idle stack size
With MMU features enabled, we are using 248 out of 256
available bytes on 32-bit. This is extremely uncomfortable, relax
to a larger value like several other arches.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-12-03 17:33:39 -05:00
Trond Einar Snekvik 7986f94275 kernel: Add K_DELAYED_WORK_DEFINE
Adds a K_DELAYED_WORK_DEFINE, matching the K_WORK_DEFINE macro, with
accompanying Z_DELAYED_WORK_INITIALIZER macro.

Makes k_delayed_work_init a static inline function, like its K_WORK
counterpart.

Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
2020-11-27 20:08:30 -05:00
Anas Nashif 4b59312a94 kernel: init: move banner handling
Move banner and boot delay handling out of init.c
The code for banner was all over the place in init.c making it
unreadable.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-11-27 20:08:14 -05:00
Anas Nashif de69edbf42 kernel: move xip code to dedicated file
No functional changes, just moving the XIP code out and build it only
when XIP is enabled.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-11-27 20:08:14 -05:00
Krzysztof Chruscinski 3ed8083dc1 kernel: Cleanup logger setup in kernel files
Most of kernel files where declaring os module without providing
log level. Because of that default log level was used instead of
CONFIG_KERNEL_LOG_LEVEL.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2020-11-27 09:56:34 -05:00
Kamil Lazowski 104f100749 kernel: memslab: Add maximum mem_slab utilization trace
Add new function to mem_slab API that enables user
to get maximum number of slabs used so far.

Signed-off-by: Kamil Lazowski <Kamil.Lazowski@nordicsemi.no>
2020-11-18 22:33:27 -05:00
Carlo Caione a7d94b003e aarch64: Use absolute symbols for the callee saved registers
Use GEN_OFFSET_SYM macro to genarate absolute symbols for the
_callee_saved struct and use these new symbols in the assembly code.

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2020-11-17 18:59:23 -05:00
Daniel Leung fd7a68dbe9 kernel: use timing functions to gather thread runtime stats
This uses the timing functions to gather execution cycles of
threads. This provides greater details if arch/SoC/board
uses timer with higher resolution.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-11-11 23:55:49 -05:00
Daniel Leung 11e6b43090 tracing: roll thread switch in/out into thread stats functions
Since the tracing of thread being switched in/out has the same
instrumentation points, we can roll the tracing function calls
into the one for thread stats gathering functions.
This avoids duplicating code to call another function.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-11-11 23:55:49 -05:00
Daniel Leung fc577c4bd1 kernel: gather basic thread runtime statistics
This adds the bits to gather the first thread runtime statictic:
thread execution time. It provides a rough idea of how much time
a thread is spent in active execution. Currently it is not being
used, pending following commits where it combines with the trace
points on context switch as they instrument the same locations.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-11-11 23:55:49 -05:00
Spoorthy Priya Yerabolu e9ef078a11 kernel: kconfig: changing recommendations for SYS_CLOCK_TICKS_PER_SEC
Documentation for kconfig SYS_CLOCK_TICKS_PER_SEC has some outdated
recommendations. Changing them to align with other documentation
under kernel timing.

Fixes: #25482

Signed-off-by: Spoorthy Priya Yerabolu <spoorthy.priya.yerabolu@intel.com>
2020-11-11 23:55:10 -05:00
Andy Ross 202adf565f kernel: Rename struct _poller
This legacy struct still had a non-standard name.  Clean it up to
conform to currrent naming guidelines.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-11-11 10:59:52 -05:00
Andy Ross dadc6643e4 kernel/poll: Move "_poller" into thread struct, fix COHERENCE collision
Fix the issue where the kernel poll code would place the tracking
struct on the caller stack and share it with other threads, thus
creating a cache coherence issue on systems where KERNEL_COHERENCE is
enabled.

This works by eliminating the thread backpointer in struct _poller and
simply placing the (now just two-byte!) struct directly into the
thread struct.

Note that this doesn't attempt to fix the API paradigm that the
natural way to structure a call to k_poll() is to use an array of
k_poll_events on the CALLER's stack.  So it's likely that most
"typical" k_poll code is still going to have problems with
KERNEL_COHERENCE.  But at least now the kernel internals aren't
fundamentally broken.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-11-11 10:59:52 -05:00
Andy Ross 310f60f5b6 kernel/poll: Store the work queue in the triggered work poll items
The poll code was playing this weird trick where the thread pointer in
the "struct _poller" object for a triggered work item.  It would not
be a thread to wake up, but instead a pointer to the (non-polling)
thread operated by the work queue being triggered.  The code would
never touch this thread, just use it as a way to get a pointer to the
enclosing work queue struct.

Just store the work queue pointer in the first place.  It's much
simpler, and makes future modifications to remove that thread pointer
possible.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-11-11 10:59:52 -05:00
Andy Ross 6c82745cb3 kernel/poll: Use a separate thread backpointer for triggered work
The triggered work scheme uses a trick where it overloads the thread
pointer field of the struct poller (which normally stores the ID of
the thread that is blocked in k_poll()) to be able to find the work
queue to which it will submit.

Give it its own pointer field to break this false dependency.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-11-11 10:59:52 -05:00
Andy Ross 0c7af40d61 kernel/poll: Make the poll callback a single-byte enum instead
Somewhat weirdly, k_poll() can do one of two things when the set of
events is signaled: it can wake up a sleeping thread, or it can submit
an unrelated work item to a work queue.  The difference in behaviors
is currently captured by a callback, but as there are only two it's
cleaner to put this into a "mode" enumerant.  That also shrinks the
size of the data such that the poller struct can be moved somewhere
other than the calling stack.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-11-11 10:59:52 -05:00
Andrew Boie ea6e4ad098 kernel: support non-identity RAM mapping
Some platforms may have multiple RAM regions which are
dis-continuous in the physical memory map. We really want
these to be in a continuous virtual region, and we need to
stop assuming that there is just one SRAM region that is
identity-mapped.

We no longer use CONFIG_SRAM_BASE_ADDRESS and CONFIG_SRAM_SIZE
as the bounds of kernel RAM, and no longer assume in the core
kernel that these are identity mapped at boot.

Two new Kconfigs, CONFIG_KERNEL_VM_BASE and
CONFIG_KERNEL_RAM_SIZE now indicate the bounds of this region
in virtual memory.

We are currently only memory-mapping physical device driver
MMIO regions so we do not need virtual-to-physical calculations
to re-map RAM yet. When the time comes an architecture interface
will be defined for this.

Platforms which just have one RAM region may continue to
identity-map it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-11-09 20:19:13 -05:00
Trond Einar Snekvik 86c793af3f sys: util: Replace MIN(MAX(a, b), c) with CLAMP
Replaces all existing variants of value clamping with the MIN and MAX
macros with the CLAMP macro.

Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
2020-11-05 12:12:17 +01:00
Maximilian Bachmann b3c5fe6720 kernel: return error instead of misaligned k_thread object
k_object_alloc(K_OBJ_THREAD) returns a usable struct k_thread pointer.
This pointer is 4 byte aligned. On x86 and x86_64 struct _thread_arch
has a member which requires alignment. Since this is currently not
supported k_object_alloc(K_OBJ_THREAD) now returns an error instead of
a misaligned pointer.

Signed-off-by: Maximilian Bachmann <m.bachmann@acontis.com>
2020-11-04 14:03:43 -08:00
Daniel Leung 2d152ab019 kernel: limit thread local storage to Zephyr SDK
Toolchains other than Zephyr SDK may not support generating
code with thread local storage. So limit TLS to Zephyr SDK
for now, and only enable TLS on other toolchains as needed.

Fixes #29541

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-10-30 15:59:06 +01:00
iva kik 687f799b7f kernel/queue: fix queue append/get race
k_queue_append and k_queue_alloc_append are in a race
    condition.

    Scenario:
    Using either of the above mentioned functions from a
    preemptive context, can lead to the element being
    appended to the queue to be lost. The element loss happens
    when the k_queue_append is interrupted at a critical point,
    when the list only contains one element and k_queue_get is
    called, before the k_queue_append is allowed to complete.

    Fix:
    Move sys_sflist_peek_tail inside queue_insert(). Add additional
    bool paramenter to queue_insert(), to indicate append/prepend
    operation.
    Fixes #29257

Signed-off-by: iva kik <megatheriumiva@gmail.com>
2020-10-28 17:01:41 +01:00
Andrew Boie 0e30c6a0fa kernel: wipe TLS when dropping to user mode
For threads that run in supervisor mode for some time before
synchronously dropping to user mode, re-initialize the TLS
area to prevent leakage of potentially sensitive information.

We did this already for CONFIG_THREAD_USERSPACE_LOCAL_DATA
but not the new CONFIG_THREAD_LOCAL_STORAGE.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-26 13:06:16 +01:00
Daniel Leung 62cf1960ad kernel: support using thread local storage for errno
This enables storing errno in the thread local storage area.
With this enabled, a syscall to access errno can be avoided
when userspace is also enabled.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-10-24 10:52:00 -07:00
Daniel Leung 388725870f arm: cortex_m: add support for thread local storage
Adds the necessary bits to initialize TLS in the stack
area and sets up CPU registers during context switch.

Note that since Cortex-M does not have the thread ID or
process ID register needed to store TLS pointer at runtime
for toolchain to access thread data, a global variable is
used instead.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-10-24 10:52:00 -07:00
Daniel Leung 02b20351cd kernel: add common bits to support TLS
This adds the common struct fields and functions to support
the implementation of thread local storage in individual
architecture. This uses the thread stack to store TLS data.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-10-24 10:52:00 -07:00
Daniel Leung 240beb42af kconfig: add configs for thread local storage
Add kconfigs to indicate whether an architecture has support
for thread local storage (TLS), and to enable TLS in kernel.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-10-24 10:52:00 -07:00
Andrew Boie ad110d495e kernel: fatal: check if _current is NULL
Arches which have custom swap to main can have _current be
NULL very, very early in the boot process. Check this to
avoid an infinite loop of fatal errors.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-24 12:54:32 -04:00
Andrew Boie f5c3fc498b kernel: add arch_mem_unmap() interface
The core kernel does not use this yet, but it will be later used
as part of infrastructure for memory-mapping stacks, as detailed
in #28899.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-23 22:02:47 -04:00
Carlo Caione 47c592cd32 mmu: Fix mapping_pos calculation
In the MMU code mapping_pos is miscalculated when for example
SRAM_BASE_ADDRESS==0x40000000 and KERNEL_VM_SIZE==0xc0000000 getting a
mapping_pos of 0x0.

The problem is that we must cast the two values to uintptr_t before
casting the result to avoid the rollover to 0.

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2020-10-23 16:24:04 -04:00
Andrew Boie 933b420235 kernel: add context pointer to thread->fn_abort
For compatibility layers like CMSIS where thread objects
are drawn from a pool, provide a context pointer to the
exited thread object so it may be freed.

This is somewhat obscure and has no supporting APIs or
overview documentation and should be considered a private
kernel feature. Applications should really be using
k_thread_join() instead.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-22 23:32:37 -04:00
Andrew Boie fa6db61eb2 userspace: do nothing if added to same domain
If we call k_mem_domain_add_thread() to a memory domain
the thread already belongs to, do nothing.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-22 16:47:07 -07:00
Anas Nashif d2c71796af kernel: document k_sleep with K_FOREVER
When calling k_sleep with K_FOREVER as the timeout value, we consider
this as a suspend call.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-10-22 07:00:15 -04:00
Anas Nashif 081605ee23 kernel: do not queue a thread that is already queued
Do not add a thread to the run queue if it was already added.

Fixes #29244

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-10-22 07:00:15 -04:00
Anas Nashif bf69afcdae kernel: only resume suspended threads
Do not try to resume a thread that was not suspended.

Fixes #28694

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-10-22 07:00:15 -04:00
Andrew Boie 52bf482471 userspace: fix k_mem_domain_init()
The synchronous arch hook wasn't being invoked when
k_mem_domain_init() was called with a partition list.
This could result with regions not being programmed in
the page tables as expected.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-21 10:20:49 -07:00
Carlo Caione f161223637 userspace: Fix thread index type in z_thread_perms_all_clear()
The type for the thread index returned by thread_index_get() must be
casted to int when comparing with (-1). Directly using uintptr_t is
breaking the ARMv8 implementation where where the check (index != -1) is
verified also when no thread index is returned.

Signed-off-by: Carlo Caione <ccaione@baylibre.com>
2020-10-21 08:00:35 -04:00
Andy Ross a8d5437799 soc/xtensa: Misc. checkpatch fixups
Code style fixes.  Kept separate from the original changes to permit
easier rebasing.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-10-21 06:38:53 -04:00
Andy Ross 4a8b3d194c kernel/poll: Mark incompatibility with KERNEL_COHERENCE
The k_poll implementation places a struct _poller on the stack and
shares it with other threads, which is incompatible with the
KERNEL_COHERENCE model of cached stacks.

Make this a hard build failure instead of a kconfig dependency for
clarity.  The failures if a user actually enables both are subtle and
difficult to debug.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-10-21 06:38:53 -04:00
Andy Ross f6d32ab0a4 kernel: Add cache coherence management framework
Zephyr SMP kernels need to be able to run on architectures with
incoherent caches.  Naive implementation of synchronization on such
architectures requires extensive cache flushing (e.g. flush+invalidate
everything on every spin lock operation, flush on every unlock!) and
is a performance problem.

Instead, many of these systems will have access to separate "coherent"
(usually uncached) and "incoherent" regions of memory.  Where this is
available, place all writable data sections by default into the
coherent region.  An "__incoherent" attribute flag is defined for data
regions that are known to be CPU-local and which should use the cache.
By default, this is used for stack memory.

Stack memory will be incoherent by default, as by definition it is
local to its current thread.  This requires special cache management
on context switch, so an arch API has been added for that.

Also, when enabled, add assertions to strategic places to ensure that
shared kernel data is indeed coherent.  We check thread objects, the
_kernel struct, waitq's, timeouts and spinlocks.  In practice almost
all kernel synchronization is built on top of these structures, and
any shared data structs will contain at least one of them.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-10-21 06:38:53 -04:00
Andrew Boie 348a0fda62 userspace: make mem domain lock non-static
Strictly speaking, any access to a mem domain or its
containing partitions should be serialized on this lock.

Architecture code may need to grab this lock if it is
using this data during, for example, context switches,
especially if they support SMP as locking interrupts
is not enough.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-20 09:37:49 -07:00
Andrew Boie 9f87deafd2 userspace: fix k_mem_domain_destroy()
This deprecated API won't be removed for one more release,
ensure it doesn't put the kernel into a bad state as it
currently sets all the member thread domain assignment to
NULL which is not what we want.

Have it reassign all member threads to the default domain.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-20 09:37:49 -07:00
Andrew Boie b5a71f74a8 userspace: remove threads from domain on abort
When threads exited we were leaving dangling references to
them in the domain's mem_domain_q.

z_thread_single_abort() now calls into the memory domain
code via z_mem_domain_exit_thread() to take it off.

The thread setup code now invokes z_mem_domain_init_thread(),
avoiding extra checks in k_mem_domain_add_thread(), we know
the object isn't currently a member of a doamin.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-10-20 09:37:49 -07:00
David Komel 211e5b73c0 kernel: k_busy_wait() should return immediately on zero timeout
When CONFIG_ARCH_HAS_CUSTOM_BUSY_WAIT is not defined, cycles_to_wait
is calculated using a division operation. This calculation could take a
significant amount of time (a few microseconds on some architectures,
depending on the system clock).
In the special case of zero usec_to_wait, the function should return
immediately rather than spend time on calculations.
For example, in spi driver (spi_context.h, _spi_context_cs_control()),
k_busy_wait() can be called with zero delay. This can increase spi
transaction time significantly.
Another improvement, is moving the start_cycles initialization
before cycles_to_wait calculation, so the time it takes to calculate
cycles_to_wait will be taken into account.

Signed-off-by: David Komel <a8961713@gmail.com>
2020-10-14 14:52:06 -04:00
Peter Bigot 923caadf3b kernel: delayed_work: update k_delayed_work_cancel documentation
Although the documentation states that only work items that have not
completed the delay can be cancelled, in fact pending items can also
be removed from a work queue.  Document that behavior

Also document the specific return value that will be obtained based on
the state of the work item at the time cancellation was attempted
using the current implementation.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-10-09 11:48:00 +02:00
Peter Bigot f69f935865 kernel: delayed_work: fix race condition in k_delayed_work_cancel
The implementation checks the work queue pointer before taking a lock
and entering code that, depending on build options, may fault if that
pointer is null.  Move the check under the lock to ensure condition is
preserved.  Then the check in work_cancel is no longer necessary since
condition is verified under lock at all call sites.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-10-09 11:48:00 +02:00
Jennifer Williams 4d33007486 kernel: stack: fix stack_push spinlock and return
The z_impl_k_stack_push() has a spinlock that is set after
stack member access, which could cause race conditions and
used multiple return statements. This commit
- moves the lock before the CHECKIF
- implements goto for flow of lock, reschedule, and unlock
- uses ret for single return at the end

Signed-off-by: Jennifer Williams <jennifer.m.williams@intel.com>
2020-10-07 17:10:36 -04:00
Peter A. Bigot f1b86caff3 kernel: timer: update k_timer API for const correctness
API that takes k_timer structures but doesn't change data in them is
updated to const-qualify the underlying object, allowing information
to be retrieved from contexts where the containing object is
immutable.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2020-10-02 11:29:14 +02:00
Peter A. Bigot 16a4081520 kernel: timer: update _timeout API for const correctness
API that takes _timeout structures but doesn't change data in them is
updated to const-qualify the underlying object, allowing information
to be retrieved from contexts where the containing object is
immutable.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2020-10-02 11:29:14 +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
Andrew Boie e0ca403f4c kernel: add assert for mis-used k_thread_create()
k_thread_create() works as expected on both uninitialized memory,
or threads that have completely exited.

However, horrible and difficult to comprehend things can happen if a
thread object is already being used by the kernel and
k_thread_create() is called on it.

Historically this has been a problem with test cases trying to be
parsimonious with thread objects and not properly cleaning up
after themselves. Add an assertion for this which should catch
both the illegal creation of a thread already active, or threads
racing to create the same thread object.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-30 14:11:59 -04:00
Andrew Boie f5a7e1a108 kernel: handle thread self-aborts on idle thread
Fixes races where threads on another CPU are joining the
exiting thread, since it could still be running when
the joiners wake up on a different CPU.

Fixes problems where the thread object is still being
used by the kernel when the fn_abort() function is called,
preventing the thread object from being recycled or
freed back to a slab pool.

Fixes a race where a thread is aborted from one CPU while
it self-aborts on another CPU, that was currently worked
around with a busy-wait.

Precedent for doing this comes from FreeRTOS, which also
performs final thread cleanup in the idle thread.

Some logic in z_thread_single_abort() rearranged such that
when we release sched_spinlock, the thread object pointer
is never dereferenced by the kernel again; join waiters
or fn_abort() logic may free it immediately.

An assertion added to z_thread_single_abort() to ensure
it never gets called with thread == _current outside of an ISR.

Some logic has been added to ensure z_thread_single_abort()
tasks don't run more than once.

Fixes: #26486
Related to: #23063 #23062

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-30 14:11:59 -04:00
Carles Cufi 28cb9dab64 kernel: Deprecate CONFIG_MULTITHREADING
Deprecate the Kconfig option for the time being. Unless a contributor
volunteers to take over the work to maintain the option, it will be
removed after 2 releases.

Relates to #27415.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-09-23 15:50:32 -05:00
Lauren Murphy f29a2d1ccc doc: Clarify semantics of k_msgq_put
Amend Doxygen documentation for k_msgq_put to note that the message
content will not be modified as a result of the function call and
constify data parameter in function prototype.

Fixes #22301

Signed-off-by: Lauren Murphy <lauren.murphy@intel.com>
2020-09-23 13:21:07 -05:00
Daniel Leung b5c2ff9397 kernel: add kconfig CONFIG_KERNEL_MEM_POOL
Adds a kconfig CONFIG_KERNEL_MEM_POOL to decide whether
kernel memory pool related code is compiled. This option
can be disabled to shrink code size. If k_heap is not
being used at all, kheap.c will also not be compiled,
resulting in further smaller code size.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-09-19 05:49:13 -04:00
Peter Bigot 332b7df61b kernel: avoid implementation-defined behavior in timeout calculation
When to->dticks is an int64_t it may happen that the calculated
remaining time is a value that cannot be exactly represented in the
destination int32_t, producing an implementation-defined result which
can include a signal (interrupt).  Cap the maximum delay to the
largest value suported by the int32_t result.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-09-17 22:19:35 -04:00
Watson Zeng 37f75d2d1f kernel: sched: bug fix for trace and monitor
sys_trace_thread_abort and z_thread_monitor_exit in
z_thread_single_abort also need to be protected by
sched_spinlock, otherwise when after the spinlock
release, if there is an pending interrupt, it will cause an
sched in the interrrupt exit, and those trace and monitor
function will never reach.

Signed-off-by: Watson Zeng <zhiwei@synopsys.com>
2020-09-17 09:30:22 +02:00
Andrew Boie a8775ab8cb sched: don't use local lock in z_tick_sleep()
We're modifying thread_state. Use sched_spinlock instead.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-16 13:11:12 -05:00
Andrew Boie 8e0f6a5936 sched: hold spinlock in z_time_slice()
We are checking thread->base members like thread_state and prio
and making decisions based on it, hold the sched_spinlock to
avoid potential concurrency problems if these members are modified
on another CPU or nested interrupt.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-16 13:11:12 -05:00
Andrew Boie 83d7770de4 sched: check if runnable in sliceable()
We need to check if a thread is runnable at all before we
contemplate putting it on the end of the priority queue,
it might not be on the queue at all if it was suspended.

Replaces the less comprehensive check to see if the thread
was pending a timeout.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-16 13:11:12 -05:00
Andrew Boie ffc5bdffbb sched: hold spinlock in z_thread_timeout()
We are checking and modifying members of thread->base
(in particular it's waitq and thread_state) which are
nominally protected by sched_spinlock. Hold it while
doing this to avoid concurrent changes on another CPU
or ISR preeemption.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-16 13:11:12 -05:00
Peter Bigot 1a7cd6ddbd kernel: device: invert sense of ready bit
The device status ready bit replaced the previous hack of clearing the
device API pointer when initialization of the device failed.  It
inadvertently changed the behavior of device_get_binding() when
invoked before the device was initialized: previously that succeeded
for uninitialized devices, after the change it failed.

Multiple driver initializations rely on being able to get a device
pointer for something they're going to depend on in their init
function, even if that device has not yet been initialized.  Although
this is wrong, and would cause faults if the device failed to
initialize before use, in practice it has been working.

It's not feasible to identify all the situations where this has
occurred, nor to add code to diagnose such cases without changing the
state associated with a device to distinguish initialized from
initialization success/failure.  Restore the previous behavior until a
more holistic solution is developed.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-09-15 18:22:38 +02:00
Anas Nashif 6e27478c3d benchmarking: remove execution benchmarking code
This code had one purpose only, feed timing information into a test and
was not used by anything else. The custom trace points unfortunatly were
not accurate and this test was delivering informatin that conflicted
with other tests we have due to placement of such trace points in the
architecture and kernel code.

For such measurements we are planning to use the tracing functionality
in a special mode that would be used for metrics without polluting the
architecture and kernel code with additional tracing and timing code.

Furthermore, much of the assembly code used had issues.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-09-05 13:28:38 -05:00
Daniel Leung 0ffcfa9633 timing: introduce timing functions as a generic feature
Add timing functions and APIs.  This is now used with some of the tests
we have for performance and metrics and will be used whereever timing
informations are needed, for example for tracing, profiling and other
operations where timing info is critical.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-09-05 13:28:38 -05:00
Watson Zeng 1dddbecb35 tracing: swap: bug fix and enhancement for ARC
* Move switched_in into the arch context switch assembly code,
  which will correctly record the switched_in information.

* Add switched_in/switched_out for context switch in irq exit.

Signed-off-by: Watson Zeng <zhiwei@synopsys.com>
2020-09-03 21:54:15 +02:00
Andrew Boie 5e0b55c30e kernel: demote k_mem_map to z_mem_map
Memory mapping, for now, will be a private kernel API
and is not intended to be application-facing at this time.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-03 14:24:38 -04:00
Andrew Boie 7d32e9f9a5 mmu: support only identity RAM mapping
We no longer plan to support a split address space with
the kernel in high memory and per-process address spaces.
Because of this, we can simplify some things. System RAM
is now always identity mapped at boot.

We no longer require any virtual-to-physical translation
for page tables, and can remove the dual-mapping logic
from the page table generation script since we won't need
to transition the instruction point off of physical
addresses.

CONFIG_KERNEL_VM_BASE and CONFIG_KERNEL_VM_LIMIT
have been removed. The kernel's address space always
starts at CONFIG_SRAM_BASE_ADDRESS, of a fixed size
specified by CONFIG_KERNEL_VM_SIZE.

Driver MMIOs and other uses of k_mem_map() are still
virtually mapped, and the later introduction of demand
paging will result in only a subset of system RAM being
a fixed identity mapping instead of all of it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-03 14:24:38 -04:00
Flavio Ceolin 5408f3102d debug: x86: Add gdbstub for X86
It implements gdb remote protocol to talk with a host gdb during the
debug session. The implementation is divided in three layers:

1 - The top layer that is responsible for the gdb remote protocol.
2 - An architecture specific layer responsible to write/read registers,
    set breakpoints, handle exceptions, ...
3 - A transport layer to be used to communicate with the host

The communication with GDB in the host is synchronous and the systems
stops execution waiting for instructions and return its execution after
a "continue" or "step" command. The protocol has an exception that is
when the host sends a packet to cause an interruption, usually triggered
by a Ctrl-C. This implementation ignores this instruction though.

This initial work supports only X86 using uart as backend.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-09-02 20:54:57 -04:00
Andrew Boie ffc1da08f9 kernel: add z_thread_single_abort to private hdr
We shouldn't be copy-pasting extern declarations like this.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-02 15:02:06 -07:00
Andrew Boie 3425c32328 kernel: move stuff into z_thread_single_abort()
The same code was being copypasted in k_thread_abort()
implementations, just move into z_thread_single_abort().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-09-02 15:02:06 -07:00
Tomasz Bursztyka ae5a761f85 kernel: Apply IRQ offload API change
Switching to constant parameter.

Fixes #27399

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-09-02 13:48:13 +02:00
Tomasz Bursztyka e18fcbba5a device: Const-ify all device driver instance pointers
Now that device_api attribute is unmodified at runtime, as well as all
the other attributes, it is possible to switch all device driver
instance to be constant.

A coccinelle rule is used for this:

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

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

Fixes #27399

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-09-02 13:48:13 +02:00
Peter Bigot 2fcf76219e userspace: update k_object API to support immutable objects
The k_object API associates mutable state structures with known kernel
objects to support userspace.  The kernel objects themselves are not
modified by the API, and in some cases (e.g. device structures) may be
const-qualified.  Update the API so that pointers to these const
kernel objects can be passed without casting away the const qualifier.

Fixes #27399

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-09-02 13:48:13 +02:00
Tomasz Bursztyka aac9e2c5e3 device: Revise how initialization status is being handled
In order to make all device instances constant, driver_api pointer is
not set to NULL anymore if initialization failed.

Instead, have a bitfield dedicated to it.

Fixes #27399

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-09-02 13:48:13 +02:00
Spoorthy Priya Yerabolu 9247e8bc44 code-guideline: Tag name should be a unique identifier
Following are the changes to variable names that are matching
with tag names (Rule 5.7 violations)

In kernel.h, event_type is matching with a tag name in
lib/os/onoff.c. Added a _ prefix to event_type and
also to the macro argument names.

In userspace.c, *dyn_obj is matching with the tag name
dyn_obj in the file itslef. Changed it to dyn

In device.h, device_mmio.h, init.h and init.c,
changed the *device to dev. Except for one change in
init.h

Signed-off-by: Spoorthy Priya Yerabolu <spoorthy.priya.yerabolu@intel.com>
2020-09-01 08:03:23 -04:00
Andrew Boie 00f71b0d63 kernel: add CONFIG_ARCH_MEM_DOMAIN_SYNCHRONOUS_API
Saves us a few bytes of program text on arches that don't need
these implemented, currently all uniprocessor MPU-based systems.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-26 20:35:02 -04:00
Andrew Boie d11e3c3456 userspace: add debug logs to mem domain code
Useful when debugging stuff.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-26 20:35:02 -04:00
Andrew Boie 9bfc8d82d0 userspace: introduce default memory domain
We make a policy change here: all threads are members of a
memory domain, never NULL. We introduce a default memory domain
for threads that haven't been assigned to or inherited another one.

Primary motivation for this change is better MMU support, as
one common configuration will be to maintain page tables at
the memory domain level.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-26 20:35:02 -04:00
Andrew Boie e433494f40 kernel: mmu: implement virtual mappings
These will grow downward from CONFIG_KERNEL_VM_LIMIT.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-25 15:49:59 -04:00
Daniel Leung 49206a86ff debug/coredump: add a primitive coredump mechanism
This adds a very primitive coredump mechanism under subsys/debug
where during fatal error, register and memory content can be
dumped to coredump backend. One such backend utilizing log
module for output is included. Once the coredump log is converted
to a binary file, it can be used with the ELF output file as
inputs to an overly simplified implementation of a GDB server.
This GDB server can be attached via the target remote command of
GDB and will be serving register and memory content. This allows
using GDB to examine stack and memory where the fatal error
occurred.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-08-24 20:28:24 -04:00
Anas Nashif 390537bf68 tracing: trace mutex/semaphore using dedicated calls
Instead of using generic trace calls, use dedicated functions for
tracing sempahores and mutexes.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-08-24 13:21:12 +02:00
Anas Nashif d1049dc258 tracing: swap: cleanup trace points and their location
Move tracing switched_in and switched_out to the architecture code and
remove duplications. This changes swap tracing for x86, xtensa.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-08-24 13:21:12 +02:00
Anas Nashif 5c31d00a6a tracing: trace k_sleep
Trace when k_sleep is called.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-08-24 13:21:12 +02:00
Anas Nashif 3b75a08e3f Kconfig: move power management Kconfig into subsys/power
Consolidate all PM related Kconfigs in one place.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-08-24 10:24:30 +02:00
Andrew Boie 72792a5e63 userspace: cleanup mem domain assertions
The memory domain APIs document that overlapping regions are
not allowed, check for this unconditionally.

Cleanup assertion error messages. Use __ASSERT_NO_MSG for
blindingly obvious NULL checks.

We now have a `check_add_partition()` function to perform
all the necessary sanity checks on adding a partition to a
domain. This returns true or false, which will help later
when we implement #24609

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-20 13:58:54 -04:00
Andrew Boie bc35b0b780 userspace: add optional member to memory domains
Some systems may need to associate arch-specific data to
a memory domain. Add a Kconfig and `arch` field for this,
and a new arch API to initialize it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-20 13:58:54 -04:00
Andrew Boie 282cd932c8 kernel: don't reschedule thread abort in ISR
Zephyr has a policy of invoking the scheduler on the way
out of IRQs anyway for all arches, this is unnecessary.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-08-18 08:36:35 +02:00
David Leach 1ab90044f2 kernel/timeout: Fix coverity warning CID 211045
The dticks field was changed from a signed to an unsigned
value so now the assert test to ensure it isn't negative
is no longer needed.

fixes #26355

Signed-off-by: David Leach <david.leach@nxp.com>
2020-08-16 09:29:41 -04:00
Anas Nashif 379b93f0d3 kernel: do not call swap if next ready thread is current thread
Check if next ready thread is same as current thread before calling
z_swap.
This avoids calling swap to just go back to the original thread.

Original code: thread 0x20000118 switches out and then in again...

>> 0x20000118 gives semaphore(signal): 0x20000104 (count: 0)
>> thread ready: 0x20000118
>> 0x20000118 switched out
>> 0x20000118 switched in
>> end call to k_sem_give
>> 0x20000118 takes semaphore(wait): 0x200000f4 (count: 0)
>> thread pend: 0x20000118
>> 0x20000118 switched out
>> 0x200001d0 switched in

with this patch:

>> 0x200001d0 gives semaphore(signal): 0x200000f4 (count: 0)
>> thread ready: 0x200001d0
>> end call to k_sem_give
>> 0x200001d0 takes semaphore(wait): 0x20000104 (count: 0)
>> thread pend: 0x200001d0
>> 0x200001d0 switched out
>> 0x20000118 switched in
>> end call to k_sem_take

The above is output from tracing with a custom format used for
debugging.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-08-12 15:32:29 -04:00
Tomasz Bursztyka 98d9b01322 device: Apply driver_api/data attributes rename everywhere
Via coccinelle:

@r_device_driver_api_and_data_1@
struct device *D;
@@
(
D->
-	driver_api
+	api
|
D->
-	driver_data
+	data
)

@r_device_driver_api_and_data_2@
expression E;
@@
(
net_if_get_device(E)->
-	driver_api
+	api
|
net_if_get_device(E)->
-	driver_data
+	data
)

And grep/sed rules for macros:

git grep -rlz 'dev)->driver_data' |
	xargs -0 sed -i 's/dev)->driver_data/dev)->data/g'

git grep -rlz 'dev->driver_data' |
	xargs -0 sed -i 's/dev->driver_data/dev->data/g'

git grep -rlz 'device->driver_data' |
	xargs -0 sed -i 's/device->driver_data/device->data/g'

Fixes #27397

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-08-11 19:30:53 +02:00
Ioannis Glaropoulos 60bd51aa37 kernel: init: allow custom switch to main for no-multithreading case
Certain architectures, such as ARM Cortex-M require a custom
switch to main(), in case the case we build Zephyr without
support for multithreading (CONFIG_MULTITHREADING=n). So as
to keep the change to kernel/init.c as unintrusive as
possible, we install an ARCH-specific hook in z_cstart(),
which gets called for architectures that require this
customized switch to main() function.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2020-08-07 13:06:04 +02:00
Torsten Rasmussen bb3946666f cmake: fix include directories to work with out-of-tree arch
Include directories for ${ARCH} is not specified correctly.
Several places in Zephyr, the include directories are specified as:
${ZEPHYR_BASE}/arch/${ARCH}/include
the correct line is:
${ARCH_DIR}/${ARCH}/include
to correctly support out of tree archs.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
2020-08-05 08:06:07 -04:00
Aastha Grover 2d9b459f15 syscalls: Add system call for cache flush & invalidate
include/cache.h: System calls declaration and implementation
kernel/cache_handlers.c: Defination of verification functions

Signed-off-by: Aastha Grover <aastha.grover@intel.com>
2020-08-04 17:26:45 -04:00
Joakim Andersson ea9590448d kernel: Add k_delayed_work_pending to check if work has been submitted
Add k_delayed_work_pending similar to k_work_pending to check if the
delayed work item has been submitted but not yet completed.
This would compliment the API since using k_work_pending or
k_delayed_work_remaining_get is not enough to check this condition.
This is because the timeout could have run out, but the timeout handler
not yet processed and put the work into the workqueue.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2020-08-04 17:32:56 +02:00
Carles Cufi 244f826e3c cmake: remove _if_kconfig() functions
This set of functions seem to be there just because of historical
reasons, stemming from Kbuild. They are non-obvious and prone to errors,
so remove them in favor of the `_ifdef()` ones with an explicit
`CONFIG_` condition.

Script used:

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

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-08-01 12:35:20 +02:00
Andrew Boie b4ce7a77c6 kernel: sys_workq thread stack is kernel-only
The system workqueue is a kernel thread that doesn't run
in user mode.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie 0c297461c5 kernel: idle thread stacks are kernel-only
The idle thread(s) always run in supervisor mode.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie 8b4b0d6264 kernel: z_interrupt_stacks are now kernel stacks
This will save memory on many platforms that enable
user mode.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie 8ce260d8df kernel: introduce supervisor-only stacks
These stacks are appropriate for threads that run purely in
supervisor mode, and also as stacks for interrupt and exception
handling.

Two new arch defines are introduced:

- ARCH_KERNEL_STACK_GUARD_SIZE
- ARCH_KERNEL_STACK_OBJ_ALIGN

New public declaration macros:

- K_KERNEL_STACK_RESERVED
- K_KERNEL_STACK_EXTERN
- K_KERNEL_STACK_DEFINE
- K_KERNEL_STACK_ARRAY_DEFINE
- K_KERNEL_STACK_MEMBER
- K_KERNEL_STACK_SIZEOF

If user mode is not enabled, K_KERNEL_STACK_* and K_THREAD_STACK_*
are equivalent.

Separately generated privilege elevation stacks are now declared
like kernel stacks, removing the need for K_PRIVILEGE_STACK_ALIGN.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie e4cc84a537 kernel: update arch_switch_to_main_thread()
This now takes a stack pointer as an argument with TLS
and random offsets accounted for properly.

Based on #24467 authored by Flavio Ceolin.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie b0c155f3ca kernel: overhaul stack specification
The core kernel computes the initial stack pointer
for a thread, properly aligning it and subtracting out
any random offsets or thread-local storage areas.
arch_new_thread() no longer needs to make any calculations,
an initial stack frame may be placed at the bounds of
the new 'stack_ptr' parameter passed in. This parameter
replaces 'stack_size'.

thread->stack_info is now set before arch_new_thread()
is invoked, z_new_thread_init() has been removed.
The values populated may need to be adjusted on arches
which carve-out MPU guard space from the actual stack
buffer.

thread->stack_info now has a new member 'delta' which
indicates any offset applied for TLS or random offset.
It's used so the calculations don't need to be repeated
if the thread later drops to user mode.

CONFIG_INIT_STACKS logic is now performed inside
z_setup_new_thread(), before arch_new_thread() is called.

thread->stack_info is now defined as the canonical
user-accessible area within the stack object, including
random offsets and TLS. It will never include any
carved-out memory for MPU guards and must be updated at
runtime if guards are removed.

Available stack space is now optimized. Some arches may
need to significantly round up the buffer size to account
for page-level granularity or MPU power-of-two requirements.
This space is now accounted for and used by virtue of
the Z_THREAD_STACK_SIZE_ADJUST() call in z_setup_new_thread.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie aa464052ff arch_interface: remove CamelCase
Naming cleanup of this interface declaration.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Andrew Boie 62eb7d99dc arch_interface: remove unnecessary params
arch_new_thread() passes along the thread priority and option
flags, but these are already initialized in thread->base and
can be accessed there if needed.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-30 21:11:14 -04:00
Daniel Leung ac53880cef kernel: smp: avoid identifier collisions
MISRA-C Rule 5.3 states that identifiers in inner scope should
not hide identifiers in outer scope.

In the function smp_init_top(), the variable "start_flags"
collide with global variable of the same name. So rename the one
inside the function.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-07-25 21:26:15 -04:00
Daniel Leung b907cf7694 kernel: 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 z_set_timeout_expiry(), the parameter "idle"
and an inner variable "next" collide with function named idle()
and next(). So rename those variables.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-07-25 21:26:15 -04:00
Daniel Leung 2acafafae1 kernel: pipes: rename inner spinlock keys
MISRA-C Rule 5.3 states that identifiers in inner scope should
not hide identifiers in outer scope. There are a few spinlock
keys simply named "key". So rename those in inner scope to avoid
shadowing the outer ones.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-07-25 21:26:15 -04:00
David Leach db36b146e1 kernel: Remove supported size comments from HEAP_MEM_POOL_SIZE
The mempool implementation doesn't require specific sizes and can
support arbitrary sizes up to the limit of available memory. The
Kconfig documentation on this configuration was confusing user.

Fixes #20418

Signed-off-by: David Leach <david.leach@nxp.com>
2020-07-24 10:19:47 +02:00
Andrew Boie 476fc405e7 kernel: mem_domain: centralize assertions
Later this year I hope to overhaul the memory domain APIs,
but at least for now let's at least consolidate these checks.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-20 15:32:16 +02:00
Andrew Boie 06cf6d27f7 kernel: add k_mem_map() and related defines
This will be the interface for mapping memory in the kernel's
part of the address space, which is guaranteed to be persistent
regardless of what thread is scheduled.

Further code for specifically managing virtual memory will end up in
kernel/mmu.c.

Further defintions for memory management in general will end up
in sys/mem_manage.h.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-17 11:38:18 +02:00
Andrew Boie 9ff148ac83 kernel: define arch_mem_map()
This is the low-level arch function to map a region into page
tables.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-07-17 11:38:18 +02:00
Anas Nashif 568211738d doc: replace lifo/fifo with LIFO/FIFO
Replace all occurances of lifo/fifo with LIFO/FIFO to be consistent.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-07-15 14:01:33 -04:00
Flavio Ceolin c4f7faea10 random: Include header where it is used
Unit tests were failing to build because random header was included by
kernel_includes.h. The problem is that rand32.h includes a generated
file that is either not generated or not included when building unit
tests. Also, it is better to limit the scope of this file to where it is
used.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-07-08 21:05:36 -04:00
Enjia Mai 7ac40aabc0 tests: adding test cases for arch-dependent SMP function
Add one another test case for testing both arch_curr_cpu() and
arch_sched_ipi() architecture layer interface.

Signed-off-by: Enjia Mai <enjiax.mai@intel.com>
2020-07-02 08:42:53 -04:00
Anas Nashif 8aa3dc340d kernel: cleanup header inclusion
Remove unused header inclusion in kernel code.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-06-25 16:12:36 -05:00
Anas Nashif 2c5d40437b kernel: logging: convert K_DEBUG to LOG_DBG
Move K_DEBUG to use LOG_DBG instead of plain printk.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-06-25 16:12:36 -05:00
Peter Bigot d8b86cba3c device: add API to check whether a device is ready to use
Currently this is useful only for some internal applications that
iterate over the device table, since applications can't get access to
a device that isn't ready, and devices can't be made unready.  So it's
introduced as internal API that may be exposed as device_ready() when
those conditions change.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-06-23 13:27:14 +02:00
Peter Bigot 219a3ca96d device: provide internal access to static device array
Device objects in Zephyr are currently placed into an array by linker
scripts, making it easy to iterate over all devices if the array
address and size can be obtained.  This has applications in device
power management, but the existing API for this was available only
when that feature was enabled.  It also uses a signed type to hold the
device count.

Provide a new API that is generally available, but marked as internal
since normally applications should not iterate over all devices.  Mark
the PM API approach deprecated.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-06-23 13:27:14 +02:00
Andrew Boie 4855eaa735 kernel: document arch_printk_char_out()
Used by very early console drivers.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-17 09:20:55 +02:00
Ioannis Glaropoulos 8ada29e06c kernel: userspace: fix variable initialization
Need to initialize tidx before using it, to
supress compiler warning.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2020-06-16 10:50:27 -05: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 be919d3bf7 userspace: improve dynamic object allocation
We now have a low-level function z_dynamic_object_create()
which is not a system call and is used for installing
kernel objects that are not supported by k_object_alloc().

Checking for valid object type enumeration values moved
completely to the implementation function.

A few debug messages and comments were improved.

Futexes and sys_mutexes are now properly excluded from
dynamic generation.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andrew Boie 378024c510 userspace: add z_is_in_user_syscall()
Certain types of system call validation may need to be pushed
deeper in the implementation and not performed in the verification
function. If such checks are only pertinent when the caller was
from user mode, we need an API to detect this situation.

This is implemented by having thread->syscall_frame be non-NULL
only while a user system call is in progress. The template for the
system call marshalling functions is changed to clear this value
on exit.

A test is added to prove that this works.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andrew Boie 64c8189ab0 userspace: fix bad ssf pointer on bad/no syscall
This was passing along _current->ssf, but these types of bad
syscalls do not go through the z_mrsh mechanism and was
passing stale data.

We have the syscall stack frame already as an argument,
propagate that so it works properly.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-06-03 22:33:32 +02:00
Andy Ross 99c2d2d047 kernel/queue: Remove interior use of k_poll()
The k_queue data structure, when CONFIG_POLL was enabled, would
inexplicably use k_poll() as its blocking mechanism instead of the
original wait_q/pend() code.  This was actually racy, see commit
b173e4353f.  The code was structured as a condition variable: using
a spinlock around the queue data before deciding to block.  But unlike
pend_current_thread(), k_poll() cannot atomically release a lock.

A workaround had been in place for this, and then accidentally
reverted (both by me!) because the code looked "wrong".

This is just fragile, there's no reason to have two implementations of
k_queue_get().  Remove.

Note that this also removes a test case in the work_queue test where
(when CONFIG_POLL was enabled, but not otherwise) it was checking for
the ability to immediately cancel a delayed work item that was
submitted with a timeout of K_NO_WAIT (i.e. "queue it immediately").
This DOES NOT work with the origina/non-poll queue backend, and has
never been a documented behavior of k_delayed_work_submit_to_queue()
under any circumstances.  I don't know why we were testing this.

Fixes #25904

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-06-03 01:47:41 +02:00
Andy Ross a343cf9480 kernel/timer: Handle K_FOREVER in k_timer_start()
The possibility of passing K_FOREVER as the initial duration argument
to k_timer_start() wasn't being handled, with the result that the
computed value became an zero timeout (effecitvely treating it as
K_NO_WAIT and firing at the next tick).

This is obviously pathlogical, but it should still do what the code
says it should and wait forever.

Make k_timer_start(..., K_FOREVER, ...) a noop.

Fixes #25820

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-05-29 19:59:14 +02:00
Andrew Boie 6af9793f0c kernek: don't allow mutex ops in ISRs
Mutex operations check ownership against _current. But in an
ISR, _current is just whatever thread was interrupted when the
ISR fired. Explicitly do not allow this.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-05-28 01:38:05 +02:00
Peter Bigot ae935dccdf device_pm: correct nop documented behavior
The device_pm_control_nop function is documented to always return zero
regardless of operation.  However, when device_get_power_state() is
invoked with this control function it returns success leaving the
output parameter state unmodified, which may not be a valid device
state.

Document and implement that the nop control function returns -ENOTSUP
always.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-05-21 20:32:12 +02:00
Andrew Boie 743ff98f51 kernel: wipe TLS before dropping to user mode
Ensures that TLS from when the thread was in supervisor mode
is erased, rather than rely on the arch code to do it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-05-13 22:02:48 +02:00
Andrew Boie 468efadd47 kernel: simplify dummy thread implementation
- simplify dummy thread initialization to a kswap.h
  inline function

- use the same inline function for both early boot and
  SMP setup

- add a note on necessity of the dummy thread even if
  a custom swap to main is implemented

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-05-13 21:23:52 +02:00
Martí Bolívar 6e8775ff84 devicetree: remove DT_HAS_NODE_STATUS_OKAY
Several reviewers agreed that DT_HAS_NODE_STATUS_OKAY(...) was an
undesirable API for the following reasons:

- it's inconsistent with the rest of the DT_NODE_HAS_FOO names
- DT_NODE_HAS_FOO_BAR_BAZ(node) was agreed upon as a shorthand
  for macros which are equivalent to
  DT_NODE_HAS_FOO(node) && DT_NODE_HAS_BAR(node) &&
- DT_NODE_HAS_BAZ(node), and DT_HAS_NODE_STATUS_OKAY is an odd duck
- DT_NODE_HAS_STATUS(..., okay) was viewed as more readable anyway
- it is seen as a somewhat aesthetically challenged name

Replace all users with DT_NODE_HAS_STATUS(..., okay), which is
semantically equivalent.

This is mostly done with sed, but a few remaining cases were done by
hand, along with whitespace, docs, and comment changes. These special
cases include the Nordic SOC static assert files.

Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
2020-05-13 18:24:42 +02:00
Peter Bigot c308f8069f kernel: init: move C++ initialization before application init loop
C++ is documented to be supported in applications, so it should be
supported in SYS_INIT() functions run at the application init level.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-05-09 11:42:20 -04:00
Tomasz Bursztyka 8d7bb8ffd8 device: Refactor device structures
When the device driver model got introduced, there were no concept of
SYS_INIT() which can be seen as software service. These were introduced
afterwards and reusing the device infrastructure for simplicity.
However, it meant to allocate a bit too much for something that only
required an initialization function to be called at right time.

Thus refactoring the devices structures relevantly:
- introducing struct init_entry which is a generic init end-point
- struct deviceconfig is removed and struct device owns everything now.
- SYS_INIT() generates only a struct init_entry via calling
  INIT_ENTRY_DEFINE()
- DEVICE_AND_API_INIT() generates a struct device and calls
  INIT_ENTRY_DEFINE()
- init objects sections are in ROM
- device objects sections are in RAM (but will end up in ROM once they
  will be 'constified')

It also generate a tiny memory gain on both ROM and RAM, which is nice.

Perhaps kernel/device.c could be renamed to something more relevant.

Signed-off-by: Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>
2020-05-08 23:07:44 +02:00
Andrew Boie c24673eefc kernel: properly name idle threads
These are now indexed by CPU.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-05-08 17:44:28 +02:00
Andrew Boie a203d21962 kernel: remove legacy fields in _kernel
UP should just use _kernel.cpus[0].

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-05-08 17:42:49 +02:00
Stephanos Ioannidis aaf93205bb kconfig: Rename CONFIG_FP_SHARING to CONFIG_FPU_SHARING
This commit renames the Kconfig `FP_SHARING` symbol to `FPU_SHARING`,
since this symbol specifically refers to the hardware FPU sharing
support by means of FPU context preservation, and the "FP" prefix is
not fully descriptive of that; leaving room for ambiguity.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2020-05-08 10:58:33 +02:00
Christopher Friedt 3315f8fecf kernel: pipe: read_avail / write_avail syscalls
These helper functions may clarify how much data is available to read
from or write to the circular buffer of a k_pipe.

Fixes #25036

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-05-07 19:39:53 +02:00
Kumar Gala fdd85d5ad7 dts: Rename DT_HAS_NODE macro to DT_HAS_NODE_STATUS_OKAY
Rename DT_HAS_NODE to DT_HAS_NODE_STATUS_OKAY so the semantics are
clear.  As going forward DT_HAS_NODE will report if a NODE exists
regardless of its status.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-05-06 05:25:41 -05:00
Andy Ross 4d417034e9 kernel/Kconfig: Add prompt for CONFIG_TIMEOUT_64BIT
This was missing a prompt string, causing recent kconfig logic to
throw an error if an app tried to set it directly.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-05-06 06:05:03 -04:00
Andrew Boie f1b5d9db8e kernel: fix issue with k_thread_join() timeouts
If k_thread_join() was passed with an actual timeout value,
and not K_FOREVER, the blocking thread was not being properly
woken up when the target thread exits. The timeout itself
was never aborted, causing the joining thread to remain
un-scheduled until the timeout expires.

Amend the k_thread_join() test cases to check that the join
completed before the provided timeout period expired.

Fixes: #24744

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-05-05 11:43:08 -07:00
Christopher Friedt d650f4b494 kernel: pipe: fix !K_NO_WAIT and >= min_xfer bytes transferred
If timeout != K_NO_WAIT, then return immediately when not all
bytes_to_read or bytes_to_write have been transfered, but >=
min_xfer have been transferred.

Fixes #24485

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
2020-04-28 16:14:55 +02:00
Joakim Andersson aac2220d29 kernel: Revert: "Add static threads to k_thread_foreach functions"
Revert commit mistakenly iterating over static threads in
k_thread_foreach functions. The static threads where already included
in the for-loop, and is now duplicated.

This reverts commit bd3b4b0caf.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2020-04-27 19:04:02 +02:00
Stephanos Ioannidis 0e6ede8929 kconfig: Rename CONFIG_FLOAT to CONFIG_FPU
This commit renames the Kconfig `FLOAT` symbol to `FPU`, since this
symbol only indicates that the hardware Floating Point Unit (FPU) is
used and does not imply and/or indicate the general availability of
toolchain-level floating point support (i.e. this symbol is not
selected when building for an FPU-less platform that supports floating
point operations through the toolchain-provided software floating point
library).

Moreover, given that the symbol that indicates the availability of FPU
is named `CPU_HAS_FPU`, it only makes sense to use "FPU" in the name of
the symbol that enables the FPU.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2020-04-27 19:03:44 +02:00
Kumar Gala 9b4298c20d arm: Convert DT_CCM_* to new devicetree.h macros
Convert various DT_CCM_* macros to use DT_CHOSEN(zephyr_ccm) and
associated macros from devicetree.h.

We remove CCM references from cortex_a and cortex_r linker scripts as
its only a feature on Cortex-M STM32 SoCs.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-04-26 06:04:46 -05:00
Kumar Gala a49817d17e arm: Convert DT_DTCM_* to new devicetree.h macros
Convert various DT_DTCM_* macros to use DT_CHOSEN(zephyr_dtcm) and
associated macros from devicetree.h.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-04-26 06:04:46 -05:00
Andy Ross 3e729b2b1c kernel/timer: Correctly clamp period argument
The period argument of a k_timer needs an offset of one tick from the
value computed in user code (because periods get reset from within the
ISR, see the comment above this code for an explanation).  When the
computed tick value was 1, it would become 0.  This is actually
perfectly correct as a k_timeout_t to be passed to z_add_timeout().

BUT: to k_timer's API, K_NO_WAIT means "never" (i.e. the same as
K_FOREVER) and not "as soon as possible", so the period timer would
not be reset.  This is sort of a wart, but it's the way the API has
been specified forever.

The upshot is that for the case of calling k_timer_start() with a
minimal period argument (i.e. one that produces "one tick"), the
period would be ignored and the timer would act like a one shot.  Fix
the clamp so it can't produce K_NO_WAIT.

This also adds a filter for absolute timeouts, which (while that's
sort of a pathological usage) were getting that one tick offset when
it wasn't appropriate.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-24 16:38:33 +02:00
Andy Ross 12bd187003 kernel/timeout: Check for K_FOREVER in z_add_timeout()
The "forever" token has always been interpreted above z_add_timeout()
(because it's always taken ticks, but K_FOREVER used to be in ms).
But it was discovered that k_delayed_work_submit_to_queue() was never
testing for this and passing a raw K_FOREVER down, where it got
interpreted as a negative timeout and caused it to fire at the next
tick.

Now that we actually see the original k_timeout_t here, we might as
well check it locally and do the correct thing (that is, nothing) if
asked to schedule a timeout that will never fire.

Fixes #24409

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-22 11:10:17 -07:00
Andrew Boie 618426d6e7 kernel: add Z_STACK_PTR_ALIGN ARCH_STACK_PTR_ALIGN
This operation is formally defined as rounding down a potential
stack pointer value to meet CPU and ABI requirments.

This was previously defined ad-hoc as STACK_ROUND_DOWN().

A new architecture constant ARCH_STACK_PTR_ALIGN is added.
Z_STACK_PTR_ALIGN() is defined in terms of it. This used to
be inconsistently specified as STACK_ALIGN or STACK_PTR_ALIGN;
in the latter case, STACK_ALIGN meant something else, typically
a required alignment for the base of a stack buffer.

STACK_ROUND_UP() only used in practice by Risc-V, delete
elsewhere.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-04-21 18:45:45 -04:00
Andrew Boie 1f6f977f05 kernel: centralize new thread priority check
This was being done inconsistently in arch_new_thread(), just
move to the core kernel.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-04-21 18:45:45 -04:00
Andrew Boie c0df99cc77 kernel: reduce scope of z_new_thread_init()
The core kernel z_setup_new_thread() calls into arch_new_thread(),
which calls back into the core kernel via z_new_thread_init().

Move everything that doesn't have to be in z_new_thread_init() to
z_setup_new_thread() and convert to an inline function.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-04-21 18:45:45 -04:00
Peter Bigot aea9d35c4e kernel: fix runtime initialization of k_pipe object
Runtime initialization failed to reset the lock field, causing
problems when the pipe object is located on a stack and passed by
reference to other code.  Lacking an API for initializing a spinlock
by itself use the idiom from _K_PIPE_INITIALIZER().

To simplify maintainability the initialization order is changed
slightly to match the structure field declaration order.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-04-21 11:19:29 +02:00
Andy Ross 38031dd599 kernel: Make the k_heap backend default for k_mem_pool
Legacy code can switch back to the original implementation where it
needs it, but we don't want new code to be unintentionally dependent
on the behavior of the older allocator.  The new one is a better
general purpose choice.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-14 10:05:55 -07:00
Andy Ross 8f0959c7b1 kernel: Add k_mem_pool compatibility layer on top of k_heap
Add a shim layer implementing the legacy k_mem_pool APIs backed by a
k_heap instead of the original implementation.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-14 10:05:55 -07:00
Andy Ross 0dd83b8c2e kernel: Add k_heap synchronized memory allocator
This adds a k_heap data structure, a synchronized wrapper around a
sys_heap memory allocator.  As of this patch, it is an alternative
implementation to k_mem_pool() with somewhat better efficiency and
performance and more conventional (and convenient) behavior.

Note that commit involves some header motion to break dependencies.
The declaration for struct k_spinlock moves to kernel_structs.h, and a
bunch of includes were trimmed.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-14 10:05:55 -07:00
Andy Ross e96ac9061f kernel: Refactor k_mem_pool APIs into a base and derived level
Almost all of the k_mem_pool API is implemented in terms of three
lower level primitives: K_MEM_POOL_DEFINE(), k_mem_pool_alloc() and
k_mem_pool_free_id().  These are themselves implemented on top of the
lower level sys_mem_pool abstraction.

Make this layering explicit by splitting the low level out into its
own files: mempool_sys.c/h.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-04-14 10:05:55 -07:00
Kumar Gala 43a7d26603 drivers: entropy: replace CONFIG_ENTROPY_NAME with DT macro
Replace CONFIG_ENTROPY_NAME with DT_CHOSEN_ZEPHYR_ENTROPY_LABEL.  We now
set zephyr,entropy in the chosen node of the device tree to the entropy
device.

This allows us to remove CONFIG_ENTROPY_NAME from dts_fixup.h.  Also
remove any other stale ENTROPY related defines in dts_fixup.h files.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2020-04-13 09:14:21 -05:00
Anas Nashif b90fafd6a0 kernel: remove unused offload workqueue option
Those are used only in tests, so remove them from kernel Kconfig and set
them in the tests that use them directly.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-04-12 18:42:27 -04:00
Andy Ross 914205ca85 kernel/timeout: Add k_uptime_ticks() API
Add a call to get the system tick count as an official API (and
redefine the existing millisecond API in terms of it).  Sophisticated
applications need to be able to count ticks directly, and the newer
timeout API supports that.  Uptime should too, for symmetry.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-03-31 19:40:47 -04:00
Andy Ross 5a5d3daf6f kernel/timeout: Add timeout remaining/expires APIs
Add tick-based (i.e. precision resistant) inspection APIs for kernel
timeouts visible via k_timer, k_delayed work and thread timeouts
(i.e. pended/sleeping threads).  These are each available in
"remaining" and "expires" variants returning time values relative to
current time and system start.  All have system calls where applicable
(i.e. everywhere but k_delayed_work, which is not a userspace API)

The pre-existing millisecond "remaining_get()" predicates for timer
and delayed work remain, but are expressed in terms of the newer
calls.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-03-31 19:40:47 -04:00
Andy Ross 4c7b77a716 kernel/timeout: Add absolute timeout APIs
Add support for "absolute" timeouts, which are expressed relative to
system uptime instead of deltas from current time.  These allow for
more race-resistant code to be written by allowing application code to
do a single timeout computation, once, and then reuse the timeout
value even if the thread wakes up and needs to suspend again later.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-03-31 19:40:47 -04:00
Andy Ross cfeb07eded kernel/timeout: Enable 64 bit timeout precision
Add a CONFIG_TIMEOUT_64BIT kconfig that, when selected, makes the
k_ticks_t used in timeout computations pervasively 64 bit.  This will
allow much longer timeouts and much faster (i.e. more precise) tick
rates.  It also enables the use of absolute (not delta) timeouts in an
upcoming commit.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-03-31 19:40:47 -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
Oleg Zhurakivskyy b1e1f64d14 global: Replace BUILD_ASSERT_MSG() with BUILD_ASSERT()
Replace all occurences of BUILD_ASSERT_MSG() with BUILD_ASSERT()
as a result of merging BUILD_ASSERT() and BUILD_ASSERT_MSG().

Signed-off-by: Oleg Zhurakivskyy <oleg.zhurakivskyy@intel.com>
2020-03-31 07:18:06 +02:00
Daniel Leung 4e1637b54e kernel: add sys init level for SMP
This adds a sys init level which allows device and sys_init
to be done after SMP initialization, z_smp_init(), when all
cores are up and running.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-03-25 19:07:28 -04:00
Andrew Boie a4c9190649 kernel: fix oops policy for k_thread_abort()
Don't generate a Z_OOPS() if k_thread_abort() is called on a
thread that isn't running. Just return to the caller instead,
much like how k_thread_join() functions.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-25 10:23:12 -07:00
Carles Cufi 4b37a8f3a4 Revert "global: Replace BUILD_ASSERT_MSG() with BUILD_ASSERT()"
This reverts commit 8739517107.

Pull Request #23437 was merged by mistake with an invalid manifest.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2020-03-19 18:45:13 +01:00
Oleg Zhurakivskyy 8739517107 global: Replace BUILD_ASSERT_MSG() with BUILD_ASSERT()
Replace all occurences of BUILD_ASSERT_MSG() with BUILD_ASSERT()
as a result of merging BUILD_ASSERT() and BUILD_ASSERT_MSG().

Signed-off-by: Oleg Zhurakivskyy <oleg.zhurakivskyy@intel.com>
2020-03-19 15:47:53 +01:00
Andrew Boie 28be793cb6 kernel: delete separate logic for priv stacks
This never needed to be put in a separate gperf table.
Privilege mode stacks can be generated by the main
gen_kobject_list.py logic, which we do here.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-17 20:11:27 +02: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 2f3a89fa8d kernel: rename _k_object_assignment
Private structure, rename to z_object_assignment

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-17 20:11:27 +02:00
Andrew Boie 4bad34e749 kernel: rename _k_thread_stack_element
Private data type, prefix with z_.

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
Andrew Boie fb1c29475f kernel: zero app shmem bss via SYS_INIT
Doesn't need to be directly in init.c.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-16 21:40:52 -04:00
Andrew Boie 80a0d9d16b kernel: interrupt/idle stacks/threads as array
The set of interrupt stacks is now expressed as an array. We
also define the idle threads and their associated stacks this
way. This allows for iteration in cases where we have multiple
CPUs.

There is now a centralized declaration in kernel_internal.h.

On uniprocessor systems, z_interrupt_stacks has one element
and can be used in the same way as _interrupt_stack.

The IRQ stack for CPU 0 is now set in init.c instead of in
arch code.

The extern definition of the main thread stack is now removed,
this doesn't need to be in a header.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-16 23:17:36 +02:00
Andrew Boie 322816eada kernel: add k_thread_join()
Callers will go to sleep until the thread exits, either normally
or crashing out.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-13 08:42:43 -04:00
Andrew Boie 5a2619e17a kernel: use z_swap_unlocked in k_thread_abort
z_swap_unlocked() does the same construction of using a
dummy spinlock; just use that and make the code simpler.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-12 10:57:02 -04:00
Andrew Boie 60be4eb653 kernel: remove comment in k_thread_abort()
z_reschedule_unlocked() is a no-op if the caller is
cooperative, because the logic that maintains the ready queue
ensures that the co-op thread is always at the front unless
some special handling is done like in k_yield(), which does
not happen here.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-12 10:57:02 -04:00
Joakim Andersson bd3b4b0caf kernel: Add static threads to k_thread_foreach functions
Add iterating over the static threads for k_thread_foreach and
k_thread_foreach_unlocked iterator functions

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
2020-03-12 10:48:29 +02:00
Ioannis Glaropoulos 1c56f87321 kernel: fatal: fix indentation in z_fatal_error
Fix indentation error in z_fatal_error().

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2020-03-11 10:26:36 +02:00
Ioannis Glaropoulos 9d184286d3 kernel: fatal: allow tests to continue upon spurious ISR trigger
We want to be regression-testing the spurious ISR functionality.
Therefore, in z_fatal_error() we need to allow a test to continue
if an error has occured due to a spurious IRQ being triggered.
Only in test mode, wee allow the function to return without an
error. In normal mode the current thread will be aborted.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2020-03-11 10:26:36 +02:00
Ioannis Glaropoulos 49fb5d0812 kernel: fatal: check for esf validity when inspecting nested IRQ
For architectures that support detection of nested interrupts,
we need to check the validity of the exception stack frame,
before we can supply it as a pointer to the function that
evaluates whether we are in a nested interrupt context. This
commits adds the required esf pointer checks in z_fatal_error().

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2020-03-11 10:26:36 +02:00
Andrew Boie c4fbc08347 kernel: fixup thread monitor locking
The lock in kernel/thread.c was pulling double-duty, protecting
both the thread monitor linked list and also serializing access
to k_thread_suspend/resume functions.

The monitor list now has its own dedicated lock.

The object tracing test has been updated to use k_thread_foreach().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-10 16:09:24 -04:00
Flavio Ceolin 8ae822c9fa kernel: random: ifdef z_early_boot_rand_get
This function had a to sys_rand_get() even without random source. As
Zephyr is built with linkage garbage collection and this function is
called only if either ENTROPY_HAS_DRIVER or TEST_RANDOM_GENERATOR is
enabled and these options automatically enable a random source.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-03-10 21:12:28 +02:00
Andrew Boie 9f0acd44a4 kernel: add APIs for atomic os on pointers
The existing APIs are insufficient on 64-bit systems as atomic_t
is 32-bits wide.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-10 10:18:16 -04:00
Andrew Boie 60e0019751 kernel: fix return type for atomic_cas()
In some cases this was a bool, in some cases an integer value
of 1 or 0. Standardize on bool.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-10 10:18:16 -04:00
Andrew Boie 6cf496f324 kernel: use sched lock for k_thread_suspend/resume
This logic should be using the sched_lock and not its own
separate lock for these two functions.

Some simplications were made; z_thread_single_resume and
z_thread_single_suspend were only used in one place, and there was
some redundant logic for whether to reschedule in the suspend case.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-03-10 09:57:58 -04:00
Flavio Ceolin fbeaa0a510 kernel: Stack pointer random depends on MULTITHREADING
Don't pretend with have stack randomization without multithreading.
When multithreading is disabled the "main" thread never starts. Zephyr
will run on the stack used for the z_cstart(), which on most
architectures is the interrupt stack.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2020-03-02 22:49:37 +02:00
Andrew Boie 896e32b414 kernel: remove problematic pend() assertion
This assertion, if built in, allows users threads to crash
the kernel in a critical section by passing a negative timeout
value, creating a DoS attack vector.

Remove this assertion, immediately below it there's a check
which just resets it to 0 anyway.

Fixes: #22999

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-02-21 08:57:07 -08:00
Peter Bigot d8146d6c6d kernel: work_q: fix return value in non-error case
A recent patch allowed an error code to be returned even though the
execution path treated it as a non-error condition.  Clear the code
before returning.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-02-20 17:50:05 +02:00
Andy Ross a2f6826f9c kernel/thread: Don't clobber arch initialization of switch_handle
The recent synchronization work required that the kernel guarantee
switch_handle is non-null, but it did it in a way that works for ARC
and x86_64 but would clobber the work xtensa had already done to
populate that field.

There's no point: just make this an assert, as it's always been the
arch layer's job.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-19 08:29:35 -05:00
Luiz Augusto von Dentz 038d727c18 kernel: work: Return error if timeout cannot be aborted
This is aligned with the documentation which states that an error shall
be returned if the work has been completed:

  '-EINVAL Work item is being processed or has completed its work.'

Though in order to be able to resubmit from the handler itself it needs
to be able to distinct when the work is already completed so instead of
-EINVAL it return -EALREADY when the work is considered to be completed.

Fixes #22803

Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
2020-02-17 22:37:26 +02:00
Ioannis Glaropoulos 3a3364eef8 kernel: fatal: unlock IRQs in early return points in z_fatal_error
We need to unlock IRQs in early return points of
z_fatal_error() functions; not only at the normal
return point.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2020-02-14 20:47:37 +02:00
Andy Ross 7353c7f95d kernel/userspace: Move syscall_frame field to thread struct
The syscall exception frame was stored on the CPU struct during
syscall execution, but that's not right.  System calls might "feel
like" exceptions, but they're actually perfectly normal kernel mode
code and can be preempted and migrated between CPUs at any time.

Put the field on the thread struct.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-08 08:51:04 -05:00
Andy Ross 8153144de0 kernel/fatal: Fatal errors must not be preempted
The code underneath z_fatal_error() (which is usually run in an
exception context, but is not required to be) was running with
interrupts enabled, which is a little surprising.

The only bug present currently is that the CPU ID extracted for
logging is subject to a race (i.e. it's possible but very unlikely
that such a handler might migrate to another CPU after the error is
flagged and log the wrong CPU ID), but in general users with custom
error handlers are likely to be surprised when their dying threads
gets preempted by other code before they can abort.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-08 08:51:04 -05:00
Andy Ross eefd3daa81 kernel/smp: arch/x86_64: Address race with CPU migration
Use of the _current_cpu pointer cannot be done safely in a preemptible
context.  If a thread is preempted and migrates to another CPU, the
old CPU record will be wrong.

Add a validation assert to the expression that catches incorrect
usages, and fix up the spots where it was wrong (most important being
a few uses of _current outside of locks, and the arch_is_in_isr()
implementation).

Note that the resulting _current expression now requires locking and
is going to be somewhat slower.  Longer term it's going to be better
to augment the arch API to allow SMP architectures to implement a
faster "get current thread pointer" action than this default.

Note also that this change means that "_current" is no longer
expressible as an lvalue (long ago, it was just a static variable), so
the places where it gets assigned now assign to _current_cpu->current
instead.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-08 08:51:04 -05:00
Andrew Boie efc5fe07a2 kernel: overhaul unused stack measurement
The existing stack_analyze APIs had some problems:

1. Not properly namespaced
2. Accepted the stack object as a parameter, yet the stack object
   does not contain the necessary information to get the associated
   buffer region, the thread object is needed for this
3. Caused a crash on certain platforms that do not allow inspection
   of unused stack space for the currently running thread
4. No user mode access
5. Separately passed in thread name

We deprecate these functions and add a new API
k_thread_stack_space_get() which addresses all of these issues.

A helper API log_stack_usage() also added which resembles
STACK_ANALYZE() in functionality.

Fixes: #17852

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-02-08 10:02:35 +02:00
Anas Nashif 73008b427c tracing: move headers under include/tracing
Move tracing.h to include/tracing/ to align with subsystem reorg.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-02-07 15:58:05 -05:00
Andrew Boie d1f50122f9 kernel: move timing externs to public header
These arch_timing_ defines get used in certain timer
drivers and need to be in the public include space,
and not the private kernel headers.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-02-06 23:07:37 -05:00
Andy Ross 5737b5c843 kernel/sched: Re-add IPI calls on k_wakeup() and k_thread_priority_set()
These got dropped by an earlier patch, but are required on SMP systems
so synchronously notify other CPUs of changed scheduler state.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-04 17:50:11 -05:00
Andy Ross c44d566aee kernel/sched: Re-fix SMP wait-for-switch on interrupt exit
This got clobbered by commit adac4cbafa in what I think was a rebase
mistake.  Without it, on SMP systems it's possible to select a new
_current thread and try to return into it before another CPU has
actually finished switching away from it.

Interestingly: the frequency with which this bug got caught once it
was reintroduced was much, much higher than it was when it was fixed
the first time due to the instruction pointer poisoning introduced in
the interrim.  Incompletely saved threads now have deliberately broken
state when assertions are enabled and will panic synchronously.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-04 17:50:11 -05:00
Andy Ross 96ccc46e03 kernel/sched: Put k_thread_start() under a single lock
Similar to the suspend refactoring earlier, this really nees to be
done in an atomic block.  There were two confirmable races here,
though it's not completely clear either was being hit in practice:

1. The bit operations in z_mark_thread_as_started() aren't atomic so
   it needs to be protected.

2. The intermediate state in z_ready_thread() could result in a dead
   or suspended thread being added to the ready queue if another
   context tried a simultaneous abort or suspend.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-03 09:31:56 -05:00
Andy Ross ed6b4fb21c kernel/sched: Properly synchronize pend()
Kernel wait_q's and the thread pended_on backpointer are scheduler
state and need to be modified under the scheduler lock.  There was one
spot in pend() where they were not.

Also unpack z_remove_thread_from_ready_q() into an unsynchronized
utility so that it can be called by this process in a single lock
block.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-03 09:31:56 -05:00
Andy Ross b8ff63e3c7 kernel/sem: Fix SMP race
This had the same race that queue did: you have to be 100% done with
state management before calling z_ready_thread(), because another CPU
can pick up the thread before the return value was set.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-02-03 09:31:56 -05:00
Daniel Leung adac4cbafa sched: smp: fix thread marked dead but still running
Under SMP, when a thread is marked aborting, this thread may still
be running on another CPU. However, if there is only one thread
available to run, this thread may be selected to run again due to
next_up() not checking for the aborting state. Moreover, when
there is no IPI to signal to others k_thread_abort() being called,
the k_thread_abort() target thread is marked dead after a new
thread is selected to run. This causes the original thread calling
k_thread_abort() to mistaken that target thread is no longer
running and returns.

Note that, with working IPI, z_sched_ipi() is called as an ISR
to mark the target thread dead. A new thread is then selected to
run, so that the target thread would not be selected due to it
being dead.

This moves the code to mark thread dead into next_up(), where
the next best thread is selected, and the current thread being
swapped out. z_sched_ipi() now becomes an empty function, and
calls to it are removed.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2020-01-31 11:46:35 -05:00
Anas Nashif 471ffbe77d coverage: do not dump coverage data by default
Only dump data when we are interested in the analysing coverage. By
default just collect the data.

CONFIG_COVERAGE_DUMP is used to control this behaviour.

This will help speed up sanitycheck and will avoid lots of noise in the
log when some tests with coverage enabled failed. Dumping data to
console is also suspected to be one of the reason why qemu hangs in CI.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-30 16:04:03 -05:00
Anas Nashif 7605ac2c4c kernel: thread: fix string for _THREAD_PRESTART
_THREAD_PRESTART means the thread was not started yet and is being
setup, for example this is the case when starting a thread with a
timeout. We do not have a 'restart' thread state.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-29 13:17:19 -08:00
Sebastian Bøe fdac7b3319 cmake: Add target for generating header files
Before C sources can be compiled any generated header that they
include must be generated. Currently, the target 'offsets_h' happens
to depend directly or indirectly on all generated headers.

This means that to compile safely, one can simply depend on
'offsets_h'. But this is coincidental and might not be true in the
future.

To be able to safely depend on a target that represents all generated
headers being ready we introduce the target
'zephyr_generated_headers'.

Any third-party build scripts can now safely depend on
'zephyr_generated_headers' and be protected from any internal changes
to the build system, like the removal of offsets_h.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2020-01-29 11:44:57 -06:00
Andrew Boie 6f654bbafd mempool: use k_malloc heap for ISR allocations
Fixes an issue where calling z_thread_malloc() would
borrow the resource pool of whatever thread happened
to be interrupted at the time.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-01-24 09:27:59 -08:00
Krzysztof Chruscinski a8b5a2e65e kernel: device: Add const qualifier to device_config
Device config structure is placed in rom section but there was
no const prefix used. Lack of prefix suggested that structure
is in ram (ram_report is also fooled). Added const prefix to
explicitly inform that it goes to rom.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2020-01-22 06:32:36 -06:00
Andy Ross 4c2fc2aed7 kernel/queue: Fix SMP race
Calling z_ready_thread() means the thread is now ready and can wake up
at any moment on another CPU.  But we weren't finished setting the
return value!  So the other side could wake up with a spurious "error"
condition if it ran too soon.  Note that on systems with a working
IPI, that wakeup can happen much faster than you might think.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-01-21 14:47:52 -08:00
Andy Ross 3235451880 kernel/swap: Add SMP "wait for switch" synchronization
On SMP, there is an inherent race when swapping: the old thread adds
itself back to the run queue before calling into the arch layer to do
the context switch.  The former is properly synchronized under the
scheduler lock, and the later operates with interrupts locally
disabled.  But until somewhere in the middle of arch_switch(), the old
thread (that is in the run queue!) does not have complete saved state
that can be restored.

So it's possible for another CPU to grab a thread before it is saved
and try to restore its unsaved register contents (which are garbage --
typically whatever state it had at the last interrupt).

Fix this by leveraging the "swapped_from" pointer already passed to
arch_switch() as a synchronization primitive.  When the switch
implementation writes the new handle value, we know the switch is
complete.  Then we can wait for that in z_swap() and at interrupt
exit.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-01-21 14:47:52 -08:00
Andy Ross e06ba702d5 kernel/sched: Address thread abort termination delay issue on SMP
It's possible for a thread to abort itself simultaneously with an
external abort from another thread.  In fact in our test suite this is
a common thing, as ztest will abort its own spawend threads at the end
of a test, as they tend to be exiting on their own.

When that happens, the thread marks itself DEAD and does all its
scheduler bookeeping, but it is STILL RUNNING on its own stack until
it makes its way to its final swap.  The external context would see
that "dead" metadata and return from k_thread_abort(), allowing the
next test to reuse and spawn the same thread struct while the old
context was still running.  Obviously that's bad.

Unfortunately, this is impossible to address completely without
modifying every SMP architecture to add a API-visible hook to every
swap that signals completion.  In practice the best we can do is add a
delay.  But note the optimization: almost always, the scheduler IPI
catches the running thread and kills it from interrupt context
(i.e. on a different stack).  When that happens, we know that the
interrupted thread will never be resumed (because it's dead) and can
elide the delay.  We only pay the cost when we actually detect a race.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-01-21 14:47:52 -08:00
Andy Ross 60247ca149 kernel/sched: Correct IPI usage
These two spots were calling z_sched_ipi() (the IPI handler run under
the ISR, which is a noop here because obviously the current thread
isn't DEAD) and not arch_sched_ipi() (which triggers an IPI on other
CPUs to inform them of scheduling state changes), presumably because
of a typo.

Apparently we don't have tests for k_wakeup() and
k_thread_priority_set() that are sensitive to latency in SMP
contexts...

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-01-21 14:47:52 -08:00
Andy Ross 86430d8d46 kernel: arch: Clarify output switch handle requirements in arch_switch
The original intent was that the output handle be written through the
pointer in the second argument, though not all architectures used that
scheme.  As it turns out, that write is becoming a synchronization
signal, so it's no longer optional.

Clarify the documentation in arch_switch() about this requirement, and
add an instruction to the x86_64 context switch to implement it as
original envisioned.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-01-21 14:47:52 -08:00
Ulf Magnusson 40b49e22ea kernel: kconfig: Make SCHED_IPI_SUPPORTED invisible
Toggling this symbol probably doesn't make sense, because the
architecture is already known when Kconfig runs.

SCHED_IPI_SUPPORTED is enabled through being selected by the ARC_CONNECT
(maybe that one shouldn't be configurable either) and X86_64 symbols.

Note that it's not possible to disable the symbol when it's being
selected, so trying to turn it off on e.g. X86_64 won't work either.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2020-01-20 18:38:10 -05:00
Anas Nashif 756d8b03e2 kernel: queue: runtime error handling
Runtime error handling for k_queue_append_list and k_queue_merge_slist.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 1ed67d1d51 kernel: stack: error handling
Add runtime error checking for both k_stack_push and k_stack_cleanup.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 11b9365542 kernel: msgq: error handling
Add runtime error handling for k_msgq_cleanup. We return 0 on success
now and -EAGAIN when cleanup is not possible.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif dfc2bbcd3c kernel: mem_slab: error handling
Add runtime error checking for k_mem_slab_init and replace asserts with
returning error codes.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 154af912e8 kernel: work_q: error handling
When trying to cancel a NULL work queue return -EAGAIN.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 361a84d07f kernel: pipe: runtime error checking
Add runtime error checking to k_pipe_cleanup and k_pipe_get and remove
asserts.
Adapted test which was expecting a fault to handle errors instead.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 5076a83ef5 kernel: semaphore: optimize code
Remove static helper functions used only once and integrate them into
calling functions.
In k_sem_take, return at the end.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 928af3ce09 kernel: semaphore: k_sem_init error checking
Check for errors at runtime and stop depending on ASSERTs.
This changes the API for
- k_sem_init

k_sem_init now returns -EINVAL on invalid data.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Anas Nashif 86bb2d06d7 kernel: mutex: add error checking
k_mutex_unlock will now perform error checking and return on failures.

If the current thread does not own the mutex, we will now return -EPERM.
In the unlikely situation where we own a lock and the lock count is
zero, we assert. This is considered an undefined bahviour and should not
happen.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-20 17:19:54 -05:00
Andrew Boie a594ca7c8f kernel: cleanup and formally define CPU start fn
The "key" parameter is legacy, remove it.

Add a typedef for the expected function pointer type.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2020-01-13 16:35:10 -05:00
Anas Nashif 0ad67650f2 tracing: better positioning of tracing points
Improve positioning of tracing calls. Avoid multiple calls and missing
events because of complex logix. Trace the event where things happen
really.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-09 11:21:19 -05:00
Anas Nashif 1530819e12 tracing: remove duplicate tracing of thread creation
This is already being called in z_setup_new_thread.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2020-01-09 11:21:19 -05:00
Andy Ross 8bdabcc46b kernel/sched: Move thread suspend and abort under the scheduler lock
Historically, these routines were placed in thread.c and would use the
scheduler via exported, synchronized functions (e.g. "remove from
ready queue").  But those steps were very fine grained, and there were
races where the thread could be seen by other contexts (in particular
under SMP) in an intermediate state.  It's not completely clear to me
that any of these were fatal bugs, but it's very hard to prove they
weren't.

At best, this is fragile.  Move the z_thread_single_suspend/abort()
functions into the scheduler and do the scheduler logic in a single
critical section.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2020-01-08 14:21:10 +01:00
Steven Wang 9b909f2d69 kernel/mutex: code improvement
Line "new_prio = mutex->owner_orig_prio" is unnecessary. So
remove it.

Signed-off-by: Steven Wang <steven.l.wang@linux.intel.com>
2020-01-07 17:13:37 +01:00
Peter Bigot 74ef395332 kernel: move test of kernel startup state to more visible location
The original implementation left this function hidden in init.h which
prevented it from showing up in documentation.  Move it to kernel.h,
and document it consistent with the other functions that allow caller
customization based on context.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2020-01-06 13:55:31 -05:00
Ulf Magnusson 1404aaf099 kconfig: Remove '# hidden' comment on ARCH_HAS_CUSTOM_BUSY_WAIT
Straggler. See commit 41713244b3 ("kconfig: Remove '# Hidden' comments
on promptless symbols").

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2020-01-06 13:34:00 -05:00
Jukka Rissanen cc6317d7ac kernel: poll: Allow 0 event input
Allow caller to supply 0 events in which case the function just
does the sleep. This is useful so that the caller does not need
to create artificial events.

Signed-off-by: Jukka Rissanen <jukka.rissanen@linux.intel.com>
2020-01-03 11:26:46 -08:00
Ulf Magnusson bd9962d8d9 kconfig: Remove '# hidden' comments on promptless symbols
Same deal as in commit 41713244b3 ("kconfig: Remove '# Hidden' comments
on promptless symbols"). I forgot to do a case-insensitive search.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2020-01-03 11:38:40 +01:00
Anas Nashif 9e3e7f6dda kernel: use 'thread' for thread variable consistently
We have been using thread, th and t for thread variables making the code
less readable, especially when we use t for timeouts and other time
related variables. Just use thread where possible and keep things
consistent.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-12-21 19:57:57 -05:00
Radoslaw Koppel 2c529ce3b6 kernel: thread: k_thread_foreach_unlocked: Implement
Implement thread foreach processing with limited locking
to allow threads processing that may take more time but allows
missing some threads processing when the thread list is modified.

Signed-off-by: Radoslaw Koppel <radoslaw.koppel@nordicsemi.no>
2019-12-20 20:20:04 -05:00
Danny Oerndrup c9d78401cc spinlock: Make SPIN_VALIDATE a Kconfig option.
SPIN_VALIDATE is, as it was previously, enabled per default when having
less than 4 CPUs and either having no flash or a flash size greater than
32kB.

Small targets, which needs to have asserts enabled, can chose to have
the spinlock validation enabled or not and thereby decide whether the
overhead added is acceptable or not.

Signed-off-by: Danny Oerndrup <daor@demant.com>
2019-12-20 19:51:16 -05:00
Anas Nashif 8d2675010a kernel: update SCHED_CPU_MASK Kconfig doc
Fix reference to APIs and reformat kconfig help message.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-12-18 20:25:33 -05:00
Peter Bigot 8162e586e3 kernel: sched: assert when k_sleep invoked from interrupt context
Fix a gap where k_sleep(K_FOREVER) could execute a code path that
would not verify that the call was not from interrupt context.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-12-13 15:47:43 -05:00
Andrew Boie b5c681071a kernel: don't use u32_t for data sizes
Use a size_t instead.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-12-12 14:48:42 -08:00
Andrew Boie 428afe5084 kernel: fix some bad casts in userspace.c
64-bit systems generate some compiler warnings about
data type sizes, use uintptr_t where int/u32_t was being cast
to void *.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-12-12 14:48:42 -08:00
Andrew Boie e48ed6a980 kernel: use uintptr_t for kobject data
This has to be wide enough to store a pointer.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-12-12 14:48:42 -08:00
Andrew Boie a824821b86 kernel: fix k_mem_partition data types
We need a size_t and not a u32_t for partition sizes,
for 64-bit compatibility.

Additionally, app_memdomain.h was also casting the base
address to a u32_t instead of a uintptr_t.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-12-12 14:48:42 -08:00
Kumar Gala a8171db6a6 doc: Fix warnings associated with 'unbalanced grouping commands'
Builds of docs with doxygen 1.8.16 has a number of warnings of the form:
'warning: unbalanced grouping commands'.  Fix those warnings be either
balancing the group command or removing it.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-12-12 12:39:35 -06:00
Peter A. Bigot c326661ee6 kernel: init: provide access to kernel startup state
Device initialization may require use of generic services such as
starting up power rails, some of which may be controlled by GPIOs on
an external controller that can't be used until full kernel services
are available.  Generic services can check k_is_in_isr() and mediate
their behavior that way, but currently have no way to determine that
the kernel is not available.

Provide a function that indicates whether initialization is still in
pre-kernel stages where no kernel services are available.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-12-11 14:45:40 -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
Andy Ross 7022000b5c kernel/mutex: Fix races, make unlock rescheduling
The k_mutex is a priority-inheriting mutex, so on unlock it's possible
that a thread's priority will be lowered.  Make this a reschedule
point so that reasoning about thread priorities is easier (possibly at
the cost of performance): most users are going to expect that the
priority elevation stops at exactly the moment of unlock.

Note that this also reorders the code to fix what appear to be obvious
race conditions.  After the call to z_ready_thread(), that thread may
be run (e.g. by an interrupt preemption or on another SMP core), yet
the return value and mutex weren't correctly set yet.  The spinlock
was also prematurely released.

Fixes #20802

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-12-03 12:33:17 -06:00
Anas Nashif e4a9be94c0 kernel: init: simplify boot banner printing
Just use printk directly instead of going over defines.

For some reason, this change lets us pass on master when running
tests/kernel/timer/timer_monotonic test. This test started failing after
rc2 was tagged, just because the changing git version string passing to
BUILD_VERSION. This is still under investigation.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-11-29 07:52:16 -05:00
Andy Ross 50d0942f5e kernel/thread: Cancel timeouts on k_thread_suspend(), make schedule point
When suspending a thread, cancel any pending timeouts which might wake
it up unexpectedly.  Also, make suspending the current thread
(specifically) a schedule point, as callers are clearly going to
expect that to be synchronous.

Also fix a documentation weirdness.  The phrasing in the earlier docs
for k_thread_suspend() was confusing: it could be interpreted as
either document the current (essentially buggy) behavior that threads
will "wake up" due to preexisting timeouts, OR to mean that thread
timeouts will continue to be tracked so that resuming a thread that
was sleeping will continue to sleep until the timeout (something that
has never been implemented: k_sleep() is implemented on top of
suspend).  Rewrite to document what we actually implement.

Fixes #20033

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-11-25 19:12:05 -05:00
Flavio Ceolin 91fd6d0866 kernel: thread: Fix randomness problem with stack pointer random
In some platforms the size of size_t can be different of 4 bytes. Use
sys_rand_get to proper fill this variable.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-11-15 13:43:32 -08:00
David Leach aa91113af7 kernel: Kconfig: Define dependencies for STACK_CANARIES
STACK_CANARIES relies on random value for the canarie so
ENTROPY_GENERATOR or TEST_RANDOM_GENERATOR needs to be
selected to get sys_rand32_get included in the build.

Fixes: #20587

Signed-off-by: David Leach <david.leach@nxp.com>
2019-11-15 10:13:15 -06:00
Andy Ross 11a050b2c3 kernel/sched: Fix edge case in MetaIRQ preemption of cooperative threads
When a MetaIRQ preempts a cooperative thread, that thread would be
added back to the generic run queue.  When the MetaIRQ is done, the
highest priority thread will be selected to run, which may obviously
be a cooperative thread of a higher priority than the one that was
preempted.

But that's wrong, because the original thread was promised that it
would NOT be preempted until it reached a scheduling point on its own
(that's the whole point of a cooperative thread, of course).

We need to track the thread that got preempted (one per CPU) and
return to it instead of whatever else the scheduler might have found.

Fixes #20255

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-11-15 13:09:02 +01:00
Krzysztof Chruscinski f831929cb5 kernel: Add assert to detect negative timeouts
Add assert when negative (except K_FOREVER) is passed as timeout.
Add negative timeout correction to 0.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2019-11-08 16:03:05 -08:00
Andrew Boie d2b8922fa3 kernel: allow threads to sleep forever
Previously, passing K_FOREVER to k_sleep() would return
immediately.

Forever is a long time. Even if woken up at some point,
we still had forever to sleep, so return K_FOREVER in this
case.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-09 00:36:34 +01:00
Andrew Boie e09a0255da kernel: sychronize irq_offload() access
Entering irq_offload() on multiple CPUs can cause
difficult to debug/reproduce crashes. Demote irq_offload()
to non-inline (it never needed to be inline anyway) and
wrap the arch call in a semaphore.

Some tests which were unnecessarily killing threads
have been fixed; these threads exit by themselves anyway
and we won't leave the semaphore dangling.

The definition of z_arch_irq_offload() moved to
arch_interface.h as it only gets called by kernel C code.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-08 15:16:43 -08:00
Andy Ross 8892406c1d kernel/sys_clock.h: Deprecate and convert uses of old conversions
Mark the old time conversion APIs deprecated, leave compatibility
macros in place, and replace all usage with the new API.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-11-08 11:08:58 +01:00
Andrew Boie 4f77c2ad53 kernel: rename z_arch_ to arch_
Promote the private z_arch_* namespace, which specifies
the interface between the core kernel and the
architecture code, to a new top-level namespace named
arch_*.

This allows our documentation generation to create
online documentation for this set of interfaces,
and this set of interfaces is worth treating in a
more formal way anyway.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-07 15:21:46 -08:00
Wayne Ren b1fbe85156 kernel: need to release spinlock before busy_wait
need to release spinlock first before busy_wait,
or other cores cannot get the spinlock when the holder is
busy waitting.

Signed-off-by: Wayne Ren <wei.ren@synopsys.com>
2019-11-07 16:54:56 -05:00
Andrew Boie 91468b5a04 kernel: fatal: show faulting CPU
Doing this in common code since we have an API for it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-06 18:11:09 -08:00
Stephanos Ioannidis 37d6241ecf kernel: Un-inline z_new_thread_init.
This commit modifies the z_new_thread_init function, that was
previously declared as ALWAYS_INLINE to be a normal function.

z_new_thread_init function is only called by the z_arch_new_thread
function and, since this is not a performance-critical function, there
is no good justification for inlining it.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2019-11-06 16:07:32 -08:00
Stephanos Ioannidis 2d7460482d headers: Refactor kernel and arch headers.
This commit refactors kernel and arch headers to establish a boundary
between private and public interface headers.

The refactoring strategy used in this commit is detailed in the issue

This commit introduces the following major changes:

1. Establish a clear boundary between private and public headers by
  removing "kernel/include" and "arch/*/include" from the global
  include paths. Ideally, only kernel/ and arch/*/ source files should
  reference the headers in these directories. If these headers must be
  used by a component, these include paths shall be manually added to
  the CMakeLists.txt file of the component. This is intended to
  discourage applications from including private kernel and arch
  headers either knowingly and unknowingly.

  - kernel/include/ (PRIVATE)
    This directory contains the private headers that provide private
   kernel definitions which should not be visible outside the kernel
   and arch source code. All public kernel definitions must be added
   to an appropriate header located under include/.

  - arch/*/include/ (PRIVATE)
    This directory contains the private headers that provide private
   architecture-specific definitions which should not be visible
   outside the arch and kernel source code. All public architecture-
   specific definitions must be added to an appropriate header located
   under include/arch/*/.

  - include/ AND include/sys/ (PUBLIC)
    This directory contains the public headers that provide public
   kernel definitions which can be referenced by both kernel and
   application code.

  - include/arch/*/ (PUBLIC)
    This directory contains the public headers that provide public
   architecture-specific definitions which can be referenced by both
   kernel and application code.

2. Split arch_interface.h into "kernel-to-arch interface" and "public
  arch interface" divisions.

  - kernel/include/kernel_arch_interface.h
    * provides private "kernel-to-arch interface" definition.
    * includes arch/*/include/kernel_arch_func.h to ensure that the
     interface function implementations are always available.
    * includes sys/arch_interface.h so that public arch interface
     definitions are automatically included when including this file.

  - arch/*/include/kernel_arch_func.h
    * provides architecture-specific "kernel-to-arch interface"
     implementation.
    * only the functions that will be used in kernel and arch source
     files are defined here.

  - include/sys/arch_interface.h
    * provides "public arch interface" definition.
    * includes include/arch/arch_inlines.h to ensure that the
     architecture-specific public inline interface function
     implementations are always available.

  - include/arch/arch_inlines.h
    * includes architecture-specific arch_inlines.h in
     include/arch/*/arch_inline.h.

  - include/arch/*/arch_inline.h
    * provides architecture-specific "public arch interface" inline
     function implementation.
    * supersedes include/sys/arch_inline.h.

3. Refactor kernel and the existing architecture implementations.

  - Remove circular dependency of kernel and arch headers. The
   following general rules should be observed:

    * Never include any private headers from public headers
    * Never include kernel_internal.h in kernel_arch_data.h
    * Always include kernel_arch_data.h from kernel_arch_func.h
    * Never include kernel.h from kernel_struct.h either directly or
     indirectly. Only add the kernel structures that must be referenced
     from public arch headers in this file.

  - Relocate syscall_handler.h to include/ so it can be used in the
   public code. This is necessary because many user-mode public codes
   reference the functions defined in this header.

  - Relocate kernel_arch_thread.h to include/arch/*/thread.h. This is
   necessary to provide architecture-specific thread definition for
   'struct k_thread' in kernel.h.

  - Remove any private header dependencies from public headers using
   the following methods:

    * If dependency is not required, simply omit
    * If dependency is required,
      - Relocate a portion of the required dependencies from the
       private header to an appropriate public header OR
      - Relocate the required private header to make it public.

This commit supersedes #20047, addresses #19666, and fixes #3056.

Signed-off-by: Stephanos Ioannidis <root@stephanos.io>
2019-11-06 16:07:32 -08:00
Andrew Boie 800b35f598 kernel: use uintptr_t for syscall arguments
We need to pass system call args using a register-width
data type and not hard-code this to u32_t.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-11-06 09:04:16 -08:00
Ulf Magnusson 1f38ea77ba kconfig: Clean up 'config FOO' (two spaces) definitions
Must've been copy-pasted around.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-04 17:31:27 -05:00
Ulf Magnusson bd6e04411e kconfig: Clean up header comments and make them consistent
Use this short header style in all Kconfig files:

    # <description>

    # <copyright>
    # <license>

    ...

Also change all <description>s from

    # Kconfig[.extension] - Foo-related options

to just

    # Foo-related options

It's clear enough that it's about Kconfig.

The <description> cleanup was done with this command, along with some
manual cleanup (big letter at the start, etc.)

    git ls-files '*Kconfig*' | \
        xargs sed -i -E '1 s/#\s*Kconfig[\w.-]*\s*-\s*/# /'

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-04 17:31:27 -05:00
Flavio Ceolin 394f66b77e kernel: canaries: Add terminator character
Add one character into stack canary.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-11-03 12:46:34 +01:00
Ulf Magnusson 975de21858 kconfig: Global whitespace/consistency cleanup
Clean up space errors and use a consistent style throughout the Kconfig
files. This makes reading the Kconfig files more distraction-free, helps
with grepping, and encourages the same style getting copied around
everywhere (meaning another pass hopefully won't be needed).

Go for the most common style:

 - Indent properties with a single tab, including for choices.

   Properties on choices work exactly the same syntactically as
   properties on symbols, so not sure how the no-indentation thing
   happened.

 - Indent help texts with a tab followed by two spaces

 - Put a space between 'config' and the symbol name, not a tab. This
   also helps when grepping for definitions.

 - Do '# A comment' instead of '#A comment'

I tweaked Kconfiglib a bit to find most of the stuff.

Some help texts were reflowed to 79 columns with 'gq' in Vim as well,
though not all, because I was afraid I'd accidentally mess up
formatting.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2019-11-01 15:53:23 +01:00
Ioannis Glaropoulos df02923944 kernel: fatal: use nested exception info in z_fatal_error
In z_fatal_error() we invoke the arch-specific API that
evaluates whether we are in a nested exception. We then
use the result to log a message that the error occurred
in ISR. In non-test mode, we unconditionally panic, if
an exception has occurred in an ISR and the fatal error
handler has not returned (apart from the case of an
error in stack sentinel check).

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-10-24 10:12:08 -07:00
Andrew Boie 979b17f243 kernel: activate arch interface headers
Duplicate definitions elsewhere have been removed.

A couple functions which are defined by the arch interface
to be non-inline, but were implemented inline by native_posix
and intel64, have been moved to non-inline.

Some missing conditional compilation for z_arch_irq_offload()
has been fixed, as this is an optional feature.

Some massaging of native_posix headers to get everything
in the right scope.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-10-21 10:13:38 -07:00
Andy Ross 8bc3b6f673 arch/x86/intel64: Fix assumption with dummy threads
The intel64 switch implementation doesn't actually use a switch handle
per se, just the raw thread struct pointers which get stored into the
handle field.  This works fine for normally initialized threads, but
when switching out of a dummy thread at initialization, nothing has
initialized that field and the code was dumping registers into the
bottom of memory through the resulting NULL pointer.

Fix this by skipping the load of the field value and just using an
offset instead to get the struct address, which is actually slightly
faster anyway (a SUB immediate instruction vs. the load).

Actually for extra credit we could even move the switch_handle field
to the top of the thread struct and eliminate the instruction
entirely, though if we did that it's probably worth adding some
conditional code to make the switch_handle field disappear entirely.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-10-19 12:09:32 -07:00
Andrew Boie 8ffff144ea kernel: add architecture interface headers
include/sys/arch_inlines.h will contain all architecture APIs
that are used by public inline functions and macros,
with implementations deriving from include/arch/cpu.h.

kernel/include/arch_interface.h will contain everything
else, with implementations deriving from
arch/*/include/kernel_arch_func.h.

Instances of duplicate documentation for these APIs have been
removed; implementation details have been left in place.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-10-11 13:30:46 -07:00
Peter Bigot e28f330a8e coccinelle: standardize k_thread create/define calls with integer timeouts
Re-run with updated script to convert integer literal delay arguments
to k_thread_create and K_THREAD_DEFINE to use the standard timeout
macros.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-10-09 08:38:10 -04:00
Charles E. Youse 64300a7ec3 kernel/Kconfig: clamp number of CPUs to 4
This maximum is implicit in the kernel support for SMP, e.g.,
kernel/init.c and kernel/smp.c assume CONFIG_MP_NUM_CPUS <= 4.

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-10-07 19:46:55 -04:00
Nicolas Pitre d12462ca6c k_mem_pool_alloc(): remove dead code
A loop in k_mem_pool_alloc() around z_sys_mem_pool_block_alloc() assumes
the later may return -EAGAIN with an elaborate comment about it. But
-EAGAIN is no longer returned by that function since commit 7845e1b01e
("lib/mempool: Fix spurious -ENOMEM due to agressive latency control").

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-10-04 18:43:33 -07:00
Piotr Zięcik 19d8349aa5 kernel: Introduce k_work_poll
This commit adds new k_work_poll interface. It allows to
submit given work to a workqueue automatically when one of the
watched pollable objects changes its state.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-10-04 17:15:17 +02:00
Piotr Zięcik 1c4177d10f kernel: Separate k_poll() infrastructure and implementation
This commit separates k_poll() infrastructure from k_poll() API
implementation, allowing other (future) API calls to use the same
framework.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2019-10-04 17:15:17 +02:00
Kumar Gala bc18159676 kernel: Fix gcc-9.2 warning with _StackCheckHandler
Remove FUNC_NORETURN attribute from _StackCheckHandler to address the
following warning from gcc-9.2:

kernel/compiler_stack_protect.c:62:32: error: '__stack_chk_fail'
specifies less restrictive attribute than its target
'_StackCheckHandler': 'noreturn' [-Werror=missing-attributes]

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-10-04 05:22:30 -07:00
Andrew Boie cb1dd7465b kernel: remove vestigal printk references
Logging is now used for these situations.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-10-01 16:15:06 -05:00
Andrew Boie 99b3f8617e kernel: use logging for userspace errors
We want to use a single API for this in kernel code.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-10-01 10:23:03 -07:00
Andrew Boie 144f2cb2b3 logging: abstract log_core_init()
Similar to how LOG_INIT(), LOG_PANIC(), etc are
wrapped.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-10-01 09:24:02 -04:00
Andrew Boie 8f0bb6afe6 tracing: simplify idle thread detection
We now define z_is_idle_thread_object() in ksched.h,
and the repeated definitions of a function that does
the same thing now changed to just use the common
definition.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie 0095ed5384 kernel: rename z_is_idle_thread()
This takes an entry point and not a thread as argument.
Rename to z_is_idle_thread_entry() to make this clearer.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie 2c1fb971e0 kernel: rename __swap
This is part of the core kernel -> architecture API and
has been renamed to z_arch_swap().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie fe031611fd kernel: rename main/idle thread/stacks
The main and idle threads, and their associated stacks,
were being referenced in various parts of the kernel
with no central definition. Expose these in kernel_internal.h
and namespace with z_ appropriately.

The main and idle threads were being defined statically,
with another variable exposed to contain their pointer
value. This wastes a bit of memory and isn't accessible
to user threads anyway, just expose the actual thread
objects.

Redundance MAIN_STACK_SIZE and IDLE_STACK_SIZE defines
in init.c removed, just use the Kconfigs they derive
from.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie e6654103ba kernel: rename boot time globals
These are renamed to z_timestamp_main and z_timestamp_idle,
and now specified in kernel_internal.h.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie f6fb634b89 kernel: rename kernel_arch_init()
This is part of the core kernel -> architecture interface and
has been renamed z_arch_kernel_init().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie 4ad9f687df kernel: rename thread return value functions
z_set_thread_return_value is part of the core kernel -> arch
interface and has been renamed to z_arch_thread_return_value_set.

z_set_thread_return_value_with_data renamed to
z_thread_return_value_set_with_data for consistency.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie 845aa6d114 kernel: renamespace arch_nop()
This is part of the core kernel -> architecture interface
and has been renamed to z_arch_nop().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie e1ec59f9c2 kernel: renamespace z_is_in_isr()
This is part of the core kernel -> architecture interface
and is appropriately renamed z_arch_is_in_isr().

References from test cases changed to k_is_in_isr().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie 61901ccb4c kernel: rename z_new_thread()
This is part of the core kernel -> architecture interface
and should have a leading prefix z_arch_.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Andrew Boie 9e1dda8804 timing_info: rename globals
Global variables related to timing information have been
renamed to be prefixed with z_arch, with naming arranged
in increasing order of specificity.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-30 15:25:55 -04:00
Anas Nashif 0bf1f9a408 tracing: add missing end_call for k_mutex_unlock
k_mutex_unlock had no end_call tracing call.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-09-30 10:49:37 -04:00
Anas Nashif 4abbd54cd5 tracing: remove useless ifdefing for CONFIG_TRACING
Tracing functions are noop if CONFIG_TRACING is disabled.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-09-30 10:49:37 -04:00
Charles E. Youse c0c4ba8516 kernel/idle.c: fix compilation failure (SMP && !SCHED_IPI_SUPPORTED)
An #endif and the brace terminating a compound statement were
transposed, causing compilation errors with the above-specified
combination of configuration options.

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-09-28 17:32:33 -04:00
Peter A. Bigot 5639ea07f8 kernel: timeout: remove unused callback parameter from init function
The callback function has been ignored in z_timeout_init() since the
timer rework in fall 2018.  Passing real handlers to it in code is
distracting when they will be overridden by whatever callback is
provided in z_add_timeout().

As this function is an internal API deprecation is not necessary.
Remove the parameter and change all call sites to drop the argument.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-09-28 15:41:18 -04:00
Jan Van Winkel 677050c2af kernel/idle: Correct SMP_FALLBACK define
Corrected the define of SMP_FALLBACK to prevent llvm warning.

llvm issues a warning as the behaviour of using defined(x) inside a
macro expansion is undefined (https://reviews.llvm.org/D15866).

Signed-off-by: Jan Van Winkel <jan.van_winkel@dxplore.eu>
2019-09-27 20:32:26 -04:00
Wayne Ren 76a3235ad2 kernel: fix the bug in atomic_c.c
* USERSPACE -> CONFIG_USERSPACE
* fix the wrong paramter type

Signed-off-by: Wayne Ren <wei.ren@synopsys.com>
2019-09-26 21:13:20 -04:00
Andy Ross d82f76a0bb kernel/sched: Don't make an IPI if we don't need it
If an architecture declares support for IPI, we still want to use it
only when running in SMP mode.

(This also fixes a build failure on ARC, which declares
CONFIG_SCHED_IPI_SUPPORTED but doesn't actually implement
z_arch_sched_ipi() yet).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Andy Ross 6a153efc1b kernel/timeout: Fix timeslicing edge case in SMP
The timeout code has an optimization where it refuses to send a new
timeout to the driver unless it is sooner than one already scheduled.
This won't work on SMP, though, because the timeout value when
timeslicing is enabled depends on the current thread, and on SMP the
decision as to the next thread will not be made until later (when we
swap, or exit an interrupt).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Andy Ross 11bd67db53 kernel/idle: Use normal idle in SMP when IPI is available
Now that we have a working IPI framework, there's no reason for the
default spin loop for the SMP idle thread.  Just use the default
platform idle and send an IPI when a new thread is readied.

Long term, this can be optimized if necessary (e.g. only send the IPI
to idling CPUs, or check priorities, etc...), but for a 2-cpu system
this is a very reasonable default.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Andy Ross 6c283ca3d0 kernel/thread: Must always initialize is_idle field
Our thread struct gets initialized piecewise in a bunch of locations
(this is sort of a design flaw).  The is_idle field, which was
introduced to identify idle threads in SMP (where there can be more
than one), was correctly set for idle threads but was being left
uninitialized elsewhere, and in a tiny handful of cases was turning up
nonzero.

The case in pipes. was particularly vexsome, as that isn't a thread at
all but one of the "dummy" threads used for timeouts (another design
flaw IMHO).

Get this right everywhere.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Andy Ross cb3964f04f kernel/sched: Reset time slice on swap in SMP
In uniprocessor mode, the kernel knows when a context switch "is
coming" because of the cache optimization and can use that to do
things like update time slice state.  But on SMP the scheduler state
may be updated on the other CPU at any time, so we don't know that a
switch is going to happen until the last minute.

Expose reset_time_slice() as a public function and call it when needed
out of z_swap().

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Andy Ross d442927667 kernel/sched: Add missing SMP thread abort case
The loop in thread abort on SMP where we wait for the results on an
IPI correctly handled the case where a thread running on another CPU
gets its interrupt and self-aborts, but it missed the case where the
other thread pends before receiving the interrupt.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Andy Ross b0158cc81f kernel/sched: Fix reschedule points in SMP
There were two related bugs when in SMP mode:

1. Underneath z_reschedule(), the code was inexplicably checking the
   swap_ok flag on the current CPU to see if it was OK to preempt the
   current thread, but reschedule is the DEFINITION of a schedule
   point and we always want to swap, even if the current thread is
   non-preemptible.

2. With similar symptoms: in k_yield() a previous fix correct the
   queue handling for SMP, but it missed the case where a thread of
   the SAME priority as _current was on the queue and would fail to
   swap.  Yielding must always add the current thread to the back of
   the current priority.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-26 16:54:06 -04:00
Jim Shu e124670f0b kernel/spinlock: Fix a SMP race condition of SPIN_VALIDATE
z_spin_lock_valid() reads shared variable twice to do two checkings. If
this variable is modified by other CPU between two read accesses, the
checking value is inconsistent. This inconsistency causes the error
that CPU0 can pass the checking when it doesn't hold spinlock because
zeroed-out thread_cpu value is ambiguous with the CPU0 ID.

Fix the inconsistency by only reading shared variable once and using
local variable value to do two checkings.

Fixes #19299.

Signed-off-by: Jim Shu <cwshu@andestech.com>
2019-09-26 16:51:38 -04:00
Charles E. Youse 3036faf88a tests/benchmarks: fix BOOT_TIME_MEASUREMENT
The boot time measurement sample was giving bogus values on x86: an
assumption was made that the system timer is in sync with the CPU TSC,
which is not the case on most x86 boards.

Boot time measurements are no longer permitted unless the timer source
is the local APIC. To avoid issues of TSC scaling, the startup datum
has been forced to 0, which is in line with the ARM implementation
(which is the only other platform which supports this feature).

Cleanups along the way:

As the datum is now assumed zero, some variables are removed and
calculations simplified. The global variables involved in boot time
measurements are moved to the kernel.h header rather than being
redeclared in every place they are referenced. Since none of the
measurements actually use 64-bit precision, the samples are reduced
to 32-bit quantities.

In addition, this feature has been enabled in long mode.

Fixes: #19144

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-09-21 16:43:26 -07:00
Nicholas Lowell 5b322d9331 debug: tracing: add sys_trace_thread_name_set
Initial thread creation and tracing information
occurs with empty thread names.  For better tracing information,
we need to a way to get actual thread names if they are set
in order to better track thread names and their IDs.

Signed-off-by: Nicholas Lowell <nlowell@lexmark.com>
2019-09-19 00:37:35 -04:00
Steven Wang 2b2fa660b0 [Code coverage]: Fix the issue of function code coverage in device.c.
It was reported in the code coverage report that Z_SYSCALL_HANDLER() was
not called by other code, if we run "sanitycheck -p qemu_x86 --coverage
-T tests/kernel/device/".

The root cause is that we include "errno.h", which includes
"include/generated/syscalls/device.h". It causes that the
declare of device_get_binding() in "include/generated/syscalls/device.h"
is marked as "has been called", rather than Z_SYSCALL_HANDLER()
in device.c.

So I remove "#include <errno.h>", which is useless in device.c. Also,
"#include <sys/util.h>" is removed for the same reason.

Signed-off-by: Steven Wang <steven.l.wang@linux.intel.com>
2019-09-17 12:35:30 +08:00
Andrew Boie a470ba1999 kernel: remove z_fatal_print()
Use LOG_ERR instead.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-09-12 05:17:39 -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 075c94f6e2 kernel: Port remaining syscalls to new API
These calls are not accessible in CI test, nor do they get built on
common platforms (in at least one case I found a typo which proved the
code was truly unused).  These changes are blind, so live in a
separate commit.  But the nature of the port is mechanical, all other
syscalls in the system work fine, and any errors should be easily
corrected.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Andy Ross 346cce31d8 kernel: Port remaining buildable syscalls to new API
These calls are buildable on common sanitycheck platforms, but are not
invoked at runtime in any tests accessible to CI.  The changes are
mostly mechanical, so the risk is low, but this commit is separated
from the main API change to allow for more careful review.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Andy Ross 6564974bae userspace: Support for split 64 bit arguments
System call arguments, at the arch layer, are single words.  So
passing wider values requires splitting them into two registers at
call time.  This gets even more complicated for values (e.g
k_timeout_t) that may have different sizes depending on configuration.
This patch adds a feature to gen_syscalls.py to detect functions with
wide arguments and automatically generates code to split/unsplit them.

Unfortunately the current scheme of Z_SYSCALL_DECLARE_* macros won't
work with functions like this, because for N arguments (our current
maximum N is 10) there are 2^N possible configurations of argument
widths.  So this generates the complete functions for each handler and
wrapper, effectively doing in python what was originally done in the
preprocessor.

Another complexity is that traditional the z_hdlr_*() function for a
system call has taken the raw list of word arguments, which does not
work when some of those arguments must be 64 bit types.  So instead of
using a single Z_SYSCALL_HANDLER macro, this splits the job of
z_hdlr_*() into two steps: An automatically-generated unmarshalling
function, z_mrsh_*(), which then calls a user-supplied verification
function z_vrfy_*().  The verification function is typesafe, and is a
simple C function with exactly the same argument and return signature
as the syscall impl function.  It is also not responsible for
validating the pointers to the extra parameter array or a wide return
value, that code gets automatically generated.

This commit includes new vrfy/msrh handling for all syscalls invoked
during CI runs.  Future commits will port the less testable code.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-09-12 11:31:50 +08:00
Pavlo Hamov 8076c8095b subsystem: kernel_shell: extend thread info
1) Dump time sinse last scheduler call
Could be handy for tickless kernel debug.
Will indicate that no rtc irq is called

2) Dump current timeout of each thread
Could be used to find yout when thread will wake up

3) Dump human friendly thread state

4) Use shell_prin instead shell_fprintf

Signed-off-by: Pavlo Hamov <pavlo_hamov@jabil.com>
2019-09-08 12:39:58 +02:00
Andrew Boie 90e6536053 kernel: fix default z_arch_cpu_halt()
k_cpu_idle() re-enables interrupts. Just spin
instead.

Fixes: #18973

Signed-off-by: Andrew Boie <andrewboie@gmail.com>
2019-09-07 09:57:40 -04:00
Peter Bigot a6067a38f8 kernel: reimplement k_uptime_get_32()
The current implementation does not return the low 32 bits of
k_uptime_get() as suggested by it's documentation; it returns the number
of milliseconds represented by the low 32-bits of the underlying system
clock.  The truncation before translation results in discontinuities at
every point where the system clock increments bit 33.

Reimplement it using the full-precision value, and update the
documentation to note that this variant has little value for
long-running applications.

Closes #18739.

Signed-off-by: Peter Bigot <peter.bigot@nordicsemi.no>
2019-09-03 22:50:41 +02:00
Peng Su 1084f48259 kernel: ignore z_fatal_halt() from code coverage
The reason we decide to ignore it in code coverage:
1.No test case can cover the function for code coverage.
2.Even if we added a test for testing, it would be marked as
  "never be called by other code" because the function cause
  CPU halted and it can't return.

Signed-off-by: Peng Su <peng.su@intel.com>
2019-08-24 23:40:22 +02:00
Andy Ross 6f13980fc7 kernel/mutex: Fix locking to be SMP-safe
The mutex locking was written to use k_sched_lock(), which doesn't
work as a synchronization primitive if there is another CPU running
(it prevents the current CPU from preempting the thread, it says
nothing about what the others are doing).

Use the pre-existing spinlock for all synchronization.  One wrinkle is
that the priority code was needing to call z_thread_priority_set(),
which is a rescheduling call that cannot be called with a lock held.
So that got split out with a low level utility that can update the
schedule state but allow the caller to defer yielding until later.

Fixes #17584

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-08-22 17:58:16 -04:00
Andrew Boie b6d961b7d4 kernel: remove log system support for fatal msgs
This needs further design work due to problems with logging
C strings. Just send always to printk() for now until this
is resolved.

Fixes: #18052

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-08-07 10:14:12 -07:00
Andrew Boie 00bf76eaa7 kernel: add z_fatal_halt() to interface
Intended to be called from application-level implementations
of k_sys_fatal_error_handler().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-08-06 19:32:22 -07:00
Yasushi SHOJI 20d072465d kernel: sched: Do not force preempt when k_sched_unlock()
The scheduler lock is a nestable lock.  Unlocking a nested,
still-having, lock shouldn't preempt the current thread.

	k_sched_lock();
	k_sched_lock();
	k_sched_unlock();  /* <--- this shouldn't be a scheduling point */
	k_sched_unlock();  /* <--- this is a scheduling point */

This commit changes the preempt_ok argument from 1 to 0.  This let
should_preempt() check whether it should preempt at the point or not.

This fixes #17869.

Signed-off-by: Yasushi SHOJI <y-shoji@ispace-inc.com>
2019-08-06 10:19:50 +02:00
Andrew Boie 8915e41b7b userspace: adjust arch memory domain interface
The current API was assuming too much, in that it expected that
arch-specific memory domain configuration is only maintained
in some global area, and updates to domains that are not currently
active have no effect.

This was true when all memory domain state was tracked in page
tables or MPU registers, but no longer works when arch-specific
memory management information is stored in thread-specific areas.

This is needed for: #13441 #13074 #15135

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-08-05 13:25:50 +02:00
Andrew Boie 7fae2bbc18 tests: increase main stack size for x86 with ztest
Some options like stack canaries use more stack space,
and on x86 this is not quite enough for ztest's main
thread stack to be 512 bytes.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-08-05 13:25:50 +02:00
Andrew Boie f281b74c56 userspace: set stack object earlier
Populate thread->stack_obj earlier in the thread initialization
process such that it is set when z_new_thread() is called.

There was nothing specific about its position, or the rest of
the code in that CONFIG_USERSPACE block, so just move it all up..

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-08-05 13:25:50 +02:00
Nicolas Pitre 1f4b5ddd0f riscv32: rename to riscv
With the upcoming riscv64 support, it is best to use "riscv" as the
subdirectory name and common symbols as riscv32 and riscv64 support
code is almost identical. Then later decide whether 32-bit or 64-bit
compilation is wanted.

Redirects for the web documentation are also included.

Then zephyrbot complained about this:

"
New files added that are not covered in CODEOWNERS:

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

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

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

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-08-02 13:54:48 -07:00
Robert Lubos e9cdcc235f kernel: timeout: Fix macro usage in next_timeout function
The `next_timeout()` function used to call the `elapsed()` function
directly in the `MAX` macro call. This caused the `elapsed()` function
to be executed twice, with possible different results, if the system
clock incremented its value in a meantime.

As a result, the whole `MAX(0, to->dticks - elapsed()` expresion could
return an incorrect value of -1, which represents the K_FOREVER timeout.
This led to a stall in devices running tickless kernel (as observed on
nRF52840).

Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
2019-08-01 12:28:44 +02:00
Andrew Boie 81ef42d2bc sanitycheck: simplify fault detection
Any fatal error will print "ZEPHYR FATAL ERROR" now, so
we don't have to maintain a set of strings in the
sanitycheck harness.py

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-25 15:06:58 -07:00
Andrew Boie 96571a8c40 kernel: rename NANO_ESF
This is now called z_arch_esf_t, conforming to our naming
convention.

This needs to remain a typedef due to how our offset generation
header mechanism works.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-25 15:06:58 -07:00
Andrew Boie 8a9e8e0cd7 kernel: support log system for fatal errors
We introduce a new z_fatal_print() API and replace all
occurrences of exception handling code to use it.
This routes messages to the logging subsystem if enabled.
Otherwise, messages are sent to printk().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-25 15:06:58 -07:00
Andrew Boie 71ce8ceb18 kernel: consolidate error handling code
* z_NanoFatalErrorHandler() is now moved to common kernel code
  and renamed z_fatal_error(). Arches dump arch-specific info
  before calling.
* z_SysFatalErrorHandler() is now moved to common kernel code
  and renamed k_sys_fatal_error_handler(). It is now much simpler;
  the default policy is simply to lock interrupts and halt the system.
  If an implementation of this function returns, then the currently
  running thread is aborted.
* New arch-specific APIs introduced:
  - z_arch_system_halt() simply powers off or halts the system.
* We now have a standard set of fatal exception reason codes,
  namespaced under K_ERR_*
* CONFIG_SIMPLE_FATAL_ERROR_HANDLER deleted
* LOG_PANIC() calls moved to k_sys_fatal_error_handler()

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-25 15:06:58 -07:00
Wentong Wu 2463ded4c8 kernel: timeout: do not active time slicing if idle thread ready
zero slice_ticks when can't time slice so that next_timeout will
ignore slice_ticks of _current_cpu and system can stay low power
state longer time.

Fixes: #17368.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-07-24 14:02:23 -07:00
Alexander Wachter b4c5f4b32b linker: Add dtcm section for Cortex M7 MCUs
This commit adds a DTCM (Device Tightly Coupled Memory) section for
Cortex F7 MCUs. The Address and length is defined in the corresponding
device tree file.

Signed-off-by: Alexander Wachter <alexander.wachter@student.tugraz.at>
2019-07-19 10:05:46 +02:00
Nicholas Lowell f9ae2d8e64 Includes: #ifdef CONFIG_USE_SWITCH instead of #if to avoid undef warning
Hitting wundef in kernel_structs.h, switching to match other instances
where #ifdef is used instead of #if

Signed-off-by: Nicholas Lowell <nlowell@lexmark.com>
2019-07-14 04:58:47 -07:00
Andy Ross 4d8e1f223b kernel/sched: Fix k_thread_priority_set() on SMP
On SMP systems, currently scheduled threads are not in the run queue
and can't be unconditionally removoed/added.

Fixes #17170

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-07-12 14:09:16 -07:00
Ioannis Glaropoulos 0e67759985 kernel: fix #endif quard error for k_float_disable
The implementation of z_impl_float_disable was missplaced
inside the #ifdef SPIN_VALIDATE. Fixing it.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-07-10 13:44:02 -07:00
Anas Nashif 7bde81f467 kernel: msgq: avoid single char variables for msgq
Use msqgq instead of the short and confusing q.

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

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-07-03 14:17:29 -07:00
Andy Ross 905209ba7d kernel/mempool: Fix ticks/ms confusion
The mempool blocking implementation was mixing tick and millisecond
APIs.  Get it right.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-07-02 22:52:29 -04:00
Andy Ross ed7d86310f kernel/sched: Interpret zero timeslice time correctly
The scheduler API has always allowed setting a zero slice size as a
way to disable timeslicing.  But the workaround introduced for
CONFIG_SWAP_NONATOMIC forgot that convention, and was calling
reset_time_slice() with that zero value (i.e. requesting an immediate
interrupt) in circumstances where z_swap() had been interrupted
nonatomically.

In practice, this never happened.  And if it did, it was a single
spurious no-op interrupt that no one cared about.  Until it did,
anyway...

Now that ticks on nRF devices are at full 32 kHz speed, we can get
into a situation where the rapidly triggering timeslice interrupts are
interrupting z_swap() calls, and the process feeds back on itself and
becomes self-sustaining.

Put that test into the time slice code itself to prevent this kind of
mistake in the future.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-07-02 22:52:29 -04:00
Andy Ross 669730f030 kernel: Crank up default tick rate
When tickless is available, all existing devices can handle much
higher timing precision than 10ms.  A 10kHz default seems acceptable
without introducing too much range limitation (rollover for a signed
time delta will happen at 2.5 days).  Leave the 100 Hz default in
place for ticked configurations, as those are going to be special
purpose usages where the user probably actually cares about interrupt
rate.

Note that the defaulting logic interacts with an obscure trick:
setting the tick rate to zero would indicate "no clock exists" to the
configuration (some platforms use this to drop code from the build).
But now that becomes a kconfig cycle, so to break it we expose
CONFIG_SYS_CLOCK_EXISTS as an app-defined tunable and not a derived
value from the tick rate.  Only one test actually did this.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-07-02 22:52:29 -04:00
Ioannis Glaropoulos 5d423b8078 userspace: minor typo fixes in various places
System call arguments are indexed from 1 to 6, so arg0
is corrected to arg1 in two occasions. In addition, the
ARM function for system calls is now called z_arm_do_syscall,
so we update the inline comment in __svc handler.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-07-02 19:18:48 -04:00
Andrew Boie 38129ce1a6 kernel: fix CONFIG_THREAD_NAME from user mode.
This mechanism had multiple problems:

- Missing parameter documentation strings.
- Multiple calls to k_thread_name_set() from user
  mode would leak memory, since the copied string was never
  freed
- k_thread_name_get() returns memory to user mode
  with no guarantees on whether user mode can actually
  read it; in the case where the string was in thread
  resource pool memory (which happens when k_thread_name_set()
  is called from user mode) it would never be readable.
- There was no test case coverage for these functions
  from user mode.

To properly fix this, thread objects now have a buffer region
reserved specifically for the thread name. Setting the thread
name copies the string into the buffer. Getting the thread name
with k_thread_name_get() still returns a pointer, but the
system call has been removed. A new API k_thread_name_copy()
is introduced to copy the thread name into a destination buffer,
and a system call has been provided for that instead.

We now have full test case coverge for these APIs in both user
and supervisor mode.

Some of the code has been cleaned up to place system call
handler functions in proximity with their implementations.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-01 16:29:45 -07:00
Andrew Boie 8753becbe1 kernel: delete k_futex_init()
There's no need for a system call for this; futexes live in
user memory and the initialization bit is ignored.

It's sufficient to just do an atomic_set().

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-07-01 08:15:10 -07:00
Andy Ross 1db9f18a08 kernel/timeout: Remove "clock_always_on", replace with "SLOPPY_IDLE"
This is an oddball API.  It's untested.  In fact testing its proper
behavior requires very elaborate automation (you need a device outside
the Zephyr hardware to measure real world time, and a mechanism for
getting the device into and out of idle without using the timer
driver).  And this makes for needless difficulty managing code
coverage metrics.

It was always just a hint anyway.  Mark the old API deprecated and
replace it with a kconfig tunable.  The effect of that is just to
change the timeout value passed to the timer driver, where we can
manage code coverage metrics more easily (only one driver cares to
actually support this feature anyway).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-06-28 14:24:56 -07:00
Anas Nashif efb8df5366 cleanup: include/: move misc/stack.h to debug/stack.h
move misc/stack.h to debug/stack.h and
create a shim for backward-compatibility.

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

Related to #16539

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

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

Related to #16539

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

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

Related to #16539

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

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

Related to #16539

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

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

Related to #16539

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

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

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif ee9dd1a54a cleanup: include/: move misc/dlist.h to sys/dlist.h
move misc/dlist.h to sys/dlist.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 969f8f1c68 cleanup: include/: move entropy.h to drivers/entropy.h
move entropy.h to drivers/entropy.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 ef281c4237 cleanup: include/: move sys_io.h to sys/sys_io.h
move sys_io.h to sys/sys_io.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 190e368275 cleanup: include/: move power.h to power/power.h
move power.h to power/power.h and
create a shim for backward-compatibility.

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

Related to #16539

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

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

Related to #16539

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-27 22:55:49 -04:00
Anas Nashif 10291a0789 cleanup: include/: move tracing.h to debug/tracing.h
move tracing.h to debug/tracing.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 659fa0d57d lifo/fifo: first word is not always first 4 bytes
The first word is used as a pointer, meaning it is 64 bits on 64-bit
systems. To reserve it, it has to be either a pointer, a long, or an
intptr_t. Not an int nor an u32_t.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-26 09:08:42 -04:00
Ioannis Glaropoulos 39c8451422 kernel: mem_domain: fix warning in ASSERT expression
While fixing the ASSERT expressions in mem_domain.c to use
%lx instead of %x for uintptr_t variables, commit
f32330b22c has overlooked
one ASSERT expression specific to ARMv8-M. This causes
printk compilation warnings for ARMv8-M builds, so we
provide a fix here.

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

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

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

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

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

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

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-25 23:29:22 -04:00
Andrew Boie 777336ef38 tests: userspace: cover missing/bad syscalls
We were missing code coverage for bad or unimplemented
system call IDs.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-25 17:28:19 -07:00
Andrew Boie aade2b5a20 kernel: offsets: exclude from coverage
None of this is runtime code.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-25 17:22:34 -07:00
Anas Nashif 68c389c1f8 include: move system timer headers to include/drivers/timer/
Move internal and architecture specific headers from include/drivers to
subfolder for timer:

   include/drivers/timer

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-25 15:27:00 -04:00
Wentong Wu 5611e92347 kernel: add futex support
A k_futex is a lightweight mutual exclusion primitive designed
to minimize kernel involvement. Uncontended operation relies
only on atomic access to shared memory. k_futex structure lives
in application memory. And when using futexes, the majority of
the synchronization operations are performed in user mode. A
user-mode thread employs the futex wait system call only when
it is likely that the program has to block for a longer time
until the condition becomes true. When the condition comes true,
futex wake operation will be used to wake up one or more threads
waiting on that futex.

This patch implements two futex operations: k_futex_wait and
k_futex_wake. For k_futex_wait, the comparison with the expected
value, and starting to sleep are performed atomically to prevent
lost wake-ups. If different context changed futex's value after
the calling use-mode thread decided to block himself based on
the old value, the comparison will help observing the value
change and will not start to sleep. And for k_futex_wake, it
will wake at most num_waiters of the waiters that are sleeping
on that futex. But no guarantees are made on which threads are
woken, that means scheduling priority is not taken into
consideration.

Fixes: #14493.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-06-24 15:38:21 -07:00
Nicolas Pitre bc30f4f019 mem_slab: rationalize block alignment assertion
The block alignment must be enforced for statically allocated slabs
as well as runtime initialized ones. It is best to implement this
check only once in create_free_list() which is invoked by both
k_mem_slab_init() and init_mem_slab_module(), where pointers are about
to be set for the first time. It is then unnecessary to perform this
test on every slab allocation as the alignment won't change at that
point.

And not only the block size needs to be aligned, but the buffer
as well.

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

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-19 15:34:13 -05:00
Marc Herbert d4df6bade1 BOOT_BANNER: show KERNEL_VERSION and BUILD_VERSION differently
Zephyr has two unrelated build _VERSIONs: KERNEL_VERSION and
BUILD_VERSION. Prefix them slightly differently in BOOT_BANNER so anyone
can instantly zoom in on which one is being used without having to
compare the implementation details of both.

Signed-off-by: Marc Herbert <marc.herbert@intel.com>
2019-06-19 15:48:08 -04:00
Andrew Boie 676b1ae93a kernel: idle: exclude no-op funcs from coverage
These get overridden anyway.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-18 09:08:01 -04:00
Andrew Boie 3f974243be kernel: allow k_sleep(K_FOREVER)
Threads that are sleeping forever may be woken up with
k_wakeup(), this shouldn't fail assertions.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-18 09:08:01 -04:00
Andrew Boie c5164f328b kernel: init: exclude unreachable code
LCOV/gcovr doesn't understand what CODE_UNREACHABLE means.
Adding LCOV_EXCL_LINE to the macro definition unfortunately
doesn't work.

Exclude a bit of code which spins endlessly when multi-
threading is disabled that runs after the coverage report
is dumped.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-18 09:08:01 -04:00
Andrew Boie 8e053330fe kernel: init: fix coverage gap
We don't get any coverage past when we dump the coverage data,
so exclude the end of the function and move setting the main
thread as nonessential to immediately before the coverage dump.
The comment was also amended.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-18 09:08:01 -04:00
Andrew Boie fe228a8184 kernel: init: exclude some funcs from coverage
data copying and bss zero are called from arch code
before z_cstart(), and coverage data gathering doesn't
work properly at that point. Not all arches use this
code anyway, some do it in optimized assembly instead.

Weak main() is also excluded; it does nothing and every
test overrides it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-06-18 09:08:01 -04:00
Nicolas Pitre 3d51f7c266 k_stack: make it 64-bit compatible
The k_stack data type cannot be u32_t on a 64-bit system as it is
often used to store pointers. Let's define a dedicated type for stack
data values, namely stack_data_t, which can be adjusted accordingly.
For now it is defined to uintptr_t which is the integer type large
enough to hold a pointer, meaning it is equivalent to u32_t on 32-bit
systems and u64_t on 64-bit systems.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-14 05:46:29 -04:00
Ioannis Glaropoulos a6cb8b06db kernel: introduce k_float_disable system call
We introduce k_float_disable() system call, to allow threads to
disable floating point context preservation. The system call is
to be used in FP Sharing Registers mode (CONFIG_FP_SHARING=y).

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-06-12 09:17:45 -07:00
Anas Nashif 6e27d6d3d1 mbedtls: move to external module
Use external module from https://github.com/zephyrproject-rtos/mbedtls

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-11 08:33:53 -04:00
Marek Pieta b83f99a14c debug: tracing: Fix tracing hooks
Change removes tracing hooks before threads are initialized
and thread switched out hook for ARM before first time switching
to main thread.

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
2019-06-07 06:56:39 -04:00
Nicolas Pitre aa9228854f linker generated list: provide an iterator to simplify list access
Given that the section name and boundary simbols can be inferred from
the struct object name, it makes sense to create an iterator that
abstracts away the access details and reduce the possibility for
mistakes.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-06 14:21:32 -07:00
Andy Ross a12f2d6666 kernel/smp: Rename smp_init()
This name collides with one in the bt subsystem, and wasn't named in
proper zephyrese anyway.

Fixes #16604

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-06-05 17:15:55 -04:00
Anas Nashif 6d359df592 logging: use os as a domain for low level system debugging
We had both kernel and os as domains covering low level layers, just use
one and fix the issue of the os domain not being registered.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-04 12:16:40 -07:00
Nicolas Pitre 58d839bc3c misc: memory address type conversions
The uintptr_t type is more appropriate to represent memory addresses
than u32_t.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-06-03 21:14:57 -04:00
Andy Ross 312b43f145 kernel/sched: Don't reschedule inside a nested lock
The internal "reschedule" API has always understood the idea that it
might run in a ISR context where it can't swap.  But it has always
been happy to swap away when in thread mode, even when the environment
contains an outer lock that would NOT be expecting to swap!  As it
happened, the way irq locks are implemented (they store flag state
that can be restored without context) this would "work" even though it
was completely breaking the synchronization promise made by the outer
lock.

But now, with spinlocks, the error gets detected (albeit in a clumsy
way) in debug builds.  The unexpected swap triggers SPIN_VALIDATE
failures in later threads (this gets reported as a "recursive" lock,
but what actually happened is that another thread got to run before
the lock was released and tried to grab the same lock).

Fix this so that swap can only be called in a situation where the irq
lock key it was passed would have the effect of unmasking interrupts.
Note that this is a real behavioral change that affects when swaps
occur: it's not impossible that there is code out there that actually
relies on this "lock breaking reschedule" for correct behavior.  But
our previous implementation was irredeemably broken and I don't know
how to address that.

Fixes #16273

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-06-03 12:03:48 -07:00
Andy Ross 84473630f4 kernel/thread_abort: Swap, don't reschedule when aborting _current
The z_reschedule() call (as of the accompanying fix) will not swap
away from a thread if called with a nested irq lock held.

But for the specific case of aborting the current thread, we
absolutely need to swap regardless of how many locks the thread that
just aborted might have held.  So call z_swap() explicitly here.

This preserves the existing z_reschedule() call in other circumstances
for compatibility with existing test cases, but adds a note explaining
why it's there when the only obvious reason for it is already covered.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-06-03 12:03:48 -07:00
Anas Nashif 76d9d7806d x86: remove unused and x86 only latency benchmark
We do have a multi-architecture latency benchmark now, this one was x86
only, was never used or compiled in and is out-dated.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-06-03 09:42:00 -07:00
Nicolas Pitre 0b5d9f71f2 thread_cpu: make it 64-bit compatible
This stores a combination of a pointer and a CPU number in the low
2 bits. On 64-bit systems, the pointer part won't fit in an int.
Let's use uintptr_t for this purpose.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-05-30 09:42:23 -04:00
Nicolas Pitre df0b49cd4f kernel/init.c: remove needless casts
Memory boundaries are declared as extern char arrays which can be used
directly rather than casting their addresses. The cast to u32_t also
breaks 64-bit builds.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
2019-05-30 09:16:35 -04:00
Marc Herbert 4afcc0f8af sanitycheck: CONFIG_TEST_USERSPACE / userspace tag cleanup
- Delete CONFIG_TEST_USERSPACE=n no-ops because it's the default
since commit 7b1ee5cf13

- Some tests have a "userspace" tag pretending to TEST_USERSPACE but
don't and vice versa: fix missing or spurious "userspace" tags in
testcase.yaml files.

Tests have a _spurious_ "userspace" tag when they PASS this command
cause none should pass:

  ./scripts/sanitycheck --tag=userspace -p qemu_x86 \
      --extra-args=CONFIG_TEST_USERSPACE=n  \
      --extra-args=CONFIG_USERSPACE=n | tee userspace.log

All tests run by this command must either fail to build or fail to run
with some userspace related error. Shortcut to look at all test
failures:

 zephyr_failure_logs() {
     awk '/see.*log/ {print $2}' "$@"
 }

Tests _missing_ "userspace" tag FAIL to either build or to run with some
userspace related error when running this:

  ./scripts/sanitycheck --exclude=userspace -p qemu_x86 \
      --extra-args=CONFIG_TEST_USERSPACE=n  \
      --extra-args=CONFIG_USERSPACE=n | tee excludeuserspace.log

Note the detection methods above are not 100% perfect because some
flexible tests like tests/kernel/queue/src/main.c evade them with #ifdef
CONFIG_USERSPACE smarts. Considering they never break, it is purely the
test author's decision to include or not such flexible tests in the
"userspace" subset.

Signed-off-by: Marc Herbert <marc.herbert@intel.com>
2019-05-30 08:45:39 -04:00
Ioannis Glaropoulos 7583696548 kernel: remove redundant #ifdef CONFIG_MULTITHREADING
Remove a redundant #ifdef CONFIG_MULTITHREADING guard
for a code block already inside CONFIG_MULTITHREADING.
Add some inline #endif comments for ease of reading.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-05-24 13:12:55 -04:00
Ioannis Glaropoulos 5a709f5dc9 kernel: init: use K_THREAD_STACK_SIZEOF when switching to main thread
For architectures with custom swap to main, currently:
- arm
- posix
we are now using K_THREAD_STACK_SIZEOF macro to pass the
main thread stack size to z_arch_switch_to_main_thread().

This does not introduce any behavioral changes for posix;
the K_THREAD_STACK_SIZEOF() simply returns the sizeof()
the stack object. For Arm, this allows us to clean-up one
more occurence of CONFIG_MPU_REQUIRES_POWER_OF_TWO_ALIGNMENT
in kernel_arch_func.h.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-05-24 13:12:55 -04:00
Andrew Boie fd49cf7d02 kernel: timeout: add syscall for runtime clk freq
If the system sets its clock frequency at runtime, this is
stored in a variable that can't be directly read by user
mode. For this case only, add a system call to fetch its
value and modify the definition of
sys_clock_hw_cycles_per_sec() to use it.

Since this is now a system call, store in a temporary variable
inside z_ms_to_ticks(). The syscall overhead only applies
when called from user mode, other contexts are completely
inlined.

Added stub syscall header for mocking framework, to get rid
of inclusion errors.

Fixes: #16238

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-22 23:33:55 +02:00
Charles E. Youse a567831bed kernel/sched.c: add k_usleep() API function
Add k_usleep() API, analogous to k_sleep(), excepting that the argument
is in microseconds rather than milliseconds.

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-05-21 23:09:16 -04:00
Charles E. Youse b186303cb6 kernel/sched.c: refactor k_sleep() implementation for varied timescales
Current z_impl_k_sleep() does double duty, converting between units
specified by the API and ticks, as well as implementing the sleeping
mechanism itself. This patch separates the API from the mechanism,
so that sleeps need not be tied to millisecond timescales.

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-05-21 23:09:16 -04:00
Carles Cufi 201fdf0aec kernel: Fix usage of CONFIG_SYS_CLOCK_EXISTS
When compiling the kernel with CONFIG_SYS_CLOCK_TICKS_PER_SEC=0,
the CONFIG_SYS_CLOCK_EXISTS internal variable is unset.
This completely disables timer handling in the kernel, but a couple of
spots missed the required conditional compilation.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2019-05-15 10:44:59 +02:00
Jakob Olesen c8708d9bf3 misc: Replace uses of __builtin_*_overflow() with <misc/math_extras.h>.
Use the new math_extras functions instead of calling builtins directly.

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

Signed-off-by: Jakob Olesen <jolesen@fb.com>
2019-05-14 19:53:30 -05:00
Andrew Boie be3d4232c2 kernel: fix k_stack_alloc_init()
k_stack_alloc_init() was creating a buffer that was 4 times
too small to support the requested number of entries, since
each entry in a k_stack is a u32_t.

Fixes: #15911

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-06 19:47:01 -04:00
Andrew Boie 0f6c9a5a04 kernel: adjust default main stack for riscv
We are just at the knife edge with 512, with stack
overflows being observed with stack canaries enabled.
Given the special case for the idle thread stack size
on this arch, seems reasonable to increase it here
for that arch.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-03 13:30:16 -07:00
Benoit Leforestier 9915b4ec4e C++: Fix compilation error "invalid conversion"
When some header are included into C++ source file, this kind of
compilations errors are generated:
error: invalid conversion from 'void*'
	to 'u32_t*' {aka 'unsigned int*'} [-fpermissive]

Signed-off-by: Benoit Leforestier <benoit.leforestier@gmail.com>
2019-05-03 14:27:07 -04:00
Ioannis Glaropoulos 873dd10ea4 kernel: mem_domain: update name/doc of API function for partition add
Update the name of mem-domain API function to add a partition
so that it complies with the 'z_' prefix convention. Correct
the function documentation.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-05-02 11:37:38 -04:00
Andrew Boie afda764ee6 kernel: increase workq sizes if COVERAGE=y
The defaults are too small if coverage is enabled.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-05-02 07:23:35 -04:00
Flavio Ceolin 2e0095a99c security: kernel: Fix STACK_POINTER_RANDOM dependency
STACK_POINTER_RANDOM depends on a random generator, this can be either a
non-random generator (used for testing purpose) or a real random
generator. Make this dependency explicitly in Kconfig to avoid linking
problems.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-05-01 08:34:13 -07:00
Andrew Boie 09dc929d41 userspace: fix copy from user locking
We don't actually need spinlocks here.

For user_copy(), we are checking that the pointer/size passed in
from user mode represents an area that the thread can read or
write to. Then we do a memcpy into the kernel-side buffer,
which is used from then on. It's OK if another thread scribbles
on the buffer contents during the copy, as we have not yet
begun any examination of its contents yet.

For the z_user_string*_copy() functions, it's also possible
that another thread could scribble on the string contents,
but we do no analysis of the string other than to establish
a length. We just need to ensure that when these functions
exit, the copied string is NULL terminated.

For SMP, the spinlocks are removed as they will not prevent a
thread running on another CPU from changing the buffer/string
contents, we just need to safely deal with that possibility.

For UP, the locks do prevent another thread from stepping
in, but it's better to just safely deal with it rather than
affect the interrupt latency of the system.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-04-18 17:13:08 -04:00
Flavio Ceolin 4f99a38b06 arch: all: Remove not used struct _caller_saved
The struct _caller_saved is not used. Most architectures put
automatically the registers onto stack, in others architectures the
exception code does it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-04-18 12:24:56 -07:00
Flavio Ceolin d61c679d43 arch: all: Remove legacy code
The struct _kernel_ach exists only because ARC' s port needed it, in
all other ports this was defined as an empty struct. Turns out that
this struct is not required even for ARC anymore, this is a legacy
code from nanokernel time.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-04-18 12:24:56 -07:00
Wentong Wu 8646a8e4f5 tests/kernel/mem_protect/stackprot: stack size adjust
revert commit 3e255e968 which is to adjust stack size
on qemu_x86 platform for coverage test, but break other
platform's CI test.

Fixes: #15379.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-04-12 10:06:43 -04:00
Wentong Wu 3e255e968a tests: adjust stack size for qemu_x86's coverage test
for SDK 0.10.0, it consumes more stack size when coverage
enabled, so adjust stack size to fix stack overflow issue.

Fixes: #15206.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-04-11 17:59:39 -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
Andrew Boie 9f04c7411d kernel: enforce usage of CONFIG_TEST_USERSPACE
If a test tries to create a user thread, and the platform
suppors user mode, and CONFIG_TEST_USERSPACE has not been
enabled, fail an assertion.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-04-06 14:30:42 -04:00
Andrew Boie 4e5c093e66 kernel: demote K_THREAD_STACK_BUFFER() to private
This macro is slated for complete removal, as it's not possible
on arches with an MPU stack guard to know the true buffer bounds
without also knowing the runtime state of its associated thread.

As removing this completely would be invasive to where we are
in the 1.14 release, demote to a private kernel Z_ API instead.
The current way that the macro is being used internally will
not cause any undue harm, we just don't want any external code
depending on it.

The final work to remove this (and overhaul stack specification in
general) will take place in 1.15 in the context of #14269

Fixes: #14766

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-04-05 16:10:02 -04:00
Wentong Wu b991962a2e tests: adjust stack size for qemu_x86 and mps2_an385's coverage test
for SDK 0.10.0, it consumes more stack size when coverage enabled
on qemu_x86 and mps2_an385 platform, adjust stack size for most of
the test cases, otherwise there will be stack overflow.

Fixes: #14500.

Signed-off-by: Wentong Wu <wentong.wu@intel.com>
2019-04-04 08:23:13 -04:00
Patrik Flykt 7c0a245d32 arch: Rename reserved function names
Rename reserved function names in arch/ subdirectory. The Python
script gen_priv_stacks.py was updated to follow the 'z_' prefix
naming.

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-04-03 17:31:00 -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
Andrew Boie 1dc6612d50 userspace: do not track net_context as a kobject
The socket APIs no longer deal with direct net context
pointers.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-04-03 13:47:45 -04:00
Andrew Boie 526807c33b userspace: add const qualifiers to user copy fns
The source data is never modified.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-29 22:21:16 -04:00
Andrew Boie ae0d1b2b79 kernel: sched: move stack sentinel check earlier
Checking the stack sentinel may abort the current thread,
make this check before we determine what the next thread
to run is.

Fixes: #15037

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-29 22:13:40 -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
Daniel Leung 416d94cd30 kernel/mutex: remove object monitoring empty loop macros
There are some remaining code from object monitoring which simply
expands to empty loop macros. Remove them as they are not
functional anyway.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2019-03-28 08:55:12 -05:00
David Brown 22029275d3 kernel: Clarify warning about no multithreading
Clarify the warning in the help for CONFIG_MULTITHREADING to make it
clear that many things will break if this is set to 'n'.

Signed-off-by: David Brown <david.brown@linaro.org>
2019-03-28 09:49:59 -04:00
Flavio Ceolin 2df02cc8db kernel: Make if/iteration evaluate boolean operands
Controlling expression of if and iteration statements must have a
boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 22:06:45 -04:00
Flavio Ceolin 625ac2e79f spinlock: Change function signature to return bool
Functions z_spin_lock_valid and z_spin_unlock_valid are essentially
boolean functions, just change their signature to return a bool instead
of an integer.

MISRA-C rule 10.1

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 22:06:45 -04:00
Anas Nashif 42f4538e40 kernel: do not use k_busy_wait when on single thread
k_busy_wait() does not work when multithreading is disabled, so do not
try to wait during boot.

Fixes #14454

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-03-26 20:09:07 -04:00
Flavio Ceolin abf27d57a3 kernel: Make statements evaluate boolean expressions
MISRA-C requires that the if statement has essentially Boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 14:31:29 -04:00
Flavio Ceolin 2ecc7cfa55 kernel: Make _is_thread_prevented_from_running return a bool
This function was returning an essentially boolean value. Just changing
the signature to return a bool.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 14:31:29 -04:00
Flavio Ceolin a996203739 kernel: Use macro BIT for shift operations
BIT macro uses an unsigned int avoiding implementation-defiend behavior
when shifting signed types.

MISRA-C rule 10.1

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-26 14:31:29 -04:00
Piotr Mienkowski a3082e49a1 power: modify HAS_STATE_SLEEP_ Kconfig options
Add SYS_POWER_ prefix to HAS_STATE_SLEEP_, HAS_STATE_DEEP_SLEEP_
options to align them with names of power states they control.
Following is a detailed list of string replacements used:
s/HAS_STATE_SLEEP_(\d)/HAS_SYS_POWER_STATE_SLEEP_$1/
s/HAS_STATE_DEEP_SLEEP_(\d)/HAS_SYS_POWER_STATE_DEEP_SLEEP_$1/

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2019-03-26 13:27:55 -04:00
Piotr Mienkowski 17b08ceca5 power: clean up system power managment function names
This commit cleans up names of system power management functions by
assuring that:
- all functions start with 'sys_pm_' prefix
- API functions which should not be exposed to the user start with '_'
- name of the function hints at its purpose

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2019-03-26 13:27:55 -04:00
Piotr Mienkowski 204311d004 power: rename Low Power States to Sleep States
There exists SoCs, e.g. STM32L4, where one of the low power modes
reduces CPU frequency and supply voltage but does not stop the CPU. Such
power modes are currently not supported by Zephyr.

To facilitate adding support for such class of power modes in the future
and to ensure the naming convention makes it clear that the currently
supported power modes stop the CPU this commit renames Low Power States
to Slep States and updates the documentation.

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2019-03-26 13:27:55 -04:00
Andy Ross 4521e0c111 kernel/sched: Mark sleeping threads suspended
On SMP, there was a bug where the logic that re-adds _current to the
run queue at swap time would accidentally reschedule threads that had
just gone to sleep, because the is_thread_prevented_from_running()
predicate only tests for threads that are "suspended" or "pending" and
not sleeping.

Overload _THREAD_SUSPENDED to indicate "sleeping" also.  Simple fix
for an immediate bug, though long term we really want to unify all the
blocked conditions to prevent this kind of state bug.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-23 19:28:15 -04:00
Andy Ross e59d19628d kernel/sched: Rework prio validity assertion
This is throwing errors in static analysis, complaining that comparing
that a prior is higher and lower is impossible.  That is wrong per my
eyes (I swear I think it might be cueing off the names of the
functions, which invert "higher" and "lower" to match our reversed
priority numbers).

But frankly this was never a very readable macro to begin with.
Refactor to put the bounds into the term, so the static analyzer can
prove it locally, and add a build assertion to catch any errors (there
are none currently) where the low<->high priority range is invalid.

Long term, we should probably remove this macro, it doesn't provide
much value.  But removing it in response to a static analysis failure
is... not very responsible as a development practice.

Fixes #14816
Fixes #14820

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-23 09:53:55 -05:00
Andrew Boie f4631d5b43 kernel: amend comment in k_thread_create handler
This behavior is expected and not of any concern.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-20 13:59:26 -07:00
Andrew Boie d0035f9779 kernel: fix stack size check in k_thread_create
The pointer arithmetic used didn't account for ARC
supervisor mode stacks, which are allocated at the
end of the stack object. Use the new macro to know
exactly how much space is reserved.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-20 13:59:26 -07:00
Andy Ross 3dea408405 kernel/sched: Flag DEAD on correct thread in cross-CPU abort
Daniel Leung caught a good one: In the (SMP) case where we were
aborting a thread that was not currently scheduled, we were flagging
the DEAD state on _current and not the thread we were aborting!  This
wasn't as fatal as it seems, as the thread that called z_sched_abort()
would effectively go on living (as a zombie?) in a state where it
would always be preempted, but would otherwise remain scheduleable.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-19 13:39:24 -05:00
Andrew Boie 7ea211256e userspace: properly namespace handler functions
Now prefixed with z_hdlr_ instead of just hdlr_.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-18 09:23:11 -07:00
Andrew Boie 50be938be5 userspace: renamespace some internal macros
These private macros are now all prefixed with Z_.

Fixes: #14447

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-18 09:23:11 -07:00
Andrew Boie b3eb510f5c kernel: fix atomic ops in user mode on some arches
Most CPUs have instructions like LOCK, LDREX/STREX, etc which
allows for atomic operations without locking interrupts that
can be invoked from user mode without complication. They typically
use compiler builtin atomic operations, or custom assembly
to implement them.

However, some CPUs may lack these kinds of instructions, such
as Cortex-M0 or some ARC. They use these C-based atomic
operation implementations instead. Unfortunately these require
grabbing a spinlock to ensure proper concurrency with other
threads and ISRs. Hence, they will trigger an exception when
called from user mode.

For these platforms, which support user mode but not atomic
operation instructions, the atomic API has been exposed as
system calls.

Some of the implementations in atomic_c.c which can be instead
expressed in terms of other atomic operations have been removed.

The kernel test of atomic operations now runs in user mode to
prove that this works.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-18 09:18:00 -04:00
Andy Ross 722aeead91 kernel/sched: Nonatomic swap workaround update for qemu behavior
The workaround for nonatomic swap had yet another edge case: it would
save off the _current pointer when pending a thread so that the next
time slice interrupt could test it to see if the swap had actually
happened before assuming that _current could be rescheduled (if it
just pended itself, that's impossible).  Then it would clear the
pending_current pointer so future interrupts wouldn't be confused.

BUT: it turns out that qemu, when faced with really rapid timer rates
that exceed its (host-based) timing accuracy, is perfectly willing to
"stack up" timer interrupts such the one goes pending before the
previous one is finished executing.  In that case, we can enter the
SECOND timer interrupt, to try timeslicing a SECOND time, STILL before
the PendSV exception has run to actually effect the context switch.
Except this time pending_current has been cleared and we try to
reschedule the pended _current thread incorrectly.  In theory real
hardware could do this too, though it would involve absolutely crazy
interrupt latency problems.

Work around this by moving the clear to the thread itself, immediately
after it wakes up from the pend call it retakes a lock and clears
pending_current if it still matches _current.  That is not a perfect
fix: there remains a 2-3 instruction race at that moment where we
return from pend and before we can lock interrupts again where a timer
interrupt will see an incorrect pointer.  But I hammered at this and
couldn't make qemu do that (i.e. return from a timer interrupt but
flag a new one in just a cycle or two).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-15 05:50:43 +01:00
Ramakrishna Pallala e1639b5345 device: Extend device_set_power_state API to support async requests
The existing device_set_power_state() API works only in synchronous
mode and this is not desirable for devices(ex: Gyro) which take
longer time (few 100 mSec) to suspend/resume.

To support async mode, a new callback argument is added to the API.
The device drivers can asynchronously suspend/resume and call the
callback function upon completion of the async request.

This commit adds the missing callback parameter to all the drivers
to make it compliant with the new API.

Signed-off-by: Ramakrishna Pallala <ramakrishna.pallala@intel.com>
2019-03-14 14:26:15 +01:00
Ioannis Glaropoulos cac20e91d8 kernel: userspace: correct documentation for Z_SYSCALL_MEMORY_ macros
Corrections in the documentation of arguments in
Z_SYSCALL_MEMORY, Z_SYSCALL_MEMORY_READ, and
Z_SYSCALL_MEMORY_WRITE macros.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-03-13 15:36:15 -07:00
Ioannis Glaropoulos c686dd5064 kernel: enhance documentation of z_arch_buffer_validate
This commit enhances the documentation of z_arch_buffer_validate
describing the cases where the validation is performed
successfully, as well as the cases where the result is
undefined.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-03-13 15:36:15 -07:00
Andy Ross ea1c99b11b kernel/sched: Fix k_yield() in SMP
This was always doing a remove/add of the _current thread to the run
queue, which is wrong because in SMP _current isn't in the queue to
remove.  But it went undetected until the recent dlist changes.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross 8c1bdda33c kernel/sched: Fix spinlock validation glitch in SMP
In SMP, we are setting the _current pointer while holding the
scheduler spinlock locally, which means that when we try to release it
the validation layer (not the spinlock per se) will scream at us
because the thread that took the lock doesn't match the one releasing
it.

Special case this when validation is enabled.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross f37e0c6e4d kernel/spinlock: Fix race in spinlock validation
The k_spin_lock() validation was setting the new owner of the spinlock
BEFORE the actual lock was taken, so it could race against other
processors trying the same thing.  Split the modification step out
into a separate function that can be called after we affirmatively
have the lock.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross b18685bcf1 kernel/sched: Clean up tracing hooks
The tracing fixes in commit e87193896a ("subsys: debug: tracing: Fix
thread tracing") were... not a readability win.  The point appears to
have been to put a tracing hook immediately before and after the
assignment to the _current pointer.  So do that in an abstracted
function and clean up _get_next_switch_handle() (which is a subtle and
important function already polluted with some unavoidable preprocessor
testing!)

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross 42ed12a387 kernel/sched: arch/x86_64: Support synchronous k_thread_abort() in SMP
Currently thread abort doesn't work if a thread is currently scheduled
on a different CPU, because we have no way of delivering an interrupt
to the other CPU to force the issue.  This patch adds a simple
framework for an architecture to provide such an IPI, implements it
for x86_64, and uses it to implement a spin loop in abort for the case
where a thread is currently scheduled elsewhere.

On SMP architectures (xtensa) where no such IPI is implemented, we
fall back to waiting on an arbitrary interrupt to occur.  This "works"
for typical code (and all current tests), but of course it cannot be
guaranteed on such an architecture that k_thread_abort() will return
in finite time (e.g. the other thread on the other CPU might have
taken a spinlock and entered an infinite loop, so it will never
receive an interrupt to terminate itself)!

On non-SMP architectures this patch changes no code paths at all.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross 6ed59bc442 kernel/smp: Fix bitrot with the way the SMP "start flag" works
Tickless timers mean that k_busy_wait() won't work until after the
timer driver is initialized, which is very early but not as early as
SMP.  No need for it, just spin.

Also the original code used a stack variable for the start flag, which
racily presumed that _arch_start_cpu() would comes back synchronously
with the other CPU fired up and running right now.  The cleaned up smp
bringup API on x86_64 isn't so perky, so it exposed the bug.  The flag
just needs to be static.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross aed8288196 kernel/sched: Handle aboring _current correctly in SMP
In SMP, _current is not "queued".  (The run queue only stores
unscheduled threads because we can't rely on the head of the list
being _current).  We weren't updating the cache choice, which would
flag swap_ok, so calling k_thread_abort(_current) (for example, when a
thread exits from its entry function) would try to switch back into
the thread and then run off the end of the function.

Amusingly this was more benign than you'd think.  Stumbled on it by
accident.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross 0f8bee9c07 kernel/smp: Warning cleanup
When CONFIG_SMP is enabled but CONFIG_MP_NUM_CPUS is 1 (which is a
legal configuration, though a weird one) this static function ends up
being defined but unused, producing a compiler warning.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-13 19:15:20 +01:00
Andy Ross c0183fdedd kernel/work_q: Fix locking across multiple queues
There was a detected user error in the code where racing insertions of
k_delayed_work items into different queues would be detected and
flagged as an error (honestly I don't see much value there -- Zephyr
doesn't as a general rule protect against errors like this, and
work_q's are inherently kernel things that don't require
userspace-style checking).

This got broken with spinlockification, where each work_q object got
its own lock, so the single lock wouldn't protect against the other
insert function any more.  As it happens, that was needless.  The core
synchronization on a work_q is in the internal k_queue object anyway
-- the lock in this file was only ever used for (very fast,
noncontending) delayed work insertion.  So go back to a global lock to
preserve the original behavior.

Fixes #14104

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-03-12 18:37:41 +01:00
Pawel Dunaj b87920bf3c kernel: Make heap smallest object size configurable
Allow application to chose the size of the smallest object taken from
the heap.

Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
2019-03-12 11:56:31 +01:00
Patrik Flykt 4344e27c26 all: Update reserved function names
Update reserved function names starting with one underscore, replacing
them as follows:
   '_k_' with 'z_'
   '_K_' with 'Z_'
   '_handler_' with 'z_handl_'
   '_Cstart' with 'z_cstart'
   '_Swap' with 'z_swap'

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

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

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

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-03-11 13:48:42 -04:00
Patrik Flykt cf2d57952e kernel/sched: Rename scheduler spinlock
Rename scheduler spinlock sched_lock to sched_spinlock as it will
collide with the cleanup of the reserved function name _sched_lock(),
which will also be called sched_lock().

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2019-03-11 13:48:42 -04:00
Andrew Boie 576ebf4991 kernel: add config for Spectre V1 mitigation
This is off by default, but may be selected by the arch
configuration.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-11 09:54:04 -07:00
Ioannis Glaropoulos d69c2f8129 kernel: documentatation for _setup_new_thread()
Add a note in the documentatation of _setup_new_thread()
function stating that the caller is responsible for
providing a size argument that corresponds to the availabe
thread stack area.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-03-09 11:57:24 -08:00
Ioannis Glaropoulos edc9e4d245 arch: arm: userspace: Force arch-specific user local data reservation
This commit forces architecture-specific implementation for
initializing the are for user mode local thread data. This
has been enforced already for ARC. We now do the same for ARM.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-03-09 11:57:24 -08:00
Flavio Ceolin d9876be30c kernel: Make statements evaluate boolean expressions
MISRA-C requires that the if statement has essentially Boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-03-05 14:58:58 -08:00
Andrew Boie e686aefe09 mbedtls: provide user mode access
The mbedtls library has some globals which results in faults
when user mode tries to access them.

Instantiate a memory partition for mbedtls's globals.
The linker will place all globals found by building this
library into this partition.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-05 08:27:20 -05:00
Andrew Boie 62fad96802 userspace: zero app memory bss earlier
Some init tasks may use some bss app memory areas and
expect them to be zeroed out. Do this much earlier
in the boot process, before any of the init tasks
run.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-05 08:27:20 -05:00
Andrew Boie 7707060959 userspace: get rid of app section placeholders
We used to leave byte-long placeholder symbols to ensure
that empty application memory sections did not cause
build errors that were very difficult to understand.

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

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

Fixes: #13923

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-04 08:05:16 -08:00
Andrew Boie 475d279382 userspace: clarify memory domain assertions
Some text added to help explain what is going on.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-04 08:05:16 -08:00
Andrew Boie 6dc3fd8e50 userspace: fix x86 issue with adding partitions
On x86, if a supervisor thread belonging to a memory domain
adds a new partition to that domain, subsequent context switches
to another thread in the same domain, or dropping itself to user
mode, does not have the correct setup in the page tables.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-03 23:44:13 -05:00
Charles E. Youse 0ad4022e51 kernel/timeout: fix k_timer_remaining_get() when tickless
In some circumstances (e.g., a tickless kernel), k_timer_remaining_get()
would not account for time passed that didn't involve clock interrupts.
This adds a simple fix for that, and adds a test case.  In addition, the
return value of k_timer_remaining_get() is clamped at 0 in the case of
overdue timers and the API description is adjusted to reflect this.

Fixes: #13353

Signed-off-by: Charles E. Youse <charles.youse@intel.com>
2019-03-01 14:53:33 -08:00
Andrew Boie d3c89fea4f kernel: move CONFIG_RETPOLINE definition
Retpolines were never completely implemented, even on x86.
Move this particular Kconfig to only concern itself with
the assembly code, and don't default it on ever since we
prefer SSBD instead.

We can restore the common kernel-wide CONFIG_RETPOLINE once
we have an end-to-end implementation.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-03-01 12:35:04 -08:00
Andy Ross dff6b71450 kernel/sched: More nonatomic swap fixes
Nonatomic swap strikes again.  These issues are all longstanding, but
were unmasked by the dlist work in commit d40b8ce1fb ("sys: dlist:
Add sys_dnode_is_linked") where list node pointers become nulls on
removal.

The previous fix was for a specific case where a timeslicing interrupt
would try to slice out the "wrong" current thread because the thread
has "just" pended itself.  That was incomplete, because the parallel
code in k_sleep() didn't flag itself the same way.

And beyond that, it turns out to be basically impossible (now that I'm
thinking about it correctly) to prevent interrupt code from calling
into the scheduler to suspend a "just pended but not quite" current
and/or preempt away to another thread.  In any of these cases, the
scheduler modifications to the state bits remain correct but the queue
nodes may be corrupt because the thread was already removed from the
ready queue.  So we have to test and correct this at the lowest level,
where a thread is being removed from a priq: check that it's (1) the
ready queue and not a waitq, (2) the current thread, and (3) already
marked suspended and thus not in the queue.

There are lots of existing issues filed in the last few months all
pointing to odd instability on ARM platforms.  I'm reasonably certain
this is the root cause for most or all of them.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-27 12:07:34 -08:00
Piotr Mienkowski f04a4c9deb power: rename CPU_LPS_n power states
CPU_LPS_n name used to indicate a low power state is cryptic and
incorrect. The low power states act on the whole SoC and not exclusively
on the CPU. This patch renames CPU_LPS_n states to LOW_POWER_n. Also
HAS_ pattern for Kconfig options is used in favor of a non standard
_SUPPORTED. Naming of deep sleep states was adjusted accordingly.

Following is a detailed list of string replacements used:
s/SYS_POWER_STATE_CPU_LPS_(\d)_SUPPORTED/HAS_STATE_LOW_POWER_$1/
s/SYS_POWER_STATE_CPU_LPS_(\d)/SYS_POWER_STATE_LOW_POWER_$1/
s/SYS_POWER_STATE_DEEP_SLEEP_(\d)_SUPPORTED/HAS_STATE_DEEP_SLEEP_$1/

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2019-02-26 02:30:13 +01:00
Piotr Mienkowski c75187587b power: simplify SYS_POWER_*_SUPPORTED Kconfig options
This commit removes dependency on SYS_POWER_LOW_POWER_STATES_SUPPORTED,
SYS_POWER_DEEP_SLEEP_STATES_SUPPORTED Kconfig options. Power management
SYS_POWER_LOW_POWER_STATES, SYS_POWER_DEEP_SLEEP_STATES options depend
now directly on specific power states supported by the given SoC. This
simplifies maintenance of SoC Kconfig files.

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2019-02-26 02:30:13 +01:00
Andrew Boie f5951cd88f kernel: syscall_handler: get rid of stdarg
We can just implement this as a macro and not needlessly
run afoul of MISRC-C rule 17.1

Fixes: #10012

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-25 13:42:03 -08:00
Andrew Boie 4ce652e4b2 userspace: remove APP_SHARED_MEM Kconfig
This is an integral part of userspace and cannot be used
on its own. Fold into the main userspace configuration.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-23 07:43:55 -05:00
Andrew Boie 01100eadb8 kernel: add stack canary to libc partition
User mode needs to be able to read this value in
compiler generated function prologues/epilogues.

Special handling in init.c for arches that use
_data_copy. This happens before _Cstart() gets
called. We need to make sure that the compiler
stack canary checks in _data_copy itself do not
fail.

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

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-22 18:50:43 -05:00
Aurelien Jarno 992f29a1bc arch: make __ramfunc support transparent
Instead of having to enable ramfunc support manually, just make it
transparently available to users, keeping the MPU region disabled if not
used to not waste a MPU region. This however wastes 24 bytes of code
area when the MPU is disabled and 48 bytes when it is enabled, and
probably a dozen of CPU cycles during boot. I believe it is something
acceptable.

Note that when XIP is used, code is already in RAM, so the __ramfunc
keyword does nothing, but does not generate an error.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2019-02-22 11:36:50 -08:00
Aurelien Jarno eb097bd095 arch: arm: mpu: get the __ramfunc region size from the linker
The linker file defines the __ramfunc_ram_size symbols to get the size
of the __ramfunc_ram section. Use that instead of computing the value at
runtime from the start and end symbols. This saves 16 bytes of code with
CONFIG_RAM_FUNCTION=y.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2019-02-22 11:36:50 -08:00
qianfan Zhao e1cc657941 arm: Placing the functions which holds __ramfunc into '.ramfunc'
Using __ramfunc to places a function in RAM instead of Flash.
Code that for example reprograms flash at runtime can't execute
from flash, in that case must placing code into RAM.

This commit create a new section named '.ramfunc' in link scripts,
all functions has __ramfunc keyword saved in thats sections and
will load from flash to sram after the system booted.

Fixes: #10253

Signed-off-by: qianfan Zhao <qianfanguijin@163.com>
2019-02-22 11:36:50 -08:00
Piotr Zięcik c45961daae power: Rework OS <-> Application interface
This commit simplifies OS <-> Application interface controlling power
management. In the previous approach application-based PM required
overriding sys_suspend() and sys_resume() functions. As these functions
actually implemented power state change, in such case application
basically had to provide own implementation of all PM-related stuff,
which was not portable and hard to maintain.

This commit changes this scheme: The sys_suspend() and sys_resume()
are now system functions while the application could either use
built-in power management policies or provide its own. All details
of power mode switching are now handled by the OS.

Also, this commit cleans up the Kconfig options related to system-level
power management grouping them under common CONFIG_SYS_PM_ prefix.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2019-02-19 13:25:36 -05:00
Carlos Stuart 75f77db432 include: misc: util.h: Rename min/max to MIN/MAX
There are issues using lowercase min and max macros when compiling a C++
application with a third-party toolchain such as GNU ARM Embedded when
using some STL headers i.e. <chrono>.

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

All files that use these macros have been updated.

Signed-off-by: Carlos Stuart <carlosstuart1970@gmail.com>
2019-02-14 22:16:03 -05:00
Andy Ross 86380483da kernel/work_q: Fix block-in-spinlock bug
Work queues are implemented in terms of k_queue objects which provide
their own synchronization.  In particular insertion is potentially
blocking and always acts as a reschedule point, which means that it
must not be called with spinlocks held.

Release the lock first, and do a little cleanup of the resulting
k_delayed_work_submit_to_queue() logic.

Fixes #13411

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-14 19:45:20 -05:00
Andrew Boie 2cfeba8507 x86: implement interrupt stack trampoline
Upon hard/soft irq or exception entry/exit, handle transitions
off or onto the trampoline stack, which is the only stack that
can be used on the kernel side when the shadow page table
is active. We swap page tables when on this stack.

Adjustments to page tables are now as follows:

- Any adjustments for stack memory access now are always done
  to the user page tables

- Any adjustments for memory domains are now always done to
  the user page tables

- With KPTI, resetting a page now clears the present bit

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-14 12:46:36 -05:00
Ioannis Glaropoulos 228702e6e1 kernel: minor syntax fix in Kconfig
Minor style (syntax) fix in the help text of symbol
config EXECUTION_BENCHMARKING.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-02-12 08:29:33 -06:00
Piotr Zięcik 9cc63e07e4 power: Fix naming of Kconfig options controlling deep sleep states
This commit changes the names of SYS_POWER_DEEP_SLEEP* Kconfig
options in order to match SYS_POWER_LOW_POWER_STATE* naming
scheme.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2019-02-12 07:46:32 -05:00
Piotr Zięcik 7a49356c77 power: Fix naming of Kconfig options controlling low power states
The SYS_POWER_LOW_POWER_STATE_SUPPORTED and SYS_POWER_LOW_POWER_STATE
suggests one low power state but these options control multiple
low power state. This commit uses plural in the names to indicate
that.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2019-02-12 07:46:32 -05:00
Andy Ross 1202810119 kernel/sched: _thread_priority_set needs to be sched_lock aware
This API doesn't use the normal thread priority comparison itself, so
doesn't get the magic that thread_base.prio provides.  If called when
another thread should be run, this would preempt the current thread
always, even if the scheduler lock was taken.

That was benign until recent spinlockifiation exposed it: a mutex in
the philosophers test run in preempt_only mode would swap away while
holding a spinlock (which used to work with irq locks) and fail later
with a "recursive" spinlock assert.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 8a3d57b6cc kernel/userspace: Spinlockification
This port is a little different.  Most subsystem synchronization uses
simple critical sections that can be replaced with global or
per-object spinlocks.  But the userspace code was heavily exploiting
the fact that irq_lock was recursive and could be taken at any time.
So outer functions were doing locking and then calling into inner
helpers that would take their own lock (because they were called from
other contexts that did not lock).

Rather than try to rework this right now, this just creates a set of
spinlocks corresponding to the recursive states in which they are
taken, to preserve the existing semantics exactly.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross b29fb220b1 kernel/timer: Spinlockify
Simple global lock around the timer API.  Actually a lot of this usage
was using needless vestigial locking around existing scheduler and
timeout APIs that are now internally synchronized.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross f582b55dd6 kernel/pipe: Spinlockify
One spinlock per pipe object.  Also removed some vestigial locking
around _ready_thread().  That call is internally synchronized now.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross d27d4e6af2 kernel/sched: Remove remaining irq_lock use
The k_sleep() locking was actually to protect the _current state from
preemption before the context switch, so document that and replace
with a spinlock.  Should probably unify this with the rather cleaner
logic in pend_curr(), but right now "sleeping" and "pended" are
needlessly distinct states.

And we can remove the locking entirely from k_wakeup().  There's no
reason for any of that to need to be synchronized.  Even if we're
racing with other thread modifiations, the state on exit will be a
runnable thread without a timeout, or whatever timeout/pend state the
other side was requesting (i.e. it's a bug, but not one solved by
synhronization).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross be03dbd4c7 kernel/msg_q: Spinlockify
One lock per msgq.  Straightforward synchronization.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross f0933d0ded kernel/stack: Spinlockify
One lock per stack.  Straightforward synchronization.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 9eeb6b8779 kernel/mbox: Spinlockify
Straightforward per-struct-k_mbox lock.  Nothing changes in locking
strategy.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 7df0216d1e kernel/mutex: Spinlockify
Use a subsystem lock, not a per-object lock.  Really we want to lock
at mutex granularity where possible, but (1) that has non-trivial
memory overhead vs. e.g. directly spinning on the mutex state and (2)
the locking in a few places was originally designed to protect access
to the mutex *owner* priority, which is not 1:1 with a single mutex.

Basically the priority-inheriting mutex code will need some rework
before it works as a fine-grained locking abstraction in SMP.

Note that this fixes an invisible bug: with the older code,
k_mutex_unlock() would actually call irq_unlock() twice along the path
where there was a new owner, which is benign on existing architectures
(so long as the key argument is unchanged) but was never guaranteed to
work.  With a spinlock, unlocking an unlocked/unowned lock is a
detectable assertion condition.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 603ea42764 kernel/queue: Spinlockify
Straightforward port.  Each struct k_queue object gets a spinlock to
control obvious data ownership.

Note that this port actually discovered a preexisting bug: the -ENOMEM
case in queue_insert() was failing to release the lock.  But because
the tests that hit that path didn't rely on other threads being
scheduled, they ran to successful completion even with interrupts
disabled.  The spinlock API detects that as a recursive lock when
asserts are enabled.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross f6521a360d kernel/thread_abort: Remove needless locking
The two APIs protected by this lock are themselves internally
synchronized.  Replace the irq_lock with a spinlock anyway, because
what I think it's doing is trying to prevent a race where something
else like an ISR or something it wakes up mucks with the thread before
this completes.  Seems fragile on SMP as it stands, but this preserves
behavior on uniprocessor architectures.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross c0bdcbaaf8 kernel/mem_slab: Spinlockify
Use a subsystem lock instead of a per-slab lock for now

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross e456d0f7dd kernel/thread: Spinlockify
Straightforward spinlock around the global thread state.  Two changes
to the locking strategy were needed:

1. There was a needless recursive lock taken in schedule_new_thread().
This is only ever invoked in circumstances where the lock was already
held, or where there is no need for internal synchronization.

2. The recursive irq_lock() around the loop that spawns the initial
static threads (which happens at the start of main thread execution)
was removed.  Most of the job (i.e. making sure the threads don't run
before the loop is finished) was already duplicated by the sched_lock
it was already taking, and the attempt to promise that all the
timeouts happen on the same tick is already true by construction at
system startup on uniprocessor systems, and not possible to guarantee
at all under SMP (where other CPUs can take that timer interrupt).  We
don't document or test for this feature, so don't try to be fancy.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 84b47a9290 kernel/mempool: Spinlockify
Really the locking in this file is vestigial.  It only exists because
the scheduler's _unpend_all() call to wake up everyone waiting on a
wait_q is unsynchronized, because it was written to assume
irq_lock-style-locking.  It would be cleaner to put that locking into
the wait_q itself and/or use the scheduler's subsystem lock.  But it's
not clear there's any performance benefit, so let's stick with the
more easily verifiable change first.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross f2b1a4bb64 kernel/poll: Spinlockify
Poll gets a single subsystem lock for now.  The existing locking in
Ben's code is subtle, being used both for latency control and for
critical section protection.  So getting each k_poll_event to use a
separate lock will require care and a little logic change.  Do the
simple version for now, which still works to decouple it from the
global lock.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 1bf9bd04b1 kernel: Add _unlocked() variant to context switch primitives
These functions, for good design reason, take a locking key to
atomically release along with the context swtich.  But there's still a
common pattern in code to do a switch unconditionally by passing
irq_lock() directly.  On SMP that's a little hurtful as it spams the
global lock.  Provide an _unlocked() variant for
_Swap/_reschedule/_pend_curr for simplicity and efficiency.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross da37a53a54 kernel/k_sem: Spinlockify
Switch semaphores to use a subsystem spinlock instead of the system
irqlock.

Note that this is only "half way there".  Semaphores will no longer
contend with other irqlock users on SMP systems, but all semaphores
are still sharing the same lock.  Really we want semaphores to be
independently synchronized, but adding 4 bytes to every one (there are
a LOT of these things) for a separate spinlock is too much to pay.

Rather, a proper SMP-aware implementation would spin on the count
variable directly.  But let's not rock that boat quite yet.

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

Just refactoring.  No logic changes.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 04382b9a2a kernel/mem_domain: Spinlockify
Simple locking requirements here mean we can just use a single
subsystem lock.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 32a29d2805 kernel/atomic_c: Spinlockify
Mostly useless patch.  All architectures have their own code for
atomic operations and don't use this fallback.  Still, it's a trivial
locking setup and we might as well.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross a37a981b21 kernel/work_q: Spinlockify
Each work_q object gets a separate spinlock to synchronize access
instead of the global lock.  Note that there was a recursive lock
condition in k_delayed_work_cancel(), so that's been split out into an
internal unlocked version and the API entry point that wraps it with a
lock.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 5aa7460e5c kernel/spinlock: Move validation out of header inlines
The validation checking recently added to spinlocks is useful, but
requires kernel-internals like _current and _current_cpu in a header
context that tends to be needed before those are declared (or where we
don't want them declared), and is causing big header dependency
headaches.

Move it to C code, it's just a validation tool, not a performance
thing.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross aa6e21c24c kernel: Split _Swap() API into irqlock and spinlock variants
We want a _Swap() variant that can atomically release/restore a
spinlock state in addition to the legacy irqlock.  The function as it
was is now named "_Swap_irqlock()", while _Swap() now refers to a
spinlock and takes two arguments.  The former will be going away once
existing users (not that many!  Swap() is an internal API, and the
long port away from legacy irqlocking is going to be happening mostly
in drivers) are ported to spinlocks.

Obviously on uniprocessor setups, these produce identical code.  But
SMP requires that the correct API be used to maintain the global lock.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross 53cae5f471 kernel: Use _reschedule() instead of _Swap() where possible
These two spots were duplicating logic that is already done inside
_reschedule(), which is the cleaner, less dangerous API.  Use it where
possible when outside the scheduler internals.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Andy Ross dc0713a706 kernel: Cleanup. Remove redundant test when calling _Swap()
_Swap() must already handle the case where _get_next_ready_thread() is
the same as _current.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-08 14:49:39 -05:00
Kumar Gala bfaaa6bbe9 dts: Convert CONFIG_CCM to DT_CCM
Since we know do DTS before Kconfig we should try and remove dts from
creating Kconfig namespaced symbols and leave that to Kconfig.  So
rename CONFIG_CCM_<FOO> to DT_CCM_<FOO>.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2019-02-08 10:29:57 -06:00
Piotr Zięcik d02e3ebd4c power: Eliminate SYS_PM_* power states.
The power management framework used two different abstractions
to describe power states. The SYS_PM_* given coarse information
what kind of power state (low power or deep sleep) was used,
while the SYS_POWER_STATE_* abstraction provided information
about particular power mode.

This commit removes the SYS_PM_* abstraction as the same
information is already carried in SYS_POWER_STATE_*.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2019-02-08 09:07:00 -05:00
Andrew Boie 41f6011c36 userspace: remove APPLICATION_MEMORY feature
This was never a long-term solution, more of a gross hack
to get test cases working until we could figure out a good
end-to-end solution for memory domains that generated
appropriate linker sections. Now that we have this with
the app shared memory feature, and have converted all tests
to remove it, delete this feature.

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

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

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

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

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

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

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-08 07:04:30 -05:00
Andrew Boie 7ecc359f2c userspace: do not auto-cleanup static objects
Dynamic kernel objects enforce that the permission state
of an object is also a reference count; using a kernel
object without permission regardless of caller privilege
level is a programming bug.

However, this is not the case for static objects. In
particular, supervisor threads are allowed to use any
object they like without worrying about permissions, and
the logic here was causing cleanup functions to be called
over and over again on kernel objects that were actually
in use.

The automatic cleanup mechanism was intended for
dynamic objects anyway, so just skip it entirely for
static objects.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2019-02-08 07:04:30 -05:00
Andy Gross 2e8cdc1e7f kernel: Enforce k_mem_slab block size alignment
This patch puts checks in place to ensure that callers to the k_mem_slab
APIs provide word aligned block sizes.  If this is not done, this can
result in unaligned accesses and subsequent crashes.

Signed-off-by: Andy Gross <andy.gross@linaro.org>
2019-02-06 07:18:45 -05:00
Ioannis Glaropoulos 6c54cac73d kernel: mem_domain: extend sane_partition for non-overlapping regions
This commit extends the implementation of sane_partition(..) in
kernel/mem_domain.c so that it generates an ASSERT if partitions
inside a mem_domain overlap. This extension is only implemented
for the case when the MPU requires non-overlapping regions.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2019-02-05 09:28:59 -08:00
Anas Nashif 427cc77115 kernel: fix smp build on esp32
set_kernel_idle_time_in_ticks is not used in non SMP code.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-02-04 18:16:58 -05:00
Daniel Leung 4bb10eeada kernel/sched: fix CPU mask kconfig typo
The kconfig used in BUILD_ASSERT_MSG() is missing a "S".
So add it back.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2019-02-04 15:53:09 -05:00
Andy Ross ab46b1b3c5 kernel/sched: CPU mask affinity/pinning API
This adds a simple implementation of SMP CPU affinity to Zephyr.  The
API is simple and doesn't try to invent abstractions like "cpu sets".
Each thread has an enable/disable flag associated with each CPU in the
system, and the bits can be turned on and off (for threads that are
not currently runnable, of course) using an easy three-function API.

Because the implementation picked requires enumerating runnable
threads in priority order looking for one that match the current CPU,
this is not a good fit for the SCALABLE or MULTIQ scheduler backends,
so it currently can be enabled only for SCHED_DUMB (which is the
default anyway).  Fancier algorithms do exist, but even the best of
them scale as O(N_CPUS), so aren't quite constant time and often
require significant memory overhead to keep separate lists for
different cpus/sets.

The intended use here is for apps that want to "pin" threads to
specific CPUs for latency control, or conversely to prevent certain
threads from taking time on specific CPUs to leave them free for fast
response.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-01 21:37:24 -05:00
Andy Ross 6d9106f288 kernel/init: Fix dummy thread initialization on SMP systems
When under SMP, _current is a macro that indirects to a CPU-specific
address, and that trick won't work until kernel_arch_init() has
returned.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-01 19:10:08 -05:00
Andy Ross bd049626c5 kernel/sched: Limit idle testing in preemption hot path
Idle threads must (for obvious reasons!) always be preemptible from
the perspective of the scheduler.  But when preemptive scheduling is
disabled, they are given a priority of -1, which is the lowest
COOPERATIVE priority.  So the scheduler preemption logic needed an
extra test for this case and couldn't just rely on the existing
priority comparison.  This was a measurable performance loss, as this
is a hot path on existing benchmarks.

Limit that test to circumstances (!CONFIG_PREEMPT_ENABLED) where it's
actually needed.

Longer term it would be better to just force the existence of one
"preemptible" thread priority always, but right now the number of
priorities and the state of the PREEMPT_ENABLED kconfig flag are
linked, and the existing interrupt return code (with no preemption,
you know with certainty which thread you are returning to and can skip
some work) on some platforms fails when I try this.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-01 15:57:21 -05:00
Andy Ross 1763a017b4 kernel/sched: Simplify init-time dummy thread & scheduling predicate
For historical reasons, some architectures had a valid _current thread
pointer at initialization time and others didn't.  So the scheduler
logic had a test that checks _current vs. NULL every time it needed to
check premption, when this was only a workaround for initialization
state.

Fix things so that there is a dummy thread always (and clean up the
code to do a struct assignment instead of a memset of bare memory),
and we can remove that test from the scheduler hot path.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-01 15:57:21 -05:00
Andy Ross b2791b0ac8 kernel/sched: Force inlining of some routines within the scheduler guts
GCC 6.2.0 is making frustratingly poor inlining decisions with some of
these routines, resulting in an awful lot of runtime calls for code
that is only ever expanded once or twice within the file.

Treat with targetted ALWAYS_INLINE's to force the issue.  The
scheduler code is a hot path.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-01 15:57:21 -05:00
Andy Ross eda4c027da misc/dlist: Swap insertion API for a faster one
The sys_dlist_insert_*() functions had a behavior where a NULL
argument for the insertion position to sys_dlist_insert_after/before()
was interpreted as "the end of the list".  We never used that
convention (except in one spot internal to dlist.h which was not
itself used anywhere), and of course already have an API for appending
and prepending to a list.

In practice this was a performance disaster.  The NULL check is
virtually never provable statically by the compiler, so that test and
branch is present always.  And worse, the check and call to another
function was pushing this beyond the complexity limit for gcc to
inline a function (at -Os optimization anyway), forcing us to use
function calls for what should be a ~8 instruction sequence.  The
upshot is that dlist insertions were 2-3x slower than they needed to
be.

Deprecate these older APIs and introduce a new sys_dlist_insert() call
which can be much better optimized.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-02-01 15:57:21 -05:00
Andy Ross 8b583acf23 kernel/timeout: Fix another recursive spinlock()
The fix in commit e664c78b82 ("kernel/timeout: Fix recursive
spinlock in z_set_timeout_expiry()") missed a spot that had also been
introduced with recent locking work.  The new
_get_next_timeout_expiry() implementation takes its own lock, which is
recursive when called from z_clock_announce().  Fix by calling the
wrapped implementation instead.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-30 13:29:42 -08:00
Anas Nashif c0ea505b2c kernel: fix typo in kconfig name
CONFIG_MULTITHREDING -> CONFIG_MULTITHREADING

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2019-01-30 13:30:17 -05:00
Peter A. Bigot b4ece0ad44 kernel: timeout: detect inactive timeouts using dnode linked state
Whether a timeout is linked into the timeout queue can be determined
from the corresponding sys_dnode_t linked state.  This removes the need
to use a special flag value in dticks to determine that the timeout is
inactive.

Update _abort_timeout to return an error code, rather than the flag
value, when the timeout to be aborted was not active.

Remove the _INACTIVE flag value, and replace its external uses with an
internal API function that checks whether a timeout is inactive.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-01-23 20:46:49 +01:00
Peter A. Bigot 4863aa809c kernel: poll: fix double-remove of node
k_poll events are registered in a linked list when their signal
condition has been met.  The code to clear event registration did not
account for events that were not registered, resulting in double-removes
that produced core dumps on native-posix sanitycheck.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-01-23 20:46:49 +01:00
Peter A. Bigot 25fbe7b60d kernel: timeout: remove local fix for double-remove
Use the new generic capability to detect unlinked sys_dnode_t instances.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-01-23 20:46:49 +01:00
Peter A. Bigot 692e1033e7 kernel: sched: fix empty list detection
CONTAINER_OF() on a NULL pointer returns some offset around NULL and not
another NULL pointer.  We have to check for that ourselves.

This only worked because the dnode happened to be at the start of the
struct.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-01-23 20:46:49 +01:00
Sebastian Bøe 5a58da57fd Kconfig: STACK_CANARIES: Correct the help text
The help text has been stating that CONFIG_STACK_CANARIES will
silently be ignored when the compiler does not support them. But this
is not the desired behaviour of CONFIG_STACK_CANARIES[1].

This patch corrects the help text to state that an error will occur if
this feature is enabled, but not supported.

[1] "I would much rather see the build break if someone tries to
enable the stack canaries, and the compiler doesn't support
it. Because what happens now is that if someone enables this option,
and there is no support, the build will succeed but there are no
actual stack canaries in place, and unless the user is paying close
attention to the cmake test output they will have no idea."
--
https://github.com/zephyrproject-rtos/zephyr/issues/5019

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2019-01-23 09:44:09 +01:00
Sebastian Bøe 1b86fb9da3 cmake: Use variables for target names
There is an effort underway to make most of the Zephyr build script's
reentrant. Meaning, the build scripts can be executed multiple times
during the same CMake invocation.

Reentrancy enables several use-cases, the motivating one is the
ability to build several Zephyr executables, or images, for instance a
bootloader and an application.

For build scripts to be reentrant they cannot be directly referencing
global variables, like target names, but must instead reference
variables, which can vary from entry to entry.

Therefore, in this patch, we replace global targets with variables.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2019-01-19 07:21:55 -05:00
Andy Ross e664c78b82 kernel/timeout: Fix recursive spinlock in z_set_timeout_expiry()
The z_set_timeout_expiry() function was added in part to simply the
locking strategy, but it missed a case where a function it was calling
was re-locking the same spinlock.  It "works"[1] in uniprocessor
environments, but can be a deadlock in SMP.

Fix this by moving the meat of the function to an unlocked utility,
use that locally, and turn the entry point into one that does locking.
Actually this only gets called from idle now, which is a use case that
will go away when TICKLESS_IDLE is removed as a separate feature (once
you know all timeouts are set tickless, you don't need to set it from
the idle entry at all).

Discovered via lucky inspection.

[1] It doesn't work.  It releases the lock prematurely at the end of
the inner block.  But in practice this wasn't discovered.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-18 06:48:51 -05:00
Peter A. Bigot bfad9721d2 kernel: remove k_alert API
This API was used in only one place in non-test code.  See whether we
can remove it.

Closes #12232

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2019-01-16 21:34:07 -05:00
Adithya Baglody 76ee02b6b3 Gcov: Added Kconfig changes needed by Gcov.
This patch addes the required changes in the Kconfig files.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2019-01-16 06:12:33 -05:00
Adithya Baglody 71e90f98fd Gcov: Enable Code coverage reporting over UART.
This patch provides support for generating Code coverage reports.
The prj.conf needs to enable CONFIG_COVERAGE. Once enabled, the
code coverage data dump now comes via UART.
This data dump on the UART is triggered once the main
thread exits.

Next step is to save this data dump on file. Then run
scripts/gen_gcov_files.py with the serial console log as argument.

The last step would be be to run the gcovr. Use the following cmd
 gcovr -r . --html -o gcov_report/coverage.html --html-details

Currently supported architectures are ARM and x86.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2019-01-16 06:12:33 -05:00
Andy Ross 7fb8eb57e8 kernel/sched: SWAP_NONATOMIC workaround for timeslicing
Timeslicing works by removing the _current thread from the run queue
and re-adding it at the end of its priority.  On systems with a
_Swap() that can be preempted by a timer interrupt, that means it's
possible for the timeslice to try to slice out a thread that had
already pended itself!

This behavior used to be benign (or at least undetectable) as the
duplicated list operations were idempotent.  But now the dlist code is
stricter about correctness and has exposed the bug -- it will blow up
if you try to remove an already-removed list node.

Fix (on affected platforms) by stashing the _current pointer in
_pend_current_thread() that is checked and cleared in the timer
interrupt.  If we discover we're trying to interrupt a thread that's
already interrupted itself, we can safely exit z_time_slice() as a
noop.  The timeslicing bookeeping was already done for us underneath
the pend code.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-15 13:06:35 +01:00
Andy Ross 23c5a63aa8 kernel/sched: Predicate SWAP_NONATOMIC workaround properly
This is a refactoring of the fix in commit 6c95dafd82 to limit its
application to affected platforms now that the root cause is
understood.

Note that the bug that fix was addressing was rare and seen only on
after multi-hour sessions on Michael Scott's test rig.  So if
something regresses, this is where to look!

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-15 13:06:35 +01:00
Andy Ross 7f42dbaf48 kernel: Add CONFIG_SWAP_NONATOMIC flag
On ARM, _Swap() isn't atomic and a hardware interrupt can land after
the (irq_locked) caller has entered _Swap() but before the context
switch actually happens.  This will require some platform-specific
workarounds in a few places in the scheduler.

This commit is just the Kconfig and selection on ARM.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-15 13:06:35 +01:00
Andy Ross 762ff2f428 kernel/swap: Simply/robustify return value handling
The call to _arch_switch is a giant screaming sign inviting optimizer
bugs.  The code that appears before is what happened long ago when we
were switched out, but the version that EXECUTED just now is actually
in a different thread.  So the assignment to _current before the
switch actually assigned OUR thread (the "new_thread" of the old
context!) to _current.

But obviously the optimizer looks at that code and assumes that the
_current which got assigned to the thread we were switching to long
ago is still correct, and used it when retrieving the swap return
value.

Obviously the real bug here is that the _arch_switch() in question
lacked a memory clobber (and it's getting one).

But we can remove two lines, remove code from inside the interrupt
lock and make the implementation more robust by moving the read to
after the irq_unlock() (which generally also has a memory clobber).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-11 15:18:52 -05:00
Andy Ross 4f911e192f kernel: Add missing include
These files were using z_thread_malloc() without including
kernel_internal.h.  On existing architectures that works due to
transitive includes, but x86_64 has a thinner include layer and
doesn't do it for us.  Include the files required for the APIs we use.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-11 15:18:52 -05:00
Aurelien Jarno 513cceb5d1 kernel: Fix asynchronous event polling interface
Commit 76b3518ce6 ("kernel: Make statements evaluate boolean
expressions") changed the type of is_polling in the struct _poller
from int to bool. In the conversion a "0" has been changed into "true"
instead of "false". Fix that.

Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
2019-01-09 17:06:08 -05:00
Flavio Ceolin 6a4a86e413 kernel: Change k_is_in_isr to return bool
Change this function to return a boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-01-07 08:52:07 -05:00
Flavio Ceolin 09e362e0d0 kernel: Change _is_thread_essential to return bool
Change this function to return a boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-01-07 08:52:07 -05:00
Flavio Ceolin 4f2e9a792a kernel: Change is_condition_met signature
Change this function to return a boolean type.

MISRA-C rule 14.4

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

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-01-07 08:52:07 -05:00
Flavio Ceolin 8a1481735b kernel: userspace: Change _thread_idx_alloc to return bool
Make this function return an essential boolean type.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2019-01-07 08:52:07 -05:00
Adithya Baglody 392219eab8 kernel: Change the prototype of k_thread_access_grant.
This API was using variable number of arguments. Which is not
allowed according to misra c guidelines(Rule 17.1). Hence making
this API into a macro and using the util macro FOR_EACH_FIXED_ARG
to get the same functionality.

There is one deviation from the old function. The last argument
shouldn't be NULL.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2019-01-03 12:35:14 -08:00
Andy Ross 9eda9350d8 kernel/timeout: Don't reset imminent timeouts
The logic in z_set_timeout_expiry() missed the case where the ticks
argument could be zero (or lower), which can happen naturally due to
timing/interrupt slop.  In those circumstances, it would still try to
reset a timer that was "about to expire at the next tick", which would
run afoul of the drivers' internal decisions about how soon a timer
interrupt could be set, and then get pushed out to the next tick.

Explicitly detect this as an "imminent" predicate to make the logic
clearer.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-03 12:29:02 -05:00
Andy Ross bb86f2019c kernel/sched: Remove stale comment
The recent change that added a locked z_set_timeout_expiry() API
obsoleted the subtle note about synchronization above
reset_time_slice().  None of that matters any more, the API is
synchronized internally in a conventional way.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-03 12:29:02 -05:00
Andy Ross 71f5e56545 kernel/timeout: Fix "not in list" predication in timeout handling
The use of dticks == INACTIVE to tell whether or not a timeout was
already in the list was insufficient.  There is a time period between
the moment a timeout is removed from the list and the end of its
handler where it is not in the list, yet its list node pointers still
point into it.  Doing things like aborting a thread while that is true
(which can be asynchronous too!)  would corrupt the list even though
all the operations on it were "atomic".

Set the timeout node pointers to nulls atomically when removed, and
check for double-remove conditions (which, again, might be perfectly
OK).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-03 12:29:02 -05:00
Andy Ross 43ab8da953 kernel/timeout: Refactor z_clock_announce() loop
This loop was structured badly, as a while(true) with multiple "exit
if" cases in the body.  It was bad enough that I genuinely fooled
myself into rewriting it, having convinced myself there was a bug in
it when there wasn't.

So keep the rewritten loop which expresses the iteration in a more
invariant way (i.e. "while we have an element to expire" and not "test
if we have to exit the loop").  Shorter and easier.  Also makes the
locking clearer as we can simply release the lock around the callback
in a natural/obvious way.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2019-01-03 12:29:02 -05:00
Sebastian Bøe 204f05b23a kconfig: Minor comments and 'help' text fixes
Minor comments and 'help' text fixes.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-12-30 16:24:50 -05:00
Sebastian Bøe f42ed32dc5 Kconfig: Hide SMP and USE_SWITCH from unsupported platforms
Don't present USE_SWITCH and SMP to user applications that are
configuring for platforms that do not support SMP or USE_SWITCH.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-12-30 16:24:50 -05:00
Sebastian Bøe 21d69579f5 kconfig: Have the 'SMP' option depend on 'USE_SWITCH'
SMP requires the new-style '_arch_switch' to be enabled. To prevent
users from creating invalid configurations where SMP is enabled while
_arch_switch is not, we add a dependency from SMP to USE_SWITCH.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-12-30 16:24:50 -05:00
Sebastian Bøe 4019bda695 kconfig: Disable 'RETPOLINE' on unsupported platforms
RETPOLINE has been enabled by default on most platforms, but it is
only supported on X86.

Features should only be enabled if they are supported and active on
the given platform. To rectify this we have RETPOLINE depend on X86,
the only platform on which it is implemented.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-12-30 16:24:50 -05:00
Anas Nashif 74a74bb6b8 power: rename api sys_soc -> sys_
sys_soc is just redundant, just call APIs with sys_*.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-12-28 16:16:28 -05:00
Anas Nashif 9151fbebf2 power: rename APIs and removing leading _
Remove leading underscore from PM APIs. _ was used for internal APIs.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-12-28 16:16:28 -05:00
Andrew Boie 74f114caef userspace: easy checking for specific driver
In general driver system calls are implemented at a subsystem
layer. However, some drivers may have capabilities specific to
the hardware not covered by the subsystem API. Such drivers may
want to define their own system calls.

This macro makes it simple to validate in the driver-specific
system call handlers that not only does the untrusted device
pointer correspond to the expected subsystem, initialization
state, and caller permissions, but also that the device object
is an instance of a specific driver (and not just any driver in
that subsystem).

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-12-27 20:31:58 -05:00
Flavio Ceolin b82a339813 kernel: init: Add nop instruction in main
The main function is just a weak function that should be override by the
applications if they need. Just adding a nop instructions to explicitly
says that this function does nothing.

MISRA-C rule 2.2

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-14 13:17:36 +01:00
Flavio Ceolin 4f6020111c kernel: Use NULL instead of 0
MISRA-C rule 11.9

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-11 14:37:10 -08:00
Anas Nashif 69c758436c doc: add kernel version API to doxygen
Put kernel version API into doxygen and make it available as a
documented API.

Fixes #6319

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-12-08 17:24:53 -05:00
Andrew Boie a68120de6d kernel: check retval of driver init
If initialization fails, zero the API struct so that
device_get_binding() can't fetch it, and do not mark
the driver object as initialized to user mode.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-12-07 19:33:23 -05:00
Adithya Baglody 91c5b84cd5 kernel: init.c: Added required hooks for the relocation
This patch splits the text section into 2 parts. The first section
will have some info regarding vector tables and debug info. The
second section will have the complete text section.
This is needed to force the required functions and data variables
the correct locations.
This is due to the behavior of the linker. The linker will only link
once and hence this text section had to be split to make room
for the generated linker script.

Added a new Kconfig CODE_DATA_RELOCATION which when enabled will
invoke the script, which does the required relocation.

Added hooks inside init.c for bss zeroing and data copy operations.
Needed when we have to copy data from ROM to required memory type.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-12-07 10:32:41 -05:00
Flavio Ceolin 118715c62d misra: Fixes for MISRA-C rule 8.3
MISRA-C says all declarations of an object or function must use the
same name and qualifiers.

MISRA-C rule 8.3

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-07 09:06:34 -05:00
Flavio Ceolin 4b35dd2628 misra: Fixes for MISRA-C rule 8.2
In C90 was introduced function prototype, that allows argument types
to be checked against parameter types, though it is not necessary
specify names for the parameters. MISRA-C requires names for function
prototype parameters, it claims that names can provide useful
information regarding the function interface.

MISRA-C rule 8.2

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-07 09:06:34 -05:00
Flavio Ceolin 26be3355ac kernel: sched: Fix undefined behavior
The order of evaluation of function calls in the arguments of a
function. This is undefined (32)/ unspecified(15-18) in C99.

MISRA-C rule 13.2 does not allow that a value of an expression and its
side effects happens in not deterministic order to avoid these
undefined behaviors.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-07 09:06:34 -05:00
Flavio Ceolin d7271ec9db kernel: poll: Fix switch usage
According with MISRA-C and unconditional break statement must
terminate every switch-clause.

MISRA-C rule 16.1 and 16.3

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-07 09:06:34 -05:00
Flavio Ceolin a42de6466a kernel: queue: Fix MISRA-C violation
MISRA-C requires the right-hand operand of && or || operator does not
contain persistent effect.

MISRA-C rule 13.5

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-12-07 09:06:34 -05:00
Ioannis Glaropoulos ccf813c22a kernel: mem_domain: remove redundant clearing of mem_partition fields
When a memory partition is removed, it is not required
to clear the start and attr fields, since a free partition
is only indicated by a zero size field. This commit removes
the un-necessary clearing of start and attr fields.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-12-05 15:15:07 -05:00
Nicolás Bértolo 258fd2dbeb kernel: mutex: delay setting lock_count = 0.
It is necessary to delay setting lock_count = 0 because an unlocking thread
maybe swapped out when it calls adjust_owner_prio(). If the thread that starts
running sees lock_count = 0 it will successfully acquire the mutex even though
it is not fully unlocked yet.

Fixes #11798.

Signed-off-by: Nicolás Bértolo <nicolasbertolo@gmail.com>
2018-12-05 11:00:10 +01:00
Patrik Flykt d0d9eb0e38 kernel: Add 'U' to unsigned variable assignments
Add 'U' to a value when assigning it to an unsigned variable.
MISRA-C rule 7.2

Signed-off-by: Patrik Flykt <patrik.flykt@intel.com>
2018-12-04 22:51:56 -05:00
Peter A. Bigot 1fa00f3b36 kernel: remove outdated comment in _Cstart
The comment explaining why _IntLibInit was being invoked was left in
place after the invocation itself was removed.  Remove it too.

Signed-off-by: Peter A. Bigot <pab@pabigot.com>
2018-12-03 09:18:06 -08:00
Flavio Ceolin b7287ceb4e kernel: syscall: Object validation checks boolean statement
The function that checks if an object is valid is essentially a boolean
function. Just changing its return type to reflect it.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-30 08:05:11 -08:00
Flavio Ceolin 80418602ed kernel: sched: Make boolean functions return bool
MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-30 08:05:11 -08:00
Andrew Boie 2b1d54e897 kernel: add user mode work_q capability
This allows for workqueues to be started in user mode.
No additional kernel objects or system calls are defined
other than starting the workqueue in user mode; for
permission purposes the embedded queue and thread objects
are sufficient.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-11-29 09:21:18 -08:00
Andrew Boie 8acf899a0d workqueues: remove object init calls
k_work and k_work_q are not kernel objects, nor will they
be. k_work_q contains some kernel objects which are tracked
independently.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-11-29 09:21:18 -08:00
Flavio Ceolin 46715faa5c kernel: Remove _IntLibInit function
There were many platforms where this function was doing nothing. Just
merging its functionality with _PrepC function.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-28 14:59:10 -08:00
Pawel Dunaj baea22407d kernel: Always set clock expiry with sync with timeout module
System must not set the clock expiry via backdoor as it may
effect in unbound time drift of all scheduled timeouts.

Fixes: #11502

Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
2018-11-26 12:24:59 +01:00
Piotr Mienkowski 970aef2905 kernel: ensure System Power Managment enables Tickless Idle.
System Power Management is only supported in Tickless Idle mode.
This patch modifies Kconfig dependencies to ensure System Power
Management option selects Tickless Idle one.

Fixes: #11046

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
2018-11-21 23:16:35 -05:00
Andy Ross 02165d76a0 kernel/timeout: Fix race with clock timeout setting
The call to z_clock_set_timeout() was being made outside the timeout
lock, which can race against other contexts setting sooner-expiring
timeouts.

Also add a long comment to one spot (timeslicing) where this call is
made outside the timeout spinlock (inside the scheduler lock) and why
this is OK.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-11-21 12:52:49 +01:00
Sathish Kuttan a8aa235d9b kernel: msg_q: k_msgq_peek() implementation
Add implementation for k_msgq_peek() which is similar to k_msgq_get()
except the message is not deleted from the queue.

Signed-off-by: Sathish Kuttan <sathish.k.kuttan@intel.com>
2018-11-19 17:53:22 -05:00
Andrew Boie 42cfd4ff26 kernel: expose k_busy_wait() to user mode
If we just had the kernel's implementation, we could
just move this to lib/, but possible arch-specific
implementations dictate that we just make this a
syscall.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-11-15 16:20:36 -05:00
Andrew Boie f253d0779d k_mem_slab: track as a kernel object
We aren't going to allow any user mode access to the
k_mem_slab APIs, but in some cases (specifically in the
case of the I2S subsystem) we need to allow user mode
to assign a memory slab to a particular driver.

This will let us verfiy (in supervisor mode) that a provided
k_mem_slab pointer is really a k_mem_slab, and know its
initialization state, and have permissions assigned to it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-11-15 16:20:36 -05:00
Ioannis Glaropoulos d8b51ea9cd kernel: mem_domain: optimize sane partition checking
This commit optimizes the process of checking that the
added partitions in a mem_domain are sane. It places the
sane_partition checking inside the loop of adding the
partitions in the mem_domain, so that the checkings are
not performed twice, and no partition is checked against
itself.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-11-15 08:18:59 -05:00
Ioannis Glaropoulos 3e390ed42d kernel: mem_domain: fix partition end address calculations
This commit fixes the calculations of the partition ending
addresses in two places in the code, according to:
<last> = <start> + <size> - 1. We also rename 'end' to 'last'
to stress that we calculate the last address in the partition.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-11-15 08:18:59 -05:00
Andrew Boie 9d14874db1 kernel: expose device_get_binding() to user mode
User mode may need to use this API to get a handle on
devices by name, expose as a system call. We impose
a maximum name length as the system call handler needs
to make a copy of the string passed in from user mode.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-11-13 19:06:05 -05:00
Andy Ross 1c3051459b kernel/sched: Fix race in k_sched_time_slice_set()
If this function is itself interrupted by a timeslice event, the
slicing state can be corrupted.  Just re-use the scheduler lock
instead of using a new spinlock; this is a low-latency function that
won't deadlock.  Found by inspection.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-11-13 17:10:07 -05:00
Andy Ross c0a184c067 drivers/timer: Select tickless via driver kconfig flag
Add a TICKLESS_CAPABLE kconfig variable which is used by the kernel to
select tickless mode's default automatically on drivers that support
it (rather than having to set the default per-board).  Select it from
the ARM SysTick and Intel HPET drivers.

Also remove the old qemu_cortex_m3 default settings which this
replaces.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-11-13 17:10:07 -05:00
Flavio Ceolin 22236c9d6d kernel: Make tag identifiers unique
Some places are using the same tag identifier with different types.
This is a MISRA-C violation and makes the code less readable.

MISRA-C rule 5.7

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-06 16:20:15 -05:00
Flavio Ceolin aecd4ecb8d kernel: Change k_poll_signal api
k_poll_signal was being used by both, struct and function. Besides
this being extremely error prone it is also a MISRA-C violation.
Changing the function to contain a verb, since it performs an action
and the struct will be a noun. This pattern must be formalized and
followed and across the project.

MISRA-C rules 5.7 and 5.9

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-04 11:37:24 -05:00
Flavio Ceolin dfbe03249d kernel: stack: Making if's body a compound statement
MISRA-C rule 15.6

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-04 11:37:24 -05:00
Flavio Ceolin a406b88fca kernel: Remove duplicated identifier
There was an struct and a variable called _kernel. This is error prone
and a MISRA-C violation. It is changing the struct to have a unique
identifier.

MISRA-C rule 5.8

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-04 11:37:24 -05:00
Flavio Ceolin ac14685211 kernel: Delimiting the scope of some variables
According with MISRA-C an object should be defined in a block scope if
it is used in a single function.

MISRA-C rule 8.9

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-04 11:37:24 -05:00
Flavio Ceolin 4369363f6c kernel: mutex: Change variable declaration
This is not violating any MISRA-C rule, though, it seems to be
triggering a false (rule 9.1) positive in some static analysis
tools. Nevertheless, it is more readable declare all variables in the
same scope together.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-11-04 11:37:24 -05:00
Flavio Ceolin a3dddedab6 kernel: Use distinct macro names
There is a struct and a macro called _ready_q, this is error
prone. Just removing it.

MISRA-C rule 5.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-10-31 19:43:47 -04:00
Adithya Baglody 87e592ebda kernel: mutex.c: MISRA C compliance.
This patch fixes few MISRA issues present in mutex.c.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-31 08:44:47 -04:00
Adithya Baglody fac6885e55 kernel: alert: Declare tracing variables only when needed.
The tracing variable in alert.c was declared by default. This
should have been declared only when CONFIG_OBJECT_TRACING is set.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-31 08:44:47 -04:00
Adithya Baglody 2a78b8d86f kernel: queue: MISRA C compliance.
This patch fixes few issues in queue.c. This patch also changes
the return type of k_queue_alloc_append and k_queue_alloc_prepend
from int to s32_t.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-31 08:44:47 -04:00
Adithya Baglody 8feda92abc kernel: device: MISRA C compliance.
This patch fixes few issues in device.c.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-31 08:44:47 -04:00
Piotr Zięcik 7700eb2a15 kernel: sched: Make k_sleep() similar to POSIX equivalent
This commit introduces k_sleep() return value, which provides
information about actual sleep time. If the returned value is
not-zero, the thread slept shorter than requested, which is
only possible if the thread has been woken up by k_wakeup() call.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2018-10-30 18:27:31 +01:00
Marek Pieta e87193896a subsys: debug: tracing: Fix thread tracing
Change fixes issue with thread execution tracing.

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
2018-10-29 22:09:12 -04:00
Ioannis Glaropoulos 3e02f38a38 kernel: mem_domain: minor typo fixes
Fixing a few minor typo fixes in kernel/mem_domain.c
and the respective documentation section.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-10-29 12:34:12 -04:00
Kumar Gala 0776392e4c kernel: msq_q: Fix compile warning
Fix a compile warning if we build using int types defined to match the
compiler.  We get the following warnings:

kernel/msg_q.c: In function ‘_impl_k_msgq_alloc_init’:
kernel/msg_q.c:75:9: warning: passing argument 3 of ‘__builtin_umul_overflow’ from incompatible pointer type [-Wincompatible-pointer-types]
         (u32_t *)&total_size)) {
         ^
kernel/msg_q.c:75:9: note: expected ‘unsigned int *’ but argument is of type ‘u32_t * {aka long unsigned int *}’

__builtin_umul_overflow expects to be passed unsigned int for all its
arguments, so cast to that instead of u32_t.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2018-10-29 10:52:00 -04:00
Spoorthi K b6cd192fa5 kernel: sched: Fix compiler warning
Ignore return value of _Swap() as it is not
used anywhere.

Signed-off-by: Spoorthi K <spoorthi.k@intel.com>
2018-10-24 09:48:17 +01:00
Paul Sokolovsky d91c11f5bf kernel: system_work_q: Set dedicated "sysworkq" name.
Previously, a generic "workqueue" name was used, but there're few
workqueues in a typical Zephyr setup, and it wasn't possible to
distinguish them.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2018-10-19 07:58:45 -04:00
Adithya Baglody 4b066212b6 kernel: sem: Fix few MISRA C violations.
This patch fixes few of the violations inside sem.c

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-17 12:17:58 -04:00
Adithya Baglody 6176692f4b kernel: ksched.h: Incorrect argument type in _pend_current_thread
In _pend_current_thread the argument key is always a unsigned
interger type and this function forces it to become a signed
interger. This is a dangerous behavior and cant be trusted to
work as expected.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-17 12:17:58 -04:00
Andy Ross 386894c2fb kernel/timeout: Fix build breakage due to stdio name collision
Duh: "remove()" is a POSIX symbol, and on at least some platforms
stdio.h can be included here out of platform headers causing a name
collision.

Fixes #10669's direct issue, though the broader issue of how to choose
names for statics remains controversial.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-17 12:15:44 -04:00
Paul Sokolovsky b779ea2d19 kernel: syscall_handler.h: Typo fix in docstring
Should be "fails" instead of "files".

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2018-10-17 10:32:10 -04:00
Adithya Baglody 28080d3896 kernel: MISRA C: Fixes a few MISRA C issues.
MISRA C guideline compliance for various rules.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-17 07:59:51 -04:00
Adithya Baglody 1424561252 kernel: sched: Fixed incorrect argument type of _reschedule()
This API shouldn't take a int type but instead it should take
u32_t. This argument has to be similar to irq_lock() and
irq_unlock().

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-10-17 07:59:51 -04:00
Andy Ross 7a035c0dc7 kernel/sched: Fix timeslice accounting for already-elapsed ticks
In tickless mode, not all elapsed ticks may have been announced yet,
so future z_time_slice() calls will include "extra" ticks that we have
to account for when setting up the slice count.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 7617371ecc kernel/timeout: Clamp ticks argument to lower bound
Our funny convention holds that passing ticks==1 to _add_timeout()
means "at the next tick".  But that means that 1, 0, and all negative
numbers are expected to behave the same.  In ticked mode, that's fine
because it will, after all, expire at the next tick.

But in tickless, the next announcement may be for several ticks, and
that zero will appear to expire "before" the next tick in the
consumption loop.

Make sure all "next tick" expirations look the same.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 9ce9677888 kernel/timeout: Fix elapsed logic
When fetching the next timeout to expire, the value is relative to the
last announced tick, so you subtract the timer-provided elapsed time
to get the true delta from "now".  When adding a new timeout, you
*have* a value relative to now, so you compute the delta vs. the last
announced tick by adding the elapsed() time.  Duh.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 1cfff07480 kernel/timeout: Fix announcement tick logic
This was wrong in subtle ways.  In tickless mode it's possible to get
an announcement for multiple ticks at a time and have multiple
callbacks to execute that were technically scheduled at different
times.  We want to fix the current tick at the value represented by
the currently-executing callback's EXPIRATION (even if we missed it!),
so that any new timeouts it sets (c.f. a k_timer period) happen at the
right point, in phase with the expected series.  In single-tick mode
the code ends up the same always, so the bug wasn't visible.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross d8421adadd kernel/timeout: Fix synchronization in z_tick_get_32()
The previous comment correctly and carefully explained why the 64 bit
value in curr_tick doesn't require locking when reading only the low
32 bits.

It completely missed the fact that the calculation of elapsed time and
the read of curr_tick ABSOLUTELY DO require locking, because the
former is expressed in terms of the latter.  This was always bug, even
in the old code, but never witnessed because we ran so little software
in tickless mode.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 1129ea9394 kernel/sched: Fix timeslicing predicate
It's possible to interrupt a thread that has already scheduled a
timeout.  Really this is a race against the usage of
_add_thread_timeout() and needs some design work to provide proper
locking (which is a distinct requirement from the scheduler lock and
timeout lock!), as the users of that API are spread around the kernel.
But existing usage always schedules the timeouts first, so this is
safe.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 2dd9e2cad4 kernel/sched: Remove spurious locking
The timeout APIs are properly synchronized now.  This irq_lock() (and
the comment explaining it) isn't needed anymore.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 08397277fc kernel/kconfig: Move TICKLESS options out of power management tree
These options are rapidly becoming a default configuration, which is
complicated by having them be hidden inside of a SYS_POWER_MANAGEMENT
variable that has to be enabled first.  Put them at the top level of
the kernel config.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross cfe62038d2 kernel: Checkpatch fixups
I was pretty careful, but these snuck in.  Most of them are due to
overbroad string replacements in comments.  The pull request is very
large, and I'm too lazy to find exactly where to back-merge all of
these.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 987c0e5fc1 kernel: New timeout implementation
Now that the API has been fixed up, replace the existing timeout queue
with a much smaller version.  The basic algorithm is unchanged:
timeouts are stored in a sorted dlist with each node nolding a delta
time from the previous node in the list; the announce call just walks
this list pulling off the heads as needed.  Advantages:

* Properly spinlocked and SMP-aware.  The earlier timer implementation
  relied on only CPU 0 doing timeout work, and on an irq_lock() being
  taken before entry (something that was violated in a few spots).
  Now any CPU can wake up for an event (or all of them) and everything
  works correctly.

* The *_thread_timeout() API is now expressible as a clean wrapping
  (just one liners) around the lower-level interface based on function
  pointer callbacks.  As a result the timeout objects no longer need
  to store backpointers to the thread and wait_q and have shrunk by
  33%.

* MUCH smaller, to the tune of hundreds of lines of code removed.

* Future proof, in that all operations on the queue are now fronted by
  just two entry points (_add_timeout() and z_clock_announce()) which
  can easily be augmented with fancier data structures.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 52e444bc05 kernel: Move timeout_remaining API
_timeout_remaining_get() was a function on a struct _timeout, doing
iteration on the timeout list, but it was defined in timer.c (the
higher level abstraction).

Move it to where it belongs.  Also have it return ticks instead of ms
to conform to scheme in the rest of the timeout API.  And rename it to
a more standard zephyr name.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 96013b0375 system_timer.h: Change "now" uptime API to be simpler for drivers
The current z_clock_uptime() call (recently renamed from
_get_elapsed_program_time) requires the driver to track a full 64 bit
uptime value in ticks, which is entirely separate from the one the
kernel is already keeping.

Don't do that.  Just ask the drivers to track uptime since the last
call to z_clock_announce(), since that is going to map better to
built-in hardware capability.

Obviously existing drivers already have this feature, so they're
actually getting slightly larger in order to implement the new API in
terms of the old one.  But future drivers will thank us.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross fe82f1c2af kernel/timeout: Refactor API
Add the callback parameter to add_timeout(), and remove the thread
argument.  Now the "low level" timeout API can be expressed without
reference to threads.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 5d203523b6 kernel/timeout: Eliminate wait_q parameters from API
Now that this is known to be an unused value, remove it from the API.
Note that this caught a few spots where we were passing values (a
non-NULL wait_q with a NULL thread handle) that were always being
ignored before.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross d61b1f8ef8 kernel/timeout: Remove timeout wait_q field
Per previous patch, this is known to be identical with
thread->pended_on.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 15d520819d kernel/timeout: Prepare unification of timeout/thread wait_q fields
The existing timeout API wants to store a wait_q on which the thread
is waiting, but it only uses that value in one spot (and there only as
a boolean flag indicating "this thread is waiting on a wait_q).

As it happens threads can already store their own backpointers to a
wait_q (needed for the SCALABLE scheduler backend), so we should use
that instead.

This patch doesn't actually perform that unification yet.  It
reorgnizes things such that the pended_on field is always set at the
point of timeout interaction, and adds a bunch of asserts to make 100%
sure the logic is correct.  The next patch will modify the API.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 2ae8f50936 kernel/include: Move stubs for timeout functions to their declarations
The timeout_q.h scheme, where it declared real functions, but the
stubs for when there was no clock were in wait_q.h was senselessly
weird.  Put them in the same file.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 9098a45c84 kernel: New timeslicing implementation
Instead of checking every time we hit the low-level context switch
path to see if the new thread has a "partner" with which it needs to
share time, just run the slice timer always and reset it from the
scheduler at the points where it has already decided a switch needs to
happen.  In TICKLESS_KERNEL situations, we pay the cost of extra timer
interrupts at ~10Hz or whatever, which is low (note also that this
kind of regular wakeup architecture is required on SMP anyway so the
scheduler can "notice" threads scheduled by other CPUs).  Advantages:

1. Much simpler logic.  Significantly smaller code.  No variance or
   dependence on tickless modes or timer driver (beyond setting a
   simple timeout).

2. No arch-specific assembly integration with _Swap() needed

3. Better performance on many workloads, as the accounting now happens
   at most once per timer interrupt (~5 Hz) and true rescheduling and
   not on every unrelated context switch and interrupt return.

4. It's SMP-safe.  The previous scheme kept the slice ticks as a
   global variable, which was an unnoticed bug.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 8b54953e4b kernel/sys_clock: Fix build when !SYS_CLOCK_EXISTS
This got broken.  Add some #ifery to handle the case.  Not clean, will
clean up in a future pass once the API is final.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 25863549be kernel: Remove clock_always_on control from k_busy_wait()
This feature was a useless noop based on mistaken API understanding.

The idea seems to have been that k_busy_wait() included guards to
ensure "clock_always_on" was true duing the loop, presumably because
the original author was afraid that "turning the clock off" would
affect the operation of k_cycle_get_32().

Then later someone came around and "optimized" this for Quark SE,
where the cycle counter is the RTC and unrelated to the timer driver
used by the clock_always_on feature.  (Except even there it presumably
should have been done at the SoC level and not just in the C1000
devboard -- note that Arduino 101 never would have gotten this).

But it was all a mistake: "clock_always_on" has nothing to do with
en/disabling the system cycle timer (which never happens when the
system is active, that's a feature of idle), it's a control over the
delivery of timer interrupts.  And needless to say we don't care about
timer interrupts when we're spinning on a cycle counter.

Yank the whole mess.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 1b3149cea1 kernel/sys_clock.c: Add asserts to watch dueling "set time" APIs
The current API has an rather unfortuate collision between two APIs:
z_clock_announce(), which is called out of the timer interrupt to
inform the kernel of time passage (and which is responsible for
invoking timer callbacks), and z_tick_set(), which is ALSO used by the
timer drivers for... confusing and inconsistent purposes.

This is sort of a mess.  The tick_set API needs to go away, but before
that I'm adding some assertions to at least make sure the existing
drivers are using them consistently.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 1c08aefe56 kernel/timeoutq: Uninline the timeout methods
There was no good reason to have these rather large functions in a
header.  Put them into sys_clock.c for now, pending rework to the
system.

Now the API is clearly visible in a small header.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 7aae75bd1c idle: Fix tickless timeout behavior
If the idle code was detecting that it needed to sleep for less than
CONFIG_SYS_TICKLESS_IDLE_THRESH, then it would never call
z_clock_set_timeout() at all, which means that the system would never
wake up unless it already had a timeout scheduled!  Apparently we
lacked a test case to detect this condition.

Honestly this seems like a crazy feature to me.  There's no benefit in
delivering needless tick announcements.  If the system has the
capacity to enter deeper sleep for long timeouts, that's already
exposed via the PM APIs, the timer subsystem needn't be involved.
But... we actually have a test (tickless_concept) that looks at this,
so support it for now and consider deprecation later.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross d7b35c9bd6 idle: Remove needless "expired" logic in sys_power_save_idle()
This code (just refactored as part of the timer API work) turns out to
be needless.  It's trying to detect the case where we're being asked
to idle for zero time, but that's not possible with a properly
functioning timer driver: the call to z_clock_announce() must happen
out of an interrupt, and this is the idle thread, which must sit below
any possible interrupt priority.  The call to z_clock_uptime() must
not ever return "too late" until after the timer interrupt has fired,
at which point we'll be inspecting the next timeout (which itself is
guaranteed to be in the future for the same reason).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 722a888ef7 timer: Clean up hairy tickless APIs
The tickless driver had a bunch of "hairy" APIs which forced the timer
drivers to do needless low-level accounting for the benefit of the
kernel, all of which then proceeded to implement them via cut and
paste.  Specifically the "program_time" calls forced the driver to
expose to the kernel exactly when the next interrupt was due and how
much time had elapsed, in a parallel API to the existing "what time is
it" and "announce a tick" interrupts that carry the same information.

Remove these from the kernel, replacing them with synthesized logic
written in terms of the simpler APIs.

In some cases there will be a performance impact due to the use of the
64 bit uptime call, but that will go away soon.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 1a1a9539ea include/system_timer.h: Timer API cleanup
Rename timer driver API functions to be consistent.  ADD DOCS TO THE
HEADER so implementations understand what the requirements are.
Remove some unused functions that don't need declarations here.

Also removes the per-platform #if's around the power control callback
in favor of a weak-linked noop function in the driver initialization
(adds a few bytes of code to default platforms -- we'll live, I
think).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross ab488277bc drivers/timer: Unify timeout setting APIs
The existing API had two almost identical functions: _set_time() and
_timer_idle_enter().  Both simply instruct the timer driver to set the
next timer interrupt expiration appropriately so that the call to
z_clock_announce() will be made at the requested number of ticks.  On
most/all hardware, these should be implementable identically.

Unfortunately because they are specified differently, existing drivers
have implemented them in parallel.

Specify a new, unified, z_clock_set_timeout().  Document it clearly
for implementors.  And provide a shim layer for legacy drivers that
will continue to use the old functions.

Note that this patch fixes an existing bug found by inspection: the
old call to _set_time() out of z_clock_announce() failed to test for
the "wait forever" case in the situation where clock_always_on is
true, meaning that a system that reached this point and then never set
another timeout would freeze its uptime clock incorrectly.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross fa99ad66d0 sys_clock: Fix up tick announce API
There were three separate "announce ticks" entry points exposed for
use by drivers.  Unify them to just a single z_clock_announce()
function, making the "final" tick announcement the business of the
driver only, not the kernel.

Note the oddness with "_sys_idle_elapsed_ticks": this was a global
variable exposed by the kernel.  But it was never actually used by the
kernel.  It was updated and inspected only within the timer drivers,
and only so that it could be passed back to the kernel as the default
(actually hidden) argument to the announce function.  Break this false
dependency by putting this variable into each timer driver
individually.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 317178b88f sys_clock: Fix unsafe tick count usage
The system tick count is a 64 bit quantity that gets updated from
interrupt context, meaning that it's dangerously non-atomic and has to
be locked.  The core kernel clock code did this right.

But the value was also exposed to the rest of the universe as a global
variable, and virtually nothing else was doing this correctly.  Even
in the timer ISRs themselves, the interrupts may be themselves
preempted (most of our architectures support nested interrupts) by
code that wants to set timeouts and inspect system uptime.

Define a z_tick_{get,set}() API, eliminate the old variable, and make
sure everyone uses the right mechanism.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross b8ffd9acd6 sys_clock: Make clock_always_on true by default
This flag is an indication to the timer driver that the OS doesn't
care about rollover conditions of the tick count while idling, so the
system doesn't need to wake up once per counter flip[1].  Obviously in
that circumstance values returned from k_uptime_get_32() are going to
be wrong, so the implementation had an assert to check for misuse.

But no one understood that from the docs, so the only place these APIs
were used in practice were as "guards" around code that needed to call
k_uptime_get_32(), even though that's 100% wrong per docs!

Clarify the docs.  Remove the incorrect guards.  Change the flag to
initialize to true so that uptime isn't broken-by-default in tickless
mode.  Also move the implemenations of the functions out of the
header, as there's no good reason for these to need to be inlined.

[1] Which can be significant.  A 100MHz ARM using the 24 bit SysTick
    counter rolls over at about 6 Hz, and if it had to come out of
    idle at that rate it would be a significant power issue that would
    swamp the gains from tickless.  Obviously systems with slow
    counters like nRF or 64 bit ones like RISC-V or x86's TSC aren't
    as affected.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross b2e4283555 sys_clock: Make sys_clock_hw_cycles_per_tick() a proper API
This was another "global variable" API.  Give it function syntax too.
Also add a warning, because on nRF devices (at least) the cycle clock
runs in kHz and is too slow to give a precise answer here.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 393ec71ec3 clock: Remove CONFIG_TICKLESS_KERNEL_TIME_UNIT_IN_MICRO_SECS
This was only used in a few places just to indirect the already
perfectly valid SYS_CLOCK_TICKS_PER_SEC value.  There's no reason for
these to ever have been kconfig units, and in fact the distinction
appears to have introduced a hidden/untested bug in the power
subsystem (the two variables were used interchangably, but they were
defined in reciprocal units!).

Just use "ticks" as our time unit pervasively, and clarify the docs to
explain that.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Andy Ross 220d4f8347 sys_clock.h: Make "global variable" APIs into proper functions
The existing API defined sys_clock_{hw_cycles,ticks}_per_sec as simple
"variables" to be shared, except that they were only real storage in
certain modes (the HPET driver, basically) and everywhere else they
were a build constant.

Properly, these should be an API defined by the timer driver (who
controls those rates) and consumed by the clock subsystem.  So give
them function syntax as a stepping stone to get there.

Note that this also removes the deprecated variable
_sys_clock_us_per_tick rather than give it the same treatment.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-10-16 15:03:10 -04:00
Anas Nashif c77c043071 kernel: remove deprecated k_thread_cancel
Remove deprecated function k_thread_cancel. We now use k_thread_abort.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-10-09 13:58:01 -04:00
Anas Nashif 0a0c8c831f kernel: move to new logger
Use the new logger framework for kernel.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-10-08 17:49:12 -04:00
Flavio Ceolin 18af4c6299 kernel: Fix overflow test problem introduced in 92ea2f9
The builtin function __builtin_umul_overflow returns a boolean and
should not checked as an integer.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-10-04 05:20:29 -07:00
Flavio Ceolin 061a2c5b63 kernel: mempool: Remove unnecessary condition check
Removing an unnecessary check in k_mem_pool_alloc. The condition is
already being checked in the if.

MISRA-C rule 14.3

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 07:58:19 +05:30
Flavio Ceolin 3e97acc7f2 kernel: Sanitize if else statement according with MISRA-C
A final else statement must be provided when an if statement is
followed by one or more else if.

MISRA-C rule 15.7

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 07:58:19 +05:30
Flavio Ceolin 0b14866437 kernel: sys_clock: Remove unnecessary if
When delta_ticks_from_prev is not 0, the variable ticks will necessarily
be lesser or equal 0, so the if checking that is no necessary.

MISRA-C rule 15.7

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 07:58:19 +05:30
Flavio Ceolin 6fc84feaf2 kernel: syscalls: Change handlers namespace
According C99 the first 31 characters of an identifier must be unique.
Shortening the namespace of the generated objects to achieve it.

C99 - 5.2.4.1
MISRA-C rule 5.1

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 07:58:19 +05:30
Mark Ruvald Pedersen d67096da05 portability: Avoid void* arithmetics which is a GNU extension
Under GNU C, sizeof(void) = 1. This commit merely makes it explicit u8.

Pointer arithmetics over void types is:
 * A GNU C extension
 * Not supported by Clang
 * Illegal across all ISO C standards

See also: https://gcc.gnu.org/onlinedocs/gcc/Pointer-Arith.html

Signed-off-by: Mark Ruvald Pedersen <mped@oticon.com>
2018-09-28 07:57:28 +05:30
Flavio Ceolin ea716bf023 kernel: Explicitly comparing pointer with NULL
MISRA-C rule: 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 06:28:41 +05:30
Flavio Ceolin 92ea2f9189 kernel: Calling Z_SYSCALL_VERIFY_MSG with boolean expressions
Explicitly making a boolean expression when calling
Z_SYSCALL_VERIFY_MSG macro.

MISRA-C rule: 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 06:28:41 +05:30
Flavio Ceolin 02ed85bd82 kernel: sched: Change boolean APIs to return bool
Change APIs that essentially return a boolean expression  - 0 for
false and 1 for true - to return a bool.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 06:28:41 +05:30
Flavio Ceolin d8837c6888 kernel: Using boolean expression on ASSERT macros
ASSERT macro expects a boolean expression, making it
explicit.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 06:28:41 +05:30
Flavio Ceolin 6fdc56d286 kernel: Using boolean types for boolean constants
Make boolean expressions use boolean types.

MISRA-C rule 14.4

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-28 06:28:41 +05:30
Anas Nashif 57554055d2 kernel: add a new API for setting thread names
Added k_thread_name_set() and enable thread name setting when declaring
static threads. This is enabled only when THREAD_MONITOR is used. System
threads get a name by default.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-09-27 08:58:55 +05:30
Ioannis Glaropoulos 57b7c3ded9 kernel: improve help text of INIT_STACKS option
This commit improves the help text of INIT_STACKS
Kconfig option, so it indicates that the stack
initialization applies also to the interrupt stack.

Fixes #7196.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-09-26 18:26:03 -05:00
Sebastian Bøe c0287695fb kconfig: Remove remnants of unimplemented BUILD_TIMESTAMP feature
The Kconfig option CONFIG_BUILD_TIMESTAMP became unused when
BUILD_VERSION was introduced, but it's option and parts of it's
implementation was not completely cleaned from the repository.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-09-26 22:18:29 +05:30
Paul Sokolovsky 2df1829c55 kernel: thread: Typo fixes in comment
Typo fixes in comment to k_thread_foreach().

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2018-09-26 17:46:23 +05:30
Daniel Leung 7228a60173 kernel: Fix compilation errors when CONFIG_TIMESLICING=n
Add ifdef guard to the z_reset_timeslice() to fix compilation
errors when CONFIG_TIMESLICING is disabled.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2018-09-25 12:54:58 +05:30
Ioannis Glaropoulos 66192618a7 arch: arm: Minor style and typo fixes in inline comments
Several style and typo fixes in inline comments of arm kernel
files and thread.c.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-09-24 04:56:34 -07:00
Findlay Feng 3c834bdf27 kernel: Fix list-node add again corruption case in timeout handling
The node of the timeout temporary list cannot be continued
to index the next node after being added again.

Signed-off-by: Findlay Feng <i@fengch.me>
2018-09-21 13:29:09 -04:00
Anas Nashif 0a73ea04fa kernel: remove deprecate k_call_stacks_analyze
This API was deperecated and is not being used in the tree anymore, so
remove it.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-09-21 10:33:05 -04:00
Flavio Ceolin 8f488ff32e kernel: stack: Fix k_stack_pop api
_pend_current_thread can return any arbitrary value set by
_set_thred_return_value(), it happens that most cases set 0. This
function can not rely on this behavior otherwise it may return an
invalid value and/or not set data's value.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-18 13:57:39 -04:00
Flavio Ceolin c806ac3d36 kernel: Compare pointers with NULL in while statements
Make while statement using pointers explicitly check whether
the value is NULL or not.

The C standard does not say that the null pointer is the same
as the pointer to memory address 0 and because of this is a good
practice always compare with the macro NULL.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-18 13:57:15 -04:00
Flavio Ceolin b3d9202704 kernel: Using boolean constants instead of 0 or 1
MISRA C requires that every controlling expression of and if or while
statement have a boolean type.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-18 13:57:15 -04:00
Flavio Ceolin 4218d5f8f0 kernel: Make If statement have essentially Boolean type
Make if statement using pointers explicitly check whether the value is
NULL or not.

The C standard does not say that the null pointer is the same as the
pointer to memory address 0 and because of this is a good practice
always compare with the macro NULL.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-18 13:57:15 -04:00
Sebastian Bøe 878a0f050e ld: Put 'sizeof(struct device)' in the generated offsets header
Rename _DEVICE_STRUCT_SIZE to _DEVICE_STRUCT_SIZEOF. This causes it to
be picked by the script 'gen_offset_header.py' and inserted into the
header file 'include/generated/offsets.h'.

Renaming from x_SIZE to x_SIZEOF will align it's name with the other
symbols that denote a sctruct's size, like K_THREAD_SIZEOF.

Furthermore, it will allow the symbol to be accessed through a header
file define, instead of only as an extern symbol. This is more
flexible, and more aligned with the other symbols in offsets.

Finally, if we are able to move all of offsets.c symbols into the
offsets.h header file we be able to remove offsets.o from the link and
thereby simplify the linking process.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-09-18 16:23:40 +02:00
Flavio Ceolin a7fffa9e00 headers: Fix headers guards
Any word started with underscore followed by and uppercase letter or a
second underscore is a reserved word according with C99.

With have *many* violations on Zephyr's code, this commit is tackling
only the violations caused by headers guards. It also takes the
opportunity to normalize them using the filename in uppercase and
replacing dot with underscore. e.g file.h -> FILE_H

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-17 15:49:26 -04:00
Flavio Ceolin 0a4478434e kernel; Checking functions return
Checking the return of some scattered functions across kernel.
MISRA-C requires that all non-void functions have their return value
checked, though, in some cases there is nothing to do. Just
acknowledging it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 65b5280e8f kernel: Check k_thread_create return value
k_thread_create is used only in k_word_q_start that has no error
handling, so the return of that function is not used.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 8f72f245bd kernel: Explicitly check _abort_thread_timemout
A lot of times this API is called during some cleanup even if the
timeout was not set to make the code simpler. In these cases it's not
necessary checking the return. Adding a cast to acknowledge it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 98c64b6d92 kernel: Change _reschedule signature
_reschedule return's value is not used anywhere, except erroneously by
pthread_barrier_wait.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 4d5397bb0a kernel: Ignore _abort_timeout return
Ignoring the return of _abort_timeout when there is nothing to
do. Either because the condition to return something different from 0
was prior checked or because it was called during come cleanup.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 1663ca8590 kernel: Ignore _pend_current_thread return in some cases
There are some cases that there is nothing to do with
_pend_current_thread() return (that is _Swap return value).

As MISRA-C requires that all non-void functions have their
return value checked, we are explicitly ignoring it when there is
nothing to do.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin da49f2e440 coccicnelle: Ignore return of memset
The return of memset is never checked. This patch explicitly ignore
the return to avoid MISRA-C violations.

The only directory excluded directory was ext/* since it contains
only imported code.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 5884c7f54b kernel: Explicitly ignoring _Swap return
Ignoring _Swap return where there is no treatment or nothing to do.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 8a9ba10c2c kernel: swap: Fix __swap signature
__swap function was returning -EAGAIN in some case, though its return
value was declared as unsigned int.

This commit changes this function to return int since it can return a
negative value and its return was already been propagate as int.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-14 16:55:37 -04:00
Flavio Ceolin 585d90f8fc kernel: Fix k_stack_alloc_init behavior
The implementation of this syscall can return either 0 or -ENOMEM, but
when USERSPACE is enabled and it is called through syscall it always
return 0.

Just change this syscall implementation to return the value of
_impl_k_stack_alloc_init

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-13 13:20:13 -04:00
Flavio Ceolin 3259ac08ca kernel: userspace: Sanitize switch usage
MISRA-C requires that every switch clause has a break instruction.
Changing gen_kobject_list script to generates compliance code.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-12 10:05:06 -04:00
Flavio Ceolin a3cea50ce7 kernel: Add missing break/default in switch statement
Explicitly add default clause and break instruction in every clauses in
switch statement.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-09-12 10:05:06 -04:00
Anas Nashif 6b6ecc0803 Revert "kernel: Enable interrupts for MULTITHREADING=n on supported arch's"
This reverts commit 17e9d623b4.

Single thread keep introducing more issues, decided to remove the
feature completely and push any required changes for after 1.13.

See #9808

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-09-06 13:09:26 -04:00
Anas Nashif a9f32d66cf tracing: remove stray event_logger code
Remove obsolete kernel event logger code.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-09-05 16:05:08 -04:00
Andy Ross 8daafd4fba kernel: Final spin in !MULTITHREADING should be locked
Now that we call main() with interrupts enabled in !MULTITHREADING, we
need to disable them again for the final fallback "loop-forever
because user code returned" state.  Otherwise some architectures will
toss interrupts into a context where we obviously aren't prepared.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-08-30 13:29:09 -04:00
Paul Sokolovsky 45c0b20470 kernel: k_poll: Introduce separate status for cancelled events
Previously (as introduced in 48fadfe62), if k_poll() waited on a
queue (or subclass like fifo), and wait was cancelled on queue's
side using k_queue_cancel_wait(), k_poll returned -EINTR. But it
did not set event->state field (to anything else but
K_POLL_STATE_NOT_READY), so in case of waiting on multiple queues,
it was not possible to differentiate which of them was cancelled.

This in particular broke detection of network socket EOF conditions
in POSIX poll() implementation.

This situation is now resolved with introduction of explicit
K_POLL_STATE_CANCELLED state, which is now set for cancelled queue
(-EINTR return remains the same).

This change also elaborates docstring for the functions mentioned, to
document this behavior.

Fixes: #9032

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2018-08-30 09:28:29 -04:00
Daniel Leung 1c6d202ee8 kernel: pipes: fix k_pipe_block_put() when not enough space
If k_pipe_block_put() is called and the pipe does not have enough
space to accomodate all the data in the memory pool, the subsequent
get operation will cause a CPU fault. The CPU fault is caused by
the timeout struct in the dummy thread not being initialized and
thus the scheduler will read bad memory. After fixing this,
another issue came up where the get operation would stall with
k_pipe_block_put() in same situation. This is due to the async
descriptor not being setup correctly. So fix this too.

This was discovered when debugging #9273.

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2018-08-29 15:57:28 -04:00
Andy Ross 9ecc4ead68 sched: Properly account for timeslicing in tickless mode
When adding a new runnable thread in tickless mode, we need to detect
whether it will timeslice with the running thread and reset the timer,
otherwise it won't get any CPU time until the next interrupt fires at
some indeterminate time in the future.

This fixes the specific bug discussed in #7193, but the broader
problem of tickless and timeslicing interacting badly remains.  The
code as it exists needs some rework to avoid all the #ifdef mess.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-08-29 10:01:41 -04:00
David B. Kinder 1c29bff055 doc: fix kconfig misspellings
Fix misspellings in kconfig files missed during regular reviews

Signed-off-by: David B. Kinder <david.b.kinder@intel.com>
2018-08-28 13:58:46 -04:00
Anas Nashif 0e07f8e97a Revert "sched: Properly account for timeslicing in tickless mode"
This reverts commit bc6fb65c81.

Causes MPU faults on multiple platforms.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-08-27 18:39:51 -04:00
Andy Ross 17e9d623b4 kernel: Enable interrupts for MULTITHREADING=n on supported arch's
Some applications have a use case for a tiny MULTITHREADING=n build
(which lacks most of the kernel) but still want special-purpose
drivers in that mode that might need to handle interupts.  This
creates a chicken and egg problem, as arch code (for obvious reasons)
runs _Cstart() with interrupts disabled, and enables them only on
switching into a newly created thread context.  Zephyr does not have a
"turn interrupts on now, please" API at the architecture level.

So this creates one as an arch-specific wrapper around
_arch_irq_unlock().  It's implemented as an optional macro the arch
can define to enable this behavior, falling back to the previous
scheme (and printing a helpful message) if it doesn't find it defined.
Only ARM and x86 are enabled in this patch.

Fixes #8393

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-08-27 16:15:10 -04:00
Andy Ross bc6fb65c81 sched: Properly account for timeslicing in tickless mode
When adding a new runnable thread in tickless mode, we need to detect
whether it will timeslice with the runnable thread and reset the
timer, otherwise it won't get any CPU time until the next interrupt
fires at some indeterminate time in the future.

This fixes the specific bug discussed in #7193, but the broader
problem of tickless and timeslicing interacting badly remains.  The
code as it exists needs some rework to avoid all the #ifdef mess.

Note that the patch also moves _ready_thread() from a ksched.h inline
to sched.c.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-08-27 13:19:29 -04:00
Andy Ross d8d5ec3f91 kernel: Fix double-list-removal corruption case in timeout handling
This fixes #8669, and is distressingly subtle for a one-line patch:

The list iteration code in _handle_expired_timeouts() would remove the
timeout from our (temporary -- the dlist header is on the stack of our
calling function) list of expired timeouts before invoking the
handler.  But sys_dlist_remove() only fixes up the containing list
pointers, leaving garbage in the node.  If the action of that handler
is to re-add the timeout (which is very common!) then that will then
try to remove it AGAIN from the same list.

Even then, the common case is that the expired list contains only one
item, so the result is a perfectly valid empty list that affects
nothing.  But if you have more than one, you get a corrupt cycle in
the iteration list and things get weird.

As it happens, there's no value in trying to remove this timeout from
the temporary list at all.  Just iterate over it naturally.

Really, this design is fragile: we shouldn't be reusing the list nodes
in struct _timeout for this purpose and should figure out some other
mechanism.  But this fix should be good for now.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-08-26 19:39:52 -07:00
Andy Ross 8b651492c8 kernel: Remove unused variable
This flag is vestigial.  It gets set but never read.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-08-26 19:39:52 -07:00
Ramakrishna Pallala 2ad647857c subsys: power: Add OS managed Power Management framework
Add support for OS managed Power Management framework for Zephyr
under 'subsys/power'. This framework takes care of implementing
the _sys_soc_suspend/_sys_soc_resume API's, a PM policy based on
SoC Low Power residencies and also provides necessary API's to
do devices suspend and resume.

Also add necessary changes to support the existing Application
managed Power Management framework.

Signed-off-by: Ramakrishna Pallala <ramakrishna.pallala@intel.com>
2018-08-22 08:07:14 -07:00
Anas Nashif 483910ab4b systemview: add support natively using tracing hooks
Add needed hooks as a subsystem that can be enabled in any application.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-08-21 05:45:47 -07:00
Anas Nashif a2248782a2 kernel: event_logger: remove kernel_event_logger
Move to more generic tracing hooks that can be implemented in different
ways and do not interfere with the kernel.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-08-21 05:45:47 -07:00
Anas Nashif b6304e66f6 tracing: support generic tracing hooks
Define generic interface and hooks for tracing to replace
kernel_event_logger and existing tracing facilities with something more
common.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-08-21 05:45:47 -07:00
Adithya Baglody bb918d85f8 tests: benchmarks: timing_info: Enable benchmarks for xtensa.
This patch provides support needed to get timing related
information from xtensa based SOC.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-08-20 06:51:25 -07:00
Daniel Leung fc182430c0 kernel: userspace: reserve stack space to store local data
This enables reserving little space on the top of stack to store
data local to thread when CONFIG_USERSPACE. The first customer
of this is errno.

Note that ARC, due to how it lays out the user stack and
privilege stack, sets the pointer itself rather than
relying on the common way.

Fixes: #9067

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2018-08-17 09:40:52 -07:00
Flavio Ceolin 6699423a2f kernel: Explicitly ignoring memcpy return
memcpy always return a pointer to dest, it can be ignored. Just making
it explicitly so compilers will never raise warnings/errors to this.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-08-16 19:47:41 -07:00
Flavio Ceolin cc74ad0805 kernel: Explicitly ignoring results of queue_insert
queue_insert will always return 0 when no memory is allocated, just
explicitly marking that we are ignoring return value in these cases.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-08-16 19:47:41 -07:00
Flavio Ceolin 8aec087268 kernel: Fix bitwise operators with unsigned operators
Bitwise operators should be used only with unsigned integer operands
because the result os bitwise operations on signed integers are
implementation-defined.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-08-16 19:47:41 -07:00
Flavio Ceolin 0866d18d03 irq: Fix irq_lock api usage
irq_lock returns an unsigned int, though, several places was using
signed int. This commit fix this behaviour.

In order to avoid this error happens again, a coccinelle script was
added and can be used to check violations.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-08-16 19:47:41 -07:00
Flavio Ceolin ec462f872c kernel: Remove unused definition
_thread definition is not used, just removing it.

Signed-off-by: Flavio Ceolin <flavio.ceolin@intel.com>
2018-08-16 19:47:41 -07:00
Sebastian Bøe 1186f5bb29 cmake: Deprecate the 2 symbols _SYSCALL_{LIMIT,BAD}
There exist two symbols that became equivalent when PR #9383 was
merged; _SYSCALL_LIMIT and K_SYSCALL_LIMIT. This patch deprecates the
redundant _SYSCALL_LIMIT symbol.

_SYSCALL_LIMIT was initally introduced because before PR #9383 was
merged K_SYSCALL_LIMIT was an enum, which couldn't be included into
assembly files. PR #9383 converted it into a define, which can be
included into assembly files, making _SYSCALL_LIMIT redundant.

Likewise for _SYSCALL_BAD.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
2018-08-15 11:46:51 -07:00
Ulf Magnusson 8cf8db3a73 Kconfig: Use a short, consistent style for prompts
Consistently use

    config FOO
            bool/int/hex/string "Prompt text"

instead of

    config FOO
            bool/int/hex/string
            prompt "Prompt text"

(...and a bunch of other variations that e.g. swapped the order of the
type and the 'prompt', or put other properties between them).

The shorthand is fully equivalent to using 'prompt'. It saves lines and
avoids tricking people into thinking there is some semantic difference.

Most of the grunt work was done by a modified version of
https://unix.stackexchange.com/questions/26284/
how-can-i-use-sed-to-replace-a-multi-line-string/26290#26290, but some
of the rarer variations had to be converted manually.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2018-08-15 04:10:10 -07:00
Piotr Zięcik 2a26576b03 kernel: sched: Use ticks as time unit in time slicing.
The time slicing settings was kept in milliseconds while all related
operations was based on ticks. Continuous back and forth conversion
between ticks and milliseconds introduced an accumulating error due
to rounding in _ms_to_ticks() and __ticks_to_ms(). As result
configured time slice duration was not achieved.

This commit removes excessive ticks <-> ms conversion by using ticks
as time unit for all operations related to time slicing.

Also, it fixes #8896 as well as #8897.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2018-08-14 07:18:44 -07:00
Piotr Zięcik e670135fdc kernel: sched: Fix comparsion in _update_time_slice_before_swap()
The _update_time_slice_before_swap() function directly compared
_time_slice_duration (expressed in ms) with value returned by
_get_remaining_program_time() which used ticks as a time unit.

Moreover, the _time_slice_duration was also used as an argument
for _set_time(), which expects time expressed in ticks.

This commit ensures that the same unit (ticks) is used in
comparsion and timer adjustments.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2018-08-14 07:18:44 -07:00
Andrew Boie 09c22cc45d userspace: add net_context as a kernel object
Socket APIs pass pointers to these disguised as file descriptors.
This lets us effectively validate them.

Kernel objects now can have Kconfig dependencies specified, in case
certain structs are not available in all configurations.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-08-13 07:19:39 -07:00
Andrew Boie 83fda7c68f userspace: add _k_object_recycle()
This is used to reset the permissions on an object while
also initializing it.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-08-13 07:19:39 -07:00
Piotr Zięcik 4a39b9ea64 kernel: sched: Use ticks as time unit in time slicing.
The time slicing settings was kept in milliseconds while all related
operations was based on ticks. Continuous back and forth conversion
between ticks and milliseconds introduced an accumulating error due
to rounding in _ms_to_ticks() and __ticks_to_ms(). As result
configured time slice duration was not achieved.

This commit removes excessive ticks <-> ms conversion by using ticks
as time unit for all operations related to time slicing.

Also, it fixes #8896 as well as #8897.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2018-08-13 07:13:22 -07:00
Piotr Zięcik ee9a0615a4 kernel: sched: Fix comparsion in _update_time_slice_before_swap()
The _update_time_slice_before_swap() function directly compared
_time_slice_duration (expressed in ms) with value returned by
_get_remaining_program_time() which used ticks as a time unit.

Moreover, the _time_slice_duration was also used as an argument
for _set_time(), which expects time expressed in ticks.

This commit ensures that the same unit (ticks) is used in
comparsion and timer adjustments.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2018-08-13 07:13:22 -07:00
Ulf Magnusson ec3eff57e0 Kconfig: Use the first default with a satisfied condition
Up until now, Zephyr has patched Kconfig to use the last 'default' with
a satisfied condition, instead of the first one. I'm not sure why the
patch was added (it predates Kconfiglib), but I suspect it's related to
Kconfig.defconfig files.

There are at least three problems with the patch:

  1. It's inconsistent with how Kconfig works in other projects, which
     might confuse newcomers.

  2. Due to oversights, earlier 'range' properties are still preferred,
     as well as earlier 'default' properties on choices.

     In addition to being inconsistent, this makes it impossible to
     override 'range' properties and choice 'default' properties if the
     base definition of the symbol/choice already has 'range'/'default'
     properties.

     I've seen errors caused by the inconsistency, and I suspect there
     are more.

  3. A fork of Kconfiglib that adds the patch needs to be maintained.

Get rid of the patch and go back to standard Kconfig behavior, as
follows:

  1. Include the Kconfig.defconfig files first instead of last in
     Kconfig.zephyr.

  2. Include boards/Kconfig and arch/<arch>/Kconfig first instead of
     last in arch/Kconfig.

  3. Include arch/<arch>/soc/*/Kconfig first instead of last in
     arch/<arch>/Kconfig.

  4. Swap a few other 'source's to preserve behavior for some scattered
     symbols with multiple definitions.

     Swap 'source's in some no-op cases too, where it might match the
     intent.

  5. Reverse the defaults on symbol definitions that have more than one
     default.

     Skip defaults that are mutually exclusive, e.g. where each default
     has an 'if <some board>' condition. They are already safe.

  6. Remove the prefer-later-defaults patch from Kconfiglib.

Testing was done with a Python script that lists all Kconfig
symbols/choices with multiple defaults, along with a whitelist of fixed
symbols. The script also verifies that there are no "unreachable"
defaults hidden by defaults without conditions

As an additional test, zephyr/.config was generated before and after the
change for several samples and checked to be identical (after sorting).

This commit includes some default-related cleanups as well:

  - Simplify some symbol definitions, e.g. where a default has 'if FOO'
    when the symbol already has 'depends on FOO'.

  - Remove some redundant 'default ""' for string symbols. This is the
    implicit default.

Piggyback fixes for swapped ranges on BT_L2CAP_RX_MTU and
BT_L2CAP_TX_MTU (caused by confusing inconsistency).

Piggyback some fixes for style nits too, e.g. unindented help texts.

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2018-08-10 12:38:28 -07:00
Daniel Leung e58b65427e kernel: threads: assign index no. to dynamically created threads
Kernel threads created at build time have unique indexes to map them
into various bitarrays. This patch extends these indexes to
dynamically created threads where the associated  kernel objects are
allocated at runtime.

Fixes: #9081

Signed-off-by: Daniel Leung <daniel.leung@intel.com>
2018-08-09 09:20:14 -07:00
David B. Kinder 7c89b63b7c doc: fix kconfig misspellings
Fix misspellings in Kconfig files missed during normal reviews

Signed-off-by: David B. Kinder <david.b.kinder@intel.com>
2018-08-08 01:48:24 -05:00
Praful Swarnakar 632597ebd1 coverage: kernel: poll: Cleanup redundant code to improve coverage
Remove few redundant code in kernel polling interface.

Signed-off-by: Praful Swarnakar <praful.swarnakar@intel.com>
2018-07-31 20:39:19 -04:00
Andrew Boie c8188f6722 userspace: add functions for copying to/from user
We now have functions for handling all the details of copying
data to/from user mode, including C strings and copying data
into resource pool allocations.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-07-31 07:47:15 -07:00
Andrew Boie 1f2eedff18 kernel: add z_arch_user_string_nlen prototype
This is used to measure the length of potentially unsafe
strings.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-07-31 07:47:15 -07:00
Shawn Mosley 573f32b6d2 userspace: compartmentalized app memory organization
Summary: revised attempt at addressing issue 6290.  The
following provides an alternative to using
CONFIG_APPLICATION_MEMORY by compartmentalizing data into
Memory Domains.  Dependent on MPU limitations, supports
compartmentalized Memory Domains for 1...N logical
applications.  This is considered an initial attempt at
designing flexible compartmentalized Memory Domains for
multiple logical applications and, with the provided python
script and edited CMakeLists.txt, provides support for power
of 2 aligned MPU architectures.

Overview: The current patch uses qualifiers to group data into
subsections.  The qualifier usage allows for dynamic subsection
creation and affords the developer a large amount of flexibility
in the grouping, naming, and size of the resulting partitions and
domains that are built on these subsections. By additional macro
calls, functions are created that help calculate the size,
address, and permissions for the subsections and enable the
developer to control application data in specified partitions and
memory domains.

Background: Initial attempts focused on creating a single
section in the linker script that then contained internally
grouped variables/data to allow MPU/MMU alignment and protection.
This did not provide additional functionality beyond
CONFIG_APPLICATION_MEMORY as we were unable to reliably group
data or determine their grouping via exported linker symbols.
Thus, the resulting decision was made to dynamically create
subsections using the current qualifier method. An attempt to
group the data by object file was tested, but found that this
broke applications such as ztest where two object files are
created: ztest and main.  This also creates an issue of grouping
the two object files together in the same memory domain while
also allowing for compartmenting other data among threads.

Because it is not possible to know a) the name of the partition
and thus the symbol in the linker, b) the size of all the data
in the subsection, nor c) the overall number of partitions
created by the developer, it was not feasible to align the
subsections at compile time without using dynamically generated
linker script for MPU architectures requiring power of 2
alignment.

In order to provide support for MPU architectures that require a
power of 2 alignment, a python script is run at build prior to
when linker_priv_stacks.cmd is generated.  This script scans the
built object files for all possible partitions and the names given
to them. It then generates a linker file (app_smem.ld) that is
included in the main linker.ld file.  This app_smem.ld allows the
compiler and linker to then create each subsection and align to
the next power of 2.

Usage:
 - Requires: app_memory/app_memdomain.h .
 - _app_dmem(id) marks a variable to be placed into a data
section for memory partition id.
 - _app_bmem(id) marks a variable to be placed into a bss
section for memory partition id.
 - These are seen in the linker.map as "data_smem_id" and
"data_smem_idb".
 - To create a k_mem_partition, call the macro
app_mem_partition(part0) where "part0" is the name then used to
refer to that partition. This macro only creates a function and
necessary data structures for the later "initialization".
 - To create a memory domain for the partition, the macro
app_mem_domain(dom0) is called where "dom0" is the name then
used for the memory domain.
 - To initialize the partition (effectively adding the partition
to a linked list), init_part_part0() is called. This is followed
by init_app_memory(), which walks all partitions in the linked
list and calculates the sizes for each partition.
 - Once the partition is initialized, the domain can be
initialized with init_domain_dom0(part0) which initializes the
domain with partition part0.
 - After the domain has been initialized, the current thread
can be added using add_thread_dom0(k_current_get()).
 - The code used in ztests ans kernel/init has been added under
a conditional #ifdef to isolate the code from other tests.
The userspace test CMakeLists.txt file has commands to insert
the CONFIG_APP_SHARED_MEM definition into the required build
targets.
  Example:
        /* create partition at top of file outside functions */
        app_mem_partition(part0);
        /* create domain */
        app_mem_domain(dom0);
        _app_dmem(dom0) int var1;
        _app_bmem(dom0) static volatile int var2;

        int main()
        {
                init_part_part0();
                init_app_memory();
                init_domain_dom0(part0);
                add_thread_dom0(k_current_get());
                ...
        }

 - If multiple partitions are being created, a variadic
preprocessor macro can be used as provided in
app_macro_support.h:

        FOR_EACH(app_mem_partition, part0, part1, part2);

or, for multiple domains, similarly:

        FOR_EACH(app_mem_domain, dom0, dom1);

Similarly, the init_part_* can also be used in the macro:

        FOR_EACH(init_part, part0, part1, part2);

Testing:
 - This has been successfully tested on qemu_x86 and the
ARM frdm_k64f board.  It compiles and builds power of 2
aligned subsections for the linker script on the 96b_carbon
boards.  These power of 2 alignments have been checked by
hand and are viewable in the zephyr.map file that is
produced during build. However, due to a shortage of
available MPU regions on the 96b_carbon board, we are unable
to test this.
 - When run on the 96b_carbon board, the test suite will
enter execution, but each individaul test will fail due to
an MPU FAULT.  This is expected as the required number of
MPU regions exceeds the number allowed due to the static
allocation. As the MPU driver does not detect this issue,
the fault occurs because the data being accessed has been
placed outside the active MPU region.
 - This now compiles successfully for the ARC boards
em_starterkit_em7d and em_starterkit_em7d_v22. However,
as we lack ARC hardware to run this build on, we are unable
to test this build.

Current known issues:
1) While the script and edited CMakeLists.txt creates the
ability to align to the next power of 2, this does not
address the shortage of available MPU regions on certain
devices (e.g. 96b_carbon).  In testing the APB and PPB
regions were commented out.
2) checkpatch.pl lists several issues regarding the
following:
a) Complex macros. The FOR_EACH macros as defined in
app_macro_support.h are listed as complex macros needing
parentheses.  Adding parentheses breaks their
functionality, and we have otherwise been unable to
resolve the reported error.
b) __aligned() preferred. The _app_dmem_pad() and
_app_bmem_pad() macros give warnings that __aligned()
is preferred. Prior iterations had this implementation,
which resulted in errors due to "complex macros".
c) Trailing semicolon. The macro init_part(name) has
a trailing semicolon as the semicolon is needed for the
inlined macro call that is generated when this macro
expands.

Update: updated to alternative CONFIG_APPLCATION_MEMORY.
Added config option CONFIG_APP_SHARED_MEM to enable a new section
app_smem to contain the shared memory component.  This commit
seperates the Kconfig definition from the definition used for the
conditional code.  The change is in response to changes in the
way the build system treats definitions.  The python script used
to generate a linker script for app_smem was also midified to
simplify the alignment directives.  A default linker script
app_smem.ld was added to remove the conditional includes dependency
on CONFIG_APP_SHARED_MEM.  By addining the default linker script
the prebuild stages link properly prior to the python script running

Signed-off-by: Joshua Domagalski <jedomag@tycho.nsa.gov>
Signed-off-by: Shawn Mosley <smmosle@tycho.nsa.gov>
2018-07-25 12:02:01 -07:00
Andrew Boie 7f4d006959 kernel: fix errno access for user mode
The errno "variable" is required to be thread-specific.
It gets defined to a macro which dereferences a pointer
returned by a kernel function.

In user mode, we cannot simply read/write the thread struct.
We do not have thread-local storage mechanism, so for now
use the lowest address of the thread stack to store this
value, since this is guaranteed to be read/writable by
a user thread.

The downside of this approach is potential stack corruption
if the stack pointer goes down this far but does not exceed
the location, since a fault won't be generated in this case.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-07-19 16:44:59 -07:00
Ramakrishna Pallala d9c37d6cfc kernel: idle: Define _sys_soc_resume functions conditionally
Define _sys_soc_resume() only if CONFIG_SYS_POWER_LOW_POWER_STATE
is enabled.

Define _sys_soc_resume_from_deep_sleep() only if
CONFIG_SYS_POWER_DEEP_SLEEP is enabled.

Signed-off-by: Ramakrishna Pallala <ramakrishna.pallala@intel.com>
2018-07-19 17:12:58 -04:00
Ramakrishna Pallala e74d85d816 kernel: thread: Simplify k_thread_foreach conditional inclusion
Simplify k_thread_foreach API conditional inclusion by putting
the whole logic under CONFIG_THREAD_MONITOR config option.

Signed-off-by: Ramakrishna Pallala <ramakrishna.pallala@intel.com>
2018-07-18 15:42:28 -04:00
Spoorthi K 47a9f9a617 kernel: thread: Exclude deprecated function from lcov
Do not consider deprecated function for code coverage

Signed-off-by: Spoorthi K <spoorthi.k@intel.com>
2018-07-18 13:26:18 -04:00
Anas Nashif eda3e16ac7 coverage: exclude k_call_stacks_analyze from coverage
Do not count deprecated functions.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-07-18 10:39:48 -04:00
Ioannis Glaropoulos 1d9bb5d793 kernel: minor improve in SYS_CLOCK_HW_CYCLES_PER_SEC help description
Minor improvement in the help text description of Kconfig option
SYS_CLOCK_HW_CYCLES_PER_SEC, clarifying that the option can be
defined in either SOC or Board Kconfig file.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
2018-07-16 11:01:47 -04:00
Krzysztof Chruscinski 6b01c89935 logging: Add log initialization to system startup
Log API can be used before user can explicitly initialize the logger.
In order to ensure that logger core is ready to buffer log messages
it must be initialize as early as possible. Initialization does not
include initialization of default backend since driver may not be
ready and backend is needed only when log messages are processed.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2018-07-14 08:32:44 -04:00
Piotr Zięcik fe2ac39bf2 kernel: Cleanup _ms_to_ticks().
This commit moves all implementations of the _ms_to_ticks() into
single file. Also, the function is now inline even if
_NEED_PRECISE_TICK_MS_CONVERSION is defined.

Signed-off-by: Piotr Zięcik <piotr.ziecik@nordicsemi.no>
2018-07-03 22:46:39 -04:00
Andy Ross 9f06a35450 kernel: Add the old "multi queue" scheduler algorithm as an option
Zephyr 1.12 removed the old scheduler and replaced it with the choice
of a "dumb" list or a balanced tree.  But the old multi-queue
algorithm is still useful in the space between these two (applications
with large-ish numbers of runnable threads, but that don't need fancy
features like EDF or SMP affinity).  So add it as a
CONFIG_SCHED_MULTIQ option.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-07-03 17:09:15 -04:00
Andy Ross 225c74bbdf kernel/Kconfig: Reorgnize wait_q and sched algorithm choices
Make these "choice" items instead of a single boolean that implies the
element unset.

Also renames WAITQ_FAST to WAITQ_SCALABLE, as the rbtree is really
only "fast" for large queue sizes (it's constant factor overhead is
bigger than a list's!)

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-07-03 17:09:15 -04:00
Anas Nashif 80e6a978a6 kernel/drivers: fix compile warnings
Uncovered by clang we have some functions being only used conditionally,
so gaurd them to make them only available when those conditions are met.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
2018-07-01 22:58:23 +02:00
Ulf Magnusson 7727d1a48e kernel: Kconfig: Remove redundant 'default n' properties
Bool symbols implicitly default to 'n'.

A 'default n' can make sense e.g. in a Kconfig.defconfig file, if you
want to override a 'default y' on the base definition of the symbol. It
isn't used like that on any of these symbols though.

Also simplify the definitions of COOP_ENABLED, PREEMPT_ENABLED, and
SYS_CLOCK_EXISTS. 'default' (and def_bool) can take any expression, not
just a fixed value.

(It would work without the parentheses around the comparisons too.)

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2018-06-22 15:21:14 -04:00
Andy Ross 3d14615f56 kernel: Restore CONFIG_MULTITHREADING=n behavior
The prepare_multithreading()/switch_to_main_thread() steps were being
done unconditionally, when with multhreading disabled we want to jump
straight into the main thread on the existing stack.

Needless to say, that doesn't work well.  Fixes #8361.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-06-13 17:23:05 -04:00
Andy Ross 55a7e46b66 kernel/poll: Remove POLLING thread state bit
The _THREAD_POLLING bit in thread_state was never actually a
legitimate thread "state".  It is a clever synchronization trick
introduced to allow the thread to release the irq_lock while looping
over the input event array without dropping events.

Instead, make that flag a word in the "poller" struct that lives on
the stack of the thread calling k_poll.  The disadvantage is the 4
bytes of thread space needed.  Advantages:

+ Cleaner API, it's now internal to poll instead of being globally
  visible.

+ The thread_state bit space is just one byte, and was almost full
  already.

+ Smaller code to write/test a full word and not a bitfield

+ Words are atomic, so no need for one of irq lock/unlock pairs.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-06-11 17:25:38 -04:00
Andy Ross b173e4353f kernel/queue: Fix spurious NULL exit condition when using timeouts
The queue loop when CONFIG_POLL is in used has an inherent race
between the return of k_poll() and the inspection of the list where no
lock can be held.  Other contending readers of the same queue can
sneak in and steal the item out of the list before the current thread
gets to the sys_sflist_get() call, and the current loop will (if it
has a timeout) spuriously return NULL before the timeout expires.

It's not even a hard race to exercise.  Consider three threads at
different priorities: High (which can be an ISR too), Mid, and Low:

1. Mid and Low both enter k_queue_get() and sleep inside k_poll() on
   an empty queue.

2. High comes along and calls k_queue_insert().  The queue code then
   wakes up Mid, and reschedules, but because High is still running Mid
   doesn't get to run yet.

3. High inserts a SECOND item.  The queue then unpends the next thread
   in the list (Low), and readies it to run.  But as before, it won't
   be scheduled yet.

4. Now High sleeps (or if it's an interrupt, exits), and Mid gets to
   run.  It dequeues and returns the item it was delivered normally.

5. But Mid is still running!  So it re-enters the loop it's sitting in
   and calls k_queue_get() again, which sees and returns the second
   item in the queue synchronously.  Then it calls it a third time and
   goes to sleep because the queue is empty.

6. Finally, Low wakes up to find an empty queue, and returns NULL
   despite the fact that the timeout hadn't expired.

The fix is simple enough: check the timeout expiration inside the loop
so we don't return early.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-06-11 17:11:51 -04:00
Paul Sokolovsky fd55935560 kernel: work_q: Document implications of default sys work_q priority
Default value of CONFIG_SYSTEM_WORKQUEUE_PRIORITY is -1, which means
it's run by the cooperative thread. Explicitly mention (in the Kconfig
help) that it means that any work handler submited to this default
queue won't be preempted by some other thread (which is generally
good, but worth documenting explicitly).

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
2018-06-11 14:40:07 -04:00
Andrew Boie 2dd91eca0e kernel: move thread monitor init to common code
The original implementation of CONFIG_THREAD_MONITOR would
try to leverage a thread's initial stack layout to provide
the entry function with arguments for any given thread.

This is problematic:

- Some arches do not have a initial stack layout suitable for
this
- Some arches never enabled this at all (riscv32, nios2)
- Some arches did not enable this properly
- Dropping to user mode would erase or provide incorrect
information.

Just spend a few extra bytes to store this stuff directly
in the k_thread struct and get rid of all the arch-specific
code for this.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-06-06 14:26:45 -04:00
Michael Scott 6c95dafd82 kernel: sched: use _is_thread_ready() in should_preempt()
We are using _is_thread_prevented_from_running() to see if the
_current thread can be preempted in should_preempt().  The idea
being that even if the _current thread is a high priority coop
thread, we can still preempt it when it's pending, suspended,
etc.

This does not take into account if the thread is sleeping.

k_sleep() merely removes the thread from the ready_q and calls
Swap().  The scheduler will swap away from the thread temporarily
and then on the next cycle get stuck to the sleeping thread for
however long the sleep timeout is, doing exactly nothing because
other functions like _ready_thread() use _is_thread_ready() as a
check before proceeding.

We should use !_is_thread_ready() to take into account when threads
are waiting on a timer, and let other threads run in the meantime.

Signed-off-by: Michael Scott <michael@opensourcefoundries.com>
2018-06-04 08:21:47 -04:00
Michael Scott f669a08eea kernel: thread: fix _THREAD_DUMMY check in _check_stack_sentinel()
All other checks of thread_state use a bit wise & operator incase
there are other flags attached to the thread_state.  Let's fix
the only outlier in _check_stack_sentinel() to be the same.

Signed-off-by: Michael Scott <michael@opensourcefoundries.com>
2018-06-01 09:03:48 -04:00
Andy Ross 43553da9b2 kernel/sched: Fix preemption logic
The should_preempt() code was catching some of the "unrunnable" cases
but not all of them, opening the possibility of failing to preempt a
just-pended thread and thus waking it up synchronously.  There are
reports of this causing spin loops over k_poll() in the network stack
work queues (see #8049).

Note that the previous _is_dummy() call is folded into (the somewhat
verbosely named) _is_thread_prevented_from_running(), and that the
order of tests has been changed/optimized to hopefully catch common
cases earlier.

Suggested-by: Michael Scott <michael@opensourcefoundries.com>
Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-31 16:46:14 -04:00
Andy Ross eace1df539 kernel/sched: Fix SMP scheduling
Recent changes post-scheduler-rewrite broke scheduling on SMP:

The "preempt_ok" feature added to isolate preemption points wasn't
honored in SMP mode.  Fix this by adding a "swap_ok" field to the CPU
record (not the thread) which is set at the same time out of
update_cache().

The "queued" flag wasn't being maintained correctly when swapping away
from _current (it was added back to the queue, but the flag wasn't
set).

Abstract out a "should_preempt()" predicate so SMP and uniprocessor
paths share the same logic, which is distressingly subtle.

There were two places where _Swap() was predicated on
_get_next_ready_thread() != _current.  That's no longer a benign
optimization in SMP, where the former function REMOVES the next thread
from the queue.  Just call _Swap() directly in SMP, which has a
unified C implementation that does this test already.  Don't change
other architectures in case it exposes bugs with _Swap() switching
back to the same thread (it should work, I just don't want to break
anything).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-31 14:02:03 -04:00
Andy Ross 75398d2c38 kernel/mempool: Handle transient failure condition
The sys_mem_pool implementation has a subtle error case where it
detected a simultaneous allocation after having released the lock, in
which case exactly one of the racing allocators will return with
-EAGAIN (the other one suceeds of course).

I documented this condition at the lower level, but forgot to actually
handle it at the k_mem_pool level where we want to retry once before
going to sleep, as it doesn't generally represent an empty heap.  It
got caught by code auditing in:

https://github.com/zephyrproject-rtos/zephyr/issues/6757

(Full disclosure: I tested this by whiteboxing the first failure.  I
wasn't able to put together a rig to reliably exercise the actual
race.)

This patch also fixes a noop thinko in the return logic in the same
function, which contained:

   (ret == -EAGAIN) || (ret && ret != -ENOMEM)

The first term is needless and implied by the second.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-27 09:55:04 -04:00
Andy Ross 3a0cb2d35d kernel: Remove legacy preemption checking
The metairq feature exposed the fact that all of our arch code (and a
few mistaken spots in the scheduler too) was trying to interpret
"preemptible" threads independently.

As of the scheduler rewrite, that logic is entirely within sched.c and
doing it externally is redundant.  And now that "cooperative" threads
can be preempted, it's wrong and produces test failures when used with
metairq threads.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-25 09:40:55 -07:00
Carles Cufi b54644913d kernel: Use IS-specific entropy function when available
During the early boot process, in prepare_multithreading(), the kernel
structures and scheduler are not ready yet. In order to obtain entropy
for early works such as stack randomization, optionally use when present
the ISR-specific function that some drivers will provide.

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
2018-05-24 15:13:13 -07:00
Leandro Pereira fb0fba91a5 arch: x86: Rename CPU_NO_SPECTRE to CPU_NO_SPECTRE_V2
There's a new known variant, so make it clear what this one is for.

Signed-off-by: Leandro Pereira <leandro.pereira@intel.com>
2018-05-24 13:07:12 -04:00
Andrew Boie 538754cb28 kernel: handle early entropy issues
We generalize querying the entropy driver directly with
a new internal API, which is now used by CONFIG_STACK_RANDOM
and stack canary initialization.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-23 19:38:06 -07:00
Kumar Gala 177bbbd35f kernel: Fix trivial typo in CONFIG_WAIT_Q_FAST
The Kconfig option is CONFIG_WAITQ_FAST not CONFIG_WAIT_Q_FAST.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
2018-05-23 17:57:06 -04:00
Leandro Pereira 389c36439a kernel: init: Use entropy API directly to initialize stack canary
Some sys_rand32_get() implementation will use shared state and protect
that using some synchronization primitive such as a mutex or a
semaphore.  It's too early in the boot process to use any of them,
which causes some issues.

Use the entropy API directly to set up the stack canaries.

This doesn't completely solve the problem, as some drivers will use the
same synchronization primitives anyway.  Some drivers (e.g.  the NRF5
entropy driver) provide an API to be used by ISRs that might be
suitable here, but not all drivers do that.

Signed-off-by: Leandro Pereira <leandro.pereira@intel.com>
2018-05-23 14:42:49 -07:00
Andrew Boie 982d5c8f55 init: run kernel_arch_init() earlier
This was in prepare_multithreading(), which was moved
to after driver initialization and not before it.
The function now really just prepares system threads.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-23 17:22:19 -04:00
Andrew Boie 4afc6c9ff2 kernel: remove STACK_ALIGN checks
STACK_ALIGN has somewhat different semantics across our arches,
particularly ARC.

These checks are unnecessary, _new_thread() is required
to properly align stack sizes anyway.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-23 15:05:15 -05:00
Andy Ross 4a2e50f6b0 kernel: Earliest-deadline-first scheduling policy
Very simple implementation of deadline scheduling.  Works by storing a
single word in each thread containing a deadline, setting it (as a
delta from "now") via a single new API call, and using it as extra
input to the existing thread priority comparison function when
priorities are equal.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-23 14:25:52 -04:00
Andy Ross 7aa25fa5eb kernel: Add "meta IRQ" thread priorities
This patch adds a set of priorities at the (numerically) lowest end of
the range which have "meta-irq" behavior.  Runnable threads at these
priorities will always be scheduled before threads at lower
priorities, EVEN IF those threads are otherwise cooperative and/or
have taken a scheduler lock.

Making such a thread runnable in any way thus has the effect of
"interrupting" the current task and running the meta-irq thread
synchronously, like an exception or system call.  The intent is to use
these priorities to implement "interrupt bottom half" or "tasklet"
behavior, allowing driver subsystems to return from interrupt context
but be guaranteed that user code will not be executed (on the current
CPU) until the remaining work is finished.

As this breaks the "promise" of non-preemptibility granted by the
current API for cooperative threads, this tool probably shouldn't be
used from application code.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-23 14:25:52 -04:00
Andy Ross 1856e2206d kernel/sched: Don't preempt cooperative threads
The scheduler rewrite added a regression in uniprocessor mode where
cooperative threads would be unexpectedly preempted, because nothing
was checking the preemption status of _current at the point where the
next-thread cache pointer was being updated.

Note that update_cache() needs a little more context: spots like
k_yield() that leave _current runable need to be able to tell it that
"yes, preemption is OK here even though the thread is cooperative'.
So it has a "preempt_ok" argument now.

Interestingly this didn't get caught because we don't test that.  We
have lots and lots of tests of the converse cases (i.e. making sure
that threads get preempted when we expect them to), but nothing that
explicitly tries to jump in front of a cooperative thread.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-23 14:25:52 -04:00
Andrew Boie 72c7ded561 kernel: prepare threads after PRE_KERNEL*
prepare_multithreading() was done very early as it had a call
to initialize the interrupt subsystem. This was causing problems
with stack pointer randomization as any HW-based entropy drivers
had not been initialized.

Move the call to initialize the interrupt system out of
prepare_multithreading(), which now really does just prepare
the system to start threads. This is now done after the PRE_KERNEL
phases.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-22 15:59:07 -07:00
Ulf Magnusson aa26289458 kconfig: Get rid of leading/trailing whitespace in prompts
Leading/trailing whitespace in prompts requires ugly workarounds in
genrest.py, as e.g. *prompt * is invalid RST. strip() all prompts in
Kconfiglib and get rid of the genrest.py workarounds. Add a warning too.

The Kconfiglib update has some unrelated cleanups and fixes (that won't
affect Zephyr).

Signed-off-by: Ulf Magnusson <Ulf.Magnusson@nordicsemi.no>
2018-05-19 09:26:39 +03:00
Andy Ross 3ce9c84ba8 kernel: Wait queues aren't dlists anymore
These assertions snuck through in crossed pull requests.  There's a
specific API for _wait_q_t now, you can't hit the list directly
(because it might be a tree).

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-19 07:00:55 +03:00
Andy Ross 1acd8c2996 kernel: Scheduler rewrite
This replaces the existing scheduler (but not priority handling)
implementation with a somewhat simpler one.  Behavior as to thread
selection does not change.  New features:

+ Unifies SMP and uniprocessing selection code (with the sole
  exception of the "cache" trick not being possible in SMP).

+ The old static multi-queue implementation is gone and has been
  replaced with a build-time choice of either a "dumb" list
  implementation (faster and significantly smaller for apps with only
  a few threads) or a balanced tree queue which scales well to
  arbitrary numbers of threads and priority levels.  This is
  controlled via the CONFIG_SCHED_DUMB kconfig variable.

+ The balanced tree implementation is usable symmetrically for the
  wait_q abstraction, fixing a scalability glitch Zephyr had when many
  threads were waiting on a single object.  This can be selected via
  CONFIG_WAITQ_FAST.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-19 07:00:55 +03:00
Andy Ross c0ba11b281 kernel: Don't _arch_switch() to yourself
The SMP testing missed the case where _Swap() decides to return back
into the _current.  Obviously there is no valid switch handle for the
running thread into which we can restore, and everything blows up.
(What happened is that the new scheduler code opened up a spot where
k_thread_priority_set() does a _reschedule() unconditionally and
doens't check to see whether or not it's needed like the old code).

But that isn't incorrect!  It's entirely possible that _Swap() may
find that no thread is runnable except _current (due, for example, to
another CPU racing the other thread you expected off to sleep or
something).  Don't blow up, check and return a noop.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-19 07:00:55 +03:00
Krzysztof Chruscinski 9666c30d5f kernel: mem_slab: Reschedule in k_mem_slab_free only when necessary.
Rescheduling was called unconditionally at the end of k_mem_slab_free
call. It is necessary only when thread is pending in the wait queue.

Signed-off-by: Krzysztof Chruscinski <krzysztof.chruscinski@nordicsemi.no>
2018-05-18 20:16:50 +03:00
Andy Ross ccf3bf7ed3 kernel: Fix sloppy wait queue API
There were multiple spots where code was using the _wait_q_t
abstraction as a synonym for a dlist and doing direct list management
on them with the dlist APIs.  Refactor _wait_q_t into a proper opaque
struct (not a typedef for sys_dlist_t) and write a simple wrapper API
for the existing usages.  Now replacement of wait_q with a different
data structure is much cleaner.

Note that there were some SYS_DLIST_FOR_EACH_SAFE loops in mailbox.c
that got replaced by the normal/non-safe macro.  While these loops do
mutate the list in the code body, they always do an early return in
those circumstances instead of returning into the macro'd for() loop,
so the _SAFE usage was needless.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-18 01:48:48 +03:00
Andy Ross 4ca0e07088 kernel: Add _unpend_all convenience wrapper to scheduler API
Refactoring.  Mempool wants to unpend all threads at once.  It's
cleaner to do this in the scheduler instead of the IPC code.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-18 01:48:48 +03:00
Andrew Boie 3772f77119 k_poll: expose to user mode
k_poll is now accessible from user mode. A memory allocation takes place
from the caller's resource pool to copy the provided poll_events
array; this can be large enough to make allocating it on the stack
not preferable.

k_poll_signal are now proper kernel objects. Two APIs have been added,
one to reset the signaled state and one to check the current signaled
state and result value.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-17 23:34:03 +03:00
Andrew Boie 8345e5ebf0 syscalls: remove policy from handler checks
The various macros to do checks in system call handlers all
implictly would generate a kernel oops if a check failed.
This is undesirable for a few reasons:

* System call handlers that acquire resources in the handler
  have no good recourse for cleanup if a check fails.
* In some cases we may want to propagate a return value back
  to the caller instead of just killing the calling thread,
  even though the base API doesn't do these checks.

These macros now all return a value, if nonzero is returned
the check failed. K_OOPS() now wraps these calls to generate
a kernel oops.

At the moment, the policy for all APIs has not changed. They
still all oops upon a failed check/

The macros now use the Z_ notation for private APIs.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-17 23:34:03 +03:00
Andrew Boie 2b9b4b2cf7 k_queue: allow user mode access via allocators
User mode may now use queue objects. Instead of embedding the kernel's
linked list information directly in the data item, a container struct
is allocated from the caller's resource pool which is then added to
the queue. The new sflist type is now used to store a flag indicating
whether a data item needs to be freed when removed from the queue.

FIFO/LIFOs are derived from k_queues and have had allocator functions
added.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-17 23:34:03 +03:00
Andrew Boie 47fa8eb98c userspace: generate list of kernel object sizes
This used to be done by hand but can easily be generated like
we do other switch statements based on object type.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie f3bee951b1 kernel: stacks: add k_stack_alloc() init
Similar to what has been done with pipes and message queues,
user mode can't be trusted to provide a buffer for the kernel
to use. Remove k_stack_init() as a syscall and offer
k_stack_alloc_init() which allocates a buffer from the caller's
resource pool.

Fixes #7285

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie 0fe789ff2e kernel: add k_msgq_alloc_init()
User mode can't be trusted to provide a memory buffer to
k_msgq_init(). Introduce k_msgq_alloc_init() which allocates
the buffer out of the calling thread's resource pool and expose
that as a system call instead.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie 44fe81228d kernel: pipes: add k_pipe_alloc_init()
User mode can't be trusted to provide the kernel buffers for
internal use. The syscall for k_pipe_init() has been removed
in favor of a new API to draw the buffer memory from the
calling thread's resource pool.

K_PIPE_DEFINE() now properly locates the allocated buffer into
kernel memory.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie 97bf001f11 userspace: get dynamic objs from thread rsrc pools
Dynamic kernel objects no longer is hard-coded to use the kernel
heap. Instead, objects will now be drawn from the calling thread's
resource pool.

Since we now have a reference counting mechanism, if an object
loses all its references and it was dynamically allocated, it will
be automatically freed.

A parallel dlist is added for efficient iteration over the set of
all dynamic objects, allowing deletion during iteration.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie 92e5bd7473 kernel: internal APIs for thread resource pools
Some kernel APIs may need to allocate memory in order to function
correctly, especially if they are exposed to userspace where
buffers provided by user code cannot be trusted.

Instead of simply drawing from the system heap, specific pools
may instead be assigned to threads, and any requests made on
behalf of the calling thread will draw heap memory from that pool.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie 337e74334c userspace: automatic resource release framework
An object's set of permissions is now also used as a form
of reference counting. If an object's permission bitmap gets
completely cleared, it is now possible to specify object type
specific cleanup functions to be implicitly called.

Currently no objects are enabled yet. Forthcoming patches
will do this on a per object basis.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie e9cfc54d00 kernel: remove k_object_access_revoke() as syscall
Forthcoming patches will dual-purpose an object's permission
bitfield as also reference tracking for kernel objects, used to
handle automatic freeing of resources.

We do not want to allow user thread A to revoke thread B's access
to some object O if B is in the middle of an API call using O.

However we do want to allow threads to revoke their own access to
an object, so introduce a new API and syscall for that.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Andrew Boie a2480bd472 mempool: add API for malloc semantics
This works like k_malloc() but allows the user to designate
a specific memory pool to use instead of the kernel heap.

Test coverage provided by existing tests for k_malloc(), which is
now derived from this API.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-16 17:32:59 -07:00
Adithya Baglody 5133cf56aa kernel: thread: Move out the function _thread_entry() to lib
The _thread_entry() is not really a part of the kernel but a part of
the zephyr's C runtime support library. Hence moving just the
function to lib/thread_entry.c

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-05-15 17:48:18 +03:00
Adithya Baglody 8618716c68 kernel: Cmake: Add __ZEPHYR_SUPERVISOR__ macro for kernel files.
Normally a syscall would check the current privilege level and then
decide to go to _impl_<syscall> directly or go through a
_handler_<syscall>.
__ZEPHYR_SUPERVISOR__ is a compiler optimization flag which will
make all the system calls from the kernel files directly link
to the _impl_<syscall>. Thereby reducing the overhead of checking the
privileges.

Signed-off-by: Adithya Baglody <adithya.nagaraj.baglody@intel.com>
2018-05-15 17:48:18 +03:00
Ramakrishna Pallala 110b8e42ff kernel: Add k_thread_foreach API
Add k_thread_foreach API to iterate over all the threads in
the system.

This API can be used for debugging threads in multi threaded
environment to dump and analyze various thread parameters like
priority, state, stack address etc...

Signed-off-by: Ramakrishna Pallala <ramakrishna.pallala@intel.com>
2018-05-15 13:43:00 +03:00
Andrew Boie 42a2c96422 newlib: fix heap user mode access for MPU devices
MPU devices that enforce power-of-two alignment now
specify the size of the buffer used for the newlib heap.
This buffer will be properly aligned and a pointer
exposed in a kernel header, such that it can be added
to a user thread's memory domain configuration if
necessary.

MPU devices that don't have these restrictions allocate
the heap as normal.

In all cases, if an MPU/MMU region needs to be programmed,
the z_newlib_get_heap_bounds() API will return the necessary
information.

Given how precious MPU regions are, no automatic programming
of the MPU is done; applications will need to do this as
needed in their memory domain configurations.

On x86, the x86 MMU-specific code has been moved to arch/x86
using the new z_newlib_get_heap_bounds() API.

Fixes: #6814

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-05-10 15:09:02 -07:00
David B. Kinder 3e136b4d23 doc: fix misspellings in doc and Kconfig files
Fix misspellings missed during regular PR reviews.

Signed-off-by: David B. Kinder <david.b.kinder@intel.com>
2018-05-09 15:06:43 -05:00
Andy Ross 15c400774e kernel: Rework SMP irq_lock() compatibility layer
This was wrong in two ways, one subtle and one awful.

The subtle problem was that the IRQ lock isn't actually globally
recursive, it gets reset when you context switch (i.e. a _Swap()
implicitly releases and reacquires it).  So the recursive count I was
keeping needs to be per-thread or else we risk deadlock any time we
swap away from a thread holding the lock.

And because part of my brain apparently knew this, there was an
"optimization" in the code that tested the current count vs. zero
outside the lock, on the argument that if it was non-zero we must
already hold the lock.  Which would be true of a per-thread counter,
but NOT a global one: the other CPU may be holding that lock, and this
test will tell you *you* do.  The upshot is that a recursive
irq_lock() would almost always SUCCEED INCORRECTLY when there was lock
contention.  That this didn't break more things is amazing to me.

The rework is actually simpler than the original, thankfully.  Though
there are some further subtleties:

* The lock state implied by irq_lock() allows the lock to be
  implicitly released on context switch (i.e. you can _Swap() with the
  lock held at a recursion level higher than 1, which needs to allow
  other processes to run).  So return paths into threads from _Swap()
  and interrupt/exception exit need to check and restore the global
  lock state, spinning as needed.

* The idle loop design specifies a k_cpu_idle() function that is on
  common architectures expected to enable interrupts (for obvious
  reasons), but there is no place to put non-arch code to wire it into
  the global lock accounting.  So on SMP, even CPU0 needs to use the
  "dumb" spinning idle loop.

Finally this patch contains a simple bugfix too, found by inspection:
the interrupt return code used when CONFIG_SWITCH is enabled wasn't
correctly setting the active flag on the threads, opening up the
potential for a race that might result in a thread being scheduled on
two CPUs simultaneously.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-02 10:00:17 -07:00
Andy Ross eb258706e0 kernel: Move SMP initialization to start of main thread
The smp_init() call was too early.  Device and subsystem
initialization doesn't happen until after the main thread starts
running.  Starting extra CPUs and allowing them to schedule threads
before their drivers are alive is a bad idea, even if it works in a
unit test.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-05-02 10:00:17 -07:00
Leandro Pereira 39dc7d03f7 scripts: gen_kobject_list: Generate enums and case statements
Adding a new kernel object type or driver subsystem requires changes
in various different places.  This patch makes it easier to create
those devices by generating as much as possible in compile time.

No behavior change.

Signed-off-by: Leandro Pereira <leandro.pereira@intel.com>
2018-04-26 02:57:12 +05:30
Leandro Pereira c200367b68 drivers: Perform a runtime check if a driver is capable of an operation
Driver APIs might not implement all operations, making it possible for
a user thread to get the kernel to execute a function at 0x00000000.

Perform runtime checks in all the driver handlers, checking if they're
capable of performing the requested operation.

Fixes #6907.

Signed-off-by: Leandro Pereira <leandro.pereira@intel.com>
2018-04-26 02:57:12 +05:30
Andy Ross e7ded11a2e kernel: Prune ksched.h of dead code
There was a ton of junk in this header.  Pare it down to just the
stuff actually used by code outside of sched.c, move the needed
internal stuff into sched.c itself, and drop everything else.

Note that (other than the tiny inlines that remain here in the header)
the scheduler interface exposed to the rest of the system is now
composed of just 12 functions.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-25 13:13:23 -07:00
Andrew Boie 31bdfc014e userspace: add support for dynamic kernel objects
A red-black tree is maintained containing the metadata for all
dynamically created kernel objects, which are allocated out of the
system heap.

Currently, k_object_alloc() and k_object_free() are supervisor-only.

Signed-off-by: Andrew Boie <andrew.p.boie@intel.com>
2018-04-24 12:27:54 -07:00
Leandro Pereira f5f95ee3a9 kernel: sem: Ensure that initial count is lesser or equal than limit
Ensure this value during static initialization (with build assertions),
and dynamic initializations through system calls.

If initial count is larger than the limit, it's possible for the count
to wraparound, causing locking issues.

Expanding the BUILD_ASSERT() macros after declaring a k_sem struct in
K_SEM_DEFINE() is necessary to support cases where a semaphore is
defined statically.

Signed-off-by: Leandro Pereira <leandro.pereira@intel.com>
2018-04-24 04:04:36 +05:30
Leandro Pereira 16472cafcf arch: x86: Use retpolines in core assembly routines
In order to mitigate Spectre variant 2 (branch target injection), use
retpolines for indirect jumps and calls.

The newly-added hidden CONFIG_X86_NO_SPECTRE flag, which is disabled
by default, must be set by a x86 SoC if its CPU performs speculative
execution.  Most targets supported by Zephyr do not, so this is
set to "y" by default.

A new setting, CONFIG_RETPOLINE, has been added to the "Security
Options" sections, and that will be enabled by default if
CONFIG_X86_NO_SPECTRE is disabled.

Signed-off-by: Leandro Pereira <leandro.pereira@intel.com>
2018-04-24 04:00:01 +05:30
Andy Ross 8a4b2e8cf2 kernel, posix: Move ready_one_thread() to scheduler
The POSIX layer had a simple ready_one_thread() utility.  Move this to
the scheduler API (with a prepended underscore -- it's an internal
API) so that it can be synchronized along with the rest of the
scheduler.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross 22642cf309 kernel: Clean up _unpend_thread() API
Almost everywhere this was called, it was immediately followed by
_abort_thread_timeout(), for obvious reasons.  The only exceptions
were in timeout and k_timer expiration (unifying these two would be
another good cleanup), which are peripheral parts of the scheduler and
can plausibly use a more "internal" API.

So make the common case the default, and expose the old behavior as
_unpend_thread_no_timeout().  (Along with identical changes for
_unpend_first_thread) Saves code bytes and simplifies scheduler
surface area for future synchronization work.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross 5792ee6da2 kernel/mutex: Clean up k_mutex_unlock()
Recent changes to the scheduler API means we can simplify this
further: move the assignment to mutex->owner outside the if(), which
removes the need to have an else clause (which just set that field to
NULL when the new_owner was already NULL); and we can likewise move
the irq_unlock() outside the block.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross 15cb5d7293 kernel: Further unify _reschedule APIs
Now that other work has eliminated the two cases where we had to do a
reschedule "but yield even if we are cooperative", we can squash both
down to a single _reschedule() function which does almost exactly what
legacy _Swap() did, but wrapped as a proper scheduler API.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross 0447a73f6c kernel: include cleanup
Recent changes have eliminated most use of _Swap() in favor of higher
level scheduler abstractions.  We can remove the header too.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross e0a572beeb kernel: Refactor, unifying _pend_current_thread() + _Swap() idiom
Everywhere the current thread is pended, the code is going to have to
do a _Swap() soon afterward, yet the scheduler API exposed these as
separate steps.  Unify this pattern everywhere it appears, which saves
some code bytes and gets _Swap() out of the general scheduler API at
zero cost.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross 8606fabf74 kernel: Scheduler refactoring: use _reschedule_*() always
There was a somewhat promiscuous pattern in the kernel where IPC
mechanisms would do something that might effect the current thread
choice, then check _must_switch_threads() (or occasionally
__must_switch_threads -- don't ask, the distinction is being replaced
by real English words), sometimes _is_in_isr() (but not always, even
in contexts where that looks like it would be a mistake), and then
call _Swap() if everything is OK, otherwise releasing the irq_lock().
Sometimes this was done directly, sometimes via the inverted test,
sometimes (poll, heh) by doing the test when the thread state was
modified and then needlessly passing the result up the call stack to
the point of the _Swap().

And some places were just calling _reschedule_threads(), which did all
this already.

Unify all this madness.  The old _reschedule_threads() function has
split into two variants: _reschedule_yield() and
_reschedule_noyield().  The latter is the "normal" one that respects
the cooperative priority of the current thread (i.e. it won't switch
out even if there is a higher priority thread ready -- the current
thread has to pend itself first), the former is used in the handful of
places where code was doing a swap unconditionally, just to preserve
precise behavior across the refactor.  I'm not at all convinced it
should exist...

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30
Andy Ross b481d0a045 kernel: Allow pending w/o wait_q for scheduler API cleanup
The mailbox code was written to use the _remove_thread_from_ready_q()
API directly, which would be good to get out of the scheduler internal
API.  What it really wanted to do is to mark a thread "PENDING"
without actually adding it to a wait queue, which is sane enough (the
message stores the "thread to wake up on receipt" handle).

So allow that naturally in the _pend_thread() API by passing a NULL
wait_q.  Really a wait_q needn't be the only way a thread can block.

Signed-off-by: Andy Ross <andrew.j.ross@intel.com>
2018-04-24 03:57:20 +05:30