blob: ff9d6c93c517c1b4d9b92998f56d869f47ffbcac [file] [log] [blame]
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001/*
2 * Copyright (c) 2016, Wind River Systems, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/**
18 * @file
19 *
20 * @brief Public kernel APIs.
21 */
22
23#ifndef _kernel__h_
24#define _kernel__h_
25
26#include <stddef.h>
27#include <stdint.h>
28#include <toolchain.h>
29#include <sections.h>
30#include <atomic.h>
31#include <errno.h>
32#include <misc/__assert.h>
33#include <misc/dlist.h>
34#include <misc/slist.h>
35
36#ifdef __cplusplus
37extern "C" {
38#endif
39
40#ifdef CONFIG_KERNEL_V2_DEBUG
41#define K_DEBUG(fmt, ...) printk("[%s] " fmt, __func__, ##__VA_ARGS__)
42#else
43#define K_DEBUG(fmt, ...)
44#endif
45
46#define K_PRIO_COOP(x) (-(CONFIG_NUM_COOP_PRIORITIES - (x)))
47#define K_PRIO_PREEMPT(x) (x)
48
49#define K_FOREVER (-1)
50#define K_NO_WAIT 0
51
52#define K_ANY NULL
53#define K_END NULL
54
Benjamin Walsh456c6da2016-09-02 18:55:39 -040055#if CONFIG_NUM_COOP_PRIORITIES > 0
56#define K_HIGHEST_THREAD_PRIO (-CONFIG_NUM_COOP_PRIORITIES)
57#else
58#define K_HIGHEST_THREAD_PRIO 0
59#endif
60
61#if CONFIG_NUM_PREEMPT_PRIORITIES > 0
62#define K_LOWEST_THREAD_PRIO CONFIG_NUM_PREEMPT_PRIORITIES
63#else
64#define K_LOWEST_THREAD_PRIO -1
65#endif
66
67#define K_HIGHEST_APPLICATION_THREAD_PRIO (K_HIGHEST_THREAD_PRIO)
68#define K_LOWEST_APPLICATION_THREAD_PRIO (K_LOWEST_THREAD_PRIO - 1)
69
70typedef sys_dlist_t _wait_q_t;
71
72#ifdef CONFIG_DEBUG_TRACING_KERNEL_OBJECTS
73#define _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(type) struct type *__next
74#define _DEBUG_TRACING_KERNEL_OBJECTS_INIT .__next = NULL,
75#else
76#define _DEBUG_TRACING_KERNEL_OBJECTS_INIT
77#define _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(type)
78#endif
79
80#define k_thread tcs
81struct tcs;
82struct k_mutex;
83struct k_sem;
84struct k_event;
85struct k_msgq;
86struct k_mbox;
87struct k_pipe;
88struct k_fifo;
89struct k_lifo;
90struct k_stack;
91struct k_mem_map;
92struct k_mem_pool;
93struct k_timer;
94
Benjamin Walshb7ef0cb2016-10-05 17:32:01 -040095typedef struct k_thread *k_tid_t;
Benjamin Walsh456c6da2016-09-02 18:55:39 -040096
97/* threads/scheduler/execution contexts */
98
99enum execution_context_types {
100 K_ISR = 0,
101 K_COOP_THREAD,
102 K_PREEMPT_THREAD,
103};
104
105struct k_thread_config {
106 char *stack;
107 unsigned stack_size;
108 unsigned prio;
109};
110
111typedef void (*k_thread_entry_t)(void *p1, void *p2, void *p3);
112extern k_tid_t k_thread_spawn(char *stack, unsigned stack_size,
113 void (*entry)(void *, void *, void*),
114 void *p1, void *p2, void *p3,
115 int32_t prio, uint32_t options, int32_t delay);
116
117extern void k_sleep(int32_t duration);
118extern void k_busy_wait(uint32_t usec_to_wait);
119extern void k_yield(void);
120extern void k_wakeup(k_tid_t thread);
121extern k_tid_t k_current_get(void);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400122extern int k_thread_cancel(k_tid_t thread);
123
124extern void k_thread_abort(k_tid_t thread);
125
126#define K_THREAD_GROUP_EXE 0x1
127#define K_THREAD_GROUP_SYS 0x2
128#define K_THREAD_GROUP_FPU 0x4
129
130/* XXX - doesn't work because CONFIG_ARCH is a string */
131#if 0
132/* arch-specific groups */
133#if CONFIG_ARCH == "x86"
134#define K_THREAD_GROUP_SSE 0x4
135#endif
136#endif
137
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400138#ifdef CONFIG_SYS_CLOCK_EXISTS
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400139#define _THREAD_TIMEOUT_INIT(obj) \
140 (obj).nano_timeout = { \
141 .node = { {0}, {0} }, \
Benjamin Walsh055262c2016-10-05 17:16:01 -0400142 .thread = NULL, \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400143 .wait_q = NULL, \
144 .delta_ticks_from_prev = -1, \
145 },
146#else
147#define _THREAD_TIMEOUT_INIT(obj)
148#endif
149
150#ifdef CONFIG_ERRNO
151#define _THREAD_ERRNO_INIT(obj) (obj).errno_var = 0,
152#else
153#define _THREAD_ERRNO_INIT(obj)
154#endif
155
Peter Mitsisa04c0d72016-09-28 19:26:00 -0400156struct _static_thread_data {
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400157 uint32_t init_groups;
158 int init_prio;
159 void (*init_entry)(void *, void *, void *);
160 void *init_p1;
161 void *init_p2;
162 void *init_p3;
163 void (*init_abort)(void);
164 union {
165 char *init_stack;
166 struct k_thread *thread;
167 };
168 unsigned int init_stack_size;
Peter Mitsisb2fd5be2016-10-11 12:06:25 -0400169 int32_t init_delay;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400170};
171
Peter Mitsisb2fd5be2016-10-11 12:06:25 -0400172/*
173 * Common macro used by both K_THREAD_INITIALIZER()
174 * and _MDEF_THREAD_INITIALIZER().
175 */
176#define _THREAD_INITIALIZER(stack, stack_size, \
177 entry, p1, p2, p3, \
178 abort, prio) \
179 .init_prio = (prio), \
180 .init_entry = (void (*)(void *, void *, void *))entry, \
181 .init_p1 = (void *)p1, \
182 .init_p2 = (void *)p2, \
183 .init_p3 = (void *)p3, \
184 .init_abort = abort, \
185 .init_stack = (stack), \
186 .init_stack_size = (stack_size),
187
188/**
189 * @brief Thread initializer macro
190 *
191 * This macro is to only be used with statically defined threads that were not
192 * defined in the MDEF file. As such the associated threads can not belong to
193 * any thread group.
194 */
195#define K_THREAD_INITIALIZER(stack, stack_size, \
196 entry, p1, p2, p3, \
197 abort, prio, delay) \
198 { \
199 _THREAD_INITIALIZER(stack, stack_size, \
200 entry, p1, p2, p3, \
201 abort, prio) \
202 .init_groups = 0, \
203 .init_delay = (delay), \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400204 }
205
Peter Mitsisb2fd5be2016-10-11 12:06:25 -0400206/**
207 * @brief Thread initializer macro
208 *
209 * This macro is to only be used with statically defined threads that were
210 * defined with legacy APIs (including the MDEF file). As such the associated
211 * threads may belong to one or more thread groups.
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400212 */
Peter Mitsisb2fd5be2016-10-11 12:06:25 -0400213#define _MDEF_THREAD_INITIALIZER(stack, stack_size, \
214 entry, p1, p2, p3, \
215 abort, prio, groups) \
216 { \
217 _THREAD_INITIALIZER(stack, stack_size, \
218 entry, p1, p2, p3, \
219 abort, prio) \
220 .init_groups = (groups), \
221 .init_delay = K_FOREVER, \
222 }
223
224/**
225 * @brief Define thread initializer and initialize it.
226 *
227 * @internal It has been observed that the x86 compiler by default aligns
228 * these _static_thread_data structures to 32-byte boundaries, thereby
229 * wasting space. To work around this, force a 4-byte alignment.
230 */
231#define K_THREAD_DEFINE(name, stack_size, \
232 entry, p1, p2, p3, \
233 abort, prio, delay) \
234 char __noinit __stack _k_thread_obj_##name[stack_size]; \
235 struct _static_thread_data _k_thread_data_##name __aligned(4) \
236 __in_section(_k_task_list, private, task) = \
237 K_THREAD_INITIALIZER(_k_thread_obj_##name, stack_size, \
238 entry, p1, p2, p3, abort, prio, delay)
239
240/**
241 * @brief Define thread initializer for MDEF defined thread and initialize it.
242 *
243 * @ref K_THREAD_DEFINE
244 */
245#define _MDEF_THREAD_DEFINE(name, stack_size, \
246 entry, p1, p2, p3, \
247 abort, prio, groups) \
248 char __noinit __stack _k_thread_obj_##name[stack_size]; \
249 struct _static_thread_data _k_thread_data_##name __aligned(4) \
250 __in_section(_k_task_list, private, task) = \
251 _MDEF_THREAD_INITIALIZER(_k_thread_obj_##name, stack_size, \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400252 entry, p1, p2, p3, abort, prio, groups)
253
Allan Stephens399d0ad2016-10-07 13:41:34 -0500254extern int k_thread_priority_get(k_tid_t thread);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400255extern void k_thread_priority_set(k_tid_t thread, int prio);
256
Benjamin Walsh71d52282016-09-29 10:49:48 -0400257extern void k_thread_suspend(k_tid_t thread);
258extern void k_thread_resume(k_tid_t thread);
259extern void k_thread_abort_handler_set(void (*handler)(void));
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400260
261extern void k_sched_time_slice_set(int32_t slice, int prio);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400262
263extern int k_am_in_isr(void);
264
265extern void k_thread_custom_data_set(void *value);
266extern void *k_thread_custom_data_get(void);
267
268/**
269 * kernel timing
270 */
271
Benjamin Walsha9604bd2016-09-21 11:05:56 -0400272#include <sys_clock.h>
273
274/* private internal time manipulation (users should never play with ticks) */
275
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500276/* added tick needed to account for tick in progress */
277#define _TICK_ALIGN 1
278
Benjamin Walsha9604bd2016-09-21 11:05:56 -0400279static int64_t __ticks_to_ms(int64_t ticks)
280{
Benjamin Walsh57d55dc2016-10-04 16:58:08 -0400281#if CONFIG_SYS_CLOCK_EXISTS
Benjamin Walsha9604bd2016-09-21 11:05:56 -0400282 return (MSEC_PER_SEC * (uint64_t)ticks) / sys_clock_ticks_per_sec;
Benjamin Walsh57d55dc2016-10-04 16:58:08 -0400283#else
284 __ASSERT(ticks == 0, "");
285 return 0;
286#endif
Benjamin Walsha9604bd2016-09-21 11:05:56 -0400287}
288
289
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400290/* timeouts */
291
292struct _timeout;
293typedef void (*_timeout_func_t)(struct _timeout *t);
294
295struct _timeout {
296 sys_dlist_t node;
Benjamin Walsh055262c2016-10-05 17:16:01 -0400297 struct k_thread *thread;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400298 sys_dlist_t *wait_q;
299 int32_t delta_ticks_from_prev;
300 _timeout_func_t func;
301};
302
Allan Stephens45bfa372016-10-12 12:39:42 -0500303
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400304/* timers */
305
306struct k_timer {
307 /*
308 * _timeout structure must be first here if we want to use
309 * dynamic timer allocation. timeout.node is used in the double-linked
310 * list of free timers
311 */
312 struct _timeout timeout;
313
Allan Stephens45bfa372016-10-12 12:39:42 -0500314 /* wait queue for the (single) thread waiting on this timer */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400315 _wait_q_t wait_q;
316
317 /* runs in ISR context */
Allan Stephens45bfa372016-10-12 12:39:42 -0500318 void (*expiry_fn)(struct k_timer *);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400319
320 /* runs in the context of the thread that calls k_timer_stop() */
Allan Stephens45bfa372016-10-12 12:39:42 -0500321 void (*stop_fn)(struct k_timer *);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400322
323 /* timer period */
324 int32_t period;
325
Allan Stephens45bfa372016-10-12 12:39:42 -0500326 /* timer status */
327 uint32_t status;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400328
Allan Stephens45bfa372016-10-12 12:39:42 -0500329 /* used to support legacy timer APIs */
330 void *_legacy_data;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400331
332 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_timer);
333};
334
335#define K_TIMER_INITIALIZER(obj) \
336 { \
337 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
338 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
339 }
340
341#define K_TIMER_DEFINE(name) \
342 struct k_timer name = K_TIMER_INITIALIZER(name)
343
Allan Stephens45bfa372016-10-12 12:39:42 -0500344/**
345 * @brief Initialize a timer.
346 *
347 * This routine must be called before the timer is used.
348 *
349 * @param timer Address of timer.
350 * @param expiry_fn Function to invoke each time timer expires.
351 * @param stop_fn Function to invoke if timer is stopped while running.
352 *
353 * @return N/A
354 */
355extern void k_timer_init(struct k_timer *timer,
356 void (*expiry_fn)(struct k_timer *),
357 void (*stop_fn)(struct k_timer *));
Andy Ross8d8b2ac2016-09-23 10:08:54 -0700358
Allan Stephens45bfa372016-10-12 12:39:42 -0500359/**
360 * @brief Start a timer.
361 *
362 * This routine starts a timer, and resets its status to zero. The timer
363 * begins counting down using the specified duration and period values.
364 *
365 * Attempting to start a timer that is already running is permitted.
366 * The timer's status is reset to zero and the timer begins counting down
367 * using the new duration and period values.
368 *
369 * @param timer Address of timer.
370 * @param duration Initial timer duration (in milliseconds).
371 * @param period Timer period (in milliseconds).
372 *
373 * @return N/A
374 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400375extern void k_timer_start(struct k_timer *timer,
Allan Stephens45bfa372016-10-12 12:39:42 -0500376 int32_t duration, int32_t period);
377
378/**
379 * @brief Stop a timer.
380 *
381 * This routine stops a running timer prematurely. The timer's stop function,
382 * if one exists, is invoked by the caller.
383 *
384 * Attempting to stop a timer that is not running is permitted, but has no
385 * effect on the timer since it is already stopped.
386 *
387 * @param timer Address of timer.
388 *
389 * @return N/A
390 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400391extern void k_timer_stop(struct k_timer *timer);
Allan Stephens45bfa372016-10-12 12:39:42 -0500392
393/**
394 * @brief Read timer status.
395 *
396 * This routine reads the timer's status, which indicates the number of times
397 * it has expired since its status was last read.
398 *
399 * Calling this routine resets the timer's status to zero.
400 *
401 * @param timer Address of timer.
402 *
403 * @return Timer status.
404 */
405extern uint32_t k_timer_status_get(struct k_timer *timer);
406
407/**
408 * @brief Synchronize thread to timer expiration.
409 *
410 * This routine blocks the calling thread until the timer's status is non-zero
411 * (indicating that it has expired at least once since it was last examined)
412 * or the timer is stopped. If the timer status is already non-zero,
413 * or the timer is already stopped, the caller continues without waiting.
414 *
415 * Calling this routine resets the timer's status to zero.
416 *
417 * This routine must not be used by interrupt handlers, since they are not
418 * allowed to block.
419 *
420 * @param timer Address of timer.
421 *
422 * @return Timer status.
423 */
424extern uint32_t k_timer_status_sync(struct k_timer *timer);
425
426/**
427 * @brief Get timer remaining before next timer expiration.
428 *
429 * This routine computes the (approximate) time remaining before a running
430 * timer next expires. If the timer is not running, it returns zero.
431 *
432 * @param timer Address of timer.
433 *
434 * @return Remaining time (in milliseconds).
435 */
436
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400437extern int32_t k_timer_remaining_get(struct k_timer *timer);
Benjamin Walshba5ddc12016-09-21 16:01:22 -0400438
439
Allan Stephens45bfa372016-10-12 12:39:42 -0500440/* kernel clocks */
441
Benjamin Walshba5ddc12016-09-21 16:01:22 -0400442/**
443 * @brief Get the time elapsed since the system booted (uptime)
444 *
445 * @return The current uptime of the system in ms
446 */
447
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400448extern int64_t k_uptime_get(void);
Benjamin Walshba5ddc12016-09-21 16:01:22 -0400449
450/**
451 * @brief Get the lower 32-bit of time elapsed since the system booted (uptime)
452 *
453 * This function is potentially less onerous in both the time it takes to
454 * execute, the interrupt latency it introduces and the amount of 64-bit math
455 * it requires than k_uptime_get(), but it only provides an uptime value of
456 * 32-bits. The user must handle possible rollovers/spillovers.
457 *
458 * At a rate of increment of 1000 per second, it rolls over approximately every
459 * 50 days.
460 *
461 * @return The current uptime of the system in ms
462 */
463
464extern uint32_t k_uptime_get_32(void);
465
466/**
467 * @brief Get the difference between a reference time and the current uptime
468 *
469 * @param reftime A pointer to a reference time. It is updated with the current
470 * uptime upon return.
471 *
472 * @return The delta between the reference time and the current uptime.
473 */
474
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400475extern int64_t k_uptime_delta(int64_t *reftime);
Benjamin Walshba5ddc12016-09-21 16:01:22 -0400476
477/**
478 * @brief Get the difference between a reference time and the current uptime
479 *
480 * The 32-bit version of k_uptime_delta(). It has the same perks and issues as
481 * k_uptime_get_32().
482 *
483 * @param reftime A pointer to a reference time. It is updated with the current
484 * uptime upon return.
485 *
486 * @return The delta between the reference time and the current uptime.
487 */
488
489extern uint32_t k_uptime_delta_32(int64_t *reftime);
490
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400491extern uint32_t k_cycle_get_32(void);
492
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400493/**
494 * data transfers (basic)
495 */
496
497/* fifos */
498
499struct k_fifo {
500 _wait_q_t wait_q;
501 sys_slist_t data_q;
502
503 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_fifo);
504};
505
506extern void k_fifo_init(struct k_fifo *fifo);
507extern void k_fifo_put(struct k_fifo *fifo, void *data);
508extern void k_fifo_put_list(struct k_fifo *fifo, void *head, void *tail);
509extern void k_fifo_put_slist(struct k_fifo *fifo, sys_slist_t *list);
510extern void *k_fifo_get(struct k_fifo *fifo, int32_t timeout);
511
512#define K_FIFO_INITIALIZER(obj) \
513 { \
514 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
Benjamin Walsh9091e5d2016-09-30 10:42:47 -0400515 .data_q = SYS_SLIST_STATIC_INIT(&obj.data_q), \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400516 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
517 }
518
519#define K_FIFO_DEFINE(name) \
Benjamin Walsh0bee91d2016-09-15 17:16:38 -0400520 struct k_fifo name = K_FIFO_INITIALIZER(name)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400521
522/* lifos */
523
524struct k_lifo {
525 _wait_q_t wait_q;
526 void *list;
527
528 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_lifo);
529};
530
531extern void k_lifo_init(struct k_lifo *lifo);
532extern void k_lifo_put(struct k_lifo *lifo, void *data);
533extern void *k_lifo_get(struct k_lifo *lifo, int32_t timeout);
534
535#define K_LIFO_INITIALIZER(obj) \
536 { \
537 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
538 .list = NULL, \
539 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
540 }
541
542#define K_LIFO_DEFINE(name) \
Benjamin Walsh0bee91d2016-09-15 17:16:38 -0400543 struct k_lifo name = K_LIFO_INITIALIZER(name)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400544
545/* stacks */
546
547struct k_stack {
548 _wait_q_t wait_q;
549 uint32_t *base, *next, *top;
550
551 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_stack);
552};
553
Allan Stephens018cd9a2016-10-07 15:13:24 -0500554extern void k_stack_init(struct k_stack *stack,
555 uint32_t *buffer, int num_entries);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400556extern void k_stack_push(struct k_stack *stack, uint32_t data);
557extern int k_stack_pop(struct k_stack *stack, uint32_t *data, int32_t timeout);
558
559#define K_STACK_INITIALIZER(obj, stack_num_entries, stack_buffer) \
560 { \
561 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
562 .base = stack_buffer, \
563 .next = stack_buffer, \
564 .top = stack_buffer + stack_num_entries, \
565 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
566 }
567
568#define K_STACK_DEFINE(name, stack_num_entries) \
569 uint32_t __noinit _k_stack_buf_##name[stack_num_entries]; \
Benjamin Walsh0bee91d2016-09-15 17:16:38 -0400570 struct k_stack name = \
571 K_STACK_INITIALIZER(name, stack_num_entries, \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400572 _k_stack_buf_##name); \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400573
574#define K_STACK_SIZE(stack_num_entries) \
575 (sizeof(struct k_stack) + (stack_num_entries * sizeof(uint32_t)))
576
577/**
578 * workqueues
579 */
580
581struct k_work;
582
583typedef void (*k_work_handler_t)(struct k_work *);
584
585/**
586 * A workqueue is a fiber that executes @ref k_work items that are
587 * queued to it. This is useful for drivers which need to schedule
588 * execution of code which might sleep from ISR context. The actual
589 * fiber identifier is not stored in the structure in order to save
590 * space.
591 */
592struct k_work_q {
593 struct k_fifo fifo;
594};
595
596/**
597 * @brief Work flags.
598 */
599enum {
Iván Briano9c7b5ea2016-10-04 18:11:05 -0300600 K_WORK_STATE_PENDING, /* Work item pending state */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400601};
602
603/**
604 * @brief An item which can be scheduled on a @ref k_work_q.
605 */
606struct k_work {
607 void *_reserved; /* Used by k_fifo implementation. */
608 k_work_handler_t handler;
609 atomic_t flags[1];
610};
611
612/**
613 * @brief Statically initialize work item
614 */
615#define K_WORK_INITIALIZER(work_handler) \
616 { \
617 ._reserved = NULL, \
618 .handler = work_handler, \
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300619 .flags = { 0 } \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400620 }
621
622/**
623 * @brief Dynamically initialize work item
624 */
625static inline void k_work_init(struct k_work *work, k_work_handler_t handler)
626{
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300627 atomic_clear_bit(work->flags, K_WORK_STATE_PENDING);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400628 work->handler = handler;
629}
630
631/**
632 * @brief Submit a work item to a workqueue.
Luiz Augusto von Dentz4ab9d322016-09-26 09:39:27 +0300633 *
634 * This procedure schedules a work item to be processed.
635 * In the case where the work item has already been submitted and is pending
636 * execution, calling this function will result in a no-op. In this case, the
637 * work item must not be modified externally (e.g. by the caller of this
638 * function), since that could cause the work item to be processed in a
639 * corrupted state.
640 *
641 * @param work_q to schedule the work item
642 * @param work work item
643 *
644 * @return N/A
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400645 */
646static inline void k_work_submit_to_queue(struct k_work_q *work_q,
647 struct k_work *work)
648{
Luiz Augusto von Dentz4ab9d322016-09-26 09:39:27 +0300649 if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) {
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400650 k_fifo_put(&work_q->fifo, work);
651 }
652}
653
654/**
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300655 * @brief Check if work item is pending.
656 */
657static inline int k_work_pending(struct k_work *work)
658{
Iván Briano9c7b5ea2016-10-04 18:11:05 -0300659 return atomic_test_bit(work->flags, K_WORK_STATE_PENDING);
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300660}
661
662/**
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400663 * @brief Start a new workqueue. This routine can be called from either
664 * fiber or task context.
665 */
666extern void k_work_q_start(struct k_work_q *work_q,
667 const struct k_thread_config *config);
668
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400669#if defined(CONFIG_SYS_CLOCK_EXISTS)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400670
671 /*
672 * @brief An item which can be scheduled on a @ref k_work_q with a
673 * delay.
674 */
675struct k_delayed_work {
676 struct k_work work;
677 struct _timeout timeout;
678 struct k_work_q *work_q;
679};
680
681/**
682 * @brief Initialize delayed work
683 */
Benjamin Walsh72e5a392016-09-30 11:32:33 -0400684extern void k_delayed_work_init(struct k_delayed_work *work,
685 k_work_handler_t handler);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400686
687/**
688 * @brief Submit a delayed work item to a workqueue.
689 *
690 * This procedure schedules a work item to be processed after a delay.
691 * Once the delay has passed, the work item is submitted to the work queue:
692 * at this point, it is no longer possible to cancel it. Once the work item's
693 * handler is about to be executed, the work is considered complete and can be
694 * resubmitted.
695 *
696 * Care must be taken if the handler blocks or yield as there is no implicit
697 * mutual exclusion mechanism. Such usage is not recommended and if necessary,
698 * it should be explicitly done between the submitter and the handler.
699 *
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500700 * @param work_q Workqueue to schedule the work item
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400701 * @param work Delayed work item
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500702 * @param delay Delay before scheduling the work item (in milliseconds)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400703 *
704 * @return 0 in case of success or negative value in case of error.
705 */
Benjamin Walsh72e5a392016-09-30 11:32:33 -0400706extern int k_delayed_work_submit_to_queue(struct k_work_q *work_q,
707 struct k_delayed_work *work,
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500708 int32_t delay);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400709
710/**
711 * @brief Cancel a delayed work item
712 *
713 * This procedure cancels a scheduled work item. If the work has been completed
714 * or is idle, this will do nothing. The only case where this can fail is when
715 * the work has been submitted to the work queue, but the handler has not run
716 * yet.
717 *
718 * @param work Delayed work item to be canceled
719 *
720 * @return 0 in case of success or negative value in case of error.
721 */
Benjamin Walsh72e5a392016-09-30 11:32:33 -0400722extern int k_delayed_work_cancel(struct k_delayed_work *work);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400723
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400724#endif /* CONFIG_SYS_CLOCK_EXISTS */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400725
726#if defined(CONFIG_SYSTEM_WORKQUEUE)
727
728extern struct k_work_q k_sys_work_q;
729
730/*
731 * @brief Submit a work item to the system workqueue.
732 *
733 * @ref k_work_submit_to_queue
734 *
735 * When using the system workqueue it is not recommended to block or yield
736 * on the handler since its fiber is shared system wide it may cause
737 * unexpected behavior.
738 */
739static inline void k_work_submit(struct k_work *work)
740{
741 k_work_submit_to_queue(&k_sys_work_q, work);
742}
743
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400744#if defined(CONFIG_SYS_CLOCK_EXISTS)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400745/*
746 * @brief Submit a delayed work item to the system workqueue.
747 *
748 * @ref k_delayed_work_submit_to_queue
749 *
750 * When using the system workqueue it is not recommended to block or yield
751 * on the handler since its fiber is shared system wide it may cause
752 * unexpected behavior.
753 */
754static inline int k_delayed_work_submit(struct k_delayed_work *work,
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500755 int32_t delay)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400756{
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500757 return k_delayed_work_submit_to_queue(&k_sys_work_q, work, delay);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400758}
759
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400760#endif /* CONFIG_SYS_CLOCK_EXISTS */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400761#endif /* CONFIG_SYSTEM_WORKQUEUE */
762
763/**
764 * synchronization
765 */
766
767/* mutexes */
768
769struct k_mutex {
770 _wait_q_t wait_q;
Benjamin Walshb7ef0cb2016-10-05 17:32:01 -0400771 struct k_thread *owner;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400772 uint32_t lock_count;
773 int owner_orig_prio;
774#ifdef CONFIG_OBJECT_MONITOR
775 int num_lock_state_changes;
776 int num_conflicts;
777#endif
778
779 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mutex);
780};
781
782#ifdef CONFIG_OBJECT_MONITOR
783#define _MUTEX_INIT_OBJECT_MONITOR \
784 .num_lock_state_changes = 0, .num_conflicts = 0,
785#else
786#define _MUTEX_INIT_OBJECT_MONITOR
787#endif
788
789#define K_MUTEX_INITIALIZER(obj) \
790 { \
791 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
792 .owner = NULL, \
793 .lock_count = 0, \
794 .owner_orig_prio = K_LOWEST_THREAD_PRIO, \
795 _MUTEX_INIT_OBJECT_MONITOR \
796 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
797 }
798
799#define K_MUTEX_DEFINE(name) \
800 struct k_mutex name = K_MUTEX_INITIALIZER(name)
801
802extern void k_mutex_init(struct k_mutex *mutex);
803extern int k_mutex_lock(struct k_mutex *mutex, int32_t timeout);
804extern void k_mutex_unlock(struct k_mutex *mutex);
805
806/* semaphores */
807
808struct k_sem {
809 _wait_q_t wait_q;
810 unsigned int count;
811 unsigned int limit;
812
813 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_sem);
814};
815
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400816/**
817 * @brief Initialize a semaphore object.
818 *
819 * An initial count and a count limit can be specified. The count will never go
820 * over the count limit if the semaphore is given multiple times without being
821 * taken.
822 *
823 * Cannot be called from ISR.
824 *
825 * @param sem Pointer to a semaphore object.
826 * @param initial_count Initial count.
827 * @param limit Highest value the count can take during operation.
828 *
829 * @return N/A
830 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400831extern void k_sem_init(struct k_sem *sem, unsigned int initial_count,
832 unsigned int limit);
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400833
834/**
835 * @brief Take a semaphore, possibly pending if not available.
836 *
837 * The current execution context tries to obtain the semaphore. If the
838 * semaphore is unavailable and a timeout other than K_NO_WAIT is specified,
839 * the context will pend.
840 *
841 * @param sem Pointer to a semaphore object.
842 * @param timeout Number of milliseconds to wait if semaphore is unavailable,
843 * or one of the special values K_NO_WAIT and K_FOREVER.
844 *
845 * @warning If it is called from the context of an ISR, then the only legal
846 * value for @a timeout is K_NO_WAIT.
847 *
848 * @retval 0 When semaphore is obtained successfully.
849 * @retval -EAGAIN When timeout expires.
850 * @retval -EBUSY When unavailable and the timeout is K_NO_WAIT.
851 *
852 * @sa K_NO_WAIT, K_FOREVER
853 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400854extern int k_sem_take(struct k_sem *sem, int32_t timeout);
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400855
856/**
857 * @brief Give a semaphore.
858 *
859 * Increase the semaphore's internal count by 1, up to its limit, if no thread
860 * is waiting on the semaphore; otherwise, wake up the first thread in the
861 * semaphore's waiting queue.
862 *
863 * If the latter case, and if the current context is preemptible, the thread
864 * that is taken off the wait queue will be scheduled in and will preempt the
865 * current thread.
866 *
867 * @param sem Pointer to a semaphore object.
868 *
869 * @return N/A
870 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400871extern void k_sem_give(struct k_sem *sem);
872
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400873/**
874 * @brief Reset a semaphore's count to zero.
875 *
876 * The only effect is that the count is set to zero. There is no other
877 * side-effect to calling this function.
878 *
879 * @param sem Pointer to a semaphore object.
880 *
881 * @return N/A
882 */
Benjamin Walsh70c68b92016-09-21 10:37:34 -0400883static inline void k_sem_reset(struct k_sem *sem)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400884{
885 sem->count = 0;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400886}
887
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400888/**
889 * @brief Get a semaphore's count.
890 *
891 * Note there is no guarantee the count has not changed by the time this
892 * function returns.
893 *
894 * @param sem Pointer to a semaphore object.
895 *
896 * @return The current semaphore count.
897 */
Tomasz Bursztyka276086d2016-09-21 16:03:21 +0200898static inline unsigned int k_sem_count_get(struct k_sem *sem)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400899{
900 return sem->count;
901}
902
Peter Mitsis45403672016-09-09 14:24:06 -0400903#ifdef CONFIG_SEMAPHORE_GROUPS
904/**
905 * @brief Take the first available semaphore
906 *
907 * Given a list of semaphore pointers, this routine will attempt to take one
908 * of them, waiting up to a maximum of @a timeout ms to do so. The taken
909 * semaphore is identified by @a sem (set to NULL on error).
910 *
911 * Be aware that the more semaphores specified in the group, the more stack
912 * space is required by the waiting thread.
913 *
914 * @param sem_array Array of semaphore pointers terminated by a K_END entry
915 * @param sem Identifies the semaphore that was taken
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400916 * @param timeout Number of milliseconds to wait if semaphores are unavailable,
917 * or one of the special values K_NO_WAIT and K_FOREVER.
Peter Mitsis45403672016-09-09 14:24:06 -0400918 *
919 * @retval 0 A semaphore was successfully taken
920 * @retval -EBUSY No semaphore was available (@a timeout = K_NO_WAIT)
921 * @retval -EAGAIN Time out occurred while waiting for semaphore
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400922 *
923 * @sa K_NO_WAIT, K_FOREVER
Peter Mitsis45403672016-09-09 14:24:06 -0400924 */
925
926extern int k_sem_group_take(struct k_sem *sem_array[], struct k_sem **sem,
927 int32_t timeout);
928
929/**
930 * @brief Give all the semaphores in the group
931 *
932 * This routine will give each semaphore in the array of semaphore pointers.
933 *
934 * @param sem_array Array of semaphore pointers terminated by a K_END entry
935 *
936 * @return N/A
937 */
938extern void k_sem_group_give(struct k_sem *sem_array[]);
939
940/**
941 * @brief Reset the count to zero on each semaphore in the array
942 *
943 * This routine resets the count of each semaphore in the group to zero.
944 * Note that it does NOT have any impact on any thread that might have
945 * been previously pending on any of the semaphores.
946 *
947 * @param sem_array Array of semaphore pointers terminated by a K_END entry
948 *
949 * @return N/A
950 */
951extern void k_sem_group_reset(struct k_sem *sem_array[]);
952#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400953
954#define K_SEM_INITIALIZER(obj, initial_count, count_limit) \
955 { \
956 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
957 .count = initial_count, \
958 .limit = count_limit, \
959 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
960 }
961
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400962/**
963 * @def K_SEM_DEFINE
964 *
965 * @brief Statically define and initialize a global semaphore.
966 *
967 * Create a global semaphore named @name. It is initialized as if k_sem_init()
968 * was called on it. If the semaphore is to be accessed outside the module
969 * where it is defined, it can be declared via
970 *
971 * extern struct k_sem @name;
972 *
973 * @param name Name of the semaphore variable.
974 * @param initial_count Initial count.
975 * @param count_limit Highest value the count can take during operation.
976 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400977#define K_SEM_DEFINE(name, initial_count, count_limit) \
978 struct k_sem name = \
979 K_SEM_INITIALIZER(name, initial_count, count_limit)
980
981/* events */
982
983#define K_EVT_DEFAULT NULL
984#define K_EVT_IGNORE ((void *)(-1))
985
986typedef int (*k_event_handler_t)(struct k_event *);
987
988struct k_event {
989 k_event_handler_t handler;
990 atomic_t send_count;
991 struct k_work work_item;
992 struct k_sem sem;
993
994 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_event);
995};
996
997extern void _k_event_deliver(struct k_work *work);
998
999#define K_EVENT_INITIALIZER(obj, event_handler) \
1000 { \
1001 .handler = (k_event_handler_t)event_handler, \
1002 .send_count = ATOMIC_INIT(0), \
1003 .work_item = K_WORK_INITIALIZER(_k_event_deliver), \
1004 .sem = K_SEM_INITIALIZER(obj.sem, 0, 1), \
1005 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1006 }
1007
1008#define K_EVENT_DEFINE(name, event_handler) \
1009 struct k_event name \
1010 __in_section(_k_event_list, event, name) = \
1011 K_EVENT_INITIALIZER(name, event_handler)
1012
1013extern void k_event_init(struct k_event *event, k_event_handler_t handler);
1014extern int k_event_recv(struct k_event *event, int32_t timeout);
1015extern void k_event_send(struct k_event *event);
1016
1017/**
1018 * data transfers (complex)
1019 */
1020
1021/* message queues */
1022
1023struct k_msgq {
1024 _wait_q_t wait_q;
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001025 size_t msg_size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001026 uint32_t max_msgs;
1027 char *buffer_start;
1028 char *buffer_end;
1029 char *read_ptr;
1030 char *write_ptr;
1031 uint32_t used_msgs;
1032
1033 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_msgq);
1034};
1035
Peter Mitsis1da807e2016-10-06 11:36:59 -04001036#define K_MSGQ_INITIALIZER(obj, q_buffer, q_msg_size, q_max_msgs) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001037 { \
1038 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
Peter Mitsis1da807e2016-10-06 11:36:59 -04001039 .max_msgs = q_max_msgs, \
1040 .msg_size = q_msg_size, \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001041 .buffer_start = q_buffer, \
Peter Mitsis1da807e2016-10-06 11:36:59 -04001042 .buffer_end = q_buffer + (q_max_msgs * q_msg_size), \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001043 .read_ptr = q_buffer, \
1044 .write_ptr = q_buffer, \
1045 .used_msgs = 0, \
1046 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1047 }
1048
Peter Mitsis1da807e2016-10-06 11:36:59 -04001049/**
1050 * @brief Define a message queue
1051 *
1052 * This declares and initializes a message queue whose buffer is aligned to
1053 * a @a q_align -byte boundary. The new message queue can be passed to the
1054 * kernel's message queue functions.
1055 *
1056 * Note that for each of the mesages in the message queue to be aligned to
1057 * @a q_align bytes, then @a q_msg_size must be a multiple of @a q_align.
1058 *
1059 * @param q_name Name of the message queue
1060 * @param q_msg_size The size in bytes of each message
1061 * @param q_max_msgs Maximum number of messages the queue can hold
1062 * @param q_align Alignment of the message queue's buffer (power of 2)
1063 */
1064#define K_MSGQ_DEFINE(q_name, q_msg_size, q_max_msgs, q_align) \
1065 static char __noinit __aligned(q_align) \
1066 _k_fifo_buf_##q_name[(q_max_msgs) * (q_msg_size)]; \
1067 struct k_msgq q_name = \
1068 K_MSGQ_INITIALIZER(q_name, _k_fifo_buf_##q_name, \
1069 q_msg_size, q_max_msgs)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001070
Peter Mitsisd7a37502016-10-13 11:37:40 -04001071/**
1072 * @brief Initialize a message queue.
1073 *
1074 * @param q Pointer to the message queue object.
1075 * @param buffer Pointer to memory area that holds queued messages.
1076 * @param msg_size Message size, in bytes.
1077 * @param max_msgs Maximum number of messages that can be queued.
1078 *
1079 * @return N/A
1080 */
Peter Mitsis1da807e2016-10-06 11:36:59 -04001081extern void k_msgq_init(struct k_msgq *q, char *buffer,
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001082 size_t msg_size, uint32_t max_msgs);
Peter Mitsisd7a37502016-10-13 11:37:40 -04001083
1084/**
1085 * @brief Add a message to a message queue.
1086 *
1087 * This routine adds an item to the message queue. When the message queue is
1088 * full, the routine will wait either for space to become available, or until
1089 * the specified time limit is reached.
1090 *
1091 * @param q Pointer to the message queue object.
1092 * @param data Pointer to message data area.
1093 * @param timeout Number of milliseconds to wait until space becomes available
1094 * to add the message into the message queue, or one of the
1095 * special values K_NO_WAIT and K_FOREVER.
1096 *
1097 * @return 0 if successful, -ENOMSG if failed immediately or after queue purge,
1098 * -EAGAIN if timed out
1099 *
1100 * @sa K_NO_WAIT, K_FOREVER
1101 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001102extern int k_msgq_put(struct k_msgq *q, void *data, int32_t timeout);
Peter Mitsisd7a37502016-10-13 11:37:40 -04001103
1104/**
1105 * @brief Obtain a message from a message queue.
1106 *
1107 * This routine fetches the oldest item from the message queue. When the message
1108 * queue is found empty, the routine will wait either until an item is added to
1109 * the message queue or until the specified time limit is reached.
1110 *
1111 * @param q Pointer to the message queue object.
1112 * @param data Pointer to message data area.
1113 * @param timeout Number of milliseconds to wait to obtain message, or one of
1114 * the special values K_NO_WAIT and K_FOREVER.
1115 *
1116 * @return 0 if successful, -ENOMSG if failed immediately, -EAGAIN if timed out
1117 *
1118 * @sa K_NO_WAIT, K_FOREVER
1119 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001120extern int k_msgq_get(struct k_msgq *q, void *data, int32_t timeout);
Peter Mitsisd7a37502016-10-13 11:37:40 -04001121
1122/**
1123 * @brief Purge contents of a message queue.
1124 *
1125 * Discards all messages currently in the message queue, and cancels
1126 * any "add message" operations initiated by waiting threads.
1127 *
1128 * @param q Pointer to the message queue object.
1129 *
1130 * @return N/A
1131 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001132extern void k_msgq_purge(struct k_msgq *q);
1133
Peter Mitsis67be2492016-10-07 11:44:34 -04001134/**
1135 * @brief Get the number of unused messages
1136 *
1137 * @param q Message queue to query
1138 *
1139 * @return Number of unused messages
1140 */
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001141static inline uint32_t k_msgq_num_free_get(struct k_msgq *q)
Peter Mitsis67be2492016-10-07 11:44:34 -04001142{
1143 return q->max_msgs - q->used_msgs;
1144}
1145
Peter Mitsisd7a37502016-10-13 11:37:40 -04001146/**
1147 * @brief Get the number of used messages
1148 *
1149 * @param q Message queue to query
1150 *
1151 * @return Number of used messages
1152 */
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001153static inline uint32_t k_msgq_num_used_get(struct k_msgq *q)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001154{
1155 return q->used_msgs;
1156}
1157
1158struct k_mem_block {
Peter Mitsis0cb65c32016-09-29 14:07:36 -04001159 struct k_mem_pool *pool_id;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001160 void *addr_in_pool;
1161 void *data;
Peter Mitsis5f399242016-10-13 13:26:25 -04001162 size_t req_size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001163};
1164
1165/* mailboxes */
1166
1167struct k_mbox_msg {
1168 /** internal use only - needed for legacy API support */
1169 uint32_t _mailbox;
1170 /** size of message (in bytes) */
Peter Mitsisd93078c2016-10-14 12:59:37 -04001171 size_t size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001172 /** application-defined information value */
1173 uint32_t info;
1174 /** sender's message data buffer */
1175 void *tx_data;
1176 /** internal use only - needed for legacy API support */
1177 void *_rx_data;
1178 /** message data block descriptor */
1179 struct k_mem_block tx_block;
1180 /** source thread id */
1181 k_tid_t rx_source_thread;
1182 /** target thread id */
1183 k_tid_t tx_target_thread;
1184 /** internal use only - thread waiting on send (may be a dummy) */
1185 k_tid_t _syncing_thread;
1186#if (CONFIG_NUM_MBOX_ASYNC_MSGS > 0)
1187 /** internal use only - semaphore used during asynchronous send */
1188 struct k_sem *_async_sem;
1189#endif
1190};
1191
1192struct k_mbox {
1193 _wait_q_t tx_msg_queue;
1194 _wait_q_t rx_msg_queue;
1195
1196 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mbox);
1197};
1198
1199#define K_MBOX_INITIALIZER(obj) \
1200 { \
1201 .tx_msg_queue = SYS_DLIST_STATIC_INIT(&obj.tx_msg_queue), \
1202 .rx_msg_queue = SYS_DLIST_STATIC_INIT(&obj.rx_msg_queue), \
1203 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1204 }
1205
Peter Mitsis12092702016-10-14 12:57:23 -04001206/**
1207 * @brief Define a mailbox
1208 *
1209 * This declares and initializes a mailbox. The new mailbox can be passed to
Peter Mitsisd7a37502016-10-13 11:37:40 -04001210 * the kernel's mailbox functions.
Peter Mitsis12092702016-10-14 12:57:23 -04001211 *
1212 * @param name Name of the mailbox
1213 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001214#define K_MBOX_DEFINE(name) \
1215 struct k_mbox name = \
1216 K_MBOX_INITIALIZER(name) \
1217
Peter Mitsis12092702016-10-14 12:57:23 -04001218/**
1219 * @brief Initialize a mailbox.
1220 *
1221 * @param mbox Pointer to the mailbox object
1222 *
1223 * @return N/A
1224 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001225extern void k_mbox_init(struct k_mbox *mbox);
1226
Peter Mitsis12092702016-10-14 12:57:23 -04001227/**
1228 * @brief Send a mailbox message in a synchronous manner.
1229 *
1230 * Sends a message to a mailbox and waits for a receiver to process it.
1231 * The message data may be in a buffer, in a memory pool block, or non-existent
1232 * (i.e. empty message).
1233 *
1234 * @param mbox Pointer to the mailbox object.
1235 * @param tx_msg Pointer to transmit message descriptor.
1236 * @param timeout Maximum time (milliseconds) to wait for the message to be
1237 * received (although not necessarily completely processed).
1238 * Use K_NO_WAIT to return immediately, or K_FOREVER to wait as long
1239 * as necessary.
1240 *
1241 * @return 0 if successful, -ENOMSG if failed immediately, -EAGAIN if timed out
1242 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001243extern int k_mbox_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001244 int32_t timeout);
Peter Mitsis12092702016-10-14 12:57:23 -04001245
1246#if (CONFIG_NUM_MBOX_ASYNC_MSGS > 0)
1247/**
1248 * @brief Send a mailbox message in an asynchronous manner.
1249 *
1250 * Sends a message to a mailbox without waiting for a receiver to process it.
1251 * The message data may be in a buffer, in a memory pool block, or non-existent
1252 * (i.e. an empty message). Optionally, the specified semaphore will be given
1253 * by the mailbox when the message has been both received and disposed of
1254 * by the receiver.
1255 *
1256 * @param mbox Pointer to the mailbox object.
1257 * @param tx_msg Pointer to transmit message descriptor.
1258 * @param sem Semaphore identifier, or NULL if none specified.
1259 *
1260 * @return N/A
1261 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001262extern void k_mbox_async_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001263 struct k_sem *sem);
Peter Mitsis12092702016-10-14 12:57:23 -04001264#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001265
Peter Mitsis12092702016-10-14 12:57:23 -04001266/**
1267 * @brief Receive a mailbox message.
1268 *
1269 * Receives a message from a mailbox, then optionally retrieves its data
1270 * and disposes of the message.
1271 *
1272 * @param mbox Pointer to the mailbox object.
1273 * @param rx_msg Pointer to receive message descriptor.
1274 * @param buffer Pointer to buffer to receive data.
1275 * (Use NULL to defer data retrieval and message disposal until later.)
1276 * @param timeout Maximum time (milliseconds) to wait for a message.
1277 * Use K_NO_WAIT to return immediately, or K_FOREVER to wait as long as
1278 * necessary.
1279 *
1280 * @return 0 if successful, -ENOMSG if failed immediately, -EAGAIN if timed out
1281 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001282extern int k_mbox_get(struct k_mbox *mbox, struct k_mbox_msg *rx_msg,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001283 void *buffer, int32_t timeout);
Peter Mitsis12092702016-10-14 12:57:23 -04001284
1285/**
1286 * @brief Retrieve mailbox message data into a buffer.
1287 *
1288 * Completes the processing of a received message by retrieving its data
1289 * into a buffer, then disposing of the message.
1290 *
1291 * Alternatively, this routine can be used to dispose of a received message
1292 * without retrieving its data.
1293 *
1294 * @param rx_msg Pointer to receive message descriptor.
1295 * @param buffer Pointer to buffer to receive data. (Use NULL to discard data.)
1296 *
1297 * @return N/A
1298 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001299extern void k_mbox_data_get(struct k_mbox_msg *rx_msg, void *buffer);
Peter Mitsis12092702016-10-14 12:57:23 -04001300
1301/**
1302 * @brief Retrieve mailbox message data into a memory pool block.
1303 *
1304 * Completes the processing of a received message by retrieving its data
1305 * into a memory pool block, then disposing of the message. The memory pool
1306 * block that results from successful retrieval must be returned to the pool
1307 * once the data has been processed, even in cases where zero bytes of data
1308 * are retrieved.
1309 *
1310 * Alternatively, this routine can be used to dispose of a received message
1311 * without retrieving its data. In this case there is no need to return a
1312 * memory pool block to the pool.
1313 *
1314 * This routine allocates a new memory pool block for the data only if the
1315 * data is not already in one. If a new block cannot be allocated, the routine
1316 * returns a failure code and the received message is left unchanged. This
1317 * permits the caller to reattempt data retrieval at a later time or to dispose
1318 * of the received message without retrieving its data.
1319 *
1320 * @param rx_msg Pointer to receive message descriptor.
1321 * @param pool Memory pool identifier. (Use NULL to discard data.)
1322 * @param block Pointer to area to hold memory pool block info.
1323 * @param timeout Maximum time (milliseconds) to wait for a memory pool block.
1324 * Use K_NO_WAIT to return immediately, or K_FOREVER to wait as long as
1325 * necessary.
1326 *
1327 * @return 0 if successful, -ENOMEM if failed immediately, -EAGAIN if timed out
1328 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001329extern int k_mbox_data_block_get(struct k_mbox_msg *rx_msg,
Peter Mitsis0cb65c32016-09-29 14:07:36 -04001330 struct k_mem_pool *pool,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001331 struct k_mem_block *block, int32_t timeout);
1332
1333/* pipes */
1334
1335struct k_pipe {
1336 unsigned char *buffer; /* Pipe buffer: may be NULL */
1337 size_t size; /* Buffer size */
1338 size_t bytes_used; /* # bytes used in buffer */
1339 size_t read_index; /* Where in buffer to read from */
1340 size_t write_index; /* Where in buffer to write */
1341
1342 struct {
1343 _wait_q_t readers; /* Reader wait queue */
1344 _wait_q_t writers; /* Writer wait queue */
1345 } wait_q;
1346
1347 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_pipe);
1348};
1349
Peter Mitsise5d9c582016-10-14 14:44:57 -04001350#define K_PIPE_INITIALIZER(obj, pipe_buffer, pipe_buffer_size) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001351 { \
1352 .buffer = pipe_buffer, \
1353 .size = pipe_buffer_size, \
1354 .bytes_used = 0, \
1355 .read_index = 0, \
1356 .write_index = 0, \
1357 .wait_q.writers = SYS_DLIST_STATIC_INIT(&obj.wait_q.writers), \
1358 .wait_q.readers = SYS_DLIST_STATIC_INIT(&obj.wait_q.readers), \
1359 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1360 }
1361
Peter Mitsise5d9c582016-10-14 14:44:57 -04001362#define K_PIPE_DEFINE(name, pipe_buffer_size, pipe_align) \
1363 static unsigned char __noinit __aligned(pipe_align) \
1364 _k_pipe_buf_##name[pipe_buffer_size]; \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001365 struct k_pipe name = \
Peter Mitsise5d9c582016-10-14 14:44:57 -04001366 K_PIPE_INITIALIZER(name, _k_pipe_buf_##name, pipe_buffer_size)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001367
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001368/**
1369 * @brief Runtime initialization of a pipe
1370 *
1371 * @param pipe Pointer to pipe to initialize
1372 * @param buffer Pointer to buffer to use for pipe's ring buffer
1373 * @param size Size of the pipe's ring buffer
1374 *
1375 * @return N/A
1376 */
1377extern void k_pipe_init(struct k_pipe *pipe, unsigned char *buffer,
1378 size_t size);
1379
1380/**
1381 * @brief Put a message into the specified pipe
1382 *
1383 * This routine synchronously adds a message into the pipe specified by
1384 * @a pipe. It will wait up to @a timeout for the pipe to accept
Peter Mitsise5d9c582016-10-14 14:44:57 -04001385 * @a bytes_to_write bytes of data. If by @a timeout, the pipe could not
1386 * accept @a min_xfer bytes of data, it fails. Fewer than @a min_xfer will
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001387 * only ever be written to the pipe if K_NO_WAIT < @a timeout < K_FOREVER.
1388 *
1389 * @param pipe Pointer to the pipe
Peter Mitsise5d9c582016-10-14 14:44:57 -04001390 * @param data Data to put into the pipe
1391 * @param bytes_to_write Desired number of bytes to put into the pipe
1392 * @param bytes_written Number of bytes the pipe accepted
1393 * @param min_xfer Minimum number of bytes accepted for success
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001394 * @param timeout Maximum number of milliseconds to wait
1395 *
Peter Mitsise5d9c582016-10-14 14:44:57 -04001396 * @retval 0 At least @a min_xfer were sent
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001397 * @retval -EIO Request can not be satisfied (@a timeout is K_NO_WAIT)
Peter Mitsise5d9c582016-10-14 14:44:57 -04001398 * @retval -EAGAIN Fewer than @a min_xfer were sent
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001399 */
Peter Mitsise5d9c582016-10-14 14:44:57 -04001400extern int k_pipe_put(struct k_pipe *pipe, void *data,
1401 size_t bytes_to_write, size_t *bytes_written,
1402 size_t min_xfer, int32_t timeout);
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001403
1404/**
1405 * @brief Get a message from the specified pipe
1406 *
1407 * This routine synchronously retrieves a message from the pipe specified by
Peter Mitsise5d9c582016-10-14 14:44:57 -04001408 * @a pipe. It will wait up to @a timeout to retrieve @a bytes_to_read
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001409 * bytes of data from the pipe. If by @a timeout, the pipe could not retrieve
Peter Mitsise5d9c582016-10-14 14:44:57 -04001410 * @a min_xfer bytes of data, it fails. Fewer than @a min_xfer will
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001411 * only ever be retrieved from the pipe if K_NO_WAIT < @a timeout < K_FOREVER.
1412 *
1413 * @param pipe Pointer to the pipe
Peter Mitsise5d9c582016-10-14 14:44:57 -04001414 * @param data Location to place retrieved data
1415 * @param bytes_to_read Desired number of bytes to retrieve from the pipe
1416 * @param bytes_read Number of bytes retrieved from the pipe
1417 * @param min_xfer Minimum number of bytes retrieved for success
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001418 * @param timeout Maximum number of milliseconds to wait
1419 *
Peter Mitsise5d9c582016-10-14 14:44:57 -04001420 * @retval 0 At least @a min_xfer were transferred
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001421 * @retval -EIO Request can not be satisfied (@a timeout is K_NO_WAIT)
Peter Mitsise5d9c582016-10-14 14:44:57 -04001422 * @retval -EAGAIN Fewer than @a min_xfer were retrieved
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001423 */
Peter Mitsise5d9c582016-10-14 14:44:57 -04001424extern int k_pipe_get(struct k_pipe *pipe, void *data,
1425 size_t bytes_to_read, size_t *bytes_read,
1426 size_t min_xfer, int32_t timeout);
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001427
Peter Mitsis2fef0232016-10-14 14:53:44 -04001428#if (CONFIG_NUM_PIPE_ASYNC_MSGS > 0)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001429/**
1430 * @brief Send a message to the specified pipe
1431 *
1432 * This routine asynchronously sends a message from the pipe specified by
1433 * @a pipe. Once all @a size bytes have been accepted by the pipe, it will
1434 * free the memory block @a block and give the semaphore @a sem (if specified).
1435 * Up to CONFIG_NUM_PIPE_ASYNC_MSGS asynchronous pipe messages can be in-flight
1436 * at any given time.
1437 *
1438 * @param pipe Pointer to the pipe
1439 * @param block Memory block containing data to send
1440 * @param size Number of data bytes in memory block to send
1441 * @param sem Semaphore to signal upon completion (else NULL)
1442 *
1443 * @retval N/A
1444 */
1445extern void k_pipe_block_put(struct k_pipe *pipe, struct k_mem_block *block,
1446 size_t size, struct k_sem *sem);
Peter Mitsis2fef0232016-10-14 14:53:44 -04001447#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001448
1449/**
1450 * memory management
1451 */
1452
1453/* memory maps */
1454
1455struct k_mem_map {
1456 _wait_q_t wait_q;
Peter Mitsisfb02d572016-10-13 16:55:45 -04001457 uint32_t num_blocks;
1458 size_t block_size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001459 char *buffer;
1460 char *free_list;
Peter Mitsisfb02d572016-10-13 16:55:45 -04001461 uint32_t num_used;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001462
1463 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mem_map);
1464};
1465
Peter Mitsis578f9112016-10-07 13:50:31 -04001466#define K_MEM_MAP_INITIALIZER(obj, map_buffer, map_block_size, map_num_blocks) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001467 { \
1468 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
1469 .num_blocks = map_num_blocks, \
1470 .block_size = map_block_size, \
1471 .buffer = map_buffer, \
1472 .free_list = NULL, \
1473 .num_used = 0, \
1474 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1475 }
1476
Peter Mitsis578f9112016-10-07 13:50:31 -04001477/**
1478 * @brief Define a memory map
1479 *
1480 * This declares and initializes a memory map whose buffer is aligned to
1481 * a @a map_align -byte boundary. The new memory map can be passed to the
1482 * kernel's memory map functions.
1483 *
1484 * Note that for each of the blocks in the memory map to be aligned to
1485 * @a map_align bytes, then @a map_block_size must be a multiple of
1486 * @a map_align.
1487 *
1488 * @param name Name of the memory map
1489 * @param map_block_size Size of each block in the buffer (in bytes)
1490 * @param map_num_blocks Number blocks in the buffer
1491 * @param map_align Alignment of the memory map's buffer (power of 2)
1492 */
1493#define K_MEM_MAP_DEFINE(name, map_block_size, map_num_blocks, map_align) \
1494 char __aligned(map_align) \
1495 _k_mem_map_buf_##name[(map_num_blocks) * (map_block_size)]; \
1496 struct k_mem_map name \
1497 __in_section(_k_mem_map_ptr, private, mem_map) = \
1498 K_MEM_MAP_INITIALIZER(name, _k_mem_map_buf_##name, \
1499 map_block_size, map_num_blocks)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001500
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001501/**
1502 * @brief Initialize a memory map.
1503 *
1504 * Initializes the memory map and creates its list of free blocks.
1505 *
1506 * @param map Pointer to the memory map object
1507 * @param buffer Pointer to buffer used for the blocks.
1508 * @param block_size Size of each block, in bytes.
1509 * @param num_blocks Number of blocks.
1510 *
1511 * @return N/A
1512 */
Peter Mitsis578f9112016-10-07 13:50:31 -04001513extern void k_mem_map_init(struct k_mem_map *map, void *buffer,
Peter Mitsisfb02d572016-10-13 16:55:45 -04001514 size_t block_size, uint32_t num_blocks);
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001515
1516/**
1517 * @brief Allocate a memory map block.
1518 *
1519 * Takes a block from the list of unused blocks.
1520 *
1521 * @param map Pointer to memory map object.
1522 * @param mem Pointer to area to receive block address.
1523 * @param timeout Maximum time (milliseconds) to wait for allocation to
1524 * complete. Use K_NO_WAIT to return immediately, or K_FOREVER to wait
1525 * as long as necessary.
1526 *
1527 * @return 0 if successful, -ENOMEM if failed immediately, -EAGAIN if timed out
1528 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001529extern int k_mem_map_alloc(struct k_mem_map *map, void **mem, int32_t timeout);
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001530
1531/**
1532 * @brief Free a memory map block.
1533 *
1534 * Gives block to a waiting thread if there is one, otherwise returns it to
1535 * the list of unused blocks.
1536 *
1537 * @param map Pointer to memory map object.
1538 * @param mem Pointer to area to containing block address.
1539 *
1540 * @return N/A
1541 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001542extern void k_mem_map_free(struct k_mem_map *map, void **mem);
1543
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001544/**
1545 * @brief Get the number of used memory blocks
1546 *
1547 * This routine gets the current number of used memory blocks in the
1548 * specified pool. It should be used for stats purposes only as that
1549 * value may potentially be out-of-date by the time it is used.
1550 *
1551 * @param map Memory map to query
1552 *
1553 * @return Number of used memory blocks
1554 */
Peter Mitsisfb02d572016-10-13 16:55:45 -04001555static inline uint32_t k_mem_map_num_used_get(struct k_mem_map *map)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001556{
1557 return map->num_used;
1558}
1559
Peter Mitsisc001aa82016-10-13 13:53:37 -04001560/**
1561 * @brief Get the number of unused memory blocks
1562 *
1563 * This routine gets the current number of unused memory blocks in the
1564 * specified pool. It should be used for stats purposes only as that value
1565 * may potentially be out-of-date by the time it is used.
1566 *
1567 * @param map Memory map to query
1568 *
1569 * @return Number of unused memory blocks
1570 */
Peter Mitsisfb02d572016-10-13 16:55:45 -04001571static inline uint32_t k_mem_map_num_free_get(struct k_mem_map *map)
Peter Mitsisc001aa82016-10-13 13:53:37 -04001572{
1573 return map->num_blocks - map->num_used;
1574}
1575
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001576/* memory pools */
1577
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001578/*
1579 * Memory pool requires a buffer and two arrays of structures for the
1580 * memory block accounting:
1581 * A set of arrays of k_mem_pool_quad_block structures where each keeps a
1582 * status of four blocks of memory.
1583 */
1584struct k_mem_pool_quad_block {
1585 char *mem_blocks; /* pointer to the first of four memory blocks */
1586 uint32_t mem_status; /* four bits. If bit is set, memory block is
1587 allocated */
1588};
1589/*
1590 * Memory pool mechanism uses one array of k_mem_pool_quad_block for accounting
1591 * blocks of one size. Block sizes go from maximal to minimal. Next memory
1592 * block size is 4 times less than the previous one and thus requires 4 times
1593 * bigger array of k_mem_pool_quad_block structures to keep track of the
1594 * memory blocks.
1595 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001596
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001597/*
1598 * The array of k_mem_pool_block_set keeps the information of each array of
1599 * k_mem_pool_quad_block structures
1600 */
1601struct k_mem_pool_block_set {
Peter Mitsis5f399242016-10-13 13:26:25 -04001602 size_t block_size; /* memory block size */
1603 uint32_t nr_of_entries; /* nr of quad block structures in the array */
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001604 struct k_mem_pool_quad_block *quad_block;
1605 int count;
1606};
1607
1608/* Memory pool descriptor */
1609struct k_mem_pool {
Peter Mitsis5f399242016-10-13 13:26:25 -04001610 size_t max_block_size;
1611 size_t min_block_size;
1612 uint32_t nr_of_maxblocks;
1613 uint32_t nr_of_block_sets;
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001614 struct k_mem_pool_block_set *block_set;
1615 char *bufblock;
1616 _wait_q_t wait_q;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001617 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mem_pool);
1618};
1619
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001620#ifdef CONFIG_ARM
1621#define _SECTION_TYPE_SIGN "%"
1622#else
1623#define _SECTION_TYPE_SIGN "@"
1624#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001625
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001626/*
1627 * Static memory pool initialization
1628 */
1629/*
1630 * Use .altmacro to be able to recalculate values and pass them as string
1631 * arguments when calling assembler macros resursively
1632 */
1633__asm__(".altmacro\n\t");
1634
1635/*
1636 * Recursively calls a macro
1637 * The followig global symbols need to be initialized:
1638 * __memory_pool_max_block_size - maximal size of the memory block
1639 * __memory_pool_min_block_size - minimal size of the memory block
1640 * Notes:
1641 * Global symbols are used due the fact that assembler macro allows only
1642 * one argument be passed with the % conversion
1643 * Some assemblers do not get division operation ("/"). To avoid it >> 2
1644 * is used instead of / 4.
1645 * n_max argument needs to go first in the invoked macro, as some
1646 * assemblers concatenate \name and %(\n_max * 4) arguments
1647 * if \name goes first
1648 */
1649__asm__(".macro __do_recurse macro_name, name, n_max\n\t"
1650 ".ifge __memory_pool_max_block_size >> 2 -"
1651 " __memory_pool_min_block_size\n\t\t"
1652 "__memory_pool_max_block_size = __memory_pool_max_block_size >> 2\n\t\t"
1653 "\\macro_name %(\\n_max * 4) \\name\n\t"
1654 ".endif\n\t"
1655 ".endm\n");
1656
1657/*
1658 * Build quad blocks
1659 * Macro allocates space in memory for the array of k_mem_pool_quad_block
1660 * structures and recursively calls itself for the next array, 4 times
1661 * larger.
1662 * The followig global symbols need to be initialized:
1663 * __memory_pool_max_block_size - maximal size of the memory block
1664 * __memory_pool_min_block_size - minimal size of the memory block
1665 * __memory_pool_quad_block_size - sizeof(struct k_mem_pool_quad_block)
1666 */
1667__asm__(".macro _build_quad_blocks n_max, name\n\t"
1668 "_mem_pool_quad_blocks_\\name\\()_\\n_max:\n\t"
1669 ".skip __memory_pool_quad_block_size * \\n_max >> 2\n\t"
1670 ".if \\n_max % 4\n\t\t"
1671 ".skip __memory_pool_quad_block_size\n\t"
1672 ".endif\n\t"
1673 "__do_recurse _build_quad_blocks \\name \\n_max\n\t"
1674 ".endm\n");
1675
1676/*
1677 * Build block sets and initialize them
1678 * Macro initializes the k_mem_pool_block_set structure and
1679 * recursively calls itself for the next one.
1680 * The followig global symbols need to be initialized:
1681 * __memory_pool_max_block_size - maximal size of the memory block
1682 * __memory_pool_min_block_size - minimal size of the memory block
1683 * __memory_pool_block_set_count, the number of the elements in the
1684 * block set array must be set to 0. Macro calculates it's real
1685 * value.
1686 * Since the macro initializes pointers to an array of k_mem_pool_quad_block
1687 * structures, _build_quad_blocks must be called prior it.
1688 */
1689__asm__(".macro _build_block_set n_max, name\n\t"
1690 ".int __memory_pool_max_block_size\n\t" /* block_size */
1691 ".if \\n_max % 4\n\t\t"
1692 ".int \\n_max >> 2 + 1\n\t" /* nr_of_entries */
1693 ".else\n\t\t"
1694 ".int \\n_max >> 2\n\t"
1695 ".endif\n\t"
1696 ".int _mem_pool_quad_blocks_\\name\\()_\\n_max\n\t" /* quad_block */
1697 ".int 0\n\t" /* count */
1698 "__memory_pool_block_set_count = __memory_pool_block_set_count + 1\n\t"
1699 "__do_recurse _build_block_set \\name \\n_max\n\t"
1700 ".endm\n");
1701
1702/*
1703 * Build a memory pool structure and initialize it
1704 * Macro uses __memory_pool_block_set_count global symbol,
1705 * block set addresses and buffer address, it may be called only after
1706 * _build_block_set
1707 */
1708__asm__(".macro _build_mem_pool name, min_size, max_size, n_max\n\t"
1709 ".pushsection ._k_memory_pool,\"aw\","
1710 _SECTION_TYPE_SIGN "progbits\n\t"
1711 ".globl \\name\n\t"
1712 "\\name:\n\t"
1713 ".int \\max_size\n\t" /* max_block_size */
1714 ".int \\min_size\n\t" /* min_block_size */
1715 ".int \\n_max\n\t" /* nr_of_maxblocks */
1716 ".int __memory_pool_block_set_count\n\t" /* nr_of_block_sets */
1717 ".int _mem_pool_block_sets_\\name\n\t" /* block_set */
1718 ".int _mem_pool_buffer_\\name\n\t" /* bufblock */
1719 ".int 0\n\t" /* wait_q->head */
1720 ".int 0\n\t" /* wait_q->next */
1721 ".popsection\n\t"
1722 ".endm\n");
1723
1724#define _MEMORY_POOL_QUAD_BLOCK_DEFINE(name, min_size, max_size, n_max) \
1725 __asm__(".pushsection ._k_memory_pool.struct,\"aw\"," \
1726 _SECTION_TYPE_SIGN "progbits\n\t"); \
1727 __asm__("__memory_pool_min_block_size = " STRINGIFY(min_size) "\n\t"); \
1728 __asm__("__memory_pool_max_block_size = " STRINGIFY(max_size) "\n\t"); \
1729 __asm__("_build_quad_blocks " STRINGIFY(n_max) " " \
1730 STRINGIFY(name) "\n\t"); \
1731 __asm__(".popsection\n\t")
1732
1733#define _MEMORY_POOL_BLOCK_SETS_DEFINE(name, min_size, max_size, n_max) \
1734 __asm__("__memory_pool_block_set_count = 0\n\t"); \
1735 __asm__("__memory_pool_max_block_size = " STRINGIFY(max_size) "\n\t"); \
1736 __asm__(".pushsection ._k_memory_pool.struct,\"aw\"," \
1737 _SECTION_TYPE_SIGN "progbits\n\t"); \
1738 __asm__("_mem_pool_block_sets_" STRINGIFY(name) ":\n\t"); \
1739 __asm__("_build_block_set " STRINGIFY(n_max) " " \
1740 STRINGIFY(name) "\n\t"); \
1741 __asm__("_mem_pool_block_set_count_" STRINGIFY(name) ":\n\t"); \
1742 __asm__(".int __memory_pool_block_set_count\n\t"); \
1743 __asm__(".popsection\n\t"); \
1744 extern uint32_t _mem_pool_block_set_count_##name; \
1745 extern struct k_mem_pool_block_set _mem_pool_block_sets_##name[]
1746
Peter Mitsis2a2b0752016-10-06 16:27:01 -04001747#define _MEMORY_POOL_BUFFER_DEFINE(name, max_size, n_max, align) \
1748 char __noinit __aligned(align) \
1749 _mem_pool_buffer_##name[(max_size) * (n_max)]
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001750
Peter Mitsis2a2b0752016-10-06 16:27:01 -04001751/**
1752 * @brief Define a memory pool
1753 *
1754 * This declares and initializes a memory pool whose buffer is aligned to
1755 * a @a align -byte boundary. The new memory pool can be passed to the
1756 * kernel's memory pool functions.
1757 *
1758 * Note that for each of the minimum sized blocks to be aligned to @a align
1759 * bytes, then @a min_size must be a multiple of @a align.
1760 *
1761 * @param name Name of the memory pool
1762 * @param min_size Minimum block size in the pool
1763 * @param max_size Maximum block size in the pool
1764 * @param n_max Number of maximum sized blocks in the pool
1765 * @param align Alignment of the memory pool's buffer
1766 */
1767#define K_MEM_POOL_DEFINE(name, min_size, max_size, n_max, align) \
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001768 _MEMORY_POOL_QUAD_BLOCK_DEFINE(name, min_size, max_size, n_max); \
1769 _MEMORY_POOL_BLOCK_SETS_DEFINE(name, min_size, max_size, n_max); \
Peter Mitsis2a2b0752016-10-06 16:27:01 -04001770 _MEMORY_POOL_BUFFER_DEFINE(name, max_size, n_max, align); \
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001771 __asm__("_build_mem_pool " STRINGIFY(name) " " STRINGIFY(min_size) " " \
1772 STRINGIFY(max_size) " " STRINGIFY(n_max) "\n\t"); \
1773 extern struct k_mem_pool name
1774
1775/*
1776 * Dummy function that assigns the value of sizeof(struct k_mem_pool_quad_block)
1777 * to __memory_pool_quad_block_size absolute symbol.
1778 * This function does not get called, but compiler calculates the value and
1779 * assigns it to the absolute symbol, that, in turn is used by assembler macros.
1780 */
1781static void __attribute__ ((used)) __k_mem_pool_quad_block_size_define(void)
1782{
1783 __asm__(".globl __memory_pool_quad_block_size\n\t"
1784 "__memory_pool_quad_block_size = %c0\n\t"
1785 :
1786 : "n"(sizeof(struct k_mem_pool_quad_block)));
1787}
1788
Peter Mitsis937042c2016-10-13 13:18:26 -04001789/**
1790 * @brief Allocate memory from a memory pool
1791 *
1792 * @param pool Pointer to the memory pool object
1793 * @param block Pointer to the allocated memory's block descriptor
1794 * @param size Minimum number of bytes to allocate
1795 * @param timeout Maximum time (milliseconds) to wait for operation to
1796 * complete. Use K_NO_WAIT to return immediately, or K_FOREVER
1797 * to wait as long as necessary.
1798 *
1799 * @return 0 on success, -ENOMEM on failure
1800 */
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001801extern int k_mem_pool_alloc(struct k_mem_pool *pool, struct k_mem_block *block,
Peter Mitsis5f399242016-10-13 13:26:25 -04001802 size_t size, int32_t timeout);
Peter Mitsis937042c2016-10-13 13:18:26 -04001803
1804/**
1805 * @brief Return previously allocated memory to its memory pool
1806 *
1807 * @param block Pointer to allocated memory's block descriptor
1808 *
1809 * @return N/A
1810 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001811extern void k_mem_pool_free(struct k_mem_block *block);
Peter Mitsis937042c2016-10-13 13:18:26 -04001812
1813/**
1814 * @brief Defragment the specified memory pool
1815 *
1816 * @param pool Pointer to the memory pool object
1817 *
1818 * @return N/A
1819 */
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001820extern void k_mem_pool_defrag(struct k_mem_pool *pool);
Peter Mitsis937042c2016-10-13 13:18:26 -04001821
1822/**
1823 * @brief Allocate memory from heap pool
1824 *
1825 * This routine provides traditional malloc semantics; internally it uses
1826 * the memory pool APIs on a dedicated HEAP pool
1827 *
1828 * @param size Size of memory requested by the caller (in bytes)
1829 *
1830 * @return Address of the allocated memory on success; otherwise NULL
1831 */
Peter Mitsis5f399242016-10-13 13:26:25 -04001832extern void *k_malloc(size_t size);
Peter Mitsis937042c2016-10-13 13:18:26 -04001833
1834/**
1835 * @brief Free memory allocated through k_malloc()
1836 *
1837 * @param ptr Pointer to previously allocated memory
1838 *
1839 * @return N/A
1840 */
1841extern void k_free(void *ptr);
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001842
1843/*
1844 * legacy.h must be before arch/cpu.h to allow the ioapic/loapic drivers to
1845 * hook into the device subsystem, which itself uses nanokernel semaphores,
1846 * and thus currently requires the definition of nano_sem.
1847 */
1848#include <legacy.h>
1849#include <arch/cpu.h>
1850
1851/*
1852 * private APIs that are utilized by one or more public APIs
1853 */
1854
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001855extern int _is_thread_essential(void);
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001856extern void _init_static_threads(void);
1857
1858#ifdef __cplusplus
1859}
1860#endif
1861
1862#endif /* _kernel__h_ */