Kernel APIs

This section contains APIs for the kernel’s core services, as described in the Zephyr Kernel Primer.

Important

Unless otherwise noted these APIs can be used by threads, but not by ISRs.

Threads

A thread is an independently scheduled series of instructions that implements a portion of an application’s processing. Threads are used to perform processing that is too lengthy or too complex to be performed by an ISR. (See Threads.)

group thread_apis

Defines

K_ESSENTIAL

system thread that must not abort

K_USER

user mode thread

This thread has dropped from supervisor mode to user mode and consequently has additional restrictions

K_INHERIT_PERMS

Inherit Permissions.

Indicates that the thread being created should inherit all kernel object permissions from the thread that created it. No effect if CONFIG_USERSPACE is not enabled.

K_THREAD_DEFINE(name, stack_size, entry, p1, p2, p3, prio, options, delay)

Statically define and initialize a thread.

The thread may be scheduled for immediate execution or a delayed start.

Thread options are architecture-specific, and can include K_ESSENTIAL, K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating them using “|” (the logical OR operator).

The ID of the thread can be accessed using:

extern const k_tid_t <name>; 

Parameters
  • name: Name of the thread.
  • stack_size: Stack size in bytes.
  • entry: Thread entry function.
  • p1: 1st entry point parameter.
  • p2: 2nd entry point parameter.
  • p3: 3rd entry point parameter.
  • prio: Thread priority.
  • options: Thread options.
  • delay: Scheduling delay (in milliseconds), or K_NO_WAIT (for no delay).

Functions

k_tid_t k_thread_create(struct k_thread *new_thread, k_thread_stack_t *stack, size_t stack_size, k_thread_entry_t entry, void *p1, void *p2, void *p3, int prio, u32_t options, s32_t delay)

Create a thread.

This routine initializes a thread, then schedules it for execution.

The new thread may be scheduled for immediate execution or a delayed start. If the newly spawned thread does not have a delayed start the kernel scheduler may preempt the current thread to allow the new thread to execute.

Thread options are architecture-specific, and can include K_ESSENTIAL, K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating them using “|” (the logical OR operator).

Historically, users often would use the beginning of the stack memory region to store the struct k_thread data, although corruption will occur if the stack overflows this region and stack protection features may not detect this situation.

Return
ID of new thread.
Parameters
  • new_thread: Pointer to uninitialized struct k_thread
  • stack: Pointer to the stack space.
  • stack_size: Stack size in bytes.
  • entry: Thread entry function.
  • p1: 1st entry point parameter.
  • p2: 2nd entry point parameter.
  • p3: 3rd entry point parameter.
  • prio: Thread priority.
  • options: Thread options.
  • delay: Scheduling delay (in milliseconds), or K_NO_WAIT (for no delay).

FUNC_NORETURN void k_thread_user_mode_enter(k_thread_entry_t entry, void *p1, void *p2, void *p3)

Drop a thread’s privileges permanently to user mode.

Parameters
  • entry: Function to start executing from
  • p1: 1st entry point parameter
  • p2: 2nd entry point parameter
  • p3: 3rd entry point parameter

void k_thread_access_grant(struct k_thread *thread, ...)

Grant a thread access to a NULL-terminated set of kernel objects.

This is a convenience function. For the provided thread, grant access to the remaining arguments, which must be pointers to kernel objects. The final argument must be a NULL.

The thread object must be initialized (i.e. running). The objects don’t need to be.

Parameters
  • thread: Thread to grant access to objects
  • ...: NULL-terminated list of kernel object pointers

static void k_thread_resource_pool_assign(struct k_thread *thread, struct k_mem_pool *pool)

Assign a resource memory pool to a thread.

By default, threads have no resource pool assigned unless their parent thread has a resource pool, in which case it is inherited. Multiple threads may be assigned to the same memory pool.

Changing a thread’s resource pool will not migrate allocations from the previous pool.

Parameters
  • thread: Target thread to assign a memory pool for resource requests, or NULL if the thread should no longer have a memory pool.
  • pool: Memory pool to use for resources.

void k_sleep(s32_t duration)

Put the current thread to sleep.

This routine puts the current thread to sleep for duration milliseconds.

Return
N/A
Parameters
  • duration: Number of milliseconds to sleep.

void k_busy_wait(u32_t usec_to_wait)

Cause the current thread to busy wait.

This routine causes the current thread to execute a “do nothing” loop for usec_to_wait microseconds.

Return
N/A

void k_yield(void)

Yield the current thread.

This routine causes the current thread to yield execution to another thread of the same or higher priority. If there are no other ready threads of the same or higher priority, the routine returns immediately.

Return
N/A

void k_wakeup(k_tid_t thread)

Wake up a sleeping thread.

This routine prematurely wakes up thread from sleeping.

If thread is not currently sleeping, the routine has no effect.

Return
N/A
Parameters
  • thread: ID of thread to wake.

k_tid_t k_current_get(void)

Get thread ID of the current thread.

Return
ID of current thread.

int k_thread_cancel(k_tid_t thread)

Cancel thread performing a delayed start.

This routine prevents thread from executing if it has not yet started execution. The thread must be re-spawned before it will execute.

Parameters
  • thread: ID of thread to cancel.
Return Value
  • 0: Thread spawning canceled.
  • -EINVAL: Thread has already started executing.

void k_thread_abort(k_tid_t thread)

Abort a thread.

This routine permanently stops execution of thread. The thread is taken off all kernel queues it is part of (i.e. the ready queue, the timeout queue, or a kernel object wait queue). However, any kernel resources the thread might currently own (such as mutexes or memory blocks) are not released. It is the responsibility of the caller of this routine to ensure all necessary cleanup is performed.

Return
N/A
Parameters
  • thread: ID of thread to abort.

void k_thread_start(k_tid_t thread)

Start an inactive thread.

If a thread was created with K_FOREVER in the delay parameter, it will not be added to the scheduling queue until this function is called on it.

Parameters
  • thread: thread to start

int k_thread_priority_get(k_tid_t thread)

Get a thread’s priority.

This routine gets the priority of thread.

Return
Priority of thread.
Parameters
  • thread: ID of thread whose priority is needed.

void k_thread_priority_set(k_tid_t thread, int prio)

Set a thread’s priority.

This routine immediately changes the priority of thread.

Rescheduling can occur immediately depending on the priority thread is set to:

  • If its priority is raised above the priority of the caller of this function, and the caller is preemptible, thread will be scheduled in.
  • If the caller operates on itself, it lowers its priority below that of other threads in the system, and the caller is preemptible, the thread of highest priority will be scheduled in.

Priority can be assigned in the range of -CONFIG_NUM_COOP_PRIORITIES to CONFIG_NUM_PREEMPT_PRIORITIES-1, where -CONFIG_NUM_COOP_PRIORITIES is the highest priority.

Warning
Changing the priority of a thread currently involved in mutex priority inheritance may result in undefined behavior.
Return
N/A
Parameters
  • thread: ID of thread whose priority is to be set.
  • prio: New priority.

void k_thread_suspend(k_tid_t thread)

Suspend a thread.

This routine prevents the kernel scheduler from making thread the current thread. All other internal operations on thread are still performed; for example, any timeout it is waiting on keeps ticking, kernel objects it is waiting on are still handed to it, etc.

If thread is already suspended, the routine has no effect.

Return
N/A
Parameters
  • thread: ID of thread to suspend.

void k_thread_resume(k_tid_t thread)

Resume a suspended thread.

This routine allows the kernel scheduler to make thread the current thread, when it is next eligible for that role.

If thread is not currently suspended, the routine has no effect.

Return
N/A
Parameters
  • thread: ID of thread to resume.

void k_sched_time_slice_set(s32_t slice, int prio)

Set time-slicing period and scope.

This routine specifies how the scheduler will perform time slicing of preemptible threads.

To enable time slicing, slice must be non-zero. The scheduler ensures that no thread runs for more than the specified time limit before other threads of that priority are given a chance to execute. Any thread whose priority is higher than prio is exempted, and may execute as long as desired without being preempted due to time slicing.

Time slicing only limits the maximum amount of time a thread may continuously execute. Once the scheduler selects a thread for execution, there is no minimum guaranteed time the thread will execute before threads of greater or equal priority are scheduled.

When the current thread is the only one of that priority eligible for execution, this routine has no effect; the thread is immediately rescheduled after the slice period expires.

To disable timeslicing, set both slice and prio to zero.

Return
N/A
Parameters
  • slice: Maximum time slice length (in milliseconds).
  • prio: Highest thread priority level eligible for time slicing.

void k_sched_lock(void)

Lock the scheduler.

This routine prevents the current thread from being preempted by another thread by instructing the scheduler to treat it as a cooperative thread. If the thread subsequently performs an operation that makes it unready, it will be context switched out in the normal manner. When the thread again becomes the current thread, its non-preemptible status is maintained.

This routine can be called recursively.

Note
k_sched_lock() and k_sched_unlock() should normally be used when the operation being performed can be safely interrupted by ISRs. However, if the amount of processing involved is very small, better performance may be obtained by using irq_lock() and irq_unlock().
Return
N/A

void k_sched_unlock(void)

Unlock the scheduler.

This routine reverses the effect of a previous call to k_sched_lock(). A thread must call the routine once for each time it called k_sched_lock() before the thread becomes preemptible.

Return
N/A

void k_thread_custom_data_set(void *value)

Set current thread’s custom data.

This routine sets the custom data for the current thread to @ value.

Custom data is not used by the kernel itself, and is freely available for a thread to use as it sees fit. It can be used as a framework upon which to build thread-local storage.

Return
N/A
Parameters
  • value: New custom data value.

void *k_thread_custom_data_get(void)

Get current thread’s custom data.

This routine returns the custom data for the current thread.

Return
Current custom data value.

struct k_thread
#include <kernel.h>

Thread Structure

Workqueues

A workqueue processes a series of work items by executing the associated functions in a dedicated thread. Workqueues are typically used by an ISR or high-priority thread to offload non-urgent processing. (See Workqueue Threads.)

group workqueue_apis

Defines

K_WORK_INITIALIZER
K_WORK_DEFINE(work, work_handler)

Initialize a statically-defined work item.

This macro can be used to initialize a statically-defined workqueue work item, prior to its first use. For example,

static K_WORK_DEFINE(<work>, <work_handler>); 

Parameters
  • work: Symbol name for work item object
  • work_handler: Function to invoke each time work item is processed.

Typedefs

typedef k_work_handler_t

Work item handler function type.

A work item’s handler function is executed by a workqueue’s thread when the work item is processed by the workqueue.

Return
N/A
Parameters
  • work: Address of the work item.

Functions

static void k_work_init(struct k_work *work, k_work_handler_t handler)

Initialize a work item.

This routine initializes a workqueue work item, prior to its first use.

Return
N/A
Parameters
  • work: Address of work item.
  • handler: Function to invoke each time work item is processed.

static void k_work_submit_to_queue(struct k_work_q *work_q, struct k_work *work)

Submit a work item.

This routine submits work item work to be processed by workqueue work_q. If the work item is already pending in the workqueue’s queue as a result of an earlier submission, this routine has no effect on the work item. If the work item has already been processed, or is currently being processed, its work is considered complete and the work item can be resubmitted.

Warning
A submitted work item must not be modified until it has been processed by the workqueue.
Note
Can be called by ISRs.
Return
N/A
Parameters
  • work_q: Address of workqueue.
  • work: Address of work item.

static int k_work_pending(struct k_work *work)

Check if a work item is pending.

This routine indicates if work item work is pending in a workqueue’s queue.

Note
Can be called by ISRs.
Return
1 if work item is pending, or 0 if it is not pending.
Parameters
  • work: Address of work item.

void k_work_q_start(struct k_work_q *work_q, k_thread_stack_t *stack, size_t stack_size, int prio)

Start a workqueue.

This routine starts workqueue work_q. The workqueue spawns its work processing thread, which runs forever.

Return
N/A
Parameters
  • work_q: Address of workqueue.
  • stack: Pointer to work queue thread’s stack space, as defined by K_THREAD_STACK_DEFINE()
  • stack_size: Size of the work queue thread’s stack (in bytes), which should either be the same constant passed to K_THREAD_STACK_DEFINE() or the value of K_THREAD_STACK_SIZEOF().
  • prio: Priority of the work queue’s thread.

void k_delayed_work_init(struct k_delayed_work *work, k_work_handler_t handler)

Initialize a delayed work item.

This routine initializes a workqueue delayed work item, prior to its first use.

Return
N/A
Parameters
  • work: Address of delayed work item.
  • handler: Function to invoke each time work item is processed.

int k_delayed_work_submit_to_queue(struct k_work_q *work_q, struct k_delayed_work *work, s32_t delay)

Submit a delayed work item.

This routine schedules work item work to be processed by workqueue work_q after a delay of delay milliseconds. The routine initiates an asynchronous countdown for the work item and then returns to the caller. Only when the countdown completes is the work item actually submitted to the workqueue and becomes pending.

Submitting a previously submitted delayed work item that is still counting down cancels the existing submission and restarts the countdown using the new delay. Note that this behavior is inherently subject to race conditions with the pre-existing timeouts and work queue, so care must be taken to synchronize such resubmissions externally.

Warning
A delayed work item must not be modified until it has been processed by the workqueue.
Note
Can be called by ISRs.
Parameters
  • work_q: Address of workqueue.
  • work: Address of delayed work item.
  • delay: Delay before submitting the work item (in milliseconds).
Return Value
  • 0: Work item countdown started.
  • -EINPROGRESS: Work item is already pending.
  • -EINVAL: Work item is being processed or has completed its work.
  • -EADDRINUSE: Work item is pending on a different workqueue.

int k_delayed_work_cancel(struct k_delayed_work *work)

Cancel a delayed work item.

This routine cancels the submission of delayed work item work. A delayed work item can only be canceled while its countdown is still underway.

Note
Can be called by ISRs.
Parameters
  • work: Address of delayed work item.
Return Value
  • 0: Work item countdown canceled.
  • -EINPROGRESS: Work item is already pending.
  • -EINVAL: Work item is being processed or has completed its work.

static void k_work_submit(struct k_work *work)

Submit a work item to the system workqueue.

This routine submits work item work to be processed by the system workqueue. If the work item is already pending in the workqueue’s queue as a result of an earlier submission, this routine has no effect on the work item. If the work item has already been processed, or is currently being processed, its work is considered complete and the work item can be resubmitted.

Warning
Work items submitted to the system workqueue should avoid using handlers that block or yield since this may prevent the system workqueue from processing other work items in a timely manner.
Note
Can be called by ISRs.
Return
N/A
Parameters
  • work: Address of work item.

static int k_delayed_work_submit(struct k_delayed_work *work, s32_t delay)

Submit a delayed work item to the system workqueue.

This routine schedules work item work to be processed by the system workqueue after a delay of delay milliseconds. The routine initiates an asynchronous countdown for the work item and then returns to the caller. Only when the countdown completes is the work item actually submitted to the workqueue and becomes pending.

Submitting a previously submitted delayed work item that is still counting down cancels the existing submission and restarts the countdown using the new delay. If the work item is currently pending on the workqueue’s queue because the countdown has completed it is too late to resubmit the item, and resubmission fails without impacting the work item. If the work item has already been processed, or is currently being processed, its work is considered complete and the work item can be resubmitted.

Warning
Work items submitted to the system workqueue should avoid using handlers that block or yield since this may prevent the system workqueue from processing other work items in a timely manner.
Note
Can be called by ISRs.
Parameters
  • work: Address of delayed work item.
  • delay: Delay before submitting the work item (in milliseconds).
Return Value
  • 0: Work item countdown started.
  • -EINPROGRESS: Work item is already pending.
  • -EINVAL: Work item is being processed or has completed its work.
  • -EADDRINUSE: Work item is pending on a different workqueue.

static s32_t k_delayed_work_remaining_get(struct k_delayed_work *work)

Get time remaining before a delayed work gets scheduled.

This routine computes the (approximate) time remaining before a delayed work gets executed. If the delayed work is not waiting to be scheduled, it returns zero.

Return
Remaining time (in milliseconds).
Parameters
  • work: Delayed work item.

Clocks

Kernel clocks enable threads and ISRs to measure the passage of time with either normal and high precision. (See Kernel Clocks.)

group clock_apis

Defines

K_NO_WAIT

Generate null timeout delay.

This macro generates a timeout delay that that instructs a kernel API not to wait if the requested operation cannot be performed immediately.

Return
Timeout delay value.

K_MSEC(ms)

Generate timeout delay from milliseconds.

This macro generates a timeout delay that that instructs a kernel API to wait up to ms milliseconds to perform the requested operation.

Return
Timeout delay value.
Parameters
  • ms: Duration in milliseconds.

K_SECONDS(s)

Generate timeout delay from seconds.

This macro generates a timeout delay that that instructs a kernel API to wait up to s seconds to perform the requested operation.

Return
Timeout delay value.
Parameters
  • s: Duration in seconds.

K_MINUTES(m)

Generate timeout delay from minutes.

This macro generates a timeout delay that that instructs a kernel API to wait up to m minutes to perform the requested operation.

Return
Timeout delay value.
Parameters
  • m: Duration in minutes.

K_HOURS(h)

Generate timeout delay from hours.

This macro generates a timeout delay that that instructs a kernel API to wait up to h hours to perform the requested operation.

Return
Timeout delay value.
Parameters
  • h: Duration in hours.

K_FOREVER

Generate infinite timeout delay.

This macro generates a timeout delay that that instructs a kernel API to wait as long as necessary to perform the requested operation.

Return
Timeout delay value.

k_cycle_get_32

Read the hardware clock.

This routine returns the current time, as measured by the system’s hardware clock.

Return
Current hardware clock up-counter (in cycles).

SYS_CLOCK_HW_CYCLES_TO_NS(X)

Compute nanoseconds from hardware clock cycles.

This macro converts a time duration expressed in hardware clock cycles to the equivalent duration expressed in nanoseconds.

Return
Duration in nanoseconds.
Parameters
  • X: Duration in hardware clock cycles.

Functions

s64_t k_uptime_get(void)

Get system uptime.

This routine returns the elapsed time since the system booted, in milliseconds.

Return
Current uptime.

static int k_enable_sys_clock_always_on(void)

Enable clock always on in tickless kernel.

This routine enables keeping the clock running when there are no timer events programmed in tickless kernel scheduling. This is necessary if the clock is used to track passage of time.

Return Value
  • prev_status: Previous status of always on flag

static void k_disable_sys_clock_always_on(void)

Disable clock always on in tickless kernel.

This routine disables keeping the clock running when there are no timer events programmed in tickless kernel scheduling. To save power, this routine should be called immediately when clock is not used to track time.

u32_t k_uptime_get_32(void)

Get system uptime (32-bit version).

This routine returns the lower 32-bits of the elapsed time since the system booted, in milliseconds.

This routine can be more efficient than k_uptime_get(), as it reduces the need for interrupt locking and 64-bit math. However, the 32-bit result cannot hold a system uptime time larger than approximately 50 days, so the caller must handle possible rollovers.

Return
Current uptime.

s64_t k_uptime_delta(s64_t *reftime)

Get elapsed time.

This routine computes the elapsed time between the current system uptime and an earlier reference time, in milliseconds.

Return
Elapsed time.
Parameters
  • reftime: Pointer to a reference time, which is updated to the current uptime upon return.

u32_t k_uptime_delta_32(s64_t *reftime)

Get elapsed time (32-bit version).

This routine computes the elapsed time between the current system uptime and an earlier reference time, in milliseconds.

This routine can be more efficient than k_uptime_delta(), as it reduces the need for interrupt locking and 64-bit math. However, the 32-bit result cannot hold an elapsed time larger than approximately 50 days, so the caller must handle possible rollovers.

Return
Elapsed time.
Parameters
  • reftime: Pointer to a reference time, which is updated to the current uptime upon return.

Timers

Timers enable threads to measure the passage of time, and to optionally execute an action when the timer expires. (See Timers.)

group timer_apis

Defines

K_TIMER_DEFINE(name, expiry_fn, stop_fn)

Statically define and initialize a timer.

The timer can be accessed outside the module where it is defined using:

extern struct k_timer <name>; 

Parameters
  • name: Name of the timer variable.
  • expiry_fn: Function to invoke each time the timer expires.
  • stop_fn: Function to invoke if the timer is stopped while running.

Typedefs

typedef k_timer_expiry_t

Timer expiry function type.

A timer’s expiry function is executed by the system clock interrupt handler each time the timer expires. The expiry function is optional, and is only invoked if the timer has been initialized with one.

Return
N/A
Parameters
  • timer: Address of timer.

typedef k_timer_stop_t

Timer stop function type.

A timer’s stop function is executed if the timer is stopped prematurely. The function runs in the context of the thread that stops the timer. The stop function is optional, and is only invoked if the timer has been initialized with one.

Return
N/A
Parameters
  • timer: Address of timer.

Functions

void k_timer_init(struct k_timer *timer, k_timer_expiry_t expiry_fn, k_timer_stop_t stop_fn)

Initialize a timer.

This routine initializes a timer, prior to its first use.

Return
N/A
Parameters
  • timer: Address of timer.
  • expiry_fn: Function to invoke each time the timer expires.
  • stop_fn: Function to invoke if the timer is stopped while running.

void k_timer_start(struct k_timer *timer, s32_t duration, s32_t period)

Start a timer.

This routine starts a timer, and resets its status to zero. The timer begins counting down using the specified duration and period values.

Attempting to start a timer that is already running is permitted. The timer’s status is reset to zero and the timer begins counting down using the new duration and period values.

Return
N/A
Parameters
  • timer: Address of timer.
  • duration: Initial timer duration (in milliseconds).
  • period: Timer period (in milliseconds).

void k_timer_stop(struct k_timer *timer)

Stop a timer.

This routine stops a running timer prematurely. The timer’s stop function, if one exists, is invoked by the caller.

Attempting to stop a timer that is not running is permitted, but has no effect on the timer.

Note
Can be called by ISRs. The stop handler has to be callable from ISRs if k_timer_stop is to be called from ISRs.
Return
N/A
Parameters
  • timer: Address of timer.

u32_t k_timer_status_get(struct k_timer *timer)

Read timer status.

This routine reads the timer’s status, which indicates the number of times it has expired since its status was last read.

Calling this routine resets the timer’s status to zero.

Return
Timer status.
Parameters
  • timer: Address of timer.

u32_t k_timer_status_sync(struct k_timer *timer)

Synchronize thread to timer expiration.

This routine blocks the calling thread until the timer’s status is non-zero (indicating that it has expired at least once since it was last examined) or the timer is stopped. If the timer status is already non-zero, or the timer is already stopped, the caller continues without waiting.

Calling this routine resets the timer’s status to zero.

This routine must not be used by interrupt handlers, since they are not allowed to block.

Return
Timer status.
Parameters
  • timer: Address of timer.

s32_t k_timer_remaining_get(struct k_timer *timer)

Get time remaining before a timer next expires.

This routine computes the (approximate) time remaining before a running timer next expires. If the timer is not running, it returns zero.

Return
Remaining time (in milliseconds).
Parameters
  • timer: Address of timer.

void k_timer_user_data_set(struct k_timer *timer, void *user_data)

Associate user-specific data with a timer.

This routine records the user_data with the timer, to be retrieved later.

It can be used e.g. in a timer handler shared across multiple subsystems to retrieve data specific to the subsystem this timer is associated with.

Return
N/A
Parameters
  • timer: Address of timer.
  • user_data: User data to associate with the timer.

void *k_timer_user_data_get(struct k_timer *timer)

Retrieve the user-specific data from a timer.

Return
The user data.
Parameters
  • timer: Address of timer.

Memory Slabs

Memory slabs enable the dynamic allocation and release of fixed-size memory blocks. (See Memory Slabs.)

group mem_slab_apis

Defines

K_MEM_SLAB_DEFINE(name, slab_block_size, slab_num_blocks, slab_align)

Statically define and initialize a memory slab.

The memory slab’s buffer contains slab_num_blocks memory blocks that are slab_block_size bytes long. The buffer is aligned to a slab_align -byte boundary. To ensure that each memory block is similarly aligned to this boundary, slab_block_size must also be a multiple of slab_align.

The memory slab can be accessed outside the module where it is defined using:

extern struct k_mem_slab <name>; 

Parameters
  • name: Name of the memory slab.
  • slab_block_size: Size of each memory block (in bytes).
  • slab_num_blocks: Number memory blocks.
  • slab_align: Alignment of the memory slab’s buffer (power of 2).

Functions

void k_mem_slab_init(struct k_mem_slab *slab, void *buffer, size_t block_size, u32_t num_blocks)

Initialize a memory slab.

Initializes a memory slab, prior to its first use.

The memory slab’s buffer contains slab_num_blocks memory blocks that are slab_block_size bytes long. The buffer must be aligned to an N-byte boundary, where N is a power of 2 larger than 2 (i.e. 4, 8, 16, …). To ensure that each memory block is similarly aligned to this boundary, slab_block_size must also be a multiple of N.

Return
N/A
Parameters
  • slab: Address of the memory slab.
  • buffer: Pointer to buffer used for the memory blocks.
  • block_size: Size of each memory block (in bytes).
  • num_blocks: Number of memory blocks.

int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem, s32_t timeout)

Allocate memory from a memory slab.

This routine allocates a memory block from a memory slab.

Parameters
  • slab: Address of the memory slab.
  • mem: Pointer to block address area.
  • timeout: Maximum time to wait for operation to complete (in milliseconds). Use K_NO_WAIT to return without waiting, or K_FOREVER to wait as long as necessary.
Return Value
  • 0: Memory allocated. The block address area pointed at by mem is set to the starting address of the memory block.
  • -ENOMEM: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_mem_slab_free(struct k_mem_slab *slab, void **mem)

Free memory allocated from a memory slab.

This routine releases a previously allocated memory block back to its associated memory slab.

Return
N/A
Parameters
  • slab: Address of the memory slab.
  • mem: Pointer to block address area (as set by k_mem_slab_alloc()).

static u32_t k_mem_slab_num_used_get(struct k_mem_slab *slab)

Get the number of used blocks in a memory slab.

This routine gets the number of memory blocks that are currently allocated in slab.

Return
Number of allocated memory blocks.
Parameters
  • slab: Address of the memory slab.

static u32_t k_mem_slab_num_free_get(struct k_mem_slab *slab)

Get the number of unused blocks in a memory slab.

This routine gets the number of memory blocks that are currently unallocated in slab.

Return
Number of unallocated memory blocks.
Parameters
  • slab: Address of the memory slab.

Memory Pools

Memory pools enable the dynamic allocation and release of variable-size memory blocks. (See Memory Pools.)

group mem_pool_apis

Defines

K_MEM_POOL_DEFINE(name, minsz, maxsz, nmax, align)

Statically define and initialize a memory pool.

The memory pool’s buffer contains n_max blocks that are max_size bytes long. The memory pool allows blocks to be repeatedly partitioned into quarters, down to blocks of min_size bytes long. The buffer is aligned to a align -byte boundary.

If the pool is to be accessed outside the module where it is defined, it can be declared via

extern struct k_mem_pool <name>; 

Parameters
  • name: Name of the memory pool.
  • minsz: Size of the smallest blocks in the pool (in bytes).
  • maxsz: Size of the largest blocks in the pool (in bytes).
  • nmax: Number of maximum sized blocks in the pool.
  • align: Alignment of the pool’s buffer (power of 2).

Functions

int k_mem_pool_alloc(struct k_mem_pool *pool, struct k_mem_block *block, size_t size, s32_t timeout)

Allocate memory from a memory pool.

This routine allocates a memory block from a memory pool.

Parameters
  • pool: Address of the memory pool.
  • block: Pointer to block descriptor for the allocated memory.
  • size: Amount of memory to allocate (in bytes).
  • timeout: Maximum time to wait for operation to complete (in milliseconds). Use K_NO_WAIT to return without waiting, or K_FOREVER to wait as long as necessary.
Return Value
  • 0: Memory allocated. The data field of the block descriptor is set to the starting address of the memory block.
  • -ENOMEM: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void *k_mem_pool_malloc(struct k_mem_pool *pool, size_t size)

Allocate memory from a memory pool with malloc() semantics.

Such memory must be released using k_free().

Return
Address of the allocated memory if successful, otherwise NULL
Parameters
  • pool: Address of the memory pool.
  • size: Amount of memory to allocate (in bytes).

void k_mem_pool_free(struct k_mem_block *block)

Free memory allocated from a memory pool.

This routine releases a previously allocated memory block back to its memory pool.

Return
N/A
Parameters
  • block: Pointer to block descriptor for the allocated memory.

void k_mem_pool_free_id(struct k_mem_block_id *id)

Free memory allocated from a memory pool.

This routine releases a previously allocated memory block back to its memory pool

Return
N/A
Parameters
  • id: Memory block identifier.

Heap Memory Pool

The heap memory pools enable the dynamic allocation and release of memory in a malloc()-like manner. (See Heap Memory Pool.)

group heap_apis

Functions

void *k_malloc(size_t size)

Allocate memory from heap.

This routine provides traditional malloc() semantics. Memory is allocated from the heap memory pool.

Return
Address of the allocated memory if successful; otherwise NULL.
Parameters
  • size: Amount of memory requested (in bytes).

void k_free(void *ptr)

Free memory allocated from heap.

This routine provides traditional free() semantics. The memory being returned must have been allocated from the heap memory pool or k_mem_pool_malloc().

If ptr is NULL, no operation is performed.

Return
N/A
Parameters
  • ptr: Pointer to previously allocated memory.

void *k_calloc(size_t nmemb, size_t size)

Allocate memory from heap, array style.

This routine provides traditional calloc() semantics. Memory is allocated from the heap memory pool and zeroed.

Return
Address of the allocated memory if successful; otherwise NULL.
Parameters
  • nmemb: Number of elements in the requested array
  • size: Size of each array element (in bytes).

Semaphores

Semaphores provide traditional counting semaphore capabilities. (See Semaphores.)

group semaphore_apis

Defines

K_SEM_DEFINE(name, initial_count, count_limit)

Statically define and initialize a semaphore.

The semaphore can be accessed outside the module where it is defined using:

extern struct k_sem <name>; 

Parameters
  • name: Name of the semaphore.
  • initial_count: Initial semaphore count.
  • count_limit: Maximum permitted semaphore count.

Functions

void k_sem_init(struct k_sem *sem, unsigned int initial_count, unsigned int limit)

Initialize a semaphore.

This routine initializes a semaphore object, prior to its first use.

Return
N/A
Parameters
  • sem: Address of the semaphore.
  • initial_count: Initial semaphore count.
  • limit: Maximum permitted semaphore count.

int k_sem_take(struct k_sem *sem, s32_t timeout)

Take a semaphore.

This routine takes sem.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Note
When porting code from the nanokernel legacy API to the new API, be careful with the return value of this function. The return value is the reverse of the one of nano_sem_take family of APIs: 0 means success, and non-zero means failure, while the nano_sem_take family returns 1 for success and 0 for failure.
Parameters
  • sem: Address of the semaphore.
  • timeout: Waiting period to take the semaphore (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Semaphore taken.
  • -EBUSY: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_sem_give(struct k_sem *sem)

Give a semaphore.

This routine gives sem, unless the semaphore is already at its maximum permitted count.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • sem: Address of the semaphore.

void k_sem_reset(struct k_sem *sem)

Reset a semaphore’s count to zero.

This routine sets the count of sem to zero.

Return
N/A
Parameters
  • sem: Address of the semaphore.

unsigned int k_sem_count_get(struct k_sem *sem)

Get a semaphore’s count.

This routine returns the current count of sem.

Return
Current semaphore count.
Parameters
  • sem: Address of the semaphore.

Mutexes

Mutexes provide traditional reentrant mutex capabilities with basic priority inheritance. (See Mutexes.)

group mutex_apis

Defines

K_MUTEX_DEFINE(name)

Statically define and initialize a mutex.

The mutex can be accessed outside the module where it is defined using:

extern struct k_mutex <name>; 

Parameters
  • name: Name of the mutex.

Functions

void k_mutex_init(struct k_mutex *mutex)

Initialize a mutex.

This routine initializes a mutex object, prior to its first use.

Upon completion, the mutex is available and does not have an owner.

Return
N/A
Parameters
  • mutex: Address of the mutex.

int k_mutex_lock(struct k_mutex *mutex, s32_t timeout)

Lock a mutex.

This routine locks mutex. If the mutex is locked by another thread, the calling thread waits until the mutex becomes available or until a timeout occurs.

A thread is permitted to lock a mutex it has already locked. The operation completes immediately and the lock count is increased by 1.

Parameters
  • mutex: Address of the mutex.
  • timeout: Waiting period to lock the mutex (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Mutex locked.
  • -EBUSY: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_mutex_unlock(struct k_mutex *mutex)

Unlock a mutex.

This routine unlocks mutex. The mutex must already be locked by the calling thread.

The mutex cannot be claimed by another thread until it has been unlocked by the calling thread as many times as it was previously locked by that thread.

Return
N/A
Parameters
  • mutex: Address of the mutex.

struct k_mutex
#include <kernel.h>

Mutex Structure

Alerts

Alerts enable an application to perform asynchronous signaling, somewhat akin to Unix-style signals. (See Alerts.)

group alert_apis

Defines

K_ALERT_DEFINE(name, alert_handler, max_num_pending_alerts)

Statically define and initialize an alert.

The alert can be accessed outside the module where it is defined using:

extern struct k_alert <name>; 

Parameters
  • name: Name of the alert.
  • alert_handler: Action to take when alert is sent. Specify either the address of a function to be invoked by the system workqueue thread, K_ALERT_IGNORE (which causes the alert to be ignored), or K_ALERT_DEFAULT (which causes the alert to pend).
  • max_num_pending_alerts: Maximum number of pending alerts.

Typedefs

typedef k_alert_handler_t

Alert handler function type.

An alert’s alert handler function is invoked by the system workqueue when the alert is signaled. The alert handler function is optional, and is only invoked if the alert has been initialized with one.

Return
0 if alert has been consumed; non-zero if alert should pend.
Parameters
  • alert: Address of the alert.

Functions

void k_alert_init(struct k_alert *alert, k_alert_handler_t handler, unsigned int max_num_pending_alerts)

Initialize an alert.

This routine initializes an alert object, prior to its first use.

Return
N/A
Parameters
  • alert: Address of the alert.
  • handler: Action to take when alert is sent. Specify either the address of a function to be invoked by the system workqueue thread, K_ALERT_IGNORE (which causes the alert to be ignored), or K_ALERT_DEFAULT (which causes the alert to pend).
  • max_num_pending_alerts: Maximum number of pending alerts.

int k_alert_recv(struct k_alert *alert, s32_t timeout)

Receive an alert.

This routine receives a pending alert for alert.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Parameters
  • alert: Address of the alert.
  • timeout: Waiting period to receive the alert (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Alert received.
  • -EBUSY: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_alert_send(struct k_alert *alert)

Signal an alert.

This routine signals alert. The action specified for alert will be taken, which may trigger the execution of an alert handler function and/or cause the alert to pend (assuming the alert has not reached its maximum number of pending alerts).

Note
Can be called by ISRs.
Return
N/A
Parameters
  • alert: Address of the alert.

FIFOs

FIFOs provide traditional first in, first out (FIFO) queuing of data items of any size. (See FIFOs.)

group fifo_apis

Defines

k_fifo_init(fifo)

Initialize a FIFO queue.

This routine initializes a FIFO queue, prior to its first use.

Return
N/A
Parameters
  • fifo: Address of the FIFO queue.

k_fifo_cancel_wait(fifo)

Cancel waiting on a FIFO queue.

This routine causes first thread pending on fifo, if any, to return from k_fifo_get() call with NULL value (as if timeout expired).

Note
Can be called by ISRs.
Return
N/A
Parameters
  • fifo: Address of the FIFO queue.

k_fifo_put(fifo, data)

Add an element to a FIFO queue.

This routine adds a data item to fifo. A FIFO data item must be aligned on a 4-byte boundary, and the first 32 bits of the item are reserved for the kernel’s use.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • fifo: Address of the FIFO.
  • data: Address of the data item.

k_fifo_alloc_put(fifo, data)

Add an element to a FIFO queue.

This routine adds a data item to fifo. There is an implicit memory allocation from the calling thread’s resource pool, which is automatically freed when the item is removed.

Note
Can be called by ISRs.
Parameters
  • fifo: Address of the FIFO.
  • data: Address of the data item.
Return Value
  • 0: on success
  • -ENOMEM: if there isn’t sufficient RAM in the caller’s resource pool

k_fifo_put_list(fifo, head, tail)

Atomically add a list of elements to a FIFO.

This routine adds a list of data items to fifo in one operation. The data items must be in a singly-linked list, with the first 32 bits each data item pointing to the next data item; the list must be NULL-terminated.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • fifo: Address of the FIFO queue.
  • head: Pointer to first node in singly-linked list.
  • tail: Pointer to last node in singly-linked list.

k_fifo_put_slist(fifo, list)

Atomically add a list of elements to a FIFO queue.

This routine adds a list of data items to fifo in one operation. The data items must be in a singly-linked list implemented using a sys_slist_t object. Upon completion, the sys_slist_t object is invalid and must be re-initialized via sys_slist_init().

Note
Can be called by ISRs.
Return
N/A
Parameters
  • fifo: Address of the FIFO queue.
  • list: Pointer to sys_slist_t object.

k_fifo_get(fifo, timeout)

Get an element from a FIFO queue.

This routine removes a data item from fifo in a “first in, first out” manner. The first 32 bits of the data item are reserved for the kernel’s use.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Return
Address of the data item if successful; NULL if returned without waiting, or waiting period timed out.
Parameters
  • fifo: Address of the FIFO queue.
  • timeout: Waiting period to obtain a data item (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.

k_fifo_is_empty(fifo)

Query a FIFO queue to see if it has data available.

Note that the data might be already gone by the time this function returns if other threads is also trying to read from the FIFO.

Note
Can be called by ISRs.
Return
Non-zero if the FIFO queue is empty.
Return
0 if data is available.
Parameters
  • fifo: Address of the FIFO queue.

k_fifo_peek_head(fifo)

Peek element at the head of a FIFO queue.

Return element from the head of FIFO queue without removing it. A usecase for this is if elements of the FIFO object are themselves containers. Then on each iteration of processing, a head container will be peeked, and some data processed out of it, and only if the container is empty, it will be completely remove from the FIFO queue.

Return
Head element, or NULL if the FIFO queue is empty.
Parameters
  • fifo: Address of the FIFO queue.

k_fifo_peek_tail(fifo)

Peek element at the tail of FIFO queue.

Return element from the tail of FIFO queue (without removing it). A usecase for this is if elements of the FIFO queue are themselves containers. Then it may be useful to add more data to the last container in a FIFO queue.

Return
Tail element, or NULL if a FIFO queue is empty.
Parameters
  • fifo: Address of the FIFO queue.

K_FIFO_DEFINE(name)

Statically define and initialize a FIFO queue.

The FIFO queue can be accessed outside the module where it is defined using:

extern struct k_fifo <name>; 

Parameters
  • name: Name of the FIFO queue.

LIFOs

LIFOs provide traditional last in, first out (LIFO) queuing of data items of any size. (See LIFOs.)

group lifo_apis

Defines

k_lifo_init(lifo)

Initialize a LIFO queue.

This routine initializes a LIFO queue object, prior to its first use.

Return
N/A
Parameters
  • lifo: Address of the LIFO queue.

k_lifo_put(lifo, data)

Add an element to a LIFO queue.

This routine adds a data item to lifo. A LIFO queue data item must be aligned on a 4-byte boundary, and the first 32 bits of the item are reserved for the kernel’s use.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • lifo: Address of the LIFO queue.
  • data: Address of the data item.

k_lifo_alloc_put(lifo, data)

Add an element to a LIFO queue.

This routine adds a data item to lifo. There is an implicit memory allocation from the calling thread’s resource pool, which is automatically freed when the item is removed.

Note
Can be called by ISRs.
Parameters
  • lifo: Address of the LIFO.
  • data: Address of the data item.
Return Value
  • 0: on success
  • -ENOMEM: if there isn’t sufficient RAM in the caller’s resource pool

k_lifo_get(lifo, timeout)

Get an element from a LIFO queue.

This routine removes a data item from lifo in a “last in, first out” manner. The first 32 bits of the data item are reserved for the kernel’s use.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Return
Address of the data item if successful; NULL if returned without waiting, or waiting period timed out.
Parameters
  • lifo: Address of the LIFO queue.
  • timeout: Waiting period to obtain a data item (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.

K_LIFO_DEFINE(name)

Statically define and initialize a LIFO queue.

The LIFO queue can be accessed outside the module where it is defined using:

extern struct k_lifo <name>; 

Parameters
  • name: Name of the fifo.

Stacks

Stacks provide traditional last in, first out (LIFO) queuing of 32-bit data items. (See Stacks.)

group stack_apis

Defines

K_STACK_DEFINE(name, stack_num_entries)

Statically define and initialize a stack.

The stack can be accessed outside the module where it is defined using:

extern struct k_stack <name>; 

Parameters
  • name: Name of the stack.
  • stack_num_entries: Maximum number of values that can be stacked.

Functions

void k_stack_init(struct k_stack *stack, u32_t *buffer, unsigned int num_entries)

Initialize a stack.

This routine initializes a stack object, prior to its first use.

Return
N/A
Parameters
  • stack: Address of the stack.
  • buffer: Address of array used to hold stacked values.
  • num_entries: Maximum number of values that can be stacked.

int k_stack_alloc_init(struct k_stack *stack, unsigned int num_entries)

Initialize a stack.

This routine initializes a stack object, prior to its first use. Internal buffers will be allocated from the calling thread’s resource pool. This memory will be released if k_stack_cleanup() is called, or userspace is enabled and the stack object loses all references to it.

Return
-ENOMEM if memory couldn’t be allocated
Parameters
  • stack: Address of the stack.
  • num_entries: Maximum number of values that can be stacked.

void k_stack_cleanup(struct k_stack *stack)

Release a stack’s allocated buffer.

If a stack object was given a dynamically allocated buffer via k_stack_alloc_init(), this will free it. This function does nothing if the buffer wasn’t dynamically allocated.

Parameters
  • stack: Address of the stack.

void k_stack_push(struct k_stack *stack, u32_t data)

Push an element onto a stack.

This routine adds a 32-bit value data to stack.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • stack: Address of the stack.
  • data: Value to push onto the stack.

int k_stack_pop(struct k_stack *stack, u32_t *data, s32_t timeout)

Pop an element from a stack.

This routine removes a 32-bit value from stack in a “last in, first out” manner and stores the value in data.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Parameters
  • stack: Address of the stack.
  • data: Address of area to hold the value popped from the stack.
  • timeout: Waiting period to obtain a value (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Element popped from stack.
  • -EBUSY: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

Queues

group queue_apis

Defines

K_QUEUE_DEFINE(name)

Statically define and initialize a queue.

The queue can be accessed outside the module where it is defined using:

extern struct k_queue <name>; 

Parameters
  • name: Name of the queue.

Functions

void k_queue_init(struct k_queue *queue)

Initialize a queue.

This routine initializes a queue object, prior to its first use.

Return
N/A
Parameters
  • queue: Address of the queue.

void k_queue_cancel_wait(struct k_queue *queue)

Cancel waiting on a queue.

This routine causes first thread pending on queue, if any, to return from k_queue_get() call with NULL value (as if timeout expired). If the queue is being waited on by k_poll(), it will return with -EINTR and K_POLL_STATE_CANCELLED state (and per above, subsequent k_queue_get() will return NULL).

Note
Can be called by ISRs.
Return
N/A
Parameters
  • queue: Address of the queue.

void k_queue_append(struct k_queue *queue, void *data)

Append an element to the end of a queue.

This routine appends a data item to queue. A queue data item must be aligned on a 4-byte boundary, and the first 32 bits of the item are reserved for the kernel’s use.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • queue: Address of the queue.
  • data: Address of the data item.

int k_queue_alloc_append(struct k_queue *queue, void *data)

Append an element to a queue.

This routine appends a data item to queue. There is an implicit memory allocation from the calling thread’s resource pool, which is automatically freed when the item is removed from the queue.

Note
Can be called by ISRs.
Parameters
  • queue: Address of the queue.
  • data: Address of the data item.
Return Value
  • 0: on success
  • -ENOMEM: if there isn’t sufficient RAM in the caller’s resource pool

void k_queue_prepend(struct k_queue *queue, void *data)

Prepend an element to a queue.

This routine prepends a data item to queue. A queue data item must be aligned on a 4-byte boundary, and the first 32 bits of the item are reserved for the kernel’s use.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • queue: Address of the queue.
  • data: Address of the data item.

int k_queue_alloc_prepend(struct k_queue *queue, void *data)

Prepend an element to a queue.

This routine prepends a data item to queue. There is an implicit memory allocation from the calling thread’s resource pool, which is automatically freed when the item is removed from the queue.

Note
Can be called by ISRs.
Parameters
  • queue: Address of the queue.
  • data: Address of the data item.
Return Value
  • 0: on success
  • -ENOMEM: if there isn’t sufficient RAM in the caller’s resource pool

void k_queue_insert(struct k_queue *queue, void *prev, void *data)

Inserts an element to a queue.

This routine inserts a data item to queue after previous item. A queue data item must be aligned on a 4-byte boundary, and the first 32 bits of the item are reserved for the kernel’s use.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • queue: Address of the queue.
  • prev: Address of the previous data item.
  • data: Address of the data item.

void k_queue_append_list(struct k_queue *queue, void *head, void *tail)

Atomically append a list of elements to a queue.

This routine adds a list of data items to queue in one operation. The data items must be in a singly-linked list, with the first 32 bits in each data item pointing to the next data item; the list must be NULL-terminated.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • queue: Address of the queue.
  • head: Pointer to first node in singly-linked list.
  • tail: Pointer to last node in singly-linked list.

void k_queue_merge_slist(struct k_queue *queue, sys_slist_t *list)

Atomically add a list of elements to a queue.

This routine adds a list of data items to queue in one operation. The data items must be in a singly-linked list implemented using a sys_slist_t object. Upon completion, the original list is empty.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • queue: Address of the queue.
  • list: Pointer to sys_slist_t object.

void *k_queue_get(struct k_queue *queue, s32_t timeout)

Get an element from a queue.

This routine removes first data item from queue. The first 32 bits of the data item are reserved for the kernel’s use.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Return
Address of the data item if successful; NULL if returned without waiting, or waiting period timed out.
Parameters
  • queue: Address of the queue.
  • timeout: Waiting period to obtain a data item (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.

static bool k_queue_remove(struct k_queue *queue, void *data)

Remove an element from a queue.

This routine removes data item from queue. The first 32 bits of the data item are reserved for the kernel’s use. Removing elements from k_queue rely on sys_slist_find_and_remove which is not a constant time operation.

Note
Can be called by ISRs
Return
true if data item was removed
Parameters
  • queue: Address of the queue.
  • data: Address of the data item.

int k_queue_is_empty(struct k_queue *queue)

Query a queue to see if it has data available.

Note that the data might be already gone by the time this function returns if other threads are also trying to read from the queue.

Note
Can be called by ISRs.
Return
Non-zero if the queue is empty.
Return
0 if data is available.
Parameters
  • queue: Address of the queue.

void *k_queue_peek_head(struct k_queue *queue)

Peek element at the head of queue.

Return element from the head of queue without removing it.

Return
Head element, or NULL if queue is empty.
Parameters
  • queue: Address of the queue.

void *k_queue_peek_tail(struct k_queue *queue)

Peek element at the tail of queue.

Return element from the tail of queue without removing it.

Return
Tail element, or NULL if queue is empty.
Parameters
  • queue: Address of the queue.

Message Queues

Message queues provide a simple message queuing mechanism for fixed-size data items. (See Message Queues.)

group msgq_apis

Defines

K_MSGQ_FLAG_ALLOC
K_MSGQ_DEFINE(q_name, q_msg_size, q_max_msgs, q_align)

Statically define and initialize a message queue.

The message queue’s ring buffer contains space for q_max_msgs messages, each of which is q_msg_size bytes long. The buffer is aligned to a q_align -byte boundary, which must be a power of 2. To ensure that each message is similarly aligned to this boundary, q_msg_size must also be a multiple of q_align.

The message queue can be accessed outside the module where it is defined using:

extern struct k_msgq <name>; 

Parameters
  • q_name: Name of the message queue.
  • q_msg_size: Message size (in bytes).
  • q_max_msgs: Maximum number of messages that can be queued.
  • q_align: Alignment of the message queue’s ring buffer.

Functions

void k_msgq_init(struct k_msgq *q, char *buffer, size_t msg_size, u32_t max_msgs)

Initialize a message queue.

This routine initializes a message queue object, prior to its first use.

The message queue’s ring buffer must contain space for max_msgs messages, each of which is msg_size bytes long. The buffer must be aligned to an N-byte boundary, where N is a power of 2 (i.e. 1, 2, 4, …). To ensure that each message is similarly aligned to this boundary, q_msg_size must also be a multiple of N.

Return
N/A
Parameters
  • q: Address of the message queue.
  • buffer: Pointer to ring buffer that holds queued messages.
  • msg_size: Message size (in bytes).
  • max_msgs: Maximum number of messages that can be queued.

int k_msgq_alloc_init(struct k_msgq *q, size_t msg_size, u32_t max_msgs)

Initialize a message queue.

This routine initializes a message queue object, prior to its first use, allocating its internal ring buffer from the calling thread’s resource pool.

Memory allocated for the ring buffer can be released by calling k_msgq_cleanup(), or if userspace is enabled and the msgq object loses all of its references.

Return
0 on success, -ENOMEM if there was insufficient memory in the thread’s resource pool, or -EINVAL if the size parameters cause an integer overflow.
Parameters
  • q: Address of the message queue.
  • msg_size: Message size (in bytes).
  • max_msgs: Maximum number of messages that can be queued.

void k_msgq_cleanup(struct k_msgq *q)
int k_msgq_put(struct k_msgq *q, void *data, s32_t timeout)

Send a message to a message queue.

This routine sends a message to message queue q.

Note
Can be called by ISRs.
Parameters
  • q: Address of the message queue.
  • data: Pointer to the message.
  • timeout: Waiting period to add the message (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Message sent.
  • -ENOMSG: Returned without waiting or queue purged.
  • -EAGAIN: Waiting period timed out.

int k_msgq_get(struct k_msgq *q, void *data, s32_t timeout)

Receive a message from a message queue.

This routine receives a message from message queue q

in a “first in,

first out” manner.

Note
Can be called by ISRs, but timeout must be set to K_NO_WAIT.
Parameters
  • q: Address of the message queue.
  • data: Address of area to hold the received message.
  • timeout: Waiting period to receive the message (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Message received.
  • -ENOMSG: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_msgq_purge(struct k_msgq *q)

Purge a message queue.

This routine discards all unreceived messages in a message queue’s ring buffer. Any threads that are blocked waiting to send a message to the message queue are unblocked and see an -ENOMSG error code.

Return
N/A
Parameters
  • q: Address of the message queue.

u32_t k_msgq_num_free_get(struct k_msgq *q)

Get the amount of free space in a message queue.

This routine returns the number of unused entries in a message queue’s ring buffer.

Return
Number of unused ring buffer entries.
Parameters
  • q: Address of the message queue.

void k_msgq_get_attrs(struct k_msgq *q, struct k_msgq_attrs *attrs)

Get basic attributes of a message queue.

This routine fetches basic attributes of message queue into attr argument.

Return
N/A
Parameters
  • q: Address of the message queue.
  • attrs: pointer to message queue attribute structure.

u32_t k_msgq_num_used_get(struct k_msgq *q)

Get the number of messages in a message queue.

This routine returns the number of messages in a message queue’s ring buffer.

Return
Number of messages.
Parameters
  • q: Address of the message queue.

struct k_msgq
#include <kernel.h>

Message Queue Structure.

struct k_msgq_attrs
#include <kernel.h>

Message Queue Attributes.

Mailboxes

Mailboxes provide an enhanced message queuing mechanism for variable-size messages. (See Mailboxes.)

group mailbox_apis

Defines

K_MBOX_DEFINE(name)

Statically define and initialize a mailbox.

The mailbox is to be accessed outside the module where it is defined using:

extern struct k_mbox <name>; 

Parameters
  • name: Name of the mailbox.

Functions

void k_mbox_init(struct k_mbox *mbox)

Initialize a mailbox.

This routine initializes a mailbox object, prior to its first use.

Return
N/A
Parameters
  • mbox: Address of the mailbox.

int k_mbox_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg, s32_t timeout)

Send a mailbox message in a synchronous manner.

This routine sends a message to mbox and waits for a receiver to both receive and process it. The message data may be in a buffer, in a memory pool block, or non-existent (i.e. an empty message).

Parameters
  • mbox: Address of the mailbox.
  • tx_msg: Address of the transmit message descriptor.
  • timeout: Waiting period for the message to be received (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER. Once the message has been received, this routine waits as long as necessary for the message to be completely processed.
Return Value
  • 0: Message sent.
  • -ENOMSG: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_mbox_async_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg, struct k_sem *sem)

Send a mailbox message in an asynchronous manner.

This routine sends a message to mbox without waiting for a receiver to process it. The message data may be in a buffer, in a memory pool block, or non-existent (i.e. an empty message). Optionally, the semaphore sem will be given when the message has been both received and completely processed by the receiver.

Return
N/A
Parameters
  • mbox: Address of the mailbox.
  • tx_msg: Address of the transmit message descriptor.
  • sem: Address of a semaphore, or NULL if none is needed.

int k_mbox_get(struct k_mbox *mbox, struct k_mbox_msg *rx_msg, void *buffer, s32_t timeout)

Receive a mailbox message.

This routine receives a message from mbox, then optionally retrieves its data and disposes of the message.

Parameters
  • mbox: Address of the mailbox.
  • rx_msg: Address of the receive message descriptor.
  • buffer: Address of the buffer to receive data, or NULL to defer data retrieval and message disposal until later.
  • timeout: Waiting period for a message to be received (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Message received.
  • -ENOMSG: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

void k_mbox_data_get(struct k_mbox_msg *rx_msg, void *buffer)

Retrieve mailbox message data into a buffer.

This routine completes the processing of a received message by retrieving its data into a buffer, then disposing of the message.

Alternatively, this routine can be used to dispose of a received message without retrieving its data.

Return
N/A
Parameters
  • rx_msg: Address of the receive message descriptor.
  • buffer: Address of the buffer to receive data, or NULL to discard the data.

int k_mbox_data_block_get(struct k_mbox_msg *rx_msg, struct k_mem_pool *pool, struct k_mem_block *block, s32_t timeout)

Retrieve mailbox message data into a memory pool block.

This routine completes the processing of a received message by retrieving its data into a memory pool block, then disposing of the message. The memory pool block that results from successful retrieval must be returned to the pool once the data has been processed, even in cases where zero bytes of data are retrieved.

Alternatively, this routine can be used to dispose of a received message without retrieving its data. In this case there is no need to return a memory pool block to the pool.

This routine allocates a new memory pool block for the data only if the data is not already in one. If a new block cannot be allocated, the routine returns a failure code and the received message is left unchanged. This permits the caller to reattempt data retrieval at a later time or to dispose of the received message without retrieving its data.

Parameters
  • rx_msg: Address of a receive message descriptor.
  • pool: Address of memory pool, or NULL to discard data.
  • block: Address of the area to hold memory pool block info.
  • timeout: Waiting period to wait for a memory pool block (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: Data retrieved.
  • -ENOMEM: Returned without waiting.
  • -EAGAIN: Waiting period timed out.

Pipes

Pipes provide a traditional anonymous pipe mechanism for sending variable-size chunks of data, in whole or in part. (See Pipes.)

group pipe_apis

Defines

K_PIPE_DEFINE(name, pipe_buffer_size, pipe_align)

Statically define and initialize a pipe.

The pipe can be accessed outside the module where it is defined using:

extern struct k_pipe <name>; 

Parameters
  • name: Name of the pipe.
  • pipe_buffer_size: Size of the pipe’s ring buffer (in bytes), or zero if no ring buffer is used.
  • pipe_align: Alignment of the pipe’s ring buffer (power of 2).

Functions

void k_pipe_init(struct k_pipe *pipe, unsigned char *buffer, size_t size)

Initialize a pipe.

This routine initializes a pipe object, prior to its first use.

Return
N/A
Parameters
  • pipe: Address of the pipe.
  • buffer: Address of the pipe’s ring buffer, or NULL if no ring buffer is used.
  • size: Size of the pipe’s ring buffer (in bytes), or zero if no ring buffer is used.

void k_pipe_cleanup(struct k_pipe *pipe)

Release a pipe’s allocated buffer.

If a pipe object was given a dynamically allocated buffer via k_pipe_alloc_init(), this will free it. This function does nothing if the buffer wasn’t dynamically allocated.

Parameters
  • pipe: Address of the pipe.

int k_pipe_alloc_init(struct k_pipe *pipe, size_t size)

Initialize a pipe and allocate a buffer for it.

Storage for the buffer region will be allocated from the calling thread’s resource pool. This memory will be released if k_pipe_cleanup() is called, or userspace is enabled and the pipe object loses all references to it.

This function should only be called on uninitialized pipe objects.

Parameters
  • pipe: Address of the pipe.
  • size: Size of the pipe’s ring buffer (in bytes), or zero if no ring buffer is used.
Return Value
  • 0: on success
  • -ENOMEM: if memory couldn’t be allocated

int k_pipe_put(struct k_pipe *pipe, void *data, size_t bytes_to_write, size_t *bytes_written, size_t min_xfer, s32_t timeout)

Write data to a pipe.

This routine writes up to bytes_to_write bytes of data to pipe.

Parameters
  • pipe: Address of the pipe.
  • data: Address of data to write.
  • bytes_to_write: Size of data (in bytes).
  • bytes_written: Address of area to hold the number of bytes written.
  • min_xfer: Minimum number of bytes to write.
  • timeout: Waiting period to wait for the data to be written (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: At least min_xfer bytes of data were written.
  • -EIO: Returned without waiting; zero data bytes were written.
  • -EAGAIN: Waiting period timed out; between zero and min_xfer minus one data bytes were written.

int k_pipe_get(struct k_pipe *pipe, void *data, size_t bytes_to_read, size_t *bytes_read, size_t min_xfer, s32_t timeout)

Read data from a pipe.

This routine reads up to bytes_to_read bytes of data from pipe.

Parameters
  • pipe: Address of the pipe.
  • data: Address to place the data read from pipe.
  • bytes_to_read: Maximum number of data bytes to read.
  • bytes_read: Address of area to hold the number of bytes read.
  • min_xfer: Minimum number of data bytes to read.
  • timeout: Waiting period to wait for the data to be read (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: At least min_xfer bytes of data were read.
  • -EIO: Returned without waiting; zero data bytes were read.
  • -EAGAIN: Waiting period timed out; between zero and min_xfer minus one data bytes were read.

void k_pipe_block_put(struct k_pipe *pipe, struct k_mem_block *block, size_t size, struct k_sem *sem)

Write memory block to a pipe.

This routine writes the data contained in a memory block to pipe. Once all of the data in the block has been written to the pipe, it will free the memory block block and give the semaphore sem (if specified).

Return
N/A
Parameters
  • pipe: Address of the pipe.
  • block: Memory block containing data to send
  • size: Number of data bytes in memory block to send
  • sem: Semaphore to signal upon completion (else NULL)

struct k_pipe
#include <kernel.h>

Pipe Structure

Asynchronous Polling

group poll_apis

Defines

K_POLL_TYPE_IGNORE
K_POLL_TYPE_SIGNAL
K_POLL_TYPE_SEM_AVAILABLE
K_POLL_TYPE_DATA_AVAILABLE
K_POLL_TYPE_FIFO_DATA_AVAILABLE
K_POLL_STATE_NOT_READY
K_POLL_STATE_SIGNALED
K_POLL_STATE_SEM_AVAILABLE
K_POLL_STATE_DATA_AVAILABLE
K_POLL_STATE_FIFO_DATA_AVAILABLE
K_POLL_STATE_CANCELLED
K_POLL_SIGNAL_INITIALIZER(obj)
K_POLL_EVENT_INITIALIZER(event_type, event_mode, event_obj)
K_POLL_EVENT_STATIC_INITIALIZER(event_type, event_mode, event_obj, event_tag)

Enums

enum k_poll_modes

Values:

K_POLL_MODE_NOTIFY_ONLY = 0
K_POLL_NUM_MODES

Functions

void k_poll_event_init(struct k_poll_event *event, u32_t type, int mode, void *obj)

Initialize one struct k_poll_event instance.

After this routine is called on a poll event, the event it ready to be placed in an event array to be passed to k_poll().

Return
N/A
Parameters
  • event: The event to initialize.
  • type: A bitfield of the types of event, from the K_POLL_TYPE_xxx values. Only values that apply to the same object being polled can be used together. Choosing K_POLL_TYPE_IGNORE disables the event.
  • mode: Future. Use K_POLL_MODE_NOTIFY_ONLY.
  • obj: Kernel object or poll signal.

int k_poll(struct k_poll_event *events, int num_events, s32_t timeout)

Wait for one or many of multiple poll events to occur.

This routine allows a thread to wait concurrently for one or many of multiple poll events to have occurred. Such events can be a kernel object being available, like a semaphore, or a poll signal event.

When an event notifies that a kernel object is available, the kernel object is not “given” to the thread calling k_poll(): it merely signals the fact that the object was available when the k_poll() call was in effect. Also, all threads trying to acquire an object the regular way, i.e. by pending on the object, have precedence over the thread polling on the object. This means that the polling thread will never get the poll event on an object until the object becomes available and its pend queue is empty. For this reason, the k_poll() call is more effective when the objects being polled only have one thread, the polling thread, trying to acquire them.

When k_poll() returns 0, the caller should loop on all the events that were passed to k_poll() and check the state field for the values that were expected and take the associated actions.

Before being reused for another call to k_poll(), the user has to reset the state field to K_POLL_STATE_NOT_READY.

When called from user mode, a temporary memory allocation is required from the caller’s resource pool.

Parameters
  • events: An array of pointers to events to be polled for.
  • num_events: The number of events in the array.
  • timeout: Waiting period for an event to be ready (in milliseconds), or one of the special values K_NO_WAIT and K_FOREVER.
Return Value
  • 0: One or more events are ready.
  • -EAGAIN: Waiting period timed out.
  • -EINTR: Polling has been interrupted, e.g. with k_queue_cancel_wait(). All output events are still set and valid, cancelled event(s) will be set to K_POLL_STATE_CANCELLED. In other words, -EINTR status means that at least one of output events is K_POLL_STATE_CANCELLED.
  • -ENOMEM: Thread resource pool insufficient memory (user mode only)
  • -EINVAL: Bad parameters (user mode only)

void k_poll_signal_init(struct k_poll_signal *signal)

Initialize a poll signal object.

Ready a poll signal object to be signaled via k_poll_signal().

Return
N/A
Parameters
  • signal: A poll signal.

void k_poll_signal_reset(struct k_poll_signal *signal)
void k_poll_signal_check(struct k_poll_signal *signal, unsigned int *signaled, int *result)

Fetch the signaled state and result value of a poll signal.

Parameters
  • signal: A poll signal object
  • signaled: An integer buffer which will be written nonzero if the object was signaled
  • result: An integer destination buffer which will be written with the result value if the object was signaled, or an undefined value if it was not.

int k_poll_signal(struct k_poll_signal *signal, int result)

Signal a poll signal object.

This routine makes ready a poll signal, which is basically a poll event of type K_POLL_TYPE_SIGNAL. If a thread was polling on that event, it will be made ready to run. A result value can be specified.

The poll signal contains a ‘signaled’ field that, when set by k_poll_signal(), stays set until the user sets it back to 0 with k_poll_signal_reset(). It thus has to be reset by the user before being passed again to k_poll() or k_poll() will consider it being signaled, and will return immediately.

Parameters
  • signal: A poll signal.
  • result: The value to store in the result field of the signal.
Return Value
  • 0: The signal was delivered successfully.
  • -EAGAIN: The polling thread’s timeout is in the process of expiring.

Interrupt Service Routines (ISRs)

An interrupt service routine is a series of instructions that is executed asynchronously in response to a hardware or software interrupt. (See Interrupts.)

group isr_apis

Defines

IRQ_CONNECT(irq_p, priority_p, isr_p, isr_param_p, flags_p)

Initialize an interrupt handler.

This routine initializes an interrupt handler for an IRQ. The IRQ must be subsequently enabled before the interrupt handler begins servicing interrupts.

Warning
Although this routine is invoked at run-time, all of its arguments must be computable by the compiler at build time.
Return
Interrupt vector assigned to this interrupt.
Parameters
  • irq_p: IRQ line number.
  • priority_p: Interrupt priority.
  • isr_p: Address of interrupt service routine.
  • isr_param_p: Parameter passed to interrupt service routine.
  • flags_p: Architecture-specific IRQ configuration flags..

IRQ_DIRECT_CONNECT(irq_p, priority_p, isr_p, flags_p)

Initialize a ‘direct’ interrupt handler.

This routine initializes an interrupt handler for an IRQ. The IRQ must be subsequently enabled via irq_enable() before the interrupt handler begins servicing interrupts.

These ISRs are designed for performance-critical interrupt handling and do not go through common interrupt handling code. They must be implemented in such a way that it is safe to put them directly in the vector table. For ISRs written in C, The ISR_DIRECT_DECLARE() macro will do this automatically. For ISRs written in assembly it is entirely up to the developer to ensure that the right steps are taken.

This type of interrupt currently has a few limitations compared to normal Zephyr interrupts:

  • No parameters are passed to the ISR.
  • No stack switch is done, the ISR will run on the interrupted context’s stack, unless the architecture automatically does the stack switch in HW.
  • Interrupt locking state is unchanged from how the HW sets it when the ISR runs. On arches that enter ISRs with interrupts locked, they will remain locked.
  • Scheduling decisions are now optional, controlled by the return value of ISRs implemented with the ISR_DIRECT_DECLARE() macro
  • The call into the OS to exit power management idle state is now optional. Normal interrupts always do this before the ISR is run, but when it runs is now controlled by the placement of a ISR_DIRECT_PM() macro, or omitted entirely.

Warning
Although this routine is invoked at run-time, all of its arguments must be computable by the compiler at build time.
Return
Interrupt vector assigned to this interrupt.
Parameters
  • irq_p: IRQ line number.
  • priority_p: Interrupt priority.
  • isr_p: Address of interrupt service routine.
  • flags_p: Architecture-specific IRQ configuration flags.

ISR_DIRECT_HEADER

Common tasks before executing the body of an ISR.

This macro must be at the beginning of all direct interrupts and performs minimal architecture-specific tasks before the ISR itself can run. It takes no arguments and has no return value.

Common tasks before exiting the body of an ISR.

This macro must be at the end of all direct interrupts and performs minimal architecture-specific tasks like EOI. It has no return value.

In a normal interrupt, a check is done at end of interrupt to invoke _Swap() logic if the current thread is preemptible and there is another thread ready to run in the kernel’s ready queue cache. This is now optional and controlled by the check_reschedule argument. If unsure, set to nonzero. On systems that do stack switching and nested interrupt tracking in software, _Swap() should only be called if this was a non-nested interrupt.

Parameters
  • check_reschedule: If nonzero, additionally invoke scheduling logic

ISR_DIRECT_PM

Perform power management idle exit logic.

This macro may optionally be invoked somewhere in between IRQ_DIRECT_HEADER() and IRQ_DIRECT_FOOTER() invocations. It performs tasks necessary to exit power management idle state. It takes no parameters and returns no arguments. It may be omitted, but be careful!

ISR_DIRECT_DECLARE(name)

Helper macro to declare a direct interrupt service routine.

This will declare the function in a proper way and automatically include the ISR_DIRECT_FOOTER() and ISR_DIRECT_HEADER() macros. The function should return nonzero status if a scheduling decision should potentially be made. See ISR_DIRECT_FOOTER() for more details on the scheduling decision.

For architectures that support ‘regular’ and ‘fast’ interrupt types, where these interrupt types require different assembly language handling of registers by the ISR, this will always generate code for the ‘fast’ interrupt type.

Example usage:

ISR_DIRECT_DECLARE(my_isr) { bool done = do_stuff(); ISR_DIRECT_PM(); < done after do_stuff() due to latency concerns if (!done) { return 0; < Don’t bother checking if we have to _Swap() } k_sem_give(some_sem); return 1; }

Parameters
  • name: symbol name of the ISR

irq_lock

Lock interrupts.

This routine disables all interrupts on the CPU. It returns an unsigned integer “lock-out key”, which is an architecture-dependent indicator of whether interrupts were locked prior to the call. The lock-out key must be passed to irq_unlock() to re-enable interrupts.

This routine can be called recursively, as long as the caller keeps track of each lock-out key that is generated. Interrupts are re-enabled by passing each of the keys to irq_unlock() in the reverse order they were acquired. (That is, each call to irq_lock() must be balanced by a corresponding call to irq_unlock().)

Note
This routine can be called by ISRs or by threads. If it is called by a thread, the interrupt lock is thread-specific; this means that interrupts remain disabled only while the thread is running. If the thread performs an operation that allows another thread to run (for example, giving a semaphore or sleeping for N milliseconds), the interrupt lock no longer applies and interrupts may be re-enabled while other processing occurs. When the thread once again becomes the current thread, the kernel re-establishes its interrupt lock; this ensures the thread won’t be interrupted until it has explicitly released the interrupt lock it established.
Warning
The lock-out key should never be used to manually re-enable interrupts or to inspect or manipulate the contents of the CPU’s interrupt bits.
Return
Lock-out key.

irq_unlock(key)

Unlock interrupts.

This routine reverses the effect of a previous call to irq_lock() using the associated lock-out key. The caller must call the routine once for each time it called irq_lock(), supplying the keys in the reverse order they were acquired, before interrupts are enabled.

Note
Can be called by ISRs.
Return
N/A
Parameters
  • key: Lock-out key generated by irq_lock().

irq_enable(irq)

Enable an IRQ.

This routine enables interrupts from source irq.

Return
N/A
Parameters
  • irq: IRQ line.

irq_disable(irq)

Disable an IRQ.

This routine disables interrupts from source irq.

Return
N/A
Parameters
  • irq: IRQ line.

irq_is_enabled(irq)

Get IRQ enable state.

This routine indicates if interrupts from source irq are enabled.

Return
interrupt enable state, true or false
Parameters
  • irq: IRQ line.

Functions

int k_is_in_isr(void)

Determine if code is running at interrupt level.

This routine allows the caller to customize its actions, depending on whether it is a thread or an ISR.

Note
Can be called by ISRs.
Return
0 if invoked by a thread.
Return
Non-zero if invoked by an ISR.

int k_is_preempt_thread(void)

Determine if code is running in a preemptible thread.

This routine allows the caller to customize its actions, depending on whether it can be preempted by another thread. The routine returns a ‘true’ value if all of the following conditions are met:

  • The code is running in a thread, not at ISR.
  • The thread’s priority is in the preemptible range.
  • The thread has not locked the scheduler.

Note
Can be called by ISRs.
Return
0 if invoked by an ISR or by a cooperative thread.
Return
Non-zero if invoked by a preemptible thread.

Atomic Services

The atomic services enable multiple threads and ISRs to read and modify 32-bit variables in an uninterruptible manner. (See Atomic Services.)

Important

All atomic services APIs can be used by both threads and ISRs.

group atomic_apis

Defines

ATOMIC_INIT(i)

Initialize an atomic variable.

This macro can be used to initialize an atomic variable. For example,

atomic_t my_var = ATOMIC_INIT(75); 

Parameters
  • i: Value to assign to atomic variable.

ATOMIC_DEFINE(name, num_bits)

Define an array of atomic variables.

This macro defines an array of atomic variables containing at least num_bits bits.

Note
If used from file scope, the bits of the array are initialized to zero; if used from within a function, the bits are left uninitialized.
Parameters
  • name: Name of array of atomic variables.
  • num_bits: Number of bits needed.

Functions

int atomic_cas(atomic_t *target, atomic_val_t old_value, atomic_val_t new_value)

Atomic compare-and-set.

This routine performs an atomic compare-and-set on target. If the current value of target equals old_value, target is set to new_value. If the current value of target does not equal old_value, target is left unchanged.

Return
1 if new_value is written, 0 otherwise.
Parameters
  • target: Address of atomic variable.
  • old_value: Original value to compare against.
  • new_value: New value to store.

atomic_val_t atomic_add(atomic_t *target, atomic_val_t value)

Atomic addition.

This routine performs an atomic addition on target.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to add.

atomic_val_t atomic_sub(atomic_t *target, atomic_val_t value)

Atomic subtraction.

This routine performs an atomic subtraction on target.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to subtract.

atomic_val_t atomic_inc(atomic_t *target)

Atomic increment.

This routine performs an atomic increment by 1 on target.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.

atomic_val_t atomic_dec(atomic_t *target)

Atomic decrement.

This routine performs an atomic decrement by 1 on target.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.

atomic_val_t atomic_get(const atomic_t *target)

Atomic get.

This routine performs an atomic read on target.

Return
Value of target.
Parameters
  • target: Address of atomic variable.

atomic_val_t atomic_set(atomic_t *target, atomic_val_t value)

Atomic get-and-set.

This routine atomically sets target to value and returns the previous value of target.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to write to target.

atomic_val_t atomic_clear(atomic_t *target)

Atomic clear.

This routine atomically sets target to zero and returns its previous value. (Hence, it is equivalent to atomic_set(target, 0).)

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.

atomic_val_t atomic_or(atomic_t *target, atomic_val_t value)

Atomic bitwise inclusive OR.

This routine atomically sets target to the bitwise inclusive OR of target and value.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to OR.

atomic_val_t atomic_xor(atomic_t *target, atomic_val_t value)

Atomic bitwise exclusive OR (XOR).

This routine atomically sets target to the bitwise exclusive OR (XOR) of target and value.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to XOR

atomic_val_t atomic_and(atomic_t *target, atomic_val_t value)

Atomic bitwise AND.

This routine atomically sets target to the bitwise AND of target and value.

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to AND.

atomic_val_t atomic_nand(atomic_t *target, atomic_val_t value)

Atomic bitwise NAND.

This routine atomically sets target to the bitwise NAND of target and value. (This operation is equivalent to target = ~(target & value).)

Return
Previous value of target.
Parameters
  • target: Address of atomic variable.
  • value: Value to NAND.

static int atomic_test_bit(const atomic_t *target, int bit)

Atomically test a bit.

This routine tests whether bit number bit of target is set or not. The target may be a single atomic variable or an array of them.

Return
1 if the bit was set, 0 if it wasn’t.
Parameters
  • target: Address of atomic variable or array.
  • bit: Bit number (starting from 0).

static int atomic_test_and_clear_bit(atomic_t *target, int bit)

Atomically test and clear a bit.

Atomically clear bit number bit of target and return its old value. The target may be a single atomic variable or an array of them.

Return
1 if the bit was set, 0 if it wasn’t.
Parameters
  • target: Address of atomic variable or array.
  • bit: Bit number (starting from 0).

static int atomic_test_and_set_bit(atomic_t *target, int bit)

Atomically set a bit.

Atomically set bit number bit of target and return its old value. The target may be a single atomic variable or an array of them.

Return
1 if the bit was set, 0 if it wasn’t.
Parameters
  • target: Address of atomic variable or array.
  • bit: Bit number (starting from 0).

static void atomic_clear_bit(atomic_t *target, int bit)

Atomically clear a bit.

Atomically clear bit number bit of target. The target may be a single atomic variable or an array of them.

Return
N/A
Parameters
  • target: Address of atomic variable or array.
  • bit: Bit number (starting from 0).

static void atomic_set_bit(atomic_t *target, int bit)

Atomically set a bit.

Atomically set bit number bit of target. The target may be a single atomic variable or an array of them.

Return
N/A
Parameters
  • target: Address of atomic variable or array.
  • bit: Bit number (starting from 0).

Profiling

group profiling_apis

Typedefs

typedef void (*k_thread_user_cb_t)(const struct k_thread *thread, void *user_data)

Functions

void k_thread_foreach(k_thread_user_cb_t user_cb, void *user_data)

Iterate over all the threads in the system.

This routine iterates over all the threads in the system and calls the user_cb function for each thread.

Note
CONFIG_THREAD_MONITOR must be set for this function to be effective. Also this API uses irq_lock to protect the _kernel.threads list which means creation of new threads and terminations of existing threads are blocked until this API returns.
Return
N/A
Parameters
  • user_cb: Pointer to the user callback function.
  • user_data: Pointer to user data.

Floating Point Services

The floating point services enable threads to use a board’s floating point registers. (See Floating Point Services.)

group float_apis

Typedefs

typedef struct k_thread *k_tid_t

Functions

void k_float_enable(k_tid_t thread, unsigned int options)

Enable preservation of floating point context information.

This routine informs the kernel that the specified thread (which may be the current thread) will be using the floating point registers. The options parameter indicates which floating point register sets will be used by the specified thread:

a) K_FP_REGS indicates x87 FPU and MMX registers only b) K_SSE_REGS indicates SSE registers (and also x87 FPU and MMX registers)

Invoking this routine initializes the thread’s floating point context info to that of an FPU that has been reset. The next time the thread is scheduled by _Swap() it will either inherit an FPU that is guaranteed to be in a “sane” state (if the most recent user of the FPU was cooperatively swapped out) or the thread’s own floating point context will be loaded (if the most recent user of the FPU was preempted, or if this thread is the first user of the FPU). Thereafter, the kernel will protect the thread’s FP context so that it is not altered during a preemptive context switch.

Warning
This routine should only be used to enable floating point support for a thread that does not currently have such support enabled already.
Return
N/A
Parameters
  • thread: ID of thread.
  • options: Registers to be preserved (K_FP_REGS or K_SSE_REGS).

void k_float_disable(k_tid_t thread)

Disable preservation of floating point context information.

This routine informs the kernel that the specified thread (which may be the current thread) will no longer be using the floating point registers.

Warning
This routine should only be used to disable floating point support for a thread that currently has such support enabled.
Return
N/A
Parameters
  • thread: ID of thread.

Ring Buffers

Ring buffers enable simple first in, first out (FIFO) queuing of variable-size data items. (See Ring Buffers.)

static void sys_ring_buf_init(struct ring_buf *buf, u32_t size, u32_t *data)

Initialize a ring buffer.

This routine initializes a ring buffer, prior to its first use. It is only used for ring buffers not defined using SYS_RING_BUF_DECLARE_POW2 or SYS_RING_BUF_DECLARE_SIZE.

Setting size to a power of 2 establishes a high performance ring buffer that doesn’t require the use of modulo arithmetic operations to maintain itself.

Parameters
  • buf: Address of ring buffer.
  • size: Ring buffer size (in 32-bit words).
  • data: Ring buffer data area (typically u32_t data[size]).

static int sys_ring_buf_is_empty(struct ring_buf *buf)

Determine if a ring buffer is empty.

Return
1 if the ring buffer is empty, or 0 if not.
Parameters
  • buf: Address of ring buffer.

static int sys_ring_buf_space_get(struct ring_buf *buf)

Determine free space in a ring buffer.

Return
Ring buffer free space (in 32-bit words).
Parameters
  • buf: Address of ring buffer.

int sys_ring_buf_put(struct ring_buf *buf, u16_t type, u8_t value, u32_t *data, u8_t size32)

Write a data item to a ring buffer.

This routine writes a data item to ring buffer buf. The data item is an array of 32-bit words (from zero to 1020 bytes in length), coupled with a 16-bit type identifier and an 8-bit integer value.

Warning
Use cases involving multiple writers to the ring buffer must prevent concurrent write operations, either by preventing all writers from being preempted or by using a mutex to govern writes to the ring buffer.
Parameters
  • buf: Address of ring buffer.
  • type: Data item’s type identifier (application specific).
  • value: Data item’s integer value (application specific).
  • data: Address of data item.
  • size32: Data item size (number of 32-bit words).
Return Value
  • 0: Data item was written.
  • -EMSGSIZE: Ring buffer has insufficient free space.

int sys_ring_buf_get(struct ring_buf *buf, u16_t *type, u8_t *value, u32_t *data, u8_t *size32)

Read a data item from a ring buffer.

This routine reads a data item from ring buffer buf. The data item is an array of 32-bit words (up to 1020 bytes in length), coupled with a 16-bit type identifier and an 8-bit integer value.

Warning
Use cases involving multiple reads of the ring buffer must prevent concurrent read operations, either by preventing all readers from being preempted or by using a mutex to govern reads to the ring buffer.
Parameters
  • buf: Address of ring buffer.
  • type: Area to store the data item’s type identifier.
  • value: Area to store the data item’s integer value.
  • data: Area to store the data item.
  • size32: Size of the data item storage area (number of 32-bit chunks).
Return Value
  • 0: Data item was fetched; size32 now contains the number of 32-bit words read into data area data.
  • -EAGAIN: Ring buffer is empty.
  • -EMSGSIZE: Data area data is too small; size32 now contains the number of 32-bit words needed.

SYS_RING_BUF_DECLARE_POW2(name, pow)

Statically define and initialize a high performance ring buffer.

This macro establishes a ring buffer whose size must be a power of 2; that is, the ring buffer contains 2^pow 32-bit words, where pow is the specified ring buffer size exponent. A high performance ring buffer doesn’t require the use of modulo arithmetic operations to maintain itself.

The ring buffer can be accessed outside the module where it is defined using:

extern struct ring_buf <name>; 

Parameters
  • name: Name of the ring buffer.
  • pow: Ring buffer size exponent.

SYS_RING_BUF_DECLARE_SIZE(name, size32)

Statically define and initialize a standard ring buffer.

This macro establishes a ring buffer of an arbitrary size. A standard ring buffer uses modulo arithmetic operations to maintain itself.

The ring buffer can be accessed outside the module where it is defined using:

extern struct ring_buf <name>; 

Parameters
  • name: Name of the ring buffer.
  • size32: Size of ring buffer (in 32-bit words).

Memory Domain

A memory domain contains some number of memory partitions. Threads can specify the range and attribute (access permission) for memory partitions in a memory domain. Threads in the same memory domain have the same access permissions to the memory partitions belong to the memory domain. (See Memory Domain.)

group mem_domain_apis

Defines

MEM_PARTITION_ENTRY(_start, _size, _attr)

Used to declare a memory partition entry.

K_MEM_PARTITION_DEFINE(name, start, size, attr)

Used to declare a memory partition.

Functions

void k_mem_domain_init(struct k_mem_domain *domain, u8_t num_parts, struct k_mem_partition *parts[])

Initialize a memory domain.

Initialize a memory domain with given name and memory partitions.

Parameters
  • domain: The memory domain to be initialized.
  • num_parts: The number of array items of “parts” parameter.
  • parts: An array of pointers to the memory partitions. Can be NULL if num_parts is zero.

void k_mem_domain_destroy(struct k_mem_domain *domain)

Destroy a memory domain.

Destroy a memory domain.

Parameters
  • domain: The memory domain to be destroyed.

void k_mem_domain_add_partition(struct k_mem_domain *domain, struct k_mem_partition *part)

Add a memory partition into a memory domain.

Add a memory partition into a memory domain.

Parameters
  • domain: The memory domain to be added a memory partition.
  • part: The memory partition to be added

void k_mem_domain_remove_partition(struct k_mem_domain *domain, struct k_mem_partition *part)

Remove a memory partition from a memory domain.

Remove a memory partition from a memory domain.

Parameters
  • domain: The memory domain to be removed a memory partition.
  • part: The memory partition to be removed

void k_mem_domain_add_thread(struct k_mem_domain *domain, k_tid_t thread)

Add a thread into a memory domain.

Add a thread into a memory domain.

Parameters
  • domain: The memory domain that the thread is going to be added into.
  • thread: ID of thread going to be added into the memory domain.

void k_mem_domain_remove_thread(k_tid_t thread)

Remove a thread from its memory domain.

Remove a thread from its memory domain.

Parameters
  • thread: ID of thread going to be removed from its memory domain.