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.)
-
typedef
k_thread_entry_t
¶ Thread entry point function type.
A thread’s entry point function is invoked when the thread starts executing. Up to 3 argument values can be passed to the function.
The thread terminates execution permanently if the entry point function returns. The thread is responsible for releasing any shared resources it may own (such as mutexes and dynamically allocated memory), prior to returning.
- Return
- N/A
- Parameters
p1
: First argument.p2
: Second argument.p3
: Third argument.
-
typedef struct _k_thread_stack_element *
k_thread_stack_t
¶
-
k_tid_t
k_thread_spawn
(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)¶ Spawn 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.
Kernel data structures for bookkeeping and context storage for this thread will be placed at the beginning of the thread’s stack memory region and may become corrupted if too much of the stack is used. This function has been deprecated in favor of k_thread_create() to give the user more control on where these data structures reside.
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 stack itself should be declared with K_THREAD_STACK_DEFINE or variant macros. The stack size parameter should either be a defined constant also passed to K_THREAD_STACK_DEFINE, or the value of K_THREAD_STACK_SIZEOF. Do not use regular C sizeof().
- Return
- ID of new thread.
- Parameters
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).
-
k_tid_t
k_thread_create
(struct k_thread *new_thread, k_thread_stack_t stack, size_t stack_size, void (*entry)(void *, void *, void *), 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_threadstack
: 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).
-
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.
-
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.
-
K_ESSENTIAL
¶
-
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).
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.)
-
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.
-
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. 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
- 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 schedules, it returns zero.
- Return
- Remaining time (in milliseconds).
- Parameters
work
: Delayed work item.
-
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 objectwork_handler
: Function to invoke each time work item is processed.
Clocks¶
Kernel clocks enable threads and ISRs to measure the passage of time with either normal and high precision. (See Kernel Clocks.)
-
s64_t
k_uptime_get
(void)¶ Get system uptime.
This routine returns the elapsed time since the system booted, in milliseconds.
- Return
- Current uptime.
-
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.
-
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_enable_sys_clock_always_on
¶
-
k_disable_sys_clock_always_on
¶
-
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.
Timers¶
Timers enable threads to measure the passage of time, and to optionally execute an action when the timer expires. (See Timers.)
-
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.
-
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.
-
static 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.
-
static 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.
-
static 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.
-
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.
Memory Slabs¶
Memory slabs enable the dynamic allocation and release of fixed-size memory blocks. (See Memory Slabs.)
-
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.
-
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).
Memory Pools¶
Memory pools enable the dynamic allocation and release of variable-size memory blocks. (See Memory Pools.)
-
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_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.
-
static void
k_mem_pool_defrag
(struct k_mem_pool *pool)¶ Defragment a memory pool.
This is a no-op API preserved for backward compatibility only.
- Return
- N/A
- Parameters
pool
: Unused
-
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).
Heap Memory Pool¶
The heap memory pools enable the dynamic allocation and release of memory
in a malloc()
-like manner.
(See Heap Memory Pool.)
-
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.
If ptr is NULL, no operation is performed.
- Return
- N/A
- Parameters
ptr
: Pointer to previously allocated memory.
Semaphores¶
Semaphores provide traditional counting semaphore capabilities. (See Semaphores.)
-
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.
-
static 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.
-
static 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.
-
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.
Mutexes¶
Mutexes provide traditional reentrant mutex capabilities with basic priority inheritance. (See Mutexes.)
-
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.
-
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.
Alerts¶
Alerts enable an application to perform asynchronous signaling, somewhat akin to Unix-style signals. (See Alerts.)
-
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.
-
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.
-
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.
Fifos¶
Fifos provide traditional first in, first out (FIFO) queuing of data items of any size. (See Fifos.)
-
k_fifo_init
(fifo)¶ Initialize a fifo.
This routine initializes a fifo object, prior to its first use.
- Return
- N/A
- Parameters
fifo
: Address of the fifo.
-
k_fifo_cancel_wait
(fifo)¶ Cancel waiting on a fifo.
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.
-
k_fifo_put
(fifo, data)¶ Add an element to a fifo.
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_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.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.
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.list
: Pointer to sys_slist_t object.
-
k_fifo_get
(fifo, timeout)¶ Get an element from a fifo.
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.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 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 is empty.
- Return
- 0 if data is available.
- Parameters
fifo
: Address of the fifo.
-
k_fifo_peek_head
(fifo)¶ Peek element at the head of fifo.
Return element from the head of fifo without removing it. A usecase for this is if elements of the fifo 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.
- Return
- Head element, or NULL if the fifo is empty.
- Parameters
fifo
: Address of the fifo.
-
k_fifo_peek_tail
(fifo)¶ Peek element at the tail of fifo.
Return element from the tail of fifo (without removing it). A usecase for this is if elements of the fifo are themselves containers. Then it may be useful to add more data to the last container in fifo.
- Return
- Tail element, or NULL if fifo is empty.
- Parameters
fifo
: Address of the fifo.
-
K_FIFO_DEFINE
(name)¶ Statically define and initialize a fifo.
The fifo can be accessed outside the module where it is defined using:
extern struct k_fifo <name>;
- Parameters
name
: Name of the fifo.
Lifos¶
Lifos provide traditional last in, first out (LIFO) queuing of data items of any size. (See Lifos.)
-
k_lifo_init
(lifo)¶ Initialize a lifo.
This routine initializes a lifo object, prior to its first use.
- Return
- N/A
- Parameters
lifo
: Address of the lifo.
-
k_lifo_put
(lifo, data)¶ Add an element to a lifo.
This routine adds a data item to lifo. A lifo 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.data
: Address of the data item.
-
k_lifo_get
(lifo, timeout)¶ Get an element from a lifo.
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.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.
The lifo 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.)
-
void
k_stack_init
(struct k_stack *stack, u32_t *buffer, 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.
-
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.
-
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.
Message Queues¶
Message queues provide a simple message queuing mechanism for fixed-size data items. (See Message Queues.)
-
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_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.
-
static 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.
-
static 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.
-
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.
Mailboxes¶
Mailboxes provide an enhanced message queuing mechanism for variable-size messages. (See Mailboxes.)
-
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.
-
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.
Pipes¶
Pipes provide a traditional anonymous pipe mechanism for sending variable-size chunks of data, in whole or in part. (See Pipes.)
-
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.
-
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 sendsize
: Number of data bytes in memory block to sendsem
: Semaphore to signal upon completion (else NULL)
-
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).
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.)
-
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.
-
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.
-
ISR_DIRECT_FOOTER
(check_reschedule)¶ 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.
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.
-
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).
-
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.
Floating Point Services¶
The floating point services enable threads to use a board’s floating point registers. (See Floating Point Services.)
-
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).