ChibiOS 21.11.5
chsys.c
Go to the documentation of this file.
1/*
2 ChibiOS - Copyright (C) 2006-2026 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 version 3 of the License.
9
10 ChibiOS is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17*/
18
19/**
20 * @file rt/src/chsys.c
21 * @brief System related code.
22 *
23 * @addtogroup system
24 * @details System related APIs and services:
25 * - Initialization.
26 * - Locks.
27 * - Interrupt Handling.
28 * - Power Management.
29 * - Abnormal Termination.
30 * - Realtime counter.
31 * .
32 * @{
33 */
34
35#include "ch.h"
36
37/*===========================================================================*/
38/* Module exported variables. */
39/*===========================================================================*/
40
41/**
42 * @brief System root object.
43 */
45
46/**
47 * @brief Core 0 OS instance.
48 */
50
51#if (CH_CFG_NO_IDLE_THREAD == FALSE) || defined(__DOXYGEN__)
52/**
53 * @brief Working area for core 0 idle thread.
54 */
55static CH_SYS_CORE0_MEMORY THD_WORKING_AREA(ch_c0_idle_thread_wa,
57#endif
58
59#if CH_DBG_ENABLE_STACK_CHECK == TRUE
61#endif
62
63/**
64 * @brief Core 0 OS instance configuration.
65 */
67 .name = "c0",
68#if CH_DBG_ENABLE_STACK_CHECK == TRUE
69 .mainthread_base = &__main_thread_stack_base__,
70 .mainthread_end = &__main_thread_stack_end__,
71#elif CH_CFG_USE_DYNAMIC == TRUE
72 .mainthread_base = NULL,
73 .mainthread_end = NULL,
74#endif
75#if CH_CFG_NO_IDLE_THREAD == FALSE
76 .idlethread_base = THD_WORKING_AREA_BASE(ch_c0_idle_thread_wa),
77 .idlethread_end = THD_WORKING_AREA_END(ch_c0_idle_thread_wa)
78#endif
79};
80
81#if (PORT_CORES_NUMBER > 1) || defined(__DOXYGEN__)
82/**
83 * @brief Core 1 OS instance.
84 */
86
87#if (CH_CFG_NO_IDLE_THREAD == FALSE) || defined(__DOXYGEN__)
88/**
89 * @brief Working area for core 1 idle thread.
90 */
91static CH_SYS_CORE1_MEMORY THD_WORKING_AREA(ch_c1_idle_thread_wa,
93#endif
94
95#if CH_DBG_ENABLE_STACK_CHECK == TRUE
97#endif
98
99/**
100 * @brief Core 1 OS instance configuration.
101 */
103 .name = "c1",
104#if CH_DBG_ENABLE_STACK_CHECK == TRUE
105 .mainthread_base = &__c1_main_thread_stack_base__,
106 .mainthread_end = &__c1_main_thread_stack_end__,
107#elif CH_CFG_USE_DYNAMIC == TRUE
108 .mainthread_base = NULL,
109 .mainthread_end = NULL,
110#endif
111#if CH_CFG_NO_IDLE_THREAD == FALSE
112 .idlethread_base = THD_WORKING_AREA_BASE(ch_c1_idle_thread_wa),
113 .idlethread_end = THD_WORKING_AREA_END(ch_c1_idle_thread_wa)
114#endif
115};
116#endif /* PORT_CORES_NUMBER > 1 */
117
118/*===========================================================================*/
119/* Module local types. */
120/*===========================================================================*/
121
122/*===========================================================================*/
123/* Module local variables. */
124/*===========================================================================*/
125
126/*===========================================================================*/
127/* Module local functions. */
128/*===========================================================================*/
129
130/*===========================================================================*/
131/* Module exported functions. */
132/*===========================================================================*/
133
134/**
135 * @brief Waits for the system state to be equal to the specified one.
136 * @note Can be called before @p chSchObjectInit() in order to wait
137 * for system initialization by another core.
138 *
139 * @special
140 */
142
143 while (ch_system.state != state) {
144 }
145}
146
147/**
148 * @brief System initialization.
149 * @details After executing this function the current instructions stream
150 * becomes the main thread.
151 * @pre Interrupts must disabled before invoking this function.
152 * @post The main thread is created with priority @p NORMALPRIO and
153 * interrupts are enabled.
154 * @post the system is in @p ch_sys_running state.
155 *
156 * @special
157 */
158void chSysInit(void) {
159 unsigned i;
160
161 /* System object initialization.*/
163 for (i = 0U; i < (unsigned)PORT_CORES_NUMBER; i++) {
164 ch_system.instances[i] = NULL;
165 }
166
167#if CH_CFG_USE_TM == TRUE
168 /* Time Measurement calibration.*/
170#endif
171
172#if (CH_CFG_USE_REGISTRY == TRUE) && (CH_CFG_SMP_MODE == TRUE)
173 /* Registry initialization when SMP mode is enabled.*/
175#endif
176
177#if CH_CFG_SMP_MODE == TRUE
178 /* RFCU initialization when SMP mode is enabled.*/
180#endif
181
182 /* User system initialization hook.*/
184
185 /* OS library modules.*/
186 __oslib_init();
187
188 /* Initializing default OS instance.*/
190
191 /* It is alive now.*/
193 chSysUnlock();
194}
195
196/**
197 * @brief Halts the system.
198 * @details This function is invoked by the operating system when an
199 * unrecoverable error is detected, for example because a programming
200 * error in the application code that triggers an assertion while
201 * in debug mode.
202 * @note Can be invoked from any system state.
203 *
204 * @param[in] reason pointer to an error string
205 *
206 * @special
207 */
208void chSysHalt(const char *reason) {
209
210 port_disable();
211
212 /* Logging the event.*/
213 __trace_halt(reason);
214
215 /* Pointing to the passed message.*/
216 currcore->dbg.panic_msg = reason;
217
218 /* Halt hook code, usually empty.*/
220
221#if defined(PORT_SYSTEM_HALT_HOOK)
222 /* Port-related actions, this could include halting other instances
223 via some inter-core messaging or other means.*/
224 PORT_SYSTEM_HALT_HOOK();
225#endif
226
227 /* Entering the halted state.*/
229
230 /* Harmless infinite loop.*/
231 while (true) {
232 }
233}
234
235/**
236 * @brief Returns a pointer to the idle thread.
237 * @note The reference counter of the idle thread is not incremented but
238 * it is not strictly required being the idle thread a static
239 * object.
240 * @note This function cannot be called from the idle thread itself,
241 * use @p chThdGetSelfX() in that case.
242 *
243 * @return Pointer to the idle thread.
244 *
245 * @xclass
246 */
248 thread_t *tp = threadref(currcore->rlist.pqueue.prev);
249
250 chDbgAssert(tp->hdr.pqueue.prio == IDLEPRIO, "not idle thread");
251
252 return tp;
253}
254
255/**
256 * @brief System integrity check.
257 * @details Performs an integrity check of the important ChibiOS/RT data
258 * structures.
259 * @note The appropriate action in case of failure is to halt the system
260 * before releasing the critical zone.
261 * @note If the system is corrupted then one possible outcome of this
262 * function is an exception caused by @p NULL or corrupted pointers
263 * in list elements. Exception vectors must be monitored as well.
264 * @note This function is not used internally, it is up to the
265 * application to define if and where to perform system
266 * checking.
267 * @note Performing all tests at once can be a slow operation and can
268 * degrade the system response time. It is suggested to execute
269 * one test at time and release the critical zone in between tests.
270 *
271 * @param[in] testmask Each bit in this mask is associated to a test to be
272 * performed.
273 * @return The test result.
274 * @retval false The test succeeded.
275 * @retval true Test failed.
276 *
277 * @iclass
278 */
279bool chSysIntegrityCheckI(unsigned testmask) {
280 os_instance_t *oip = currcore;
281 cnt_t n;
282
284
285 /* Ready List integrity check.*/
286 if ((testmask & CH_INTEGRITY_RLIST) != 0U) {
288
289 /* Scanning the ready list forward.*/
290 n = (cnt_t)0;
291 pqp = oip->rlist.pqueue.next;
292 while (pqp != &oip->rlist.pqueue) {
293 n++;
294 pqp = pqp->next;
295 }
296
297 /* Scanning the ready list backward.*/
298 pqp = oip->rlist.pqueue.prev;
299 while (pqp != &oip->rlist.pqueue) {
300 n--;
301 pqp = pqp->prev;
302 }
303
304 /* The number of elements must match.*/
305 if (n != (cnt_t)0) {
306 return true;
307 }
308 }
309
310 /* Timers list integrity check.*/
311 if ((testmask & CH_INTEGRITY_VTLIST) != 0U) {
312 ch_delta_list_t *dlp;
313
314 /* Scanning the timers list forward.*/
315 n = (cnt_t)0;
316 dlp = oip->vtlist.dlist.next;
317 while (dlp != &oip->vtlist.dlist) {
318 n++;
319 dlp = dlp->next;
320 }
321
322 /* Scanning the timers list backward.*/
323 dlp = oip->vtlist.dlist.prev;
324 while (dlp != &oip->vtlist.dlist) {
325 n--;
326 dlp = dlp->prev;
327 }
328
329 /* The number of elements must match.*/
330 if (n != (cnt_t)0) {
331 return true;
332 }
333 }
334
335#if CH_CFG_USE_REGISTRY == TRUE
336 if ((testmask & CH_INTEGRITY_REGISTRY) != 0U) {
337 ch_queue_t *qp, *rqp;
338
339 /* Registry header, access to this list depends on the current
340 kernel configuration.*/
341 rqp = REG_HEADER(oip);
342
343 /* Scanning the registry list forward.*/
344 n = (cnt_t)0;
345 qp = rqp->next;
346 while (qp != rqp) {
347 n++;
348 qp = qp->next;
349 }
350
351 /* Scanning the registry list backward.*/
352 qp = rqp->prev;
353 while (qp != rqp) {
354 n--;
355 qp = qp->prev;
356 }
357
358 /* The number of elements must match.*/
359 if (n != (cnt_t)0) {
360 return true;
361 }
362 }
363#endif /* CH_CFG_USE_REGISTRY == TRUE */
364
365#if defined(PORT_INTEGRITY_CHECK)
366 if ((testmask & CH_INTEGRITY_PORT) != 0U) {
367 PORT_INTEGRITY_CHECK();
368 }
369#endif
370
371 return false;
372}
373
374/**
375 * @brief Handles time ticks for round robin preemption and timer increments.
376 * @details Decrements the remaining time quantum of the running thread
377 * and preempts it when the quantum is used up. Increments system
378 * time and manages the timers.
379 * @note The frequency of the timer determines the system tick granularity
380 * and, together with the @p CH_CFG_TIME_QUANTUM macro, the round robin
381 * interval.
382 *
383 * @iclass
384 */
386#if (CH_CFG_TIME_QUANTUM > 0) || (CH_DBG_THREADS_PROFILING == TRUE)
387 thread_t *currtp = chThdGetSelfX();
388#endif
389
391
392#if CH_CFG_TIME_QUANTUM > 0
393 /* Running thread has not used up quantum yet? */
394 if (currtp->ticks > (tslices_t)0) {
395 /* Decrement remaining quantum.*/
396 currtp->ticks--;
397 }
398#endif
399#if CH_DBG_THREADS_PROFILING == TRUE
400 currtp->time++;
401#endif
402 chVTDoTickI();
404}
405
406#if (CH_PORT_SUPPORTS_RECURSIVE_LOCKS == TRUE) || defined(__DOXYGEN__)
407/**
408 * @brief Returns the execution status and enters a critical zone.
409 * @details This functions enters into a critical zone and can be called
410 * from any context. Because its flexibility it is less efficient
411 * than @p chSysLock() which is preferable when the calling context
412 * is known.
413 * @post The system is in a critical zone.
414 * @note This function is only available if the underlying port supports
415 * @p port_get_lock_status() and @p port_is_locked().
416 *
417 * @return The previous system status, the encoding of this
418 * status word is architecture-dependent and opaque.
419 *
420 * @xclass
421 */
423
425 if (!port_is_locked(sts)) {
426 if (port_is_isr_context()) {
428 }
429 else {
430 chSysLock();
431 }
432 }
433 return sts;
434}
435
436/**
437 * @brief Restores the specified execution status and leaves a critical zone.
438 * @note A call to @p chSchRescheduleS() is automatically performed
439 * if exiting the critical zone and if not in ISR context.
440 * @note This function is only available if the underlying port supports
441 * @p port_get_lock_status() and @p port_is_locked().
442 *
443 * @param[in] sts the system status to be restored.
444 *
445 * @xclass
446 */
448
449 if (!port_is_locked(sts)) {
450 if (port_is_isr_context()) {
452 }
453 else {
455 chSysUnlock();
456 }
457 }
458}
459#endif /* CH_PORT_SUPPORTS_RECURSIVE_LOCKS == TRUE */
460
461#if (PORT_SUPPORTS_RT == TRUE) || defined(__DOXYGEN__)
462/**
463 * @brief Realtime window test.
464 * @details This function verifies if the current realtime counter value
465 * lies within the specified range or not. The test takes care
466 * of the realtime counter wrapping to zero on overflow.
467 * @note When start==end then the function returns always false because a
468 * null time range is specified.
469 * @note This function is only available if the port layer supports the
470 * option @p PORT_SUPPORTS_RT.
471 *
472 * @param[in] cnt the counter value to be tested
473 * @param[in] start the start of the time window (inclusive)
474 * @param[in] end the end of the time window (non inclusive)
475 * @retval true current time within the specified time window.
476 * @retval false current time not within the specified time window.
477 *
478 * @xclass
479 */
481
482 return (bool)(((rtcnt_t)cnt - (rtcnt_t)start) <
483 ((rtcnt_t)end - (rtcnt_t)start));
484}
485
486/**
487 * @brief Polled delay.
488 * @note The real delay is always few cycles in excess of the specified
489 * value.
490 * @note This function is only available if the port layer supports the
491 * option @p PORT_SUPPORTS_RT.
492 *
493 * @param[in] cycles number of cycles
494 *
495 * @xclass
496 */
499 rtcnt_t end = start + cycles;
500
501 while (chSysIsCounterWithinX(chSysGetRealtimeCounterX(), start, end)) {
502 }
503}
504#endif /* PORT_SUPPORTS_RT == TRUE */
505
506/** @} */
#define chThdGetSelfX()
Returns a pointer to the current thread_t.
#define chSysLockFromISR()
Enters the kernel lock state from within an interrupt handler.
#define chSysUnlock()
Leaves the kernel lock state.
#define chSysLock()
Enters the kernel lock state.
#define chSysUnlockFromISR()
Leaves the kernel lock state from within an interrupt handler.
#define chDbgAssert(c, r)
Condition assertion.
Definition chdebug.h:143
#define chDbgCheckClassI()
Definition chdebug.h:98
#define CH_CFG_SYSTEM_TICK_HOOK()
System tick event hook.
#define CH_CFG_SYSTEM_HALT_HOOK(reason)
System halt hook.
#define CH_CFG_SYSTEM_INIT_HOOK()
System initialization hook.
void chInstanceObjectInit(os_instance_t *oip, const os_instance_config_t *oicp)
Initializes a system instance.
Definition chinstances.c:88
struct ch_priority_queue ch_priority_queue_t
Type of a generic priority-ordered bidirectional linked list header and element.
Definition chlists.h:77
struct ch_delta_list ch_delta_list_t
Type of a generic bidirectional linked delta list header and element.
Definition chlists.h:94
struct ch_queue ch_queue_t
Type of a generic bidirectional linked list header and element.
Definition chlists.h:62
#define threadref(p)
Safe cast of a queue pointer to a thread pointer.
Definition chearly.h:205
int32_t cnt_t
Definition chearly.h:91
port_syssts_t syssts_t
Definition chearly.h:78
struct ch_system ch_system_t
Type of system data structure.
struct ch_os_instance os_instance_t
Type of an OS instance structure.
Definition chearly.h:137
struct ch_os_instance_config os_instance_config_t
Type of an system instance configuration.
port_rtcnt_t rtcnt_t
Definition chearly.h:76
uint8_t tslices_t
Definition chearly.h:85
port_stkalign_t stkalign_t
Definition chearly.h:79
system_state_t
Global state of the operating system.
Definition chobjects.h:49
struct ch_thread thread_t
Type of a thread structure.
Definition chearly.h:132
@ ch_sys_running
Definition chobjects.h:52
@ ch_sys_initializing
Definition chobjects.h:51
@ ch_sys_halted
Definition chobjects.h:53
static void __oslib_init(void)
Initialization of all library modules.
Definition chlib.h:248
static void port_disable(void)
Disables all the interrupt sources.
Definition chcore.h:375
#define port_get_lock_status()
Returns a word representing a critical section status.
Definition chcore.h:282
#define PORT_IDLE_THREAD_STACK_SIZE
Stack size for the system idle thread.
Definition chcore.h:110
#define port_is_locked(sts)
Determines if in a critical section.
Definition chcore.h:292
static bool port_is_isr_context(void)
Determines the current execution context.
Definition chcore.h:328
#define PORT_CORES_NUMBER
Definition chport.h:125
#define REG_HEADER(oip)
Access to the registry list header.
Definition chregistry.h:97
static void __reg_object_init(registry_t *rp)
Initializes a registry.
Definition chregistry.h:150
static void __rfcu_object_init(rfcu_t *rfcup)
Runtime Faults Collection Unit initialization.
Definition chrfcu.h:103
void chSchRescheduleS(void)
Performs a reschedule if a higher priority thread is runnable.
Definition chschd.c:457
#define IDLEPRIO
Idle priority.
Definition chschd.h:51
#define CH_SYS_CORE0_MEMORY
Core zero memory affinity macro.
Definition chsys.h:61
stkalign_t __main_thread_stack_end__
Definition chsys.c:60
#define chSysGetRealtimeCounterX()
Returns the current value of the system real time counter.
Definition chsys.h:291
syssts_t chSysGetStatusAndLockX(void)
Returns the execution status and enters a critical zone.
Definition chsys.c:422
#define CH_INTEGRITY_VTLIST
Definition chsys.h:41
CH_SYS_CORE1_MEMORY os_instance_t ch1
Core 1 OS instance.
Definition chsys.c:85
bool chSysIsCounterWithinX(rtcnt_t cnt, rtcnt_t start, rtcnt_t end)
Realtime window test.
Definition chsys.c:480
void chSysTimerHandlerI(void)
Handles time ticks for round robin preemption and timer increments.
Definition chsys.c:385
CH_SYS_CORE0_MEMORY os_instance_t ch0
Core 0 OS instance.
Definition chsys.c:49
bool chSysIntegrityCheckI(unsigned testmask)
System integrity check.
Definition chsys.c:279
#define CH_SYS_CORE1_MEMORY
Core one memory affinity macro.
Definition chsys.h:73
#define CH_INTEGRITY_REGISTRY
Definition chsys.h:42
thread_t * chSysGetIdleThreadX(void)
Returns a pointer to the idle thread.
Definition chsys.c:247
stkalign_t __c1_main_thread_stack_end__
Definition chsys.c:96
void chSysPolledDelayX(rtcnt_t cycles)
Polled delay.
Definition chsys.c:497
const os_instance_config_t ch_core0_cfg
Core 0 OS instance configuration.
Definition chsys.c:66
void chSysWaitSystemState(system_state_t state)
Waits for the system state to be equal to the specified one.
Definition chsys.c:141
stkalign_t __c1_main_thread_stack_base__
const os_instance_config_t ch_core1_cfg
Core 1 OS instance configuration.
Definition chsys.c:102
void chSysRestoreStatusX(syssts_t sts)
Restores the specified execution status and leaves a critical zone.
Definition chsys.c:447
#define CH_INTEGRITY_RLIST
Definition chsys.h:40
#define CH_INTEGRITY_PORT
Definition chsys.h:43
#define currcore
Access to current core's instance structure.
Definition chsys.h:89
stkalign_t __main_thread_stack_base__
void chSysInit(void)
System initialization.
Definition chsys.c:158
void chSysHalt(const char *reason)
Halts the system.
Definition chsys.c:208
#define THD_WORKING_AREA_END(s)
End of a working area casted to the correct type.
Definition chthreads.h:156
#define THD_WORKING_AREA_BASE(s)
Base of a working area casted to the correct type.
Definition chthreads.h:149
#define THD_WORKING_AREA(s, n)
Static working area allocation.
Definition chthreads.h:142
static void __tm_calibration_object_init(tm_calibration_t *tcp)
Time measurement initialization.
Definition chtm.h:118
void chVTDoTickI(void)
Virtual timers ticker.
Definition chvt.c:463
#define __trace_halt(reason)
Definition chtrace.h:232
ch_delta_list_t * next
Next in the delta list.
Definition chlists.h:100
ch_delta_list_t * prev
Previous in the delta list.
Definition chlists.h:101
virtual_timers_list_t vtlist
Virtual timers delta list header.
Definition chobjects.h:411
ready_list_t rlist
Ready list header.
Definition chobjects.h:407
ch_priority_queue_t * next
Next in the queue.
Definition chlists.h:85
tprio_t prio
Priority of this element.
Definition chlists.h:87
ch_priority_queue_t * prev
Previous in the queue.
Definition chlists.h:86
ch_queue_t * prev
Previous in the queue.
Definition chlists.h:70
ch_queue_t * next
Next in the list/queue.
Definition chlists.h:69
ch_priority_queue_t pqueue
Threads ordered queues header.
Definition chobjects.h:362
Type of system data structure.
Definition chobjects.h:466
tm_calibration_t tmc
Time measurement calibration data.
Definition chobjects.h:479
os_instance_t * instances[PORT_CORES_NUMBER]
Initialized OS instances or NULL.
Definition chobjects.h:474
rfcu_t rfcu
Runtime Faults Collection Unit.
Definition chobjects.h:494
system_state_t state
Operating system state.
Definition chobjects.h:470
registry_t reglist
Registry header.
Definition chobjects.h:487
union ch_thread::@065317322233202114332352372014266163076165303275 hdr
Shared list headers.
tslices_t ticks
Number of ticks remaining to this thread.
Definition chobjects.h:218
volatile systime_t time
Thread consumed time in ticks.
Definition chobjects.h:225
ch_priority_queue_t pqueue
Threads ordered queues element.
Definition chobjects.h:169
ch_delta_list_t dlist
Delta list header.
Definition chobjects.h:101