blob: d083d6db4b20ed9253df76bafdcb328051c11bba [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
Peter Mitsis602e6a82016-10-17 11:48:43 -0400559#define K_STACK_INITIALIZER(obj, stack_buffer, stack_num_entries) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400560 { \
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
Peter Mitsis602e6a82016-10-17 11:48:43 -0400568#define K_STACK_DEFINE(name, stack_num_entries) \
569 uint32_t __noinit \
570 _k_stack_buf_##name[stack_num_entries]; \
571 struct k_stack name = \
572 K_STACK_INITIALIZER(name, _k_stack_buf_##name, \
573 stack_num_entries)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400574
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400575/**
576 * workqueues
577 */
578
579struct k_work;
580
581typedef void (*k_work_handler_t)(struct k_work *);
582
583/**
584 * A workqueue is a fiber that executes @ref k_work items that are
585 * queued to it. This is useful for drivers which need to schedule
586 * execution of code which might sleep from ISR context. The actual
587 * fiber identifier is not stored in the structure in order to save
588 * space.
589 */
590struct k_work_q {
591 struct k_fifo fifo;
592};
593
594/**
595 * @brief Work flags.
596 */
597enum {
Iván Briano9c7b5ea2016-10-04 18:11:05 -0300598 K_WORK_STATE_PENDING, /* Work item pending state */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400599};
600
601/**
602 * @brief An item which can be scheduled on a @ref k_work_q.
603 */
604struct k_work {
605 void *_reserved; /* Used by k_fifo implementation. */
606 k_work_handler_t handler;
607 atomic_t flags[1];
608};
609
610/**
611 * @brief Statically initialize work item
612 */
613#define K_WORK_INITIALIZER(work_handler) \
614 { \
615 ._reserved = NULL, \
616 .handler = work_handler, \
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300617 .flags = { 0 } \
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400618 }
619
620/**
621 * @brief Dynamically initialize work item
622 */
623static inline void k_work_init(struct k_work *work, k_work_handler_t handler)
624{
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300625 atomic_clear_bit(work->flags, K_WORK_STATE_PENDING);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400626 work->handler = handler;
627}
628
629/**
630 * @brief Submit a work item to a workqueue.
Luiz Augusto von Dentz4ab9d322016-09-26 09:39:27 +0300631 *
632 * This procedure schedules a work item to be processed.
633 * In the case where the work item has already been submitted and is pending
634 * execution, calling this function will result in a no-op. In this case, the
635 * work item must not be modified externally (e.g. by the caller of this
636 * function), since that could cause the work item to be processed in a
637 * corrupted state.
638 *
639 * @param work_q to schedule the work item
640 * @param work work item
641 *
642 * @return N/A
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400643 */
644static inline void k_work_submit_to_queue(struct k_work_q *work_q,
645 struct k_work *work)
646{
Luiz Augusto von Dentz4ab9d322016-09-26 09:39:27 +0300647 if (!atomic_test_and_set_bit(work->flags, K_WORK_STATE_PENDING)) {
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400648 k_fifo_put(&work_q->fifo, work);
649 }
650}
651
652/**
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300653 * @brief Check if work item is pending.
654 */
655static inline int k_work_pending(struct k_work *work)
656{
Iván Briano9c7b5ea2016-10-04 18:11:05 -0300657 return atomic_test_bit(work->flags, K_WORK_STATE_PENDING);
Luiz Augusto von Dentzee1e99b2016-09-26 09:36:49 +0300658}
659
660/**
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400661 * @brief Start a new workqueue. This routine can be called from either
662 * fiber or task context.
663 */
664extern void k_work_q_start(struct k_work_q *work_q,
665 const struct k_thread_config *config);
666
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400667#if defined(CONFIG_SYS_CLOCK_EXISTS)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400668
669 /*
670 * @brief An item which can be scheduled on a @ref k_work_q with a
671 * delay.
672 */
673struct k_delayed_work {
674 struct k_work work;
675 struct _timeout timeout;
676 struct k_work_q *work_q;
677};
678
679/**
680 * @brief Initialize delayed work
681 */
Benjamin Walsh72e5a392016-09-30 11:32:33 -0400682extern void k_delayed_work_init(struct k_delayed_work *work,
683 k_work_handler_t handler);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400684
685/**
686 * @brief Submit a delayed work item to a workqueue.
687 *
688 * This procedure schedules a work item to be processed after a delay.
689 * Once the delay has passed, the work item is submitted to the work queue:
690 * at this point, it is no longer possible to cancel it. Once the work item's
691 * handler is about to be executed, the work is considered complete and can be
692 * resubmitted.
693 *
694 * Care must be taken if the handler blocks or yield as there is no implicit
695 * mutual exclusion mechanism. Such usage is not recommended and if necessary,
696 * it should be explicitly done between the submitter and the handler.
697 *
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500698 * @param work_q Workqueue to schedule the work item
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400699 * @param work Delayed work item
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500700 * @param delay Delay before scheduling the work item (in milliseconds)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400701 *
702 * @return 0 in case of success or negative value in case of error.
703 */
Benjamin Walsh72e5a392016-09-30 11:32:33 -0400704extern int k_delayed_work_submit_to_queue(struct k_work_q *work_q,
705 struct k_delayed_work *work,
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500706 int32_t delay);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400707
708/**
709 * @brief Cancel a delayed work item
710 *
711 * This procedure cancels a scheduled work item. If the work has been completed
712 * or is idle, this will do nothing. The only case where this can fail is when
713 * the work has been submitted to the work queue, but the handler has not run
714 * yet.
715 *
716 * @param work Delayed work item to be canceled
717 *
718 * @return 0 in case of success or negative value in case of error.
719 */
Benjamin Walsh72e5a392016-09-30 11:32:33 -0400720extern int k_delayed_work_cancel(struct k_delayed_work *work);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400721
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400722#endif /* CONFIG_SYS_CLOCK_EXISTS */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400723
724#if defined(CONFIG_SYSTEM_WORKQUEUE)
725
726extern struct k_work_q k_sys_work_q;
727
728/*
729 * @brief Submit a work item to the system workqueue.
730 *
731 * @ref k_work_submit_to_queue
732 *
733 * When using the system workqueue it is not recommended to block or yield
734 * on the handler since its fiber is shared system wide it may cause
735 * unexpected behavior.
736 */
737static inline void k_work_submit(struct k_work *work)
738{
739 k_work_submit_to_queue(&k_sys_work_q, work);
740}
741
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400742#if defined(CONFIG_SYS_CLOCK_EXISTS)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400743/*
744 * @brief Submit a delayed work item to the system workqueue.
745 *
746 * @ref k_delayed_work_submit_to_queue
747 *
748 * When using the system workqueue it is not recommended to block or yield
749 * on the handler since its fiber is shared system wide it may cause
750 * unexpected behavior.
751 */
752static inline int k_delayed_work_submit(struct k_delayed_work *work,
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500753 int32_t delay)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400754{
Allan Stephens6c98c4d2016-10-17 14:34:53 -0500755 return k_delayed_work_submit_to_queue(&k_sys_work_q, work, delay);
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400756}
757
Benjamin Walsh1a5450b2016-10-06 15:04:23 -0400758#endif /* CONFIG_SYS_CLOCK_EXISTS */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400759#endif /* CONFIG_SYSTEM_WORKQUEUE */
760
761/**
762 * synchronization
763 */
764
765/* mutexes */
766
767struct k_mutex {
768 _wait_q_t wait_q;
Benjamin Walshb7ef0cb2016-10-05 17:32:01 -0400769 struct k_thread *owner;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400770 uint32_t lock_count;
771 int owner_orig_prio;
772#ifdef CONFIG_OBJECT_MONITOR
773 int num_lock_state_changes;
774 int num_conflicts;
775#endif
776
777 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mutex);
778};
779
780#ifdef CONFIG_OBJECT_MONITOR
781#define _MUTEX_INIT_OBJECT_MONITOR \
782 .num_lock_state_changes = 0, .num_conflicts = 0,
783#else
784#define _MUTEX_INIT_OBJECT_MONITOR
785#endif
786
787#define K_MUTEX_INITIALIZER(obj) \
788 { \
789 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
790 .owner = NULL, \
791 .lock_count = 0, \
792 .owner_orig_prio = K_LOWEST_THREAD_PRIO, \
793 _MUTEX_INIT_OBJECT_MONITOR \
794 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
795 }
796
797#define K_MUTEX_DEFINE(name) \
798 struct k_mutex name = K_MUTEX_INITIALIZER(name)
799
800extern void k_mutex_init(struct k_mutex *mutex);
801extern int k_mutex_lock(struct k_mutex *mutex, int32_t timeout);
802extern void k_mutex_unlock(struct k_mutex *mutex);
803
804/* semaphores */
805
806struct k_sem {
807 _wait_q_t wait_q;
808 unsigned int count;
809 unsigned int limit;
810
811 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_sem);
812};
813
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400814/**
815 * @brief Initialize a semaphore object.
816 *
817 * An initial count and a count limit can be specified. The count will never go
818 * over the count limit if the semaphore is given multiple times without being
819 * taken.
820 *
821 * Cannot be called from ISR.
822 *
823 * @param sem Pointer to a semaphore object.
824 * @param initial_count Initial count.
825 * @param limit Highest value the count can take during operation.
826 *
827 * @return N/A
828 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400829extern void k_sem_init(struct k_sem *sem, unsigned int initial_count,
830 unsigned int limit);
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400831
832/**
833 * @brief Take a semaphore, possibly pending if not available.
834 *
835 * The current execution context tries to obtain the semaphore. If the
836 * semaphore is unavailable and a timeout other than K_NO_WAIT is specified,
837 * the context will pend.
838 *
839 * @param sem Pointer to a semaphore object.
840 * @param timeout Number of milliseconds to wait if semaphore is unavailable,
841 * or one of the special values K_NO_WAIT and K_FOREVER.
842 *
843 * @warning If it is called from the context of an ISR, then the only legal
844 * value for @a timeout is K_NO_WAIT.
845 *
846 * @retval 0 When semaphore is obtained successfully.
847 * @retval -EAGAIN When timeout expires.
848 * @retval -EBUSY When unavailable and the timeout is K_NO_WAIT.
849 *
850 * @sa K_NO_WAIT, K_FOREVER
851 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400852extern int k_sem_take(struct k_sem *sem, int32_t timeout);
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400853
854/**
855 * @brief Give a semaphore.
856 *
857 * Increase the semaphore's internal count by 1, up to its limit, if no thread
858 * is waiting on the semaphore; otherwise, wake up the first thread in the
859 * semaphore's waiting queue.
860 *
861 * If the latter case, and if the current context is preemptible, the thread
862 * that is taken off the wait queue will be scheduled in and will preempt the
863 * current thread.
864 *
865 * @param sem Pointer to a semaphore object.
866 *
867 * @return N/A
868 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400869extern void k_sem_give(struct k_sem *sem);
870
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400871/**
872 * @brief Reset a semaphore's count to zero.
873 *
874 * The only effect is that the count is set to zero. There is no other
875 * side-effect to calling this function.
876 *
877 * @param sem Pointer to a semaphore object.
878 *
879 * @return N/A
880 */
Benjamin Walsh70c68b92016-09-21 10:37:34 -0400881static inline void k_sem_reset(struct k_sem *sem)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400882{
883 sem->count = 0;
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400884}
885
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400886/**
887 * @brief Get a semaphore's count.
888 *
889 * Note there is no guarantee the count has not changed by the time this
890 * function returns.
891 *
892 * @param sem Pointer to a semaphore object.
893 *
894 * @return The current semaphore count.
895 */
Tomasz Bursztyka276086d2016-09-21 16:03:21 +0200896static inline unsigned int k_sem_count_get(struct k_sem *sem)
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400897{
898 return sem->count;
899}
900
Peter Mitsis45403672016-09-09 14:24:06 -0400901#ifdef CONFIG_SEMAPHORE_GROUPS
902/**
903 * @brief Take the first available semaphore
904 *
905 * Given a list of semaphore pointers, this routine will attempt to take one
906 * of them, waiting up to a maximum of @a timeout ms to do so. The taken
907 * semaphore is identified by @a sem (set to NULL on error).
908 *
909 * Be aware that the more semaphores specified in the group, the more stack
910 * space is required by the waiting thread.
911 *
912 * @param sem_array Array of semaphore pointers terminated by a K_END entry
913 * @param sem Identifies the semaphore that was taken
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400914 * @param timeout Number of milliseconds to wait if semaphores are unavailable,
915 * or one of the special values K_NO_WAIT and K_FOREVER.
Peter Mitsis45403672016-09-09 14:24:06 -0400916 *
917 * @retval 0 A semaphore was successfully taken
918 * @retval -EBUSY No semaphore was available (@a timeout = K_NO_WAIT)
919 * @retval -EAGAIN Time out occurred while waiting for semaphore
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400920 *
921 * @sa K_NO_WAIT, K_FOREVER
Peter Mitsis45403672016-09-09 14:24:06 -0400922 */
923
924extern int k_sem_group_take(struct k_sem *sem_array[], struct k_sem **sem,
925 int32_t timeout);
926
927/**
928 * @brief Give all the semaphores in the group
929 *
930 * This routine will give each semaphore in the array of semaphore pointers.
931 *
932 * @param sem_array Array of semaphore pointers terminated by a K_END entry
933 *
934 * @return N/A
935 */
936extern void k_sem_group_give(struct k_sem *sem_array[]);
937
938/**
939 * @brief Reset the count to zero on each semaphore in the array
940 *
941 * This routine resets the count of each semaphore in the group to zero.
942 * Note that it does NOT have any impact on any thread that might have
943 * been previously pending on any of the semaphores.
944 *
945 * @param sem_array Array of semaphore pointers terminated by a K_END entry
946 *
947 * @return N/A
948 */
949extern void k_sem_group_reset(struct k_sem *sem_array[]);
950#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400951
952#define K_SEM_INITIALIZER(obj, initial_count, count_limit) \
953 { \
954 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
955 .count = initial_count, \
956 .limit = count_limit, \
957 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
958 }
959
Benjamin Walshb9c1a062016-10-15 17:12:35 -0400960/**
961 * @def K_SEM_DEFINE
962 *
963 * @brief Statically define and initialize a global semaphore.
964 *
965 * Create a global semaphore named @name. It is initialized as if k_sem_init()
966 * was called on it. If the semaphore is to be accessed outside the module
967 * where it is defined, it can be declared via
968 *
969 * extern struct k_sem @name;
970 *
971 * @param name Name of the semaphore variable.
972 * @param initial_count Initial count.
973 * @param count_limit Highest value the count can take during operation.
974 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -0400975#define K_SEM_DEFINE(name, initial_count, count_limit) \
976 struct k_sem name = \
977 K_SEM_INITIALIZER(name, initial_count, count_limit)
978
979/* events */
980
981#define K_EVT_DEFAULT NULL
982#define K_EVT_IGNORE ((void *)(-1))
983
984typedef int (*k_event_handler_t)(struct k_event *);
985
986struct k_event {
987 k_event_handler_t handler;
988 atomic_t send_count;
989 struct k_work work_item;
990 struct k_sem sem;
991
992 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_event);
993};
994
995extern void _k_event_deliver(struct k_work *work);
996
997#define K_EVENT_INITIALIZER(obj, event_handler) \
998 { \
999 .handler = (k_event_handler_t)event_handler, \
1000 .send_count = ATOMIC_INIT(0), \
1001 .work_item = K_WORK_INITIALIZER(_k_event_deliver), \
1002 .sem = K_SEM_INITIALIZER(obj.sem, 0, 1), \
1003 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1004 }
1005
1006#define K_EVENT_DEFINE(name, event_handler) \
1007 struct k_event name \
1008 __in_section(_k_event_list, event, name) = \
1009 K_EVENT_INITIALIZER(name, event_handler)
1010
1011extern void k_event_init(struct k_event *event, k_event_handler_t handler);
1012extern int k_event_recv(struct k_event *event, int32_t timeout);
1013extern void k_event_send(struct k_event *event);
1014
1015/**
1016 * data transfers (complex)
1017 */
1018
1019/* message queues */
1020
1021struct k_msgq {
1022 _wait_q_t wait_q;
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001023 size_t msg_size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001024 uint32_t max_msgs;
1025 char *buffer_start;
1026 char *buffer_end;
1027 char *read_ptr;
1028 char *write_ptr;
1029 uint32_t used_msgs;
1030
1031 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_msgq);
1032};
1033
Peter Mitsis1da807e2016-10-06 11:36:59 -04001034#define K_MSGQ_INITIALIZER(obj, q_buffer, q_msg_size, q_max_msgs) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001035 { \
1036 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
Peter Mitsis1da807e2016-10-06 11:36:59 -04001037 .max_msgs = q_max_msgs, \
1038 .msg_size = q_msg_size, \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001039 .buffer_start = q_buffer, \
Peter Mitsis1da807e2016-10-06 11:36:59 -04001040 .buffer_end = q_buffer + (q_max_msgs * q_msg_size), \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001041 .read_ptr = q_buffer, \
1042 .write_ptr = q_buffer, \
1043 .used_msgs = 0, \
1044 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1045 }
1046
Peter Mitsis1da807e2016-10-06 11:36:59 -04001047/**
1048 * @brief Define a message queue
1049 *
1050 * This declares and initializes a message queue whose buffer is aligned to
1051 * a @a q_align -byte boundary. The new message queue can be passed to the
1052 * kernel's message queue functions.
1053 *
1054 * Note that for each of the mesages in the message queue to be aligned to
1055 * @a q_align bytes, then @a q_msg_size must be a multiple of @a q_align.
1056 *
1057 * @param q_name Name of the message queue
1058 * @param q_msg_size The size in bytes of each message
1059 * @param q_max_msgs Maximum number of messages the queue can hold
1060 * @param q_align Alignment of the message queue's buffer (power of 2)
1061 */
1062#define K_MSGQ_DEFINE(q_name, q_msg_size, q_max_msgs, q_align) \
1063 static char __noinit __aligned(q_align) \
1064 _k_fifo_buf_##q_name[(q_max_msgs) * (q_msg_size)]; \
1065 struct k_msgq q_name = \
1066 K_MSGQ_INITIALIZER(q_name, _k_fifo_buf_##q_name, \
1067 q_msg_size, q_max_msgs)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001068
Peter Mitsisd7a37502016-10-13 11:37:40 -04001069/**
1070 * @brief Initialize a message queue.
1071 *
1072 * @param q Pointer to the message queue object.
1073 * @param buffer Pointer to memory area that holds queued messages.
1074 * @param msg_size Message size, in bytes.
1075 * @param max_msgs Maximum number of messages that can be queued.
1076 *
1077 * @return N/A
1078 */
Peter Mitsis1da807e2016-10-06 11:36:59 -04001079extern void k_msgq_init(struct k_msgq *q, char *buffer,
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001080 size_t msg_size, uint32_t max_msgs);
Peter Mitsisd7a37502016-10-13 11:37:40 -04001081
1082/**
1083 * @brief Add a message to a message queue.
1084 *
1085 * This routine adds an item to the message queue. When the message queue is
1086 * full, the routine will wait either for space to become available, or until
1087 * the specified time limit is reached.
1088 *
1089 * @param q Pointer to the message queue object.
1090 * @param data Pointer to message data area.
1091 * @param timeout Number of milliseconds to wait until space becomes available
1092 * to add the message into the message queue, or one of the
1093 * special values K_NO_WAIT and K_FOREVER.
1094 *
1095 * @return 0 if successful, -ENOMSG if failed immediately or after queue purge,
1096 * -EAGAIN if timed out
1097 *
1098 * @sa K_NO_WAIT, K_FOREVER
1099 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001100extern int k_msgq_put(struct k_msgq *q, void *data, int32_t timeout);
Peter Mitsisd7a37502016-10-13 11:37:40 -04001101
1102/**
1103 * @brief Obtain a message from a message queue.
1104 *
1105 * This routine fetches the oldest item from the message queue. When the message
1106 * queue is found empty, the routine will wait either until an item is added to
1107 * the message queue or until the specified time limit is reached.
1108 *
1109 * @param q Pointer to the message queue object.
1110 * @param data Pointer to message data area.
1111 * @param timeout Number of milliseconds to wait to obtain message, or one of
1112 * the special values K_NO_WAIT and K_FOREVER.
1113 *
1114 * @return 0 if successful, -ENOMSG if failed immediately, -EAGAIN if timed out
1115 *
1116 * @sa K_NO_WAIT, K_FOREVER
1117 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001118extern int k_msgq_get(struct k_msgq *q, void *data, int32_t timeout);
Peter Mitsisd7a37502016-10-13 11:37:40 -04001119
1120/**
1121 * @brief Purge contents of a message queue.
1122 *
1123 * Discards all messages currently in the message queue, and cancels
1124 * any "add message" operations initiated by waiting threads.
1125 *
1126 * @param q Pointer to the message queue object.
1127 *
1128 * @return N/A
1129 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001130extern void k_msgq_purge(struct k_msgq *q);
1131
Peter Mitsis67be2492016-10-07 11:44:34 -04001132/**
1133 * @brief Get the number of unused messages
1134 *
1135 * @param q Message queue to query
1136 *
1137 * @return Number of unused messages
1138 */
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001139static inline uint32_t k_msgq_num_free_get(struct k_msgq *q)
Peter Mitsis67be2492016-10-07 11:44:34 -04001140{
1141 return q->max_msgs - q->used_msgs;
1142}
1143
Peter Mitsisd7a37502016-10-13 11:37:40 -04001144/**
1145 * @brief Get the number of used messages
1146 *
1147 * @param q Message queue to query
1148 *
1149 * @return Number of used messages
1150 */
Peter Mitsis026b4ed2016-10-13 11:41:45 -04001151static inline uint32_t k_msgq_num_used_get(struct k_msgq *q)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001152{
1153 return q->used_msgs;
1154}
1155
1156struct k_mem_block {
Peter Mitsis0cb65c32016-09-29 14:07:36 -04001157 struct k_mem_pool *pool_id;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001158 void *addr_in_pool;
1159 void *data;
Peter Mitsis5f399242016-10-13 13:26:25 -04001160 size_t req_size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001161};
1162
1163/* mailboxes */
1164
1165struct k_mbox_msg {
1166 /** internal use only - needed for legacy API support */
1167 uint32_t _mailbox;
1168 /** size of message (in bytes) */
Peter Mitsisd93078c2016-10-14 12:59:37 -04001169 size_t size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001170 /** application-defined information value */
1171 uint32_t info;
1172 /** sender's message data buffer */
1173 void *tx_data;
1174 /** internal use only - needed for legacy API support */
1175 void *_rx_data;
1176 /** message data block descriptor */
1177 struct k_mem_block tx_block;
1178 /** source thread id */
1179 k_tid_t rx_source_thread;
1180 /** target thread id */
1181 k_tid_t tx_target_thread;
1182 /** internal use only - thread waiting on send (may be a dummy) */
1183 k_tid_t _syncing_thread;
1184#if (CONFIG_NUM_MBOX_ASYNC_MSGS > 0)
1185 /** internal use only - semaphore used during asynchronous send */
1186 struct k_sem *_async_sem;
1187#endif
1188};
1189
1190struct k_mbox {
1191 _wait_q_t tx_msg_queue;
1192 _wait_q_t rx_msg_queue;
1193
1194 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mbox);
1195};
1196
1197#define K_MBOX_INITIALIZER(obj) \
1198 { \
1199 .tx_msg_queue = SYS_DLIST_STATIC_INIT(&obj.tx_msg_queue), \
1200 .rx_msg_queue = SYS_DLIST_STATIC_INIT(&obj.rx_msg_queue), \
1201 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1202 }
1203
Peter Mitsis12092702016-10-14 12:57:23 -04001204/**
1205 * @brief Define a mailbox
1206 *
1207 * This declares and initializes a mailbox. The new mailbox can be passed to
Peter Mitsisd7a37502016-10-13 11:37:40 -04001208 * the kernel's mailbox functions.
Peter Mitsis12092702016-10-14 12:57:23 -04001209 *
1210 * @param name Name of the mailbox
1211 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001212#define K_MBOX_DEFINE(name) \
1213 struct k_mbox name = \
1214 K_MBOX_INITIALIZER(name) \
1215
Peter Mitsis12092702016-10-14 12:57:23 -04001216/**
1217 * @brief Initialize a mailbox.
1218 *
1219 * @param mbox Pointer to the mailbox object
1220 *
1221 * @return N/A
1222 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001223extern void k_mbox_init(struct k_mbox *mbox);
1224
Peter Mitsis12092702016-10-14 12:57:23 -04001225/**
1226 * @brief Send a mailbox message in a synchronous manner.
1227 *
1228 * Sends a message to a mailbox and waits for a receiver to process it.
1229 * The message data may be in a buffer, in a memory pool block, or non-existent
1230 * (i.e. empty message).
1231 *
1232 * @param mbox Pointer to the mailbox object.
1233 * @param tx_msg Pointer to transmit message descriptor.
1234 * @param timeout Maximum time (milliseconds) to wait for the message to be
1235 * received (although not necessarily completely processed).
1236 * Use K_NO_WAIT to return immediately, or K_FOREVER to wait as long
1237 * as necessary.
1238 *
1239 * @return 0 if successful, -ENOMSG if failed immediately, -EAGAIN if timed out
1240 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001241extern int k_mbox_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001242 int32_t timeout);
Peter Mitsis12092702016-10-14 12:57:23 -04001243
1244#if (CONFIG_NUM_MBOX_ASYNC_MSGS > 0)
1245/**
1246 * @brief Send a mailbox message in an asynchronous manner.
1247 *
1248 * Sends a message to a mailbox without waiting for a receiver to process it.
1249 * The message data may be in a buffer, in a memory pool block, or non-existent
1250 * (i.e. an empty message). Optionally, the specified semaphore will be given
1251 * by the mailbox when the message has been both received and disposed of
1252 * by the receiver.
1253 *
1254 * @param mbox Pointer to the mailbox object.
1255 * @param tx_msg Pointer to transmit message descriptor.
1256 * @param sem Semaphore identifier, or NULL if none specified.
1257 *
1258 * @return N/A
1259 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001260extern void k_mbox_async_put(struct k_mbox *mbox, struct k_mbox_msg *tx_msg,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001261 struct k_sem *sem);
Peter Mitsis12092702016-10-14 12:57:23 -04001262#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001263
Peter Mitsis12092702016-10-14 12:57:23 -04001264/**
1265 * @brief Receive a mailbox message.
1266 *
1267 * Receives a message from a mailbox, then optionally retrieves its data
1268 * and disposes of the message.
1269 *
1270 * @param mbox Pointer to the mailbox object.
1271 * @param rx_msg Pointer to receive message descriptor.
1272 * @param buffer Pointer to buffer to receive data.
1273 * (Use NULL to defer data retrieval and message disposal until later.)
1274 * @param timeout Maximum time (milliseconds) to wait for a message.
1275 * Use K_NO_WAIT to return immediately, or K_FOREVER to wait as long as
1276 * necessary.
1277 *
1278 * @return 0 if successful, -ENOMSG if failed immediately, -EAGAIN if timed out
1279 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001280extern int k_mbox_get(struct k_mbox *mbox, struct k_mbox_msg *rx_msg,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001281 void *buffer, int32_t timeout);
Peter Mitsis12092702016-10-14 12:57:23 -04001282
1283/**
1284 * @brief Retrieve mailbox message data into a buffer.
1285 *
1286 * Completes the processing of a received message by retrieving its data
1287 * into a buffer, then disposing of the message.
1288 *
1289 * Alternatively, this routine can be used to dispose of a received message
1290 * without retrieving its data.
1291 *
1292 * @param rx_msg Pointer to receive message descriptor.
1293 * @param buffer Pointer to buffer to receive data. (Use NULL to discard data.)
1294 *
1295 * @return N/A
1296 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001297extern void k_mbox_data_get(struct k_mbox_msg *rx_msg, void *buffer);
Peter Mitsis12092702016-10-14 12:57:23 -04001298
1299/**
1300 * @brief Retrieve mailbox message data into a memory pool block.
1301 *
1302 * Completes the processing of a received message by retrieving its data
1303 * into a memory pool block, then disposing of the message. The memory pool
1304 * block that results from successful retrieval must be returned to the pool
1305 * once the data has been processed, even in cases where zero bytes of data
1306 * are retrieved.
1307 *
1308 * Alternatively, this routine can be used to dispose of a received message
1309 * without retrieving its data. In this case there is no need to return a
1310 * memory pool block to the pool.
1311 *
1312 * This routine allocates a new memory pool block for the data only if the
1313 * data is not already in one. If a new block cannot be allocated, the routine
1314 * returns a failure code and the received message is left unchanged. This
1315 * permits the caller to reattempt data retrieval at a later time or to dispose
1316 * of the received message without retrieving its data.
1317 *
1318 * @param rx_msg Pointer to receive message descriptor.
1319 * @param pool Memory pool identifier. (Use NULL to discard data.)
1320 * @param block Pointer to area to hold memory pool block info.
1321 * @param timeout Maximum time (milliseconds) to wait for a memory pool block.
1322 * Use K_NO_WAIT to return immediately, or K_FOREVER to wait as long as
1323 * necessary.
1324 *
1325 * @return 0 if successful, -ENOMEM if failed immediately, -EAGAIN if timed out
1326 */
Peter Mitsis40680f62016-10-14 10:04:55 -04001327extern int k_mbox_data_block_get(struct k_mbox_msg *rx_msg,
Peter Mitsis0cb65c32016-09-29 14:07:36 -04001328 struct k_mem_pool *pool,
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001329 struct k_mem_block *block, int32_t timeout);
1330
1331/* pipes */
1332
1333struct k_pipe {
1334 unsigned char *buffer; /* Pipe buffer: may be NULL */
1335 size_t size; /* Buffer size */
1336 size_t bytes_used; /* # bytes used in buffer */
1337 size_t read_index; /* Where in buffer to read from */
1338 size_t write_index; /* Where in buffer to write */
1339
1340 struct {
1341 _wait_q_t readers; /* Reader wait queue */
1342 _wait_q_t writers; /* Writer wait queue */
1343 } wait_q;
1344
1345 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_pipe);
1346};
1347
Peter Mitsise5d9c582016-10-14 14:44:57 -04001348#define K_PIPE_INITIALIZER(obj, pipe_buffer, pipe_buffer_size) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001349 { \
1350 .buffer = pipe_buffer, \
1351 .size = pipe_buffer_size, \
1352 .bytes_used = 0, \
1353 .read_index = 0, \
1354 .write_index = 0, \
1355 .wait_q.writers = SYS_DLIST_STATIC_INIT(&obj.wait_q.writers), \
1356 .wait_q.readers = SYS_DLIST_STATIC_INIT(&obj.wait_q.readers), \
1357 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1358 }
1359
Peter Mitsise5d9c582016-10-14 14:44:57 -04001360#define K_PIPE_DEFINE(name, pipe_buffer_size, pipe_align) \
1361 static unsigned char __noinit __aligned(pipe_align) \
1362 _k_pipe_buf_##name[pipe_buffer_size]; \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001363 struct k_pipe name = \
Peter Mitsise5d9c582016-10-14 14:44:57 -04001364 K_PIPE_INITIALIZER(name, _k_pipe_buf_##name, pipe_buffer_size)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001365
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001366/**
1367 * @brief Runtime initialization of a pipe
1368 *
1369 * @param pipe Pointer to pipe to initialize
1370 * @param buffer Pointer to buffer to use for pipe's ring buffer
1371 * @param size Size of the pipe's ring buffer
1372 *
1373 * @return N/A
1374 */
1375extern void k_pipe_init(struct k_pipe *pipe, unsigned char *buffer,
1376 size_t size);
1377
1378/**
1379 * @brief Put a message into the specified pipe
1380 *
1381 * This routine synchronously adds a message into the pipe specified by
1382 * @a pipe. It will wait up to @a timeout for the pipe to accept
Peter Mitsise5d9c582016-10-14 14:44:57 -04001383 * @a bytes_to_write bytes of data. If by @a timeout, the pipe could not
1384 * accept @a min_xfer bytes of data, it fails. Fewer than @a min_xfer will
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001385 * only ever be written to the pipe if K_NO_WAIT < @a timeout < K_FOREVER.
1386 *
1387 * @param pipe Pointer to the pipe
Peter Mitsise5d9c582016-10-14 14:44:57 -04001388 * @param data Data to put into the pipe
1389 * @param bytes_to_write Desired number of bytes to put into the pipe
1390 * @param bytes_written Number of bytes the pipe accepted
1391 * @param min_xfer Minimum number of bytes accepted for success
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001392 * @param timeout Maximum number of milliseconds to wait
1393 *
Peter Mitsise5d9c582016-10-14 14:44:57 -04001394 * @retval 0 At least @a min_xfer were sent
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001395 * @retval -EIO Request can not be satisfied (@a timeout is K_NO_WAIT)
Peter Mitsise5d9c582016-10-14 14:44:57 -04001396 * @retval -EAGAIN Fewer than @a min_xfer were sent
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001397 */
Peter Mitsise5d9c582016-10-14 14:44:57 -04001398extern int k_pipe_put(struct k_pipe *pipe, void *data,
1399 size_t bytes_to_write, size_t *bytes_written,
1400 size_t min_xfer, int32_t timeout);
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001401
1402/**
1403 * @brief Get a message from the specified pipe
1404 *
1405 * This routine synchronously retrieves a message from the pipe specified by
Peter Mitsise5d9c582016-10-14 14:44:57 -04001406 * @a pipe. It will wait up to @a timeout to retrieve @a bytes_to_read
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001407 * bytes of data from the pipe. If by @a timeout, the pipe could not retrieve
Peter Mitsise5d9c582016-10-14 14:44:57 -04001408 * @a min_xfer bytes of data, it fails. Fewer than @a min_xfer will
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001409 * only ever be retrieved from the pipe if K_NO_WAIT < @a timeout < K_FOREVER.
1410 *
1411 * @param pipe Pointer to the pipe
Peter Mitsise5d9c582016-10-14 14:44:57 -04001412 * @param data Location to place retrieved data
1413 * @param bytes_to_read Desired number of bytes to retrieve from the pipe
1414 * @param bytes_read Number of bytes retrieved from the pipe
1415 * @param min_xfer Minimum number of bytes retrieved for success
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001416 * @param timeout Maximum number of milliseconds to wait
1417 *
Peter Mitsise5d9c582016-10-14 14:44:57 -04001418 * @retval 0 At least @a min_xfer were transferred
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001419 * @retval -EIO Request can not be satisfied (@a timeout is K_NO_WAIT)
Peter Mitsise5d9c582016-10-14 14:44:57 -04001420 * @retval -EAGAIN Fewer than @a min_xfer were retrieved
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001421 */
Peter Mitsise5d9c582016-10-14 14:44:57 -04001422extern int k_pipe_get(struct k_pipe *pipe, void *data,
1423 size_t bytes_to_read, size_t *bytes_read,
1424 size_t min_xfer, int32_t timeout);
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001425
Peter Mitsis2fef0232016-10-14 14:53:44 -04001426#if (CONFIG_NUM_PIPE_ASYNC_MSGS > 0)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001427/**
1428 * @brief Send a message to the specified pipe
1429 *
1430 * This routine asynchronously sends a message from the pipe specified by
1431 * @a pipe. Once all @a size bytes have been accepted by the pipe, it will
1432 * free the memory block @a block and give the semaphore @a sem (if specified).
1433 * Up to CONFIG_NUM_PIPE_ASYNC_MSGS asynchronous pipe messages can be in-flight
1434 * at any given time.
1435 *
1436 * @param pipe Pointer to the pipe
1437 * @param block Memory block containing data to send
1438 * @param size Number of data bytes in memory block to send
1439 * @param sem Semaphore to signal upon completion (else NULL)
1440 *
1441 * @retval N/A
1442 */
1443extern void k_pipe_block_put(struct k_pipe *pipe, struct k_mem_block *block,
1444 size_t size, struct k_sem *sem);
Peter Mitsis2fef0232016-10-14 14:53:44 -04001445#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001446
1447/**
1448 * memory management
1449 */
1450
1451/* memory maps */
1452
1453struct k_mem_map {
1454 _wait_q_t wait_q;
Peter Mitsisfb02d572016-10-13 16:55:45 -04001455 uint32_t num_blocks;
1456 size_t block_size;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001457 char *buffer;
1458 char *free_list;
Peter Mitsisfb02d572016-10-13 16:55:45 -04001459 uint32_t num_used;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001460
1461 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mem_map);
1462};
1463
Peter Mitsis578f9112016-10-07 13:50:31 -04001464#define K_MEM_MAP_INITIALIZER(obj, map_buffer, map_block_size, map_num_blocks) \
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001465 { \
1466 .wait_q = SYS_DLIST_STATIC_INIT(&obj.wait_q), \
1467 .num_blocks = map_num_blocks, \
1468 .block_size = map_block_size, \
1469 .buffer = map_buffer, \
1470 .free_list = NULL, \
1471 .num_used = 0, \
1472 _DEBUG_TRACING_KERNEL_OBJECTS_INIT \
1473 }
1474
Peter Mitsis578f9112016-10-07 13:50:31 -04001475/**
1476 * @brief Define a memory map
1477 *
1478 * This declares and initializes a memory map whose buffer is aligned to
1479 * a @a map_align -byte boundary. The new memory map can be passed to the
1480 * kernel's memory map functions.
1481 *
1482 * Note that for each of the blocks in the memory map to be aligned to
1483 * @a map_align bytes, then @a map_block_size must be a multiple of
1484 * @a map_align.
1485 *
1486 * @param name Name of the memory map
1487 * @param map_block_size Size of each block in the buffer (in bytes)
1488 * @param map_num_blocks Number blocks in the buffer
1489 * @param map_align Alignment of the memory map's buffer (power of 2)
1490 */
1491#define K_MEM_MAP_DEFINE(name, map_block_size, map_num_blocks, map_align) \
1492 char __aligned(map_align) \
1493 _k_mem_map_buf_##name[(map_num_blocks) * (map_block_size)]; \
1494 struct k_mem_map name \
1495 __in_section(_k_mem_map_ptr, private, mem_map) = \
1496 K_MEM_MAP_INITIALIZER(name, _k_mem_map_buf_##name, \
1497 map_block_size, map_num_blocks)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001498
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001499/**
1500 * @brief Initialize a memory map.
1501 *
1502 * Initializes the memory map and creates its list of free blocks.
1503 *
1504 * @param map Pointer to the memory map object
1505 * @param buffer Pointer to buffer used for the blocks.
1506 * @param block_size Size of each block, in bytes.
1507 * @param num_blocks Number of blocks.
1508 *
1509 * @return N/A
1510 */
Peter Mitsis578f9112016-10-07 13:50:31 -04001511extern void k_mem_map_init(struct k_mem_map *map, void *buffer,
Peter Mitsisfb02d572016-10-13 16:55:45 -04001512 size_t block_size, uint32_t num_blocks);
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001513
1514/**
1515 * @brief Allocate a memory map block.
1516 *
1517 * Takes a block from the list of unused blocks.
1518 *
1519 * @param map Pointer to memory map object.
1520 * @param mem Pointer to area to receive block address.
1521 * @param timeout Maximum time (milliseconds) to wait for allocation to
1522 * complete. Use K_NO_WAIT to return immediately, or K_FOREVER to wait
1523 * as long as necessary.
1524 *
1525 * @return 0 if successful, -ENOMEM if failed immediately, -EAGAIN if timed out
1526 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001527extern int k_mem_map_alloc(struct k_mem_map *map, void **mem, int32_t timeout);
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001528
1529/**
1530 * @brief Free a memory map block.
1531 *
1532 * Gives block to a waiting thread if there is one, otherwise returns it to
1533 * the list of unused blocks.
1534 *
1535 * @param map Pointer to memory map object.
1536 * @param mem Pointer to area to containing block address.
1537 *
1538 * @return N/A
1539 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001540extern void k_mem_map_free(struct k_mem_map *map, void **mem);
1541
Peter Mitsis4a5d62f2016-10-13 16:53:30 -04001542/**
1543 * @brief Get the number of used memory blocks
1544 *
1545 * This routine gets the current number of used memory blocks in the
1546 * specified pool. It should be used for stats purposes only as that
1547 * value may potentially be out-of-date by the time it is used.
1548 *
1549 * @param map Memory map to query
1550 *
1551 * @return Number of used memory blocks
1552 */
Peter Mitsisfb02d572016-10-13 16:55:45 -04001553static inline uint32_t k_mem_map_num_used_get(struct k_mem_map *map)
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001554{
1555 return map->num_used;
1556}
1557
Peter Mitsisc001aa82016-10-13 13:53:37 -04001558/**
1559 * @brief Get the number of unused memory blocks
1560 *
1561 * This routine gets the current number of unused memory blocks in the
1562 * specified pool. It should be used for stats purposes only as that value
1563 * may potentially be out-of-date by the time it is used.
1564 *
1565 * @param map Memory map to query
1566 *
1567 * @return Number of unused memory blocks
1568 */
Peter Mitsisfb02d572016-10-13 16:55:45 -04001569static inline uint32_t k_mem_map_num_free_get(struct k_mem_map *map)
Peter Mitsisc001aa82016-10-13 13:53:37 -04001570{
1571 return map->num_blocks - map->num_used;
1572}
1573
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001574/* memory pools */
1575
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001576/*
1577 * Memory pool requires a buffer and two arrays of structures for the
1578 * memory block accounting:
1579 * A set of arrays of k_mem_pool_quad_block structures where each keeps a
1580 * status of four blocks of memory.
1581 */
1582struct k_mem_pool_quad_block {
1583 char *mem_blocks; /* pointer to the first of four memory blocks */
1584 uint32_t mem_status; /* four bits. If bit is set, memory block is
1585 allocated */
1586};
1587/*
1588 * Memory pool mechanism uses one array of k_mem_pool_quad_block for accounting
1589 * blocks of one size. Block sizes go from maximal to minimal. Next memory
1590 * block size is 4 times less than the previous one and thus requires 4 times
1591 * bigger array of k_mem_pool_quad_block structures to keep track of the
1592 * memory blocks.
1593 */
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001594
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001595/*
1596 * The array of k_mem_pool_block_set keeps the information of each array of
1597 * k_mem_pool_quad_block structures
1598 */
1599struct k_mem_pool_block_set {
Peter Mitsis5f399242016-10-13 13:26:25 -04001600 size_t block_size; /* memory block size */
1601 uint32_t nr_of_entries; /* nr of quad block structures in the array */
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001602 struct k_mem_pool_quad_block *quad_block;
1603 int count;
1604};
1605
1606/* Memory pool descriptor */
1607struct k_mem_pool {
Peter Mitsis5f399242016-10-13 13:26:25 -04001608 size_t max_block_size;
1609 size_t min_block_size;
1610 uint32_t nr_of_maxblocks;
1611 uint32_t nr_of_block_sets;
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001612 struct k_mem_pool_block_set *block_set;
1613 char *bufblock;
1614 _wait_q_t wait_q;
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001615 _DEBUG_TRACING_KERNEL_OBJECTS_NEXT_PTR(k_mem_pool);
1616};
1617
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001618#ifdef CONFIG_ARM
1619#define _SECTION_TYPE_SIGN "%"
1620#else
1621#define _SECTION_TYPE_SIGN "@"
1622#endif
Benjamin Walsh456c6da2016-09-02 18:55:39 -04001623
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001624/*
1625 * Static memory pool initialization
1626 */
1627/*
1628 * Use .altmacro to be able to recalculate values and pass them as string
1629 * arguments when calling assembler macros resursively
1630 */
1631__asm__(".altmacro\n\t");
1632
1633/*
1634 * Recursively calls a macro
1635 * The followig global symbols need to be initialized:
1636 * __memory_pool_max_block_size - maximal size of the memory block
1637 * __memory_pool_min_block_size - minimal size of the memory block
1638 * Notes:
1639 * Global symbols are used due the fact that assembler macro allows only
1640 * one argument be passed with the % conversion
1641 * Some assemblers do not get division operation ("/"). To avoid it >> 2
1642 * is used instead of / 4.
1643 * n_max argument needs to go first in the invoked macro, as some
1644 * assemblers concatenate \name and %(\n_max * 4) arguments
1645 * if \name goes first
1646 */
1647__asm__(".macro __do_recurse macro_name, name, n_max\n\t"
1648 ".ifge __memory_pool_max_block_size >> 2 -"
1649 " __memory_pool_min_block_size\n\t\t"
1650 "__memory_pool_max_block_size = __memory_pool_max_block_size >> 2\n\t\t"
1651 "\\macro_name %(\\n_max * 4) \\name\n\t"
1652 ".endif\n\t"
1653 ".endm\n");
1654
1655/*
1656 * Build quad blocks
1657 * Macro allocates space in memory for the array of k_mem_pool_quad_block
1658 * structures and recursively calls itself for the next array, 4 times
1659 * larger.
1660 * The followig global symbols need to be initialized:
1661 * __memory_pool_max_block_size - maximal size of the memory block
1662 * __memory_pool_min_block_size - minimal size of the memory block
1663 * __memory_pool_quad_block_size - sizeof(struct k_mem_pool_quad_block)
1664 */
1665__asm__(".macro _build_quad_blocks n_max, name\n\t"
Dmitriy Korovkin3c906512016-10-06 15:50:40 -04001666 ".balign 4\n\t"
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001667 "_mem_pool_quad_blocks_\\name\\()_\\n_max:\n\t"
1668 ".skip __memory_pool_quad_block_size * \\n_max >> 2\n\t"
1669 ".if \\n_max % 4\n\t\t"
1670 ".skip __memory_pool_quad_block_size\n\t"
1671 ".endif\n\t"
1672 "__do_recurse _build_quad_blocks \\name \\n_max\n\t"
1673 ".endm\n");
1674
1675/*
1676 * Build block sets and initialize them
1677 * Macro initializes the k_mem_pool_block_set structure and
1678 * recursively calls itself for the next one.
1679 * The followig global symbols need to be initialized:
1680 * __memory_pool_max_block_size - maximal size of the memory block
1681 * __memory_pool_min_block_size - minimal size of the memory block
1682 * __memory_pool_block_set_count, the number of the elements in the
1683 * block set array must be set to 0. Macro calculates it's real
1684 * value.
1685 * Since the macro initializes pointers to an array of k_mem_pool_quad_block
1686 * structures, _build_quad_blocks must be called prior it.
1687 */
1688__asm__(".macro _build_block_set n_max, name\n\t"
1689 ".int __memory_pool_max_block_size\n\t" /* block_size */
1690 ".if \\n_max % 4\n\t\t"
1691 ".int \\n_max >> 2 + 1\n\t" /* nr_of_entries */
1692 ".else\n\t\t"
1693 ".int \\n_max >> 2\n\t"
1694 ".endif\n\t"
1695 ".int _mem_pool_quad_blocks_\\name\\()_\\n_max\n\t" /* quad_block */
1696 ".int 0\n\t" /* count */
1697 "__memory_pool_block_set_count = __memory_pool_block_set_count + 1\n\t"
1698 "__do_recurse _build_block_set \\name \\n_max\n\t"
1699 ".endm\n");
1700
1701/*
1702 * Build a memory pool structure and initialize it
1703 * Macro uses __memory_pool_block_set_count global symbol,
1704 * block set addresses and buffer address, it may be called only after
1705 * _build_block_set
1706 */
1707__asm__(".macro _build_mem_pool name, min_size, max_size, n_max\n\t"
1708 ".pushsection ._k_memory_pool,\"aw\","
1709 _SECTION_TYPE_SIGN "progbits\n\t"
1710 ".globl \\name\n\t"
1711 "\\name:\n\t"
1712 ".int \\max_size\n\t" /* max_block_size */
1713 ".int \\min_size\n\t" /* min_block_size */
1714 ".int \\n_max\n\t" /* nr_of_maxblocks */
1715 ".int __memory_pool_block_set_count\n\t" /* nr_of_block_sets */
1716 ".int _mem_pool_block_sets_\\name\n\t" /* block_set */
1717 ".int _mem_pool_buffer_\\name\n\t" /* bufblock */
1718 ".int 0\n\t" /* wait_q->head */
1719 ".int 0\n\t" /* wait_q->next */
1720 ".popsection\n\t"
1721 ".endm\n");
1722
1723#define _MEMORY_POOL_QUAD_BLOCK_DEFINE(name, min_size, max_size, n_max) \
1724 __asm__(".pushsection ._k_memory_pool.struct,\"aw\"," \
1725 _SECTION_TYPE_SIGN "progbits\n\t"); \
1726 __asm__("__memory_pool_min_block_size = " STRINGIFY(min_size) "\n\t"); \
1727 __asm__("__memory_pool_max_block_size = " STRINGIFY(max_size) "\n\t"); \
1728 __asm__("_build_quad_blocks " STRINGIFY(n_max) " " \
1729 STRINGIFY(name) "\n\t"); \
1730 __asm__(".popsection\n\t")
1731
1732#define _MEMORY_POOL_BLOCK_SETS_DEFINE(name, min_size, max_size, n_max) \
1733 __asm__("__memory_pool_block_set_count = 0\n\t"); \
1734 __asm__("__memory_pool_max_block_size = " STRINGIFY(max_size) "\n\t"); \
1735 __asm__(".pushsection ._k_memory_pool.struct,\"aw\"," \
1736 _SECTION_TYPE_SIGN "progbits\n\t"); \
Dmitriy Korovkin3c906512016-10-06 15:50:40 -04001737 __asm__(".balign 4\n\t"); \
Dmitriy Korovkin3c426882016-09-01 18:14:17 -04001738 __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_ */