ChibiOS/NIL  3.1.0
ch.h
Go to the documentation of this file.
1 /*
2  ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio.
3 
4  This file is part of ChibiOS.
5 
6  ChibiOS is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation; either version 3 of the License, or
9  (at your option) any later version.
10 
11  ChibiOS is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 /**
21  * @file ch.h
22  * @brief Nil RTOS main header file.
23  * @details This header includes all the required kernel headers so it is the
24  * only header you usually need to include in your application.
25  *
26  * @addtogroup NIL_KERNEL
27  * @{
28  */
29 
30 #ifndef CH_H
31 #define CH_H
32 
33 #include "chtypes.h"
34 #include "chconf.h"
35 #include "chlicense.h"
36 
37 /*===========================================================================*/
38 /* Module constants. */
39 /*===========================================================================*/
40 
41 /**
42  * @brief ChibiOS/NIL identification macro.
43  */
44 #define _CHIBIOS_NIL_
45 
46 /**
47  * @brief Stable release flag.
48  */
49 #define CH_KERNEL_STABLE 1
50 
51 /**
52  * @name ChibiOS/NIL version identification
53  * @{
54  */
55 /**
56  * @brief Kernel version string.
57  */
58 #define CH_KERNEL_VERSION "3.1.0"
59 
60 /**
61  * @brief Kernel version major number.
62  */
63 #define CH_KERNEL_MAJOR 3
64 
65 /**
66  * @brief Kernel version minor number.
67  */
68 #define CH_KERNEL_MINOR 1
69 
70 /**
71  * @brief Kernel version patch number.
72  */
73 #define CH_KERNEL_PATCH 0
74 /** @} */
75 
76 /**
77  * @name Wakeup messages
78  * @{
79  */
80 #define MSG_OK (msg_t)0 /**< @brief OK wakeup message. */
81 #define MSG_TIMEOUT (msg_t)-1 /**< @brief Wake-up caused by
82  a timeout condition. */
83 #define MSG_RESET (msg_t)-2 /**< @brief Wake-up caused by
84  a reset condition. */
85 /** @} */
86 
87 /**
88  * @name Special time constants
89  * @{
90  */
91 /**
92  * @brief Zero time specification for some functions with a timeout
93  * specification.
94  * @note Not all functions accept @p TIME_IMMEDIATE as timeout parameter,
95  * see the specific function documentation.
96  */
97 #define TIME_IMMEDIATE ((sysinterval_t)-1)
98 
99 /**
100  * @brief Infinite time specification for all functions with a timeout
101  * specification.
102  */
103 #define TIME_INFINITE ((sysinterval_t)0)
104 
105 /**
106  * @brief Maximum interval constant usable as timeout.
107  */
108 #define TIME_MAX_INTERVAL ((sysinterval_t)-2)
109 
110 /**
111  * @brief Maximum system of system time before it wraps.
112  */
113 #define TIME_MAX_SYSTIME ((systime_t)-1)
114 /** @} */
116 /**
117  * @name Thread state related macros
118  * @{
119  */
120 #define NIL_STATE_READY (tstate_t)0 /**< @brief Thread ready or
121  executing. */
122 #define NIL_STATE_SLEEPING (tstate_t)1 /**< @brief Thread sleeping. */
123 #define NIL_STATE_SUSP (tstate_t)2 /**< @brief Thread suspended. */
124 #define NIL_STATE_WTQUEUE (tstate_t)3 /**< @brief On queue or semaph. */
125 #define NIL_STATE_WTOREVT (tstate_t)4 /**< @brief Waiting for events. */
126 #define NIL_THD_IS_READY(tr) ((tr)->state == NIL_STATE_READY)
127 #define NIL_THD_IS_SLEEPING(tr) ((tr)->state == NIL_STATE_SLEEPING)
128 #define NIL_THD_IS_SUSP(tr) ((tr)->state == NIL_STATE_SUSP)
129 #define NIL_THD_IS_WTQUEUE(tr) ((tr)->state == NIL_STATE_WTQUEUE)
130 #define NIL_THD_IS_WTOREVT(tr) ((tr)->state == NIL_STATE_WTOREVT)
131 /** @} */
132 
133 /**
134  * @name Events related macros
135  * @{
136  */
137 /**
138  * @brief All events allowed mask.
139  */
140 #define ALL_EVENTS ((eventmask_t)-1)
141 
142 /**
143  * @brief Returns an event mask from an event identifier.
144  */
145 #define EVENT_MASK(eid) ((eventmask_t)(1 << (eid)))
146 /** @} */
147 
148 /*===========================================================================*/
149 /* Module pre-compile time settings. */
150 /*===========================================================================*/
151 
152 /*-*
153  * @brief Number of user threads in the application.
154  * @note This number is not inclusive of the idle thread which is
155  * implicitly handled.
156  */
157 #if !defined(CH_CFG_NUM_THREADS) || defined(__DOXYGEN__)
158 #define CH_CFG_NUM_THREADS 2
159 #endif
160 
161 /*-*
162  * @brief System time counter resolution.
163  * @note Allowed values are 16 or 32 bits.
164  */
165 #if !defined(CH_CFG_ST_RESOLUTION) || defined(__DOXYGEN__)
166 #define CH_CFG_ST_RESOLUTION 32
167 #endif
168 
169 /*-*
170  * @brief System tick frequency.
171  * @note This value together with the @p CH_CFG_ST_RESOLUTION
172  * option defines the maximum amount of time allowed for
173  * timeouts.
174  */
175 #if !defined(CH_CFG_ST_FREQUENCY) || defined(__DOXYGEN__)
176 #define CH_CFG_ST_FREQUENCY 100
177 #endif
178 
179 /*-*
180  * @brief Time delta constant for the tick-less mode.
181  * @note If this value is zero then the system uses the classic
182  * periodic tick. This value represents the minimum number
183  * of ticks that is safe to specify in a timeout directive.
184  * The value one is not valid, timeouts are rounded up to
185  * this value.
186  */
187 #if !defined(CH_CFG_ST_TIMEDELTA) || defined(__DOXYGEN__)
188 #define CH_CFG_ST_TIMEDELTA 0
189 #endif
190 
191 /*-*
192  * @brief Semaphores APIs.
193  * @details If enabled then the Semaphores APIs are included in the kernel.
194  *
195  * @note The default is @p TRUE.
196  */
197 #if !defined(CH_CFG_USE_SEMAPHORES) || defined(__DOXYGEN__)
198 #define CH_CFG_USE_SEMAPHORES TRUE
199 #endif
200 
201 /*-*
202  * @brief Mutexes APIs.
203  * @details If enabled then the mutexes APIs are included in the kernel.
204  *
205  * @note Feature not currently implemented.
206  * @note The default is @p FALSE.
207  */
208 #if !defined(CH_CFG_USE_MUTEXES) || defined(__DOXYGEN__)
209 #define CH_CFG_USE_MUTEXES FALSE
210 #endif
211 
212 /*-*
213  * @brief Events Flags APIs.
214  * @details If enabled then the event flags APIs are included in the kernel.
215  *
216  * @note The default is @p TRUE.
217  */
218 #if !defined(CH_CFG_USE_EVENTS) || defined(__DOXYGEN__)
219 #define CH_CFG_USE_EVENTS TRUE
220 #endif
221 
222 /*-*
223  * @brief Mailboxes APIs.
224  * @details If enabled then the asynchronous messages (mailboxes) APIs are
225  * included in the kernel.
226  *
227  * @note The default is @p TRUE.
228  * @note Requires @p CH_CFG_USE_SEMAPHORES.
229  */
230 #if !defined(CH_CFG_USE_MAILBOXES) || defined(__DOXYGEN__)
231 #define CH_CFG_USE_MAILBOXES TRUE
232 #endif
233 
234 /*-*
235  * @brief Core Memory Manager APIs.
236  * @details If enabled then the core memory manager APIs are included
237  * in the kernel.
238  *
239  * @note The default is @p TRUE.
240  */
241 #if !defined(CH_CFG_USE_MEMCORE) || defined(__DOXYGEN__)
242 #define CH_CFG_USE_MEMCORE TRUE
243 #endif
244 
245 /*-*
246  * @brief Heap Allocator APIs.
247  * @details If enabled then the memory heap allocator APIs are included
248  * in the kernel.
249  *
250  * @note The default is @p TRUE.
251  */
252 #if !defined(CH_CFG_USE_HEAP) || defined(__DOXYGEN__)
253 #define CH_CFG_USE_HEAP TRUE
254 #endif
255 
256 /*-*
257  * @brief Memory Pools Allocator APIs.
258  * @details If enabled then the memory pools allocator APIs are included
259  * in the kernel.
260  *
261  * @note The default is @p TRUE.
262  */
263 #if !defined(CH_CFG_USE_MEMPOOLS) || defined(__DOXYGEN__)
264 #define CH_CFG_USE_MEMPOOLS TRUE
265 #endif
266 /**
267  * @brief Objects Factory APIs.
268  * @details If enabled then the objects factory APIs are included in the
269  * kernel.
270  *
271  * @note The default is @p FALSE.
272  */
273 #if !defined(CH_CFG_USE_FACTORY) || defined(__DOXYGEN__)
274 #define CH_CFG_USE_FACTORY TRUE
275 #endif
276 
277 /**
278  * @brief Maximum length for object names.
279  * @details If the specified length is zero then the name is stored by
280  * pointer but this could have unintended side effects.
281  */
282 #if !defined(CH_CFG_FACTORY_MAX_NAMES_LENGTH) || defined(__DOXYGEN__)
283 #define CH_CFG_FACTORY_MAX_NAMES_LENGTH 8
284 #endif
285 
286 /**
287  * @brief Enables the registry of generic objects.
288  */
289 #if !defined(CH_CFG_FACTORY_OBJECTS_REGISTRY) || defined(__DOXYGEN__)
290 #define CH_CFG_FACTORY_OBJECTS_REGISTRY TRUE
291 #endif
292 
293 /**
294  * @brief Enables factory for generic buffers.
295  */
296 #if !defined(CH_CFG_FACTORY_GENERIC_BUFFERS) || defined(__DOXYGEN__)
297 #define CH_CFG_FACTORY_GENERIC_BUFFERS TRUE
298 #endif
299 
300 /**
301  * @brief Enables factory for semaphores.
302  */
303 #if !defined(CH_CFG_FACTORY_SEMAPHORES) || defined(__DOXYGEN__)
304 #define CH_CFG_FACTORY_SEMAPHORES TRUE
305 #endif
306 
307 /**
308  * @brief Enables factory for mailboxes.
309  */
310 #if !defined(CH_CFG_FACTORY_MAILBOXES) || defined(__DOXYGEN__)
311 #define CH_CFG_FACTORY_MAILBOXES TRUE
312 #endif
313 
314 /**
315  * @brief Enables factory for objects FIFOs.
316  */
317 #if !defined(CH_CFG_FACTORY_OBJ_FIFOS) || defined(__DOXYGEN__)
318 #define CH_CFG_FACTORY_OBJ_FIFOS TRUE
319 #endif
320 
321 /*-*
322  * @brief Debug option, kernel statistics.
323  *
324  * @note Feature not currently implemented.
325  * @note The default is @p FALSE.
326  */
327 #if !defined(CH_DBG_STATISTICS) || defined(__DOXYGEN__)
328 #define CH_DBG_STATISTICS FALSE
329 #endif
330 
331 /*-*
332  * @brief Debug option, system state check.
333  * @note This is a planned feature, not yet implemented.
334  *
335  * @note The default is @p FALSE.
336  */
337 #if !defined(CH_DBG_SYSTEM_STATE_CHECK) || defined(__DOXYGEN__)
338 #define CH_DBG_SYSTEM_STATE_CHECK FALSE
339 #endif
340 
341 /*-*
342  * @brief Debug option, parameters checks.
343  *
344  * @note The default is @p FALSE.
345  */
346 #if !defined(CH_DBG_ENABLE_CHECKS) || defined(__DOXYGEN__)
347 #define CH_DBG_ENABLE_CHECKS FALSE
348 #endif
349 
350 /*-*
351  * @brief System assertions.
352  *
353  * @note The default is @p FALSE.
354  */
355 #if !defined(CH_DBG_ENABLE_ASSERTS) || defined(__DOXYGEN__)
356 #define CH_DBG_ENABLE_ASSERTS FALSE
357 #endif
358 
359 /*-*
360  * @brief Stack check.
361  *
362  * @note The default is @p FALSE.
363  */
364 #if !defined(CH_DBG_ENABLE_STACK_CHECK) || defined(__DOXYGEN__)
365 #define CH_DBG_ENABLE_STACK_CHECK FALSE
366 #endif
367 
368 /*-*
369  * @brief System initialization hook.
370  */
371 #if !defined(CH_CFG_SYSTEM_INIT_HOOK) || defined(__DOXYGEN__)
372 #define CH_CFG_SYSTEM_INIT_HOOK() {}
373 #endif
374 
375 /*-*
376  * @brief Threads descriptor structure extension.
377  * @details User fields added to the end of the @p thread_t structure.
378  */
379 #if !defined(CH_CFG_THREAD_EXT_FIELDS) || defined(__DOXYGEN__)
380 #define CH_CFG_THREAD_EXT_FIELDS
381 #endif
382 
383 /*-*
384  * @brief Threads initialization hook.
385  */
386 #if !defined(CH_CFG_THREAD_EXT_INIT_HOOK) || defined(__DOXYGEN__)
387 #define CH_CFG_THREAD_EXT_INIT_HOOK(tr) {}
388 #endif
389 
390 /*-*
391  * @brief Idle thread enter hook.
392  * @note This hook is invoked within a critical zone, no OS functions
393  * should be invoked from here.
394  * @note This macro can be used to activate a power saving mode.
395  */
396 #if !defined(CH_CFG_IDLE_ENTER_HOOK) || defined(__DOXYGEN__)
397 #define CH_CFG_IDLE_ENTER_HOOK() {}
398 #endif
399 
400 /*-*
401  * @brief Idle thread leave hook.
402  * @note This hook is invoked within a critical zone, no OS functions
403  * should be invoked from here.
404  * @note This macro can be used to deactivate a power saving mode.
405  */
406 #if !defined(CH_CFG_IDLE_LEAVE_HOOK) || defined(__DOXYGEN__)
407 #define CH_CFG_IDLE_LEAVE_HOOK() {}
408 #endif
409 
410 /*-*
411  * @brief System halt hook.
412  */
413 #if !defined(CH_CFG_SYSTEM_HALT_HOOK) || defined(__DOXYGEN__)
414 #define CH_CFG_SYSTEM_HALT_HOOK(reason) {}
415 #endif
416 
417 /*===========================================================================*/
418 /* Derived constants and error checks. */
419 /*===========================================================================*/
420 
421 #if CH_CUSTOMER_LIC_NIL == FALSE
422 #error "ChibiOS/NIL not licensed"
423 #endif
424 
425 #if (CH_LICENSE_FEATURES != CH_FEATURES_FULL) && \
426  (CH_LICENSE_FEATURES != CH_FEATURES_INTERMEDIATE) && \
427  (CH_LICENSE_FEATURES == CH_FEATURES_BASIC)
428 #error "invalid CH_LICENSE_FEATURES setting"
429 #endif
430 
431 /* Restrictions in basic and intermediate modes.*/
432 #if (CH_LICENSE_FEATURES == CH_FEATURES_INTERMEDIATE) || \
433  (CH_LICENSE_FEATURES == CH_FEATURES_BASIC)
434 
435 /* System tick limited to 1000hz.*/
436 #if CH_CFG_ST_FREQUENCY > 1000
437 #undef CH_CFG_ST_FREQUENCY
438 #define CH_CFG_ST_FREQUENCY 1000
439 #endif
440 
441 /* Restricted subsystems.*/
442 #undef CH_CFG_USE_MAILBOXES
443 
444 #define CH_CFG_USE_MAILBOXES FALSE
445 
446 #endif /* (CH_LICENSE_FEATURES == CH_FEATURES_INTERMEDIATE) ||
447  (CH_LICENSE_FEATURES == CH_FEATURES_BASIC) */
448 
449 /* Restrictions in basic mode.*/
450 #if CH_LICENSE_FEATURES == CH_FEATURES_BASIC
451 
452 /* Tick-Less mode restricted.*/
453 #undef CH_CFG_ST_TIMEDELTA
454 #define CH_CFG_ST_TIMEDELTA 0
455 
456 /* Restricted subsystems.*/
457 #undef CH_CFG_USE_MEMCORE
458 #undef CH_CFG_USE_MEMPOOLS
459 #undef CH_CFG_USE_HEAP
460 
461 #define CH_CFG_USE_MEMCORE FALSE
462 #define CH_CFG_USE_MEMPOOLS FALSE
463 #define CH_CFG_USE_HEAP FALSE
464 
465 #endif /* CH_LICENSE_FEATURES == CH_FEATURES_BASIC */
466 
467 #if !defined(_CHIBIOS_NIL_CONF_)
468 #error "missing or wrong configuration file"
469 #endif
470 
471 #if !defined(_CHIBIOS_NIL_CONF_VER_3_0_)
472 #error "obsolete or unknown configuration file"
473 #endif
474 
475 #if CH_CFG_NUM_THREADS < 1
476 #error "at least one thread must be defined"
477 #endif
478 
479 #if CH_CFG_NUM_THREADS > 16
480 #error "ChibiOS/NIL is not recommended for thread-intensive applications," \
481  "consider ChibiOS/RT instead"
482 #endif
483 
484 #if (CH_CFG_ST_RESOLUTION != 16) && (CH_CFG_ST_RESOLUTION != 32)
485 #error "invalid CH_CFG_ST_RESOLUTION specified, must be 16 or 32"
486 #endif
487 
488 #if CH_CFG_ST_FREQUENCY <= 0
489 #error "invalid CH_CFG_ST_FREQUENCY specified, must be greater than zero"
490 #endif
491 
492 #if (CH_CFG_ST_TIMEDELTA < 0) || (CH_CFG_ST_TIMEDELTA == 1)
493 #error "invalid CH_CFG_ST_TIMEDELTA specified, must " \
494  "be zero or greater than one"
495 #endif
496 
497 #if CH_CFG_USE_MUTEXES == TRUE
498 #error "mutexes not yet supported"
499 #endif
500 
501 #if CH_DBG_STATISTICS == TRUE
502 #error "statistics not yet supported"
503 #endif
504 
505 #if (CH_DBG_SYSTEM_STATE_CHECK == TRUE) || \
506  (CH_DBG_ENABLE_CHECKS == TRUE) || \
507  (CH_DBG_ENABLE_ASSERTS == TRUE) || \
508  (CH_DBG_ENABLE_STACK_CHECK == TRUE)
509 #define NIL_DBG_ENABLED TRUE
510 #else
511 #define NIL_DBG_ENABLED FALSE
512 #endif
513 
514 /** Boundaries of the idle thread boundaries, only required if stack checking
515  is enabled.*/
516 #if (CH_DBG_ENABLE_STACK_CHECK == TRUE) || defined(__DOXYGEN__)
517 #define THD_IDLE_BASE (&__main_thread_stack_base__)
518 #define THD_IDLE_END (&__main_thread_stack_end__)
519 #else
520 #define THD_IDLE_BASE NULL
521 #define THD_IDLE_END NULL
522 #endif
523 
524 /*===========================================================================*/
525 /* Module data structures and types. */
526 /*===========================================================================*/
527 
528 #if (CH_CFG_ST_RESOLUTION == 32) || defined(__DOXYGEN__)
529 /**
530  * @brief Type of system time.
531  * @note It is selectable in configuration between 16 or 32 bits.
532  */
533 typedef uint32_t systime_t;
534 
535 /**
536  * @brief Type of time interval.
537  * @note It is selectable in configuration between 16 or 32 bits.
538  */
539 typedef uint32_t sysinterval_t;
540 
541 /**
542  * @brief Type of time conversion variable.
543  * @note This type must have double width than other time types, it is
544  * only used internally for conversions.
545  */
546 typedef uint64_t time_conv_t;
547 
548 #else
549 typedef uint16_t systime_t;
550 typedef uint16_t sysinterval_t;
551 typedef uint32_t time_conv_t;
552 #endif
553 
554 /**
555  * @brief Type of a structure representing a thread.
556  * @note It is required as an early definition.
557  */
558 typedef struct nil_thread thread_t;
559 
560 #include "chcore.h"
562 /**
563  * @brief Structure representing a queue of threads.
564  */
565 struct nil_threads_queue {
566  volatile cnt_t cnt; /**< @brief Threads Queue counter. */
567 };
569 /**
570  * @brief Type of a queue of threads.
571  */
572 typedef struct nil_threads_queue threads_queue_t;
573 
574 #if (CH_CFG_USE_SEMAPHORES == TRUE) || defined(__DOXYGEN__)
575 /**
576  * @brief Type of a structure representing a semaphore.
577  * @note Semaphores are implemented on thread queues, the object is the
578  * same, the behavior is slightly different.
579  */
581 #endif /* CH_CFG_USE_SEMAPHORES == TRUE */
582 
583 /**
584  * @brief Thread function.
585  */
586 typedef void (*tfunc_t)(void *p);
587 
588 /**
589  * @brief Type of a structure representing a thread static configuration.
590  */
591 typedef struct nil_thread_cfg thread_config_t;
592 
593 /**
594  * @brief Structure representing a thread static configuration.
595  */
596 struct nil_thread_cfg {
597  stkalign_t *wbase; /**< @brief Thread working area base. */
598  stkalign_t *wend; /**< @brief Thread working area end. */
599  const char *namep; /**< @brief Thread name, for debugging. */
600  tfunc_t funcp; /**< @brief Thread function. */
601  void *arg; /**< @brief Thread function argument. */
602 };
604 /**
605  * @brief Type of a thread reference.
606  */
607 typedef thread_t * thread_reference_t;
608 
609 /**
610  * @brief Structure representing a thread.
611  */
612 struct nil_thread {
613  struct port_context ctx; /**< @brief Processor context. */
614  tstate_t state; /**< @brief Thread state. */
615  /* Note, the following union contains a pointer while the thread is in a
616  sleeping state (!NIL_THD_IS_READY()) else contains the wake-up message.*/
617  union {
618  msg_t msg; /**< @brief Wake-up message. */
619  void *p; /**< @brief Generic pointer. */
620  thread_reference_t *trp; /**< @brief Pointer to thread reference.*/
621  threads_queue_t *tqp; /**< @brief Pointer to thread queue. */
622 #if (CH_CFG_USE_SEMAPHORES == TRUE) || defined(__DOXYGEN__)
623  semaphore_t *semp; /**< @brief Pointer to semaphore. */
624 #endif
625 #if (CH_CFG_USE_EVENTS == TRUE) || defined(__DOXYGEN__)
626  eventmask_t ewmask; /**< @brief Enabled events mask. */
627 #endif
628  } u1;
629  volatile sysinterval_t timeout; /**< @brief Timeout counter, zero
630  if disabled. */
631 #if (CH_CFG_USE_EVENTS == TRUE) || defined(__DOXYGEN__)
632  eventmask_t epmask; /**< @brief Pending events mask. */
633 #endif
634 #if (CH_DBG_ENABLE_STACK_CHECK == TRUE) || defined(__DOXYGEN__)
635  stkalign_t *wabase; /**< @brief Thread stack boundary. */
636 #endif
637  /* Optional extra fields.*/
639 };
640 
641 /**
642  * @brief Type of a structure representing the system.
643  */
644 typedef struct nil_system nil_system_t;
645 
646 /**
647  * @brief System data structure.
648  * @note This structure contain all the data areas used by the OS except
649  * stacks.
650  */
651 struct nil_system {
652  /**
653  * @brief Pointer to the running thread.
654  */
655  thread_t *current;
656  /**
657  * @brief Pointer to the next thread to be executed.
658  * @note This pointer must point at the same thread pointed by @p current
659  * or to an higher priority thread if a switch is required.
660  */
661  thread_t *next;
662 #if (CH_CFG_ST_TIMEDELTA == 0) || defined(__DOXYGEN__)
663  /**
664  * @brief System time.
665  */
666  volatile systime_t systime;
667 #endif
668 #if (CH_CFG_ST_TIMEDELTA > 0) || defined(__DOXYGEN__)
669  /**
670  * @brief System time of the last tick event.
671  */
672  systime_t lasttime;
673  /**
674  * @brief Time of the next scheduled tick event.
675  */
676  systime_t nexttime;
677 #endif
678 #if (CH_DBG_SYSTEM_STATE_CHECK == TRUE) || defined(__DOXYGEN__)
679  /**
680  * @brief ISR nesting level.
681  */
682  cnt_t isr_cnt;
683  /**
684  * @brief Lock nesting level.
685  */
686  cnt_t lock_cnt;
687 #endif
688 #if (NIL_DBG_ENABLED == TRUE) || defined(__DOXYGEN__)
689  /**
690  * @brief Panic message.
691  * @note This field is only present if some debug options have been
692  * activated.
693  * @note Accesses to this pointer must never be optimized out so the
694  * field itself is declared volatile.
695  */
696  const char * volatile dbg_panic_msg;
697 #endif
698  /**
699  * @brief Thread structures for all the defined threads.
700  */
701  thread_t threads[CH_CFG_NUM_THREADS + 1];
702 };
703 
704 /*===========================================================================*/
705 /* Module macros. */
706 /*===========================================================================*/
707 
708 #if CH_DBG_SYSTEM_STATE_CHECK == TRUE
709 #define _dbg_enter_lock() (nil.lock_cnt = (cnt_t)1)
710 #define _dbg_leave_lock() (nil.lock_cnt = (cnt_t)0)
711 #endif
712 
713 /**
714  * @brief Utility to make the parameter a quoted string.
715  */
716 #define __CH_STRINGIFY(a) #a
717 
718 /**
719  * @name Threads tables definition macros
720  * @{
721  */
722 /**
723  * @brief Start of user threads table.
724  */
725 #define THD_TABLE_BEGIN \
726  const thread_config_t nil_thd_configs[CH_CFG_NUM_THREADS + 1] = {
727 
728 /**
729  * @brief Entry of user threads table
730  */
731 #define THD_TABLE_ENTRY(wap, name, funcp, arg) \
732  {wap, ((stkalign_t *)(wap)) + (sizeof (wap) / sizeof(stkalign_t)), \
733  name, funcp, arg},
735 /**
736  * @brief End of user threads table.
737  */
738 #define THD_TABLE_END \
739  {THD_IDLE_BASE, THD_IDLE_END, "idle", NULL, NULL} \
740 };
741 /** @} */
742 
743 /**
744  * @name Memory alignment support macros
745  */
746 /**
747  * @brief Alignment mask constant.
748  *
749  * @param[in] a alignment, must be a power of two
750  */
751 #define MEM_ALIGN_MASK(a) ((size_t)(a) - 1U)
752 
753 /**
754  * @brief Aligns to the previous aligned memory address.
755  *
756  * @param[in] p variable to be aligned
757  * @param[in] a alignment, must be a power of two
758  */
759 #define MEM_ALIGN_PREV(p, a) ((size_t)(p) & ~MEM_ALIGN_MASK(a))
760 
761 /**
762  * @brief Aligns to the new aligned memory address.
763  *
764  * @param[in] p variable to be aligned
765  * @param[in] a alignment, must be a power of two
766  */
767 #define MEM_ALIGN_NEXT(p, a) MEM_ALIGN_PREV((size_t)(p) + \
768  MEM_ALIGN_MASK(a), (a))
769 
770 /**
771  * @brief Returns whatever a pointer or memory size is aligned.
772  *
773  * @param[in] p variable to be aligned
774  * @param[in] a alignment, must be a power of two
775  */
776 #define MEM_IS_ALIGNED(p, a) (((size_t)(p) & MEM_ALIGN_MASK(a)) == 0U)
777 
778 /**
779  * @brief Returns whatever a constant is a valid alignment.
780  * @details Valid alignments are powers of two.
781  *
782  * @param[in] a alignment to be checked, must be a constant
783  */
784 #define MEM_IS_VALID_ALIGNMENT(a) \
785  (((size_t)(a) != 0U) && (((size_t)(a) & ((size_t)(a) - 1U)) == 0U))
786 /** @} */
788 /**
789  * @name Working Areas
790  */
791 /**
792  * @brief Calculates the total Working Area size.
793  *
794  * @param[in] n the stack size to be assigned to the thread
795  * @return The total used memory in bytes.
796  *
797  * @api
798  */
799 #define THD_WORKING_AREA_SIZE(n) MEM_ALIGN_NEXT(PORT_WA_SIZE(n), \
800  PORT_STACK_ALIGN)
801 
802 /**
803  * @brief Static working area allocation.
804  * @details This macro is used to allocate a static thread working area
805  * aligned as both position and size.
806  *
807  * @param[in] s the name to be assigned to the stack array
808  * @param[in] n the stack size to be assigned to the thread
809  *
810  * @api
811  */
812 #define THD_WORKING_AREA(s, n) PORT_WORKING_AREA(s, n)
813 /** @} */
814 
815 /**
816  * @name Threads abstraction macros
817  */
818 /**
819  * @brief Thread declaration macro.
820  * @note Thread declarations should be performed using this macro because
821  * the port layer could define optimizations for thread functions.
822  */
823 #define THD_FUNCTION(tname, arg) PORT_THD_FUNCTION(tname, arg)
824 /** @} */
825 
826 /**
827  * @name ISRs abstraction macros
828  */
829 /**
830  * @brief Priority level validation macro.
831  * @details This macro determines if the passed value is a valid priority
832  * level for the underlying architecture.
833  *
834  * @param[in] prio the priority level
835  * @return Priority range result.
836  * @retval false if the priority is invalid or if the architecture
837  * does not support priorities.
838  * @retval true if the priority is valid.
839  */
840 #if defined(PORT_IRQ_IS_VALID_PRIORITY) || defined(__DOXYGEN__)
841 #define CH_IRQ_IS_VALID_PRIORITY(prio) \
842  PORT_IRQ_IS_VALID_PRIORITY(prio)
843 #else
844 #define CH_IRQ_IS_VALID_PRIORITY(prio) false
845 #endif
846 
847 /**
848  * @brief Priority level validation macro.
849  * @details This macro determines if the passed value is a valid priority
850  * level that cannot preempt the kernel critical zone.
851  *
852  * @param[in] prio the priority level
853  * @return Priority range result.
854  * @retval false if the priority is invalid or if the architecture
855  * does not support priorities.
856  * @retval true if the priority is valid.
857  */
858 #if defined(PORT_IRQ_IS_VALID_KERNEL_PRIORITY) || defined(__DOXYGEN__)
859 #define CH_IRQ_IS_VALID_KERNEL_PRIORITY(prio) \
860  PORT_IRQ_IS_VALID_KERNEL_PRIORITY(prio)
861 #else
862 #define CH_IRQ_IS_VALID_KERNEL_PRIORITY(prio) false
863 #endif
864 
865 /**
866  * @brief IRQ handler enter code.
867  * @note Usually IRQ handlers functions are also declared naked.
868  * @note On some architectures this macro can be empty.
869  *
870  * @special
871  */
872 #define CH_IRQ_PROLOGUE() \
873  PORT_IRQ_PROLOGUE(); \
874  _dbg_check_enter_isr()
876 /**
877  * @brief IRQ handler exit code.
878  * @note Usually IRQ handlers function are also declared naked.
879  *
880  * @special
881  */
882 #define CH_IRQ_EPILOGUE() \
883  _dbg_check_leave_isr(); \
884  PORT_IRQ_EPILOGUE()
886 /**
887  * @brief Standard normal IRQ handler declaration.
888  * @note @p id can be a function name or a vector number depending on the
889  * port implementation.
890  *
891  * @special
892  */
893 #define CH_IRQ_HANDLER(id) PORT_IRQ_HANDLER(id)
894 /** @} */
895 
896 /**
897  * @name Fast ISRs abstraction macros
898  */
899 /**
900  * @brief Standard fast IRQ handler declaration.
901  * @note @p id can be a function name or a vector number depending on the
902  * port implementation.
903  * @note Not all architectures support fast interrupts.
904  *
905  * @special
906  */
907 #define CH_FAST_IRQ_HANDLER(id) PORT_FAST_IRQ_HANDLER(id)
908 /** @} */
909 
910 /**
911  * @name Time conversion utilities
912  * @{
913  */
914 /**
915  * @brief Seconds to time interval.
916  * @details Converts from seconds to system ticks number.
917  * @note The result is rounded upward to the next tick boundary.
918  * @note Use of this macro for large values is not secure because
919  * integer overflows, make sure your value can be correctly
920  * converted.
921  *
922  * @param[in] secs number of seconds
923  * @return The number of ticks.
924  *
925  * @api
926  */
927 #define TIME_S2I(secs) \
928  ((sysinterval_t)((time_conv_t)(secs) * (time_conv_t)CH_CFG_ST_FREQUENCY))
929 
930 /**
931  * @brief Milliseconds to time interval.
932  * @details Converts from milliseconds to system ticks number.
933  * @note The result is rounded upward to the next tick boundary.
934  * @note Use of this macro for large values is not secure because
935  * integer overflows, make sure your value can be correctly
936  * converted.
937  *
938  * @param[in] msecs number of milliseconds
939  * @return The number of ticks.
940  *
941  * @api
942  */
943 #define TIME_MS2I(msecs) \
944  ((sysinterval_t)((((time_conv_t)(msecs) * \
945  (time_conv_t)CH_CFG_ST_FREQUENCY) + \
946  (time_conv_t)999) / (time_conv_t)1000))
947 
948 /**
949  * @brief Microseconds to time interval.
950  * @details Converts from microseconds to system ticks number.
951  * @note The result is rounded upward to the next tick boundary.
952  * @note Use of this macro for large values is not secure because
953  * integer overflows, make sure your value can be correctly
954  * converted.
955  *
956  * @param[in] usecs number of microseconds
957  * @return The number of ticks.
958  *
959  * @api
960  */
961 #define TIME_US2I(usecs) \
962  ((sysinterval_t)((((time_conv_t)(usecs) * \
963  (time_conv_t)CH_CFG_ST_FREQUENCY) + \
964  (time_conv_t)999999) / (time_conv_t)1000000))
965 
966 /**
967  * @brief Time interval to seconds.
968  * @details Converts from system ticks number to seconds.
969  * @note The result is rounded up to the next second boundary.
970  * @note Use of this macro for large values is not secure because
971  * integer overflows, make sure your value can be correctly
972  * converted.
973  *
974  * @param[in] interval interval in ticks
975  * @return The number of seconds.
976  *
977  * @api
978  */
979 #define TIME_I2S(interval) \
980  (time_secs_t)(((time_conv_t)(interval) + \
981  (time_conv_t)CH_CFG_ST_FREQUENCY - \
982  (time_conv_t)1) / (time_conv_t)CH_CFG_ST_FREQUENCY)
983 
984 /**
985  * @brief Time interval to milliseconds.
986  * @details Converts from system ticks number to milliseconds.
987  * @note The result is rounded up to the next millisecond boundary.
988  * @note Use of this macro for large values is not secure because
989  * integer overflows, make sure your value can be correctly
990  * converted.
991  *
992  * @param[in] interval interval in ticks
993  * @return The number of milliseconds.
994  *
995  * @api
996  */
997 #define TIME_I2MS(interval) \
998  (time_msecs_t)((((time_conv_t)(interval) * (time_conv_t)1000) + \
999  (time_conv_t)CH_CFG_ST_FREQUENCY - (time_conv_t)1) / \
1000  (time_conv_t)CH_CFG_ST_FREQUENCY)
1001 
1002 /**
1003  * @brief Time interval to microseconds.
1004  * @details Converts from system ticks number to microseconds.
1005  * @note The result is rounded up to the next microsecond boundary.
1006  * @note Use of this macro for large values is not secure because
1007  * integer overflows, make sure your value can be correctly
1008  * converted.
1009  *
1010  * @param[in] interval interval in ticks
1011  * @return The number of microseconds.
1012  *
1013  * @api
1014  */
1015 #define TIME_I2US(interval) \
1016  (time_msecs_t)((((time_conv_t)(interval) * (time_conv_t)1000000) + \
1017  (time_conv_t)CH_CFG_ST_FREQUENCY - (time_conv_t)1) / \
1018  (time_conv_t)CH_CFG_ST_FREQUENCY)
1019 /** @} */
1020 
1021 /**
1022  * @name Threads queues
1023  */
1024 /**
1025  * @brief Data part of a static threads queue object initializer.
1026  * @details This macro should be used when statically initializing a threads
1027  * queue that is part of a bigger structure.
1028  *
1029  * @param[in] name the name of the threads queue variable
1030  */
1031 #define _THREADS_QUEUE_DATA(name) {(cnt_t)0}
1032 
1033 /**
1034  * @brief Static threads queue object initializer.
1035  * @details Statically initialized threads queues require no explicit
1036  * initialization using @p queue_init().
1037  *
1038  * @param[in] name the name of the threads queue variable
1039  */
1040 #define _THREADS_QUEUE_DECL(name) \
1041  threads_queue_t name = _THREADS_QUEUE_DATA(name)
1042 /** @} */
1044 /**
1045  * @name Semaphores macros
1046  * @{
1047  */
1048 /**
1049  * @brief Data part of a static semaphore initializer.
1050  * @details This macro should be used when statically initializing a semaphore
1051  * that is part of a bigger structure.
1052  *
1053  * @param[in] name the name of the semaphore variable
1054  * @param[in] n the counter initial value, this value must be
1055  * non-negative
1056  */
1057 #define _SEMAPHORE_DATA(name, n) {n}
1058 
1059 /**
1060  * @brief Static semaphore initializer.
1061  * @details Statically initialized semaphores require no explicit
1062  * initialization using @p chSemInit().
1063  *
1064  * @param[in] name the name of the semaphore variable
1065  * @param[in] n the counter initial value, this value must be
1066  * non-negative
1067  */
1068 #define SEMAPHORE_DECL(name, n) semaphore_t name = _SEMAPHORE_DATA(name, n)
1069 /** @} */
1070 
1071 /**
1072  * @name Macro Functions
1073  * @{
1074  */
1075 /**
1076  * @brief Returns the current value of the system real time counter.
1077  * @note This function is only available if the port layer supports the
1078  * option @p PORT_SUPPORTS_RT.
1079  *
1080  * @return The value of the system realtime counter of
1081  * type rtcnt_t.
1082  *
1083  * @xclass
1084  */
1085 #if (PORT_SUPPORTS_RT == TRUE) || defined(__DOXYGEN__)
1086 #define chSysGetRealtimeCounterX() (rtcnt_t)port_rt_get_counter_value()
1087 #endif
1088 
1089 /**
1090  * @brief Raises the system interrupt priority mask to the maximum level.
1091  * @details All the maskable interrupt sources are disabled regardless their
1092  * hardware priority.
1093  * @note Do not invoke this API from within a kernel lock.
1094  *
1095  * @special
1096  */
1097 #define chSysDisable() { \
1098  port_disable(); \
1099  _dbg_check_disable(); \
1101 
1102 /**
1103  * @brief Raises the system interrupt priority mask to system level.
1104  * @details The interrupt sources that should not be able to preempt the kernel
1105  * are disabled, interrupt sources with higher priority are still
1106  * enabled.
1107  * @note Do not invoke this API from within a kernel lock.
1108  * @note This API is no replacement for @p chSysLock(), the @p chSysLock()
1109  * could do more than just disable the interrupts.
1110  *
1111  * @special
1112  */
1113 #define chSysSuspend() { \
1114  port_suspend(); \
1115  _dbg_check_suspend(); \
1117 
1118 /**
1119  * @brief Lowers the system interrupt priority mask to user level.
1120  * @details All the interrupt sources are enabled.
1121  * @note Do not invoke this API from within a kernel lock.
1122  * @note This API is no replacement for @p chSysUnlock(), the
1123  * @p chSysUnlock() could do more than just enable the interrupts.
1124  *
1125  * @special
1126  */
1127 #define chSysEnable() { \
1128  _dbg_check_enable(); \
1129  port_enable(); \
1131 
1132 /**
1133  * @brief Enters the kernel lock state.
1134  *
1135  * @special
1136  */
1137 #define chSysLock() { \
1138  port_lock(); \
1139  _dbg_check_lock(); \
1141 
1142 /**
1143  * @brief Leaves the kernel lock state.
1144  *
1145  * @special
1146  */
1147 #define chSysUnlock() { \
1148  _dbg_check_unlock(); \
1149  port_unlock(); \
1151 
1152 /**
1153  * @brief Enters the kernel lock state from within an interrupt handler.
1154  * @note This API may do nothing on some architectures, it is required
1155  * because on ports that support preemptable interrupt handlers
1156  * it is required to raise the interrupt mask to the same level of
1157  * the system mutual exclusion zone.<br>
1158  * It is good practice to invoke this API before invoking any I-class
1159  * syscall from an interrupt handler.
1160  * @note This API must be invoked exclusively from interrupt handlers.
1161  *
1162  * @special
1163  */
1164 #define chSysLockFromISR() { \
1165  port_lock_from_isr(); \
1166  _dbg_check_lock_from_isr(); \
1168 
1169 /**
1170  * @brief Leaves the kernel lock state from within an interrupt handler.
1171  *
1172  * @note This API may do nothing on some architectures, it is required
1173  * because on ports that support preemptable interrupt handlers
1174  * it is required to raise the interrupt mask to the same level of
1175  * the system mutual exclusion zone.<br>
1176  * It is good practice to invoke this API after invoking any I-class
1177  * syscall from an interrupt handler.
1178  * @note This API must be invoked exclusively from interrupt handlers.
1179  *
1180  * @special
1181  */
1182 #define chSysUnlockFromISR() { \
1183  _dbg_check_unlock_from_isr(); \
1184  port_unlock_from_isr(); \
1186 
1187 /**
1188  * @brief Evaluates if a reschedule is required.
1189  *
1190  * @retval true if there is a thread that must go in running state
1191  * immediately.
1192  * @retval false if preemption is not required.
1193  *
1194  * @iclass
1195  */
1196 #define chSchIsRescRequiredI() ((bool)(nil.current != nil.next))
1197 
1198 /**
1199  * @brief Returns a pointer to the current @p thread_t.
1200  *
1201  * @xclass
1202  */
1203 #define chThdGetSelfX() nil.current
1204 
1205 /**
1206  * @brief Delays the invoking thread for the specified number of seconds.
1207  * @note The specified time is rounded up to a value allowed by the real
1208  * system clock.
1209  * @note The maximum specified value is implementation dependent.
1210  *
1211  * @param[in] secs time in seconds, must be different from zero
1212  *
1213  * @api
1214  */
1215 #define chThdSleepSeconds(secs) chThdSleep(TIME_S2I(secs))
1216 
1217 /**
1218  * @brief Delays the invoking thread for the specified number of
1219  * milliseconds.
1220  * @note The specified time is rounded up to a value allowed by the real
1221  * system clock.
1222  * @note The maximum specified value is implementation dependent.
1223  *
1224  * @param[in] msecs time in milliseconds, must be different from zero
1225  *
1226  * @api
1227  */
1228 #define chThdSleepMilliseconds(msecs) chThdSleep(TIME_MS2I(msecs))
1229 
1230 /**
1231  * @brief Delays the invoking thread for the specified number of
1232  * microseconds.
1233  * @note The specified time is rounded up to a value allowed by the real
1234  * system clock.
1235  * @note The maximum specified value is implementation dependent.
1236  *
1237  * @param[in] usecs time in microseconds, must be different from zero
1238  *
1239  * @api
1240  */
1241 #define chThdSleepMicroseconds(usecs) chThdSleep(TIME_US2I(usecs))
1242 
1243 /**
1244  * @brief Suspends the invoking thread for the specified time.
1245  *
1246  * @param[in] timeout the delay in system ticks
1247  *
1248  * @sclass
1249  */
1250 #define chThdSleepS(timeout) \
1251  (void) chSchGoSleepTimeoutS(NIL_STATE_SLEEPING, timeout)
1252 
1253 /**
1254  * @brief Suspends the invoking thread until the system time arrives to the
1255  * specified value.
1256  *
1257  * @param[in] abstime absolute system time
1258  *
1259  * @sclass
1260  */
1261 #define chThdSleepUntilS(abstime) \
1262  (void) chSchGoSleepTimeoutS(NIL_STATE_SLEEPING, \
1263  chTimeDiffX(chVTGetSystemTimeX(), (abstime)))
1265 /**
1266  * @brief Initializes a threads queue object.
1267  *
1268  * @param[out] tqp pointer to the threads queue object
1269  *
1270  * @init
1271  */
1272 #define chThdQueueObjectInit(tqp) ((tqp)->cnt = (cnt_t)0)
1273 
1274 /**
1275  * @brief Evaluates to @p true if the specified queue is empty.
1276  *
1277  * @param[out] tqp pointer to the threads queue object
1278  * @return The queue status.
1279  * @retval false if the queue is not empty.
1280  * @retval true if the queue is empty.
1281  *
1282  * @iclass
1283  */
1284 #define chThdQueueIsEmptyI(tqp) ((bool)(tqp->cnt >= (cnt_t)0))
1285 
1286 #if (CH_CFG_USE_SEMAPHORES == TRUE) || defined(__DOXYGEN__)
1287 /**
1288  * @brief Initializes a semaphore with the specified counter value.
1289  *
1290  * @param[out] sp pointer to a @p semaphore_t structure
1291  * @param[in] n initial value of the semaphore counter. Must be
1292  * non-negative.
1293  *
1294  * @init
1295  */
1296 #define chSemObjectInit(sp, n) ((sp)->cnt = n)
1297 
1298 /**
1299  * @brief Performs a wait operation on a semaphore.
1300  *
1301  * @param[in] sp pointer to a @p semaphore_t structure
1302  * @return A message specifying how the invoking thread has been
1303  * released from the semaphore.
1304  * @retval CH_MSG_OK if the thread has not stopped on the semaphore or the
1305  * semaphore has been signaled.
1306  * @retval CH_MSG_RST if the semaphore has been reset using @p chSemReset().
1307  *
1308  * @api
1309  */
1310 #define chSemWait(sp) chSemWaitTimeout(sp, TIME_INFINITE)
1311 
1312 /**
1313  * @brief Performs a wait operation on a semaphore.
1314  *
1315  * @param[in] sp pointer to a @p semaphore_t structure
1316  * @return A message specifying how the invoking thread has been
1317  * released from the semaphore.
1318  * @retval CH_MSG_OK if the thread has not stopped on the semaphore or the
1319  * semaphore has been signaled.
1320  * @retval CH_MSG_RST if the semaphore has been reset using @p chSemReset().
1321  *
1322  * @sclass
1323  */
1324 #define chSemWaitS(sp) chSemWaitTimeoutS(sp, TIME_INFINITE)
1325 
1326 /**
1327  * @brief Decreases the semaphore counter.
1328  * @details This macro can be used when the counter is known to be positive.
1329  *
1330  * @param[in] sp pointer to a @p semaphore_t structure
1331  *
1332  * @iclass
1333  */
1334 #define chSemFastWaitI(sp) ((sp)->cnt--)
1335 
1336 /**
1337  * @brief Increases the semaphore counter.
1338  * @details This macro can be used when the counter is known to be not
1339  * negative.
1340  *
1341  * @param[in] sp pointer to a @p semaphore_t structure
1342  *
1343  * @iclass
1344  */
1345 #define chSemFastSignalI(sp) ((sp)->cnt++)
1346 
1347 /**
1348  * @brief Returns the semaphore counter current value.
1349  *
1350  * @iclass
1351  */
1352 #define chSemGetCounterI(sp) ((sp)->cnt)
1353 #endif /* CH_CFG_USE_SEMAPHORES == TRUE */
1354 
1355 /**
1356  * @brief Current system time.
1357  * @details Returns the number of system ticks since the @p chSysInit()
1358  * invocation.
1359  * @note The counter can reach its maximum and then restart from zero.
1360  * @note This function can be called from any context but its atomicity
1361  * is not guaranteed on architectures whose word size is less than
1362  * @p systime_t size.
1363  *
1364  * @return The system time in ticks.
1365  *
1366  * @xclass
1367  */
1368 #if (CH_CFG_ST_TIMEDELTA == 0) || defined(__DOXYGEN__)
1369 #define chVTGetSystemTimeX() (nil.systime)
1370 #else
1371 #define chVTGetSystemTimeX() port_timer_get_time()
1372 #endif
1373 
1374 /**
1375  * @brief Returns the elapsed time since the specified start time.
1376  *
1377  * @param[in] start start time
1378  * @return The elapsed time.
1379  *
1380  * @xclass
1381  */
1382 #define chVTTimeElapsedSinceX(start) \
1383  chTimeDiffX((start), chVTGetSystemTimeX())
1384 
1385 /**
1386  * @brief Adds an interval to a system time returning a system time.
1387  *
1388  * @param[in] systime base system time
1389  * @param[in] interval interval to be added
1390  * @return The new system time.
1391  *
1392  * @xclass
1393  */
1394 #define chTimeAddX(systime, interval) \
1395  ((systime_t)(systime) + (systime_t)(interval))
1396 
1397 /**
1398  * @brief Subtracts two system times returning an interval.
1399  *
1400  * @param[in] start first system time
1401  * @param[in] end second system time
1402  * @return The interval representing the time difference.
1403  *
1404  * @xclass
1405  */
1406 #define chTimeDiffX(start, end) \
1407  ((sysinterval_t)((systime_t)((systime_t)(end) - (systime_t)(start))))
1408 
1409 /**
1410  * @brief Checks if the specified time is within the specified time range.
1411  * @note When start==end then the function returns always true because the
1412  * whole time range is specified.
1413  *
1414  * @param[in] time the time to be verified
1415  * @param[in] start the start of the time window (inclusive)
1416  * @param[in] end the end of the time window (non inclusive)
1417  * @retval true current time within the specified time window.
1418  * @retval false current time not within the specified time window.
1419  *
1420  * @xclass
1421  */
1422 #define chTimeIsInRangeX(time, start, end) \
1423  ((bool)((systime_t)((systime_t)(time) - (systime_t)(start)) < \
1424  (systime_t)((systime_t)(end) - (systime_t)(start))))
1426 /**
1427  * @brief Function parameters check.
1428  * @details If the condition check fails then the kernel panics and halts.
1429  * @note The condition is tested only if the @p CH_DBG_ENABLE_CHECKS switch
1430  * is specified in @p chconf.h else the macro does nothing.
1431  *
1432  * @param[in] c the condition to be verified to be true
1433  *
1434  * @api
1435  */
1436 #if !defined(chDbgCheck)
1437 #define chDbgCheck(c) do { \
1438  /*lint -save -e506 -e774 [2.1, 14.3] Can be a constant by design.*/ \
1439  if (CH_DBG_ENABLE_CHECKS != FALSE) { \
1440  if (!(c)) { \
1441  /*lint -restore*/ \
1442  chSysHalt(__func__); \
1443  } \
1444  } \
1445 } while (false)
1446 #endif /* !defined(chDbgCheck) */
1447 
1448 /**
1449  * @brief Condition assertion.
1450  * @details If the condition check fails then the kernel panics with a
1451  * message and halts.
1452  * @note The condition is tested only if the @p CH_DBG_ENABLE_ASSERTS
1453  * switch is specified in @p chconf.h else the macro does nothing.
1454  * @note The remark string is not currently used except for putting a
1455  * comment in the code about the assertion.
1456  *
1457  * @param[in] c the condition to be verified to be true
1458  * @param[in] r a remark string
1459  *
1460  * @api
1461  */
1462 #if !defined(chDbgAssert)
1463 #define chDbgAssert(c, r) do { \
1464  /*lint -save -e506 -e774 [2.1, 14.3] Can be a constant by design.*/ \
1465  if (CH_DBG_ENABLE_ASSERTS != FALSE) { \
1466  if (!(c)) { \
1467  /*lint -restore*/ \
1468  chSysHalt(__func__); \
1469  } \
1470  } \
1471 } while (false)
1472 #endif /* !defined(chDbgAssert) */
1473 /** @} */
1474 
1475 /* Empty macros if the state checker is not enabled.*/
1476 #if CH_DBG_SYSTEM_STATE_CHECK == FALSE
1477 #define _dbg_enter_lock()
1478 #define _dbg_leave_lock()
1479 #define _dbg_check_disable()
1480 #define _dbg_check_suspend()
1481 #define _dbg_check_enable()
1482 #define _dbg_check_lock()
1483 #define _dbg_check_unlock()
1484 #define _dbg_check_lock_from_isr()
1485 #define _dbg_check_unlock_from_isr()
1486 #define _dbg_check_enter_isr()
1487 #define _dbg_check_leave_isr()
1488 #define chDbgCheckClassI()
1489 #define chDbgCheckClassS()
1490 #endif
1491 
1492 /*===========================================================================*/
1493 /* External declarations. */
1494 /*===========================================================================*/
1495 
1496 #if !defined(__DOXYGEN__)
1497 #if (CH_DBG_ENABLE_STACK_CHECK == TRUE) || defined(__DOXYGEN__)
1498 extern stkalign_t __main_thread_stack_base__, __main_thread_stack_end__;
1499 #endif
1500 extern nil_system_t nil;
1501 extern const thread_config_t nil_thd_configs[CH_CFG_NUM_THREADS + 1];
1502 #endif
1503 
1504 #ifdef __cplusplus
1505 extern "C" {
1506 #endif
1507  void chSysInit(void);
1508  void chSysHalt(const char *reason);
1509  void chSysTimerHandlerI(void);
1510  void chSysUnconditionalLock(void);
1511  void chSysUnconditionalUnlock(void);
1512  syssts_t chSysGetStatusAndLockX(void);
1513  bool chSysIsCounterWithinX(rtcnt_t cnt, rtcnt_t start, rtcnt_t end);
1514  void chSysPolledDelayX(rtcnt_t cycles);
1515  void chSysRestoreStatusX(syssts_t sts);
1516  thread_t *chSchReadyI(thread_t *tp, msg_t msg);
1517  bool chSchIsPreemptionRequired(void);
1518  void chSchDoReschedule(void);
1519  void chSchRescheduleS(void);
1520  msg_t chSchGoSleepTimeoutS(tstate_t newstate, sysinterval_t timeout);
1522  void chThdResumeI(thread_reference_t *trp, msg_t msg);
1523  void chThdResume(thread_reference_t *trp, msg_t msg);
1524  void chThdSleep(sysinterval_t timeout);
1525  void chThdSleepUntil(systime_t abstime);
1526  msg_t chThdEnqueueTimeoutS(threads_queue_t *tqp, sysinterval_t timeout);
1527  void chThdDoDequeueNextI(threads_queue_t *tqp, msg_t msg);
1528  void chThdDequeueNextI(threads_queue_t *tqp, msg_t msg);
1529  void chThdDequeueAllI(threads_queue_t *tqp, msg_t msg);
1530 #if CH_CFG_USE_SEMAPHORES == TRUE
1531  msg_t chSemWaitTimeout(semaphore_t *sp, sysinterval_t timeout);
1532  msg_t chSemWaitTimeoutS(semaphore_t *sp, sysinterval_t timeout);
1533  void chSemSignal(semaphore_t *sp);
1534  void chSemSignalI(semaphore_t *sp);
1535  void chSemReset(semaphore_t *sp, cnt_t n);
1536  void chSemResetI(semaphore_t *sp, cnt_t n);
1537 #endif /* CH_CFG_USE_SEMAPHORES == TRUE */
1538 #if CH_CFG_USE_EVENTS == TRUE
1539  void chEvtSignal(thread_t *tp, eventmask_t mask);
1540  void chEvtSignalI(thread_t *tp, eventmask_t mask);
1541  eventmask_t chEvtWaitAnyTimeout(eventmask_t mask, sysinterval_t timeout);
1542 #endif
1543 #if CH_DBG_SYSTEM_STATE_CHECK == TRUE
1544  void _dbg_check_disable(void);
1545  void _dbg_check_suspend(void);
1546  void _dbg_check_enable(void);
1547  void _dbg_check_lock(void);
1548  void _dbg_check_unlock(void);
1549  void _dbg_check_lock_from_isr(void);
1550  void _dbg_check_unlock_from_isr(void);
1551  void _dbg_check_enter_isr(void);
1552  void _dbg_check_leave_isr(void);
1553  void chDbgCheckClassI(void);
1554  void chDbgCheckClassS(void);
1555 #endif
1556 #ifdef __cplusplus
1557 }
1558 #endif
1559 
1560 /* Optional subsystems.*/
1561 #include "chmboxes.h"
1562 #include "chmemcore.h"
1563 #include "chheap.h"
1564 #include "chmempools.h"
1565 #include "chfifo.h"
1566 #include "chfactory.h"
1567 
1568 #endif /* CH_H */
1569 
1570 /** @} */
ChibiOS objects factory structures and macros.
threads_queue_t semaphore_t
Type of a structure representing a semaphore.
Definition: ch.h:583
Structure representing a thread.
Definition: ch.h:615
void chSchRescheduleS(void)
Reschedules if needed.
Definition: ch.c:660
Heaps macros and structures.
void chEvtSignal(thread_t *tp, eventmask_t mask)
Adds a set of event flags directly to the specified thread_t.
Definition: ch.c:1115
msg_t chSchGoSleepTimeoutS(tstate_t newstate, sysinterval_t timeout)
Puts the current thread to sleep into the specified state with timeout specification.
Definition: ch.c:686
void chSysHalt(const char *reason)
Halts the system.
Definition: ch.c:357
volatile cnt_t cnt
Threads Queue counter.
Definition: ch.h:569
void chThdDequeueAllI(threads_queue_t *tqp, msg_t msg)
Dequeues and wakes up all threads from the threads queue object.
Definition: ch.c:939
void chSemSignal(semaphore_t *sp)
Performs a signal operation on a semaphore.
Definition: ch.c:1026
Objects FIFO structures and macros.
msg_t chThdSuspendTimeoutS(thread_reference_t *trp, sysinterval_t timeout)
Sends the current thread sleeping and sets a reference variable.
Definition: ch.c:770
void chThdResume(thread_reference_t *trp, msg_t msg)
Wakes up a thread waiting on a thread reference object.
Definition: ch.c:815
void chEvtSignalI(thread_t *tp, eventmask_t mask)
Adds a set of event flags directly to the specified thread_t.
Definition: ch.c:1135
thread_t * thread_reference_t
Type of a thread reference.
Definition: ch.h:610
Memory Pools macros and structures.
void(* tfunc_t)(void *p)
Thread function.
Definition: ch.h:589
Core memory manager macros and structures.
void chThdResumeI(thread_reference_t *trp, msg_t msg)
Wakes up a thread waiting on a thread reference object.
Definition: ch.c:793
void chSemSignalI(semaphore_t *sp)
Performs a signal operation on a semaphore.
Definition: ch.c:1045
void chThdDoDequeueNextI(threads_queue_t *tqp, msg_t msg)
Dequeues and wakes up one thread from the threads queue object.
Definition: ch.c:902
Structure representing a thread static configuration.
Definition: ch.h:599
void chSysRestoreStatusX(syssts_t sts)
Restores the specified execution status and leaves a critical zone.
Definition: ch.c:539
eventmask_t chEvtWaitAnyTimeout(eventmask_t mask, sysinterval_t timeout)
Waits for any of the specified events.
Definition: ch.c:1165
void chDbgCheckClassS(void)
S-class functions context check.
Definition: ch.c:257
#define CH_CFG_THREAD_EXT_FIELDS
Threads descriptor structure extension.
Definition: chconf.h:290
void chSemReset(semaphore_t *sp, cnt_t n)
Performs a reset operation on the semaphore.
Definition: ch.c:1068
void chSemResetI(semaphore_t *sp, cnt_t n)
Performs a reset operation on the semaphore.
Definition: ch.c:1092
void _dbg_check_suspend(void)
Guard code for chSysSuspend().
Definition: ch.c:133
void chThdSleepUntil(systime_t abstime)
Suspends the invoking thread until the system time arrives to the specified value.
Definition: ch.c:845
void chDbgCheckClassI(void)
I-class functions context check.
Definition: ch.c:242
uint32_t sysinterval_t
Type of time interval.
Definition: ch.h:542
void chThdSleep(sysinterval_t timeout)
Suspends the invoking thread for the specified time.
Definition: ch.c:830
void chSysUnconditionalLock(void)
Unconditionally enters the kernel lock state.
Definition: ch.c:482
msg_t chThdEnqueueTimeoutS(threads_queue_t *tqp, sysinterval_t timeout)
Enqueues the caller thread on a threads queue object.
Definition: ch.c:875
Mailboxes macros and structures.
Configuration file template.
void chSysPolledDelayX(rtcnt_t cycles)
Polled delay.
Definition: ch.c:587
void _dbg_check_lock(void)
Guard code for chSysLock().
Definition: ch.c:157
#define CH_CFG_NUM_THREADS
Number of user threads in the application.
Definition: chconf.h:46
void chSysInit(void)
Initializes the kernel.
Definition: ch.c:276
uint32_t systime_t
Type of system time.
Definition: ch.h:536
void chThdDequeueNextI(threads_queue_t *tqp, msg_t msg)
Dequeues and wakes up one thread from the threads queue object, if any.
Definition: ch.c:921
License Module macros and structures.
uint64_t time_conv_t
Type of time conversion variable.
Definition: ch.h:549
bool chSchIsPreemptionRequired(void)
Evaluates if preemption is required.
Definition: ch.c:633
void chSysTimerHandlerI(void)
Time management handler.
Definition: ch.c:382
void _dbg_check_lock_from_isr(void)
Guard code for chSysLockFromIsr().
Definition: ch.c:183
void _dbg_check_unlock_from_isr(void)
Guard code for chSysUnlockFromIsr().
Definition: ch.c:196
void _dbg_check_enable(void)
Guard code for chSysEnable().
Definition: ch.c:145
bool chSysIsCounterWithinX(rtcnt_t cnt, rtcnt_t start, rtcnt_t end)
Realtime window test.
Definition: ch.c:571
void chSysUnconditionalUnlock(void)
Unconditionally leaves the kernel lock state.
Definition: ch.c:496
Structure representing a queue of threads.
Definition: ch.h:568
thread_t * chSchReadyI(thread_t *tp, msg_t msg)
Makes the specified thread ready for execution.
Definition: ch.c:604
void _dbg_check_leave_isr(void)
Guard code for CH_IRQ_EPILOGUE().
Definition: ch.c:224
syssts_t chSysGetStatusAndLockX(void)
Returns the execution status and enters a critical zone.
Definition: ch.c:516
void _dbg_check_enter_isr(void)
Guard code for CH_IRQ_PROLOGUE().
Definition: ch.c:209
void chSchDoReschedule(void)
Switches to the first thread on the runnable queue.
Definition: ch.c:645
msg_t chSemWaitTimeout(semaphore_t *sp, sysinterval_t timeout)
Performs a wait operation on a semaphore with timeout specification.
Definition: ch.c:967
nil_system_t nil
System data structures.
Definition: ch.c:41
System data structure.
Definition: ch.h:654
msg_t chSemWaitTimeoutS(semaphore_t *sp, sysinterval_t timeout)
Performs a wait operation on a semaphore with timeout specification.
Definition: ch.c:996
void _dbg_check_unlock(void)
Guard code for chSysUnlock().
Definition: ch.c:170
void _dbg_check_disable(void)
Guard code for chSysDisable().
Definition: ch.c:121