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