Line data Source code
1 1 : /*
2 : * Copyright (c) 2016, Wind River Systems, Inc.
3 : *
4 : * SPDX-License-Identifier: Apache-2.0
5 : */
6 :
7 : /**
8 : * @file
9 : *
10 : * @brief Public kernel APIs.
11 : */
12 :
13 : #ifndef ZEPHYR_INCLUDE_KERNEL_H_
14 : #define ZEPHYR_INCLUDE_KERNEL_H_
15 :
16 : #if !defined(_ASMLANGUAGE)
17 : #include <zephyr/kernel_includes.h>
18 : #include <errno.h>
19 : #include <limits.h>
20 : #include <stdbool.h>
21 : #include <zephyr/toolchain.h>
22 : #include <zephyr/tracing/tracing_macros.h>
23 : #include <zephyr/sys/mem_stats.h>
24 : #include <zephyr/sys/iterable_sections.h>
25 : #include <zephyr/sys/ring_buffer.h>
26 :
27 : #ifdef __cplusplus
28 : extern "C" {
29 : #endif
30 :
31 : /*
32 : * Zephyr currently assumes the size of a couple standard types to simplify
33 : * print string formats. Let's make sure this doesn't change without notice.
34 : */
35 : BUILD_ASSERT(sizeof(int32_t) == sizeof(int));
36 : BUILD_ASSERT(sizeof(int64_t) == sizeof(long long));
37 : BUILD_ASSERT(sizeof(intptr_t) == sizeof(long));
38 :
39 : /**
40 : * @brief Kernel APIs
41 : * @defgroup kernel_apis Kernel APIs
42 : * @since 1.0
43 : * @version 1.0.0
44 : * @{
45 : * @}
46 : */
47 :
48 0 : #define K_ANY NULL
49 :
50 : #if (CONFIG_NUM_COOP_PRIORITIES + CONFIG_NUM_PREEMPT_PRIORITIES) == 0
51 : #error Zero available thread priorities defined!
52 : #endif
53 :
54 0 : #define K_PRIO_COOP(x) (-(CONFIG_NUM_COOP_PRIORITIES - (x)))
55 0 : #define K_PRIO_PREEMPT(x) (x)
56 :
57 0 : #define K_HIGHEST_THREAD_PRIO (-CONFIG_NUM_COOP_PRIORITIES)
58 0 : #define K_LOWEST_THREAD_PRIO CONFIG_NUM_PREEMPT_PRIORITIES
59 0 : #define K_IDLE_PRIO K_LOWEST_THREAD_PRIO
60 0 : #define K_HIGHEST_APPLICATION_THREAD_PRIO (K_HIGHEST_THREAD_PRIO)
61 0 : #define K_LOWEST_APPLICATION_THREAD_PRIO (K_LOWEST_THREAD_PRIO - 1)
62 :
63 : #ifdef CONFIG_POLL
64 : #define Z_POLL_EVENT_OBJ_INIT(obj) \
65 : .poll_events = SYS_DLIST_STATIC_INIT(&obj.poll_events),
66 : #define Z_DECL_POLL_EVENT sys_dlist_t poll_events;
67 : #else
68 : #define Z_POLL_EVENT_OBJ_INIT(obj)
69 : #define Z_DECL_POLL_EVENT
70 : #endif
71 :
72 : struct k_thread;
73 : struct k_mutex;
74 : struct k_sem;
75 : struct k_msgq;
76 : struct k_mbox;
77 : struct k_pipe;
78 : struct k_queue;
79 : struct k_fifo;
80 : struct k_lifo;
81 : struct k_stack;
82 : struct k_mem_slab;
83 : struct k_timer;
84 : struct k_poll_event;
85 : struct k_poll_signal;
86 : struct k_mem_domain;
87 : struct k_mem_partition;
88 : struct k_futex;
89 : struct k_event;
90 :
91 0 : enum execution_context_types {
92 : K_ISR = 0,
93 : K_COOP_THREAD,
94 : K_PREEMPT_THREAD,
95 : };
96 :
97 : /* private, used by k_poll and k_work_poll */
98 : struct k_work_poll;
99 : typedef int (*_poller_cb_t)(struct k_poll_event *event, uint32_t state);
100 :
101 : /**
102 : * @addtogroup thread_apis
103 : * @{
104 : */
105 :
106 0 : typedef void (*k_thread_user_cb_t)(const struct k_thread *thread,
107 : void *user_data);
108 :
109 : /**
110 : * @brief Iterate over all the threads in the system.
111 : *
112 : * This routine iterates over all the threads in the system and
113 : * calls the user_cb function for each thread.
114 : *
115 : * @param user_cb Pointer to the user callback function.
116 : * @param user_data Pointer to user data.
117 : *
118 : * @note @kconfig{CONFIG_THREAD_MONITOR} must be set for this function
119 : * to be effective.
120 : * @note This API uses @ref k_spin_lock to protect the _kernel.threads
121 : * list which means creation of new threads and terminations of existing
122 : * threads are blocked until this API returns.
123 : */
124 1 : void k_thread_foreach(k_thread_user_cb_t user_cb, void *user_data);
125 :
126 : /**
127 : * @brief Iterate over all the threads in running on specified cpu.
128 : *
129 : * This function is does otherwise the same thing as k_thread_foreach(),
130 : * but it only loops through the threads running on specified cpu only.
131 : * If CONFIG_SMP is not defined the implementation this is the same as
132 : * k_thread_foreach(), with an assert cpu == 0.
133 : *
134 : * @param cpu The filtered cpu number
135 : * @param user_cb Pointer to the user callback function.
136 : * @param user_data Pointer to user data.
137 : *
138 : * @note @kconfig{CONFIG_THREAD_MONITOR} must be set for this function
139 : * to be effective.
140 : * @note This API uses @ref k_spin_lock to protect the _kernel.threads
141 : * list which means creation of new threads and terminations of existing
142 : * threads are blocked until this API returns.
143 : */
144 : #ifdef CONFIG_SMP
145 1 : void k_thread_foreach_filter_by_cpu(unsigned int cpu,
146 : k_thread_user_cb_t user_cb, void *user_data);
147 : #else
148 : static inline
149 : void k_thread_foreach_filter_by_cpu(unsigned int cpu,
150 : k_thread_user_cb_t user_cb, void *user_data)
151 : {
152 : __ASSERT(cpu == 0, "cpu filter out of bounds");
153 : ARG_UNUSED(cpu);
154 : k_thread_foreach(user_cb, user_data);
155 : }
156 : #endif
157 :
158 : /**
159 : * @brief Iterate over all the threads in the system without locking.
160 : *
161 : * This routine works exactly the same like @ref k_thread_foreach
162 : * but unlocks interrupts when user_cb is executed.
163 : *
164 : * @param user_cb Pointer to the user callback function.
165 : * @param user_data Pointer to user data.
166 : *
167 : * @note @kconfig{CONFIG_THREAD_MONITOR} must be set for this function
168 : * to be effective.
169 : * @note This API uses @ref k_spin_lock only when accessing the _kernel.threads
170 : * queue elements. It unlocks it during user callback function processing.
171 : * If a new task is created when this @c foreach function is in progress,
172 : * the added new task would not be included in the enumeration.
173 : * If a task is aborted during this enumeration, there would be a race here
174 : * and there is a possibility that this aborted task would be included in the
175 : * enumeration.
176 : * @note If the task is aborted and the memory occupied by its @c k_thread
177 : * structure is reused when this @c k_thread_foreach_unlocked is in progress
178 : * it might even lead to the system behave unstable.
179 : * This function may never return, as it would follow some @c next task
180 : * pointers treating given pointer as a pointer to the k_thread structure
181 : * while it is something different right now.
182 : * Do not reuse the memory that was occupied by k_thread structure of aborted
183 : * task if it was aborted after this function was called in any context.
184 : */
185 1 : void k_thread_foreach_unlocked(
186 : k_thread_user_cb_t user_cb, void *user_data);
187 :
188 : /**
189 : * @brief Iterate over the threads in running on current cpu without locking.
190 : *
191 : * This function does otherwise the same thing as
192 : * k_thread_foreach_unlocked(), but it only loops through the threads
193 : * running on specified cpu. If CONFIG_SMP is not defined the
194 : * implementation this is the same as k_thread_foreach_unlocked(), with an
195 : * assert requiring cpu == 0.
196 : *
197 : * @param cpu The filtered cpu number
198 : * @param user_cb Pointer to the user callback function.
199 : * @param user_data Pointer to user data.
200 : *
201 : * @note @kconfig{CONFIG_THREAD_MONITOR} must be set for this function
202 : * to be effective.
203 : * @note This API uses @ref k_spin_lock only when accessing the _kernel.threads
204 : * queue elements. It unlocks it during user callback function processing.
205 : * If a new task is created when this @c foreach function is in progress,
206 : * the added new task would not be included in the enumeration.
207 : * If a task is aborted during this enumeration, there would be a race here
208 : * and there is a possibility that this aborted task would be included in the
209 : * enumeration.
210 : * @note If the task is aborted and the memory occupied by its @c k_thread
211 : * structure is reused when this @c k_thread_foreach_unlocked is in progress
212 : * it might even lead to the system behave unstable.
213 : * This function may never return, as it would follow some @c next task
214 : * pointers treating given pointer as a pointer to the k_thread structure
215 : * while it is something different right now.
216 : * Do not reuse the memory that was occupied by k_thread structure of aborted
217 : * task if it was aborted after this function was called in any context.
218 : */
219 : #ifdef CONFIG_SMP
220 1 : void k_thread_foreach_unlocked_filter_by_cpu(unsigned int cpu,
221 : k_thread_user_cb_t user_cb, void *user_data);
222 : #else
223 : static inline
224 : void k_thread_foreach_unlocked_filter_by_cpu(unsigned int cpu,
225 : k_thread_user_cb_t user_cb, void *user_data)
226 : {
227 : __ASSERT(cpu == 0, "cpu filter out of bounds");
228 : ARG_UNUSED(cpu);
229 : k_thread_foreach_unlocked(user_cb, user_data);
230 : }
231 : #endif
232 :
233 : /** @} */
234 :
235 : /**
236 : * @defgroup thread_apis Thread APIs
237 : * @ingroup kernel_apis
238 : * @{
239 : */
240 :
241 : #endif /* !_ASMLANGUAGE */
242 :
243 :
244 : /*
245 : * Thread user options. May be needed by assembly code. Common part uses low
246 : * bits, arch-specific use high bits.
247 : */
248 :
249 : /**
250 : * @brief system thread that must not abort
251 : * */
252 1 : #define K_ESSENTIAL (BIT(0))
253 :
254 0 : #define K_FP_IDX 1
255 : /**
256 : * @brief FPU registers are managed by context switch
257 : *
258 : * @details
259 : * This option indicates that the thread uses the CPU's floating point
260 : * registers. This instructs the kernel to take additional steps to save
261 : * and restore the contents of these registers when scheduling the thread.
262 : * No effect if @kconfig{CONFIG_FPU_SHARING} is not enabled.
263 : */
264 1 : #define K_FP_REGS (BIT(K_FP_IDX))
265 :
266 : /**
267 : * @brief user mode thread
268 : *
269 : * This thread has dropped from supervisor mode to user mode and consequently
270 : * has additional restrictions
271 : */
272 1 : #define K_USER (BIT(2))
273 :
274 : /**
275 : * @brief Inherit Permissions
276 : *
277 : * @details
278 : * Indicates that the thread being created should inherit all kernel object
279 : * permissions from the thread that created it. No effect if
280 : * @kconfig{CONFIG_USERSPACE} is not enabled.
281 : */
282 1 : #define K_INHERIT_PERMS (BIT(3))
283 :
284 : /**
285 : * @brief Callback item state
286 : *
287 : * @details
288 : * This is a single bit of state reserved for "callback manager"
289 : * utilities (p4wq initially) who need to track operations invoked
290 : * from within a user-provided callback they have been invoked.
291 : * Effectively it serves as a tiny bit of zero-overhead TLS data.
292 : */
293 1 : #define K_CALLBACK_STATE (BIT(4))
294 :
295 : /**
296 : * @brief DSP registers are managed by context switch
297 : *
298 : * @details
299 : * This option indicates that the thread uses the CPU's DSP registers.
300 : * This instructs the kernel to take additional steps to save and
301 : * restore the contents of these registers when scheduling the thread.
302 : * No effect if @kconfig{CONFIG_DSP_SHARING} is not enabled.
303 : */
304 1 : #define K_DSP_IDX 6
305 0 : #define K_DSP_REGS (BIT(K_DSP_IDX))
306 :
307 : /**
308 : * @brief AGU registers are managed by context switch
309 : *
310 : * @details
311 : * This option indicates that the thread uses the ARC processor's XY
312 : * memory and DSP feature. Often used with @kconfig{CONFIG_ARC_AGU_SHARING}.
313 : * No effect if @kconfig{CONFIG_ARC_AGU_SHARING} is not enabled.
314 : */
315 1 : #define K_AGU_IDX 7
316 0 : #define K_AGU_REGS (BIT(K_AGU_IDX))
317 :
318 : /**
319 : * @brief FP and SSE registers are managed by context switch on x86
320 : *
321 : * @details
322 : * This option indicates that the thread uses the x86 CPU's floating point
323 : * and SSE registers. This instructs the kernel to take additional steps to
324 : * save and restore the contents of these registers when scheduling
325 : * the thread. No effect if @kconfig{CONFIG_X86_SSE} is not enabled.
326 : */
327 1 : #define K_SSE_REGS (BIT(7))
328 :
329 : /* end - thread options */
330 :
331 : #if !defined(_ASMLANGUAGE)
332 : /**
333 : * @brief Dynamically allocate a thread stack.
334 : *
335 : * Dynamically allocate a thread stack either from a pool of thread stacks of
336 : * size @kconfig{CONFIG_DYNAMIC_THREAD_POOL_SIZE}, or from the system heap.
337 : * Order is determined by the @kconfig{CONFIG_DYNAMIC_THREAD_PREFER_ALLOC} and
338 : * @kconfig{CONFIG_DYNAMIC_THREAD_PREFER_POOL} options. Thread stacks from the
339 : * pool are of maximum size @kconfig{CONFIG_DYNAMIC_THREAD_STACK_SIZE}.
340 : *
341 : * @note When no longer required, thread stacks allocated with
342 : * `k_thread_stack_alloc()` must be freed with @ref k_thread_stack_free to
343 : * avoid leaking memory.
344 : *
345 : * @param size Stack size in bytes.
346 : * @param flags Stack creation flags, or 0.
347 : *
348 : * @retval the allocated thread stack on success.
349 : * @retval NULL on failure.
350 : *
351 : * Relevant stack creation flags include:
352 : * - @ref K_USER allocate a userspace thread (requires @kconfig{CONFIG_USERSPACE})
353 : *
354 : * @see @kconfig{CONFIG_DYNAMIC_THREAD}
355 : */
356 1 : __syscall k_thread_stack_t *k_thread_stack_alloc(size_t size, int flags);
357 :
358 : /**
359 : * @brief Free a dynamically allocated thread stack.
360 : *
361 : * @param stack Pointer to the thread stack.
362 : *
363 : * @retval 0 on success.
364 : * @retval -EBUSY if the thread stack is in use.
365 : * @retval -EINVAL if @p stack is invalid.
366 : * @retval -ENOSYS if dynamic thread stack allocation is disabled
367 : *
368 : * @see @kconfig{CONFIG_DYNAMIC_THREAD}
369 : */
370 1 : __syscall int k_thread_stack_free(k_thread_stack_t *stack);
371 :
372 : /**
373 : * @brief Create a thread.
374 : *
375 : * This routine initializes a thread, then schedules it for execution.
376 : *
377 : * The new thread may be scheduled for immediate execution or a delayed start.
378 : * If the newly spawned thread does not have a delayed start the kernel
379 : * scheduler may preempt the current thread to allow the new thread to
380 : * execute.
381 : *
382 : * Thread options are architecture-specific, and can include K_ESSENTIAL,
383 : * K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating
384 : * them using "|" (the logical OR operator).
385 : *
386 : * Stack objects passed to this function may be statically allocated with
387 : * either of these macros in order to be portable:
388 : *
389 : * - K_THREAD_STACK_DEFINE() - For stacks that may support either user or
390 : * supervisor threads.
391 : * - K_KERNEL_STACK_DEFINE() - For stacks that may support supervisor
392 : * threads only. These stacks use less memory if CONFIG_USERSPACE is
393 : * enabled.
394 : *
395 : * Alternatively, the stack may be dynamically allocated using
396 : * @ref k_thread_stack_alloc.
397 : *
398 : * The stack_size parameter has constraints. It must either be:
399 : *
400 : * - The original size value passed to K_THREAD_STACK_DEFINE() or
401 : * K_KERNEL_STACK_DEFINE()
402 : * - The return value of K_THREAD_STACK_SIZEOF(stack) if the stack was
403 : * defined with K_THREAD_STACK_DEFINE()
404 : * - The return value of K_KERNEL_STACK_SIZEOF(stack) if the stack was
405 : * defined with K_KERNEL_STACK_DEFINE().
406 : *
407 : * Using other values, or sizeof(stack) may produce undefined behavior.
408 : *
409 : * @param new_thread Pointer to uninitialized struct k_thread
410 : * @param stack Pointer to the stack space.
411 : * @param stack_size Stack size in bytes.
412 : * @param entry Thread entry function.
413 : * @param p1 1st entry point parameter.
414 : * @param p2 2nd entry point parameter.
415 : * @param p3 3rd entry point parameter.
416 : * @param prio Thread priority.
417 : * @param options Thread options.
418 : * @param delay Scheduling delay, or K_NO_WAIT (for no delay).
419 : *
420 : * @return ID of new thread.
421 : *
422 : */
423 1 : __syscall k_tid_t k_thread_create(struct k_thread *new_thread,
424 : k_thread_stack_t *stack,
425 : size_t stack_size,
426 : k_thread_entry_t entry,
427 : void *p1, void *p2, void *p3,
428 : int prio, uint32_t options, k_timeout_t delay);
429 :
430 : /**
431 : * @brief Drop a thread's privileges permanently to user mode
432 : *
433 : * This allows a supervisor thread to be re-used as a user thread.
434 : * This function does not return, but control will transfer to the provided
435 : * entry point as if this was a new user thread.
436 : *
437 : * The implementation ensures that the stack buffer contents are erased.
438 : * Any thread-local storage will be reverted to a pristine state.
439 : *
440 : * Memory domain membership, resource pool assignment, kernel object
441 : * permissions, priority, and thread options are preserved.
442 : *
443 : * A common use of this function is to re-use the main thread as a user thread
444 : * once all supervisor mode-only tasks have been completed.
445 : *
446 : * @param entry Function to start executing from
447 : * @param p1 1st entry point parameter
448 : * @param p2 2nd entry point parameter
449 : * @param p3 3rd entry point parameter
450 : */
451 1 : FUNC_NORETURN void k_thread_user_mode_enter(k_thread_entry_t entry,
452 : void *p1, void *p2,
453 : void *p3);
454 :
455 : /**
456 : * @brief Grant a thread access to a set of kernel objects
457 : *
458 : * This is a convenience function. For the provided thread, grant access to
459 : * the remaining arguments, which must be pointers to kernel objects.
460 : *
461 : * The thread object must be initialized (i.e. running). The objects don't
462 : * need to be.
463 : * Note that NULL shouldn't be passed as an argument.
464 : *
465 : * @param thread Thread to grant access to objects
466 : * @param ... list of kernel object pointers
467 : */
468 1 : #define k_thread_access_grant(thread, ...) \
469 : FOR_EACH_FIXED_ARG(k_object_access_grant, (;), (thread), __VA_ARGS__)
470 :
471 : /**
472 : * @brief Assign a resource memory pool to a thread
473 : *
474 : * By default, threads have no resource pool assigned unless their parent
475 : * thread has a resource pool, in which case it is inherited. Multiple
476 : * threads may be assigned to the same memory pool.
477 : *
478 : * Changing a thread's resource pool will not migrate allocations from the
479 : * previous pool.
480 : *
481 : * @param thread Target thread to assign a memory pool for resource requests.
482 : * @param heap Heap object to use for resources,
483 : * or NULL if the thread should no longer have a memory pool.
484 : */
485 1 : static inline void k_thread_heap_assign(struct k_thread *thread,
486 : struct k_heap *heap)
487 : {
488 : thread->resource_pool = heap;
489 : }
490 :
491 : #if defined(CONFIG_INIT_STACKS) && defined(CONFIG_THREAD_STACK_INFO)
492 : /**
493 : * @brief Obtain stack usage information for the specified thread
494 : *
495 : * User threads will need to have permission on the target thread object.
496 : *
497 : * Some hardware may prevent inspection of a stack buffer currently in use.
498 : * If this API is called from supervisor mode, on the currently running thread,
499 : * on a platform which selects @kconfig{CONFIG_NO_UNUSED_STACK_INSPECTION}, an
500 : * error will be generated.
501 : *
502 : * @param thread Thread to inspect stack information
503 : * @param unused_ptr Output parameter, filled in with the unused stack space
504 : * of the target thread in bytes.
505 : * @return 0 on success
506 : * @return -EBADF Bad thread object (user mode only)
507 : * @return -EPERM No permissions on thread object (user mode only)
508 : * #return -ENOTSUP Forbidden by hardware policy
509 : * @return -EINVAL Thread is uninitialized or exited (user mode only)
510 : * @return -EFAULT Bad memory address for unused_ptr (user mode only)
511 : */
512 : __syscall int k_thread_stack_space_get(const struct k_thread *thread,
513 : size_t *unused_ptr);
514 : #endif
515 :
516 : #if (K_HEAP_MEM_POOL_SIZE > 0)
517 : /**
518 : * @brief Assign the system heap as a thread's resource pool
519 : *
520 : * Similar to k_thread_heap_assign(), but the thread will use
521 : * the kernel heap to draw memory.
522 : *
523 : * Use with caution, as a malicious thread could perform DoS attacks on the
524 : * kernel heap.
525 : *
526 : * @param thread Target thread to assign the system heap for resource requests
527 : *
528 : */
529 : void k_thread_system_pool_assign(struct k_thread *thread);
530 : #endif /* (K_HEAP_MEM_POOL_SIZE > 0) */
531 :
532 : /**
533 : * @brief Sleep until a thread exits
534 : *
535 : * The caller will be put to sleep until the target thread exits, either due
536 : * to being aborted, self-exiting, or taking a fatal error. This API returns
537 : * immediately if the thread isn't running.
538 : *
539 : * This API may only be called from ISRs with a K_NO_WAIT timeout,
540 : * where it can be useful as a predicate to detect when a thread has
541 : * aborted.
542 : *
543 : * @param thread Thread to wait to exit
544 : * @param timeout upper bound time to wait for the thread to exit.
545 : * @retval 0 success, target thread has exited or wasn't running
546 : * @retval -EBUSY returned without waiting
547 : * @retval -EAGAIN waiting period timed out
548 : * @retval -EDEADLK target thread is joining on the caller, or target thread
549 : * is the caller
550 : */
551 1 : __syscall int k_thread_join(struct k_thread *thread, k_timeout_t timeout);
552 :
553 : /**
554 : * @brief Put the current thread to sleep.
555 : *
556 : * This routine puts the current thread to sleep for @a duration,
557 : * specified as a k_timeout_t object.
558 : *
559 : * @param timeout Desired duration of sleep.
560 : *
561 : * @return Zero if the requested time has elapsed or the time left to
562 : * sleep rounded up to the nearest millisecond (e.g. if the thread was
563 : * awoken by the \ref k_wakeup call). Will be clamped to INT_MAX in
564 : * the case where the remaining time is unrepresentable in an int32_t.
565 : */
566 1 : __syscall int32_t k_sleep(k_timeout_t timeout);
567 :
568 : /**
569 : * @brief Put the current thread to sleep.
570 : *
571 : * This routine puts the current thread to sleep for @a duration milliseconds.
572 : *
573 : * @param ms Number of milliseconds to sleep.
574 : *
575 : * @return Zero if the requested time has elapsed or if the thread was woken up
576 : * by the \ref k_wakeup call, the time left to sleep rounded up to the nearest
577 : * millisecond.
578 : */
579 1 : static inline int32_t k_msleep(int32_t ms)
580 : {
581 : return k_sleep(Z_TIMEOUT_MS(ms));
582 : }
583 :
584 : /**
585 : * @brief Put the current thread to sleep with microsecond resolution.
586 : *
587 : * This function is unlikely to work as expected without kernel tuning.
588 : * In particular, because the lower bound on the duration of a sleep is
589 : * the duration of a tick, @kconfig{CONFIG_SYS_CLOCK_TICKS_PER_SEC} must be
590 : * adjusted to achieve the resolution desired. The implications of doing
591 : * this must be understood before attempting to use k_usleep(). Use with
592 : * caution.
593 : *
594 : * @param us Number of microseconds to sleep.
595 : *
596 : * @return Zero if the requested time has elapsed or if the thread was woken up
597 : * by the \ref k_wakeup call, the time left to sleep rounded up to the nearest
598 : * microsecond.
599 : */
600 1 : __syscall int32_t k_usleep(int32_t us);
601 :
602 : /**
603 : * @brief Cause the current thread to busy wait.
604 : *
605 : * This routine causes the current thread to execute a "do nothing" loop for
606 : * @a usec_to_wait microseconds.
607 : *
608 : * @note The clock used for the microsecond-resolution delay here may
609 : * be skewed relative to the clock used for system timeouts like
610 : * k_sleep(). For example k_busy_wait(1000) may take slightly more or
611 : * less time than k_sleep(K_MSEC(1)), with the offset dependent on
612 : * clock tolerances.
613 : *
614 : * @note In case when @kconfig{CONFIG_SYSTEM_CLOCK_SLOPPY_IDLE} and
615 : * @kconfig{CONFIG_PM} options are enabled, this function may not work.
616 : * The timer/clock used for delay processing may be disabled/inactive.
617 : */
618 1 : __syscall void k_busy_wait(uint32_t usec_to_wait);
619 :
620 : /**
621 : * @brief Check whether it is possible to yield in the current context.
622 : *
623 : * This routine checks whether the kernel is in a state where it is possible to
624 : * yield or call blocking API's. It should be used by code that needs to yield
625 : * to perform correctly, but can feasibly be called from contexts where that
626 : * is not possible. For example in the PRE_KERNEL initialization step, or when
627 : * being run from the idle thread.
628 : *
629 : * @return True if it is possible to yield in the current context, false otherwise.
630 : */
631 1 : bool k_can_yield(void);
632 :
633 : /**
634 : * @brief Yield the current thread.
635 : *
636 : * This routine causes the current thread to yield execution to another
637 : * thread of the same or higher priority. If there are no other ready threads
638 : * of the same or higher priority, the routine returns immediately.
639 : */
640 1 : __syscall void k_yield(void);
641 :
642 : /**
643 : * @brief Wake up a sleeping thread.
644 : *
645 : * This routine prematurely wakes up @a thread from sleeping.
646 : *
647 : * If @a thread is not currently sleeping, the routine has no effect.
648 : *
649 : * @param thread ID of thread to wake.
650 : */
651 1 : __syscall void k_wakeup(k_tid_t thread);
652 :
653 : /**
654 : * @brief Query thread ID of the current thread.
655 : *
656 : * This unconditionally queries the kernel via a system call.
657 : *
658 : * @note Use k_current_get() unless absolutely sure this is necessary.
659 : * This should only be used directly where the thread local
660 : * variable cannot be used or may contain invalid values
661 : * if thread local storage (TLS) is enabled. If TLS is not
662 : * enabled, this is the same as k_current_get().
663 : *
664 : * @return ID of current thread.
665 : */
666 : __attribute_const__
667 1 : __syscall k_tid_t k_sched_current_thread_query(void);
668 :
669 : /**
670 : * @brief Get thread ID of the current thread.
671 : *
672 : * @return ID of current thread.
673 : *
674 : */
675 : __attribute_const__
676 1 : static inline k_tid_t k_current_get(void)
677 : {
678 : #ifdef CONFIG_CURRENT_THREAD_USE_TLS
679 :
680 : /* Thread-local cache of current thread ID, set in z_thread_entry() */
681 : extern Z_THREAD_LOCAL k_tid_t z_tls_current;
682 :
683 : return z_tls_current;
684 : #else
685 : return k_sched_current_thread_query();
686 : #endif
687 : }
688 :
689 : /**
690 : * @brief Abort a thread.
691 : *
692 : * This routine permanently stops execution of @a thread. The thread is taken
693 : * off all kernel queues it is part of (i.e. the ready queue, the timeout
694 : * queue, or a kernel object wait queue). However, any kernel resources the
695 : * thread might currently own (such as mutexes or memory blocks) are not
696 : * released. It is the responsibility of the caller of this routine to ensure
697 : * all necessary cleanup is performed.
698 : *
699 : * After k_thread_abort() returns, the thread is guaranteed not to be
700 : * running or to become runnable anywhere on the system. Normally
701 : * this is done via blocking the caller (in the same manner as
702 : * k_thread_join()), but in interrupt context on SMP systems the
703 : * implementation is required to spin for threads that are running on
704 : * other CPUs.
705 : *
706 : * @param thread ID of thread to abort.
707 : */
708 1 : __syscall void k_thread_abort(k_tid_t thread);
709 :
710 : k_ticks_t z_timeout_expires(const struct _timeout *timeout);
711 : k_ticks_t z_timeout_remaining(const struct _timeout *timeout);
712 :
713 : #ifdef CONFIG_SYS_CLOCK_EXISTS
714 :
715 : /**
716 : * @brief Get time when a thread wakes up, in system ticks
717 : *
718 : * This routine computes the system uptime when a waiting thread next
719 : * executes, in units of system ticks. If the thread is not waiting,
720 : * it returns current system time.
721 : */
722 1 : __syscall k_ticks_t k_thread_timeout_expires_ticks(const struct k_thread *thread);
723 :
724 : static inline k_ticks_t z_impl_k_thread_timeout_expires_ticks(
725 : const struct k_thread *thread)
726 : {
727 : return z_timeout_expires(&thread->base.timeout);
728 : }
729 :
730 : /**
731 : * @brief Get time remaining before a thread wakes up, in system ticks
732 : *
733 : * This routine computes the time remaining before a waiting thread
734 : * next executes, in units of system ticks. If the thread is not
735 : * waiting, it returns zero.
736 : */
737 1 : __syscall k_ticks_t k_thread_timeout_remaining_ticks(const struct k_thread *thread);
738 :
739 : static inline k_ticks_t z_impl_k_thread_timeout_remaining_ticks(
740 : const struct k_thread *thread)
741 : {
742 : return z_timeout_remaining(&thread->base.timeout);
743 : }
744 :
745 : #endif /* CONFIG_SYS_CLOCK_EXISTS */
746 :
747 : /**
748 : * @cond INTERNAL_HIDDEN
749 : */
750 :
751 : struct _static_thread_data {
752 : struct k_thread *init_thread;
753 : k_thread_stack_t *init_stack;
754 : unsigned int init_stack_size;
755 : k_thread_entry_t init_entry;
756 : void *init_p1;
757 : void *init_p2;
758 : void *init_p3;
759 : int init_prio;
760 : uint32_t init_options;
761 : const char *init_name;
762 : #ifdef CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME
763 : int32_t init_delay_ms;
764 : #else
765 : k_timeout_t init_delay;
766 : #endif
767 : };
768 :
769 : #ifdef CONFIG_TIMER_READS_ITS_FREQUENCY_AT_RUNTIME
770 : #define Z_THREAD_INIT_DELAY_INITIALIZER(ms) .init_delay_ms = (ms)
771 : #define Z_THREAD_INIT_DELAY(thread) SYS_TIMEOUT_MS((thread)->init_delay_ms)
772 : #else
773 : #define Z_THREAD_INIT_DELAY_INITIALIZER(ms) .init_delay = SYS_TIMEOUT_MS_INIT(ms)
774 : #define Z_THREAD_INIT_DELAY(thread) (thread)->init_delay
775 : #endif
776 :
777 : #define Z_THREAD_INITIALIZER(thread, stack, stack_size, \
778 : entry, p1, p2, p3, \
779 : prio, options, delay, tname) \
780 : { \
781 : .init_thread = (thread), \
782 : .init_stack = (stack), \
783 : .init_stack_size = (stack_size), \
784 : .init_entry = (k_thread_entry_t)entry, \
785 : .init_p1 = (void *)p1, \
786 : .init_p2 = (void *)p2, \
787 : .init_p3 = (void *)p3, \
788 : .init_prio = (prio), \
789 : .init_options = (options), \
790 : .init_name = STRINGIFY(tname), \
791 : Z_THREAD_INIT_DELAY_INITIALIZER(delay) \
792 : }
793 :
794 : /*
795 : * Refer to K_THREAD_DEFINE() and K_KERNEL_THREAD_DEFINE() for
796 : * information on arguments.
797 : */
798 : #define Z_THREAD_COMMON_DEFINE(name, stack_size, \
799 : entry, p1, p2, p3, \
800 : prio, options, delay) \
801 : struct k_thread _k_thread_obj_##name; \
802 : STRUCT_SECTION_ITERABLE(_static_thread_data, \
803 : _k_thread_data_##name) = \
804 : Z_THREAD_INITIALIZER(&_k_thread_obj_##name, \
805 : _k_thread_stack_##name, stack_size,\
806 : entry, p1, p2, p3, prio, options, \
807 : delay, name); \
808 : __maybe_unused const k_tid_t name = (k_tid_t)&_k_thread_obj_##name
809 :
810 : /**
811 : * INTERNAL_HIDDEN @endcond
812 : */
813 :
814 : /**
815 : * @brief Statically define and initialize a thread.
816 : *
817 : * The thread may be scheduled for immediate execution or a delayed start.
818 : *
819 : * Thread options are architecture-specific, and can include K_ESSENTIAL,
820 : * K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating
821 : * them using "|" (the logical OR operator).
822 : *
823 : * The ID of the thread can be accessed using:
824 : *
825 : * @code extern const k_tid_t <name>; @endcode
826 : *
827 : * @param name Name of the thread.
828 : * @param stack_size Stack size in bytes.
829 : * @param entry Thread entry function.
830 : * @param p1 1st entry point parameter.
831 : * @param p2 2nd entry point parameter.
832 : * @param p3 3rd entry point parameter.
833 : * @param prio Thread priority.
834 : * @param options Thread options.
835 : * @param delay Scheduling delay (in milliseconds), zero for no delay.
836 : *
837 : * @note Static threads with zero delay should not normally have
838 : * MetaIRQ priority levels. This can preempt the system
839 : * initialization handling (depending on the priority of the main
840 : * thread) and cause surprising ordering side effects. It will not
841 : * affect anything in the OS per se, but consider it bad practice.
842 : * Use a SYS_INIT() callback if you need to run code before entrance
843 : * to the application main().
844 : */
845 : #define K_THREAD_DEFINE(name, stack_size, \
846 : entry, p1, p2, p3, \
847 1 : prio, options, delay) \
848 : K_THREAD_STACK_DEFINE(_k_thread_stack_##name, stack_size); \
849 : Z_THREAD_COMMON_DEFINE(name, stack_size, entry, p1, p2, p3, \
850 : prio, options, delay)
851 :
852 : /**
853 : * @brief Statically define and initialize a thread intended to run only in kernel mode.
854 : *
855 : * The thread may be scheduled for immediate execution or a delayed start.
856 : *
857 : * Thread options are architecture-specific, and can include K_ESSENTIAL,
858 : * K_FP_REGS, and K_SSE_REGS. Multiple options may be specified by separating
859 : * them using "|" (the logical OR operator).
860 : *
861 : * The ID of the thread can be accessed using:
862 : *
863 : * @code extern const k_tid_t <name>; @endcode
864 : *
865 : * @note Threads defined by this can only run in kernel mode, and cannot be
866 : * transformed into user thread via k_thread_user_mode_enter().
867 : *
868 : * @warning Depending on the architecture, the stack size (@p stack_size)
869 : * may need to be multiples of CONFIG_MMU_PAGE_SIZE (if MMU)
870 : * or in power-of-two size (if MPU).
871 : *
872 : * @param name Name of the thread.
873 : * @param stack_size Stack size in bytes.
874 : * @param entry Thread entry function.
875 : * @param p1 1st entry point parameter.
876 : * @param p2 2nd entry point parameter.
877 : * @param p3 3rd entry point parameter.
878 : * @param prio Thread priority.
879 : * @param options Thread options.
880 : * @param delay Scheduling delay (in milliseconds), zero for no delay.
881 : */
882 : #define K_KERNEL_THREAD_DEFINE(name, stack_size, \
883 : entry, p1, p2, p3, \
884 1 : prio, options, delay) \
885 : K_KERNEL_STACK_DEFINE(_k_thread_stack_##name, stack_size); \
886 : Z_THREAD_COMMON_DEFINE(name, stack_size, entry, p1, p2, p3, \
887 : prio, options, delay)
888 :
889 : /**
890 : * @brief Get a thread's priority.
891 : *
892 : * This routine gets the priority of @a thread.
893 : *
894 : * @param thread ID of thread whose priority is needed.
895 : *
896 : * @return Priority of @a thread.
897 : */
898 1 : __syscall int k_thread_priority_get(k_tid_t thread);
899 :
900 : /**
901 : * @brief Set a thread's priority.
902 : *
903 : * This routine immediately changes the priority of @a thread.
904 : *
905 : * Rescheduling can occur immediately depending on the priority @a thread is
906 : * set to:
907 : *
908 : * - If its priority is raised above the priority of a currently scheduled
909 : * preemptible thread, @a thread will be scheduled in.
910 : *
911 : * - If the caller lowers the priority of a currently scheduled preemptible
912 : * thread below that of other threads in the system, the thread of the highest
913 : * priority will be scheduled in.
914 : *
915 : * Priority can be assigned in the range of -CONFIG_NUM_COOP_PRIORITIES to
916 : * CONFIG_NUM_PREEMPT_PRIORITIES-1, where -CONFIG_NUM_COOP_PRIORITIES is the
917 : * highest priority.
918 : *
919 : * @param thread ID of thread whose priority is to be set.
920 : * @param prio New priority.
921 : *
922 : * @warning Changing the priority of a thread currently involved in mutex
923 : * priority inheritance may result in undefined behavior.
924 : */
925 1 : __syscall void k_thread_priority_set(k_tid_t thread, int prio);
926 :
927 :
928 : #ifdef CONFIG_SCHED_DEADLINE
929 : /**
930 : * @brief Set deadline expiration time for scheduler
931 : *
932 : * This sets the "deadline" expiration as a time delta from the
933 : * current time, in the same units used by k_cycle_get_32(). The
934 : * scheduler (when deadline scheduling is enabled) will choose the
935 : * next expiring thread when selecting between threads at the same
936 : * static priority. Threads at different priorities will be scheduled
937 : * according to their static priority.
938 : *
939 : * @note Deadlines are stored internally using 32 bit unsigned
940 : * integers. The number of cycles between the "first" deadline in the
941 : * scheduler queue and the "last" deadline must be less than 2^31 (i.e
942 : * a signed non-negative quantity). Failure to adhere to this rule
943 : * may result in scheduled threads running in an incorrect deadline
944 : * order.
945 : *
946 : * @note Despite the API naming, the scheduler makes no guarantees
947 : * the thread WILL be scheduled within that deadline, nor does it take
948 : * extra metadata (like e.g. the "runtime" and "period" parameters in
949 : * Linux sched_setattr()) that allows the kernel to validate the
950 : * scheduling for achievability. Such features could be implemented
951 : * above this call, which is simply input to the priority selection
952 : * logic.
953 : *
954 : * @note You should enable @kconfig{CONFIG_SCHED_DEADLINE} in your project
955 : * configuration.
956 : *
957 : * @param thread A thread on which to set the deadline
958 : * @param deadline A time delta, in cycle units
959 : *
960 : */
961 1 : __syscall void k_thread_deadline_set(k_tid_t thread, int deadline);
962 :
963 : /**
964 : * @brief Set deadline expiration time for scheduler
965 : *
966 : * This sets the "deadline" expiration as a timestamp in the same
967 : * units used by k_cycle_get_32(). The scheduler (when deadline scheduling
968 : * is enabled) will choose the next expiring thread when selecting between
969 : * threads at the same static priority. Threads at different priorities
970 : * will be scheduled according to their static priority.
971 : *
972 : * Unlike @ref k_thread_deadline_set which sets a relative timestamp to a
973 : * "now" implicitly determined during its call, this routine sets an
974 : * absolute timestamp that is computed from a timestamp relative to
975 : * an explicit "now" that was determined before this routine is called.
976 : * This allows the caller to specify deadlines for multiple threads
977 : * using a common "now".
978 : *
979 : * @note Deadlines are stored internally using 32 bit unsigned
980 : * integers. The number of cycles between the "first" deadline in the
981 : * scheduler queue and the "last" deadline must be less than 2^31 (i.e
982 : * a signed non-negative quantity). Failure to adhere to this rule
983 : * may result in scheduled threads running in an incorrect deadline
984 : * order.
985 : *
986 : * @note Even if a provided timestamp is in the past, the kernel will
987 : * still schedule threads with deadlines in order from the earliest to
988 : * the latest
989 : *
990 : * @note Despite the API naming, the scheduler makes no guarantees
991 : * the thread WILL be scheduled within that deadline, nor does it take
992 : * extra metadata (like e.g. the "runtime" and "period" parameters in
993 : * Linux sched_setattr()) that allows the kernel to validate the
994 : * scheduling for achievability. Such features could be implemented
995 : * above this call, which is simply input to the priority selection
996 : * logic.
997 : *
998 : * @note You should enable @kconfig_dep{CONFIG_SCHED_DEADLINE} in your project
999 : * configuration.
1000 : *
1001 : * @param thread A thread on which to set the deadline
1002 : * @param deadline A timestamp, in cycle units
1003 : */
1004 1 : __syscall void k_thread_absolute_deadline_set(k_tid_t thread, int deadline);
1005 : #endif
1006 :
1007 : /**
1008 : * @brief Invoke the scheduler
1009 : *
1010 : * This routine invokes the scheduler to force a schedule point on the current
1011 : * CPU. If invoked from within a thread, the scheduler will be invoked
1012 : * immediately (provided interrupts were not locked when invoked). If invoked
1013 : * from within an ISR, the scheduler will be invoked upon exiting the ISR.
1014 : *
1015 : * Invoking the scheduler allows the kernel to make an immediate determination
1016 : * as to what the next thread to execute should be. Unlike yielding, this
1017 : * routine is not guaranteed to switch to a thread of equal or higher priority
1018 : * if any are available. For example, if the current thread is cooperative and
1019 : * there is a still higher priority cooperative thread that is ready, then
1020 : * yielding will switch to that higher priority thread whereas this routine
1021 : * will not.
1022 : *
1023 : * Most applications will never use this routine.
1024 : */
1025 1 : __syscall void k_reschedule(void);
1026 :
1027 : #ifdef CONFIG_SCHED_CPU_MASK
1028 : /**
1029 : * @brief Sets all CPU enable masks to zero
1030 : *
1031 : * After this returns, the thread will no longer be schedulable on any
1032 : * CPUs. The thread must not be currently runnable.
1033 : *
1034 : * @note You should enable @kconfig{CONFIG_SCHED_CPU_MASK} in your project
1035 : * configuration.
1036 : *
1037 : * @param thread Thread to operate upon
1038 : * @return Zero on success, otherwise error code
1039 : */
1040 1 : int k_thread_cpu_mask_clear(k_tid_t thread);
1041 :
1042 : /**
1043 : * @brief Sets all CPU enable masks to one
1044 : *
1045 : * After this returns, the thread will be schedulable on any CPU. The
1046 : * thread must not be currently runnable.
1047 : *
1048 : * @note You should enable @kconfig{CONFIG_SCHED_CPU_MASK} in your project
1049 : * configuration.
1050 : *
1051 : * @param thread Thread to operate upon
1052 : * @return Zero on success, otherwise error code
1053 : */
1054 1 : int k_thread_cpu_mask_enable_all(k_tid_t thread);
1055 :
1056 : /**
1057 : * @brief Enable thread to run on specified CPU
1058 : *
1059 : * The thread must not be currently runnable.
1060 : *
1061 : * @note You should enable @kconfig{CONFIG_SCHED_CPU_MASK} in your project
1062 : * configuration.
1063 : *
1064 : * @param thread Thread to operate upon
1065 : * @param cpu CPU index
1066 : * @return Zero on success, otherwise error code
1067 : */
1068 1 : int k_thread_cpu_mask_enable(k_tid_t thread, int cpu);
1069 :
1070 : /**
1071 : * @brief Prevent thread to run on specified CPU
1072 : *
1073 : * The thread must not be currently runnable.
1074 : *
1075 : * @note You should enable @kconfig{CONFIG_SCHED_CPU_MASK} in your project
1076 : * configuration.
1077 : *
1078 : * @param thread Thread to operate upon
1079 : * @param cpu CPU index
1080 : * @return Zero on success, otherwise error code
1081 : */
1082 1 : int k_thread_cpu_mask_disable(k_tid_t thread, int cpu);
1083 :
1084 : /**
1085 : * @brief Pin a thread to a CPU
1086 : *
1087 : * Pin a thread to a CPU by first clearing the cpu mask and then enabling the
1088 : * thread on the selected CPU.
1089 : *
1090 : * @param thread Thread to operate upon
1091 : * @param cpu CPU index
1092 : * @return Zero on success, otherwise error code
1093 : */
1094 1 : int k_thread_cpu_pin(k_tid_t thread, int cpu);
1095 : #endif
1096 :
1097 : /**
1098 : * @brief Suspend a thread.
1099 : *
1100 : * This routine prevents the kernel scheduler from making @a thread
1101 : * the current thread. All other internal operations on @a thread are
1102 : * still performed; for example, kernel objects it is waiting on are
1103 : * still handed to it. Thread suspension does not impact any timeout
1104 : * upon which the thread may be waiting (such as a timeout from a call
1105 : * to k_sem_take() or k_sleep()). Thus if the timeout expires while the
1106 : * thread is suspended, it is still suspended until k_thread_resume()
1107 : * is called.
1108 : *
1109 : * When the target thread is active on another CPU, the caller will block until
1110 : * the target thread is halted (suspended or aborted). But if the caller is in
1111 : * an interrupt context, it will spin waiting for that target thread active on
1112 : * another CPU to halt.
1113 : *
1114 : * If @a thread is already suspended, the routine has no effect.
1115 : *
1116 : * @param thread ID of thread to suspend.
1117 : */
1118 1 : __syscall void k_thread_suspend(k_tid_t thread);
1119 :
1120 : /**
1121 : * @brief Resume a suspended thread.
1122 : *
1123 : * This routine reverses the thread suspension from k_thread_suspend()
1124 : * and allows the kernel scheduler to make @a thread the current thread
1125 : * when it is next eligible for that role.
1126 : *
1127 : * If @a thread is not currently suspended, the routine has no effect.
1128 : *
1129 : * @param thread ID of thread to resume.
1130 : */
1131 1 : __syscall void k_thread_resume(k_tid_t thread);
1132 :
1133 : /**
1134 : * @brief Start an inactive thread
1135 : *
1136 : * If a thread was created with K_FOREVER in the delay parameter, it will
1137 : * not be added to the scheduling queue until this function is called
1138 : * on it.
1139 : *
1140 : * @note This is a legacy API for compatibility. Modern Zephyr
1141 : * threads are initialized in the "sleeping" state and do not need
1142 : * special handling for "start".
1143 : *
1144 : * @param thread thread to start
1145 : */
1146 1 : static inline void k_thread_start(k_tid_t thread)
1147 : {
1148 : k_wakeup(thread);
1149 : }
1150 :
1151 : /**
1152 : * @brief Set time-slicing period and scope.
1153 : *
1154 : * This routine specifies how the scheduler will perform time slicing of
1155 : * preemptible threads.
1156 : *
1157 : * To enable time slicing, @a slice must be non-zero. The scheduler
1158 : * ensures that no thread runs for more than the specified time limit
1159 : * before other threads of that priority are given a chance to execute.
1160 : * Any thread whose priority is higher than @a prio is exempted, and may
1161 : * execute as long as desired without being preempted due to time slicing.
1162 : *
1163 : * Time slicing only limits the maximum amount of time a thread may continuously
1164 : * execute. Once the scheduler selects a thread for execution, there is no
1165 : * minimum guaranteed time the thread will execute before threads of greater or
1166 : * equal priority are scheduled.
1167 : *
1168 : * When the current thread is the only one of that priority eligible
1169 : * for execution, this routine has no effect; the thread is immediately
1170 : * rescheduled after the slice period expires.
1171 : *
1172 : * To disable timeslicing, set both @a slice and @a prio to zero.
1173 : *
1174 : * @param slice Maximum time slice length (in milliseconds).
1175 : * @param prio Highest thread priority level eligible for time slicing.
1176 : */
1177 1 : void k_sched_time_slice_set(int32_t slice, int prio);
1178 :
1179 : /**
1180 : * @brief Set thread time slice
1181 : *
1182 : * As for k_sched_time_slice_set, but (when
1183 : * CONFIG_TIMESLICE_PER_THREAD=y) sets the timeslice for a specific
1184 : * thread. When non-zero, this timeslice will take precedence over
1185 : * the global value.
1186 : *
1187 : * When such a thread's timeslice expires, the configured callback
1188 : * will be called before the thread is removed/re-added to the run
1189 : * queue. This callback will occur in interrupt context, and the
1190 : * specified thread is guaranteed to have been preempted by the
1191 : * currently-executing ISR. Such a callback is free to, for example,
1192 : * modify the thread priority or slice time for future execution,
1193 : * suspend the thread, etc...
1194 : *
1195 : * @note Unlike the older API, the time slice parameter here is
1196 : * specified in ticks, not milliseconds. Ticks have always been the
1197 : * internal unit, and not all platforms have integer conversions
1198 : * between the two.
1199 : *
1200 : * @note Threads with a non-zero slice time set will be timesliced
1201 : * always, even if they are higher priority than the maximum timeslice
1202 : * priority set via k_sched_time_slice_set().
1203 : *
1204 : * @note The callback notification for slice expiration happens, as it
1205 : * must, while the thread is still "current", and thus it happens
1206 : * before any registered timeouts at this tick. This has the somewhat
1207 : * confusing side effect that the tick time (c.f. k_uptime_get()) does
1208 : * not yet reflect the expired ticks. Applications wishing to make
1209 : * fine-grained timing decisions within this callback should use the
1210 : * cycle API, or derived facilities like k_thread_runtime_stats_get().
1211 : *
1212 : * @param th A valid, initialized thread
1213 : * @param slice_ticks Maximum timeslice, in ticks
1214 : * @param expired Callback function called on slice expiration
1215 : * @param data Parameter for the expiration handler
1216 : */
1217 1 : void k_thread_time_slice_set(struct k_thread *th, int32_t slice_ticks,
1218 : k_thread_timeslice_fn_t expired, void *data);
1219 :
1220 : /** @} */
1221 :
1222 : /**
1223 : * @addtogroup isr_apis
1224 : * @{
1225 : */
1226 :
1227 : /**
1228 : * @brief Determine if code is running at interrupt level.
1229 : *
1230 : * This routine allows the caller to customize its actions, depending on
1231 : * whether it is a thread or an ISR.
1232 : *
1233 : * @funcprops \isr_ok
1234 : *
1235 : * @return false if invoked by a thread.
1236 : * @return true if invoked by an ISR.
1237 : */
1238 1 : bool k_is_in_isr(void);
1239 :
1240 : /**
1241 : * @brief Determine if code is running in a preemptible thread.
1242 : *
1243 : * This routine allows the caller to customize its actions, depending on
1244 : * whether it can be preempted by another thread. The routine returns a 'true'
1245 : * value if all of the following conditions are met:
1246 : *
1247 : * - The code is running in a thread, not at ISR.
1248 : * - The thread's priority is in the preemptible range.
1249 : * - The thread has not locked the scheduler.
1250 : *
1251 : * @funcprops \isr_ok
1252 : *
1253 : * @return 0 if invoked by an ISR or by a cooperative thread.
1254 : * @return Non-zero if invoked by a preemptible thread.
1255 : */
1256 1 : __syscall int k_is_preempt_thread(void);
1257 :
1258 : /**
1259 : * @brief Test whether startup is in the before-main-task phase.
1260 : *
1261 : * This routine allows the caller to customize its actions, depending on
1262 : * whether it being invoked before the kernel is fully active.
1263 : *
1264 : * @funcprops \isr_ok
1265 : *
1266 : * @return true if invoked before post-kernel initialization
1267 : * @return false if invoked during/after post-kernel initialization
1268 : */
1269 1 : static inline bool k_is_pre_kernel(void)
1270 : {
1271 : extern bool z_sys_post_kernel; /* in init.c */
1272 :
1273 : return !z_sys_post_kernel;
1274 : }
1275 :
1276 : /**
1277 : * @}
1278 : */
1279 :
1280 : /**
1281 : * @addtogroup thread_apis
1282 : * @{
1283 : */
1284 :
1285 : /**
1286 : * @brief Lock the scheduler.
1287 : *
1288 : * This routine prevents the current thread from being preempted by another
1289 : * thread by instructing the scheduler to treat it as a cooperative thread.
1290 : * If the thread subsequently performs an operation that makes it unready,
1291 : * it will be context switched out in the normal manner. When the thread
1292 : * again becomes the current thread, its non-preemptible status is maintained.
1293 : *
1294 : * This routine can be called recursively.
1295 : *
1296 : * Owing to clever implementation details, scheduler locks are
1297 : * extremely fast for non-userspace threads (just one byte
1298 : * inc/decrement in the thread struct).
1299 : *
1300 : * @note This works by elevating the thread priority temporarily to a
1301 : * cooperative priority, allowing cheap synchronization vs. other
1302 : * preemptible or cooperative threads running on the current CPU. It
1303 : * does not prevent preemption or asynchrony of other types. It does
1304 : * not prevent threads from running on other CPUs when CONFIG_SMP=y.
1305 : * It does not prevent interrupts from happening, nor does it prevent
1306 : * threads with MetaIRQ priorities from preempting the current thread.
1307 : * In general this is a historical API not well-suited to modern
1308 : * applications, use with care.
1309 : */
1310 1 : void k_sched_lock(void);
1311 :
1312 : /**
1313 : * @brief Unlock the scheduler.
1314 : *
1315 : * This routine reverses the effect of a previous call to k_sched_lock().
1316 : * A thread must call the routine once for each time it called k_sched_lock()
1317 : * before the thread becomes preemptible.
1318 : */
1319 1 : void k_sched_unlock(void);
1320 :
1321 : /**
1322 : * @brief Set current thread's custom data.
1323 : *
1324 : * This routine sets the custom data for the current thread to @ value.
1325 : *
1326 : * Custom data is not used by the kernel itself, and is freely available
1327 : * for a thread to use as it sees fit. It can be used as a framework
1328 : * upon which to build thread-local storage.
1329 : *
1330 : * @param value New custom data value.
1331 : *
1332 : */
1333 1 : __syscall void k_thread_custom_data_set(void *value);
1334 :
1335 : /**
1336 : * @brief Get current thread's custom data.
1337 : *
1338 : * This routine returns the custom data for the current thread.
1339 : *
1340 : * @return Current custom data value.
1341 : */
1342 1 : __syscall void *k_thread_custom_data_get(void);
1343 :
1344 : /**
1345 : * @brief Set current thread name
1346 : *
1347 : * Set the name of the thread to be used when @kconfig{CONFIG_THREAD_MONITOR}
1348 : * is enabled for tracing and debugging.
1349 : *
1350 : * @param thread Thread to set name, or NULL to set the current thread
1351 : * @param str Name string
1352 : * @retval 0 on success
1353 : * @retval -EFAULT Memory access error with supplied string
1354 : * @retval -ENOSYS Thread name configuration option not enabled
1355 : * @retval -EINVAL Thread name too long
1356 : */
1357 1 : __syscall int k_thread_name_set(k_tid_t thread, const char *str);
1358 :
1359 : /**
1360 : * @brief Get thread name
1361 : *
1362 : * Get the name of a thread
1363 : *
1364 : * @param thread Thread ID
1365 : * @retval Thread name, or NULL if configuration not enabled
1366 : */
1367 1 : const char *k_thread_name_get(k_tid_t thread);
1368 :
1369 : /**
1370 : * @brief Copy the thread name into a supplied buffer
1371 : *
1372 : * @param thread Thread to obtain name information
1373 : * @param buf Destination buffer
1374 : * @param size Destination buffer size
1375 : * @retval -ENOSPC Destination buffer too small
1376 : * @retval -EFAULT Memory access error
1377 : * @retval -ENOSYS Thread name feature not enabled
1378 : * @retval 0 Success
1379 : */
1380 1 : __syscall int k_thread_name_copy(k_tid_t thread, char *buf,
1381 : size_t size);
1382 :
1383 : /**
1384 : * @brief Get thread state string
1385 : *
1386 : * This routine generates a human friendly string containing the thread's
1387 : * state, and copies as much of it as possible into @a buf.
1388 : *
1389 : * @param thread_id Thread ID
1390 : * @param buf Buffer into which to copy state strings
1391 : * @param buf_size Size of the buffer
1392 : *
1393 : * @retval Pointer to @a buf if data was copied, else a pointer to "".
1394 : */
1395 1 : const char *k_thread_state_str(k_tid_t thread_id, char *buf, size_t buf_size);
1396 :
1397 : /**
1398 : * @}
1399 : */
1400 :
1401 : /**
1402 : * @addtogroup clock_apis
1403 : * @{
1404 : */
1405 :
1406 : /**
1407 : * @brief Generate null timeout delay.
1408 : *
1409 : * This macro generates a timeout delay that instructs a kernel API
1410 : * not to wait if the requested operation cannot be performed immediately.
1411 : *
1412 : * @return Timeout delay value.
1413 : */
1414 1 : #define K_NO_WAIT Z_TIMEOUT_NO_WAIT
1415 :
1416 : /**
1417 : * @brief Generate timeout delay from nanoseconds.
1418 : *
1419 : * This macro generates a timeout delay that instructs a kernel API to
1420 : * wait up to @a t nanoseconds to perform the requested operation.
1421 : * Note that timer precision is limited to the tick rate, not the
1422 : * requested value.
1423 : *
1424 : * @param t Duration in nanoseconds.
1425 : *
1426 : * @return Timeout delay value.
1427 : */
1428 1 : #define K_NSEC(t) Z_TIMEOUT_NS(t)
1429 :
1430 : /**
1431 : * @brief Generate timeout delay from microseconds.
1432 : *
1433 : * This macro generates a timeout delay that instructs a kernel API
1434 : * to wait up to @a t microseconds to perform the requested operation.
1435 : * Note that timer precision is limited to the tick rate, not the
1436 : * requested value.
1437 : *
1438 : * @param t Duration in microseconds.
1439 : *
1440 : * @return Timeout delay value.
1441 : */
1442 1 : #define K_USEC(t) Z_TIMEOUT_US(t)
1443 :
1444 : /**
1445 : * @brief Generate timeout delay from cycles.
1446 : *
1447 : * This macro generates a timeout delay that instructs a kernel API
1448 : * to wait up to @a t cycles to perform the requested operation.
1449 : *
1450 : * @param t Duration in cycles.
1451 : *
1452 : * @return Timeout delay value.
1453 : */
1454 1 : #define K_CYC(t) Z_TIMEOUT_CYC(t)
1455 :
1456 : /**
1457 : * @brief Generate timeout delay from system ticks.
1458 : *
1459 : * This macro generates a timeout delay that instructs a kernel API
1460 : * to wait up to @a t ticks to perform the requested operation.
1461 : *
1462 : * @param t Duration in system ticks.
1463 : *
1464 : * @return Timeout delay value.
1465 : */
1466 1 : #define K_TICKS(t) Z_TIMEOUT_TICKS(t)
1467 :
1468 : /**
1469 : * @brief Generate timeout delay from milliseconds.
1470 : *
1471 : * This macro generates a timeout delay that instructs a kernel API
1472 : * to wait up to @a ms milliseconds to perform the requested operation.
1473 : *
1474 : * @param ms Duration in milliseconds.
1475 : *
1476 : * @return Timeout delay value.
1477 : */
1478 1 : #define K_MSEC(ms) Z_TIMEOUT_MS(ms)
1479 :
1480 : /**
1481 : * @brief Generate timeout delay from seconds.
1482 : *
1483 : * This macro generates a timeout delay that instructs a kernel API
1484 : * to wait up to @a s seconds to perform the requested operation.
1485 : *
1486 : * @param s Duration in seconds.
1487 : *
1488 : * @return Timeout delay value.
1489 : */
1490 1 : #define K_SECONDS(s) K_MSEC((s) * MSEC_PER_SEC)
1491 :
1492 : /**
1493 : * @brief Generate timeout delay from minutes.
1494 :
1495 : * This macro generates a timeout delay that instructs a kernel API
1496 : * to wait up to @a m minutes to perform the requested operation.
1497 : *
1498 : * @param m Duration in minutes.
1499 : *
1500 : * @return Timeout delay value.
1501 : */
1502 1 : #define K_MINUTES(m) K_SECONDS((m) * 60)
1503 :
1504 : /**
1505 : * @brief Generate timeout delay from hours.
1506 : *
1507 : * This macro generates a timeout delay that instructs a kernel API
1508 : * to wait up to @a h hours to perform the requested operation.
1509 : *
1510 : * @param h Duration in hours.
1511 : *
1512 : * @return Timeout delay value.
1513 : */
1514 1 : #define K_HOURS(h) K_MINUTES((h) * 60)
1515 :
1516 : /**
1517 : * @brief Generate infinite timeout delay.
1518 : *
1519 : * This macro generates a timeout delay that instructs a kernel API
1520 : * to wait as long as necessary to perform the requested operation.
1521 : *
1522 : * @return Timeout delay value.
1523 : */
1524 1 : #define K_FOREVER Z_FOREVER
1525 :
1526 : #ifdef CONFIG_TIMEOUT_64BIT
1527 :
1528 : /**
1529 : * @brief Generates an absolute/uptime timeout value from system ticks
1530 : *
1531 : * This macro generates a timeout delay that represents an expiration
1532 : * at the absolute uptime value specified, in system ticks. That is, the
1533 : * timeout will expire immediately after the system uptime reaches the
1534 : * specified tick count. Value is clamped to the range 0 to INT64_MAX-1.
1535 : *
1536 : * @param t Tick uptime value
1537 : * @return Timeout delay value
1538 : */
1539 : #define K_TIMEOUT_ABS_TICKS(t) \
1540 : Z_TIMEOUT_TICKS(Z_TICK_ABS((k_ticks_t)CLAMP(t, 0, (INT64_MAX - 1))))
1541 :
1542 : /**
1543 : * @brief Generates an absolute/uptime timeout value from seconds
1544 : *
1545 : * This macro generates a timeout delay that represents an expiration
1546 : * at the absolute uptime value specified, in seconds. That is, the
1547 : * timeout will expire immediately after the system uptime reaches the
1548 : * specified tick count.
1549 : *
1550 : * @param t Second uptime value
1551 : * @return Timeout delay value
1552 : */
1553 : #define K_TIMEOUT_ABS_SEC(t) K_TIMEOUT_ABS_TICKS(k_sec_to_ticks_ceil64(t))
1554 :
1555 : /**
1556 : * @brief Generates an absolute/uptime timeout value from milliseconds
1557 : *
1558 : * This macro generates a timeout delay that represents an expiration
1559 : * at the absolute uptime value specified, in milliseconds. That is,
1560 : * the timeout will expire immediately after the system uptime reaches
1561 : * the specified tick count.
1562 : *
1563 : * @param t Millisecond uptime value
1564 : * @return Timeout delay value
1565 : */
1566 : #define K_TIMEOUT_ABS_MS(t) K_TIMEOUT_ABS_TICKS(k_ms_to_ticks_ceil64(t))
1567 :
1568 : /**
1569 : * @brief Generates an absolute/uptime timeout value from microseconds
1570 : *
1571 : * This macro generates a timeout delay that represents an expiration
1572 : * at the absolute uptime value specified, in microseconds. That is,
1573 : * the timeout will expire immediately after the system uptime reaches
1574 : * the specified time. Note that timer precision is limited by the
1575 : * system tick rate and not the requested timeout value.
1576 : *
1577 : * @param t Microsecond uptime value
1578 : * @return Timeout delay value
1579 : */
1580 : #define K_TIMEOUT_ABS_US(t) K_TIMEOUT_ABS_TICKS(k_us_to_ticks_ceil64(t))
1581 :
1582 : /**
1583 : * @brief Generates an absolute/uptime timeout value from nanoseconds
1584 : *
1585 : * This macro generates a timeout delay that represents an expiration
1586 : * at the absolute uptime value specified, in nanoseconds. That is,
1587 : * the timeout will expire immediately after the system uptime reaches
1588 : * the specified time. Note that timer precision is limited by the
1589 : * system tick rate and not the requested timeout value.
1590 : *
1591 : * @param t Nanosecond uptime value
1592 : * @return Timeout delay value
1593 : */
1594 : #define K_TIMEOUT_ABS_NS(t) K_TIMEOUT_ABS_TICKS(k_ns_to_ticks_ceil64(t))
1595 :
1596 : /**
1597 : * @brief Generates an absolute/uptime timeout value from system cycles
1598 : *
1599 : * This macro generates a timeout delay that represents an expiration
1600 : * at the absolute uptime value specified, in cycles. That is, the
1601 : * timeout will expire immediately after the system uptime reaches the
1602 : * specified time. Note that timer precision is limited by the system
1603 : * tick rate and not the requested timeout value.
1604 : *
1605 : * @param t Cycle uptime value
1606 : * @return Timeout delay value
1607 : */
1608 : #define K_TIMEOUT_ABS_CYC(t) K_TIMEOUT_ABS_TICKS(k_cyc_to_ticks_ceil64(t))
1609 :
1610 : #endif
1611 :
1612 : /**
1613 : * @}
1614 : */
1615 :
1616 : /**
1617 : * @brief Kernel timer structure
1618 : *
1619 : * This structure is used to represent a kernel timer.
1620 : * All the members are internal and should not be accessed directly.
1621 : */
1622 1 : struct k_timer {
1623 : /**
1624 : * @cond INTERNAL_HIDDEN
1625 : */
1626 :
1627 : /*
1628 : * _timeout structure must be first here if we want to use
1629 : * dynamic timer allocation. timeout.node is used in the double-linked
1630 : * list of free timers
1631 : */
1632 : struct _timeout timeout;
1633 :
1634 : /* wait queue for the (single) thread waiting on this timer */
1635 : _wait_q_t wait_q;
1636 :
1637 : /* runs in ISR context */
1638 : void (*expiry_fn)(struct k_timer *timer);
1639 :
1640 : /* runs in the context of the thread that calls k_timer_stop() */
1641 : void (*stop_fn)(struct k_timer *timer);
1642 :
1643 : /* timer period */
1644 : k_timeout_t period;
1645 :
1646 : /* timer status */
1647 : uint32_t status;
1648 :
1649 : /* user-specific data, also used to support legacy features */
1650 : void *user_data;
1651 :
1652 : SYS_PORT_TRACING_TRACKING_FIELD(k_timer)
1653 :
1654 : #ifdef CONFIG_OBJ_CORE_TIMER
1655 : struct k_obj_core obj_core;
1656 : #endif
1657 : /**
1658 : * INTERNAL_HIDDEN @endcond
1659 : */
1660 : };
1661 :
1662 : /**
1663 : * @cond INTERNAL_HIDDEN
1664 : */
1665 : #define Z_TIMER_INITIALIZER(obj, expiry, stop) \
1666 : { \
1667 : .timeout = { \
1668 : .node = {},\
1669 : .fn = z_timer_expiration_handler, \
1670 : .dticks = 0, \
1671 : }, \
1672 : .wait_q = Z_WAIT_Q_INIT(&obj.wait_q), \
1673 : .expiry_fn = expiry, \
1674 : .stop_fn = stop, \
1675 : .period = {}, \
1676 : .status = 0, \
1677 : .user_data = 0, \
1678 : }
1679 :
1680 : /**
1681 : * INTERNAL_HIDDEN @endcond
1682 : */
1683 :
1684 : /**
1685 : * @defgroup timer_apis Timer APIs
1686 : * @ingroup kernel_apis
1687 : * @{
1688 : */
1689 :
1690 : /**
1691 : * @typedef k_timer_expiry_t
1692 : * @brief Timer expiry function type.
1693 : *
1694 : * A timer's expiry function is executed by the system clock interrupt handler
1695 : * each time the timer expires. The expiry function is optional, and is only
1696 : * invoked if the timer has been initialized with one.
1697 : *
1698 : * @param timer Address of timer.
1699 : */
1700 1 : typedef void (*k_timer_expiry_t)(struct k_timer *timer);
1701 :
1702 : /**
1703 : * @typedef k_timer_stop_t
1704 : * @brief Timer stop function type.
1705 : *
1706 : * A timer's stop function is executed if the timer is stopped prematurely.
1707 : * The function runs in the context of call that stops the timer. As
1708 : * k_timer_stop() can be invoked from an ISR, the stop function must be
1709 : * callable from interrupt context (isr-ok).
1710 : *
1711 : * The stop function is optional, and is only invoked if the timer has been
1712 : * initialized with one.
1713 : *
1714 : * @param timer Address of timer.
1715 : */
1716 1 : typedef void (*k_timer_stop_t)(struct k_timer *timer);
1717 :
1718 : /**
1719 : * @brief Statically define and initialize a timer.
1720 : *
1721 : * The timer can be accessed outside the module where it is defined using:
1722 : *
1723 : * @code extern struct k_timer <name>; @endcode
1724 : *
1725 : * @param name Name of the timer variable.
1726 : * @param expiry_fn Function to invoke each time the timer expires.
1727 : * @param stop_fn Function to invoke if the timer is stopped while running.
1728 : */
1729 1 : #define K_TIMER_DEFINE(name, expiry_fn, stop_fn) \
1730 : STRUCT_SECTION_ITERABLE(k_timer, name) = \
1731 : Z_TIMER_INITIALIZER(name, expiry_fn, stop_fn)
1732 :
1733 : /**
1734 : * @brief Initialize a timer.
1735 : *
1736 : * This routine initializes a timer, prior to its first use.
1737 : *
1738 : * @param timer Address of timer.
1739 : * @param expiry_fn Function to invoke each time the timer expires.
1740 : * @param stop_fn Function to invoke if the timer is stopped while running.
1741 : */
1742 1 : void k_timer_init(struct k_timer *timer,
1743 : k_timer_expiry_t expiry_fn,
1744 : k_timer_stop_t stop_fn);
1745 :
1746 : /**
1747 : * @brief Start a timer.
1748 : *
1749 : * This routine starts a timer, and resets its status to zero. The timer
1750 : * begins counting down using the specified duration and period values.
1751 : *
1752 : * Attempting to start a timer that is already running is permitted.
1753 : * The timer's status is reset to zero and the timer begins counting down
1754 : * using the new duration and period values.
1755 : *
1756 : * This routine neither updates nor has any other effect on the specified
1757 : * timer if @a duration is K_FOREVER.
1758 : *
1759 : * @param timer Address of timer.
1760 : * @param duration Initial timer duration.
1761 : * @param period Timer period.
1762 : */
1763 1 : __syscall void k_timer_start(struct k_timer *timer,
1764 : k_timeout_t duration, k_timeout_t period);
1765 :
1766 : /**
1767 : * @brief Stop a timer.
1768 : *
1769 : * This routine stops a running timer prematurely. The timer's stop function,
1770 : * if one exists, is invoked by the caller.
1771 : *
1772 : * Attempting to stop a timer that is not running is permitted, but has no
1773 : * effect on the timer.
1774 : *
1775 : * @note The stop handler has to be callable from ISRs if @a k_timer_stop is to
1776 : * be called from ISRs.
1777 : *
1778 : * @funcprops \isr_ok
1779 : *
1780 : * @param timer Address of timer.
1781 : */
1782 1 : __syscall void k_timer_stop(struct k_timer *timer);
1783 :
1784 : /**
1785 : * @brief Read timer status.
1786 : *
1787 : * This routine reads the timer's status, which indicates the number of times
1788 : * it has expired since its status was last read.
1789 : *
1790 : * Calling this routine resets the timer's status to zero.
1791 : *
1792 : * @param timer Address of timer.
1793 : *
1794 : * @return Timer status.
1795 : */
1796 1 : __syscall uint32_t k_timer_status_get(struct k_timer *timer);
1797 :
1798 : /**
1799 : * @brief Synchronize thread to timer expiration.
1800 : *
1801 : * This routine blocks the calling thread until the timer's status is non-zero
1802 : * (indicating that it has expired at least once since it was last examined)
1803 : * or the timer is stopped. If the timer status is already non-zero,
1804 : * or the timer is already stopped, the caller continues without waiting.
1805 : *
1806 : * Calling this routine resets the timer's status to zero.
1807 : *
1808 : * This routine must not be used by interrupt handlers, since they are not
1809 : * allowed to block.
1810 : *
1811 : * @param timer Address of timer.
1812 : *
1813 : * @return Timer status.
1814 : */
1815 1 : __syscall uint32_t k_timer_status_sync(struct k_timer *timer);
1816 :
1817 : #ifdef CONFIG_SYS_CLOCK_EXISTS
1818 :
1819 : /**
1820 : * @brief Get next expiration time of a timer, in system ticks
1821 : *
1822 : * This routine returns the future system uptime reached at the next
1823 : * time of expiration of the timer, in units of system ticks. If the
1824 : * timer is not running, current system time is returned.
1825 : *
1826 : * @param timer The timer object
1827 : * @return Uptime of expiration, in ticks
1828 : */
1829 1 : __syscall k_ticks_t k_timer_expires_ticks(const struct k_timer *timer);
1830 :
1831 : static inline k_ticks_t z_impl_k_timer_expires_ticks(
1832 : const struct k_timer *timer)
1833 : {
1834 : return z_timeout_expires(&timer->timeout);
1835 : }
1836 :
1837 : /**
1838 : * @brief Get time remaining before a timer next expires, in system ticks
1839 : *
1840 : * This routine computes the time remaining before a running timer
1841 : * next expires, in units of system ticks. If the timer is not
1842 : * running, it returns zero.
1843 : *
1844 : * @param timer The timer object
1845 : * @return Remaining time until expiration, in ticks
1846 : */
1847 1 : __syscall k_ticks_t k_timer_remaining_ticks(const struct k_timer *timer);
1848 :
1849 : static inline k_ticks_t z_impl_k_timer_remaining_ticks(
1850 : const struct k_timer *timer)
1851 : {
1852 : return z_timeout_remaining(&timer->timeout);
1853 : }
1854 :
1855 : /**
1856 : * @brief Get time remaining before a timer next expires.
1857 : *
1858 : * This routine computes the (approximate) time remaining before a running
1859 : * timer next expires. If the timer is not running, it returns zero.
1860 : *
1861 : * @param timer Address of timer.
1862 : *
1863 : * @return Remaining time (in milliseconds).
1864 : */
1865 1 : static inline uint32_t k_timer_remaining_get(struct k_timer *timer)
1866 : {
1867 : return k_ticks_to_ms_floor32(k_timer_remaining_ticks(timer));
1868 : }
1869 :
1870 : #endif /* CONFIG_SYS_CLOCK_EXISTS */
1871 :
1872 : /**
1873 : * @brief Associate user-specific data with a timer.
1874 : *
1875 : * This routine records the @a user_data with the @a timer, to be retrieved
1876 : * later.
1877 : *
1878 : * It can be used e.g. in a timer handler shared across multiple subsystems to
1879 : * retrieve data specific to the subsystem this timer is associated with.
1880 : *
1881 : * @param timer Address of timer.
1882 : * @param user_data User data to associate with the timer.
1883 : */
1884 1 : __syscall void k_timer_user_data_set(struct k_timer *timer, void *user_data);
1885 :
1886 : /**
1887 : * @internal
1888 : */
1889 : static inline void z_impl_k_timer_user_data_set(struct k_timer *timer,
1890 : void *user_data)
1891 : {
1892 : timer->user_data = user_data;
1893 : }
1894 :
1895 : /**
1896 : * @brief Retrieve the user-specific data from a timer.
1897 : *
1898 : * @param timer Address of timer.
1899 : *
1900 : * @return The user data.
1901 : */
1902 1 : __syscall void *k_timer_user_data_get(const struct k_timer *timer);
1903 :
1904 : static inline void *z_impl_k_timer_user_data_get(const struct k_timer *timer)
1905 : {
1906 : return timer->user_data;
1907 : }
1908 :
1909 : /** @} */
1910 :
1911 : /**
1912 : * @addtogroup clock_apis
1913 : * @ingroup kernel_apis
1914 : * @{
1915 : */
1916 :
1917 : /**
1918 : * @brief Get system uptime, in system ticks.
1919 : *
1920 : * This routine returns the elapsed time since the system booted, in
1921 : * ticks (c.f. @kconfig{CONFIG_SYS_CLOCK_TICKS_PER_SEC}), which is the
1922 : * fundamental unit of resolution of kernel timekeeping.
1923 : *
1924 : * @return Current uptime in ticks.
1925 : */
1926 1 : __syscall int64_t k_uptime_ticks(void);
1927 :
1928 : /**
1929 : * @brief Get system uptime.
1930 : *
1931 : * This routine returns the elapsed time since the system booted,
1932 : * in milliseconds.
1933 : *
1934 : * @note
1935 : * While this function returns time in milliseconds, it does
1936 : * not mean it has millisecond resolution. The actual resolution depends on
1937 : * @kconfig{CONFIG_SYS_CLOCK_TICKS_PER_SEC} config option.
1938 : *
1939 : * @return Current uptime in milliseconds.
1940 : */
1941 1 : static inline int64_t k_uptime_get(void)
1942 : {
1943 : return k_ticks_to_ms_floor64(k_uptime_ticks());
1944 : }
1945 :
1946 : /**
1947 : * @brief Get system uptime (32-bit version).
1948 : *
1949 : * This routine returns the lower 32 bits of the system uptime in
1950 : * milliseconds.
1951 : *
1952 : * Because correct conversion requires full precision of the system
1953 : * clock there is no benefit to using this over k_uptime_get() unless
1954 : * you know the application will never run long enough for the system
1955 : * clock to approach 2^32 ticks. Calls to this function may involve
1956 : * interrupt blocking and 64-bit math.
1957 : *
1958 : * @note
1959 : * While this function returns time in milliseconds, it does
1960 : * not mean it has millisecond resolution. The actual resolution depends on
1961 : * @kconfig{CONFIG_SYS_CLOCK_TICKS_PER_SEC} config option
1962 : *
1963 : * @return The low 32 bits of the current uptime, in milliseconds.
1964 : */
1965 1 : static inline uint32_t k_uptime_get_32(void)
1966 : {
1967 : return (uint32_t)k_uptime_get();
1968 : }
1969 :
1970 : /**
1971 : * @brief Get system uptime in seconds.
1972 : *
1973 : * This routine returns the elapsed time since the system booted,
1974 : * in seconds.
1975 : *
1976 : * @return Current uptime in seconds.
1977 : */
1978 1 : static inline uint32_t k_uptime_seconds(void)
1979 : {
1980 : return k_ticks_to_sec_floor32(k_uptime_ticks());
1981 : }
1982 :
1983 : /**
1984 : * @brief Get elapsed time.
1985 : *
1986 : * This routine computes the elapsed time between the current system uptime
1987 : * and an earlier reference time, in milliseconds.
1988 : *
1989 : * @param reftime Pointer to a reference time, which is updated to the current
1990 : * uptime upon return.
1991 : *
1992 : * @return Elapsed time.
1993 : */
1994 1 : static inline int64_t k_uptime_delta(int64_t *reftime)
1995 : {
1996 : int64_t uptime, delta;
1997 :
1998 : uptime = k_uptime_get();
1999 : delta = uptime - *reftime;
2000 : *reftime = uptime;
2001 :
2002 : return delta;
2003 : }
2004 :
2005 : /**
2006 : * @brief Read the hardware clock.
2007 : *
2008 : * This routine returns the current time, as measured by the system's hardware
2009 : * clock.
2010 : *
2011 : * @return Current hardware clock up-counter (in cycles).
2012 : */
2013 1 : static inline uint32_t k_cycle_get_32(void)
2014 : {
2015 : return arch_k_cycle_get_32();
2016 : }
2017 :
2018 : /**
2019 : * @brief Read the 64-bit hardware clock.
2020 : *
2021 : * This routine returns the current time in 64-bits, as measured by the
2022 : * system's hardware clock, if available.
2023 : *
2024 : * @see CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER
2025 : *
2026 : * @return Current hardware clock up-counter (in cycles).
2027 : */
2028 1 : static inline uint64_t k_cycle_get_64(void)
2029 : {
2030 : if (!IS_ENABLED(CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER)) {
2031 : __ASSERT(0, "64-bit cycle counter not enabled on this platform. "
2032 : "See CONFIG_TIMER_HAS_64BIT_CYCLE_COUNTER");
2033 : return 0;
2034 : }
2035 :
2036 : return arch_k_cycle_get_64();
2037 : }
2038 :
2039 : /**
2040 : * @}
2041 : */
2042 :
2043 0 : struct k_queue {
2044 0 : sys_sflist_t data_q;
2045 0 : struct k_spinlock lock;
2046 0 : _wait_q_t wait_q;
2047 :
2048 : Z_DECL_POLL_EVENT
2049 :
2050 : SYS_PORT_TRACING_TRACKING_FIELD(k_queue)
2051 : };
2052 :
2053 : /**
2054 : * @cond INTERNAL_HIDDEN
2055 : */
2056 :
2057 : #define Z_QUEUE_INITIALIZER(obj) \
2058 : { \
2059 : .data_q = SYS_SFLIST_STATIC_INIT(&obj.data_q), \
2060 : .lock = { }, \
2061 : .wait_q = Z_WAIT_Q_INIT(&obj.wait_q), \
2062 : Z_POLL_EVENT_OBJ_INIT(obj) \
2063 : }
2064 :
2065 : /**
2066 : * INTERNAL_HIDDEN @endcond
2067 : */
2068 :
2069 : /**
2070 : * @defgroup queue_apis Queue APIs
2071 : * @ingroup kernel_apis
2072 : * @{
2073 : */
2074 :
2075 : /**
2076 : * @brief Initialize a queue.
2077 : *
2078 : * This routine initializes a queue object, prior to its first use.
2079 : *
2080 : * @param queue Address of the queue.
2081 : */
2082 1 : __syscall void k_queue_init(struct k_queue *queue);
2083 :
2084 : /**
2085 : * @brief Cancel waiting on a queue.
2086 : *
2087 : * This routine causes first thread pending on @a queue, if any, to
2088 : * return from k_queue_get() call with NULL value (as if timeout expired).
2089 : * If the queue is being waited on by k_poll(), it will return with
2090 : * -EINTR and K_POLL_STATE_CANCELLED state (and per above, subsequent
2091 : * k_queue_get() will return NULL).
2092 : *
2093 : * @funcprops \isr_ok
2094 : *
2095 : * @param queue Address of the queue.
2096 : */
2097 1 : __syscall void k_queue_cancel_wait(struct k_queue *queue);
2098 :
2099 : /**
2100 : * @brief Append an element to the end of a queue.
2101 : *
2102 : * This routine appends a data item to @a queue. A queue data item must be
2103 : * aligned on a word boundary, and the first word of the item is reserved
2104 : * for the kernel's use.
2105 : *
2106 : * @funcprops \isr_ok
2107 : *
2108 : * @param queue Address of the queue.
2109 : * @param data Address of the data item.
2110 : */
2111 1 : void k_queue_append(struct k_queue *queue, void *data);
2112 :
2113 : /**
2114 : * @brief Append an element to a queue.
2115 : *
2116 : * This routine appends a data item to @a queue. There is an implicit memory
2117 : * allocation to create an additional temporary bookkeeping data structure from
2118 : * the calling thread's resource pool, which is automatically freed when the
2119 : * item is removed. The data itself is not copied.
2120 : *
2121 : * @funcprops \isr_ok
2122 : *
2123 : * @param queue Address of the queue.
2124 : * @param data Address of the data item.
2125 : *
2126 : * @retval 0 on success
2127 : * @retval -ENOMEM if there isn't sufficient RAM in the caller's resource pool
2128 : */
2129 1 : __syscall int32_t k_queue_alloc_append(struct k_queue *queue, void *data);
2130 :
2131 : /**
2132 : * @brief Prepend an element to a queue.
2133 : *
2134 : * This routine prepends a data item to @a queue. A queue data item must be
2135 : * aligned on a word boundary, and the first word of the item is reserved
2136 : * for the kernel's use.
2137 : *
2138 : * @funcprops \isr_ok
2139 : *
2140 : * @param queue Address of the queue.
2141 : * @param data Address of the data item.
2142 : */
2143 1 : void k_queue_prepend(struct k_queue *queue, void *data);
2144 :
2145 : /**
2146 : * @brief Prepend an element to a queue.
2147 : *
2148 : * This routine prepends a data item to @a queue. There is an implicit memory
2149 : * allocation to create an additional temporary bookkeeping data structure from
2150 : * the calling thread's resource pool, which is automatically freed when the
2151 : * item is removed. The data itself is not copied.
2152 : *
2153 : * @funcprops \isr_ok
2154 : *
2155 : * @param queue Address of the queue.
2156 : * @param data Address of the data item.
2157 : *
2158 : * @retval 0 on success
2159 : * @retval -ENOMEM if there isn't sufficient RAM in the caller's resource pool
2160 : */
2161 1 : __syscall int32_t k_queue_alloc_prepend(struct k_queue *queue, void *data);
2162 :
2163 : /**
2164 : * @brief Inserts an element to a queue.
2165 : *
2166 : * This routine inserts a data item to @a queue after previous item. A queue
2167 : * data item must be aligned on a word boundary, and the first word of
2168 : * the item is reserved for the kernel's use.
2169 : *
2170 : * @funcprops \isr_ok
2171 : *
2172 : * @param queue Address of the queue.
2173 : * @param prev Address of the previous data item.
2174 : * @param data Address of the data item.
2175 : */
2176 1 : void k_queue_insert(struct k_queue *queue, void *prev, void *data);
2177 :
2178 : /**
2179 : * @brief Atomically append a list of elements to a queue.
2180 : *
2181 : * This routine adds a list of data items to @a queue in one operation.
2182 : * The data items must be in a singly-linked list, with the first word
2183 : * in each data item pointing to the next data item; the list must be
2184 : * NULL-terminated.
2185 : *
2186 : * @funcprops \isr_ok
2187 : *
2188 : * @param queue Address of the queue.
2189 : * @param head Pointer to first node in singly-linked list.
2190 : * @param tail Pointer to last node in singly-linked list.
2191 : *
2192 : * @retval 0 on success
2193 : * @retval -EINVAL on invalid supplied data
2194 : *
2195 : */
2196 1 : int k_queue_append_list(struct k_queue *queue, void *head, void *tail);
2197 :
2198 : /**
2199 : * @brief Atomically add a list of elements to a queue.
2200 : *
2201 : * This routine adds a list of data items to @a queue in one operation.
2202 : * The data items must be in a singly-linked list implemented using a
2203 : * sys_slist_t object. Upon completion, the original list is empty.
2204 : *
2205 : * @funcprops \isr_ok
2206 : *
2207 : * @param queue Address of the queue.
2208 : * @param list Pointer to sys_slist_t object.
2209 : *
2210 : * @retval 0 on success
2211 : * @retval -EINVAL on invalid data
2212 : */
2213 1 : int k_queue_merge_slist(struct k_queue *queue, sys_slist_t *list);
2214 :
2215 : /**
2216 : * @brief Get an element from a queue.
2217 : *
2218 : * This routine removes first data item from @a queue. The first word of the
2219 : * data item is reserved for the kernel's use.
2220 : *
2221 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
2222 : *
2223 : * @funcprops \isr_ok
2224 : *
2225 : * @param queue Address of the queue.
2226 : * @param timeout Waiting period to obtain a data item, or one of the special
2227 : * values K_NO_WAIT and K_FOREVER.
2228 : *
2229 : * @return Address of the data item if successful; NULL if returned
2230 : * without waiting, or waiting period timed out.
2231 : */
2232 1 : __syscall void *k_queue_get(struct k_queue *queue, k_timeout_t timeout);
2233 :
2234 : /**
2235 : * @brief Remove an element from a queue.
2236 : *
2237 : * This routine removes data item from @a queue. The first word of the
2238 : * data item is reserved for the kernel's use. Removing elements from k_queue
2239 : * rely on sys_slist_find_and_remove which is not a constant time operation.
2240 : *
2241 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
2242 : *
2243 : * @funcprops \isr_ok
2244 : *
2245 : * @param queue Address of the queue.
2246 : * @param data Address of the data item.
2247 : *
2248 : * @return true if data item was removed
2249 : */
2250 1 : bool k_queue_remove(struct k_queue *queue, void *data);
2251 :
2252 : /**
2253 : * @brief Append an element to a queue only if it's not present already.
2254 : *
2255 : * This routine appends data item to @a queue. The first word of the data
2256 : * item is reserved for the kernel's use. Appending elements to k_queue
2257 : * relies on sys_slist_is_node_in_list which is not a constant time operation.
2258 : *
2259 : * @funcprops \isr_ok
2260 : *
2261 : * @param queue Address of the queue.
2262 : * @param data Address of the data item.
2263 : *
2264 : * @return true if data item was added, false if not
2265 : */
2266 1 : bool k_queue_unique_append(struct k_queue *queue, void *data);
2267 :
2268 : /**
2269 : * @brief Query a queue to see if it has data available.
2270 : *
2271 : * Note that the data might be already gone by the time this function returns
2272 : * if other threads are also trying to read from the queue.
2273 : *
2274 : * @funcprops \isr_ok
2275 : *
2276 : * @param queue Address of the queue.
2277 : *
2278 : * @return Non-zero if the queue is empty.
2279 : * @return 0 if data is available.
2280 : */
2281 1 : __syscall int k_queue_is_empty(struct k_queue *queue);
2282 :
2283 : static inline int z_impl_k_queue_is_empty(struct k_queue *queue)
2284 : {
2285 : return sys_sflist_is_empty(&queue->data_q) ? 1 : 0;
2286 : }
2287 :
2288 : /**
2289 : * @brief Peek element at the head of queue.
2290 : *
2291 : * Return element from the head of queue without removing it.
2292 : *
2293 : * @param queue Address of the queue.
2294 : *
2295 : * @return Head element, or NULL if queue is empty.
2296 : */
2297 1 : __syscall void *k_queue_peek_head(struct k_queue *queue);
2298 :
2299 : /**
2300 : * @brief Peek element at the tail of queue.
2301 : *
2302 : * Return element from the tail of queue without removing it.
2303 : *
2304 : * @param queue Address of the queue.
2305 : *
2306 : * @return Tail element, or NULL if queue is empty.
2307 : */
2308 1 : __syscall void *k_queue_peek_tail(struct k_queue *queue);
2309 :
2310 : /**
2311 : * @brief Statically define and initialize a queue.
2312 : *
2313 : * The queue can be accessed outside the module where it is defined using:
2314 : *
2315 : * @code extern struct k_queue <name>; @endcode
2316 : *
2317 : * @param name Name of the queue.
2318 : */
2319 1 : #define K_QUEUE_DEFINE(name) \
2320 : STRUCT_SECTION_ITERABLE(k_queue, name) = \
2321 : Z_QUEUE_INITIALIZER(name)
2322 :
2323 : /** @} */
2324 :
2325 : #ifdef CONFIG_USERSPACE
2326 : /**
2327 : * @brief futex structure
2328 : *
2329 : * A k_futex is a lightweight mutual exclusion primitive designed
2330 : * to minimize kernel involvement. Uncontended operation relies
2331 : * only on atomic access to shared memory. k_futex are tracked as
2332 : * kernel objects and can live in user memory so that any access
2333 : * bypasses the kernel object permission management mechanism.
2334 : */
2335 1 : struct k_futex {
2336 0 : atomic_t val;
2337 : };
2338 :
2339 : /**
2340 : * @brief futex kernel data structure
2341 : *
2342 : * z_futex_data are the helper data structure for k_futex to complete
2343 : * futex contended operation on kernel side, structure z_futex_data
2344 : * of every futex object is invisible in user mode.
2345 : */
2346 : struct z_futex_data {
2347 : _wait_q_t wait_q;
2348 : struct k_spinlock lock;
2349 : };
2350 :
2351 : #define Z_FUTEX_DATA_INITIALIZER(obj) \
2352 : { \
2353 : .wait_q = Z_WAIT_Q_INIT(&obj.wait_q) \
2354 : }
2355 :
2356 : /**
2357 : * @defgroup futex_apis FUTEX APIs
2358 : * @ingroup kernel_apis
2359 : * @{
2360 : */
2361 :
2362 : /**
2363 : * @brief Pend the current thread on a futex
2364 : *
2365 : * Tests that the supplied futex contains the expected value, and if so,
2366 : * goes to sleep until some other thread calls k_futex_wake() on it.
2367 : *
2368 : * @param futex Address of the futex.
2369 : * @param expected Expected value of the futex, if it is different the caller
2370 : * will not wait on it.
2371 : * @param timeout Waiting period on the futex, or one of the special values
2372 : * K_NO_WAIT or K_FOREVER.
2373 : * @retval -EACCES Caller does not have read access to futex address.
2374 : * @retval -EAGAIN If the futex value did not match the expected parameter.
2375 : * @retval -EINVAL Futex parameter address not recognized by the kernel.
2376 : * @retval -ETIMEDOUT Thread woke up due to timeout and not a futex wakeup.
2377 : * @retval 0 if the caller went to sleep and was woken up. The caller
2378 : * should check the futex's value on wakeup to determine if it needs
2379 : * to block again.
2380 : */
2381 1 : __syscall int k_futex_wait(struct k_futex *futex, int expected,
2382 : k_timeout_t timeout);
2383 :
2384 : /**
2385 : * @brief Wake one/all threads pending on a futex
2386 : *
2387 : * Wake up the highest priority thread pending on the supplied futex, or
2388 : * wakeup all the threads pending on the supplied futex, and the behavior
2389 : * depends on wake_all.
2390 : *
2391 : * @param futex Futex to wake up pending threads.
2392 : * @param wake_all If true, wake up all pending threads; If false,
2393 : * wakeup the highest priority thread.
2394 : * @retval -EACCES Caller does not have access to the futex address.
2395 : * @retval -EINVAL Futex parameter address not recognized by the kernel.
2396 : * @retval Number of threads that were woken up.
2397 : */
2398 1 : __syscall int k_futex_wake(struct k_futex *futex, bool wake_all);
2399 :
2400 : /** @} */
2401 : #endif
2402 :
2403 : /**
2404 : * @defgroup event_apis Event APIs
2405 : * @ingroup kernel_apis
2406 : * @{
2407 : */
2408 :
2409 : /**
2410 : * Event Structure
2411 : * @ingroup event_apis
2412 : */
2413 :
2414 : /**
2415 : * @brief Kernel Event structure
2416 : *
2417 : * This structure is used to represent kernel events. All the members
2418 : * are internal and should not be accessed directly.
2419 : */
2420 :
2421 1 : struct k_event {
2422 : /**
2423 : * @cond INTERNAL_HIDDEN
2424 : */
2425 : _wait_q_t wait_q;
2426 : uint32_t events;
2427 : struct k_spinlock lock;
2428 :
2429 : SYS_PORT_TRACING_TRACKING_FIELD(k_event)
2430 :
2431 : #ifdef CONFIG_OBJ_CORE_EVENT
2432 : struct k_obj_core obj_core;
2433 : #endif
2434 : /**
2435 : * INTERNAL_HIDDEN @endcond
2436 : */
2437 :
2438 : };
2439 :
2440 : /**
2441 : * @cond INTERNAL_HIDDEN
2442 : */
2443 :
2444 : #define Z_EVENT_INITIALIZER(obj) \
2445 : { \
2446 : .wait_q = Z_WAIT_Q_INIT(&obj.wait_q), \
2447 : .events = 0, \
2448 : .lock = {}, \
2449 : }
2450 : /**
2451 : * INTERNAL_HIDDEN @endcond
2452 : */
2453 :
2454 : /**
2455 : * @brief Initialize an event object
2456 : *
2457 : * This routine initializes an event object, prior to its first use.
2458 : *
2459 : * @param event Address of the event object.
2460 : */
2461 1 : __syscall void k_event_init(struct k_event *event);
2462 :
2463 : /**
2464 : * @brief Post one or more events to an event object
2465 : *
2466 : * This routine posts one or more events to an event object. All tasks waiting
2467 : * on the event object @a event whose waiting conditions become met by this
2468 : * posting immediately unpend.
2469 : *
2470 : * Posting differs from setting in that posted events are merged together with
2471 : * the current set of events tracked by the event object.
2472 : *
2473 : * @funcprops \isr_ok
2474 : *
2475 : * @param event Address of the event object
2476 : * @param events Set of events to post to @a event
2477 : *
2478 : * @retval Previous value of the events in @a event
2479 : */
2480 1 : __syscall uint32_t k_event_post(struct k_event *event, uint32_t events);
2481 :
2482 : /**
2483 : * @brief Set the events in an event object
2484 : *
2485 : * This routine sets the events stored in event object to the specified value.
2486 : * All tasks waiting on the event object @a event whose waiting conditions
2487 : * become met by this immediately unpend.
2488 : *
2489 : * Setting differs from posting in that set events replace the current set of
2490 : * events tracked by the event object.
2491 : *
2492 : * @funcprops \isr_ok
2493 : *
2494 : * @param event Address of the event object
2495 : * @param events Set of events to set in @a event
2496 : *
2497 : * @retval Previous value of the events in @a event
2498 : */
2499 1 : __syscall uint32_t k_event_set(struct k_event *event, uint32_t events);
2500 :
2501 : /**
2502 : * @brief Set or clear the events in an event object
2503 : *
2504 : * This routine sets the events stored in event object to the specified value.
2505 : * All tasks waiting on the event object @a event whose waiting conditions
2506 : * become met by this immediately unpend. Unlike @ref k_event_set, this routine
2507 : * allows specific event bits to be set and cleared as determined by the mask.
2508 : *
2509 : * @funcprops \isr_ok
2510 : *
2511 : * @param event Address of the event object
2512 : * @param events Set of events to set/clear in @a event
2513 : * @param events_mask Mask to be applied to @a events
2514 : *
2515 : * @retval Previous value of the events in @a events_mask
2516 : */
2517 1 : __syscall uint32_t k_event_set_masked(struct k_event *event, uint32_t events,
2518 : uint32_t events_mask);
2519 :
2520 : /**
2521 : * @brief Clear the events in an event object
2522 : *
2523 : * This routine clears (resets) the specified events stored in an event object.
2524 : *
2525 : * @funcprops \isr_ok
2526 : *
2527 : * @param event Address of the event object
2528 : * @param events Set of events to clear in @a event
2529 : *
2530 : * @retval Previous value of the events in @a event
2531 : */
2532 1 : __syscall uint32_t k_event_clear(struct k_event *event, uint32_t events);
2533 :
2534 : /**
2535 : * @brief Wait for any of the specified events
2536 : *
2537 : * This routine waits on event object @a event until any of the specified
2538 : * events have been delivered to the event object, or the maximum wait time
2539 : * @a timeout has expired. A thread may wait on up to 32 distinctly numbered
2540 : * events that are expressed as bits in a single 32-bit word.
2541 : *
2542 : * @note The caller must be careful when resetting if there are multiple threads
2543 : * waiting for the event object @a event.
2544 : *
2545 : * @note This function may be called from ISR context only when @a timeout is
2546 : * set to K_NO_WAIT.
2547 : *
2548 : * @param event Address of the event object
2549 : * @param events Set of desired events on which to wait
2550 : * @param reset If true, clear the set of events tracked by the event object
2551 : * before waiting. If false, do not clear the events.
2552 : * @param timeout Waiting period for the desired set of events or one of the
2553 : * special values K_NO_WAIT and K_FOREVER.
2554 : *
2555 : * @retval set of matching events upon success
2556 : * @retval 0 if matching events were not received within the specified time
2557 : */
2558 1 : __syscall uint32_t k_event_wait(struct k_event *event, uint32_t events,
2559 : bool reset, k_timeout_t timeout);
2560 :
2561 : /**
2562 : * @brief Wait for all of the specified events
2563 : *
2564 : * This routine waits on event object @a event until all of the specified
2565 : * events have been delivered to the event object, or the maximum wait time
2566 : * @a timeout has expired. A thread may wait on up to 32 distinctly numbered
2567 : * events that are expressed as bits in a single 32-bit word.
2568 : *
2569 : * @note The caller must be careful when resetting if there are multiple threads
2570 : * waiting for the event object @a event.
2571 : *
2572 : * @note This function may be called from ISR context only when @a timeout is
2573 : * set to K_NO_WAIT.
2574 : *
2575 : * @param event Address of the event object
2576 : * @param events Set of desired events on which to wait
2577 : * @param reset If true, clear the set of events tracked by the event object
2578 : * before waiting. If false, do not clear the events.
2579 : * @param timeout Waiting period for the desired set of events or one of the
2580 : * special values K_NO_WAIT and K_FOREVER.
2581 : *
2582 : * @retval set of matching events upon success
2583 : * @retval 0 if matching events were not received within the specified time
2584 : */
2585 1 : __syscall uint32_t k_event_wait_all(struct k_event *event, uint32_t events,
2586 : bool reset, k_timeout_t timeout);
2587 :
2588 : /**
2589 : * @brief Wait for any of the specified events (safe version)
2590 : *
2591 : * This call is nearly identical to @ref k_event_wait with the main difference
2592 : * being that the safe version atomically clears received events from the
2593 : * event object. This mitigates the need for calling @ref k_event_clear, or
2594 : * passing a "reset" argument, since doing so may result in lost event
2595 : * information.
2596 : *
2597 : * @param event Address of the event object
2598 : * @param events Set of desired events on which to wait
2599 : * @param reset If true, clear the set of events tracked by the event object
2600 : * before waiting. If false, do not clear the events.
2601 : * @param timeout Waiting period for the desired set of events or one of the
2602 : * special values K_NO_WAIT and K_FOREVER.
2603 : *
2604 : * @retval set of matching events upon success
2605 : * @retval 0 if no matching event was received within the specified time
2606 : */
2607 1 : __syscall uint32_t k_event_wait_safe(struct k_event *event, uint32_t events,
2608 : bool reset, k_timeout_t timeout);
2609 :
2610 : /**
2611 : * @brief Wait for all of the specified events (safe version)
2612 : *
2613 : * This call is nearly identical to @ref k_event_wait_all with the main
2614 : * difference being that the safe version atomically clears received events
2615 : * from the event object. This mitigates the need for calling
2616 : * @ref k_event_clear, or passing a "reset" argument, since doing so may
2617 : * result in lost event information.
2618 : *
2619 : * @param event Address of the event object
2620 : * @param events Set of desired events on which to wait
2621 : * @param reset If true, clear the set of events tracked by the event object
2622 : * before waiting. If false, do not clear the events.
2623 : * @param timeout Waiting period for the desired set of events or one of the
2624 : * special values K_NO_WAIT and K_FOREVER.
2625 : *
2626 : * @retval set of matching events upon success
2627 : * @retval 0 if all matching events were not received within the specified time
2628 : */
2629 1 : __syscall uint32_t k_event_wait_all_safe(struct k_event *event, uint32_t events,
2630 : bool reset, k_timeout_t timeout);
2631 :
2632 :
2633 :
2634 : /**
2635 : * @brief Test the events currently tracked in the event object
2636 : *
2637 : * @funcprops \isr_ok
2638 : *
2639 : * @param event Address of the event object
2640 : * @param events_mask Set of desired events to test
2641 : *
2642 : * @retval Current value of events in @a events_mask
2643 : */
2644 1 : static inline uint32_t k_event_test(struct k_event *event, uint32_t events_mask)
2645 : {
2646 : return k_event_wait(event, events_mask, false, K_NO_WAIT);
2647 : }
2648 :
2649 : /**
2650 : * @brief Statically define and initialize an event object
2651 : *
2652 : * The event can be accessed outside the module where it is defined using:
2653 : *
2654 : * @code extern struct k_event <name>; @endcode
2655 : *
2656 : * @param name Name of the event object.
2657 : */
2658 1 : #define K_EVENT_DEFINE(name) \
2659 : STRUCT_SECTION_ITERABLE(k_event, name) = \
2660 : Z_EVENT_INITIALIZER(name);
2661 :
2662 : /** @} */
2663 :
2664 0 : struct k_fifo {
2665 : struct k_queue _queue;
2666 : #ifdef CONFIG_OBJ_CORE_FIFO
2667 : struct k_obj_core obj_core;
2668 : #endif
2669 : };
2670 :
2671 : /**
2672 : * @cond INTERNAL_HIDDEN
2673 : */
2674 : #define Z_FIFO_INITIALIZER(obj) \
2675 : { \
2676 : ._queue = Z_QUEUE_INITIALIZER(obj._queue) \
2677 : }
2678 :
2679 : /**
2680 : * INTERNAL_HIDDEN @endcond
2681 : */
2682 :
2683 : /**
2684 : * @defgroup fifo_apis FIFO APIs
2685 : * @ingroup kernel_apis
2686 : * @{
2687 : */
2688 :
2689 : /**
2690 : * @brief Initialize a FIFO queue.
2691 : *
2692 : * This routine initializes a FIFO queue, prior to its first use.
2693 : *
2694 : * @param fifo Address of the FIFO queue.
2695 : */
2696 1 : #define k_fifo_init(fifo) \
2697 : ({ \
2698 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, init, fifo); \
2699 : k_queue_init(&(fifo)->_queue); \
2700 : K_OBJ_CORE_INIT(K_OBJ_CORE(fifo), _obj_type_fifo); \
2701 : K_OBJ_CORE_LINK(K_OBJ_CORE(fifo)); \
2702 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, init, fifo); \
2703 : })
2704 :
2705 : /**
2706 : * @brief Cancel waiting on a FIFO queue.
2707 : *
2708 : * This routine causes first thread pending on @a fifo, if any, to
2709 : * return from k_fifo_get() call with NULL value (as if timeout
2710 : * expired).
2711 : *
2712 : * @funcprops \isr_ok
2713 : *
2714 : * @param fifo Address of the FIFO queue.
2715 : */
2716 1 : #define k_fifo_cancel_wait(fifo) \
2717 : ({ \
2718 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, cancel_wait, fifo); \
2719 : k_queue_cancel_wait(&(fifo)->_queue); \
2720 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, cancel_wait, fifo); \
2721 : })
2722 :
2723 : /**
2724 : * @brief Add an element to a FIFO queue.
2725 : *
2726 : * This routine adds a data item to @a fifo. A FIFO data item must be
2727 : * aligned on a word boundary, and the first word of the item is reserved
2728 : * for the kernel's use.
2729 : *
2730 : * @funcprops \isr_ok
2731 : *
2732 : * @param fifo Address of the FIFO.
2733 : * @param data Address of the data item.
2734 : */
2735 1 : #define k_fifo_put(fifo, data) \
2736 : ({ \
2737 : void *_data = data; \
2738 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, put, fifo, _data); \
2739 : k_queue_append(&(fifo)->_queue, _data); \
2740 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, put, fifo, _data); \
2741 : })
2742 :
2743 : /**
2744 : * @brief Add an element to a FIFO queue.
2745 : *
2746 : * This routine adds a data item to @a fifo. There is an implicit memory
2747 : * allocation to create an additional temporary bookkeeping data structure from
2748 : * the calling thread's resource pool, which is automatically freed when the
2749 : * item is removed. The data itself is not copied.
2750 : *
2751 : * @funcprops \isr_ok
2752 : *
2753 : * @param fifo Address of the FIFO.
2754 : * @param data Address of the data item.
2755 : *
2756 : * @retval 0 on success
2757 : * @retval -ENOMEM if there isn't sufficient RAM in the caller's resource pool
2758 : */
2759 1 : #define k_fifo_alloc_put(fifo, data) \
2760 : ({ \
2761 : void *_data = data; \
2762 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, alloc_put, fifo, _data); \
2763 : int fap_ret = k_queue_alloc_append(&(fifo)->_queue, _data); \
2764 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, alloc_put, fifo, _data, fap_ret); \
2765 : fap_ret; \
2766 : })
2767 :
2768 : /**
2769 : * @brief Atomically add a list of elements to a FIFO.
2770 : *
2771 : * This routine adds a list of data items to @a fifo in one operation.
2772 : * The data items must be in a singly-linked list, with the first word of
2773 : * each data item pointing to the next data item; the list must be
2774 : * NULL-terminated.
2775 : *
2776 : * @funcprops \isr_ok
2777 : *
2778 : * @param fifo Address of the FIFO queue.
2779 : * @param head Pointer to first node in singly-linked list.
2780 : * @param tail Pointer to last node in singly-linked list.
2781 : */
2782 1 : #define k_fifo_put_list(fifo, head, tail) \
2783 : ({ \
2784 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, put_list, fifo, head, tail); \
2785 : k_queue_append_list(&(fifo)->_queue, head, tail); \
2786 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, put_list, fifo, head, tail); \
2787 : })
2788 :
2789 : /**
2790 : * @brief Atomically add a list of elements to a FIFO queue.
2791 : *
2792 : * This routine adds a list of data items to @a fifo in one operation.
2793 : * The data items must be in a singly-linked list implemented using a
2794 : * sys_slist_t object. Upon completion, the sys_slist_t object is invalid
2795 : * and must be re-initialized via sys_slist_init().
2796 : *
2797 : * @funcprops \isr_ok
2798 : *
2799 : * @param fifo Address of the FIFO queue.
2800 : * @param list Pointer to sys_slist_t object.
2801 : */
2802 1 : #define k_fifo_put_slist(fifo, list) \
2803 : ({ \
2804 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, put_slist, fifo, list); \
2805 : k_queue_merge_slist(&(fifo)->_queue, list); \
2806 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, put_slist, fifo, list); \
2807 : })
2808 :
2809 : /**
2810 : * @brief Get an element from a FIFO queue.
2811 : *
2812 : * This routine removes a data item from @a fifo in a "first in, first out"
2813 : * manner. The first word of the data item is reserved for the kernel's use.
2814 : *
2815 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
2816 : *
2817 : * @funcprops \isr_ok
2818 : *
2819 : * @param fifo Address of the FIFO queue.
2820 : * @param timeout Waiting period to obtain a data item,
2821 : * or one of the special values K_NO_WAIT and K_FOREVER.
2822 : *
2823 : * @return Address of the data item if successful; NULL if returned
2824 : * without waiting, or waiting period timed out.
2825 : */
2826 1 : #define k_fifo_get(fifo, timeout) \
2827 : ({ \
2828 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, get, fifo, timeout); \
2829 : void *fg_ret = k_queue_get(&(fifo)->_queue, timeout); \
2830 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, get, fifo, timeout, fg_ret); \
2831 : fg_ret; \
2832 : })
2833 :
2834 : /**
2835 : * @brief Query a FIFO queue to see if it has data available.
2836 : *
2837 : * Note that the data might be already gone by the time this function returns
2838 : * if other threads is also trying to read from the FIFO.
2839 : *
2840 : * @funcprops \isr_ok
2841 : *
2842 : * @param fifo Address of the FIFO queue.
2843 : *
2844 : * @return Non-zero if the FIFO queue is empty.
2845 : * @return 0 if data is available.
2846 : */
2847 1 : #define k_fifo_is_empty(fifo) \
2848 : k_queue_is_empty(&(fifo)->_queue)
2849 :
2850 : /**
2851 : * @brief Peek element at the head of a FIFO queue.
2852 : *
2853 : * Return element from the head of FIFO queue without removing it. A usecase
2854 : * for this is if elements of the FIFO object are themselves containers. Then
2855 : * on each iteration of processing, a head container will be peeked,
2856 : * and some data processed out of it, and only if the container is empty,
2857 : * it will be completely remove from the FIFO queue.
2858 : *
2859 : * @param fifo Address of the FIFO queue.
2860 : *
2861 : * @return Head element, or NULL if the FIFO queue is empty.
2862 : */
2863 1 : #define k_fifo_peek_head(fifo) \
2864 : ({ \
2865 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, peek_head, fifo); \
2866 : void *fph_ret = k_queue_peek_head(&(fifo)->_queue); \
2867 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, peek_head, fifo, fph_ret); \
2868 : fph_ret; \
2869 : })
2870 :
2871 : /**
2872 : * @brief Peek element at the tail of FIFO queue.
2873 : *
2874 : * Return element from the tail of FIFO queue (without removing it). A usecase
2875 : * for this is if elements of the FIFO queue are themselves containers. Then
2876 : * it may be useful to add more data to the last container in a FIFO queue.
2877 : *
2878 : * @param fifo Address of the FIFO queue.
2879 : *
2880 : * @return Tail element, or NULL if a FIFO queue is empty.
2881 : */
2882 1 : #define k_fifo_peek_tail(fifo) \
2883 : ({ \
2884 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_fifo, peek_tail, fifo); \
2885 : void *fpt_ret = k_queue_peek_tail(&(fifo)->_queue); \
2886 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_fifo, peek_tail, fifo, fpt_ret); \
2887 : fpt_ret; \
2888 : })
2889 :
2890 : /**
2891 : * @brief Statically define and initialize a FIFO queue.
2892 : *
2893 : * The FIFO queue can be accessed outside the module where it is defined using:
2894 : *
2895 : * @code extern struct k_fifo <name>; @endcode
2896 : *
2897 : * @param name Name of the FIFO queue.
2898 : */
2899 1 : #define K_FIFO_DEFINE(name) \
2900 : STRUCT_SECTION_ITERABLE(k_fifo, name) = \
2901 : Z_FIFO_INITIALIZER(name)
2902 :
2903 : /** @} */
2904 :
2905 0 : struct k_lifo {
2906 : struct k_queue _queue;
2907 : #ifdef CONFIG_OBJ_CORE_LIFO
2908 : struct k_obj_core obj_core;
2909 : #endif
2910 : };
2911 :
2912 : /**
2913 : * @cond INTERNAL_HIDDEN
2914 : */
2915 :
2916 : #define Z_LIFO_INITIALIZER(obj) \
2917 : { \
2918 : ._queue = Z_QUEUE_INITIALIZER(obj._queue) \
2919 : }
2920 :
2921 : /**
2922 : * INTERNAL_HIDDEN @endcond
2923 : */
2924 :
2925 : /**
2926 : * @defgroup lifo_apis LIFO APIs
2927 : * @ingroup kernel_apis
2928 : * @{
2929 : */
2930 :
2931 : /**
2932 : * @brief Initialize a LIFO queue.
2933 : *
2934 : * This routine initializes a LIFO queue object, prior to its first use.
2935 : *
2936 : * @param lifo Address of the LIFO queue.
2937 : */
2938 1 : #define k_lifo_init(lifo) \
2939 : ({ \
2940 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_lifo, init, lifo); \
2941 : k_queue_init(&(lifo)->_queue); \
2942 : K_OBJ_CORE_INIT(K_OBJ_CORE(lifo), _obj_type_lifo); \
2943 : K_OBJ_CORE_LINK(K_OBJ_CORE(lifo)); \
2944 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_lifo, init, lifo); \
2945 : })
2946 :
2947 : /**
2948 : * @brief Add an element to a LIFO queue.
2949 : *
2950 : * This routine adds a data item to @a lifo. A LIFO queue data item must be
2951 : * aligned on a word boundary, and the first word of the item is
2952 : * reserved for the kernel's use.
2953 : *
2954 : * @funcprops \isr_ok
2955 : *
2956 : * @param lifo Address of the LIFO queue.
2957 : * @param data Address of the data item.
2958 : */
2959 1 : #define k_lifo_put(lifo, data) \
2960 : ({ \
2961 : void *_data = data; \
2962 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_lifo, put, lifo, _data); \
2963 : k_queue_prepend(&(lifo)->_queue, _data); \
2964 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_lifo, put, lifo, _data); \
2965 : })
2966 :
2967 : /**
2968 : * @brief Add an element to a LIFO queue.
2969 : *
2970 : * This routine adds a data item to @a lifo. There is an implicit memory
2971 : * allocation to create an additional temporary bookkeeping data structure from
2972 : * the calling thread's resource pool, which is automatically freed when the
2973 : * item is removed. The data itself is not copied.
2974 : *
2975 : * @funcprops \isr_ok
2976 : *
2977 : * @param lifo Address of the LIFO.
2978 : * @param data Address of the data item.
2979 : *
2980 : * @retval 0 on success
2981 : * @retval -ENOMEM if there isn't sufficient RAM in the caller's resource pool
2982 : */
2983 1 : #define k_lifo_alloc_put(lifo, data) \
2984 : ({ \
2985 : void *_data = data; \
2986 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_lifo, alloc_put, lifo, _data); \
2987 : int lap_ret = k_queue_alloc_prepend(&(lifo)->_queue, _data); \
2988 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_lifo, alloc_put, lifo, _data, lap_ret); \
2989 : lap_ret; \
2990 : })
2991 :
2992 : /**
2993 : * @brief Get an element from a LIFO queue.
2994 : *
2995 : * This routine removes a data item from @a LIFO in a "last in, first out"
2996 : * manner. The first word of the data item is reserved for the kernel's use.
2997 : *
2998 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
2999 : *
3000 : * @funcprops \isr_ok
3001 : *
3002 : * @param lifo Address of the LIFO queue.
3003 : * @param timeout Waiting period to obtain a data item,
3004 : * or one of the special values K_NO_WAIT and K_FOREVER.
3005 : *
3006 : * @return Address of the data item if successful; NULL if returned
3007 : * without waiting, or waiting period timed out.
3008 : */
3009 1 : #define k_lifo_get(lifo, timeout) \
3010 : ({ \
3011 : SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_lifo, get, lifo, timeout); \
3012 : void *lg_ret = k_queue_get(&(lifo)->_queue, timeout); \
3013 : SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_lifo, get, lifo, timeout, lg_ret); \
3014 : lg_ret; \
3015 : })
3016 :
3017 : /**
3018 : * @brief Statically define and initialize a LIFO queue.
3019 : *
3020 : * The LIFO queue can be accessed outside the module where it is defined using:
3021 : *
3022 : * @code extern struct k_lifo <name>; @endcode
3023 : *
3024 : * @param name Name of the fifo.
3025 : */
3026 1 : #define K_LIFO_DEFINE(name) \
3027 : STRUCT_SECTION_ITERABLE(k_lifo, name) = \
3028 : Z_LIFO_INITIALIZER(name)
3029 :
3030 : /** @} */
3031 :
3032 : /**
3033 : * @cond INTERNAL_HIDDEN
3034 : */
3035 : #define K_STACK_FLAG_ALLOC ((uint8_t)1) /* Buffer was allocated */
3036 :
3037 : typedef uintptr_t stack_data_t;
3038 :
3039 : struct k_stack {
3040 : _wait_q_t wait_q;
3041 : struct k_spinlock lock;
3042 : stack_data_t *base, *next, *top;
3043 :
3044 : uint8_t flags;
3045 :
3046 : SYS_PORT_TRACING_TRACKING_FIELD(k_stack)
3047 :
3048 : #ifdef CONFIG_OBJ_CORE_STACK
3049 : struct k_obj_core obj_core;
3050 : #endif
3051 : };
3052 :
3053 : #define Z_STACK_INITIALIZER(obj, stack_buffer, stack_num_entries) \
3054 : { \
3055 : .wait_q = Z_WAIT_Q_INIT(&(obj).wait_q), \
3056 : .base = (stack_buffer), \
3057 : .next = (stack_buffer), \
3058 : .top = (stack_buffer) + (stack_num_entries), \
3059 : }
3060 :
3061 : /**
3062 : * INTERNAL_HIDDEN @endcond
3063 : */
3064 :
3065 : /**
3066 : * @defgroup stack_apis Stack APIs
3067 : * @ingroup kernel_apis
3068 : * @{
3069 : */
3070 :
3071 : /**
3072 : * @brief Initialize a stack.
3073 : *
3074 : * This routine initializes a stack object, prior to its first use.
3075 : *
3076 : * @param stack Address of the stack.
3077 : * @param buffer Address of array used to hold stacked values.
3078 : * @param num_entries Maximum number of values that can be stacked.
3079 : */
3080 1 : void k_stack_init(struct k_stack *stack,
3081 : stack_data_t *buffer, uint32_t num_entries);
3082 :
3083 :
3084 : /**
3085 : * @brief Initialize a stack.
3086 : *
3087 : * This routine initializes a stack object, prior to its first use. Internal
3088 : * buffers will be allocated from the calling thread's resource pool.
3089 : * This memory will be released if k_stack_cleanup() is called, or
3090 : * userspace is enabled and the stack object loses all references to it.
3091 : *
3092 : * @param stack Address of the stack.
3093 : * @param num_entries Maximum number of values that can be stacked.
3094 : *
3095 : * @return -ENOMEM if memory couldn't be allocated
3096 : */
3097 :
3098 1 : __syscall int32_t k_stack_alloc_init(struct k_stack *stack,
3099 : uint32_t num_entries);
3100 :
3101 : /**
3102 : * @brief Release a stack's allocated buffer
3103 : *
3104 : * If a stack object was given a dynamically allocated buffer via
3105 : * k_stack_alloc_init(), this will free it. This function does nothing
3106 : * if the buffer wasn't dynamically allocated.
3107 : *
3108 : * @param stack Address of the stack.
3109 : * @retval 0 on success
3110 : * @retval -EAGAIN when object is still in use
3111 : */
3112 1 : int k_stack_cleanup(struct k_stack *stack);
3113 :
3114 : /**
3115 : * @brief Push an element onto a stack.
3116 : *
3117 : * This routine adds a stack_data_t value @a data to @a stack.
3118 : *
3119 : * @funcprops \isr_ok
3120 : *
3121 : * @param stack Address of the stack.
3122 : * @param data Value to push onto the stack.
3123 : *
3124 : * @retval 0 on success
3125 : * @retval -ENOMEM if stack is full
3126 : */
3127 1 : __syscall int k_stack_push(struct k_stack *stack, stack_data_t data);
3128 :
3129 : /**
3130 : * @brief Pop an element from a stack.
3131 : *
3132 : * This routine removes a stack_data_t value from @a stack in a "last in,
3133 : * first out" manner and stores the value in @a data.
3134 : *
3135 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
3136 : *
3137 : * @funcprops \isr_ok
3138 : *
3139 : * @param stack Address of the stack.
3140 : * @param data Address of area to hold the value popped from the stack.
3141 : * @param timeout Waiting period to obtain a value,
3142 : * or one of the special values K_NO_WAIT and
3143 : * K_FOREVER.
3144 : *
3145 : * @retval 0 Element popped from stack.
3146 : * @retval -EBUSY Returned without waiting.
3147 : * @retval -EAGAIN Waiting period timed out.
3148 : */
3149 1 : __syscall int k_stack_pop(struct k_stack *stack, stack_data_t *data,
3150 : k_timeout_t timeout);
3151 :
3152 : /**
3153 : * @brief Statically define and initialize a stack
3154 : *
3155 : * The stack can be accessed outside the module where it is defined using:
3156 : *
3157 : * @code extern struct k_stack <name>; @endcode
3158 : *
3159 : * @param name Name of the stack.
3160 : * @param stack_num_entries Maximum number of values that can be stacked.
3161 : */
3162 1 : #define K_STACK_DEFINE(name, stack_num_entries) \
3163 : stack_data_t __noinit \
3164 : _k_stack_buf_##name[stack_num_entries]; \
3165 : STRUCT_SECTION_ITERABLE(k_stack, name) = \
3166 : Z_STACK_INITIALIZER(name, _k_stack_buf_##name, \
3167 : stack_num_entries)
3168 :
3169 : /** @} */
3170 :
3171 : /**
3172 : * @cond INTERNAL_HIDDEN
3173 : */
3174 :
3175 : struct k_work;
3176 : struct k_work_q;
3177 : struct k_work_queue_config;
3178 : extern struct k_work_q k_sys_work_q;
3179 :
3180 : /**
3181 : * INTERNAL_HIDDEN @endcond
3182 : */
3183 :
3184 : /**
3185 : * @defgroup mutex_apis Mutex APIs
3186 : * @ingroup kernel_apis
3187 : * @{
3188 : */
3189 :
3190 : /**
3191 : * Mutex Structure
3192 : * @ingroup mutex_apis
3193 : */
3194 1 : struct k_mutex {
3195 : /** Mutex wait queue */
3196 1 : _wait_q_t wait_q;
3197 : /** Mutex owner */
3198 1 : struct k_thread *owner;
3199 :
3200 : /** Current lock count */
3201 1 : uint32_t lock_count;
3202 :
3203 : /** Original thread priority */
3204 1 : int owner_orig_prio;
3205 :
3206 : SYS_PORT_TRACING_TRACKING_FIELD(k_mutex)
3207 :
3208 : #ifdef CONFIG_OBJ_CORE_MUTEX
3209 : struct k_obj_core obj_core;
3210 : #endif
3211 : };
3212 :
3213 : /**
3214 : * @cond INTERNAL_HIDDEN
3215 : */
3216 : #define Z_MUTEX_INITIALIZER(obj) \
3217 : { \
3218 : .wait_q = Z_WAIT_Q_INIT(&(obj).wait_q), \
3219 : .owner = NULL, \
3220 : .lock_count = 0, \
3221 : .owner_orig_prio = K_LOWEST_APPLICATION_THREAD_PRIO, \
3222 : }
3223 :
3224 : /**
3225 : * INTERNAL_HIDDEN @endcond
3226 : */
3227 :
3228 : /**
3229 : * @brief Statically define and initialize a mutex.
3230 : *
3231 : * The mutex can be accessed outside the module where it is defined using:
3232 : *
3233 : * @code extern struct k_mutex <name>; @endcode
3234 : *
3235 : * @param name Name of the mutex.
3236 : */
3237 1 : #define K_MUTEX_DEFINE(name) \
3238 : STRUCT_SECTION_ITERABLE(k_mutex, name) = \
3239 : Z_MUTEX_INITIALIZER(name)
3240 :
3241 : /**
3242 : * @brief Initialize a mutex.
3243 : *
3244 : * This routine initializes a mutex object, prior to its first use.
3245 : *
3246 : * Upon completion, the mutex is available and does not have an owner.
3247 : *
3248 : * @param mutex Address of the mutex.
3249 : *
3250 : * @retval 0 Mutex object created
3251 : *
3252 : */
3253 1 : __syscall int k_mutex_init(struct k_mutex *mutex);
3254 :
3255 :
3256 : /**
3257 : * @brief Lock a mutex.
3258 : *
3259 : * This routine locks @a mutex. If the mutex is locked by another thread,
3260 : * the calling thread waits until the mutex becomes available or until
3261 : * a timeout occurs.
3262 : *
3263 : * A thread is permitted to lock a mutex it has already locked. The operation
3264 : * completes immediately and the lock count is increased by 1.
3265 : *
3266 : * Mutexes may not be locked in ISRs.
3267 : *
3268 : * @param mutex Address of the mutex.
3269 : * @param timeout Waiting period to lock the mutex,
3270 : * or one of the special values K_NO_WAIT and
3271 : * K_FOREVER.
3272 : *
3273 : * @retval 0 Mutex locked.
3274 : * @retval -EBUSY Returned without waiting.
3275 : * @retval -EAGAIN Waiting period timed out.
3276 : */
3277 1 : __syscall int k_mutex_lock(struct k_mutex *mutex, k_timeout_t timeout);
3278 :
3279 : /**
3280 : * @brief Unlock a mutex.
3281 : *
3282 : * This routine unlocks @a mutex. The mutex must already be locked by the
3283 : * calling thread.
3284 : *
3285 : * The mutex cannot be claimed by another thread until it has been unlocked by
3286 : * the calling thread as many times as it was previously locked by that
3287 : * thread.
3288 : *
3289 : * Mutexes may not be unlocked in ISRs, as mutexes must only be manipulated
3290 : * in thread context due to ownership and priority inheritance semantics.
3291 : *
3292 : * @param mutex Address of the mutex.
3293 : *
3294 : * @retval 0 Mutex unlocked.
3295 : * @retval -EPERM The current thread does not own the mutex
3296 : * @retval -EINVAL The mutex is not locked
3297 : *
3298 : */
3299 1 : __syscall int k_mutex_unlock(struct k_mutex *mutex);
3300 :
3301 : /**
3302 : * @}
3303 : */
3304 :
3305 :
3306 0 : struct k_condvar {
3307 0 : _wait_q_t wait_q;
3308 :
3309 : #ifdef CONFIG_OBJ_CORE_CONDVAR
3310 : struct k_obj_core obj_core;
3311 : #endif
3312 : };
3313 :
3314 : #define Z_CONDVAR_INITIALIZER(obj) \
3315 : { \
3316 : .wait_q = Z_WAIT_Q_INIT(&obj.wait_q), \
3317 : }
3318 :
3319 : /**
3320 : * @defgroup condvar_apis Condition Variables APIs
3321 : * @ingroup kernel_apis
3322 : * @{
3323 : */
3324 :
3325 : /**
3326 : * @brief Initialize a condition variable
3327 : *
3328 : * @param condvar pointer to a @p k_condvar structure
3329 : * @retval 0 Condition variable created successfully
3330 : */
3331 1 : __syscall int k_condvar_init(struct k_condvar *condvar);
3332 :
3333 : /**
3334 : * @brief Signals one thread that is pending on the condition variable
3335 : *
3336 : * @param condvar pointer to a @p k_condvar structure
3337 : * @retval 0 On success
3338 : */
3339 1 : __syscall int k_condvar_signal(struct k_condvar *condvar);
3340 :
3341 : /**
3342 : * @brief Unblock all threads that are pending on the condition
3343 : * variable
3344 : *
3345 : * @param condvar pointer to a @p k_condvar structure
3346 : * @return An integer with number of woken threads on success
3347 : */
3348 1 : __syscall int k_condvar_broadcast(struct k_condvar *condvar);
3349 :
3350 : /**
3351 : * @brief Waits on the condition variable releasing the mutex lock
3352 : *
3353 : * Atomically releases the currently owned mutex, blocks the current thread
3354 : * waiting on the condition variable specified by @a condvar,
3355 : * and finally acquires the mutex again.
3356 : *
3357 : * The waiting thread unblocks only after another thread calls
3358 : * k_condvar_signal, or k_condvar_broadcast with the same condition variable.
3359 : *
3360 : * @param condvar pointer to a @p k_condvar structure
3361 : * @param mutex Address of the mutex.
3362 : * @param timeout Waiting period for the condition variable
3363 : * or one of the special values K_NO_WAIT and K_FOREVER.
3364 : * @retval 0 On success
3365 : * @retval -EAGAIN Waiting period timed out.
3366 : */
3367 1 : __syscall int k_condvar_wait(struct k_condvar *condvar, struct k_mutex *mutex,
3368 : k_timeout_t timeout);
3369 :
3370 : /**
3371 : * @brief Statically define and initialize a condition variable.
3372 : *
3373 : * The condition variable can be accessed outside the module where it is
3374 : * defined using:
3375 : *
3376 : * @code extern struct k_condvar <name>; @endcode
3377 : *
3378 : * @param name Name of the condition variable.
3379 : */
3380 1 : #define K_CONDVAR_DEFINE(name) \
3381 : STRUCT_SECTION_ITERABLE(k_condvar, name) = \
3382 : Z_CONDVAR_INITIALIZER(name)
3383 : /**
3384 : * @}
3385 : */
3386 :
3387 : /**
3388 : * @defgroup semaphore_apis Semaphore APIs
3389 : * @ingroup kernel_apis
3390 : * @{
3391 : */
3392 :
3393 : /**
3394 : * @brief Semaphore structure
3395 : *
3396 : * This structure is used to represent a semaphore.
3397 : * All the members are internal and should not be accessed directly.
3398 : */
3399 1 : struct k_sem {
3400 : /**
3401 : * @cond INTERNAL_HIDDEN
3402 : */
3403 : _wait_q_t wait_q;
3404 : unsigned int count;
3405 : unsigned int limit;
3406 :
3407 : Z_DECL_POLL_EVENT
3408 :
3409 : SYS_PORT_TRACING_TRACKING_FIELD(k_sem)
3410 :
3411 : #ifdef CONFIG_OBJ_CORE_SEM
3412 : struct k_obj_core obj_core;
3413 : #endif
3414 : /** @endcond */
3415 : };
3416 :
3417 : /**
3418 : * @cond INTERNAL_HIDDEN
3419 : */
3420 :
3421 : #define Z_SEM_INITIALIZER(obj, initial_count, count_limit) \
3422 : { \
3423 : .wait_q = Z_WAIT_Q_INIT(&(obj).wait_q), \
3424 : .count = (initial_count), \
3425 : .limit = (count_limit), \
3426 : Z_POLL_EVENT_OBJ_INIT(obj) \
3427 : }
3428 :
3429 : /**
3430 : * @endcond
3431 : */
3432 :
3433 : /**
3434 : * @brief Maximum limit value allowed for a semaphore.
3435 : *
3436 : * This is intended for use when a semaphore does not have
3437 : * an explicit maximum limit, and instead is just used for
3438 : * counting purposes.
3439 : *
3440 : */
3441 1 : #define K_SEM_MAX_LIMIT UINT_MAX
3442 :
3443 : /**
3444 : * @brief Initialize a semaphore.
3445 : *
3446 : * This routine initializes a semaphore object, prior to its first use.
3447 : *
3448 : * @param sem Address of the semaphore.
3449 : * @param initial_count Initial semaphore count.
3450 : * @param limit Maximum permitted semaphore count.
3451 : *
3452 : * @see K_SEM_MAX_LIMIT
3453 : *
3454 : * @retval 0 Semaphore created successfully
3455 : * @retval -EINVAL Invalid values
3456 : *
3457 : */
3458 1 : __syscall int k_sem_init(struct k_sem *sem, unsigned int initial_count,
3459 : unsigned int limit);
3460 :
3461 : /**
3462 : * @brief Take a semaphore.
3463 : *
3464 : * This routine takes @a sem.
3465 : *
3466 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
3467 : *
3468 : * @funcprops \isr_ok
3469 : *
3470 : * @param sem Address of the semaphore.
3471 : * @param timeout Waiting period to take the semaphore,
3472 : * or one of the special values K_NO_WAIT and K_FOREVER.
3473 : *
3474 : * @retval 0 Semaphore taken.
3475 : * @retval -EBUSY Returned without waiting.
3476 : * @retval -EAGAIN Waiting period timed out,
3477 : * or the semaphore was reset during the waiting period.
3478 : */
3479 1 : __syscall int k_sem_take(struct k_sem *sem, k_timeout_t timeout);
3480 :
3481 : /**
3482 : * @brief Give a semaphore.
3483 : *
3484 : * This routine gives @a sem, unless the semaphore is already at its maximum
3485 : * permitted count.
3486 : *
3487 : * @funcprops \isr_ok
3488 : *
3489 : * @param sem Address of the semaphore.
3490 : */
3491 1 : __syscall void k_sem_give(struct k_sem *sem);
3492 :
3493 : /**
3494 : * @brief Resets a semaphore's count to zero.
3495 : *
3496 : * This routine sets the count of @a sem to zero.
3497 : * Any outstanding semaphore takes will be aborted
3498 : * with -EAGAIN.
3499 : *
3500 : * @param sem Address of the semaphore.
3501 : */
3502 1 : __syscall void k_sem_reset(struct k_sem *sem);
3503 :
3504 : /**
3505 : * @brief Get a semaphore's count.
3506 : *
3507 : * This routine returns the current count of @a sem.
3508 : *
3509 : * @param sem Address of the semaphore.
3510 : *
3511 : * @return Current semaphore count.
3512 : */
3513 1 : __syscall unsigned int k_sem_count_get(struct k_sem *sem);
3514 :
3515 : /**
3516 : * @internal
3517 : */
3518 : static inline unsigned int z_impl_k_sem_count_get(struct k_sem *sem)
3519 : {
3520 : return sem->count;
3521 : }
3522 :
3523 : /**
3524 : * @brief Statically define and initialize a semaphore.
3525 : *
3526 : * The semaphore can be accessed outside the module where it is defined using:
3527 : *
3528 : * @code extern struct k_sem <name>; @endcode
3529 : *
3530 : * @param name Name of the semaphore.
3531 : * @param initial_count Initial semaphore count.
3532 : * @param count_limit Maximum permitted semaphore count.
3533 : */
3534 1 : #define K_SEM_DEFINE(name, initial_count, count_limit) \
3535 : STRUCT_SECTION_ITERABLE(k_sem, name) = \
3536 : Z_SEM_INITIALIZER(name, initial_count, count_limit); \
3537 : BUILD_ASSERT(((count_limit) != 0) && \
3538 : (((initial_count) < (count_limit)) || ((initial_count) == (count_limit))) && \
3539 : ((count_limit) <= K_SEM_MAX_LIMIT));
3540 :
3541 : /** @} */
3542 :
3543 : #if defined(CONFIG_SCHED_IPI_SUPPORTED) || defined(__DOXYGEN__)
3544 : struct k_ipi_work;
3545 :
3546 :
3547 0 : typedef void (*k_ipi_func_t)(struct k_ipi_work *work);
3548 :
3549 : /**
3550 : * @brief IPI work item structure
3551 : *
3552 : * This structure is used to represent an IPI work item.
3553 : * All the members are internal and should not be accessed directly.
3554 : */
3555 1 : struct k_ipi_work {
3556 : /**
3557 : * @cond INTERNAL_HIDDEN
3558 : */
3559 : sys_dnode_t node[CONFIG_MP_MAX_NUM_CPUS]; /* Node in IPI work queue */
3560 : k_ipi_func_t func; /* Function to execute on target CPU */
3561 : struct k_event event; /* Event to signal when processed */
3562 : uint32_t bitmask; /* Bitmask of targeted CPUs */
3563 : /** INTERNAL_HIDDEN @endcond */
3564 : };
3565 :
3566 :
3567 : /**
3568 : * @brief Initialize the specified IPI work item
3569 : *
3570 : * @kconfig_dep{CONFIG_SCHED_IPI_SUPPORTED}
3571 : *
3572 : * @param work Pointer to the IPI work item to be initialized
3573 : */
3574 1 : static inline void k_ipi_work_init(struct k_ipi_work *work)
3575 : {
3576 : k_event_init(&work->event);
3577 : for (unsigned int i = 0; i < CONFIG_MP_MAX_NUM_CPUS; i++) {
3578 : sys_dnode_init(&work->node[i]);
3579 : }
3580 : work->bitmask = 0;
3581 : }
3582 :
3583 : /**
3584 : * @brief Add an IPI work item to the IPI work queue
3585 : *
3586 : * Adds the specified IPI work item to the IPI work queues of each CPU
3587 : * identified by @a cpu_bitmask. The specified IPI work item will subsequently
3588 : * execute at ISR level as those CPUs process their received IPIs. Do not
3589 : * re-use the specified IPI work item until it has been processed by all of
3590 : * the identified CPUs.
3591 : *
3592 : * @kconfig_dep{CONFIG_SCHED_IPI_SUPPORTED}
3593 : *
3594 : * @param work Pointer to the IPI work item
3595 : * @param cpu_bitmask Set of CPUs to which the IPI work item will be sent
3596 : * @param func Function to execute on the targeted CPU(s)
3597 : *
3598 : * @retval 0 on success
3599 : * @retval -EBUSY if the specified IPI work item is still being processed
3600 : */
3601 1 : int k_ipi_work_add(struct k_ipi_work *work, uint32_t cpu_bitmask,
3602 : k_ipi_func_t func);
3603 :
3604 : /**
3605 : * @brief Wait until the IPI work item has been processed by all targeted CPUs
3606 : *
3607 : * This routine waits until the IPI work item has been processed by all CPUs
3608 : * to which it was sent. If called from an ISR, then @a timeout must be set to
3609 : * K_NO_WAIT. To prevent deadlocks the caller must not have IRQs locked when
3610 : * calling this function.
3611 : *
3612 : * @note It is not in general possible to poll safely for completion of this
3613 : * function in ISR or locked contexts where the calling CPU cannot service IPIs
3614 : * (because the targeted CPUs may themselves be waiting on the calling CPU).
3615 : * Application code must be prepared for failure or to poll from a thread
3616 : * context.
3617 : *
3618 : * @kconfig_dep{CONFIG_SCHED_IPI_SUPPORTED}
3619 : *
3620 : * @param work Pointer to the IPI work item
3621 : * @param timeout Maximum time to wait for IPI work to be processed
3622 : *
3623 : * @retval -EAGAIN Waiting period timed out.
3624 : * @retval 0 if processed by all targeted CPUs
3625 : */
3626 1 : int k_ipi_work_wait(struct k_ipi_work *work, k_timeout_t timeout);
3627 :
3628 : /**
3629 : * @brief Signal that there is one or more IPI work items to process
3630 : *
3631 : * This routine sends an IPI to the set of CPUs identified by calls to
3632 : * k_ipi_work_add() since this CPU sent its last set of IPIs.
3633 : *
3634 : * @kconfig_dep{CONFIG_SCHED_IPI_SUPPORTED}
3635 : */
3636 1 : void k_ipi_work_signal(void);
3637 :
3638 : #endif /* CONFIG_SCHED_IPI_SUPPORTED */
3639 :
3640 : /**
3641 : * @cond INTERNAL_HIDDEN
3642 : */
3643 :
3644 : struct k_work_delayable;
3645 : struct k_work_sync;
3646 :
3647 : /**
3648 : * INTERNAL_HIDDEN @endcond
3649 : */
3650 :
3651 : /**
3652 : * @defgroup workqueue_apis Work Queue APIs
3653 : * @ingroup kernel_apis
3654 : * @{
3655 : */
3656 :
3657 : /** @brief The signature for a work item handler function.
3658 : *
3659 : * The function will be invoked by the thread animating a work queue.
3660 : *
3661 : * @param work the work item that provided the handler.
3662 : */
3663 1 : typedef void (*k_work_handler_t)(struct k_work *work);
3664 :
3665 : /** @brief Initialize a (non-delayable) work structure.
3666 : *
3667 : * This must be invoked before submitting a work structure for the first time.
3668 : * It need not be invoked again on the same work structure. It can be
3669 : * re-invoked to change the associated handler, but this must be done when the
3670 : * work item is idle.
3671 : *
3672 : * @funcprops \isr_ok
3673 : *
3674 : * @param work the work structure to be initialized.
3675 : *
3676 : * @param handler the handler to be invoked by the work item.
3677 : */
3678 1 : void k_work_init(struct k_work *work,
3679 : k_work_handler_t handler);
3680 :
3681 : /** @brief Busy state flags from the work item.
3682 : *
3683 : * A zero return value indicates the work item appears to be idle.
3684 : *
3685 : * @note This is a live snapshot of state, which may change before the result
3686 : * is checked. Use locks where appropriate.
3687 : *
3688 : * @funcprops \isr_ok
3689 : *
3690 : * @param work pointer to the work item.
3691 : *
3692 : * @return a mask of flags K_WORK_DELAYED, K_WORK_QUEUED,
3693 : * K_WORK_RUNNING, K_WORK_CANCELING, and K_WORK_FLUSHING.
3694 : */
3695 1 : int k_work_busy_get(const struct k_work *work);
3696 :
3697 : /** @brief Test whether a work item is currently pending.
3698 : *
3699 : * Wrapper to determine whether a work item is in a non-idle state.
3700 : *
3701 : * @note This is a live snapshot of state, which may change before the result
3702 : * is checked. Use locks where appropriate.
3703 : *
3704 : * @funcprops \isr_ok
3705 : *
3706 : * @param work pointer to the work item.
3707 : *
3708 : * @return true if and only if k_work_busy_get() returns a non-zero value.
3709 : */
3710 : static inline bool k_work_is_pending(const struct k_work *work);
3711 :
3712 : /** @brief Submit a work item to a queue.
3713 : *
3714 : * @param queue pointer to the work queue on which the item should run. If
3715 : * NULL the queue from the most recent submission will be used.
3716 : *
3717 : * @funcprops \isr_ok
3718 : *
3719 : * @param work pointer to the work item.
3720 : *
3721 : * @retval 0 if work was already submitted to a queue
3722 : * @retval 1 if work was not submitted and has been queued to @p queue
3723 : * @retval 2 if work was running and has been queued to the queue that was
3724 : * running it
3725 : * @retval -EBUSY
3726 : * * if work submission was rejected because the work item is cancelling; or
3727 : * * @p queue is draining; or
3728 : * * @p queue is plugged.
3729 : * @retval -EINVAL if @p queue is null and the work item has never been run.
3730 : * @retval -ENODEV if @p queue has not been started.
3731 : */
3732 1 : int k_work_submit_to_queue(struct k_work_q *queue,
3733 : struct k_work *work);
3734 :
3735 : /** @brief Submit a work item to the system queue.
3736 : *
3737 : * @funcprops \isr_ok
3738 : *
3739 : * @param work pointer to the work item.
3740 : *
3741 : * @return as with k_work_submit_to_queue().
3742 : */
3743 1 : int k_work_submit(struct k_work *work);
3744 :
3745 : /** @brief Wait for last-submitted instance to complete.
3746 : *
3747 : * Resubmissions may occur while waiting, including chained submissions (from
3748 : * within the handler).
3749 : *
3750 : * @note Be careful of caller and work queue thread relative priority. If
3751 : * this function sleeps it will not return until the work queue thread
3752 : * completes the tasks that allow this thread to resume.
3753 : *
3754 : * @note Behavior is undefined if this function is invoked on @p work from a
3755 : * work queue running @p work.
3756 : *
3757 : * @param work pointer to the work item.
3758 : *
3759 : * @param sync pointer to an opaque item containing state related to the
3760 : * pending cancellation. The object must persist until the call returns, and
3761 : * be accessible from both the caller thread and the work queue thread. The
3762 : * object must not be used for any other flush or cancel operation until this
3763 : * one completes. On architectures with CONFIG_KERNEL_COHERENCE the object
3764 : * must be allocated in coherent memory.
3765 : *
3766 : * @retval true if call had to wait for completion
3767 : * @retval false if work was already idle
3768 : */
3769 1 : bool k_work_flush(struct k_work *work,
3770 : struct k_work_sync *sync);
3771 :
3772 : /** @brief Cancel a work item.
3773 : *
3774 : * This attempts to prevent a pending (non-delayable) work item from being
3775 : * processed by removing it from the work queue. If the item is being
3776 : * processed, the work item will continue to be processed, but resubmissions
3777 : * are rejected until cancellation completes.
3778 : *
3779 : * If this returns zero cancellation is complete, otherwise something
3780 : * (probably a work queue thread) is still referencing the item.
3781 : *
3782 : * See also k_work_cancel_sync().
3783 : *
3784 : * @funcprops \isr_ok
3785 : *
3786 : * @param work pointer to the work item.
3787 : *
3788 : * @return the k_work_busy_get() status indicating the state of the item after all
3789 : * cancellation steps performed by this call are completed.
3790 : */
3791 1 : int k_work_cancel(struct k_work *work);
3792 :
3793 : /** @brief Cancel a work item and wait for it to complete.
3794 : *
3795 : * Same as k_work_cancel() but does not return until cancellation is complete.
3796 : * This can be invoked by a thread after k_work_cancel() to synchronize with a
3797 : * previous cancellation.
3798 : *
3799 : * On return the work structure will be idle unless something submits it after
3800 : * the cancellation was complete.
3801 : *
3802 : * @note Be careful of caller and work queue thread relative priority. If
3803 : * this function sleeps it will not return until the work queue thread
3804 : * completes the tasks that allow this thread to resume.
3805 : *
3806 : * @note Behavior is undefined if this function is invoked on @p work from a
3807 : * work queue running @p work.
3808 : *
3809 : * @param work pointer to the work item.
3810 : *
3811 : * @param sync pointer to an opaque item containing state related to the
3812 : * pending cancellation. The object must persist until the call returns, and
3813 : * be accessible from both the caller thread and the work queue thread. The
3814 : * object must not be used for any other flush or cancel operation until this
3815 : * one completes. On architectures with CONFIG_KERNEL_COHERENCE the object
3816 : * must be allocated in coherent memory.
3817 : *
3818 : * @retval true if work was pending (call had to wait for cancellation of a
3819 : * running handler to complete, or scheduled or submitted operations were
3820 : * cancelled);
3821 : * @retval false otherwise
3822 : */
3823 1 : bool k_work_cancel_sync(struct k_work *work, struct k_work_sync *sync);
3824 :
3825 : /** @brief Initialize a work queue structure.
3826 : *
3827 : * This must be invoked before starting a work queue structure for the first time.
3828 : * It need not be invoked again on the same work queue structure.
3829 : *
3830 : * @funcprops \isr_ok
3831 : *
3832 : * @param queue the queue structure to be initialized.
3833 : */
3834 1 : void k_work_queue_init(struct k_work_q *queue);
3835 :
3836 : /** @brief Initialize a work queue.
3837 : *
3838 : * This configures the work queue thread and starts it running. The function
3839 : * should not be re-invoked on a queue.
3840 : *
3841 : * @param queue pointer to the queue structure. It must be initialized
3842 : * in zeroed/bss memory or with @ref k_work_queue_init before
3843 : * use.
3844 : *
3845 : * @param stack pointer to the work thread stack area.
3846 : *
3847 : * @param stack_size size of the work thread stack area, in bytes.
3848 : *
3849 : * @param prio initial thread priority
3850 : *
3851 : * @param cfg optional additional configuration parameters. Pass @c
3852 : * NULL if not required, to use the defaults documented in
3853 : * k_work_queue_config.
3854 : */
3855 1 : void k_work_queue_start(struct k_work_q *queue,
3856 : k_thread_stack_t *stack, size_t stack_size,
3857 : int prio, const struct k_work_queue_config *cfg);
3858 :
3859 : /** @brief Run work queue using calling thread
3860 : *
3861 : * This will run the work queue forever unless stopped by @ref k_work_queue_stop.
3862 : *
3863 : * @param queue the queue to run
3864 : *
3865 : * @param cfg optional additional configuration parameters. Pass @c
3866 : * NULL if not required, to use the defaults documented in
3867 : * k_work_queue_config.
3868 : */
3869 1 : void k_work_queue_run(struct k_work_q *queue, const struct k_work_queue_config *cfg);
3870 :
3871 : /** @brief Access the thread that animates a work queue.
3872 : *
3873 : * This is necessary to grant a work queue thread access to things the work
3874 : * items it will process are expected to use.
3875 : *
3876 : * @param queue pointer to the queue structure.
3877 : *
3878 : * @return the thread associated with the work queue.
3879 : */
3880 : static inline k_tid_t k_work_queue_thread_get(struct k_work_q *queue);
3881 :
3882 : /** @brief Wait until the work queue has drained, optionally plugging it.
3883 : *
3884 : * This blocks submission to the work queue except when coming from queue
3885 : * thread, and blocks the caller until no more work items are available in the
3886 : * queue.
3887 : *
3888 : * If @p plug is true then submission will continue to be blocked after the
3889 : * drain operation completes until k_work_queue_unplug() is invoked.
3890 : *
3891 : * Note that work items that are delayed are not yet associated with their
3892 : * work queue. They must be cancelled externally if a goal is to ensure the
3893 : * work queue remains empty. The @p plug feature can be used to prevent
3894 : * delayed items from being submitted after the drain completes.
3895 : *
3896 : * @param queue pointer to the queue structure.
3897 : *
3898 : * @param plug if true the work queue will continue to block new submissions
3899 : * after all items have drained.
3900 : *
3901 : * @retval 1 if call had to wait for the drain to complete
3902 : * @retval 0 if call did not have to wait
3903 : * @retval negative if wait was interrupted or failed
3904 : */
3905 1 : int k_work_queue_drain(struct k_work_q *queue, bool plug);
3906 :
3907 : /** @brief Release a work queue to accept new submissions.
3908 : *
3909 : * This releases the block on new submissions placed when k_work_queue_drain()
3910 : * is invoked with the @p plug option enabled. If this is invoked before the
3911 : * drain completes new items may be submitted as soon as the drain completes.
3912 : *
3913 : * @funcprops \isr_ok
3914 : *
3915 : * @param queue pointer to the queue structure.
3916 : *
3917 : * @retval 0 if successfully unplugged
3918 : * @retval -EALREADY if the work queue was not plugged.
3919 : */
3920 1 : int k_work_queue_unplug(struct k_work_q *queue);
3921 :
3922 : /** @brief Stop a work queue.
3923 : *
3924 : * Stops the work queue thread and ensures that no further work will be processed.
3925 : * This call is blocking and guarantees that the work queue thread has terminated
3926 : * cleanly if successful, no work will be processed past this point.
3927 : *
3928 : * @param queue Pointer to the queue structure.
3929 : * @param timeout Maximum time to wait for the work queue to stop.
3930 : *
3931 : * @retval 0 if the work queue was stopped
3932 : * @retval -EALREADY if the work queue was not started (or already stopped)
3933 : * @retval -EBUSY if the work queue is actively processing work items
3934 : * @retval -ETIMEDOUT if the work queue did not stop within the stipulated timeout
3935 : */
3936 1 : int k_work_queue_stop(struct k_work_q *queue, k_timeout_t timeout);
3937 :
3938 : /** @brief Initialize a delayable work structure.
3939 : *
3940 : * This must be invoked before scheduling a delayable work structure for the
3941 : * first time. It need not be invoked again on the same work structure. It
3942 : * can be re-invoked to change the associated handler, but this must be done
3943 : * when the work item is idle.
3944 : *
3945 : * @funcprops \isr_ok
3946 : *
3947 : * @param dwork the delayable work structure to be initialized.
3948 : *
3949 : * @param handler the handler to be invoked by the work item.
3950 : */
3951 1 : void k_work_init_delayable(struct k_work_delayable *dwork,
3952 : k_work_handler_t handler);
3953 :
3954 : /**
3955 : * @brief Get the parent delayable work structure from a work pointer.
3956 : *
3957 : * This function is necessary when a @c k_work_handler_t function is passed to
3958 : * k_work_schedule_for_queue() and the handler needs to access data from the
3959 : * container of the containing `k_work_delayable`.
3960 : *
3961 : * @param work Address passed to the work handler
3962 : *
3963 : * @return Address of the containing @c k_work_delayable structure.
3964 : */
3965 : static inline struct k_work_delayable *
3966 : k_work_delayable_from_work(struct k_work *work);
3967 :
3968 : /** @brief Busy state flags from the delayable work item.
3969 : *
3970 : * @funcprops \isr_ok
3971 : *
3972 : * @note This is a live snapshot of state, which may change before the result
3973 : * can be inspected. Use locks where appropriate.
3974 : *
3975 : * @param dwork pointer to the delayable work item.
3976 : *
3977 : * @return a mask of flags K_WORK_DELAYED, K_WORK_QUEUED, K_WORK_RUNNING,
3978 : * K_WORK_CANCELING, and K_WORK_FLUSHING. A zero return value indicates the
3979 : * work item appears to be idle.
3980 : */
3981 1 : int k_work_delayable_busy_get(const struct k_work_delayable *dwork);
3982 :
3983 : /** @brief Test whether a delayed work item is currently pending.
3984 : *
3985 : * Wrapper to determine whether a delayed work item is in a non-idle state.
3986 : *
3987 : * @note This is a live snapshot of state, which may change before the result
3988 : * can be inspected. Use locks where appropriate.
3989 : *
3990 : * @funcprops \isr_ok
3991 : *
3992 : * @param dwork pointer to the delayable work item.
3993 : *
3994 : * @return true if and only if k_work_delayable_busy_get() returns a non-zero
3995 : * value.
3996 : */
3997 : static inline bool k_work_delayable_is_pending(
3998 : const struct k_work_delayable *dwork);
3999 :
4000 : /** @brief Get the absolute tick count at which a scheduled delayable work
4001 : * will be submitted.
4002 : *
4003 : * @note This is a live snapshot of state, which may change before the result
4004 : * can be inspected. Use locks where appropriate.
4005 : *
4006 : * @funcprops \isr_ok
4007 : *
4008 : * @param dwork pointer to the delayable work item.
4009 : *
4010 : * @return the tick count when the timer that will schedule the work item will
4011 : * expire, or the current tick count if the work is not scheduled.
4012 : */
4013 : static inline k_ticks_t k_work_delayable_expires_get(
4014 : const struct k_work_delayable *dwork);
4015 :
4016 : /** @brief Get the number of ticks until a scheduled delayable work will be
4017 : * submitted.
4018 : *
4019 : * @note This is a live snapshot of state, which may change before the result
4020 : * can be inspected. Use locks where appropriate.
4021 : *
4022 : * @funcprops \isr_ok
4023 : *
4024 : * @param dwork pointer to the delayable work item.
4025 : *
4026 : * @return the number of ticks until the timer that will schedule the work
4027 : * item will expire, or zero if the item is not scheduled.
4028 : */
4029 : static inline k_ticks_t k_work_delayable_remaining_get(
4030 : const struct k_work_delayable *dwork);
4031 :
4032 : /** @brief Submit an idle work item to a queue after a delay.
4033 : *
4034 : * Unlike k_work_reschedule_for_queue() this is a no-op if the work item is
4035 : * already scheduled or submitted, even if @p delay is @c K_NO_WAIT.
4036 : *
4037 : * @funcprops \isr_ok
4038 : *
4039 : * @param queue the queue on which the work item should be submitted after the
4040 : * delay.
4041 : *
4042 : * @param dwork pointer to the delayable work item.
4043 : *
4044 : * @param delay the time to wait before submitting the work item. If @c
4045 : * K_NO_WAIT and the work is not pending this is equivalent to
4046 : * k_work_submit_to_queue().
4047 : *
4048 : * @retval 0 if work was already scheduled or submitted.
4049 : * @retval 1 if work has been scheduled.
4050 : * @retval 2 if @p delay is @c K_NO_WAIT and work
4051 : * was running and has been queued to the queue that was running it.
4052 : * @retval -EBUSY if @p delay is @c K_NO_WAIT and
4053 : * k_work_submit_to_queue() fails with this code.
4054 : * @retval -EINVAL if @p delay is @c K_NO_WAIT and
4055 : * k_work_submit_to_queue() fails with this code.
4056 : * @retval -ENODEV if @p delay is @c K_NO_WAIT and
4057 : * k_work_submit_to_queue() fails with this code.
4058 : */
4059 1 : int k_work_schedule_for_queue(struct k_work_q *queue,
4060 : struct k_work_delayable *dwork,
4061 : k_timeout_t delay);
4062 :
4063 : /** @brief Submit an idle work item to the system work queue after a
4064 : * delay.
4065 : *
4066 : * This is a thin wrapper around k_work_schedule_for_queue(), with all the API
4067 : * characteristics of that function.
4068 : *
4069 : * @param dwork pointer to the delayable work item.
4070 : *
4071 : * @param delay the time to wait before submitting the work item. If @c
4072 : * K_NO_WAIT this is equivalent to k_work_submit_to_queue().
4073 : *
4074 : * @return as with k_work_schedule_for_queue().
4075 : */
4076 1 : int k_work_schedule(struct k_work_delayable *dwork,
4077 : k_timeout_t delay);
4078 :
4079 : /** @brief Reschedule a work item to a queue after a delay.
4080 : *
4081 : * Unlike k_work_schedule_for_queue() this function can change the deadline of
4082 : * a scheduled work item, and will schedule a work item that is in any state
4083 : * (e.g. is idle, submitted, or running). This function does not affect
4084 : * ("unsubmit") a work item that has been submitted to a queue.
4085 : *
4086 : * @funcprops \isr_ok
4087 : *
4088 : * @param queue the queue on which the work item should be submitted after the
4089 : * delay.
4090 : *
4091 : * @param dwork pointer to the delayable work item.
4092 : *
4093 : * @param delay the time to wait before submitting the work item. If @c
4094 : * K_NO_WAIT this is equivalent to k_work_submit_to_queue() after canceling
4095 : * any previous scheduled submission.
4096 : *
4097 : * @note If delay is @c K_NO_WAIT ("no delay") the return values are as with
4098 : * k_work_submit_to_queue().
4099 : *
4100 : * @retval 0 if delay is @c K_NO_WAIT and work was already on a queue
4101 : * @retval 1 if
4102 : * * delay is @c K_NO_WAIT and work was not submitted but has now been queued
4103 : * to @p queue; or
4104 : * * delay not @c K_NO_WAIT and work has been scheduled
4105 : * @retval 2 if delay is @c K_NO_WAIT and work was running and has been queued
4106 : * to the queue that was running it
4107 : * @retval -EBUSY if @p delay is @c K_NO_WAIT and
4108 : * k_work_submit_to_queue() fails with this code.
4109 : * @retval -EINVAL if @p delay is @c K_NO_WAIT and
4110 : * k_work_submit_to_queue() fails with this code.
4111 : * @retval -ENODEV if @p delay is @c K_NO_WAIT and
4112 : * k_work_submit_to_queue() fails with this code.
4113 : */
4114 1 : int k_work_reschedule_for_queue(struct k_work_q *queue,
4115 : struct k_work_delayable *dwork,
4116 : k_timeout_t delay);
4117 :
4118 : /** @brief Reschedule a work item to the system work queue after a
4119 : * delay.
4120 : *
4121 : * This is a thin wrapper around k_work_reschedule_for_queue(), with all the
4122 : * API characteristics of that function.
4123 : *
4124 : * @param dwork pointer to the delayable work item.
4125 : *
4126 : * @param delay the time to wait before submitting the work item.
4127 : *
4128 : * @return as with k_work_reschedule_for_queue().
4129 : */
4130 1 : int k_work_reschedule(struct k_work_delayable *dwork,
4131 : k_timeout_t delay);
4132 :
4133 : /** @brief Flush delayable work.
4134 : *
4135 : * If the work is scheduled, it is immediately submitted. Then the caller
4136 : * blocks until the work completes, as with k_work_flush().
4137 : *
4138 : * @note Be careful of caller and work queue thread relative priority. If
4139 : * this function sleeps it will not return until the work queue thread
4140 : * completes the tasks that allow this thread to resume.
4141 : *
4142 : * @note Behavior is undefined if this function is invoked on @p dwork from a
4143 : * work queue running @p dwork.
4144 : *
4145 : * @param dwork pointer to the delayable work item.
4146 : *
4147 : * @param sync pointer to an opaque item containing state related to the
4148 : * pending cancellation. The object must persist until the call returns, and
4149 : * be accessible from both the caller thread and the work queue thread. The
4150 : * object must not be used for any other flush or cancel operation until this
4151 : * one completes. On architectures with CONFIG_KERNEL_COHERENCE the object
4152 : * must be allocated in coherent memory.
4153 : *
4154 : * @retval true if call had to wait for completion
4155 : * @retval false if work was already idle
4156 : */
4157 1 : bool k_work_flush_delayable(struct k_work_delayable *dwork,
4158 : struct k_work_sync *sync);
4159 :
4160 : /** @brief Cancel delayable work.
4161 : *
4162 : * Similar to k_work_cancel() but for delayable work. If the work is
4163 : * scheduled or submitted it is canceled. This function does not wait for the
4164 : * cancellation to complete.
4165 : *
4166 : * @note The work may still be running when this returns. Use
4167 : * k_work_flush_delayable() or k_work_cancel_delayable_sync() to ensure it is
4168 : * not running.
4169 : *
4170 : * @note Canceling delayable work does not prevent rescheduling it. It does
4171 : * prevent submitting it until the cancellation completes.
4172 : *
4173 : * @funcprops \isr_ok
4174 : *
4175 : * @param dwork pointer to the delayable work item.
4176 : *
4177 : * @return the k_work_delayable_busy_get() status indicating the state of the
4178 : * item after all cancellation steps performed by this call are completed.
4179 : */
4180 1 : int k_work_cancel_delayable(struct k_work_delayable *dwork);
4181 :
4182 : /** @brief Cancel delayable work and wait.
4183 : *
4184 : * Like k_work_cancel_delayable() but waits until the work becomes idle.
4185 : *
4186 : * @note Canceling delayable work does not prevent rescheduling it. It does
4187 : * prevent submitting it until the cancellation completes.
4188 : *
4189 : * @note Be careful of caller and work queue thread relative priority. If
4190 : * this function sleeps it will not return until the work queue thread
4191 : * completes the tasks that allow this thread to resume.
4192 : *
4193 : * @note Behavior is undefined if this function is invoked on @p dwork from a
4194 : * work queue running @p dwork.
4195 : *
4196 : * @param dwork pointer to the delayable work item.
4197 : *
4198 : * @param sync pointer to an opaque item containing state related to the
4199 : * pending cancellation. The object must persist until the call returns, and
4200 : * be accessible from both the caller thread and the work queue thread. The
4201 : * object must not be used for any other flush or cancel operation until this
4202 : * one completes. On architectures with CONFIG_KERNEL_COHERENCE the object
4203 : * must be allocated in coherent memory.
4204 : *
4205 : * @retval true if work was not idle (call had to wait for cancellation of a
4206 : * running handler to complete, or scheduled or submitted operations were
4207 : * cancelled);
4208 : * @retval false otherwise
4209 : */
4210 1 : bool k_work_cancel_delayable_sync(struct k_work_delayable *dwork,
4211 : struct k_work_sync *sync);
4212 :
4213 0 : enum {
4214 : /**
4215 : * @cond INTERNAL_HIDDEN
4216 : */
4217 :
4218 : /* The atomic API is used for all work and queue flags fields to
4219 : * enforce sequential consistency in SMP environments.
4220 : */
4221 :
4222 : /* Bits that represent the work item states. At least nine of the
4223 : * combinations are distinct valid stable states.
4224 : */
4225 : K_WORK_RUNNING_BIT = 0,
4226 : K_WORK_CANCELING_BIT = 1,
4227 : K_WORK_QUEUED_BIT = 2,
4228 : K_WORK_DELAYED_BIT = 3,
4229 : K_WORK_FLUSHING_BIT = 4,
4230 :
4231 : K_WORK_MASK = BIT(K_WORK_DELAYED_BIT) | BIT(K_WORK_QUEUED_BIT)
4232 : | BIT(K_WORK_RUNNING_BIT) | BIT(K_WORK_CANCELING_BIT) | BIT(K_WORK_FLUSHING_BIT),
4233 :
4234 : /* Static work flags */
4235 : K_WORK_DELAYABLE_BIT = 8,
4236 : K_WORK_DELAYABLE = BIT(K_WORK_DELAYABLE_BIT),
4237 :
4238 : /* Dynamic work queue flags */
4239 : K_WORK_QUEUE_STARTED_BIT = 0,
4240 : K_WORK_QUEUE_STARTED = BIT(K_WORK_QUEUE_STARTED_BIT),
4241 : K_WORK_QUEUE_BUSY_BIT = 1,
4242 : K_WORK_QUEUE_BUSY = BIT(K_WORK_QUEUE_BUSY_BIT),
4243 : K_WORK_QUEUE_DRAIN_BIT = 2,
4244 : K_WORK_QUEUE_DRAIN = BIT(K_WORK_QUEUE_DRAIN_BIT),
4245 : K_WORK_QUEUE_PLUGGED_BIT = 3,
4246 : K_WORK_QUEUE_PLUGGED = BIT(K_WORK_QUEUE_PLUGGED_BIT),
4247 : K_WORK_QUEUE_STOP_BIT = 4,
4248 : K_WORK_QUEUE_STOP = BIT(K_WORK_QUEUE_STOP_BIT),
4249 :
4250 : /* Static work queue flags */
4251 : K_WORK_QUEUE_NO_YIELD_BIT = 8,
4252 : K_WORK_QUEUE_NO_YIELD = BIT(K_WORK_QUEUE_NO_YIELD_BIT),
4253 :
4254 : /**
4255 : * INTERNAL_HIDDEN @endcond
4256 : */
4257 : /* Transient work flags */
4258 :
4259 : /** @brief Flag indicating a work item that is running under a work
4260 : * queue thread.
4261 : *
4262 : * Accessed via k_work_busy_get(). May co-occur with other flags.
4263 : */
4264 : K_WORK_RUNNING = BIT(K_WORK_RUNNING_BIT),
4265 :
4266 : /** @brief Flag indicating a work item that is being canceled.
4267 : *
4268 : * Accessed via k_work_busy_get(). May co-occur with other flags.
4269 : */
4270 : K_WORK_CANCELING = BIT(K_WORK_CANCELING_BIT),
4271 :
4272 : /** @brief Flag indicating a work item that has been submitted to a
4273 : * queue but has not started running.
4274 : *
4275 : * Accessed via k_work_busy_get(). May co-occur with other flags.
4276 : */
4277 : K_WORK_QUEUED = BIT(K_WORK_QUEUED_BIT),
4278 :
4279 : /** @brief Flag indicating a delayed work item that is scheduled for
4280 : * submission to a queue.
4281 : *
4282 : * Accessed via k_work_busy_get(). May co-occur with other flags.
4283 : */
4284 : K_WORK_DELAYED = BIT(K_WORK_DELAYED_BIT),
4285 :
4286 : /** @brief Flag indicating a synced work item that is being flushed.
4287 : *
4288 : * Accessed via k_work_busy_get(). May co-occur with other flags.
4289 : */
4290 : K_WORK_FLUSHING = BIT(K_WORK_FLUSHING_BIT),
4291 : };
4292 :
4293 : /** @brief A structure used to submit work. */
4294 1 : struct k_work {
4295 : /* All fields are protected by the work module spinlock. No fields
4296 : * are to be accessed except through kernel API.
4297 : */
4298 :
4299 : /* Node to link into k_work_q pending list. */
4300 0 : sys_snode_t node;
4301 :
4302 : /* The function to be invoked by the work queue thread. */
4303 0 : k_work_handler_t handler;
4304 :
4305 : /* The queue on which the work item was last submitted. */
4306 0 : struct k_work_q *queue;
4307 :
4308 : /* State of the work item.
4309 : *
4310 : * The item can be DELAYED, QUEUED, and RUNNING simultaneously.
4311 : *
4312 : * It can be RUNNING and CANCELING simultaneously.
4313 : */
4314 0 : uint32_t flags;
4315 : };
4316 :
4317 : #define Z_WORK_INITIALIZER(work_handler) { \
4318 : .handler = (work_handler), \
4319 : }
4320 :
4321 : /** @brief A structure used to submit work after a delay. */
4322 1 : struct k_work_delayable {
4323 : /* The work item. */
4324 0 : struct k_work work;
4325 :
4326 : /* Timeout used to submit work after a delay. */
4327 0 : struct _timeout timeout;
4328 :
4329 : /* The queue to which the work should be submitted. */
4330 0 : struct k_work_q *queue;
4331 : };
4332 :
4333 : #define Z_WORK_DELAYABLE_INITIALIZER(work_handler) { \
4334 : .work = { \
4335 : .handler = (work_handler), \
4336 : .flags = K_WORK_DELAYABLE, \
4337 : }, \
4338 : }
4339 :
4340 : /**
4341 : * @brief Initialize a statically-defined delayable work item.
4342 : *
4343 : * This macro can be used to initialize a statically-defined delayable
4344 : * work item, prior to its first use. For example,
4345 : *
4346 : * @code static K_WORK_DELAYABLE_DEFINE(<dwork>, <work_handler>); @endcode
4347 : *
4348 : * Note that if the runtime dependencies support initialization with
4349 : * k_work_init_delayable() using that will eliminate the initialized
4350 : * object in ROM that is produced by this macro and copied in at
4351 : * system startup.
4352 : *
4353 : * @param work Symbol name for delayable work item object
4354 : * @param work_handler Function to invoke each time work item is processed.
4355 : */
4356 1 : #define K_WORK_DELAYABLE_DEFINE(work, work_handler) \
4357 : struct k_work_delayable work \
4358 : = Z_WORK_DELAYABLE_INITIALIZER(work_handler)
4359 :
4360 : /**
4361 : * @cond INTERNAL_HIDDEN
4362 : */
4363 :
4364 : /* Record used to wait for work to flush.
4365 : *
4366 : * The work item is inserted into the queue that will process (or is
4367 : * processing) the item, and will be processed as soon as the item
4368 : * completes. When the flusher is processed the semaphore will be
4369 : * signaled, releasing the thread waiting for the flush.
4370 : */
4371 : struct z_work_flusher {
4372 : struct k_work work;
4373 : struct k_sem sem;
4374 : };
4375 :
4376 : /* Record used to wait for work to complete a cancellation.
4377 : *
4378 : * The work item is inserted into a global queue of pending cancels.
4379 : * When a cancelling work item goes idle any matching waiters are
4380 : * removed from pending_cancels and are woken.
4381 : */
4382 : struct z_work_canceller {
4383 : sys_snode_t node;
4384 : struct k_work *work;
4385 : struct k_sem sem;
4386 : };
4387 :
4388 : /**
4389 : * INTERNAL_HIDDEN @endcond
4390 : */
4391 :
4392 : /** @brief A structure holding internal state for a pending synchronous
4393 : * operation on a work item or queue.
4394 : *
4395 : * Instances of this type are provided by the caller for invocation of
4396 : * k_work_flush(), k_work_cancel_sync() and sibling flush and cancel APIs. A
4397 : * referenced object must persist until the call returns, and be accessible
4398 : * from both the caller thread and the work queue thread.
4399 : *
4400 : * @note If CONFIG_KERNEL_COHERENCE is enabled the object must be allocated in
4401 : * coherent memory; see arch_mem_coherent(). The stack on these architectures
4402 : * is generally not coherent. be stack-allocated. Violations are detected by
4403 : * runtime assertion.
4404 : */
4405 1 : struct k_work_sync {
4406 : union {
4407 0 : struct z_work_flusher flusher;
4408 0 : struct z_work_canceller canceller;
4409 0 : };
4410 : };
4411 :
4412 : /** @brief A structure holding optional configuration items for a work
4413 : * queue.
4414 : *
4415 : * This structure, and values it references, are not retained by
4416 : * k_work_queue_start().
4417 : */
4418 1 : struct k_work_queue_config {
4419 : /** The name to be given to the work queue thread.
4420 : *
4421 : * If left null the thread will not have a name.
4422 : */
4423 1 : const char *name;
4424 :
4425 : /** Control whether the work queue thread should yield between
4426 : * items.
4427 : *
4428 : * Yielding between items helps guarantee the work queue
4429 : * thread does not starve other threads, including cooperative
4430 : * ones released by a work item. This is the default behavior.
4431 : *
4432 : * Set this to @c true to prevent the work queue thread from
4433 : * yielding between items. This may be appropriate when a
4434 : * sequence of items should complete without yielding
4435 : * control.
4436 : */
4437 1 : bool no_yield;
4438 :
4439 : /** Control whether the work queue thread should be marked as
4440 : * essential thread.
4441 : */
4442 1 : bool essential;
4443 :
4444 : /** Controls whether work queue monitors work timeouts.
4445 : *
4446 : * If non-zero, and CONFIG_WORKQUEUE_WORK_TIMEOUT is enabled,
4447 : * the work queue will monitor the duration of each work item.
4448 : * If the work item handler takes longer than the specified
4449 : * time to execute, the work queue thread will be aborted, and
4450 : * an error will be logged if CONFIG_LOG is enabled.
4451 : */
4452 1 : uint32_t work_timeout_ms;
4453 : };
4454 :
4455 : /** @brief A structure used to hold work until it can be processed. */
4456 1 : struct k_work_q {
4457 : /* The thread that animates the work. */
4458 0 : struct k_thread thread;
4459 :
4460 : /* The thread ID that animates the work. This may be an external thread
4461 : * if k_work_queue_run() is used.
4462 : */
4463 0 : k_tid_t thread_id;
4464 :
4465 : /* All the following fields must be accessed only while the
4466 : * work module spinlock is held.
4467 : */
4468 :
4469 : /* List of k_work items to be worked. */
4470 0 : sys_slist_t pending;
4471 :
4472 : /* Wait queue for idle work thread. */
4473 0 : _wait_q_t notifyq;
4474 :
4475 : /* Wait queue for threads waiting for the queue to drain. */
4476 0 : _wait_q_t drainq;
4477 :
4478 : /* Flags describing queue state. */
4479 0 : uint32_t flags;
4480 :
4481 : #if defined(CONFIG_WORKQUEUE_WORK_TIMEOUT)
4482 : struct _timeout work_timeout_record;
4483 : struct k_work *work;
4484 : k_timeout_t work_timeout;
4485 : #endif /* defined(CONFIG_WORKQUEUE_WORK_TIMEOUT) */
4486 : };
4487 :
4488 : /* Provide the implementation for inline functions declared above */
4489 :
4490 1 : static inline bool k_work_is_pending(const struct k_work *work)
4491 : {
4492 : return k_work_busy_get(work) != 0;
4493 : }
4494 :
4495 : static inline struct k_work_delayable *
4496 1 : k_work_delayable_from_work(struct k_work *work)
4497 : {
4498 : return CONTAINER_OF(work, struct k_work_delayable, work);
4499 : }
4500 :
4501 1 : static inline bool k_work_delayable_is_pending(
4502 : const struct k_work_delayable *dwork)
4503 : {
4504 : return k_work_delayable_busy_get(dwork) != 0;
4505 : }
4506 :
4507 1 : static inline k_ticks_t k_work_delayable_expires_get(
4508 : const struct k_work_delayable *dwork)
4509 : {
4510 : return z_timeout_expires(&dwork->timeout);
4511 : }
4512 :
4513 1 : static inline k_ticks_t k_work_delayable_remaining_get(
4514 : const struct k_work_delayable *dwork)
4515 : {
4516 : return z_timeout_remaining(&dwork->timeout);
4517 : }
4518 :
4519 1 : static inline k_tid_t k_work_queue_thread_get(struct k_work_q *queue)
4520 : {
4521 : return queue->thread_id;
4522 : }
4523 :
4524 : /** @} */
4525 :
4526 : struct k_work_user;
4527 :
4528 : /**
4529 : * @addtogroup workqueue_apis
4530 : * @{
4531 : */
4532 :
4533 : /**
4534 : * @typedef k_work_user_handler_t
4535 : * @brief Work item handler function type for user work queues.
4536 : *
4537 : * A work item's handler function is executed by a user workqueue's thread
4538 : * when the work item is processed by the workqueue.
4539 : *
4540 : * @param work Address of the work item.
4541 : */
4542 1 : typedef void (*k_work_user_handler_t)(struct k_work_user *work);
4543 :
4544 : /**
4545 : * @cond INTERNAL_HIDDEN
4546 : */
4547 :
4548 : struct k_work_user_q {
4549 : struct k_queue queue;
4550 : struct k_thread thread;
4551 : };
4552 :
4553 : enum {
4554 : K_WORK_USER_STATE_PENDING, /* Work item pending state */
4555 : };
4556 :
4557 : struct k_work_user {
4558 : void *_reserved; /* Used by k_queue implementation. */
4559 : k_work_user_handler_t handler;
4560 : atomic_t flags;
4561 : };
4562 :
4563 : /**
4564 : * INTERNAL_HIDDEN @endcond
4565 : */
4566 :
4567 : #if defined(__cplusplus) && ((__cplusplus - 0) < 202002L)
4568 : #define Z_WORK_USER_INITIALIZER(work_handler) { NULL, work_handler, 0 }
4569 : #else
4570 : #define Z_WORK_USER_INITIALIZER(work_handler) \
4571 : { \
4572 : ._reserved = NULL, \
4573 : .handler = (work_handler), \
4574 : .flags = 0 \
4575 : }
4576 : #endif
4577 :
4578 : /**
4579 : * @brief Initialize a statically-defined user work item.
4580 : *
4581 : * This macro can be used to initialize a statically-defined user work
4582 : * item, prior to its first use. For example,
4583 : *
4584 : * @code static K_WORK_USER_DEFINE(<work>, <work_handler>); @endcode
4585 : *
4586 : * @param work Symbol name for work item object
4587 : * @param work_handler Function to invoke each time work item is processed.
4588 : */
4589 1 : #define K_WORK_USER_DEFINE(work, work_handler) \
4590 : struct k_work_user work = Z_WORK_USER_INITIALIZER(work_handler)
4591 :
4592 : /**
4593 : * @brief Initialize a userspace work item.
4594 : *
4595 : * This routine initializes a user workqueue work item, prior to its
4596 : * first use.
4597 : *
4598 : * @param work Address of work item.
4599 : * @param handler Function to invoke each time work item is processed.
4600 : */
4601 1 : static inline void k_work_user_init(struct k_work_user *work,
4602 : k_work_user_handler_t handler)
4603 : {
4604 : *work = (struct k_work_user)Z_WORK_USER_INITIALIZER(handler);
4605 : }
4606 :
4607 : /**
4608 : * @brief Check if a userspace work item is pending.
4609 : *
4610 : * This routine indicates if user work item @a work is pending in a workqueue's
4611 : * queue.
4612 : *
4613 : * @note Checking if the work is pending gives no guarantee that the
4614 : * work will still be pending when this information is used. It is up to
4615 : * the caller to make sure that this information is used in a safe manner.
4616 : *
4617 : * @funcprops \isr_ok
4618 : *
4619 : * @param work Address of work item.
4620 : *
4621 : * @return true if work item is pending, or false if it is not pending.
4622 : */
4623 1 : static inline bool k_work_user_is_pending(struct k_work_user *work)
4624 : {
4625 : return atomic_test_bit(&work->flags, K_WORK_USER_STATE_PENDING);
4626 : }
4627 :
4628 : /**
4629 : * @brief Submit a work item to a user mode workqueue
4630 : *
4631 : * Submits a work item to a workqueue that runs in user mode. A temporary
4632 : * memory allocation is made from the caller's resource pool which is freed
4633 : * once the worker thread consumes the k_work item. The workqueue
4634 : * thread must have memory access to the k_work item being submitted. The caller
4635 : * must have permission granted on the work_q parameter's queue object.
4636 : *
4637 : * @funcprops \isr_ok
4638 : *
4639 : * @param work_q Address of workqueue.
4640 : * @param work Address of work item.
4641 : *
4642 : * @retval -EBUSY if the work item was already in some workqueue
4643 : * @retval -ENOMEM if no memory for thread resource pool allocation
4644 : * @retval 0 Success
4645 : */
4646 1 : static inline int k_work_user_submit_to_queue(struct k_work_user_q *work_q,
4647 : struct k_work_user *work)
4648 : {
4649 : int ret = -EBUSY;
4650 :
4651 : if (!atomic_test_and_set_bit(&work->flags,
4652 : K_WORK_USER_STATE_PENDING)) {
4653 : ret = k_queue_alloc_append(&work_q->queue, work);
4654 :
4655 : /* Couldn't insert into the queue. Clear the pending bit
4656 : * so the work item can be submitted again
4657 : */
4658 : if (ret != 0) {
4659 : atomic_clear_bit(&work->flags,
4660 : K_WORK_USER_STATE_PENDING);
4661 : }
4662 : }
4663 :
4664 : return ret;
4665 : }
4666 :
4667 : /**
4668 : * @brief Start a workqueue in user mode
4669 : *
4670 : * This works identically to k_work_queue_start() except it is callable from
4671 : * user mode, and the worker thread created will run in user mode. The caller
4672 : * must have permissions granted on both the work_q parameter's thread and
4673 : * queue objects, and the same restrictions on priority apply as
4674 : * k_thread_create().
4675 : *
4676 : * @param work_q Address of workqueue.
4677 : * @param stack Pointer to work queue thread's stack space, as defined by
4678 : * K_THREAD_STACK_DEFINE()
4679 : * @param stack_size Size of the work queue thread's stack (in bytes), which
4680 : * should either be the same constant passed to
4681 : * K_THREAD_STACK_DEFINE() or the value of K_THREAD_STACK_SIZEOF().
4682 : * @param prio Priority of the work queue's thread.
4683 : * @param name optional thread name. If not null a copy is made into the
4684 : * thread's name buffer.
4685 : */
4686 1 : void k_work_user_queue_start(struct k_work_user_q *work_q,
4687 : k_thread_stack_t *stack,
4688 : size_t stack_size, int prio,
4689 : const char *name);
4690 :
4691 : /**
4692 : * @brief Access the user mode thread that animates a work queue.
4693 : *
4694 : * This is necessary to grant a user mode work queue thread access to things
4695 : * the work items it will process are expected to use.
4696 : *
4697 : * @param work_q pointer to the user mode queue structure.
4698 : *
4699 : * @return the user mode thread associated with the work queue.
4700 : */
4701 1 : static inline k_tid_t k_work_user_queue_thread_get(struct k_work_user_q *work_q)
4702 : {
4703 : return &work_q->thread;
4704 : }
4705 :
4706 : /** @} */
4707 :
4708 : /**
4709 : * @cond INTERNAL_HIDDEN
4710 : */
4711 :
4712 : struct k_work_poll {
4713 : struct k_work work;
4714 : struct k_work_q *workq;
4715 : struct z_poller poller;
4716 : struct k_poll_event *events;
4717 : int num_events;
4718 : k_work_handler_t real_handler;
4719 : struct _timeout timeout;
4720 : int poll_result;
4721 : };
4722 :
4723 : /**
4724 : * INTERNAL_HIDDEN @endcond
4725 : */
4726 :
4727 : /**
4728 : * @addtogroup workqueue_apis
4729 : * @{
4730 : */
4731 :
4732 : /**
4733 : * @brief Initialize a statically-defined work item.
4734 : *
4735 : * This macro can be used to initialize a statically-defined workqueue work
4736 : * item, prior to its first use. For example,
4737 : *
4738 : * @code static K_WORK_DEFINE(<work>, <work_handler>); @endcode
4739 : *
4740 : * @param work Symbol name for work item object
4741 : * @param work_handler Function to invoke each time work item is processed.
4742 : */
4743 1 : #define K_WORK_DEFINE(work, work_handler) \
4744 : struct k_work work = Z_WORK_INITIALIZER(work_handler)
4745 :
4746 : /**
4747 : * @brief Initialize a triggered work item.
4748 : *
4749 : * This routine initializes a workqueue triggered work item, prior to
4750 : * its first use.
4751 : *
4752 : * @param work Address of triggered work item.
4753 : * @param handler Function to invoke each time work item is processed.
4754 : */
4755 1 : void k_work_poll_init(struct k_work_poll *work,
4756 : k_work_handler_t handler);
4757 :
4758 : /**
4759 : * @brief Submit a triggered work item.
4760 : *
4761 : * This routine schedules work item @a work to be processed by workqueue
4762 : * @a work_q when one of the given @a events is signaled. The routine
4763 : * initiates internal poller for the work item and then returns to the caller.
4764 : * Only when one of the watched events happen the work item is actually
4765 : * submitted to the workqueue and becomes pending.
4766 : *
4767 : * Submitting a previously submitted triggered work item that is still
4768 : * waiting for the event cancels the existing submission and reschedules it
4769 : * the using the new event list. Note that this behavior is inherently subject
4770 : * to race conditions with the pre-existing triggered work item and work queue,
4771 : * so care must be taken to synchronize such resubmissions externally.
4772 : *
4773 : * @funcprops \isr_ok
4774 : *
4775 : * @warning
4776 : * Provided array of events as well as a triggered work item must be placed
4777 : * in persistent memory (valid until work handler execution or work
4778 : * cancellation) and cannot be modified after submission.
4779 : *
4780 : * @param work_q Address of workqueue.
4781 : * @param work Address of delayed work item.
4782 : * @param events An array of events which trigger the work.
4783 : * @param num_events The number of events in the array.
4784 : * @param timeout Timeout after which the work will be scheduled
4785 : * for execution even if not triggered.
4786 : *
4787 : *
4788 : * @retval 0 Work item started watching for events.
4789 : * @retval -EINVAL Work item is being processed or has completed its work.
4790 : * @retval -EADDRINUSE Work item is pending on a different workqueue.
4791 : */
4792 1 : int k_work_poll_submit_to_queue(struct k_work_q *work_q,
4793 : struct k_work_poll *work,
4794 : struct k_poll_event *events,
4795 : int num_events,
4796 : k_timeout_t timeout);
4797 :
4798 : /**
4799 : * @brief Submit a triggered work item to the system workqueue.
4800 : *
4801 : * This routine schedules work item @a work to be processed by system
4802 : * workqueue when one of the given @a events is signaled. The routine
4803 : * initiates internal poller for the work item and then returns to the caller.
4804 : * Only when one of the watched events happen the work item is actually
4805 : * submitted to the workqueue and becomes pending.
4806 : *
4807 : * Submitting a previously submitted triggered work item that is still
4808 : * waiting for the event cancels the existing submission and reschedules it
4809 : * the using the new event list. Note that this behavior is inherently subject
4810 : * to race conditions with the pre-existing triggered work item and work queue,
4811 : * so care must be taken to synchronize such resubmissions externally.
4812 : *
4813 : * @funcprops \isr_ok
4814 : *
4815 : * @warning
4816 : * Provided array of events as well as a triggered work item must not be
4817 : * modified until the item has been processed by the workqueue.
4818 : *
4819 : * @param work Address of delayed work item.
4820 : * @param events An array of events which trigger the work.
4821 : * @param num_events The number of events in the array.
4822 : * @param timeout Timeout after which the work will be scheduled
4823 : * for execution even if not triggered.
4824 : *
4825 : * @retval 0 Work item started watching for events.
4826 : * @retval -EINVAL Work item is being processed or has completed its work.
4827 : * @retval -EADDRINUSE Work item is pending on a different workqueue.
4828 : */
4829 1 : int k_work_poll_submit(struct k_work_poll *work,
4830 : struct k_poll_event *events,
4831 : int num_events,
4832 : k_timeout_t timeout);
4833 :
4834 : /**
4835 : * @brief Cancel a triggered work item.
4836 : *
4837 : * This routine cancels the submission of triggered work item @a work.
4838 : * A triggered work item can only be canceled if no event triggered work
4839 : * submission.
4840 : *
4841 : * @funcprops \isr_ok
4842 : *
4843 : * @param work Address of delayed work item.
4844 : *
4845 : * @retval 0 Work item canceled.
4846 : * @retval -EINVAL Work item is being processed or has completed its work.
4847 : */
4848 1 : int k_work_poll_cancel(struct k_work_poll *work);
4849 :
4850 : /** @} */
4851 :
4852 : /**
4853 : * @defgroup msgq_apis Message Queue APIs
4854 : * @ingroup kernel_apis
4855 : * @{
4856 : */
4857 :
4858 : /**
4859 : * @brief Message Queue Structure
4860 : */
4861 1 : struct k_msgq {
4862 : /** Message queue wait queue */
4863 1 : _wait_q_t wait_q;
4864 : /** Lock */
4865 1 : struct k_spinlock lock;
4866 : /** Message size */
4867 1 : size_t msg_size;
4868 : /** Maximal number of messages */
4869 1 : uint32_t max_msgs;
4870 : /** Start of message buffer */
4871 1 : char *buffer_start;
4872 : /** End of message buffer */
4873 1 : char *buffer_end;
4874 : /** Read pointer */
4875 1 : char *read_ptr;
4876 : /** Write pointer */
4877 1 : char *write_ptr;
4878 : /** Number of used messages */
4879 1 : uint32_t used_msgs;
4880 :
4881 : Z_DECL_POLL_EVENT
4882 :
4883 : /** Message queue */
4884 1 : uint8_t flags;
4885 :
4886 : SYS_PORT_TRACING_TRACKING_FIELD(k_msgq)
4887 :
4888 : #ifdef CONFIG_OBJ_CORE_MSGQ
4889 : struct k_obj_core obj_core;
4890 : #endif
4891 : };
4892 : /**
4893 : * @cond INTERNAL_HIDDEN
4894 : */
4895 :
4896 :
4897 : #define Z_MSGQ_INITIALIZER(obj, q_buffer, q_msg_size, q_max_msgs) \
4898 : { \
4899 : .wait_q = Z_WAIT_Q_INIT(&obj.wait_q), \
4900 : .lock = {}, \
4901 : .msg_size = q_msg_size, \
4902 : .max_msgs = q_max_msgs, \
4903 : .buffer_start = q_buffer, \
4904 : .buffer_end = q_buffer + (q_max_msgs * q_msg_size), \
4905 : .read_ptr = q_buffer, \
4906 : .write_ptr = q_buffer, \
4907 : .used_msgs = 0, \
4908 : Z_POLL_EVENT_OBJ_INIT(obj) \
4909 : .flags = 0, \
4910 : }
4911 :
4912 : /**
4913 : * INTERNAL_HIDDEN @endcond
4914 : */
4915 :
4916 :
4917 0 : #define K_MSGQ_FLAG_ALLOC BIT(0)
4918 :
4919 : /**
4920 : * @brief Message Queue Attributes
4921 : */
4922 1 : struct k_msgq_attrs {
4923 : /** Message Size */
4924 1 : size_t msg_size;
4925 : /** Maximal number of messages */
4926 1 : uint32_t max_msgs;
4927 : /** Used messages */
4928 1 : uint32_t used_msgs;
4929 : };
4930 :
4931 :
4932 : /**
4933 : * @brief Statically define and initialize a message queue.
4934 : *
4935 : * The message queue's ring buffer contains space for @a q_max_msgs messages,
4936 : * each of which is @a q_msg_size bytes long. Alignment of the message queue's
4937 : * ring buffer is not necessary, setting @a q_align to 1 is sufficient.
4938 : *
4939 : * The message queue can be accessed outside the module where it is defined
4940 : * using:
4941 : *
4942 : * @code extern struct k_msgq <name>; @endcode
4943 : *
4944 : * @param q_name Name of the message queue.
4945 : * @param q_msg_size Message size (in bytes).
4946 : * @param q_max_msgs Maximum number of messages that can be queued.
4947 : * @param q_align Alignment of the message queue's ring buffer (power of 2).
4948 : *
4949 : */
4950 1 : #define K_MSGQ_DEFINE(q_name, q_msg_size, q_max_msgs, q_align) \
4951 : static char __noinit __aligned(q_align) \
4952 : _k_fifo_buf_##q_name[(q_max_msgs) * (q_msg_size)]; \
4953 : STRUCT_SECTION_ITERABLE(k_msgq, q_name) = \
4954 : Z_MSGQ_INITIALIZER(q_name, _k_fifo_buf_##q_name, \
4955 : (q_msg_size), (q_max_msgs))
4956 :
4957 : /**
4958 : * @brief Initialize a message queue.
4959 : *
4960 : * This routine initializes a message queue object, prior to its first use.
4961 : *
4962 : * The message queue's ring buffer must contain space for @a max_msgs messages,
4963 : * each of which is @a msg_size bytes long. Alignment of the message queue's
4964 : * ring buffer is not necessary.
4965 : *
4966 : * @param msgq Address of the message queue.
4967 : * @param buffer Pointer to ring buffer that holds queued messages.
4968 : * @param msg_size Message size (in bytes).
4969 : * @param max_msgs Maximum number of messages that can be queued.
4970 : */
4971 1 : void k_msgq_init(struct k_msgq *msgq, char *buffer, size_t msg_size,
4972 : uint32_t max_msgs);
4973 :
4974 : /**
4975 : * @brief Initialize a message queue.
4976 : *
4977 : * This routine initializes a message queue object, prior to its first use,
4978 : * allocating its internal ring buffer from the calling thread's resource
4979 : * pool.
4980 : *
4981 : * Memory allocated for the ring buffer can be released by calling
4982 : * k_msgq_cleanup(), or if userspace is enabled and the msgq object loses
4983 : * all of its references.
4984 : *
4985 : * @param msgq Address of the message queue.
4986 : * @param msg_size Message size (in bytes).
4987 : * @param max_msgs Maximum number of messages that can be queued.
4988 : *
4989 : * @return 0 on success, -ENOMEM if there was insufficient memory in the
4990 : * thread's resource pool, or -EINVAL if the size parameters cause
4991 : * an integer overflow.
4992 : */
4993 1 : __syscall int k_msgq_alloc_init(struct k_msgq *msgq, size_t msg_size,
4994 : uint32_t max_msgs);
4995 :
4996 : /**
4997 : * @brief Release allocated buffer for a queue
4998 : *
4999 : * Releases memory allocated for the ring buffer.
5000 : *
5001 : * @param msgq message queue to cleanup
5002 : *
5003 : * @retval 0 on success
5004 : * @retval -EBUSY Queue not empty
5005 : */
5006 1 : int k_msgq_cleanup(struct k_msgq *msgq);
5007 :
5008 : /**
5009 : * @brief Send a message to the end of a message queue.
5010 : *
5011 : * This routine sends a message to message queue @a q.
5012 : *
5013 : * @note The message content is copied from @a data into @a msgq and the @a data
5014 : * pointer is not retained, so the message content will not be modified
5015 : * by this function.
5016 : *
5017 : * @funcprops \isr_ok
5018 : *
5019 : * @param msgq Address of the message queue.
5020 : * @param data Pointer to the message.
5021 : * @param timeout Waiting period to add the message, or one of the special
5022 : * values K_NO_WAIT and K_FOREVER.
5023 : *
5024 : * @retval 0 Message sent.
5025 : * @retval -ENOMSG Returned without waiting or queue purged.
5026 : * @retval -EAGAIN Waiting period timed out.
5027 : */
5028 1 : __syscall int k_msgq_put(struct k_msgq *msgq, const void *data, k_timeout_t timeout);
5029 :
5030 : /**
5031 : * @brief Send a message to the front of a message queue.
5032 : *
5033 : * This routine sends a message to the beginning (head) of message queue @a q.
5034 : * Messages sent with this method will be retrieved before any pre-existing
5035 : * messages in the queue.
5036 : *
5037 : * @note if there is no space in the message queue, this function will
5038 : * behave the same as k_msgq_put.
5039 : *
5040 : * @note The message content is copied from @a data into @a msgq and the @a data
5041 : * pointer is not retained, so the message content will not be modified
5042 : * by this function.
5043 : *
5044 : * @note k_msgq_put_front() does not block.
5045 : *
5046 : * @funcprops \isr_ok
5047 : *
5048 : * @param msgq Address of the message queue.
5049 : * @param data Pointer to the message.
5050 : *
5051 : * @retval 0 Message sent.
5052 : * @retval -ENOMSG Returned without waiting or queue purged.
5053 : */
5054 1 : __syscall int k_msgq_put_front(struct k_msgq *msgq, const void *data);
5055 :
5056 : /**
5057 : * @brief Receive a message from a message queue.
5058 : *
5059 : * This routine receives a message from message queue @a q in a "first in,
5060 : * first out" manner.
5061 : *
5062 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
5063 : *
5064 : * @funcprops \isr_ok
5065 : *
5066 : * @param msgq Address of the message queue.
5067 : * @param data Address of area to hold the received message.
5068 : * @param timeout Waiting period to receive the message,
5069 : * or one of the special values K_NO_WAIT and
5070 : * K_FOREVER.
5071 : *
5072 : * @retval 0 Message received.
5073 : * @retval -ENOMSG Returned without waiting or queue purged.
5074 : * @retval -EAGAIN Waiting period timed out.
5075 : */
5076 1 : __syscall int k_msgq_get(struct k_msgq *msgq, void *data, k_timeout_t timeout);
5077 :
5078 : /**
5079 : * @brief Peek/read a message from a message queue.
5080 : *
5081 : * This routine reads a message from message queue @a q in a "first in,
5082 : * first out" manner and leaves the message in the queue.
5083 : *
5084 : * @funcprops \isr_ok
5085 : *
5086 : * @param msgq Address of the message queue.
5087 : * @param data Address of area to hold the message read from the queue.
5088 : *
5089 : * @retval 0 Message read.
5090 : * @retval -ENOMSG Returned when the queue has no message.
5091 : */
5092 1 : __syscall int k_msgq_peek(struct k_msgq *msgq, void *data);
5093 :
5094 : /**
5095 : * @brief Peek/read a message from a message queue at the specified index
5096 : *
5097 : * This routine reads a message from message queue at the specified index
5098 : * and leaves the message in the queue.
5099 : * k_msgq_peek_at(msgq, data, 0) is equivalent to k_msgq_peek(msgq, data)
5100 : *
5101 : * @funcprops \isr_ok
5102 : *
5103 : * @param msgq Address of the message queue.
5104 : * @param data Address of area to hold the message read from the queue.
5105 : * @param idx Message queue index at which to peek
5106 : *
5107 : * @retval 0 Message read.
5108 : * @retval -ENOMSG Returned when the queue has no message at index.
5109 : */
5110 1 : __syscall int k_msgq_peek_at(struct k_msgq *msgq, void *data, uint32_t idx);
5111 :
5112 : /**
5113 : * @brief Purge a message queue.
5114 : *
5115 : * This routine discards all unreceived messages in a message queue's ring
5116 : * buffer. Any threads that are blocked waiting to send a message to the
5117 : * message queue are unblocked and see an -ENOMSG error code.
5118 : *
5119 : * @param msgq Address of the message queue.
5120 : */
5121 1 : __syscall void k_msgq_purge(struct k_msgq *msgq);
5122 :
5123 : /**
5124 : * @brief Get the amount of free space in a message queue.
5125 : *
5126 : * This routine returns the number of unused entries in a message queue's
5127 : * ring buffer.
5128 : *
5129 : * @param msgq Address of the message queue.
5130 : *
5131 : * @return Number of unused ring buffer entries.
5132 : */
5133 1 : __syscall uint32_t k_msgq_num_free_get(struct k_msgq *msgq);
5134 :
5135 : /**
5136 : * @brief Get basic attributes of a message queue.
5137 : *
5138 : * This routine fetches basic attributes of message queue into attr argument.
5139 : *
5140 : * @param msgq Address of the message queue.
5141 : * @param attrs pointer to message queue attribute structure.
5142 : */
5143 1 : __syscall void k_msgq_get_attrs(struct k_msgq *msgq,
5144 : struct k_msgq_attrs *attrs);
5145 :
5146 :
5147 : static inline uint32_t z_impl_k_msgq_num_free_get(struct k_msgq *msgq)
5148 : {
5149 : return msgq->max_msgs - msgq->used_msgs;
5150 : }
5151 :
5152 : /**
5153 : * @brief Get the number of messages in a message queue.
5154 : *
5155 : * This routine returns the number of messages in a message queue's ring buffer.
5156 : *
5157 : * @param msgq Address of the message queue.
5158 : *
5159 : * @return Number of messages.
5160 : */
5161 1 : __syscall uint32_t k_msgq_num_used_get(struct k_msgq *msgq);
5162 :
5163 : static inline uint32_t z_impl_k_msgq_num_used_get(struct k_msgq *msgq)
5164 : {
5165 : return msgq->used_msgs;
5166 : }
5167 :
5168 : /** @} */
5169 :
5170 : /**
5171 : * @defgroup mailbox_apis Mailbox APIs
5172 : * @ingroup kernel_apis
5173 : * @{
5174 : */
5175 :
5176 : /**
5177 : * @brief Mailbox Message Structure
5178 : *
5179 : */
5180 1 : struct k_mbox_msg {
5181 : /** size of message (in bytes) */
5182 1 : size_t size;
5183 : /** application-defined information value */
5184 1 : uint32_t info;
5185 : /** sender's message data buffer */
5186 1 : void *tx_data;
5187 : /** source thread id */
5188 1 : k_tid_t rx_source_thread;
5189 : /** target thread id */
5190 1 : k_tid_t tx_target_thread;
5191 : /** internal use only - thread waiting on send (may be a dummy) */
5192 : k_tid_t _syncing_thread;
5193 : #if (CONFIG_NUM_MBOX_ASYNC_MSGS > 0)
5194 : /** internal use only - semaphore used during asynchronous send */
5195 : struct k_sem *_async_sem;
5196 : #endif
5197 : };
5198 : /**
5199 : * @brief Mailbox Structure
5200 : *
5201 : */
5202 1 : struct k_mbox {
5203 : /** Transmit messages queue */
5204 1 : _wait_q_t tx_msg_queue;
5205 : /** Receive message queue */
5206 1 : _wait_q_t rx_msg_queue;
5207 0 : struct k_spinlock lock;
5208 :
5209 : SYS_PORT_TRACING_TRACKING_FIELD(k_mbox)
5210 :
5211 : #ifdef CONFIG_OBJ_CORE_MAILBOX
5212 : struct k_obj_core obj_core;
5213 : #endif
5214 : };
5215 : /**
5216 : * @cond INTERNAL_HIDDEN
5217 : */
5218 :
5219 : #define Z_MBOX_INITIALIZER(obj) \
5220 : { \
5221 : .tx_msg_queue = Z_WAIT_Q_INIT(&obj.tx_msg_queue), \
5222 : .rx_msg_queue = Z_WAIT_Q_INIT(&obj.rx_msg_queue), \
5223 : }
5224 :
5225 : /**
5226 : * INTERNAL_HIDDEN @endcond
5227 : */
5228 :
5229 : /**
5230 : * @brief Statically define and initialize a mailbox.
5231 : *
5232 : * The mailbox is to be accessed outside the module where it is defined using:
5233 : *
5234 : * @code extern struct k_mbox <name>; @endcode
5235 : *
5236 : * @param name Name of the mailbox.
5237 : */
5238 1 : #define K_MBOX_DEFINE(name) \
5239 : STRUCT_SECTION_ITERABLE(k_mbox, name) = \
5240 : Z_MBOX_INITIALIZER(name) \
5241 :
5242 : /**
5243 : * @brief Initialize a mailbox.
5244 : *
5245 : * This routine initializes a mailbox object, prior to its first use.
5246 : *
5247 : * @param mbox Address of the mailbox.
5248 : */
5249 1 : void k_mbox_init(struct k_mbox *mbox);
5250 :
5251 : /**
5252 : * @brief Send a mailbox message in a synchronous manner.
5253 : *
5254 : * This routine sends a message to @a mbox and waits for a receiver to both
5255 : * receive and process it. The message data may be in a buffer or non-existent
5256 : * (i.e. an empty message).
5257 : *
5258 : * @param mbox Address of the mailbox.
5259 : * @param tx_msg Address of the transmit message descriptor.
5260 : * @param timeout Waiting period for the message to be received,
5261 : * or one of the special values K_NO_WAIT
5262 : * and K_FOREVER. Once the message has been received,
5263 : * this routine waits as long as necessary for the message
5264 : * to be completely processed.
5265 : *
5266 : * @retval 0 Message sent.
5267 : * @retval -ENOMSG Returned without waiting.
5268 : * @retval -EAGAIN Waiting period timed out.
5269 : */
5270 1 : int k_mbox_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg,
5271 : k_timeout_t timeout);
5272 :
5273 : /**
5274 : * @brief Send a mailbox message in an asynchronous manner.
5275 : *
5276 : * This routine sends a message to @a mbox without waiting for a receiver
5277 : * to process it. The message data may be in a buffer or non-existent
5278 : * (i.e. an empty message). Optionally, the semaphore @a sem will be given
5279 : * when the message has been both received and completely processed by
5280 : * the receiver.
5281 : *
5282 : * @param mbox Address of the mailbox.
5283 : * @param tx_msg Address of the transmit message descriptor.
5284 : * @param sem Address of a semaphore, or NULL if none is needed.
5285 : */
5286 1 : void k_mbox_async_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg,
5287 : struct k_sem *sem);
5288 :
5289 : /**
5290 : * @brief Receive a mailbox message.
5291 : *
5292 : * This routine receives a message from @a mbox, then optionally retrieves
5293 : * its data and disposes of the message.
5294 : *
5295 : * @param mbox Address of the mailbox.
5296 : * @param rx_msg Address of the receive message descriptor.
5297 : * @param buffer Address of the buffer to receive data, or NULL to defer data
5298 : * retrieval and message disposal until later.
5299 : * @param timeout Waiting period for a message to be received,
5300 : * or one of the special values K_NO_WAIT and K_FOREVER.
5301 : *
5302 : * @retval 0 Message received.
5303 : * @retval -ENOMSG Returned without waiting.
5304 : * @retval -EAGAIN Waiting period timed out.
5305 : */
5306 1 : int k_mbox_get(struct k_mbox *mbox, struct k_mbox_msg *rx_msg,
5307 : void *buffer, k_timeout_t timeout);
5308 :
5309 : /**
5310 : * @brief Retrieve mailbox message data into a buffer.
5311 : *
5312 : * This routine completes the processing of a received message by retrieving
5313 : * its data into a buffer, then disposing of the message.
5314 : *
5315 : * Alternatively, this routine can be used to dispose of a received message
5316 : * without retrieving its data.
5317 : *
5318 : * @param rx_msg Address of the receive message descriptor.
5319 : * @param buffer Address of the buffer to receive data, or NULL to discard
5320 : * the data.
5321 : */
5322 1 : void k_mbox_data_get(struct k_mbox_msg *rx_msg, void *buffer);
5323 :
5324 : /** @} */
5325 :
5326 : /**
5327 : * @defgroup pipe_apis Pipe APIs
5328 : * @ingroup kernel_apis
5329 : * @{
5330 : */
5331 :
5332 : /**
5333 : * @brief initialize a pipe
5334 : *
5335 : * This routine initializes a pipe object, prior to its first use.
5336 : *
5337 : * @param pipe Address of the pipe.
5338 : * @param buffer Address of the pipe's buffer, or NULL if no ring buffer is used.
5339 : * @param buffer_size Size of the pipe's buffer, or zero if no ring buffer is used.
5340 : */
5341 1 : __syscall void k_pipe_init(struct k_pipe *pipe, uint8_t *buffer, size_t buffer_size);
5342 :
5343 0 : enum pipe_flags {
5344 : PIPE_FLAG_OPEN = BIT(0),
5345 : PIPE_FLAG_RESET = BIT(1),
5346 : };
5347 :
5348 0 : struct k_pipe {
5349 0 : size_t waiting;
5350 0 : struct ring_buf buf;
5351 0 : struct k_spinlock lock;
5352 0 : _wait_q_t data;
5353 0 : _wait_q_t space;
5354 0 : uint8_t flags;
5355 :
5356 : Z_DECL_POLL_EVENT
5357 : #ifdef CONFIG_OBJ_CORE_PIPE
5358 : struct k_obj_core obj_core;
5359 : #endif
5360 : SYS_PORT_TRACING_TRACKING_FIELD(k_pipe)
5361 : };
5362 :
5363 : /**
5364 : * @cond INTERNAL_HIDDEN
5365 : */
5366 : #define Z_PIPE_INITIALIZER(obj, pipe_buffer, pipe_buffer_size) \
5367 : { \
5368 : .waiting = 0, \
5369 : .buf = RING_BUF_INIT(pipe_buffer, pipe_buffer_size), \
5370 : .data = Z_WAIT_Q_INIT(&obj.data), \
5371 : .space = Z_WAIT_Q_INIT(&obj.space), \
5372 : .flags = PIPE_FLAG_OPEN, \
5373 : Z_POLL_EVENT_OBJ_INIT(obj) \
5374 : }
5375 : /**
5376 : * INTERNAL_HIDDEN @endcond
5377 : */
5378 :
5379 : /**
5380 : * @brief Statically define and initialize a pipe.
5381 : *
5382 : * The pipe can be accessed outside the module where it is defined using:
5383 : *
5384 : * @code extern struct k_pipe <name>; @endcode
5385 : *
5386 : * @param name Name of the pipe.
5387 : * @param pipe_buffer_size Size of the pipe's ring buffer (in bytes)
5388 : * or zero if no ring buffer is used.
5389 : * @param pipe_align Alignment of the pipe's ring buffer (power of 2).
5390 : *
5391 : */
5392 1 : #define K_PIPE_DEFINE(name, pipe_buffer_size, pipe_align) \
5393 : static unsigned char __noinit __aligned(pipe_align) \
5394 : _k_pipe_buf_##name[pipe_buffer_size]; \
5395 : STRUCT_SECTION_ITERABLE(k_pipe, name) = \
5396 : Z_PIPE_INITIALIZER(name, _k_pipe_buf_##name, pipe_buffer_size)
5397 :
5398 :
5399 : /**
5400 : * @brief Write data to a pipe
5401 : *
5402 : * This routine writes up to @a len bytes of data to @a pipe.
5403 : * If the pipe is full, the routine will block until the data can be written or the timeout expires.
5404 : *
5405 : * @param pipe Address of the pipe.
5406 : * @param data Address of data to write.
5407 : * @param len Size of data (in bytes).
5408 : * @param timeout Waiting period to wait for the data to be written.
5409 : *
5410 : * @retval number of bytes written on success
5411 : * @retval -EAGAIN if no data could be written before the timeout expired
5412 : * @retval -ECANCELED if the write was interrupted by k_pipe_reset(..)
5413 : * @retval -EPIPE if the pipe was closed
5414 : */
5415 1 : __syscall int k_pipe_write(struct k_pipe *pipe, const uint8_t *data, size_t len,
5416 : k_timeout_t timeout);
5417 :
5418 : /**
5419 : * @brief Read data from a pipe
5420 : * This routine reads up to @a len bytes of data from @a pipe.
5421 : * If the pipe is empty, the routine will block until the data can be read or the timeout expires.
5422 : *
5423 : * @param pipe Address of the pipe.
5424 : * @param data Address to place the data read from pipe.
5425 : * @param len Requested number of bytes to read.
5426 : * @param timeout Waiting period to wait for the data to be read.
5427 : *
5428 : * @retval number of bytes read on success
5429 : * @retval -EAGAIN if no data could be read before the timeout expired
5430 : * @retval -ECANCELED if the read was interrupted by k_pipe_reset(..)
5431 : * @retval -EPIPE if the pipe was closed
5432 : */
5433 1 : __syscall int k_pipe_read(struct k_pipe *pipe, uint8_t *data, size_t len,
5434 : k_timeout_t timeout);
5435 :
5436 : /**
5437 : * @brief Reset a pipe
5438 : * This routine resets the pipe, discarding any unread data and unblocking any threads waiting to
5439 : * write or read, causing the waiting threads to return with -ECANCELED. Calling k_pipe_read(..) or
5440 : * k_pipe_write(..) when the pipe is resetting but not yet reset will return -ECANCELED.
5441 : * The pipe is left open after a reset and can be used as normal.
5442 : *
5443 : * @param pipe Address of the pipe.
5444 : */
5445 1 : __syscall void k_pipe_reset(struct k_pipe *pipe);
5446 :
5447 : /**
5448 : * @brief Close a pipe
5449 : *
5450 : * This routine closes a pipe. Any threads that were blocked on the pipe
5451 : * will be unblocked and receive an error code.
5452 : *
5453 : * @param pipe Address of the pipe.
5454 : */
5455 1 : __syscall void k_pipe_close(struct k_pipe *pipe);
5456 : /** @} */
5457 :
5458 : /**
5459 : * @cond INTERNAL_HIDDEN
5460 : */
5461 : struct k_mem_slab_info {
5462 : uint32_t num_blocks;
5463 : size_t block_size;
5464 : uint32_t num_used;
5465 : #ifdef CONFIG_MEM_SLAB_TRACE_MAX_UTILIZATION
5466 : uint32_t max_used;
5467 : #endif
5468 : };
5469 :
5470 : struct k_mem_slab {
5471 : _wait_q_t wait_q;
5472 : struct k_spinlock lock;
5473 : char *buffer;
5474 : char *free_list;
5475 : struct k_mem_slab_info info;
5476 :
5477 : SYS_PORT_TRACING_TRACKING_FIELD(k_mem_slab)
5478 :
5479 : #ifdef CONFIG_OBJ_CORE_MEM_SLAB
5480 : struct k_obj_core obj_core;
5481 : #endif
5482 : };
5483 :
5484 : #define Z_MEM_SLAB_INITIALIZER(_slab, _slab_buffer, _slab_block_size, \
5485 : _slab_num_blocks) \
5486 : { \
5487 : .wait_q = Z_WAIT_Q_INIT(&(_slab).wait_q), \
5488 : .lock = {}, \
5489 : .buffer = _slab_buffer, \
5490 : .free_list = NULL, \
5491 : .info = {_slab_num_blocks, _slab_block_size, 0} \
5492 : }
5493 :
5494 :
5495 : /**
5496 : * INTERNAL_HIDDEN @endcond
5497 : */
5498 :
5499 : /**
5500 : * @defgroup mem_slab_apis Memory Slab APIs
5501 : * @ingroup kernel_apis
5502 : * @{
5503 : */
5504 :
5505 : /**
5506 : * @brief Statically define and initialize a memory slab in a user-provided memory section with
5507 : * public (non-static) scope.
5508 : *
5509 : * The memory slab's buffer contains @a slab_num_blocks memory blocks
5510 : * that are @a slab_block_size bytes long. The buffer is aligned to a
5511 : * @a slab_align -byte boundary. To ensure that each memory block is similarly
5512 : * aligned to this boundary, @a slab_block_size must also be a multiple of
5513 : * @a slab_align.
5514 : *
5515 : * The memory slab can be accessed outside the module where it is defined
5516 : * using:
5517 : *
5518 : * @code extern struct k_mem_slab <name>; @endcode
5519 : *
5520 : * @note This macro cannot be used together with a static keyword.
5521 : * If such a use-case is desired, use @ref K_MEM_SLAB_DEFINE_IN_SECT_STATIC
5522 : * instead.
5523 : *
5524 : * @param name Name of the memory slab.
5525 : * @param in_section Section attribute specifier such as Z_GENERIC_SECTION.
5526 : * @param slab_block_size Size of each memory block (in bytes).
5527 : * @param slab_num_blocks Number memory blocks.
5528 : * @param slab_align Alignment of the memory slab's buffer (power of 2).
5529 : */
5530 1 : #define K_MEM_SLAB_DEFINE_IN_SECT(name, in_section, slab_block_size, slab_num_blocks, slab_align) \
5531 : BUILD_ASSERT(((slab_block_size) % (slab_align)) == 0, \
5532 : "slab_block_size must be a multiple of slab_align"); \
5533 : BUILD_ASSERT((((slab_align) & ((slab_align) - 1)) == 0), \
5534 : "slab_align must be a power of 2"); \
5535 : char in_section __aligned(WB_UP( \
5536 : slab_align)) _k_mem_slab_buf_##name[(slab_num_blocks) * WB_UP(slab_block_size)]; \
5537 : STRUCT_SECTION_ITERABLE(k_mem_slab, name) = Z_MEM_SLAB_INITIALIZER( \
5538 : name, _k_mem_slab_buf_##name, WB_UP(slab_block_size), slab_num_blocks)
5539 :
5540 : /**
5541 : * @brief Statically define and initialize a memory slab in a public (non-static) scope.
5542 : *
5543 : * The memory slab's buffer contains @a slab_num_blocks memory blocks
5544 : * that are @a slab_block_size bytes long. The buffer is aligned to a
5545 : * @a slab_align -byte boundary. To ensure that each memory block is similarly
5546 : * aligned to this boundary, @a slab_block_size must also be a multiple of
5547 : * @a slab_align.
5548 : *
5549 : * The memory slab can be accessed outside the module where it is defined
5550 : * using:
5551 : *
5552 : * @code extern struct k_mem_slab <name>; @endcode
5553 : *
5554 : * @note This macro cannot be used together with a static keyword.
5555 : * If such a use-case is desired, use @ref K_MEM_SLAB_DEFINE_STATIC
5556 : * instead.
5557 : *
5558 : * @param name Name of the memory slab.
5559 : * @param slab_block_size Size of each memory block (in bytes).
5560 : * @param slab_num_blocks Number memory blocks.
5561 : * @param slab_align Alignment of the memory slab's buffer (power of 2).
5562 : */
5563 1 : #define K_MEM_SLAB_DEFINE(name, slab_block_size, slab_num_blocks, slab_align) \
5564 : K_MEM_SLAB_DEFINE_IN_SECT(name, __noinit_named(k_mem_slab_buf_##name), slab_block_size, \
5565 : slab_num_blocks, slab_align)
5566 :
5567 : /**
5568 : * @brief Statically define and initialize a memory slab in a user-provided memory section with
5569 : * private (static) scope.
5570 : *
5571 : * The memory slab's buffer contains @a slab_num_blocks memory blocks
5572 : * that are @a slab_block_size bytes long. The buffer is aligned to a
5573 : * @a slab_align -byte boundary. To ensure that each memory block is similarly
5574 : * aligned to this boundary, @a slab_block_size must also be a multiple of
5575 : * @a slab_align.
5576 : *
5577 : * @param name Name of the memory slab.
5578 : * @param in_section Section attribute specifier such as Z_GENERIC_SECTION.
5579 : * @param slab_block_size Size of each memory block (in bytes).
5580 : * @param slab_num_blocks Number memory blocks.
5581 : * @param slab_align Alignment of the memory slab's buffer (power of 2).
5582 : */
5583 : #define K_MEM_SLAB_DEFINE_IN_SECT_STATIC(name, in_section, slab_block_size, slab_num_blocks, \
5584 1 : slab_align) \
5585 : BUILD_ASSERT(((slab_block_size) % (slab_align)) == 0, \
5586 : "slab_block_size must be a multiple of slab_align"); \
5587 : BUILD_ASSERT((((slab_align) & ((slab_align) - 1)) == 0), \
5588 : "slab_align must be a power of 2"); \
5589 : static char in_section __aligned(WB_UP( \
5590 : slab_align)) _k_mem_slab_buf_##name[(slab_num_blocks) * WB_UP(slab_block_size)]; \
5591 : static STRUCT_SECTION_ITERABLE(k_mem_slab, name) = Z_MEM_SLAB_INITIALIZER( \
5592 : name, _k_mem_slab_buf_##name, WB_UP(slab_block_size), slab_num_blocks)
5593 :
5594 : /**
5595 : * @brief Statically define and initialize a memory slab in a private (static) scope.
5596 : *
5597 : * The memory slab's buffer contains @a slab_num_blocks memory blocks
5598 : * that are @a slab_block_size bytes long. The buffer is aligned to a
5599 : * @a slab_align -byte boundary. To ensure that each memory block is similarly
5600 : * aligned to this boundary, @a slab_block_size must also be a multiple of
5601 : * @a slab_align.
5602 : *
5603 : * @param name Name of the memory slab.
5604 : * @param slab_block_size Size of each memory block (in bytes).
5605 : * @param slab_num_blocks Number memory blocks.
5606 : * @param slab_align Alignment of the memory slab's buffer (power of 2).
5607 : */
5608 1 : #define K_MEM_SLAB_DEFINE_STATIC(name, slab_block_size, slab_num_blocks, slab_align) \
5609 : K_MEM_SLAB_DEFINE_IN_SECT_STATIC(name, __noinit_named(k_mem_slab_buf_##name), \
5610 : slab_block_size, slab_num_blocks, slab_align)
5611 :
5612 : /**
5613 : * @brief Initialize a memory slab.
5614 : *
5615 : * Initializes a memory slab, prior to its first use.
5616 : *
5617 : * The memory slab's buffer contains @a slab_num_blocks memory blocks
5618 : * that are @a slab_block_size bytes long. The buffer must be aligned to an
5619 : * N-byte boundary matching a word boundary, where N is a power of 2
5620 : * (i.e. 4 on 32-bit systems, 8, 16, ...).
5621 : * To ensure that each memory block is similarly aligned to this boundary,
5622 : * @a slab_block_size must also be a multiple of N.
5623 : *
5624 : * @param slab Address of the memory slab.
5625 : * @param buffer Pointer to buffer used for the memory blocks.
5626 : * @param block_size Size of each memory block (in bytes).
5627 : * @param num_blocks Number of memory blocks.
5628 : *
5629 : * @retval 0 on success
5630 : * @retval -EINVAL invalid data supplied
5631 : *
5632 : */
5633 1 : int k_mem_slab_init(struct k_mem_slab *slab, void *buffer,
5634 : size_t block_size, uint32_t num_blocks);
5635 :
5636 : /**
5637 : * @brief Allocate memory from a memory slab.
5638 : *
5639 : * This routine allocates a memory block from a memory slab.
5640 : *
5641 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
5642 : * @note When CONFIG_MULTITHREADING=n any @a timeout is treated as K_NO_WAIT.
5643 : *
5644 : * @funcprops \isr_ok
5645 : *
5646 : * @param slab Address of the memory slab.
5647 : * @param mem Pointer to block address area.
5648 : * @param timeout Waiting period to wait for operation to complete.
5649 : * Use K_NO_WAIT to return without waiting,
5650 : * or K_FOREVER to wait as long as necessary.
5651 : *
5652 : * @retval 0 Memory allocated. The block address area pointed at by @a mem
5653 : * is set to the starting address of the memory block.
5654 : * @retval -ENOMEM Returned without waiting.
5655 : * @retval -EAGAIN Waiting period timed out.
5656 : * @retval -EINVAL Invalid data supplied
5657 : */
5658 1 : int k_mem_slab_alloc(struct k_mem_slab *slab, void **mem,
5659 : k_timeout_t timeout);
5660 :
5661 : /**
5662 : * @brief Free memory allocated from a memory slab.
5663 : *
5664 : * This routine releases a previously allocated memory block back to its
5665 : * associated memory slab.
5666 : *
5667 : * @param slab Address of the memory slab.
5668 : * @param mem Pointer to the memory block (as returned by k_mem_slab_alloc()).
5669 : */
5670 1 : void k_mem_slab_free(struct k_mem_slab *slab, void *mem);
5671 :
5672 : /**
5673 : * @brief Get the number of used blocks in a memory slab.
5674 : *
5675 : * This routine gets the number of memory blocks that are currently
5676 : * allocated in @a slab.
5677 : *
5678 : * @param slab Address of the memory slab.
5679 : *
5680 : * @return Number of allocated memory blocks.
5681 : */
5682 1 : static inline uint32_t k_mem_slab_num_used_get(struct k_mem_slab *slab)
5683 : {
5684 : return slab->info.num_used;
5685 : }
5686 :
5687 : /**
5688 : * @brief Get the number of maximum used blocks so far in a memory slab.
5689 : *
5690 : * This routine gets the maximum number of memory blocks that were
5691 : * allocated in @a slab.
5692 : *
5693 : * @param slab Address of the memory slab.
5694 : *
5695 : * @return Maximum number of allocated memory blocks.
5696 : */
5697 1 : static inline uint32_t k_mem_slab_max_used_get(struct k_mem_slab *slab)
5698 : {
5699 : #ifdef CONFIG_MEM_SLAB_TRACE_MAX_UTILIZATION
5700 : return slab->info.max_used;
5701 : #else
5702 : ARG_UNUSED(slab);
5703 : return 0;
5704 : #endif
5705 : }
5706 :
5707 : /**
5708 : * @brief Get the number of unused blocks in a memory slab.
5709 : *
5710 : * This routine gets the number of memory blocks that are currently
5711 : * unallocated in @a slab.
5712 : *
5713 : * @param slab Address of the memory slab.
5714 : *
5715 : * @return Number of unallocated memory blocks.
5716 : */
5717 1 : static inline uint32_t k_mem_slab_num_free_get(struct k_mem_slab *slab)
5718 : {
5719 : return slab->info.num_blocks - slab->info.num_used;
5720 : }
5721 :
5722 : /**
5723 : * @brief Get the memory stats for a memory slab
5724 : *
5725 : * This routine gets the runtime memory usage stats for the slab @a slab.
5726 : *
5727 : * @param slab Address of the memory slab
5728 : * @param stats Pointer to memory into which to copy memory usage statistics
5729 : *
5730 : * @retval 0 Success
5731 : * @retval -EINVAL Any parameter points to NULL
5732 : */
5733 :
5734 1 : int k_mem_slab_runtime_stats_get(struct k_mem_slab *slab, struct sys_memory_stats *stats);
5735 :
5736 : /**
5737 : * @brief Reset the maximum memory usage for a slab
5738 : *
5739 : * This routine resets the maximum memory usage for the slab @a slab to its
5740 : * current usage.
5741 : *
5742 : * @param slab Address of the memory slab
5743 : *
5744 : * @retval 0 Success
5745 : * @retval -EINVAL Memory slab is NULL
5746 : */
5747 1 : int k_mem_slab_runtime_stats_reset_max(struct k_mem_slab *slab);
5748 :
5749 : /** @} */
5750 :
5751 : /**
5752 : * @addtogroup heap_apis
5753 : * @{
5754 : */
5755 :
5756 : /* kernel synchronized heap struct */
5757 :
5758 0 : struct k_heap {
5759 0 : struct sys_heap heap;
5760 0 : _wait_q_t wait_q;
5761 0 : struct k_spinlock lock;
5762 : };
5763 :
5764 : /**
5765 : * @brief Initialize a k_heap
5766 : *
5767 : * This constructs a synchronized k_heap object over a memory region
5768 : * specified by the user. Note that while any alignment and size can
5769 : * be passed as valid parameters, internal alignment restrictions
5770 : * inside the inner sys_heap mean that not all bytes may be usable as
5771 : * allocated memory.
5772 : *
5773 : * @param h Heap struct to initialize
5774 : * @param mem Pointer to memory.
5775 : * @param bytes Size of memory region, in bytes
5776 : */
5777 1 : void k_heap_init(struct k_heap *h, void *mem,
5778 : size_t bytes) __attribute_nonnull(1);
5779 :
5780 : /**
5781 : * @brief Allocate aligned memory from a k_heap
5782 : *
5783 : * Behaves in all ways like k_heap_alloc(), except that the returned
5784 : * memory (if available) will have a starting address in memory which
5785 : * is a multiple of the specified power-of-two alignment value in
5786 : * bytes. The resulting memory can be returned to the heap using
5787 : * k_heap_free().
5788 : *
5789 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
5790 : * @note When CONFIG_MULTITHREADING=n any @a timeout is treated as K_NO_WAIT.
5791 : *
5792 : * @funcprops \isr_ok
5793 : *
5794 : * @param h Heap from which to allocate
5795 : * @param align Alignment in bytes, must be a power of two
5796 : * @param bytes Number of bytes requested
5797 : * @param timeout How long to wait, or K_NO_WAIT
5798 : * @return Pointer to memory the caller can now use
5799 : */
5800 1 : void *k_heap_aligned_alloc(struct k_heap *h, size_t align, size_t bytes,
5801 : k_timeout_t timeout) __attribute_nonnull(1);
5802 :
5803 : /**
5804 : * @brief Allocate memory from a k_heap
5805 : *
5806 : * Allocates and returns a memory buffer from the memory region owned
5807 : * by the heap. If no memory is available immediately, the call will
5808 : * block for the specified timeout (constructed via the standard
5809 : * timeout API, or K_NO_WAIT or K_FOREVER) waiting for memory to be
5810 : * freed. If the allocation cannot be performed by the expiration of
5811 : * the timeout, NULL will be returned.
5812 : * Allocated memory is aligned on a multiple of pointer sizes.
5813 : *
5814 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
5815 : * @note When CONFIG_MULTITHREADING=n any @a timeout is treated as K_NO_WAIT.
5816 : *
5817 : * @funcprops \isr_ok
5818 : *
5819 : * @param h Heap from which to allocate
5820 : * @param bytes Desired size of block to allocate
5821 : * @param timeout How long to wait, or K_NO_WAIT
5822 : * @return A pointer to valid heap memory, or NULL
5823 : */
5824 1 : void *k_heap_alloc(struct k_heap *h, size_t bytes,
5825 : k_timeout_t timeout) __attribute_nonnull(1);
5826 :
5827 : /**
5828 : * @brief Allocate and initialize memory for an array of objects from a k_heap
5829 : *
5830 : * Allocates memory for an array of num objects of size and initializes all
5831 : * bytes in the allocated storage to zero. If no memory is available
5832 : * immediately, the call will block for the specified timeout (constructed
5833 : * via the standard timeout API, or K_NO_WAIT or K_FOREVER) waiting for memory
5834 : * to be freed. If the allocation cannot be performed by the expiration of
5835 : * the timeout, NULL will be returned.
5836 : * Allocated memory is aligned on a multiple of pointer sizes.
5837 : *
5838 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
5839 : * @note When CONFIG_MULTITHREADING=n any @a timeout is treated as K_NO_WAIT.
5840 : *
5841 : * @funcprops \isr_ok
5842 : *
5843 : * @param h Heap from which to allocate
5844 : * @param num Number of objects to allocate
5845 : * @param size Desired size of each object to allocate
5846 : * @param timeout How long to wait, or K_NO_WAIT
5847 : * @return A pointer to valid heap memory, or NULL
5848 : */
5849 1 : void *k_heap_calloc(struct k_heap *h, size_t num, size_t size, k_timeout_t timeout)
5850 : __attribute_nonnull(1);
5851 :
5852 : /**
5853 : * @brief Reallocate memory from a k_heap
5854 : *
5855 : * Reallocates and returns a memory buffer from the memory region owned
5856 : * by the heap. If no memory is available immediately, the call will
5857 : * block for the specified timeout (constructed via the standard
5858 : * timeout API, or K_NO_WAIT or K_FOREVER) waiting for memory to be
5859 : * freed. If the allocation cannot be performed by the expiration of
5860 : * the timeout, NULL will be returned.
5861 : * Reallocated memory is aligned on a multiple of pointer sizes.
5862 : *
5863 : * @note @a timeout must be set to K_NO_WAIT if called from ISR.
5864 : * @note When CONFIG_MULTITHREADING=n any @a timeout is treated as K_NO_WAIT.
5865 : *
5866 : * @funcprops \isr_ok
5867 : *
5868 : * @param h Heap from which to allocate
5869 : * @param ptr Original pointer returned from a previous allocation
5870 : * @param bytes Desired size of block to allocate
5871 : * @param timeout How long to wait, or K_NO_WAIT
5872 : *
5873 : * @return Pointer to memory the caller can now use, or NULL
5874 : */
5875 1 : void *k_heap_realloc(struct k_heap *h, void *ptr, size_t bytes, k_timeout_t timeout)
5876 : __attribute_nonnull(1);
5877 :
5878 : /**
5879 : * @brief Free memory allocated by k_heap_alloc()
5880 : *
5881 : * Returns the specified memory block, which must have been returned
5882 : * from k_heap_alloc(), to the heap for use by other callers. Passing
5883 : * a NULL block is legal, and has no effect.
5884 : *
5885 : * @param h Heap to which to return the memory
5886 : * @param mem A valid memory block, or NULL
5887 : */
5888 1 : void k_heap_free(struct k_heap *h, void *mem) __attribute_nonnull(1);
5889 :
5890 : /* Hand-calculated minimum heap sizes needed to return a successful
5891 : * 1-byte allocation. See details in lib/os/heap.[ch]
5892 : */
5893 : #define Z_HEAP_MIN_SIZE ((sizeof(void *) > 4) ? 56 : 44)
5894 :
5895 : /**
5896 : * @brief Define a static k_heap in the specified linker section
5897 : *
5898 : * This macro defines and initializes a static memory region and
5899 : * k_heap of the requested size in the specified linker section.
5900 : * After kernel start, &name can be used as if k_heap_init() had
5901 : * been called.
5902 : *
5903 : * Note that this macro enforces a minimum size on the memory region
5904 : * to accommodate metadata requirements. Very small heaps will be
5905 : * padded to fit.
5906 : *
5907 : * @param name Symbol name for the struct k_heap object
5908 : * @param bytes Size of memory region, in bytes
5909 : * @param in_section Section attribute specifier such as Z_GENERIC_SECTION.
5910 : */
5911 : #define Z_HEAP_DEFINE_IN_SECT(name, bytes, in_section) \
5912 : char in_section \
5913 : __aligned(8) /* CHUNK_UNIT */ \
5914 : kheap_##name[MAX(bytes, Z_HEAP_MIN_SIZE)]; \
5915 : STRUCT_SECTION_ITERABLE(k_heap, name) = { \
5916 : .heap = { \
5917 : .init_mem = kheap_##name, \
5918 : .init_bytes = MAX(bytes, Z_HEAP_MIN_SIZE), \
5919 : }, \
5920 : }
5921 :
5922 : /**
5923 : * @brief Define a static k_heap
5924 : *
5925 : * This macro defines and initializes a static memory region and
5926 : * k_heap of the requested size. After kernel start, &name can be
5927 : * used as if k_heap_init() had been called.
5928 : *
5929 : * Note that this macro enforces a minimum size on the memory region
5930 : * to accommodate metadata requirements. Very small heaps will be
5931 : * padded to fit.
5932 : *
5933 : * @param name Symbol name for the struct k_heap object
5934 : * @param bytes Size of memory region, in bytes
5935 : */
5936 1 : #define K_HEAP_DEFINE(name, bytes) \
5937 : Z_HEAP_DEFINE_IN_SECT(name, bytes, \
5938 : __noinit_named(kheap_buf_##name))
5939 :
5940 : /**
5941 : * @brief Define a static k_heap in uncached memory
5942 : *
5943 : * This macro defines and initializes a static memory region and
5944 : * k_heap of the requested size in uncached memory. After kernel
5945 : * start, &name can be used as if k_heap_init() had been called.
5946 : *
5947 : * Note that this macro enforces a minimum size on the memory region
5948 : * to accommodate metadata requirements. Very small heaps will be
5949 : * padded to fit.
5950 : *
5951 : * @param name Symbol name for the struct k_heap object
5952 : * @param bytes Size of memory region, in bytes
5953 : */
5954 1 : #define K_HEAP_DEFINE_NOCACHE(name, bytes) \
5955 : Z_HEAP_DEFINE_IN_SECT(name, bytes, __nocache)
5956 :
5957 : /** @brief Get the array of statically defined heaps
5958 : *
5959 : * Returns the pointer to the start of the static heap array.
5960 : * Static heaps are those declared through one of the `K_HEAP_DEFINE`
5961 : * macros.
5962 : *
5963 : * @param heap Pointer to location where heap array address is written
5964 : * @return Number of static heaps
5965 : */
5966 1 : int k_heap_array_get(struct k_heap **heap);
5967 :
5968 : /**
5969 : * @}
5970 : */
5971 :
5972 : /**
5973 : * @defgroup heap_apis Heap APIs
5974 : * @brief Memory allocation from the Heap
5975 : * @ingroup kernel_apis
5976 : * @{
5977 : */
5978 :
5979 : /**
5980 : * @brief Allocate memory from the heap with a specified alignment.
5981 : *
5982 : * This routine provides semantics similar to aligned_alloc(); memory is
5983 : * allocated from the heap with a specified alignment. However, one minor
5984 : * difference is that k_aligned_alloc() accepts any non-zero @p size,
5985 : * whereas aligned_alloc() only accepts a @p size that is an integral
5986 : * multiple of @p align.
5987 : *
5988 : * Above, aligned_alloc() refers to:
5989 : * C11 standard (ISO/IEC 9899:2011): 7.22.3.1
5990 : * The aligned_alloc function (p: 347-348)
5991 : *
5992 : * @param align Alignment of memory requested (in bytes).
5993 : * @param size Amount of memory requested (in bytes).
5994 : *
5995 : * @return Address of the allocated memory if successful; otherwise NULL.
5996 : */
5997 1 : void *k_aligned_alloc(size_t align, size_t size);
5998 :
5999 : /**
6000 : * @brief Allocate memory from the heap.
6001 : *
6002 : * This routine provides traditional malloc() semantics. Memory is
6003 : * allocated from the heap memory pool.
6004 : * Allocated memory is aligned on a multiple of pointer sizes.
6005 : *
6006 : * @param size Amount of memory requested (in bytes).
6007 : *
6008 : * @return Address of the allocated memory if successful; otherwise NULL.
6009 : */
6010 1 : void *k_malloc(size_t size);
6011 :
6012 : /**
6013 : * @brief Free memory allocated from heap.
6014 : *
6015 : * This routine provides traditional free() semantics. The memory being
6016 : * returned must have been allocated from the heap memory pool.
6017 : *
6018 : * If @a ptr is NULL, no operation is performed.
6019 : *
6020 : * @param ptr Pointer to previously allocated memory.
6021 : */
6022 1 : void k_free(void *ptr);
6023 :
6024 : /**
6025 : * @brief Allocate memory from heap, array style
6026 : *
6027 : * This routine provides traditional calloc() semantics. Memory is
6028 : * allocated from the heap memory pool and zeroed.
6029 : *
6030 : * @param nmemb Number of elements in the requested array
6031 : * @param size Size of each array element (in bytes).
6032 : *
6033 : * @return Address of the allocated memory if successful; otherwise NULL.
6034 : */
6035 1 : void *k_calloc(size_t nmemb, size_t size);
6036 :
6037 : /** @brief Expand the size of an existing allocation
6038 : *
6039 : * Returns a pointer to a new memory region with the same contents,
6040 : * but a different allocated size. If the new allocation can be
6041 : * expanded in place, the pointer returned will be identical.
6042 : * Otherwise the data will be copies to a new block and the old one
6043 : * will be freed as per sys_heap_free(). If the specified size is
6044 : * smaller than the original, the block will be truncated in place and
6045 : * the remaining memory returned to the heap. If the allocation of a
6046 : * new block fails, then NULL will be returned and the old block will
6047 : * not be freed or modified.
6048 : *
6049 : * @param ptr Original pointer returned from a previous allocation
6050 : * @param size Amount of memory requested (in bytes).
6051 : *
6052 : * @return Pointer to memory the caller can now use, or NULL.
6053 : */
6054 1 : void *k_realloc(void *ptr, size_t size);
6055 :
6056 : /** @} */
6057 :
6058 : /* polling API - PRIVATE */
6059 :
6060 : #ifdef CONFIG_POLL
6061 : #define _INIT_OBJ_POLL_EVENT(obj) do { (obj)->poll_event = NULL; } while (false)
6062 : #else
6063 : #define _INIT_OBJ_POLL_EVENT(obj) do { } while (false)
6064 : #endif
6065 :
6066 : /* private - types bit positions */
6067 : enum _poll_types_bits {
6068 : /* can be used to ignore an event */
6069 : _POLL_TYPE_IGNORE,
6070 :
6071 : /* to be signaled by k_poll_signal_raise() */
6072 : _POLL_TYPE_SIGNAL,
6073 :
6074 : /* semaphore availability */
6075 : _POLL_TYPE_SEM_AVAILABLE,
6076 :
6077 : /* queue/FIFO/LIFO data availability */
6078 : _POLL_TYPE_DATA_AVAILABLE,
6079 :
6080 : /* msgq data availability */
6081 : _POLL_TYPE_MSGQ_DATA_AVAILABLE,
6082 :
6083 : /* pipe data availability */
6084 : _POLL_TYPE_PIPE_DATA_AVAILABLE,
6085 :
6086 : _POLL_NUM_TYPES
6087 : };
6088 :
6089 : #define Z_POLL_TYPE_BIT(type) (1U << ((type) - 1U))
6090 :
6091 : /* private - states bit positions */
6092 : enum _poll_states_bits {
6093 : /* default state when creating event */
6094 : _POLL_STATE_NOT_READY,
6095 :
6096 : /* signaled by k_poll_signal_raise() */
6097 : _POLL_STATE_SIGNALED,
6098 :
6099 : /* semaphore is available */
6100 : _POLL_STATE_SEM_AVAILABLE,
6101 :
6102 : /* data is available to read on queue/FIFO/LIFO */
6103 : _POLL_STATE_DATA_AVAILABLE,
6104 :
6105 : /* queue/FIFO/LIFO wait was cancelled */
6106 : _POLL_STATE_CANCELLED,
6107 :
6108 : /* data is available to read on a message queue */
6109 : _POLL_STATE_MSGQ_DATA_AVAILABLE,
6110 :
6111 : /* data is available to read from a pipe */
6112 : _POLL_STATE_PIPE_DATA_AVAILABLE,
6113 :
6114 : _POLL_NUM_STATES
6115 : };
6116 :
6117 : #define Z_POLL_STATE_BIT(state) (1U << ((state) - 1U))
6118 :
6119 : #define _POLL_EVENT_NUM_UNUSED_BITS \
6120 : (32 - (0 \
6121 : + 8 /* tag */ \
6122 : + _POLL_NUM_TYPES \
6123 : + _POLL_NUM_STATES \
6124 : + 1 /* modes */ \
6125 : ))
6126 :
6127 : /* end of polling API - PRIVATE */
6128 :
6129 :
6130 : /**
6131 : * @defgroup poll_apis Async polling APIs
6132 : * @brief An API to wait concurrently for any one of multiple conditions to be
6133 : * fulfilled
6134 : * @ingroup kernel_apis
6135 : * @{
6136 : */
6137 :
6138 : /* Public polling API */
6139 :
6140 : /* public - values for k_poll_event.type bitfield */
6141 0 : #define K_POLL_TYPE_IGNORE 0
6142 0 : #define K_POLL_TYPE_SIGNAL Z_POLL_TYPE_BIT(_POLL_TYPE_SIGNAL)
6143 0 : #define K_POLL_TYPE_SEM_AVAILABLE Z_POLL_TYPE_BIT(_POLL_TYPE_SEM_AVAILABLE)
6144 0 : #define K_POLL_TYPE_DATA_AVAILABLE Z_POLL_TYPE_BIT(_POLL_TYPE_DATA_AVAILABLE)
6145 0 : #define K_POLL_TYPE_FIFO_DATA_AVAILABLE K_POLL_TYPE_DATA_AVAILABLE
6146 0 : #define K_POLL_TYPE_MSGQ_DATA_AVAILABLE Z_POLL_TYPE_BIT(_POLL_TYPE_MSGQ_DATA_AVAILABLE)
6147 0 : #define K_POLL_TYPE_PIPE_DATA_AVAILABLE Z_POLL_TYPE_BIT(_POLL_TYPE_PIPE_DATA_AVAILABLE)
6148 :
6149 : /* public - polling modes */
6150 0 : enum k_poll_modes {
6151 : /* polling thread does not take ownership of objects when available */
6152 : K_POLL_MODE_NOTIFY_ONLY = 0,
6153 :
6154 : K_POLL_NUM_MODES
6155 : };
6156 :
6157 : /* public - values for k_poll_event.state bitfield */
6158 0 : #define K_POLL_STATE_NOT_READY 0
6159 0 : #define K_POLL_STATE_SIGNALED Z_POLL_STATE_BIT(_POLL_STATE_SIGNALED)
6160 0 : #define K_POLL_STATE_SEM_AVAILABLE Z_POLL_STATE_BIT(_POLL_STATE_SEM_AVAILABLE)
6161 0 : #define K_POLL_STATE_DATA_AVAILABLE Z_POLL_STATE_BIT(_POLL_STATE_DATA_AVAILABLE)
6162 0 : #define K_POLL_STATE_FIFO_DATA_AVAILABLE K_POLL_STATE_DATA_AVAILABLE
6163 0 : #define K_POLL_STATE_MSGQ_DATA_AVAILABLE Z_POLL_STATE_BIT(_POLL_STATE_MSGQ_DATA_AVAILABLE)
6164 0 : #define K_POLL_STATE_PIPE_DATA_AVAILABLE Z_POLL_STATE_BIT(_POLL_STATE_PIPE_DATA_AVAILABLE)
6165 0 : #define K_POLL_STATE_CANCELLED Z_POLL_STATE_BIT(_POLL_STATE_CANCELLED)
6166 :
6167 : /* public - poll signal object */
6168 0 : struct k_poll_signal {
6169 : /** PRIVATE - DO NOT TOUCH */
6170 1 : sys_dlist_t poll_events;
6171 :
6172 : /**
6173 : * 1 if the event has been signaled, 0 otherwise. Stays set to 1 until
6174 : * user resets it to 0.
6175 : */
6176 1 : unsigned int signaled;
6177 :
6178 : /** custom result value passed to k_poll_signal_raise() if needed */
6179 1 : int result;
6180 : };
6181 :
6182 0 : #define K_POLL_SIGNAL_INITIALIZER(obj) \
6183 : { \
6184 : .poll_events = SYS_DLIST_STATIC_INIT(&obj.poll_events), \
6185 : .signaled = 0, \
6186 : .result = 0, \
6187 : }
6188 : /**
6189 : * @brief Poll Event
6190 : *
6191 : */
6192 1 : struct k_poll_event {
6193 : /** PRIVATE - DO NOT TOUCH */
6194 : sys_dnode_t _node;
6195 :
6196 : /** PRIVATE - DO NOT TOUCH */
6197 1 : struct z_poller *poller;
6198 :
6199 : /** optional user-specified tag, opaque, untouched by the API */
6200 1 : uint32_t tag:8;
6201 :
6202 : /** bitfield of event types (bitwise-ORed K_POLL_TYPE_xxx values) */
6203 1 : uint32_t type:_POLL_NUM_TYPES;
6204 :
6205 : /** bitfield of event states (bitwise-ORed K_POLL_STATE_xxx values) */
6206 1 : uint32_t state:_POLL_NUM_STATES;
6207 :
6208 : /** mode of operation, from enum k_poll_modes */
6209 1 : uint32_t mode:1;
6210 :
6211 : /** unused bits in 32-bit word */
6212 1 : uint32_t unused:_POLL_EVENT_NUM_UNUSED_BITS;
6213 :
6214 : /** per-type data */
6215 : union {
6216 : /* The typed_* fields below are used by K_POLL_EVENT_*INITIALIZER() macros to ensure
6217 : * type safety of polled objects.
6218 : */
6219 0 : void *obj, *typed_K_POLL_TYPE_IGNORE;
6220 0 : struct k_poll_signal *signal, *typed_K_POLL_TYPE_SIGNAL;
6221 0 : struct k_sem *sem, *typed_K_POLL_TYPE_SEM_AVAILABLE;
6222 0 : struct k_fifo *fifo, *typed_K_POLL_TYPE_FIFO_DATA_AVAILABLE;
6223 0 : struct k_queue *queue, *typed_K_POLL_TYPE_DATA_AVAILABLE;
6224 0 : struct k_msgq *msgq, *typed_K_POLL_TYPE_MSGQ_DATA_AVAILABLE;
6225 0 : struct k_pipe *pipe, *typed_K_POLL_TYPE_PIPE_DATA_AVAILABLE;
6226 1 : };
6227 : };
6228 :
6229 0 : #define K_POLL_EVENT_INITIALIZER(_event_type, _event_mode, _event_obj) \
6230 : { \
6231 : .poller = NULL, \
6232 : .type = _event_type, \
6233 : .state = K_POLL_STATE_NOT_READY, \
6234 : .mode = _event_mode, \
6235 : .unused = 0, \
6236 : { \
6237 : .typed_##_event_type = _event_obj, \
6238 : }, \
6239 : }
6240 :
6241 : #define K_POLL_EVENT_STATIC_INITIALIZER(_event_type, _event_mode, _event_obj, \
6242 0 : event_tag) \
6243 : { \
6244 : .tag = event_tag, \
6245 : .type = _event_type, \
6246 : .state = K_POLL_STATE_NOT_READY, \
6247 : .mode = _event_mode, \
6248 : .unused = 0, \
6249 : { \
6250 : .typed_##_event_type = _event_obj, \
6251 : }, \
6252 : }
6253 :
6254 : /**
6255 : * @brief Initialize one struct k_poll_event instance
6256 : *
6257 : * After this routine is called on a poll event, the event it ready to be
6258 : * placed in an event array to be passed to k_poll().
6259 : *
6260 : * @param event The event to initialize.
6261 : * @param type A bitfield of the types of event, from the K_POLL_TYPE_xxx
6262 : * values. Only values that apply to the same object being polled
6263 : * can be used together. Choosing K_POLL_TYPE_IGNORE disables the
6264 : * event.
6265 : * @param mode Future. Use K_POLL_MODE_NOTIFY_ONLY.
6266 : * @param obj Kernel object or poll signal.
6267 : */
6268 :
6269 1 : void k_poll_event_init(struct k_poll_event *event, uint32_t type,
6270 : int mode, void *obj);
6271 :
6272 : /**
6273 : * @brief Wait for one or many of multiple poll events to occur
6274 : *
6275 : * This routine allows a thread to wait concurrently for one or many of
6276 : * multiple poll events to have occurred. Such events can be a kernel object
6277 : * being available, like a semaphore, or a poll signal event.
6278 : *
6279 : * When an event notifies that a kernel object is available, the kernel object
6280 : * is not "given" to the thread calling k_poll(): it merely signals the fact
6281 : * that the object was available when the k_poll() call was in effect. Also,
6282 : * all threads trying to acquire an object the regular way, i.e. by pending on
6283 : * the object, have precedence over the thread polling on the object. This
6284 : * means that the polling thread will never get the poll event on an object
6285 : * until the object becomes available and its pend queue is empty. For this
6286 : * reason, the k_poll() call is more effective when the objects being polled
6287 : * only have one thread, the polling thread, trying to acquire them.
6288 : *
6289 : * When k_poll() returns 0, the caller should loop on all the events that were
6290 : * passed to k_poll() and check the state field for the values that were
6291 : * expected and take the associated actions.
6292 : *
6293 : * Before being reused for another call to k_poll(), the user has to reset the
6294 : * state field to K_POLL_STATE_NOT_READY.
6295 : *
6296 : * When called from user mode, a temporary memory allocation is required from
6297 : * the caller's resource pool.
6298 : *
6299 : * @param events An array of events to be polled for.
6300 : * @param num_events The number of events in the array.
6301 : * @param timeout Waiting period for an event to be ready,
6302 : * or one of the special values K_NO_WAIT and K_FOREVER.
6303 : *
6304 : * @retval 0 One or more events are ready.
6305 : * @retval -EAGAIN Waiting period timed out.
6306 : * @retval -EINTR Polling has been interrupted, e.g. with
6307 : * k_queue_cancel_wait(). All output events are still set and valid,
6308 : * cancelled event(s) will be set to K_POLL_STATE_CANCELLED. In other
6309 : * words, -EINTR status means that at least one of output events is
6310 : * K_POLL_STATE_CANCELLED.
6311 : * @retval -ENOMEM Thread resource pool insufficient memory (user mode only)
6312 : * @retval -EINVAL Bad parameters (user mode only)
6313 : */
6314 :
6315 1 : __syscall int k_poll(struct k_poll_event *events, int num_events,
6316 : k_timeout_t timeout);
6317 :
6318 : /**
6319 : * @brief Initialize a poll signal object.
6320 : *
6321 : * Ready a poll signal object to be signaled via k_poll_signal_raise().
6322 : *
6323 : * @param sig A poll signal.
6324 : */
6325 :
6326 1 : __syscall void k_poll_signal_init(struct k_poll_signal *sig);
6327 :
6328 : /**
6329 : * @brief Reset a poll signal object's state to unsignaled.
6330 : *
6331 : * @param sig A poll signal object
6332 : */
6333 1 : __syscall void k_poll_signal_reset(struct k_poll_signal *sig);
6334 :
6335 : /**
6336 : * @brief Fetch the signaled state and result value of a poll signal
6337 : *
6338 : * @param sig A poll signal object
6339 : * @param signaled An integer buffer which will be written nonzero if the
6340 : * object was signaled
6341 : * @param result An integer destination buffer which will be written with the
6342 : * result value if the object was signaled, or an undefined
6343 : * value if it was not.
6344 : */
6345 1 : __syscall void k_poll_signal_check(struct k_poll_signal *sig,
6346 : unsigned int *signaled, int *result);
6347 :
6348 : /**
6349 : * @brief Signal a poll signal object.
6350 : *
6351 : * This routine makes ready a poll signal, which is basically a poll event of
6352 : * type K_POLL_TYPE_SIGNAL. If a thread was polling on that event, it will be
6353 : * made ready to run. A @a result value can be specified.
6354 : *
6355 : * The poll signal contains a 'signaled' field that, when set by
6356 : * k_poll_signal_raise(), stays set until the user sets it back to 0 with
6357 : * k_poll_signal_reset(). It thus has to be reset by the user before being
6358 : * passed again to k_poll() or k_poll() will consider it being signaled, and
6359 : * will return immediately.
6360 : *
6361 : * @note The result is stored and the 'signaled' field is set even if
6362 : * this function returns an error indicating that an expiring poll was
6363 : * not notified. The next k_poll() will detect the missed raise.
6364 : *
6365 : * @param sig A poll signal.
6366 : * @param result The value to store in the result field of the signal.
6367 : *
6368 : * @retval 0 The signal was delivered successfully.
6369 : * @retval -EAGAIN The polling thread's timeout is in the process of expiring.
6370 : */
6371 :
6372 1 : __syscall int k_poll_signal_raise(struct k_poll_signal *sig, int result);
6373 :
6374 : /** @} */
6375 :
6376 : /**
6377 : * @defgroup cpu_idle_apis CPU Idling APIs
6378 : * @ingroup kernel_apis
6379 : * @{
6380 : */
6381 : /**
6382 : * @brief Make the CPU idle.
6383 : *
6384 : * This function makes the CPU idle until an event wakes it up.
6385 : *
6386 : * In a regular system, the idle thread should be the only thread responsible
6387 : * for making the CPU idle and triggering any type of power management.
6388 : * However, in some more constrained systems, such as a single-threaded system,
6389 : * the only thread would be responsible for this if needed.
6390 : *
6391 : * @note In some architectures, before returning, the function unmasks interrupts
6392 : * unconditionally.
6393 : */
6394 1 : static inline void k_cpu_idle(void)
6395 : {
6396 : arch_cpu_idle();
6397 : }
6398 :
6399 : /**
6400 : * @brief Make the CPU idle in an atomic fashion.
6401 : *
6402 : * Similar to k_cpu_idle(), but must be called with interrupts locked.
6403 : *
6404 : * Enabling interrupts and entering a low-power mode will be atomic,
6405 : * i.e. there will be no period of time where interrupts are enabled before
6406 : * the processor enters a low-power mode.
6407 : *
6408 : * After waking up from the low-power mode, the interrupt lockout state will
6409 : * be restored as if by irq_unlock(key).
6410 : *
6411 : * @param key Interrupt locking key obtained from irq_lock().
6412 : */
6413 1 : static inline void k_cpu_atomic_idle(unsigned int key)
6414 : {
6415 : arch_cpu_atomic_idle(key);
6416 : }
6417 :
6418 : /**
6419 : * @}
6420 : */
6421 :
6422 : /**
6423 : * @cond INTERNAL_HIDDEN
6424 : * @internal
6425 : */
6426 : #ifdef ARCH_EXCEPT
6427 : /* This architecture has direct support for triggering a CPU exception */
6428 : #define z_except_reason(reason) ARCH_EXCEPT(reason)
6429 : #else
6430 :
6431 : #if !defined(CONFIG_ASSERT_NO_FILE_INFO)
6432 : #define __EXCEPT_LOC() __ASSERT_PRINT("@ %s:%d\n", __FILE__, __LINE__)
6433 : #else
6434 : #define __EXCEPT_LOC()
6435 : #endif
6436 :
6437 : /* NOTE: This is the implementation for arches that do not implement
6438 : * ARCH_EXCEPT() to generate a real CPU exception.
6439 : *
6440 : * We won't have a real exception frame to determine the PC value when
6441 : * the oops occurred, so print file and line number before we jump into
6442 : * the fatal error handler.
6443 : */
6444 : #define z_except_reason(reason) do { \
6445 : __EXCEPT_LOC(); \
6446 : z_fatal_error(reason, NULL); \
6447 : } while (false)
6448 :
6449 : #endif /* _ARCH__EXCEPT */
6450 : /**
6451 : * INTERNAL_HIDDEN @endcond
6452 : */
6453 :
6454 : /**
6455 : * @brief Fatally terminate a thread
6456 : *
6457 : * This should be called when a thread has encountered an unrecoverable
6458 : * runtime condition and needs to terminate. What this ultimately
6459 : * means is determined by the _fatal_error_handler() implementation, which
6460 : * will be called with reason code K_ERR_KERNEL_OOPS.
6461 : *
6462 : * If this is called from ISR context, the default system fatal error handler
6463 : * will treat it as an unrecoverable system error, just like k_panic().
6464 : */
6465 1 : #define k_oops() z_except_reason(K_ERR_KERNEL_OOPS)
6466 :
6467 : /**
6468 : * @brief Fatally terminate the system
6469 : *
6470 : * This should be called when the Zephyr kernel has encountered an
6471 : * unrecoverable runtime condition and needs to terminate. What this ultimately
6472 : * means is determined by the _fatal_error_handler() implementation, which
6473 : * will be called with reason code K_ERR_KERNEL_PANIC.
6474 : */
6475 1 : #define k_panic() z_except_reason(K_ERR_KERNEL_PANIC)
6476 :
6477 : /**
6478 : * @cond INTERNAL_HIDDEN
6479 : */
6480 :
6481 : /*
6482 : * private APIs that are utilized by one or more public APIs
6483 : */
6484 :
6485 : /**
6486 : * @internal
6487 : */
6488 : void z_timer_expiration_handler(struct _timeout *timeout);
6489 : /**
6490 : * INTERNAL_HIDDEN @endcond
6491 : */
6492 :
6493 : #ifdef CONFIG_PRINTK
6494 : /**
6495 : * @brief Emit a character buffer to the console device
6496 : *
6497 : * @param c String of characters to print
6498 : * @param n The length of the string
6499 : *
6500 : */
6501 : __syscall void k_str_out(char *c, size_t n);
6502 : #endif
6503 :
6504 : /**
6505 : * @defgroup float_apis Floating Point APIs
6506 : * @ingroup kernel_apis
6507 : * @{
6508 : */
6509 :
6510 : /**
6511 : * @brief Disable preservation of floating point context information.
6512 : *
6513 : * This routine informs the kernel that the specified thread
6514 : * will no longer be using the floating point registers.
6515 : *
6516 : * @warning
6517 : * Some architectures apply restrictions on how the disabling of floating
6518 : * point preservation may be requested, see arch_float_disable.
6519 : *
6520 : * @warning
6521 : * This routine should only be used to disable floating point support for
6522 : * a thread that currently has such support enabled.
6523 : *
6524 : * @param thread ID of thread.
6525 : *
6526 : * @retval 0 On success.
6527 : * @retval -ENOTSUP If the floating point disabling is not implemented.
6528 : * -EINVAL If the floating point disabling could not be performed.
6529 : */
6530 1 : __syscall int k_float_disable(struct k_thread *thread);
6531 :
6532 : /**
6533 : * @brief Enable preservation of floating point context information.
6534 : *
6535 : * This routine informs the kernel that the specified thread
6536 : * will use the floating point registers.
6537 :
6538 : * Invoking this routine initializes the thread's floating point context info
6539 : * to that of an FPU that has been reset. The next time the thread is scheduled
6540 : * by z_swap() it will either inherit an FPU that is guaranteed to be in a
6541 : * "sane" state (if the most recent user of the FPU was cooperatively swapped
6542 : * out) or the thread's own floating point context will be loaded (if the most
6543 : * recent user of the FPU was preempted, or if this thread is the first user
6544 : * of the FPU). Thereafter, the kernel will protect the thread's FP context
6545 : * so that it is not altered during a preemptive context switch.
6546 : *
6547 : * The @a options parameter indicates which floating point register sets will
6548 : * be used by the specified thread.
6549 : *
6550 : * For x86 options:
6551 : *
6552 : * - K_FP_REGS indicates x87 FPU and MMX registers only
6553 : * - K_SSE_REGS indicates SSE registers (and also x87 FPU and MMX registers)
6554 : *
6555 : * @warning
6556 : * Some architectures apply restrictions on how the enabling of floating
6557 : * point preservation may be requested, see arch_float_enable.
6558 : *
6559 : * @warning
6560 : * This routine should only be used to enable floating point support for
6561 : * a thread that currently has such support enabled.
6562 : *
6563 : * @param thread ID of thread.
6564 : * @param options architecture dependent options
6565 : *
6566 : * @retval 0 On success.
6567 : * @retval -ENOTSUP If the floating point enabling is not implemented.
6568 : * -EINVAL If the floating point enabling could not be performed.
6569 : */
6570 1 : __syscall int k_float_enable(struct k_thread *thread, unsigned int options);
6571 :
6572 : /**
6573 : * @}
6574 : */
6575 :
6576 : /**
6577 : * @brief Get the runtime statistics of a thread
6578 : *
6579 : * @param thread ID of thread.
6580 : * @param stats Pointer to struct to copy statistics into.
6581 : * @return -EINVAL if null pointers, otherwise 0
6582 : */
6583 1 : int k_thread_runtime_stats_get(k_tid_t thread,
6584 : k_thread_runtime_stats_t *stats);
6585 :
6586 : /**
6587 : * @brief Get the runtime statistics of all threads
6588 : *
6589 : * @param stats Pointer to struct to copy statistics into.
6590 : * @return -EINVAL if null pointers, otherwise 0
6591 : */
6592 1 : int k_thread_runtime_stats_all_get(k_thread_runtime_stats_t *stats);
6593 :
6594 : /**
6595 : * @brief Get the runtime statistics of all threads on specified cpu
6596 : *
6597 : * @param cpu The cpu number
6598 : * @param stats Pointer to struct to copy statistics into.
6599 : * @return -EINVAL if null pointers, otherwise 0
6600 : */
6601 1 : int k_thread_runtime_stats_cpu_get(int cpu, k_thread_runtime_stats_t *stats);
6602 :
6603 : /**
6604 : * @brief Enable gathering of runtime statistics for specified thread
6605 : *
6606 : * This routine enables the gathering of runtime statistics for the specified
6607 : * thread.
6608 : *
6609 : * @param thread ID of thread
6610 : * @return -EINVAL if invalid thread ID, otherwise 0
6611 : */
6612 1 : int k_thread_runtime_stats_enable(k_tid_t thread);
6613 :
6614 : /**
6615 : * @brief Disable gathering of runtime statistics for specified thread
6616 : *
6617 : * This routine disables the gathering of runtime statistics for the specified
6618 : * thread.
6619 : *
6620 : * @param thread ID of thread
6621 : * @return -EINVAL if invalid thread ID, otherwise 0
6622 : */
6623 1 : int k_thread_runtime_stats_disable(k_tid_t thread);
6624 :
6625 : /**
6626 : * @brief Enable gathering of system runtime statistics
6627 : *
6628 : * This routine enables the gathering of system runtime statistics. Note that
6629 : * it does not affect the gathering of similar statistics for individual
6630 : * threads.
6631 : */
6632 1 : void k_sys_runtime_stats_enable(void);
6633 :
6634 : /**
6635 : * @brief Disable gathering of system runtime statistics
6636 : *
6637 : * This routine disables the gathering of system runtime statistics. Note that
6638 : * it does not affect the gathering of similar statistics for individual
6639 : * threads.
6640 : */
6641 1 : void k_sys_runtime_stats_disable(void);
6642 :
6643 : #ifdef __cplusplus
6644 : }
6645 : #endif
6646 :
6647 : #include <zephyr/tracing/tracing.h>
6648 : #include <zephyr/syscalls/kernel.h>
6649 :
6650 : #endif /* !_ASMLANGUAGE */
6651 :
6652 : #endif /* ZEPHYR_INCLUDE_KERNEL_H_ */
|