diff options
Diffstat (limited to 'os/rt')
83 files changed, 16249 insertions, 0 deletions
diff --git a/os/rt/include/ch.h b/os/rt/include/ch.h new file mode 100644 index 000000000..bd8fe92d3 --- /dev/null +++ b/os/rt/include/ch.h @@ -0,0 +1,99 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ch.h
+ * @brief ChibiOS/RT main include file.
+ * @details This header includes all the required kernel headers so it is the
+ * only kernel header you usually want to include in your application.
+ *
+ * @addtogroup kernel_info
+ * @details Kernel related info.
+ * @{
+ */
+
+#ifndef _CH_H_
+#define _CH_H_
+
+/**
+ * @brief ChibiOS/RT identification macro.
+ */
+#define _CHIBIOS_RT_
+
+/**
+ * @brief Kernel version string.
+ */
+#define CH_KERNEL_VERSION "3.0.0dev"
+
+/**
+ * @name Kernel version
+ * @{
+ */
+/**
+ * @brief Kernel version major number.
+ */
+#define CH_KERNEL_MAJOR 3
+
+/**
+ * @brief Kernel version minor number.
+ */
+#define CH_KERNEL_MINOR 0
+
+/**
+ * @brief Kernel version patch number.
+ */
+#define CH_KERNEL_PATCH 0
+/** @} */
+
+/* Required forward declaration, knowledge of this type is required by all
+ modules.*/
+typedef struct thread thread_t;
+
+/* Core headers.*/
+#include "chtypes.h"
+#include "chconf.h"
+#include "chcore.h"
+#include "chdebug.h"
+#include "chtm.h"
+#include "chstats.h"
+#include "chschd.h"
+#include "chsys.h"
+#include "chvt.h"
+#include "chthreads.h"
+
+/* Optional subsystems headers.*/
+#include "chregistry.h"
+#include "chsem.h"
+#include "chbsem.h"
+#include "chmtx.h"
+#include "chcond.h"
+#include "chevents.h"
+#include "chmsg.h"
+#include "chmboxes.h"
+#include "chmemcore.h"
+#include "chheap.h"
+#include "chmempools.h"
+#include "chdynamic.h"
+#include "chqueues.h"
+#include "chstreams.h"
+
+#endif /* _CH_H_ */
+
+/** @} */
diff --git a/os/rt/include/chbsem.h b/os/rt/include/chbsem.h new file mode 100644 index 000000000..6a5397e8e --- /dev/null +++ b/os/rt/include/chbsem.h @@ -0,0 +1,312 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chbsem.h
+ * @brief Binary semaphores structures and macros.
+ *
+ * @addtogroup binary_semaphores
+ * @details Binary semaphores related APIs and services.
+ *
+ * <h2>Operation mode</h2>
+ * Binary semaphores are implemented as a set of macros that use the
+ * existing counting semaphores primitives. The difference between
+ * counting and binary semaphores is that the counter of binary
+ * semaphores is not allowed to grow above the value 1. Repeated
+ * signal operation are ignored. A binary semaphore can thus have
+ * only two defined states:
+ * - <b>Taken</b>, when its counter has a value of zero or lower
+ * than zero. A negative number represent the number of threads
+ * queued on the binary semaphore.
+ * - <b>Not taken</b>, when its counter has a value of one.
+ * .
+ * Binary semaphores are different from mutexes because there is no
+ * the concept of ownership, a binary semaphore can be taken by a
+ * thread and signaled by another thread or an interrupt handler,
+ * mutexes can only be taken and released by the same thread. Another
+ * difference is that binary semaphores, unlike mutexes, do not
+ * implement the priority inheritance protocol.<br>
+ * In order to use the binary semaphores APIs the @p CH_CFG_USE_SEMAPHORES
+ * option must be enabled in @p chconf.h.
+ * @{
+ */
+
+#ifndef _CHBSEM_H_
+#define _CHBSEM_H_
+
+#if CH_CFG_USE_SEMAPHORES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @extends semaphore_t
+ *
+ * @brief Binary semaphore type.
+ */
+typedef struct {
+ semaphore_t bs_sem;
+} binary_semaphore_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static semaphore initializer.
+ * @details This macro should be used when statically initializing a semaphore
+ * that is part of a bigger structure.
+ *
+ * @param[in] name the name of the semaphore variable
+ * @param[in] taken the semaphore initial state
+ */
+#define _BSEMAPHORE_DATA(name, taken) \
+ {_SEMAPHORE_DATA(name.bs_sem, ((taken) ? 0 : 1))}
+
+/**
+ * @brief Static semaphore initializer.
+ * @details Statically initialized semaphores require no explicit
+ * initialization using @p chBSemInit().
+ *
+ * @param[in] name the name of the semaphore variable
+ * @param[in] taken the semaphore initial state
+ */
+#define BSEMAPHORE_DECL(name, taken) \
+ binary_semaphore_t name = _BSEMAPHORE_DATA(name, taken)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes a binary semaphore.
+ *
+ * @param[out] bsp pointer to a @p binary_semaphore_t structure
+ * @param[in] taken initial state of the binary semaphore:
+ * - @a false, the initial state is not taken.
+ * - @a true, the initial state is taken.
+ * .
+ *
+ * @init
+ */
+static inline void chBSemObjectInit(binary_semaphore_t *bsp, bool taken) {
+
+ chSemObjectInit(&bsp->bs_sem, taken ? 0 : 1);
+}
+
+/**
+ * @brief Wait operation on the binary semaphore.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval RDY_OK if the binary semaphore has been successfully taken.
+ * @retval RDY_RESET if the binary semaphore has been reset using
+ * @p bsemReset().
+ *
+ * @api
+ */
+static inline msg_t chBSemWait(binary_semaphore_t *bsp) {
+
+ return chSemWait(&bsp->bs_sem);
+}
+
+/**
+ * @brief Wait operation on the binary semaphore.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval RDY_OK if the binary semaphore has been successfully taken.
+ * @retval RDY_RESET if the binary semaphore has been reset using
+ * @p bsemReset().
+ *
+ * @sclass
+ */
+static inline msg_t chBSemWaitS(binary_semaphore_t *bsp) {
+
+ chDbgCheckClassS();
+
+ return chSemWaitS(&bsp->bs_sem);
+}
+
+/**
+ * @brief Wait operation on the binary semaphore.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval RDY_OK if the binary semaphore has been successfully taken.
+ * @retval RDY_RESET if the binary semaphore has been reset using
+ * @p bsemReset().
+ * @retval RDY_TIMEOUT if the binary semaphore has not been signaled or reset
+ * within the specified timeout.
+ *
+ * @sclass
+ */
+static inline msg_t chBSemWaitTimeoutS(binary_semaphore_t *bsp,
+ systime_t time) {
+
+ chDbgCheckClassS();
+
+ return chSemWaitTimeoutS(&bsp->bs_sem, time);
+}
+
+/**
+ * @brief Wait operation on the binary semaphore.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval RDY_OK if the binary semaphore has been successfully taken.
+ * @retval RDY_RESET if the binary semaphore has been reset using
+ * @p bsemReset().
+ * @retval RDY_TIMEOUT if the binary semaphore has not been signaled or reset
+ * within the specified timeout.
+ *
+ * @api
+ */
+static inline msg_t chBSemWaitTimeout(binary_semaphore_t *bsp,
+ systime_t time) {
+
+ return chSemWaitTimeout(&bsp->bs_sem, time);
+}
+
+/**
+ * @brief Reset operation on the binary semaphore.
+ * @note The released threads can recognize they were waked up by a reset
+ * rather than a signal because the @p bsemWait() will return
+ * @p RDY_RESET instead of @p RDY_OK.
+ * @note This function does not reschedule.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @param[in] taken new state of the binary semaphore
+ * - @a false, the new state is not taken.
+ * - @a true, the new state is taken.
+ * .
+ *
+ * @iclass
+ */
+static inline void chBSemResetI(binary_semaphore_t *bsp, bool taken) {
+
+ chDbgCheckClassI();
+
+ chSemResetI(&bsp->bs_sem, taken ? 0 : 1);
+}
+
+/**
+ * @brief Reset operation on the binary semaphore.
+ * @note The released threads can recognize they were waked up by a reset
+ * rather than a signal because the @p bsemWait() will return
+ * @p RDY_RESET instead of @p RDY_OK.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @param[in] taken new state of the binary semaphore
+ * - @a false, the new state is not taken.
+ * - @a true, the new state is taken.
+ * .
+ *
+ * @api
+ */
+static inline void chBSemReset(binary_semaphore_t *bsp, bool taken) {
+
+ chSemReset(&bsp->bs_sem, taken ? 0 : 1);
+}
+
+/**
+ * @brief Performs a signal operation on a binary semaphore.
+ * @note This function does not reschedule.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ *
+ * @iclass
+ */
+static inline void chBSemSignalI(binary_semaphore_t *bsp) {
+
+ chDbgCheckClassI();
+
+ if (bsp->bs_sem.s_cnt < 1)
+ chSemSignalI(&bsp->bs_sem);
+}
+
+/**
+ * @brief Performs a signal operation on a binary semaphore.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ *
+ * @api
+ */
+static inline void chBSemSignal(binary_semaphore_t *bsp) {
+
+ chSysLock();
+ chBSemSignalI(bsp);
+ chSchRescheduleS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Returns the binary semaphore current state.
+ *
+ * @param[in] bsp pointer to a @p binary_semaphore_t structure
+ * @return The binary semaphore current state.
+ * @retval false if the binary semaphore is not taken.
+ * @retval true if the binary semaphore is taken.
+ *
+ * @iclass
+ */
+static inline bool chBSemGetStateI(binary_semaphore_t *bsp) {
+
+ chDbgCheckClassI();
+
+ return bsp->bs_sem.s_cnt > 0 ? false : true;
+}
+
+#endif /* CH_CFG_USE_SEMAPHORES */
+
+#endif /* _CHBSEM_H_ */
+
+/** @} */
diff --git a/os/rt/include/chcond.h b/os/rt/include/chcond.h new file mode 100644 index 000000000..802d59d3a --- /dev/null +++ b/os/rt/include/chcond.h @@ -0,0 +1,117 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+/*
+ Concepts and parts of this file have been contributed by Leon Woestenberg.
+ */
+
+/**
+ * @file chcond.h
+ * @brief Condition Variables macros and structures.
+ *
+ * @addtogroup condvars
+ * @{
+ */
+
+#ifndef _CHCOND_H_
+#define _CHCOND_H_
+
+#if CH_CFG_USE_CONDVARS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if !CH_CFG_USE_MUTEXES
+#error "CH_CFG_USE_CONDVARS requires CH_CFG_USE_MUTEXES"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief condition_variable_t structure.
+ */
+typedef struct condition_variable {
+ threads_queue_t c_queue; /**< @brief Condition variable
+ threads queue. */
+} condition_variable_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static condition variable initializer.
+ * @details This macro should be used when statically initializing a condition
+ * variable that is part of a bigger structure.
+ *
+ * @param[in] name the name of the condition variable
+ */
+#define _CONDVAR_DATA(name) {_threads_queue_t_DATA(name.c_queue)}
+
+/**
+ * @brief Static condition variable initializer.
+ * @details Statically initialized condition variables require no explicit
+ * initialization using @p chCondInit().
+ *
+ * @param[in] name the name of the condition variable
+ */
+#define CONDVAR_DECL(name) condition_variable_t name = _CONDVAR_DATA(name)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chCondObjectInit(condition_variable_t *cp);
+ void chCondSignal(condition_variable_t *cp);
+ void chCondSignalI(condition_variable_t *cp);
+ void chCondBroadcast(condition_variable_t *cp);
+ void chCondBroadcastI(condition_variable_t *cp);
+ msg_t chCondWait(condition_variable_t *cp);
+ msg_t chCondWaitS(condition_variable_t *cp);
+#if CH_CFG_USE_CONDVARS_TIMEOUT
+ msg_t chCondWaitTimeout(condition_variable_t *cp, systime_t time);
+ msg_t chCondWaitTimeoutS(condition_variable_t *cp, systime_t time);
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* CH_CFG_USE_CONDVARS */
+
+#endif /* _CHCOND_H_ */
+
+/** @} */
diff --git a/os/rt/include/chdebug.h b/os/rt/include/chdebug.h new file mode 100644 index 000000000..44f44116f --- /dev/null +++ b/os/rt/include/chdebug.h @@ -0,0 +1,237 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chdebug.h
+ * @brief Debug macros and structures.
+ *
+ * @addtogroup debug
+ * @{
+ */
+
+#ifndef _CHDEBUG_H_
+#define _CHDEBUG_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/**
+ * @name Debug related settings
+ * @{
+ */
+/**
+ * @brief Trace buffer entries.
+ */
+#ifndef CH_DBG_TRACE_BUFFER_SIZE
+#define CH_DBG_TRACE_BUFFER_SIZE 64
+#endif
+
+/**
+ * @brief Fill value for thread stack area in debug mode.
+ */
+#ifndef CH_DBG_STACK_FILL_VALUE
+#define CH_DBG_STACK_FILL_VALUE 0x55
+#endif
+
+/**
+ * @brief Fill value for thread area in debug mode.
+ * @note The chosen default value is 0xFF in order to make evident which
+ * thread fields were not initialized when inspecting the memory with
+ * a debugger. A uninitialized field is not an error in itself but it
+ * better to know it.
+ */
+#ifndef CH_DBG_THREAD_FILL_VALUE
+#define CH_DBG_THREAD_FILL_VALUE 0xFF
+#endif
+/** @} */
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if CH_DBG_ENABLE_ASSERTS || CH_DBG_ENABLE_CHECKS || \
+ CH_DBG_ENABLE_STACK_CHECK || CH_DBG_SYSTEM_STATE_CHECK
+#define CH_DBG_ENABLED TRUE
+#else
+#define CH_DBG_ENABLED FALSE
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+#if CH_DBG_ENABLE_TRACE || defined(__DOXYGEN__)
+/**
+ * @brief Trace buffer record.
+ */
+typedef struct {
+ /**
+ * @brief Time of the switch event.
+ */
+ systime_t se_time;
+ /**
+ * @brief Switched in thread.
+ */
+ thread_t *se_tp;
+ /**
+ * @brief Object where going to sleep.
+ */
+ void *se_wtobjp;
+ /**
+ * @brief Switched out thread state.
+ */
+ uint8_t se_state;
+} ch_swc_event_t;
+
+/**
+ * @brief Trace buffer header.
+ */
+typedef struct {
+ /**
+ * @brief Trace buffer size (entries).
+ */
+ unsigned tb_size;
+ /**
+ * @brief Pointer to the buffer front.
+ */
+ ch_swc_event_t *tb_ptr;
+ /**
+ * @brief Ring buffer.
+ */
+ ch_swc_event_t tb_buffer[CH_DBG_TRACE_BUFFER_SIZE];
+} ch_trace_buffer_t;
+#endif /* CH_DBG_ENABLE_TRACE */
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+#if CH_DBG_SYSTEM_STATE_CHECK
+#define _dbg_enter_lock() (ch.dbg_lock_cnt = 1)
+#define _dbg_leave_lock() (ch.dbg_lock_cnt = 0)
+#endif
+
+/* When the state checker feature is disabled then the following functions
+ are replaced by an empty macro.*/
+#if !CH_DBG_SYSTEM_STATE_CHECK
+#define _dbg_enter_lock()
+#define _dbg_leave_lock()
+#define _dbg_check_disable()
+#define _dbg_check_suspend()
+#define _dbg_check_enable()
+#define _dbg_check_lock()
+#define _dbg_check_unlock()
+#define _dbg_check_lock_from_isr()
+#define _dbg_check_unlock_from_isr()
+#define _dbg_check_enter_isr()
+#define _dbg_check_leave_isr()
+#define chDbgCheckClassI()
+#define chDbgCheckClassS()
+#endif
+
+/* When the trace feature is disabled this function is replaced by an empty
+ macro.*/
+#if !CH_DBG_ENABLE_TRACE
+#define _dbg_trace(otp)
+#endif
+
+/**
+ * @name Macro Functions
+ * @{
+ */
+/**
+ * @brief Function parameters check.
+ * @details If the condition check fails then the kernel panics and halts.
+ * @note The condition is tested only if the @p CH_DBG_ENABLE_CHECKS switch
+ * is specified in @p chconf.h else the macro does nothing.
+ *
+ * @param[in] c the condition to be verified to be true
+ *
+ * @api
+ */
+#if !defined(chDbgCheck)
+#define chDbgCheck(c) do { \
+ if (CH_DBG_ENABLE_CHECKS && !(c)) \
+ chSysHalt(__func__); \
+} while (0)
+#endif /* !defined(chDbgCheck) */
+
+/**
+ * @brief Condition assertion.
+ * @details If the condition check fails then the kernel panics with a
+ * message and halts.
+ * @note The condition is tested only if the @p CH_DBG_ENABLE_ASSERTS switch
+ * is specified in @p chconf.h else the macro does nothing.
+ * @note The remark string is not currently used except for putting a
+ * comment in the code about the assertion.
+ *
+ * @param[in] c the condition to be verified to be true
+ * @param[in] r a remark string
+ *
+ * @api
+ */
+#if !defined(chDbgAssert)
+#define chDbgAssert(c, r) do { \
+ if (CH_DBG_ENABLE_ASSERTS && !(c)) \
+ chSysHalt(__func__); \
+} while (0)
+#endif /* !defined(chDbgAssert) */
+/** @} */
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+#if CH_DBG_SYSTEM_STATE_CHECK
+ void _dbg_check_disable(void);
+ void _dbg_check_suspend(void);
+ void _dbg_check_enable(void);
+ void _dbg_check_lock(void);
+ void _dbg_check_unlock(void);
+ void _dbg_check_lock_from_isr(void);
+ void _dbg_check_unlock_from_isr(void);
+ void _dbg_check_enter_isr(void);
+ void _dbg_check_leave_isr(void);
+ void chDbgCheckClassI(void);
+ void chDbgCheckClassS(void);
+#endif
+#if CH_DBG_ENABLE_TRACE || defined(__DOXYGEN__)
+ void _trace_init(void);
+ void _dbg_trace(thread_t *otp);
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* _CHDEBUG_H_ */
+
+/** @} */
diff --git a/os/rt/include/chdynamic.h b/os/rt/include/chdynamic.h new file mode 100644 index 000000000..cb72bb244 --- /dev/null +++ b/os/rt/include/chdynamic.h @@ -0,0 +1,96 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chdynamic.h
+ * @brief Dynamic threads macros and structures.
+ *
+ * @addtogroup dynamic_threads
+ * @{
+ */
+
+#ifndef _CHDYNAMIC_H_
+#define _CHDYNAMIC_H_
+
+#if CH_CFG_USE_DYNAMIC || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*
+ * Module dependencies check.
+ */
+#if CH_CFG_USE_DYNAMIC && !CH_CFG_USE_WAITEXIT
+#error "CH_CFG_USE_DYNAMIC requires CH_CFG_USE_WAITEXIT"
+#endif
+#if CH_CFG_USE_DYNAMIC && !CH_CFG_USE_HEAP && !CH_CFG_USE_MEMPOOLS
+#error "CH_CFG_USE_DYNAMIC requires CH_CFG_USE_HEAP and/or CH_CFG_USE_MEMPOOLS"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/*
+ * Dynamic threads APIs.
+ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+ thread_t *chThdAddRef(thread_t *tp);
+ void chThdRelease(thread_t *tp);
+#if CH_CFG_USE_HEAP
+ thread_t *chThdCreateFromHeap(memory_heap_t *heapp, size_t size,
+ tprio_t prio, tfunc_t pf, void *arg);
+#endif
+#if CH_CFG_USE_MEMPOOLS
+ thread_t *chThdCreateFromMemoryPool(memory_pool_t *mp, tprio_t prio,
+ tfunc_t pf, void *arg);
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* CH_CFG_USE_DYNAMIC */
+
+#endif /* _CHDYNAMIC_H_ */
+
+/** @} */
diff --git a/os/rt/include/chevents.h b/os/rt/include/chevents.h new file mode 100644 index 000000000..e15d0e6cb --- /dev/null +++ b/os/rt/include/chevents.h @@ -0,0 +1,240 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+/*
+ Concepts and parts of this file have been contributed by Scott (skute).
+ */
+
+/**
+ * @file chevents.h
+ * @brief Events macros and structures.
+ *
+ * @addtogroup events
+ * @{
+ */
+
+#ifndef _CHEVENTS_H_
+#define _CHEVENTS_H_
+
+#if CH_CFG_USE_EVENTS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+typedef struct event_listener event_listener_t;
+
+/**
+ * @brief Event Listener structure.
+ */
+struct event_listener {
+ event_listener_t *el_next; /**< @brief Next Event Listener
+ registered on the event
+ source. */
+ thread_t *el_listener; /**< @brief Thread interested in the
+ event source. */
+ eventmask_t el_mask; /**< @brief Event identifiers mask. */
+ eventflags_t el_flags; /**< @brief Flags added to the listener
+ by the event source.*/
+};
+
+/**
+ * @brief Event Source structure.
+ */
+typedef struct event_source {
+ event_listener_t *es_next; /**< @brief First Event Listener
+ registered on the Event
+ Source. */
+} event_source_t;
+
+/**
+ * @brief Event Handler callback function.
+ */
+typedef void (*evhandler_t)(eventid_t);
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief All events allowed mask.
+ */
+#define ALL_EVENTS ((eventmask_t)-1)
+
+/**
+ * @brief Returns an event mask from an event identifier.
+ */
+#define EVENT_MASK(eid) ((eventmask_t)(1 << (eid)))
+
+/**
+ * @brief Data part of a static event source initializer.
+ * @details This macro should be used when statically initializing an event
+ * source that is part of a bigger structure.
+ * @param name the name of the event source variable
+ */
+#define _EVENTSOURCE_DATA(name) {(void *)(&name)}
+
+/**
+ * @brief Static event source initializer.
+ * @details Statically initialized event sources require no explicit
+ * initialization using @p chEvtInit().
+ *
+ * @param name the name of the event source variable
+ */
+#define EVENTSOURCE_DECL(name) event_source_t name = _EVENTSOURCE_DATA(name)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chEvtRegisterMask(event_source_t *esp,
+ event_listener_t *elp,
+ eventmask_t mask);
+ void chEvtUnregister(event_source_t *esp, event_listener_t *elp);
+ eventmask_t chEvtGetAndClearEvents(eventmask_t mask);
+ eventmask_t chEvtAddEvents(eventmask_t mask);
+ eventflags_t chEvtGetAndClearFlags(event_listener_t *elp);
+ eventflags_t chEvtGetAndClearFlagsI(event_listener_t *elp);
+ void chEvtSignal(thread_t *tp, eventmask_t mask);
+ void chEvtSignalI(thread_t *tp, eventmask_t mask);
+ void chEvtBroadcastFlags(event_source_t *esp, eventflags_t flags);
+ void chEvtBroadcastFlagsI(event_source_t *esp, eventflags_t flags);
+ void chEvtDispatch(const evhandler_t *handlers, eventmask_t mask);
+#if CH_CFG_OPTIMIZE_SPEED || !CH_CFG_USE_EVENTS_TIMEOUT
+ eventmask_t chEvtWaitOne(eventmask_t mask);
+ eventmask_t chEvtWaitAny(eventmask_t mask);
+ eventmask_t chEvtWaitAll(eventmask_t mask);
+#endif
+#if CH_CFG_USE_EVENTS_TIMEOUT
+ eventmask_t chEvtWaitOneTimeout(eventmask_t mask, systime_t time);
+ eventmask_t chEvtWaitAnyTimeout(eventmask_t mask, systime_t time);
+ eventmask_t chEvtWaitAllTimeout(eventmask_t mask, systime_t time);
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+#if !CH_CFG_OPTIMIZE_SPEED && CH_CFG_USE_EVENTS_TIMEOUT
+#define chEvtWaitOne(mask) chEvtWaitOneTimeout(mask, TIME_INFINITE)
+#define chEvtWaitAny(mask) chEvtWaitAnyTimeout(mask, TIME_INFINITE)
+#define chEvtWaitAll(mask) chEvtWaitAllTimeout(mask, TIME_INFINITE)
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes an Event Source.
+ * @note This function can be invoked before the kernel is initialized
+ * because it just prepares a @p event_source_t structure.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ *
+ * @init
+ */
+static inline void chEvtObjectInit(event_source_t *esp) {
+
+ esp->es_next = (event_listener_t *)(void *)esp;
+}
+
+/**
+ * @brief Registers an Event Listener on an Event Source.
+ * @note Multiple Event Listeners can use the same event identifier, the
+ * listener will share the callback function.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ * @param[out] elp pointer to the @p event_listener_t structure
+ * @param[in] eid numeric identifier assigned to the Event Listener. The
+ * identifier is used as index for the event callback
+ * function.
+ * The value must range between zero and the size, in bit,
+ * of the @p eventid_t type minus one.
+ *
+ * @api
+ */
+static inline void chEvtRegister(event_source_t *esp,
+ event_listener_t *elp,
+ eventid_t eid) {
+
+ chEvtRegisterMask(esp, elp, EVENT_MASK(eid));
+}
+
+/**
+ * @brief Verifies if there is at least one @p event_listener_t registered.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ *
+ * @iclass
+ */
+static inline bool chEvtIsListeningI(event_source_t *esp) {
+
+ return (bool)((void *)esp != (void *)esp->es_next);
+}
+
+/**
+ * @brief Signals all the Event Listeners registered on the specified Event
+ * Source.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ *
+ * @api
+ */
+static inline void chEvtBroadcast(event_source_t *esp) {
+
+ chEvtBroadcastFlags(esp, 0);
+}
+
+/**
+ * @brief Signals all the Event Listeners registered on the specified Event
+ * Source.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ *
+ * @iclass
+ */
+static inline void chEvtBroadcastI(event_source_t *esp) {
+
+ chEvtBroadcastFlagsI(esp, 0);
+}
+
+#endif /* CH_CFG_USE_EVENTS */
+
+#endif /* _CHEVENTS_H_ */
+
+/** @} */
diff --git a/os/rt/include/chheap.h b/os/rt/include/chheap.h new file mode 100644 index 000000000..73e0d4148 --- /dev/null +++ b/os/rt/include/chheap.h @@ -0,0 +1,119 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chheap.h
+ * @brief Heaps macros and structures.
+ *
+ * @addtogroup heaps
+ * @{
+ */
+
+#ifndef _CHHEAP_H_
+#define _CHHEAP_H_
+
+#if CH_CFG_USE_HEAP || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if !CH_CFG_USE_MEMCORE
+#error "CH_CFG_USE_HEAP requires CH_CFG_USE_MEMCORE"
+#endif
+
+#if !CH_CFG_USE_MUTEXES && !CH_CFG_USE_SEMAPHORES
+#error "CH_CFG_USE_HEAP requires CH_CFG_USE_MUTEXES and/or CH_CFG_USE_SEMAPHORES"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Type of a memory heap.
+ */
+typedef struct memory_heap memory_heap_t;
+
+/**
+ * @brief Memory heap block header.
+ */
+union heap_header {
+ stkalign_t align;
+ struct {
+ union {
+ union heap_header *next; /**< @brief Next block in free list. */
+ memory_heap_t *heap; /**< @brief Block owner heap. */
+ } u; /**< @brief Overlapped fields. */
+ size_t size; /**< @brief Size of the memory block. */
+ } h;
+};
+
+/**
+ * @brief Structure describing a memory heap.
+ */
+struct memory_heap {
+ memgetfunc_t h_provider; /**< @brief Memory blocks provider for
+ this heap. */
+ union heap_header h_free; /**< @brief Free blocks list header. */
+#if CH_CFG_USE_MUTEXES
+ mutex_t h_mtx; /**< @brief Heap access mutex. */
+#else
+ semaphore_t h_sem; /**< @brief Heap access semaphore. */
+#endif
+};
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _heap_init(void);
+ void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size);
+ void *chHeapAlloc(memory_heap_t *heapp, size_t size);
+ void chHeapFree(void *p);
+ size_t chHeapStatus(memory_heap_t *heapp, size_t *sizep);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* CH_CFG_USE_HEAP */
+
+#endif /* _CHHEAP_H_ */
+
+/** @} */
diff --git a/os/rt/include/chmboxes.h b/os/rt/include/chmboxes.h new file mode 100644 index 000000000..8d1dedfd1 --- /dev/null +++ b/os/rt/include/chmboxes.h @@ -0,0 +1,200 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmboxes.h
+ * @brief Mailboxes macros and structures.
+ *
+ * @addtogroup mailboxes
+ * @{
+ */
+
+#ifndef _CHMBOXES_H_
+#define _CHMBOXES_H_
+
+#if CH_CFG_USE_MAILBOXES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if !CH_CFG_USE_SEMAPHORES
+#error "CH_CFG_USE_MAILBOXES requires CH_CFG_USE_SEMAPHORES"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Structure representing a mailbox object.
+ */
+typedef struct {
+ msg_t *mb_buffer; /**< @brief Pointer to the mailbox
+ buffer. */
+ msg_t *mb_top; /**< @brief Pointer to the location
+ after the buffer. */
+ msg_t *mb_wrptr; /**< @brief Write pointer. */
+ msg_t *mb_rdptr; /**< @brief Read pointer. */
+ semaphore_t mb_fullsem; /**< @brief Full counter
+ @p semaphore_t. */
+ semaphore_t mb_emptysem; /**< @brief Empty counter
+ @p semaphore_t. */
+} mailbox_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static mailbox initializer.
+ * @details This macro should be used when statically initializing a
+ * mailbox that is part of a bigger structure.
+ *
+ * @param[in] name the name of the mailbox variable
+ * @param[in] buffer pointer to the mailbox buffer area
+ * @param[in] size size of the mailbox buffer area
+ */
+#define _MAILBOX_DATA(name, buffer, size) { \
+ (msg_t *)(buffer), \
+ (msg_t *)(buffer) + size, \
+ (msg_t *)(buffer), \
+ (msg_t *)(buffer), \
+ _SEMAPHORE_DATA(name.mb_fullsem, 0), \
+ _SEMAPHORE_DATA(name.mb_emptysem, size), \
+}
+
+/**
+ * @brief Static mailbox initializer.
+ * @details Statically initialized mailboxes require no explicit
+ * initialization using @p chMBInit().
+ *
+ * @param[in] name the name of the mailbox variable
+ * @param[in] buffer pointer to the mailbox buffer area
+ * @param[in] size size of the mailbox buffer area
+ */
+#define MAILBOX_DECL(name, buffer, size) \
+ mailbox_t name = _MAILBOX_DATA(name, buffer, size)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chMBObjectInit(mailbox_t *mbp, msg_t *buf, cnt_t n);
+ void chMBReset(mailbox_t *mbp);
+ msg_t chMBPost(mailbox_t *mbp, msg_t msg, systime_t timeout);
+ msg_t chMBPostS(mailbox_t *mbp, msg_t msg, systime_t timeout);
+ msg_t chMBPostI(mailbox_t *mbp, msg_t msg);
+ msg_t chMBPostAhead(mailbox_t *mbp, msg_t msg, systime_t timeout);
+ msg_t chMBPostAheadS(mailbox_t *mbp, msg_t msg, systime_t timeout);
+ msg_t chMBPostAheadI(mailbox_t *mbp, msg_t msg);
+ msg_t chMBFetch(mailbox_t *mbp, msg_t *msgp, systime_t timeout);
+ msg_t chMBFetchS(mailbox_t *mbp, msg_t *msgp, systime_t timeout);
+ msg_t chMBFetchI(mailbox_t *mbp, msg_t *msgp);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Returns the mailbox buffer size.
+ *
+ * @param[in] mbp the pointer to an initialized mailbox_t object
+ *
+ * @iclass
+ */
+static inline size_t chMBSizeI(mailbox_t *mbp) {
+
+ return (size_t)(mbp->mb_top - mbp->mb_buffer);
+}
+
+/**
+ * @brief Returns the number of free message slots into a mailbox.
+ * @note Can be invoked in any system state but if invoked out of a locked
+ * state then the returned value may change after reading.
+ * @note The returned value can be less than zero when there are waiting
+ * threads on the internal semaphore.
+ *
+ * @param[in] mbp the pointer to an initialized mailbox_t object
+ * @return The number of empty message slots.
+ *
+ * @iclass
+ */
+static inline cnt_t chMBGetFreeCountI(mailbox_t *mbp) {
+
+ chDbgCheckClassI();
+
+ return chSemGetCounterI(&mbp->mb_emptysem);
+}
+
+/**
+ * @brief Returns the number of used message slots into a mailbox.
+ * @note Can be invoked in any system state but if invoked out of a locked
+ * state then the returned value may change after reading.
+ * @note The returned value can be less than zero when there are waiting
+ * threads on the internal semaphore.
+ *
+ * @param[in] mbp the pointer to an initialized mailbox_t object
+ * @return The number of queued messages.
+ *
+ * @iclass
+ */
+static inline cnt_t chMBGetUsedCountI(mailbox_t *mbp) {
+
+ chDbgCheckClassI();
+
+ return chSemGetCounterI(&mbp->mb_fullsem);
+}
+
+/**
+ * @brief Returns the next message in the queue without removing it.
+ * @pre A message must be waiting in the queue for this function to work
+ * or it would return garbage. The correct way to use this macro is
+ * to use @p chMBGetFullCountI() and then use this macro, all within
+ * a lock state.
+ *
+ * @iclass
+ */
+static inline cnt_t chMBPeekI(mailbox_t *mbp) {
+
+ chDbgCheckClassI();
+
+ return *mbp->mb_rdptr;
+}
+
+#endif /* CH_CFG_USE_MAILBOXES */
+
+#endif /* _CHMBOXES_H_ */
+
+/** @} */
diff --git a/os/rt/include/chmemcore.h b/os/rt/include/chmemcore.h new file mode 100644 index 000000000..314e94365 --- /dev/null +++ b/os/rt/include/chmemcore.h @@ -0,0 +1,114 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmemcore.h
+ * @brief Core memory manager macros and structures.
+ *
+ * @addtogroup memcore
+ * @{
+ */
+
+#ifndef _CHMEMCORE_H_
+#define _CHMEMCORE_H_
+
+#if CH_CFG_USE_MEMCORE || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Memory get function.
+ * @note This type must be assignment compatible with the @p chMemAlloc()
+ * function.
+ */
+typedef void *(*memgetfunc_t)(size_t size);
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @name Alignment support macros
+ */
+/**
+ * @brief Alignment size constant.
+ */
+#define MEM_ALIGN_SIZE sizeof(stkalign_t)
+
+/**
+ * @brief Alignment mask constant.
+ */
+#define MEM_ALIGN_MASK (MEM_ALIGN_SIZE - 1)
+
+/**
+ * @brief Alignment helper macro.
+ */
+#define MEM_ALIGN_PREV(p) ((size_t)(p) & ~MEM_ALIGN_MASK)
+
+/**
+ * @brief Alignment helper macro.
+ */
+#define MEM_ALIGN_NEXT(p) MEM_ALIGN_PREV((size_t)(p) + MEM_ALIGN_MASK)
+
+/**
+ * @brief Returns whatever a pointer or memory size is aligned to
+ * the type @p align_t.
+ */
+#define MEM_IS_ALIGNED(p) (((size_t)(p) & MEM_ALIGN_MASK) == 0)
+/** @} */
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _core_init(void);
+ void *chCoreAlloc(size_t size);
+ void *chCoreAllocI(size_t size);
+ size_t chCoreStatus(void);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* CH_CFG_USE_MEMCORE */
+
+#endif /* _CHMEMCORE_H_ */
+
+/** @} */
diff --git a/os/rt/include/chmempools.h b/os/rt/include/chmempools.h new file mode 100644 index 000000000..85b94fc73 --- /dev/null +++ b/os/rt/include/chmempools.h @@ -0,0 +1,169 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmempools.h
+ * @brief Memory Pools macros and structures.
+ *
+ * @addtogroup pools
+ * @{
+ */
+
+#ifndef _CHMEMPOOLS_H_
+#define _CHMEMPOOLS_H_
+
+#if CH_CFG_USE_MEMPOOLS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+#if !CH_CFG_USE_MEMCORE
+#error "CH_CFG_USE_MEMPOOLS requires CH_CFG_USE_MEMCORE"
+#endif
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Memory pool free object header.
+ */
+struct pool_header {
+ struct pool_header *ph_next; /**< @brief Pointer to the next pool
+ header in the list. */
+};
+
+/**
+ * @brief Memory pool descriptor.
+ */
+typedef struct {
+ struct pool_header *mp_next; /**< @brief Pointer to the header. */
+ size_t mp_object_size; /**< @brief Memory pool objects
+ size. */
+ memgetfunc_t mp_provider; /**< @brief Memory blocks provider
+ for this pool. */
+} memory_pool_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static memory pool initializer.
+ * @details This macro should be used when statically initializing a
+ * memory pool that is part of a bigger structure.
+ *
+ * @param[in] name the name of the memory pool variable
+ * @param[in] size size of the memory pool contained objects
+ * @param[in] provider memory provider function for the memory pool
+ */
+#define _MEMORYPOOL_DATA(name, size, provider) \
+ {NULL, size, provider}
+
+/**
+ * @brief Static memory pool initializer in hungry mode.
+ * @details Statically initialized memory pools require no explicit
+ * initialization using @p chPoolInit().
+ *
+ * @param[in] name the name of the memory pool variable
+ * @param[in] size size of the memory pool contained objects
+ * @param[in] provider memory provider function for the memory pool or @p NULL
+ * if the pool is not allowed to grow automatically
+ */
+#define MEMORYPOOL_DECL(name, size, provider) \
+ memory_pool_t name = _MEMORYPOOL_DATA(name, size, provider)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chPoolObjectInit(memory_pool_t *mp, size_t size, memgetfunc_t provider);
+ void chPoolLoadArray(memory_pool_t *mp, void *p, size_t n);
+ void *chPoolAllocI(memory_pool_t *mp);
+ void *chPoolAlloc(memory_pool_t *mp);
+ void chPoolFreeI(memory_pool_t *mp, void *objp);
+ void chPoolFree(memory_pool_t *mp, void *objp);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Adds an object to a memory pool.
+ * @pre The memory pool must be already been initialized.
+ * @pre The added object must be of the right size for the specified
+ * memory pool.
+ * @pre The added object must be memory aligned to the size of
+ * @p stkalign_t type.
+ * @note This function is just an alias for @p chPoolFree() and has been
+ * added for clarity.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @param[in] objp the pointer to the object to be added
+ *
+ * @api
+ */
+static inline void chPoolAdd(memory_pool_t *mp, void *objp) {
+
+ chPoolFree(mp, objp);
+}
+
+/**
+ * @brief Adds an object to a memory pool.
+ * @pre The memory pool must be already been initialized.
+ * @pre The added object must be of the right size for the specified
+ * memory pool.
+ * @pre The added object must be memory aligned to the size of
+ * @p stkalign_t type.
+ * @note This function is just an alias for @p chPoolFree() and has been
+ * added for clarity.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @param[in] objp the pointer to the object to be added
+ *
+ * @iclass
+ */
+static inline void chPoolAddI(memory_pool_t *mp, void *objp) {
+
+ chDbgCheckClassI();
+
+ chPoolFreeI(mp, objp);
+}
+
+#endif /* CH_CFG_USE_MEMPOOLS */
+
+#endif /* _CHMEMPOOLS_H_ */
+
+/** @} */
diff --git a/os/rt/include/chmsg.h b/os/rt/include/chmsg.h new file mode 100644 index 000000000..ff07edfb3 --- /dev/null +++ b/os/rt/include/chmsg.h @@ -0,0 +1,120 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmsg.h
+ * @brief Messages macros and structures.
+ *
+ * @addtogroup messages
+ * @{
+ */
+
+#ifndef _CHMSG_H_
+#define _CHMSG_H_
+
+#if CH_CFG_USE_MESSAGES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ msg_t chMsgSend(thread_t *tp, msg_t msg);
+ thread_t * chMsgWait(void);
+ void chMsgRelease(thread_t *tp, msg_t msg);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/**
+ * @brief Evaluates to @p true if the thread has pending messages.
+ *
+ * @iclass
+ */
+static inline bool chMsgIsPendingI(thread_t *tp) {
+
+ chDbgCheckClassI();
+
+ return (bool)(tp->p_msgqueue.p_next != (thread_t *)&tp->p_msgqueue);
+}
+
+/**
+ * @brief Returns the message carried by the specified thread.
+ * @pre This function must be invoked immediately after exiting a call
+ * to @p chMsgWait().
+ *
+ * @param[in] tp pointer to the thread
+ * @return The message carried by the sender.
+ *
+ * @api
+ */
+static inline msg_t chMsgGet(thread_t *tp) {
+
+ return tp->p_msg;
+}
+
+/**
+ * @brief Releases the thread waiting on top of the messages queue.
+ * @pre Invoke this function only after a message has been received
+ * using @p chMsgWait().
+ *
+ * @param[in] tp pointer to the thread
+ * @param[in] msg message to be returned to the sender
+ *
+ * @sclass
+ */
+static inline void chMsgReleaseS(thread_t *tp, msg_t msg) {
+
+ chDbgCheckClassS();
+
+ chSchWakeupS(tp, msg);
+}
+
+#endif /* CH_CFG_USE_MESSAGES */
+
+#endif /* _CHMSG_H_ */
+
+/** @} */
diff --git a/os/rt/include/chmtx.h b/os/rt/include/chmtx.h new file mode 100644 index 000000000..9a7f2163d --- /dev/null +++ b/os/rt/include/chmtx.h @@ -0,0 +1,151 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmtx.h
+ * @brief Mutexes macros and structures.
+ *
+ * @addtogroup mutexes
+ * @{
+ */
+
+#ifndef _CHMTX_H_
+#define _CHMTX_H_
+
+#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Type of a mutex structure.
+ */
+typedef struct mutex mutex_t;
+
+/**
+ * @brief Mutex structure.
+ */
+struct mutex {
+ threads_queue_t m_queue; /**< @brief Queue of the threads sleeping
+ on this mutex. */
+ thread_t *m_owner; /**< @brief Owner @p thread_t pointer or
+ @p NULL. */
+ mutex_t *m_next; /**< @brief Next @p mutex_t into an
+ owner-list or @p NULL. */
+#if CH_CFG_USE_MUTEXES_RECURSIVE || defined(__DOXYGEN__)
+ cnt_t m_cnt; /**< @brief Mutex recursion counter. */
+#endif
+};
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static mutex initializer.
+ * @details This macro should be used when statically initializing a mutex
+ * that is part of a bigger structure.
+ *
+ * @param[in] name the name of the mutex variable
+ */
+#if CH_CFG_USE_MUTEXES_RECURSIVE || defined(__DOXYGEN__)
+#define _MUTEX_DATA(name) {_threads_queue_t_DATA(name.m_queue), NULL, NULL, 0}
+#else
+#define _MUTEX_DATA(name) {_threads_queue_t_DATA(name.m_queue), NULL, NULL}
+#endif
+
+/**
+ * @brief Static mutex initializer.
+ * @details Statically initialized mutexes require no explicit initialization
+ * using @p chMtxInit().
+ *
+ * @param[in] name the name of the mutex variable
+ */
+#define MUTEX_DECL(name) mutex_t name = _MUTEX_DATA(name)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chMtxObjectInit(mutex_t *mp);
+ void chMtxLock(mutex_t *mp);
+ void chMtxLockS(mutex_t *mp);
+ bool chMtxTryLock(mutex_t *mp);
+ bool chMtxTryLockS(mutex_t *mp);
+ void chMtxUnlock(mutex_t *mp);
+ void chMtxUnlockS(mutex_t *mp);
+ void chMtxUnlockAll(void);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Returns @p true if the mutex queue contains at least a waiting
+ * thread.
+ *
+ * @deprecated
+ * @sclass
+ */
+static inline bool chMtxQueueNotEmptyS(mutex_t *mp) {
+
+ chDbgCheckClassS();
+
+ return queue_notempty(&mp->m_queue);
+}
+
+/**
+ * @brief Returns the next mutex in the mutexes stack of the current thread.
+ *
+ * @return A pointer to the next mutex in the stack.
+ * @retval NULL if the stack is empty.
+ *
+ * @sclass
+ */
+static inline mutex_t *chMtxGetNextMutexS(void) {
+
+ return chThdGetSelfX()->p_mtxlist;
+}
+
+#endif /* CH_CFG_USE_MUTEXES */
+
+#endif /* _CHMTX_H_ */
+
+/** @} */
diff --git a/os/rt/include/chqueues.h b/os/rt/include/chqueues.h new file mode 100644 index 000000000..1cf778d3f --- /dev/null +++ b/os/rt/include/chqueues.h @@ -0,0 +1,431 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chqueues.h
+ * @brief I/O Queues macros and structures.
+ *
+ * @addtogroup io_queues
+ * @{
+ */
+
+#ifndef _CHQUEUES_H_
+#define _CHQUEUES_H_
+
+#if CH_CFG_USE_QUEUES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Queue functions returned status value
+ * @{
+ */
+#define Q_OK MSG_OK /**< @brief Operation successful. */
+#define Q_TIMEOUT MSG_TIMEOUT /**< @brief Timeout condition. */
+#define Q_RESET MSG_RESET /**< @brief Queue has been reset. */
+#define Q_EMPTY -3 /**< @brief Queue empty. */
+#define Q_FULL -4 /**< @brief Queue full, */
+/** @} */
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Type of a generic I/O queue structure.
+ */
+typedef struct io_queue io_queue_t;
+
+/** @brief Queue notification callback type.*/
+typedef void (*qnotify_t)(io_queue_t *qp);
+
+/**
+ * @brief Generic I/O queue structure.
+ * @details This structure represents a generic Input or Output asymmetrical
+ * queue. The queue is asymmetrical because one end is meant to be
+ * accessed from a thread context, and thus can be blocking, the other
+ * end is accessible from interrupt handlers or from within a kernel
+ * lock zone (see <b>I-Locked</b> and <b>S-Locked</b> states in
+ * @ref system_states) and is non-blocking.
+ */
+struct io_queue {
+ threads_queue_t q_waiting; /**< @brief Queue of waiting threads. */
+ size_t q_counter; /**< @brief Resources counter. */
+ uint8_t *q_buffer; /**< @brief Pointer to the queue buffer.*/
+ uint8_t *q_top; /**< @brief Pointer to the first location
+ after the buffer. */
+ uint8_t *q_wrptr; /**< @brief Write pointer. */
+ uint8_t *q_rdptr; /**< @brief Read pointer. */
+ qnotify_t q_notify; /**< @brief Data notification callback. */
+ void *q_link; /**< @brief Application defined field. */
+};
+
+/**
+ * @extends io_queue_t
+ *
+ * @brief Type of an input queue structure.
+ * @details This structure represents a generic asymmetrical input queue.
+ * Writing to the queue is non-blocking and can be performed from
+ * interrupt handlers or from within a kernel lock zone (see
+ * <b>I-Locked</b> and <b>S-Locked</b> states in @ref system_states).
+ * Reading the queue can be a blocking operation and is supposed to
+ * be performed by a system thread.
+ */
+typedef io_queue_t input_queue_t;
+
+/**
+ * @extends io_queue_t
+ *
+ * @brief Type of an output queue structure.
+ * @details This structure represents a generic asymmetrical output queue.
+ * Reading from the queue is non-blocking and can be performed from
+ * interrupt handlers or from within a kernel lock zone (see
+ * <b>I-Locked</b> and <b>S-Locked</b> states in @ref system_states).
+ * Writing the queue can be a blocking operation and is supposed to
+ * be performed by a system thread.
+ */
+typedef io_queue_t output_queue_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static input queue initializer.
+ * @details This macro should be used when statically initializing an
+ * input queue that is part of a bigger structure.
+ *
+ * @param[in] name the name of the input queue variable
+ * @param[in] buffer pointer to the queue buffer area
+ * @param[in] size size of the queue buffer area
+ * @param[in] inotify input notification callback pointer
+ * @param[in] link application defined pointer
+ */
+#define _INPUTQUEUE_DATA(name, buffer, size, inotify, link) { \
+ _threads_queue_t_DATA(name), \
+ 0, \
+ (uint8_t *)(buffer), \
+ (uint8_t *)(buffer) + (size), \
+ (uint8_t *)(buffer), \
+ (uint8_t *)(buffer), \
+ (inotify), \
+ (link) \
+}
+
+/**
+ * @brief Static input queue initializer.
+ * @details Statically initialized input queues require no explicit
+ * initialization using @p chIQInit().
+ *
+ * @param[in] name the name of the input queue variable
+ * @param[in] buffer pointer to the queue buffer area
+ * @param[in] size size of the queue buffer area
+ * @param[in] inotify input notification callback pointer
+ * @param[in] link application defined pointer
+ */
+#define INPUTQUEUE_DECL(name, buffer, size, inotify, link) \
+ input_queue_t name = _INPUTQUEUE_DATA(name, buffer, size, inotify, link)
+
+/**
+ * @brief Data part of a static output queue initializer.
+ * @details This macro should be used when statically initializing an
+ * output queue that is part of a bigger structure.
+ *
+ * @param[in] name the name of the output queue variable
+ * @param[in] buffer pointer to the queue buffer area
+ * @param[in] size size of the queue buffer area
+ * @param[in] onotify output notification callback pointer
+ * @param[in] link application defined pointer
+ */
+#define _OUTPUTQUEUE_DATA(name, buffer, size, onotify, link) { \
+ _threads_queue_t_DATA(name), \
+ (size), \
+ (uint8_t *)(buffer), \
+ (uint8_t *)(buffer) + (size), \
+ (uint8_t *)(buffer), \
+ (uint8_t *)(buffer), \
+ (onotify), \
+ (link) \
+}
+
+/**
+ * @brief Static output queue initializer.
+ * @details Statically initialized output queues require no explicit
+ * initialization using @p chOQInit().
+ *
+ * @param[in] name the name of the output queue variable
+ * @param[in] buffer pointer to the queue buffer area
+ * @param[in] size size of the queue buffer area
+ * @param[in] onotify output notification callback pointer
+ * @param[in] link application defined pointer
+ */
+#define OUTPUTQUEUE_DECL(name, buffer, size, onotify, link) \
+ output_queue_t name = _OUTPUTQUEUE_DATA(name, buffer, size, onotify, link)
+
+/**
+ * @name Macro Functions
+ * @{
+ */
+/**
+ * @brief Returns the queue's buffer size.
+ *
+ * @param[in] qp pointer to a @p io_queue_t structure.
+ * @return The buffer size.
+ *
+ * @iclass
+ */
+#define chQSizeI(qp) ((size_t)((qp)->q_top - (qp)->q_buffer))
+
+/**
+ * @brief Queue space.
+ * @details Returns the used space if used on an input queue or the empty
+ * space if used on an output queue.
+ *
+ * @param[in] qp pointer to a @p io_queue_t structure.
+ * @return The buffer space.
+ *
+ * @iclass
+ */
+#define chQSpaceI(qp) ((qp)->q_counter)
+
+/**
+ * @brief Returns the queue application-defined link.
+ *
+ * @param[in] qp pointer to a @p io_queue_t structure.
+ * @return The application-defined link.
+ *
+ * @xclass
+ */
+#define chQGetLinkX(qp) ((qp)->q_link)
+/** @} */
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chIQObjectInit(input_queue_t *iqp, uint8_t *bp, size_t size,
+ qnotify_t infy, void *link);
+ void chIQResetI(input_queue_t *iqp);
+ msg_t chIQPutI(input_queue_t *iqp, uint8_t b);
+ msg_t chIQGetTimeout(input_queue_t *iqp, systime_t time);
+ size_t chIQReadTimeout(input_queue_t *iqp, uint8_t *bp,
+ size_t n, systime_t time);
+
+ void chOQObjectInit(output_queue_t *oqp, uint8_t *bp, size_t size,
+ qnotify_t onfy, void *link);
+ void chOQResetI(output_queue_t *oqp);
+ msg_t chOQPutTimeout(output_queue_t *oqp, uint8_t b, systime_t time);
+ msg_t chOQGetI(output_queue_t *oqp);
+ size_t chOQWriteTimeout(output_queue_t *oqp, const uint8_t *bp,
+ size_t n, systime_t time);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Returns the filled space into an input queue.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ * @return The number of full bytes in the queue.
+ * @retval 0 if the queue is empty.
+ *
+ * @iclass
+ */
+static inline size_t chIQGetFullI(input_queue_t *iqp) {
+
+ chDbgCheckClassI();
+
+ return (size_t)chQSpaceI(iqp);
+}
+
+/**
+ * @brief Returns the empty space into an input queue.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ * @return The number of empty bytes in the queue.
+ * @retval 0 if the queue is full.
+ *
+ * @iclass
+ */
+static inline size_t chIQGetEmptyI(input_queue_t *iqp) {
+
+ chDbgCheckClassI();
+
+ return (size_t)(chQSizeI(iqp) - chQSpaceI(iqp));
+}
+
+/**
+ * @brief Evaluates to @p true if the specified input queue is empty.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure.
+ * @return The queue status.
+ * @retval false if the queue is not empty.
+ * @retval true if the queue is empty.
+ *
+ * @iclass
+ */
+static inline bool chIQIsEmptyI(input_queue_t *iqp) {
+
+ chDbgCheckClassI();
+
+ return (bool)(chQSpaceI(iqp) <= 0);
+}
+
+/**
+ * @brief Evaluates to @p true if the specified input queue is full.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure.
+ * @return The queue status.
+ * @retval false if the queue is not full.
+ * @retval true if the queue is full.
+ *
+ * @iclass
+ */
+static inline bool chIQIsFullI(input_queue_t *iqp) {
+
+ chDbgCheckClassI();
+
+ return (bool)((iqp->q_wrptr == iqp->q_rdptr) && (iqp->q_counter != 0));
+}
+
+/**
+ * @brief Input queue read.
+ * @details This function reads a byte value from an input queue. If the queue
+ * is empty then the calling thread is suspended until a byte arrives
+ * in the queue.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ * @return A byte value from the queue.
+ * @retval Q_RESET if the queue has been reset.
+ *
+ * @api
+ */
+static inline msg_t chIQGet(input_queue_t *iqp) {
+
+ return chIQGetTimeout(iqp, TIME_INFINITE);
+}
+
+/**
+ * @brief Returns the filled space into an output queue.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ * @return The number of full bytes in the queue.
+ * @retval 0 if the queue is empty.
+ *
+ * @iclass
+ */
+static inline size_t chOQGetFullI(output_queue_t *oqp) {
+
+ chDbgCheckClassI();
+
+ return (size_t)(chQSizeI(oqp) - chQSpaceI(oqp));
+}
+
+/**
+ * @brief Returns the empty space into an output queue.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ * @return The number of empty bytes in the queue.
+ * @retval 0 if the queue is full.
+ *
+ * @iclass
+ */
+static inline size_t chOQGetEmptyI(output_queue_t *oqp) {
+
+ chDbgCheckClassI();
+
+ return (size_t)chQSpaceI(oqp);
+}
+
+/**
+ * @brief Evaluates to @p true if the specified output queue is empty.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure.
+ * @return The queue status.
+ * @retval false if the queue is not empty.
+ * @retval true if the queue is empty.
+ *
+ * @iclass
+ */
+static inline bool chOQIsEmptyI(output_queue_t *oqp) {
+
+ chDbgCheckClassI();
+
+ return (bool)((oqp->q_wrptr == oqp->q_rdptr) && (oqp->q_counter != 0));
+}
+
+/**
+ * @brief Evaluates to @p true if the specified output queue is full.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure.
+ * @return The queue status.
+ * @retval false if the queue is not full.
+ * @retval true if the queue is full.
+ *
+ * @iclass
+ */
+static inline bool chOQIsFullI(output_queue_t *oqp) {
+
+ chDbgCheckClassI();
+
+ return (bool)(chQSpaceI(oqp) <= 0);
+}
+
+/**
+ * @brief Output queue write.
+ * @details This function writes a byte value to an output queue. If the queue
+ * is full then the calling thread is suspended until there is space
+ * in the queue.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ * @param[in] b the byte value to be written in the queue
+ * @return The operation status.
+ * @retval Q_OK if the operation succeeded.
+ * @retval Q_RESET if the queue has been reset.
+ *
+ * @api
+ */
+static inline msg_t chOQPut(output_queue_t *oqp, uint8_t b) {
+
+ return chOQPutTimeout(oqp, b, TIME_INFINITE);
+}
+
+#endif /* CH_CFG_USE_QUEUES */
+
+#endif /* _CHQUEUES_H_ */
+
+/** @} */
diff --git a/os/rt/include/chregistry.h b/os/rt/include/chregistry.h new file mode 100644 index 000000000..e4cbb0d68 --- /dev/null +++ b/os/rt/include/chregistry.h @@ -0,0 +1,167 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chregistry.h
+ * @brief Threads registry macros and structures.
+ *
+ * @addtogroup registry
+ * @{
+ */
+
+#ifndef _CHREGISTRY_H_
+#define _CHREGISTRY_H_
+
+#if CH_CFG_USE_REGISTRY || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief ChibiOS/RT memory signature record.
+ */
+typedef struct {
+ char ch_identifier[4]; /**< @brief Always set to "main". */
+ uint8_t ch_zero; /**< @brief Must be zero. */
+ uint8_t ch_size; /**< @brief Size of this structure. */
+ uint16_t ch_version; /**< @brief Encoded ChibiOS/RT version. */
+ uint8_t ch_ptrsize; /**< @brief Size of a pointer. */
+ uint8_t ch_timesize; /**< @brief Size of a @p systime_t. */
+ uint8_t ch_threadsize; /**< @brief Size of a @p thread_t. */
+ uint8_t cf_off_prio; /**< @brief Offset of @p p_prio field. */
+ uint8_t cf_off_ctx; /**< @brief Offset of @p p_ctx field. */
+ uint8_t cf_off_newer; /**< @brief Offset of @p p_newer field. */
+ uint8_t cf_off_older; /**< @brief Offset of @p p_older field. */
+ uint8_t cf_off_name; /**< @brief Offset of @p p_name field. */
+ uint8_t cf_off_stklimit; /**< @brief Offset of @p p_stklimit
+ field. */
+ uint8_t cf_off_state; /**< @brief Offset of @p p_state field. */
+ uint8_t cf_off_flags; /**< @brief Offset of @p p_flags field. */
+ uint8_t cf_off_refs; /**< @brief Offset of @p p_refs field. */
+ uint8_t cf_off_preempt; /**< @brief Offset of @p p_preempt
+ field. */
+ uint8_t cf_off_time; /**< @brief Offset of @p p_time field. */
+} chdebug_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Removes a thread from the registry list.
+ * @note This macro is not meant for use in application code.
+ *
+ * @param[in] tp thread to remove from the registry
+ */
+#define REG_REMOVE(tp) { \
+ (tp)->p_older->p_newer = (tp)->p_newer; \
+ (tp)->p_newer->p_older = (tp)->p_older; \
+}
+
+/**
+ * @brief Adds a thread to the registry list.
+ * @note This macro is not meant for use in application code.
+ *
+ * @param[in] tp thread to add to the registry
+ */
+#define REG_INSERT(tp) { \
+ (tp)->p_newer = (thread_t *)&ch.rlist; \
+ (tp)->p_older = ch.rlist.r_older; \
+ (tp)->p_older->p_newer = ch.rlist.r_older = (tp); \
+}
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ extern ROMCONST chdebug_t ch_debug;
+ thread_t *chRegFirstThread(void);
+ thread_t *chRegNextThread(thread_t *tp);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Sets the current thread name.
+ * @pre This function only stores the pointer to the name if the option
+ * @p CH_CFG_USE_REGISTRY is enabled else no action is performed.
+ *
+ * @param[in] p thread name as a zero terminated string
+ *
+ * @api
+ */
+static inline void chRegSetThreadName(const char *name) {
+
+#if CH_CFG_USE_REGISTRY
+ currp->p_name = name;
+#else
+ (void)name;
+#endif
+}
+
+/**
+ * @brief Returns the name of the specified thread.
+ * @pre This function only returns the pointer to the name if the option
+ * @p CH_CFG_USE_REGISTRY is enabled else @p NULL is returned.
+ *
+ * @param[in] tp pointer to the thread
+ *
+ * @return Thread name as a zero terminated string.
+ * @retval NULL if the thread name has not been set.
+ *
+ * @iclass
+ */
+static inline const char *chRegGetThreadNameI(thread_t *tp) {
+
+ chDbgCheckClassI();
+
+#if CH_CFG_USE_REGISTRY
+ return tp->p_name;
+#else
+ (void)tp;
+ return NULL;
+#endif
+}
+
+#endif /* CH_CFG_USE_REGISTRY */
+
+#endif /* _CHREGISTRY_H_ */
+
+/** @} */
diff --git a/os/rt/include/chschd.h b/os/rt/include/chschd.h new file mode 100644 index 000000000..a89c49161 --- /dev/null +++ b/os/rt/include/chschd.h @@ -0,0 +1,607 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chschd.h
+ * @brief Scheduler macros and structures.
+ *
+ * @addtogroup scheduler
+ * @{
+ */
+
+#ifndef _CHSCHD_H_
+#define _CHSCHD_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Wakeup status codes
+ * @{
+ */
+#define MSG_OK 0 /**< @brief Normal wakeup message. */
+#define MSG_TIMEOUT -1 /**< @brief Wakeup caused by a timeout
+ condition. */
+#define MSG_RESET -2 /**< @brief Wakeup caused by a reset
+ condition. */
+/** @} */
+
+/**
+ * @name Priority constants
+ * @{
+ */
+#define NOPRIO 0 /**< @brief Ready list header priority. */
+#define IDLEPRIO 1 /**< @brief Idle thread priority. */
+#define LOWPRIO 2 /**< @brief Lowest user priority. */
+#define NORMALPRIO 64 /**< @brief Normal user priority. */
+#define HIGHPRIO 127 /**< @brief Highest user priority. */
+#define ABSPRIO 255 /**< @brief Greatest possible priority. */
+/** @} */
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @extends threads_queue_t
+ *
+ * @brief Type of a thread structure.
+ */
+typedef struct thread thread_t;
+
+/**
+ * @extends threads_list_t
+ *
+ * @brief Type of a generic threads bidirectional linked list header and element.
+ */
+typedef struct {
+ thread_t *p_next; /**< @brief Next in the list/queue. */
+ thread_t *p_prev; /**< @brief Previous in the queue. */
+} threads_queue_t;
+
+/**
+ * @brief Type of a generic threads single link list, it works like a stack.
+ */
+typedef struct {
+ thread_t *p_next; /**< @brief Next in the list/queue. */
+} threads_list_t;
+
+/**
+ * @extends threads_queue_t
+ *
+ * @brief Ready list header.
+ */
+typedef struct {
+ threads_queue_t r_queue; /**< @brief Threads queue. */
+ tprio_t r_prio; /**< @brief This field must be
+ initialized to zero. */
+ struct context r_ctx; /**< @brief Not used, present because
+ offsets. */
+#if CH_CFG_USE_REGISTRY || defined(__DOXYGEN__)
+ thread_t *r_newer; /**< @brief Newer registry element. */
+ thread_t *r_older; /**< @brief Older registry element. */
+#endif
+ /* End of the fields shared with the thread_t structure.*/
+ thread_t *r_current; /**< @brief The currently running
+ thread. */
+} ready_list_t;
+
+/**
+ * @brief Structure representing a thread.
+ * @note Not all the listed fields are always needed, by switching off some
+ * not needed ChibiOS/RT subsystems it is possible to save RAM space
+ * by shrinking this structure.
+ */
+struct thread {
+ thread_t *p_next; /**< @brief Next in the list/queue. */
+ /* End of the fields shared with the threads_list_t structure.*/
+ thread_t *p_prev; /**< @brief Previous in the queue. */
+ /* End of the fields shared with the threads_queue_t structure.*/
+ tprio_t p_prio; /**< @brief Thread priority. */
+ struct context p_ctx; /**< @brief Processor context. */
+#if CH_CFG_USE_REGISTRY || defined(__DOXYGEN__)
+ thread_t *p_newer; /**< @brief Newer registry element. */
+ thread_t *p_older; /**< @brief Older registry element. */
+#endif
+ /* End of the fields shared with the ReadyList structure. */
+#if CH_CFG_USE_REGISTRY || defined(__DOXYGEN__)
+ /**
+ * @brief Thread name or @p NULL.
+ */
+ const char *p_name;
+#endif
+#if CH_DBG_ENABLE_STACK_CHECK || defined(__DOXYGEN__)
+ /**
+ * @brief Thread stack boundary.
+ */
+ stkalign_t *p_stklimit;
+#endif
+ /**
+ * @brief Current thread state.
+ */
+ tstate_t p_state;
+ /**
+ * @brief Various thread flags.
+ */
+ tmode_t p_flags;
+#if CH_CFG_USE_DYNAMIC || defined(__DOXYGEN__)
+ /**
+ * @brief References to this thread.
+ */
+ trefs_t p_refs;
+#endif
+ /**
+ * @brief Number of ticks remaining to this thread.
+ */
+#if (CH_CFG_TIME_QUANTUM > 0) || defined(__DOXYGEN__)
+ tslices_t p_preempt;
+#endif
+#if CH_DBG_THREADS_PROFILING || defined(__DOXYGEN__)
+ /**
+ * @brief Thread consumed time in ticks.
+ * @note This field can overflow.
+ */
+ volatile systime_t p_time;
+#endif
+ /**
+ * @brief State-specific fields.
+ * @note All the fields declared in this union are only valid in the
+ * specified state or condition and are thus volatile.
+ */
+ union {
+ /**
+ * @brief Thread wakeup code.
+ * @note This field contains the low level message sent to the thread
+ * by the waking thread or interrupt handler. The value is valid
+ * after exiting the @p chSchWakeupS() function.
+ */
+ msg_t rdymsg;
+ /**
+ * @brief Thread exit code.
+ * @note The thread termination code is stored in this field in order
+ * to be retrieved by the thread performing a @p chThdWait() on
+ * this thread.
+ */
+ msg_t exitcode;
+ /**
+ * @brief Pointer to a generic "wait" object.
+ * @note This field is used to get a generic pointer to a synchronization
+ * object and is valid when the thread is in one of the wait
+ * states.
+ */
+ void *wtobjp;
+#if CH_CFG_USE_EVENTS || defined(__DOXYGEN__)
+ /**
+ * @brief Enabled events mask.
+ * @note This field is only valid while the thread is in the
+ * @p CH_STATE_WTOREVT or @p CH_STATE_WTANDEVT states.
+ */
+ eventmask_t ewmask;
+#endif
+ } p_u;
+#if CH_CFG_USE_WAITEXIT || defined(__DOXYGEN__)
+ /**
+ * @brief Termination waiting list.
+ */
+ threads_list_t p_waiting;
+#endif
+#if CH_CFG_USE_MESSAGES || defined(__DOXYGEN__)
+ /**
+ * @brief Messages queue.
+ */
+ threads_queue_t p_msgqueue;
+ /**
+ * @brief Thread message.
+ */
+ msg_t p_msg;
+#endif
+#if CH_CFG_USE_EVENTS || defined(__DOXYGEN__)
+ /**
+ * @brief Pending events mask.
+ */
+ eventmask_t p_epending;
+#endif
+#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
+ /**
+ * @brief List of the mutexes owned by this thread.
+ * @note The list is terminated by a @p NULL in this field.
+ */
+ struct mutex *p_mtxlist;
+ /**
+ * @brief Thread's own, non-inherited, priority.
+ */
+ tprio_t p_realprio;
+#endif
+#if (CH_CFG_USE_DYNAMIC && CH_CFG_USE_MEMPOOLS) || defined(__DOXYGEN__)
+ /**
+ * @brief Memory Pool where the thread workspace is returned.
+ */
+ void *p_mpool;
+#endif
+#if CH_DBG_STATISTICS || defined(__DOXYGEN__)
+ time_measurement_t p_stats;
+#endif
+#if defined(CH_CFG_THREAD_EXTRA_FIELDS)
+ /* Extra fields defined in chconf.h.*/
+ CH_CFG_THREAD_EXTRA_FIELDS
+#endif
+};
+
+/**
+ * @brief Type of a Virtual Timer callback function.
+ */
+typedef void (*vtfunc_t)(void *);
+
+/**
+ * @brief Type of a Virtual Timer structure.
+ */
+typedef struct virtual_timer virtual_timer_t;
+
+/**
+ * @extends virtual_timers_list_t
+ *
+ * @brief Virtual Timer descriptor structure.
+ */
+struct virtual_timer {
+ virtual_timer_t *vt_next; /**< @brief Next timer in the list. */
+ virtual_timer_t *vt_prev; /**< @brief Previous timer in the list. */
+ systime_t vt_delta; /**< @brief Time delta before timeout. */
+ vtfunc_t vt_func; /**< @brief Timer callback function
+ pointer. */
+ void *vt_par; /**< @brief Timer callback function
+ parameter. */
+};
+
+/**
+ * @brief Virtual timers list header.
+ * @note The timers list is implemented as a double link bidirectional list
+ * in order to make the unlink time constant, the reset of a virtual
+ * timer is often used in the code.
+ */
+typedef struct {
+ virtual_timer_t *vt_next; /**< @brief Next timer in the delta
+ list. */
+ virtual_timer_t *vt_prev; /**< @brief Last timer in the delta
+ list. */
+ systime_t vt_delta; /**< @brief Must be initialized to -1. */
+#if CH_CFG_ST_TIMEDELTA == 0 || defined(__DOXYGEN__)
+ volatile systime_t vt_systime; /**< @brief System Time counter. */
+#endif
+#if CH_CFG_ST_TIMEDELTA > 0 || defined(__DOXYGEN__)
+ /**
+ * @brief System time of the last tick event.
+ */
+ systime_t vt_lasttime;/**< @brief System time of the last
+ tick event. */
+#endif
+} virtual_timers_list_t;
+
+/**
+ * @brief System data structure.
+ * @note This structure contain all the data areas used by the OS except
+ * stacks.
+ */
+typedef struct ch_system {
+ /**
+ * @brief Ready list header.
+ */
+ ready_list_t rlist;
+ /**
+ * @brief Virtual timers delta list header.
+ */
+ virtual_timers_list_t vtlist;
+#if CH_CFG_USE_TM || defined(__DOXYGEN__)
+ /**
+ * @brief Measurement calibration value.
+ */
+ rtcnt_t measurement_offset;
+#endif
+#if CH_DBG_STATISTICS || defined(__DOXYGEN__)
+ /**
+ * @brief Global kernel statistics.
+ */
+ kernel_stats_t kernel_stats;
+#endif
+#if CH_DBG_ENABLED || defined(__DOXYGEN__)
+ /**
+ * @brief Pointer to the panic message.
+ * @details This pointer is meant to be accessed through the debugger, it is
+ * written once and then the system is halted.
+ * @note Accesses to this pointer must never be optimized out so the
+ * field itself is declared volatile.
+ */
+ const char * volatile dbg_panic_msg;
+#endif
+#if CH_DBG_SYSTEM_STATE_CHECK || defined(__DOXYGEN__)
+ /**
+ * @brief ISR nesting level.
+ */
+ cnt_t dbg_isr_cnt;
+ /**
+ * @brief Lock nesting level.
+ */
+ cnt_t dbg_lock_cnt;
+#endif
+#if CH_DBG_ENABLE_TRACE || defined(__DOXYGEN__)
+ /**
+ * @brief Public trace buffer.
+ */
+ ch_trace_buffer_t dbg_trace_buffer;
+#endif
+} ch_system_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Returns the priority of the first thread on the given ready list.
+ *
+ * @notapi
+ */
+#define firstprio(rlp) ((rlp)->p_next->p_prio)
+
+/**
+ * @brief Current thread pointer access macro.
+ * @note This macro is not meant to be used in the application code but
+ * only from within the kernel, use the @p chThdSelf() API instead.
+ * @note It is forbidden to use this macro in order to change the pointer
+ * (currp = something), use @p setcurrp() instead.
+ */
+#define currp ch.rlist.r_current
+
+/**
+ * @brief Current thread pointer change macro.
+ * @note This macro is not meant to be used in the application code but
+ * only from within the kernel.
+ *
+ * @notapi
+ */
+#define setcurrp(tp) (currp = (tp))
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#if !defined(__DOXYGEN__)
+extern ch_system_t ch;
+#endif
+
+/*
+ * Scheduler APIs.
+ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _scheduler_init(void);
+ thread_t *chSchReadyI(thread_t *tp);
+ void chSchGoSleepS(tstate_t newstate);
+ msg_t chSchGoSleepTimeoutS(tstate_t newstate, systime_t time);
+ void chSchWakeupS(thread_t *tp, msg_t msg);
+ void chSchRescheduleS(void);
+ bool chSchIsPreemptionRequired(void);
+ void chSchDoRescheduleBehind(void);
+ void chSchDoRescheduleAhead(void);
+ void chSchDoReschedule(void);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+ /**
+ * @brief Threads list initialization.
+ *
+ * @notapi
+ */
+ static inline void list_init(threads_list_t *tlp) {
+
+ tlp->p_next = (thread_t *)tlp;
+ }
+
+ /**
+ * @brief Evaluates to @p true if the specified threads list is empty.
+ *
+ * @notapi
+ */
+ static inline bool list_isempty(threads_list_t *tlp) {
+
+ return (bool)(tlp->p_next == (thread_t *)tlp);
+ }
+
+ /**
+ * @brief Evaluates to @p true if the specified threads list is not empty.
+ *
+ * @notapi
+ */
+ static inline bool list_notempty(threads_list_t *tlp) {
+
+ return (bool)(tlp->p_next != (thread_t *)tlp);
+ }
+
+ /**
+ * @brief Threads queue initialization.
+ *
+ * @notapi
+ */
+ static inline void queue_init(threads_queue_t *tqp) {
+
+ tqp->p_next = tqp->p_prev = (thread_t *)tqp;
+ }
+
+ /**
+ * @brief Evaluates to @p true if the specified threads queue is empty.
+ *
+ * @notapi
+ */
+ static inline bool queue_isempty(threads_queue_t *tqp) {
+
+ return (bool)(tqp->p_next == (thread_t *)tqp);
+ }
+
+ /**
+ * @brief Evaluates to @p true if the specified threads queue is not empty.
+ *
+ * @notapi
+ */
+ static inline bool queue_notempty(threads_queue_t *tqp) {
+
+ return (bool)(tqp->p_next != (thread_t *)tqp);
+ }
+
+ /* If the performance code path has been chosen then all the following
+ functions are inlined into the various kernel modules.*/
+ #if CH_CFG_OPTIMIZE_SPEED
+ static inline void list_insert(thread_t *tp, threads_list_t *tlp) {
+
+ tp->p_next = tlp->p_next;
+ tlp->p_next = tp;
+ }
+
+ static inline thread_t *list_remove(threads_list_t *tlp) {
+
+ thread_t *tp = tlp->p_next;
+ tlp->p_next = tp->p_next;
+ return tp;
+ }
+
+ static inline void queue_prio_insert(thread_t *tp, threads_queue_t *tqp) {
+
+ thread_t *cp = (thread_t *)tqp;
+ do {
+ cp = cp->p_next;
+ } while ((cp != (thread_t *)tqp) && (cp->p_prio >= tp->p_prio));
+ tp->p_next = cp;
+ tp->p_prev = cp->p_prev;
+ tp->p_prev->p_next = cp->p_prev = tp;
+ }
+
+ static inline void queue_insert(thread_t *tp, threads_queue_t *tqp) {
+
+ tp->p_next = (thread_t *)tqp;
+ tp->p_prev = tqp->p_prev;
+ tp->p_prev->p_next = tqp->p_prev = tp;
+ }
+
+ static inline thread_t *queue_fifo_remove(threads_queue_t *tqp) {
+ thread_t *tp = tqp->p_next;
+
+ (tqp->p_next = tp->p_next)->p_prev = (thread_t *)tqp;
+ return tp;
+ }
+
+ static inline thread_t *queue_lifo_remove(threads_queue_t *tqp) {
+ thread_t *tp = tqp->p_prev;
+
+ (tqp->p_prev = tp->p_prev)->p_next = (thread_t *)tqp;
+ return tp;
+ }
+
+ static inline thread_t *queue_dequeue(thread_t *tp) {
+
+ tp->p_prev->p_next = tp->p_next;
+ tp->p_next->p_prev = tp->p_prev;
+ return tp;
+ }
+#endif /* CH_CFG_OPTIMIZE_SPEED */
+
+/**
+ * @brief Determines if the current thread must reschedule.
+ * @details This function returns @p true if there is a ready thread with
+ * higher priority.
+ *
+ * @iclass
+ */
+static inline bool chSchIsRescRequiredI(void) {
+
+ chDbgCheckClassI();
+
+ return firstprio(&ch.rlist.r_queue) > currp->p_prio;
+}
+
+/**
+ * @brief Determines if yielding is possible.
+ * @details This function returns @p true if there is a ready thread with
+ * equal or higher priority.
+ *
+ * @sclass
+ */
+static inline bool chSchCanYieldS(void) {
+
+ chDbgCheckClassI();
+
+ return firstprio(&ch.rlist.r_queue) >= currp->p_prio;
+}
+
+/**
+ * @brief Yields the time slot.
+ * @details Yields the CPU control to the next thread in the ready list with
+ * equal or higher priority, if any.
+ *
+ * @sclass
+ */
+static inline void chSchDoYieldS(void) {
+
+ chDbgCheckClassS();
+
+ if (chSchCanYieldS())
+ chSchDoRescheduleBehind();
+}
+
+/**
+ * @brief Inline-able preemption code.
+ * @details This is the common preemption code, this function must be invoked
+ * exclusively from the port layer.
+ *
+ * @special
+ */
+static inline void chSchPreemption(void) {
+ tprio_t p1 = firstprio(&ch.rlist.r_queue);
+ tprio_t p2 = currp->p_prio;
+
+#if CH_CFG_TIME_QUANTUM > 0
+ if (currp->p_preempt) {
+ if (p1 > p2)
+ chSchDoRescheduleAhead();
+ }
+ else {
+ if (p1 >= p2)
+ chSchDoRescheduleBehind();
+ }
+#else /* CH_CFG_TIME_QUANTUM == 0 */
+ if (p1 >= p2)
+ chSchDoRescheduleAhead();
+#endif /* CH_CFG_TIME_QUANTUM == 0 */
+}
+
+#endif /* _CHSCHD_H_ */
+
+/** @} */
diff --git a/os/rt/include/chsem.h b/os/rt/include/chsem.h new file mode 100644 index 000000000..21ee14293 --- /dev/null +++ b/os/rt/include/chsem.h @@ -0,0 +1,154 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chsem.h
+ * @brief Semaphores macros and structures.
+ *
+ * @addtogroup semaphores
+ * @{
+ */
+
+#ifndef _CHSEM_H_
+#define _CHSEM_H_
+
+#if CH_CFG_USE_SEMAPHORES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Semaphore structure.
+ */
+typedef struct semaphore {
+ threads_queue_t s_queue; /**< @brief Queue of the threads sleeping
+ on this semaphore. */
+ cnt_t s_cnt; /**< @brief The semaphore counter. */
+} semaphore_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Data part of a static semaphore initializer.
+ * @details This macro should be used when statically initializing a semaphore
+ * that is part of a bigger structure.
+ *
+ * @param[in] name the name of the semaphore variable
+ * @param[in] n the counter initial value, this value must be
+ * non-negative
+ */
+#define _SEMAPHORE_DATA(name, n) {_threads_queue_t_DATA(name.s_queue), n}
+
+/**
+ * @brief Static semaphore initializer.
+ * @details Statically initialized semaphores require no explicit
+ * initialization using @p chSemInit().
+ *
+ * @param[in] name the name of the semaphore variable
+ * @param[in] n the counter initial value, this value must be
+ * non-negative
+ */
+#define SEMAPHORE_DECL(name, n) semaphore_t name = _SEMAPHORE_DATA(name, n)
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chSemObjectInit(semaphore_t *sp, cnt_t n);
+ void chSemReset(semaphore_t *sp, cnt_t n);
+ void chSemResetI(semaphore_t *sp, cnt_t n);
+ msg_t chSemWait(semaphore_t *sp);
+ msg_t chSemWaitS(semaphore_t *sp);
+ msg_t chSemWaitTimeout(semaphore_t *sp, systime_t time);
+ msg_t chSemWaitTimeoutS(semaphore_t *sp, systime_t time);
+ void chSemSignal(semaphore_t *sp);
+ void chSemSignalI(semaphore_t *sp);
+ void chSemAddCounterI(semaphore_t *sp, cnt_t n);
+ msg_t chSemSignalWait(semaphore_t *sps, semaphore_t *spw);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Decreases the semaphore counter.
+ * @details This macro can be used when the counter is known to be positive.
+ *
+ * @iclass
+ */
+static inline void chSemFastWaitI(semaphore_t *sp) {
+
+ chDbgCheckClassI();
+
+ sp->s_cnt--;
+}
+
+/**
+ * @brief Increases the semaphore counter.
+ * @details This macro can be used when the counter is known to be not
+ * negative.
+ *
+ * @iclass
+ */
+static inline void chSemFastSignalI(semaphore_t *sp) {
+
+ chDbgCheckClassI();
+
+ sp->s_cnt++;
+}
+
+/**
+ * @brief Returns the semaphore counter current value.
+ *
+ * @iclass
+ */
+static inline cnt_t chSemGetCounterI(semaphore_t *sp) {
+
+ chDbgCheckClassI();
+
+ return sp->s_cnt;
+}
+
+#endif /* CH_CFG_USE_SEMAPHORES */
+
+#endif /* _CHSEM_H_ */
+
+/** @} */
diff --git a/os/rt/include/chstats.h b/os/rt/include/chstats.h new file mode 100644 index 000000000..b6e131141 --- /dev/null +++ b/os/rt/include/chstats.h @@ -0,0 +1,106 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chstats.h
+ * @brief Statistics module macros and structures.
+ *
+ * @addtogroup statistics
+ * @{
+ */
+
+#ifndef _CHSTATS_H_
+#define _CHSTATS_H_
+
+#if CH_DBG_STATISTICS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+#if !CH_CFG_USE_TM
+#error "CH_DBG_STATISTICS requires CH_CFG_USE_TM"
+#endif
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Type of a kernel statistics structure.
+ */
+typedef struct {
+ ucnt_t n_irq; /**< @brief Number of IRQs. */
+ ucnt_t n_ctxswc; /**< @brief Number of context switches. */
+ time_measurement_t m_crit_thd; /**< @brief Measurement of threads
+ critical zones duration. */
+ time_measurement_t m_crit_isr; /**< @brief Measurement of ISRs critical
+ zones duration. */
+} kernel_stats_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _stats_init(void);
+ void _stats_increase_irq(void);
+ void _stats_ctxswc(thread_t *ntp, thread_t *otp);
+ void _stats_start_measure_crit_thd(void);
+ void _stats_stop_measure_crit_thd(void);
+ void _stats_start_measure_crit_isr(void);
+ void _stats_stop_measure_crit_isr(void);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#else /* !CH_DBG_STATISTICS */
+
+/* Stub functions for when the statistics module is disabled. */
+#define _stats_increase_irq()
+#define _stats_ctxswc(old, new)
+#define _stats_start_measure_crit_thd()
+#define _stats_stop_measure_crit_thd()
+#define _stats_start_measure_crit_isr()
+#define _stats_stop_measure_crit_isr()
+
+#endif /* !CH_DBG_STATISTICS */
+
+#endif /* _CHSTATS_H_ */
+
+/** @} */
diff --git a/os/rt/include/chstreams.h b/os/rt/include/chstreams.h new file mode 100644 index 000000000..b9c40cac2 --- /dev/null +++ b/os/rt/include/chstreams.h @@ -0,0 +1,147 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chstreams.h
+ * @brief Data streams.
+ * @details This header defines abstract interfaces useful to access generic
+ * data streams in a standardized way.
+ *
+ * @addtogroup data_streams
+ * @details This module define an abstract interface for generic data streams.
+ * Note that no code is present, just abstract interfaces-like
+ * structures, you should look at the system as to a set of
+ * abstract C++ classes (even if written in C). This system
+ * has then advantage to make the access to data streams
+ * independent from the implementation logic.<br>
+ * The stream interface can be used as base class for high level
+ * object types such as files, sockets, serial ports, pipes etc.
+ * @{
+ */
+
+#ifndef _CHSTREAMS_H_
+#define _CHSTREAMS_H_
+
+/**
+ * @brief BaseSequentialStream specific methods.
+ */
+#define _base_sequential_stream_methods \
+ /* Stream write buffer method.*/ \
+ size_t (*write)(void *instance, const uint8_t *bp, size_t n); \
+ /* Stream read buffer method.*/ \
+ size_t (*read)(void *instance, uint8_t *bp, size_t n); \
+ /* Channel put method, blocking.*/ \
+ msg_t (*put)(void *instance, uint8_t b); \
+ /* Channel get method, blocking.*/ \
+ msg_t (*get)(void *instance); \
+
+/**
+ * @brief @p BaseSequentialStream specific data.
+ * @note It is empty because @p BaseSequentialStream is only an interface
+ * without implementation.
+ */
+#define _base_sequential_stream_data
+
+/**
+ * @brief @p BaseSequentialStream virtual methods table.
+ */
+struct BaseSequentialStreamVMT {
+ _base_sequential_stream_methods
+};
+
+/**
+ * @brief Base stream class.
+ * @details This class represents a generic blocking unbuffered sequential
+ * data stream.
+ */
+typedef struct {
+ /** @brief Virtual Methods Table.*/
+ const struct BaseSequentialStreamVMT *vmt;
+ _base_sequential_stream_data
+} BaseSequentialStream;
+
+/**
+ * @name Macro Functions (BaseSequentialStream)
+ * @{
+ */
+/**
+ * @brief Sequential Stream write.
+ * @details The function writes data from a buffer to a stream.
+ *
+ * @param[in] ip pointer to a @p BaseSequentialStream or derived class
+ * @param[in] bp pointer to the data buffer
+ * @param[in] n the maximum amount of data to be transferred
+ * @return The number of bytes transferred. The return value can
+ * be less than the specified number of bytes if an
+ * end-of-file condition has been met.
+ *
+ * @api
+ */
+#define chSequentialStreamWrite(ip, bp, n) ((ip)->vmt->write(ip, bp, n))
+
+/**
+ * @brief Sequential Stream read.
+ * @details The function reads data from a stream into a buffer.
+ *
+ * @param[in] ip pointer to a @p BaseSequentialStream or derived class
+ * @param[out] bp pointer to the data buffer
+ * @param[in] n the maximum amount of data to be transferred
+ * @return The number of bytes transferred. The return value can
+ * be less than the specified number of bytes if an
+ * end-of-file condition has been met.
+ *
+ * @api
+ */
+#define chSequentialStreamRead(ip, bp, n) ((ip)->vmt->read(ip, bp, n))
+
+/**
+ * @brief Sequential Stream blocking byte write.
+ * @details This function writes a byte value to a channel. If the channel
+ * is not ready to accept data then the calling thread is suspended.
+ *
+ * @param[in] ip pointer to a @p BaseChannel or derived class
+ * @param[in] b the byte value to be written to the channel
+ *
+ * @return The operation status.
+ * @retval Q_OK if the operation succeeded.
+ * @retval Q_RESET if an end-of-file condition has been met.
+ *
+ * @api
+ */
+#define chSequentialStreamPut(ip, b) ((ip)->vmt->put(ip, b))
+
+/**
+ * @brief Sequential Stream blocking byte read.
+ * @details This function reads a byte value from a channel. If the data
+ * is not available then the calling thread is suspended.
+ *
+ * @param[in] ip pointer to a @p BaseChannel or derived class
+ *
+ * @return A byte value from the queue.
+ * @retval Q_RESET if an end-of-file condition has been met.
+ *
+ * @api
+ */
+#define chSequentialStreamGet(ip) ((ip)->vmt->get(ip))
+/** @} */
+
+#endif /* _CHSTREAMS_H_ */
+
+/** @} */
diff --git a/os/rt/include/chsys.h b/os/rt/include/chsys.h new file mode 100644 index 000000000..6c2d61684 --- /dev/null +++ b/os/rt/include/chsys.h @@ -0,0 +1,366 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chsys.h
+ * @brief System related macros and structures.
+ *
+ * @addtogroup system
+ * @{
+ */
+
+#ifndef _CHSYS_H_
+#define _CHSYS_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @name ISRs abstraction macros
+ */
+/**
+ * @brief IRQ handler enter code.
+ * @note Usually IRQ handlers functions are also declared naked.
+ * @note On some architectures this macro can be empty.
+ *
+ * @special
+ */
+#define CH_IRQ_PROLOGUE() \
+ PORT_IRQ_PROLOGUE(); \
+ _stats_increase_irq(); \
+ _dbg_check_enter_isr()
+
+/**
+ * @brief IRQ handler exit code.
+ * @note Usually IRQ handlers function are also declared naked.
+ * @note This macro usually performs the final reschedule by using
+ * @p chSchIsPreemptionRequired() and @p chSchDoReschedule().
+ *
+ * @special
+ */
+#define CH_IRQ_EPILOGUE() \
+ _dbg_check_leave_isr(); \
+ PORT_IRQ_EPILOGUE()
+
+/**
+ * @brief Standard normal IRQ handler declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ *
+ * @special
+ */
+#define CH_IRQ_HANDLER(id) PORT_IRQ_HANDLER(id)
+/** @} */
+
+/**
+ * @name Fast ISRs abstraction macros
+ */
+/**
+ * @brief Standard fast IRQ handler declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ * @note Not all architectures support fast interrupts.
+ *
+ * @special
+ */
+#define CH_FAST_IRQ_HANDLER(id) PORT_FAST_IRQ_HANDLER(id)
+/** @} */
+
+/**
+ * @name Time conversion utilities for the realtime counter
+ * @{
+ */
+/**
+ * @brief Seconds to realtime counter.
+ * @details Converts from seconds to realtime counter cycles.
+ * @note The macro assumes that @p freq >= @p 1.
+ *
+ * @param[in] freq clock frequency, in Hz, of the realtime counter
+ * @param[in] sec number of seconds
+ * @return The number of cycles.
+ *
+ * @api
+ */
+#define S2RTC(freq, sec) ((freq) * (sec))
+
+/**
+ * @brief Milliseconds to realtime counter.
+ * @details Converts from milliseconds to realtime counter cycles.
+ * @note The result is rounded upward to the next millisecond boundary.
+ * @note The macro assumes that @p freq >= @p 1000.
+ *
+ * @param[in] freq clock frequency, in Hz, of the realtime counter
+ * @param[in] msec number of milliseconds
+ * @return The number of cycles.
+ *
+ * @api
+ */
+#define MS2RTC(freq, msec) (rtcnt_t)((((freq) + 999UL) / 1000UL) * (msec))
+
+/**
+ * @brief Microseconds to realtime counter.
+ * @details Converts from microseconds to realtime counter cycles.
+ * @note The result is rounded upward to the next microsecond boundary.
+ * @note The macro assumes that @p freq >= @p 1000000.
+ *
+ * @param[in] freq clock frequency, in Hz, of the realtime counter
+ * @param[in] usec number of microseconds
+ * @return The number of cycles.
+ *
+ * @api
+ */
+#define US2RTC(freq, usec) (rtcnt_t)((((freq) + 999999UL) / 1000000UL) * (usec))
+
+/**
+ * @brief Realtime counter cycles to seconds.
+ * @details Converts from realtime counter cycles number to seconds.
+ * @note The result is rounded up to the next second boundary.
+ * @note The macro assumes that @p freq >= @p 1.
+ *
+ * @param[in] freq clock frequency, in Hz, of the realtime counter
+ * @param[in] n number of cycles
+ * @return The number of seconds.
+ *
+ * @api
+ */
+#define RTC2S(freq, n) ((((n) - 1UL) / (freq)) + 1UL)
+
+/**
+ * @brief Realtime counter cycles to milliseconds.
+ * @details Converts from realtime counter cycles number to milliseconds.
+ * @note The result is rounded up to the next millisecond boundary.
+ * @note The macro assumes that @p freq >= @p 1000.
+ *
+ * @param[in] freq clock frequency, in Hz, of the realtime counter
+ * @param[in] n number of cycles
+ * @return The number of milliseconds.
+ *
+ * @api
+ */
+#define RTC2MS(freq, n) ((((n) - 1UL) / ((freq) / 1000UL)) + 1UL)
+
+/**
+ * @brief Realtime counter cycles to microseconds.
+ * @details Converts from realtime counter cycles number to microseconds.
+ * @note The result is rounded up to the next microsecond boundary.
+ * @note The macro assumes that @p freq >= @p 1000000.
+ *
+ * @param[in] freq clock frequency, in Hz, of the realtime counter
+ * @param[in] n number of cycles
+ * @return The number of microseconds.
+ *
+ * @api
+ */
+#define RTC2US(freq, n) ((((n) - 1UL) / ((freq) / 1000000UL)) + 1UL)
+/** @} */
+
+/**
+ * @brief Returns the current value of the system real time counter.
+ * @note This function is only available if the port layer supports the
+ * option @p PORT_SUPPORTS_RT.
+ *
+ * @return The value of the system realtime counter of
+ * type rtcnt_t.
+ *
+ * @xclass
+ */
+#if PORT_SUPPORTS_RT || defined(__DOXYGEN__)
+#define chSysGetRealtimeCounterX() (rtcnt_t)port_rt_get_counter_value()
+#endif
+
+/**
+ * @brief Performs a context switch.
+ * @note Not a user function, it is meant to be invoked by the scheduler
+ * itself or from within the port layer.
+ *
+ * @param[in] ntp the thread to be switched in
+ * @param[in] otp the thread to be switched out
+ *
+ * @special
+ */
+#define chSysSwitch(ntp, otp) { \
+ \
+ _dbg_trace(otp); \
+ _stats_ctxswc(ntp, otp); \
+ CH_CFG_CONTEXT_SWITCH_HOOK(ntp, otp); \
+ port_switch(ntp, otp); \
+}
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chSysInit(void);
+ void chSysHalt(const char *reason);
+ void chSysTimerHandlerI(void);
+ syssts_t chSysGetStatusAndLockX(void);
+ void chSysRestoreStatusX(syssts_t sts);
+#if PORT_SUPPORTS_RT
+ bool chSysIsCounterWithinX(rtcnt_t cnt, rtcnt_t start, rtcnt_t end);
+ void chSysPolledDelayX(rtcnt_t cycles);
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Raises the system interrupt priority mask to the maximum level.
+ * @details All the maskable interrupt sources are disabled regardless their
+ * hardware priority.
+ * @note Do not invoke this API from within a kernel lock.
+ *
+ * @special
+ */
+static inline void chSysDisable(void) {
+
+ port_disable();
+ _dbg_check_disable();
+}
+
+/**
+ * @brief Raises the system interrupt priority mask to system level.
+ * @details The interrupt sources that should not be able to preempt the kernel
+ * are disabled, interrupt sources with higher priority are still
+ * enabled.
+ * @note Do not invoke this API from within a kernel lock.
+ * @note This API is no replacement for @p chSysLock(), the @p chSysLock()
+ * could do more than just disable the interrupts.
+ *
+ * @special
+ */
+static inline void chSysSuspend(void) {
+
+ port_suspend();
+ _dbg_check_suspend();
+}
+
+/**
+ * @brief Lowers the system interrupt priority mask to user level.
+ * @details All the interrupt sources are enabled.
+ * @note Do not invoke this API from within a kernel lock.
+ * @note This API is no replacement for @p chSysUnlock(), the
+ * @p chSysUnlock() could do more than just enable the interrupts.
+ *
+ * @special
+ */
+static inline void chSysEnable(void) {
+
+ _dbg_check_enable();
+ port_enable();
+}
+
+/**
+ * @brief Enters the kernel lock mode.
+ *
+ * @special
+ */
+static inline void chSysLock(void) {
+
+ port_lock();
+ _stats_start_measure_crit_thd();
+ _dbg_check_lock();
+}
+
+/**
+ * @brief Leaves the kernel lock mode.
+ *
+ * @special
+ */
+static inline void chSysUnlock(void) {
+
+ _dbg_check_unlock();
+ _stats_stop_measure_crit_thd();
+
+ /* The following condition can be triggered by the use of i-class functions
+ in a critical section not followed by a chSchResceduleS(), this means
+ that the current thread has a lower priority than the next thread in
+ the ready list.*/
+ chDbgAssert(ch.rlist.r_current->p_prio >= ch.rlist.r_queue.p_next->p_prio,
+ "priority violation, missing reschedule");
+
+ port_unlock();
+}
+
+/**
+ * @brief Enters the kernel lock mode from within an interrupt handler.
+ * @note This API may do nothing on some architectures, it is required
+ * because on ports that support preemptable interrupt handlers
+ * it is required to raise the interrupt mask to the same level of
+ * the system mutual exclusion zone.<br>
+ * It is good practice to invoke this API before invoking any I-class
+ * syscall from an interrupt handler.
+ * @note This API must be invoked exclusively from interrupt handlers.
+ *
+ * @special
+ */
+static inline void chSysLockFromISR(void) {
+
+ port_lock_from_isr();
+ _stats_start_measure_crit_isr();
+ _dbg_check_lock_from_isr();
+}
+
+/**
+ * @brief Leaves the kernel lock mode from within an interrupt handler.
+ *
+ * @note This API may do nothing on some architectures, it is required
+ * because on ports that support preemptable interrupt handlers
+ * it is required to raise the interrupt mask to the same level of
+ * the system mutual exclusion zone.<br>
+ * It is good practice to invoke this API after invoking any I-class
+ * syscall from an interrupt handler.
+ * @note This API must be invoked exclusively from interrupt handlers.
+ *
+ * @special
+ */
+static inline void chSysUnlockFromISR(void) {
+
+ _dbg_check_unlock_from_isr();
+ _stats_stop_measure_crit_isr();
+ port_unlock_from_isr();
+}
+
+#endif /* _CHSYS_H_ */
+
+/** @} */
diff --git a/os/rt/include/chthreads.h b/os/rt/include/chthreads.h new file mode 100644 index 000000000..ef83fc963 --- /dev/null +++ b/os/rt/include/chthreads.h @@ -0,0 +1,380 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chthreads.h
+ * @brief Threads module macros and structures.
+ *
+ * @addtogroup threads
+ * @{
+ */
+
+#ifndef _CHTHREADS_H_
+#define _CHTHREADS_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Thread states
+ * @{
+ */
+#define CH_STATE_READY 0 /**< @brief Waiting on the ready list. */
+#define CH_STATE_CURRENT 1 /**< @brief Currently running. */
+#define CH_STATE_WTSTART 2 /**< @brief Created but not started. */
+#define CH_STATE_SUSPENDED 3 /**< @brief Created in suspended state. */
+#define CH_STATE_QUEUED 4 /**< @brief Waiting on an I/O queue. */
+#define CH_STATE_WTSEM 5 /**< @brief Waiting on a semaphore. */
+#define CH_STATE_WTMTX 6 /**< @brief Waiting on a mutex. */
+#define CH_STATE_WTCOND 7 /**< @brief Waiting on a condition
+ variable. */
+#define CH_STATE_SLEEPING 8 /**< @brief Waiting in @p chThdSleep()
+ or @p chThdSleepUntil(). */
+#define CH_STATE_WTEXIT 9 /**< @brief Waiting in @p chThdWait(). */
+#define CH_STATE_WTOREVT 10 /**< @brief Waiting for an event. */
+#define CH_STATE_WTANDEVT 11 /**< @brief Waiting for several events. */
+#define CH_STATE_SNDMSGQ 12 /**< @brief Sending a message, in queue.*/
+#define CH_STATE_SNDMSG 13 /**< @brief Sent a message, waiting
+ answer. */
+#define CH_STATE_WTMSG 14 /**< @brief Waiting for a message. */
+#define CH_STATE_FINAL 15 /**< @brief Thread terminated. */
+
+/**
+ * @brief Thread states as array of strings.
+ * @details Each element in an array initialized with this macro can be
+ * indexed using the numeric thread state values.
+ */
+#define CH_STATE_NAMES \
+ "READY", "WTSTART", "CURRENT", "SUSPENDED", "QUEUED", "WTSEM", "WTMTX", \
+ "WTCOND", "SLEEPING", "WTEXIT", "WTOREVT", "WTANDEVT", "SNDMSGQ", \
+ "SNDMSG", "WTMSG", "FINAL"
+/** @} */
+
+/**
+ * @name Thread flags and attributes
+ * @{
+ */
+#define CH_FLAG_MODE_MASK 3 /**< @brief Thread memory mode mask. */
+#define CH_FLAG_MODE_STATIC 0 /**< @brief Static thread. */
+#define CH_FLAG_MODE_HEAP 1 /**< @brief Thread allocated from a
+ Memory Heap. */
+#define CH_FLAG_MODE_MEMPOOL 2 /**< @brief Thread allocated from a
+ Memory Pool. */
+#define CH_FLAG_TERMINATE 4 /**< @brief Termination requested flag. */
+/** @} */
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Type of a thread reference.
+ */
+typedef thread_t * thread_reference_t;
+
+/**
+ * @brief Thread function.
+ */
+typedef msg_t (*tfunc_t)(void *);
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @name Working Areas and Alignment
+ */
+/**
+ * @brief Enforces a correct alignment for a stack area size value.
+ *
+ * @param[in] n the stack size to be aligned to the next stack
+ * alignment boundary
+ * @return The aligned stack size.
+ *
+ * @api
+ */
+#define THD_ALIGN_STACK_SIZE(n) \
+ ((((n) - 1) | (sizeof(stkalign_t) - 1)) + 1)
+
+/**
+ * @brief Calculates the total Working Area size.
+ *
+ * @param[in] n the stack size to be assigned to the thread
+ * @return The total used memory in bytes.
+ *
+ * @api
+ */
+#define THD_WORKING_AREA_SIZE(n) \
+ THD_ALIGN_STACK_SIZE(sizeof(thread_t) + PORT_WA_SIZE(n))
+
+/**
+ * @brief Static working area allocation.
+ * @details This macro is used to allocate a static thread working area
+ * aligned as both position and size.
+ *
+ * @param[in] s the name to be assigned to the stack array
+ * @param[in] n the stack size to be assigned to the thread
+ *
+ * @api
+ */
+#define THD_WORKING_AREA(s, n) \
+ stkalign_t s[THD_WORKING_AREA_SIZE(n) / sizeof(stkalign_t)]
+/** @} */
+
+/**
+ * @name Threads abstraction macros
+ */
+/**
+ * @brief Thread declaration macro.
+ * @note Thread declarations should be performed using this macro because
+ * the port layer could define optimizations for thread functions.
+ */
+#define THD_FUNCTION(tname, arg) PORT_THD_FUNCTION(tname, arg)
+/** @} */
+
+/**
+ * @name Threads queues
+ */
+/**
+ * @brief Data part of a static threads queue object initializer.
+ * @details This macro should be used when statically initializing a threads
+ * queue that is part of a bigger structure.
+ *
+ * @param[in] name the name of the threads queue variable
+ */
+#define _threads_queue_t_DATA(name) {(thread_t *)&name, (thread_t *)&name}
+
+/**
+ * @brief Static threads queue object initializer.
+ * @details Statically initialized threads queues require no explicit
+ * initialization using @p queue_init().
+ *
+ * @param[in] name the name of the threads queue variable
+ */
+#define threads_queue_t_DECL(name) \
+ threads_queue_t name = _threads_queue_t_DATA(name)
+/** @} */
+
+/**
+ * @name Macro Functions
+ * @{
+ */
+/**
+ * @brief Delays the invoking thread for the specified number of seconds.
+ * @note The specified time is rounded up to a value allowed by the real
+ * system tick clock.
+ * @note The maximum specifiable value is implementation dependent.
+ *
+ * @param[in] sec time in seconds, must be different from zero
+ *
+ * @api
+ */
+#define chThdSleepSeconds(sec) chThdSleep(S2ST(sec))
+
+/**
+ * @brief Delays the invoking thread for the specified number of
+ * milliseconds.
+ * @note The specified time is rounded up to a value allowed by the real
+ * system tick clock.
+ * @note The maximum specifiable value is implementation dependent.
+ *
+ * @param[in] msec time in milliseconds, must be different from zero
+ *
+ * @api
+ */
+#define chThdSleepMilliseconds(msec) chThdSleep(MS2ST(msec))
+
+/**
+ * @brief Delays the invoking thread for the specified number of
+ * microseconds.
+ * @note The specified time is rounded up to a value allowed by the real
+ * system tick clock.
+ * @note The maximum specifiable value is implementation dependent.
+ *
+ * @param[in] usec time in microseconds, must be different from zero
+ *
+ * @api
+ */
+#define chThdSleepMicroseconds(usec) chThdSleep(US2ST(usec))
+/** @} */
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ thread_t *_thread_init(thread_t *tp, tprio_t prio);
+#if CH_DBG_FILL_THREADS
+ void _thread_memfill(uint8_t *startp, uint8_t *endp, uint8_t v);
+#endif
+ thread_t *chThdCreateI(void *wsp, size_t size,
+ tprio_t prio, tfunc_t pf, void *arg);
+ thread_t *chThdCreateStatic(void *wsp, size_t size,
+ tprio_t prio, tfunc_t pf, void *arg);
+ thread_t *chThdStart(thread_t *tp);
+ tprio_t chThdSetPriority(tprio_t newprio);
+ msg_t chThdSuspendS(thread_reference_t *trp);
+ msg_t chThdSuspendTimeoutS(thread_reference_t *trp, systime_t timeout);
+ void chThdResumeI(thread_reference_t *trp, msg_t msg);
+ void chThdResumeS(thread_reference_t *trp, msg_t msg);
+ void chThdResume(thread_reference_t *trp, msg_t msg);
+ msg_t chThdEnqueueTimeoutS(threads_queue_t *tqp, systime_t timeout);
+ void chThdDequeueNextI(threads_queue_t *tqp, msg_t msg);
+ void chThdDequeueAllI(threads_queue_t *tqp, msg_t msg);
+ void chThdTerminate(thread_t *tp);
+ void chThdSleep(systime_t time);
+ void chThdSleepUntil(systime_t time);
+ void chThdYield(void);
+ void chThdExit(msg_t msg);
+ void chThdExitS(msg_t msg);
+#if CH_CFG_USE_WAITEXIT
+ msg_t chThdWait(thread_t *tp);
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+ /**
+ * @brief Returns a pointer to the current @p thread_t.
+ *
+ * @xclass
+ */
+static inline thread_t *chThdGetSelfX(void) {
+
+ return ch.rlist.r_current;
+}
+
+/**
+ * @brief Returns the current thread priority.
+ * @note Can be invoked in any context.
+ *
+ * @xclass
+ */
+static inline tprio_t chThdGetPriorityX(void) {
+
+ return chThdGetSelfX()->p_prio;
+}
+
+/**
+ * @brief Returns the number of ticks consumed by the specified thread.
+ * @note This function is only available when the
+ * @p CH_DBG_THREADS_PROFILING configuration option is enabled.
+ *
+ * @param[in] tp pointer to the thread
+ *
+ * @xclass
+ */
+#if CH_DBG_THREADS_PROFILING || defined(__DOXYGEN__)
+static inline systime_t chThdGetTicksX(thread_t *tp) {
+
+ return tp->p_time;
+}
+#endif
+
+/**
+ * @brief Verifies if the specified thread is in the @p CH_STATE_FINAL state.
+ *
+ * @param[in] tp pointer to the thread
+ * @retval true thread terminated.
+ * @retval false thread not terminated.
+ *
+ * @xclass
+ */
+static inline bool chThdTerminatedX(thread_t *tp) {
+
+ return (bool)(tp->p_state == CH_STATE_FINAL);
+}
+
+/**
+ * @brief Verifies if the current thread has a termination request pending.
+ *
+ * @retval true termination request pending.
+ * @retval false termination request not pending.
+ *
+ * @xclass
+ */
+static inline bool chThdShouldTerminateX(void) {
+
+ return (bool)((chThdGetSelfX()->p_flags & CH_FLAG_TERMINATE) != 0);
+}
+
+/**
+ * @brief Resumes a thread created with @p chThdCreateI().
+ *
+ * @param[in] tp pointer to the thread
+ *
+ * @iclass
+ */
+static inline thread_t *chThdStartI(thread_t *tp) {
+
+ chDbgAssert(tp->p_state == CH_STATE_WTSTART, "wrong state");
+
+ return chSchReadyI(tp);
+}
+
+/**
+ * @brief Suspends the invoking thread for the specified time.
+ *
+ * @param[in] time the delay in system ticks, the special values are
+ * handled as follow:
+ * - @a TIME_INFINITE the thread enters an infinite sleep
+ * state.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ *
+ * @sclass
+ */
+static inline void chThdSleepS(systime_t time) {
+
+ chDbgCheck(time != TIME_IMMEDIATE);
+
+ chSchGoSleepTimeoutS(CH_STATE_SLEEPING, time);
+}
+
+/**
+ * @brief Initializes a threads queue object.
+ *
+ * @param[out] tqp pointer to the threads queue object
+ *
+ * @init
+ */
+static inline void chThdQueueObjectInit(threads_queue_t *tqp) {
+
+ queue_init(tqp);
+}
+
+#endif /* _CHTHREADS_H_ */
+
+/** @} */
diff --git a/os/rt/include/chtm.h b/os/rt/include/chtm.h new file mode 100644 index 000000000..f85b68ca8 --- /dev/null +++ b/os/rt/include/chtm.h @@ -0,0 +1,100 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chtm.h
+ * @brief Time Measurement module macros and structures.
+ *
+ * @addtogroup time_measurement
+ * @{
+ */
+
+#ifndef _CHTM_H_
+#define _CHTM_H_
+
+#if CH_CFG_USE_TM || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if !PORT_SUPPORTS_RT
+#error "CH_CFG_USE_TM requires PORT_SUPPORTS_RT"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/**
+ * @brief Type of a Time Measurement object.
+ * @note The maximum measurable time period depends on the implementation
+ * of the realtime counter and its clock frequency.
+ * @note The measurement is not 100% cycle-accurate, it can be in excess
+ * of few cycles depending on the compiler and target architecture.
+ * @note Interrupts can affect measurement if the measurement is performed
+ * with interrupts enabled.
+ */
+typedef struct {
+ rtcnt_t best; /**< @brief Best measurement. */
+ rtcnt_t worst; /**< @brief Worst measurement. */
+ rtcnt_t last; /**< @brief Last measurement. */
+ ucnt_t n; /**< @brief Number of measurements. */
+ rttime_t cumulative; /**< @brief Cumulative measurement. */
+} time_measurement_t;
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _tm_init(void);
+ void chTMObjectInit(time_measurement_t *tmp);
+ NOINLINE void chTMStartMeasurementX(time_measurement_t *tmp);
+ NOINLINE void chTMStopMeasurementX(time_measurement_t *tmp);
+ NOINLINE void chTMChainMeasurementToX(time_measurement_t *tmp1,
+ time_measurement_t *tmp2);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* CH_CFG_USE_TM */
+
+#endif /* _CHTM_H_ */
+
+/** @} */
diff --git a/os/rt/include/chvt.h b/os/rt/include/chvt.h new file mode 100644 index 000000000..471ba22ee --- /dev/null +++ b/os/rt/include/chvt.h @@ -0,0 +1,495 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chvt.h
+ * @brief Time and Virtual Timers module macros and structures.
+ *
+ * @addtogroup time
+ * @{
+ */
+
+#ifndef _CHVT_H_
+#define _CHVT_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Special time constants
+ * @{
+ */
+/**
+ * @brief Zero time specification for some functions with a timeout
+ * specification.
+ * @note Not all functions accept @p TIME_IMMEDIATE as timeout parameter,
+ * see the specific function documentation.
+ */
+#define TIME_IMMEDIATE ((systime_t)0)
+
+/**
+ * @brief Infinite time specification for all functions with a timeout
+ * specification.
+ * @note Not all functions accept @p TIME_INFINITE as timeout parameter,
+ * see the specific function documentation.
+ */
+#define TIME_INFINITE ((systime_t)-1)
+/** @} */
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if (CH_CFG_ST_RESOLUTION != 16) && (CH_CFG_ST_RESOLUTION != 32)
+#error "invalid CH_CFG_ST_RESOLUTION specified, must be 16 or 32"
+#endif
+
+#if CH_CFG_ST_FREQUENCY <= 0
+#error "invalid CH_CFG_ST_FREQUENCY specified, must be greated than zero"
+#endif
+
+#if (CH_CFG_ST_TIMEDELTA < 0) || (CH_CFG_ST_TIMEDELTA == 1)
+#error "invalid CH_CFG_ST_TIMEDELTA specified, must " \
+ "be zero or greater than one"
+#endif
+
+#if (CH_CFG_ST_TIMEDELTA > 0) && (CH_CFG_TIME_QUANTUM > 0)
+#error "CH_CFG_TIME_QUANTUM not supported in tickless mode"
+#endif
+
+#if (CH_CFG_ST_TIMEDELTA > 0) && CH_DBG_THREADS_PROFILING
+#error "CH_DBG_THREADS_PROFILING not supported in tickless mode"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @name Time conversion utilities
+ * @{
+ */
+/**
+ * @brief Seconds to system ticks.
+ * @details Converts from seconds to system ticks number.
+ * @note The result is rounded upward to the next tick boundary.
+ *
+ * @param[in] sec number of seconds
+ * @return The number of ticks.
+ *
+ * @api
+ */
+#define S2ST(sec) \
+ ((systime_t)((uint32_t)(sec) * (uint32_t)CH_CFG_ST_FREQUENCY))
+
+/**
+ * @brief Milliseconds to system ticks.
+ * @details Converts from milliseconds to system ticks number.
+ * @note The result is rounded upward to the next tick boundary.
+ *
+ * @param[in] msec number of milliseconds
+ * @return The number of ticks.
+ *
+ * @api
+ */
+#define MS2ST(msec) \
+ ((systime_t)(((((uint32_t)(msec)) * \
+ ((uint32_t)CH_CFG_ST_FREQUENCY) - 1UL) / 1000UL) + 1UL))
+
+/**
+ * @brief Microseconds to system ticks.
+ * @details Converts from microseconds to system ticks number.
+ * @note The result is rounded upward to the next tick boundary.
+ *
+ * @param[in] usec number of microseconds
+ * @return The number of ticks.
+ *
+ * @api
+ */
+#define US2ST(usec) \
+ ((systime_t)(((((uint32_t)(usec)) * \
+ ((uint32_t)CH_CFG_ST_FREQUENCY) - 1UL) / 1000000UL) + 1UL))
+
+/**
+ * @brief System ticks to seconds.
+ * @details Converts from system ticks number to seconds.
+ * @note The result is rounded up to the next second boundary.
+ *
+ * @param[in] n number of system ticks
+ * @return The number of seconds.
+ *
+ * @api
+ */
+#define ST2S(n) ((((n) - 1UL) / CH_CFG_ST_FREQUENCY) + 1UL)
+
+/**
+ * @brief System ticks to milliseconds.
+ * @details Converts from system ticks number to milliseconds.
+ * @note The result is rounded up to the next millisecond boundary.
+ *
+ * @param[in] n number of system ticks
+ * @return The number of milliseconds.
+ *
+ * @api
+ */
+#define ST2MS(n) ((((n) - 1UL) / (CH_CFG_ST_FREQUENCY / 1000UL)) + 1UL)
+
+/**
+ * @brief System ticks to microseconds.
+ * @details Converts from system ticks number to microseconds.
+ * @note The result is rounded up to the next microsecond boundary.
+ *
+ * @param[in] n number of system ticks
+ * @return The number of microseconds.
+ *
+ * @api
+ */
+#define ST2US(n) ((((n) - 1UL) / (CH_CFG_ST_FREQUENCY / 1000000UL)) + 1UL)
+/** @} */
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/*
+ * Virtual Timers APIs.
+ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _vt_init(void);
+ void chVTDoSetI(virtual_timer_t *vtp, systime_t delay,
+ vtfunc_t vtfunc, void *par);
+ void chVTDoResetI(virtual_timer_t *vtp);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes a @p virtual_timer_t object.
+ * @note Initializing a timer object is not strictly required because
+ * the function @p chVTSetI() initializes the object too. This
+ * function is only useful if you need to perform a @p chVTIsArmed()
+ * check before calling @p chVTSetI().
+ *
+ * @param[out] vtp the @p virtual_timer_t structure pointer
+ *
+ * @init
+ */
+static inline void chVTObjectInit(virtual_timer_t *vtp) {
+
+ vtp->vt_func = NULL;
+}
+
+/**
+ * @brief Current system time.
+ * @details Returns the number of system ticks since the @p chSysInit()
+ * invocation.
+ * @note The counter can reach its maximum and then restart from zero.
+ * @note This function can be called from any context but its atomicity
+ * is not guaranteed on architectures whose word size is less than
+ * @systime_t size.
+ *
+ * @return The system time in ticks.
+ *
+ * @xclass
+ */
+static inline systime_t chVTGetSystemTimeX(void) {
+
+#if CH_CFG_ST_TIMEDELTA == 0
+ return ch.vtlist.vt_systime;
+#else /* CH_CFG_ST_TIMEDELTA > 0 */
+ return port_timer_get_time();
+#endif /* CH_CFG_ST_TIMEDELTA > 0 */
+}
+
+/**
+ * @brief Current system time.
+ * @details Returns the number of system ticks since the @p chSysInit()
+ * invocation.
+ * @note The counter can reach its maximum and then restart from zero.
+ *
+ * @return The system time in ticks.
+ *
+ * @api
+ */
+static inline systime_t chVTGetSystemTime(void) {
+ systime_t systime;
+
+ chSysLock();
+ systime = chVTGetSystemTimeX();
+ chSysUnlock();
+ return systime;
+}
+
+/**
+ * @brief Returns the elapsed time since the specified start time.
+ *
+ * @param[in] start start time
+ * @return The elapsed time.
+ *
+ * @xclass
+ */
+static inline systime_t chVTTimeElapsedSinceX(systime_t start) {
+
+ return chVTGetSystemTimeX() - start;
+}
+
+/**
+ * @brief Checks if the specified time is within the specified time window.
+ * @note When start==end then the function returns always true because the
+ * whole time range is specified.
+ * @note This function can be called from any context.
+ *
+ * @param[in] time the time to be verified
+ * @param[in] start the start of the time window (inclusive)
+ * @param[in] end the end of the time window (non inclusive)
+ * @retval true current time within the specified time window.
+ * @retval false current time not within the specified time window.
+ *
+ * @xclass
+ */
+static inline bool chVTIsTimeWithinX(systime_t time,
+ systime_t start,
+ systime_t end) {
+
+ return (bool)(time - start < end - start);
+}
+
+/**
+ * @brief Checks if the current system time is within the specified time
+ * window.
+ * @note When start==end then the function returns always true because the
+ * whole time range is specified.
+ *
+ * @param[in] start the start of the time window (inclusive)
+ * @param[in] end the end of the time window (non inclusive)
+ * @retval true current time within the specified time window.
+ * @retval false current time not within the specified time window.
+ *
+ * @xclass
+ */
+static inline bool chVTIsSystemTimeWithinX(systime_t start, systime_t end) {
+
+ chDbgCheckClassI();
+
+ return chVTIsTimeWithinX(chVTGetSystemTimeX(), start, end);
+}
+
+/**
+ * @brief Checks if the current system time is within the specified time
+ * window.
+ * @note When start==end then the function returns always true because the
+ * whole time range is specified.
+ *
+ * @param[in] start the start of the time window (inclusive)
+ * @param[in] end the end of the time window (non inclusive)
+ * @retval true current time within the specified time window.
+ * @retval false current time not within the specified time window.
+ *
+ * @api
+ */
+static inline bool chVTIsSystemTimeWithin(systime_t start, systime_t end) {
+
+ return chVTIsTimeWithinX(chVTGetSystemTime(), start, end);
+}
+
+/**
+ * @brief Returns @p true if the specified timer is armed.
+ * @pre The timer must have been initialized using @p chVTObjectInit()
+ * or @p chVTDoSetI().
+ *
+ * @param[in] vtp the @p virtual_timer_t structure pointer
+ * @return true if the timer is armed.
+ *
+ * @iclass
+ */
+static inline bool chVTIsArmedI(virtual_timer_t *vtp) {
+
+ chDbgCheckClassI();
+
+ return (bool)(vtp->vt_func != NULL);
+}
+
+/**
+ * @brief Disables a Virtual Timer.
+ * @note The timer is first checked and disabled only if armed.
+ * @pre The timer must have been initialized using @p chVTObjectInit()
+ * or @p chVTDoSetI().
+ *
+ * @param[in] vtp the @p virtual_timer_t structure pointer
+ *
+ * @iclass
+ */
+static inline void chVTResetI(virtual_timer_t *vtp) {
+
+ if (chVTIsArmedI(vtp))
+ chVTDoResetI(vtp);
+}
+
+/**
+ * @brief Disables a Virtual Timer.
+ * @note The timer is first checked and disabled only if armed.
+ * @pre The timer must have been initialized using @p chVTObjectInit()
+ * or @p chVTDoSetI().
+ *
+ * @param[in] vtp the @p virtual_timer_t structure pointer
+ *
+ * @api
+ */
+static inline void chVTReset(virtual_timer_t *vtp) {
+
+ chSysLock();
+ chVTResetI(vtp);
+ chSysUnlock();
+}
+
+/**
+ * @brief Enables a virtual timer.
+ * @details If the virtual timer was already enabled then it is re-enabled
+ * using the new parameters.
+ * @pre The timer must have been initialized using @p chVTObjectInit()
+ * or @p chVTDoSetI().
+ *
+ * @param[in] vtp the @p virtual_timer_t structure pointer
+ * @param[in] delay the number of ticks before the operation timeouts, the
+ * special values are handled as follow:
+ * - @a TIME_INFINITE is allowed but interpreted as a
+ * normal time specification.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ * @param[in] vtfunc the timer callback function. After invoking the
+ * callback the timer is disabled and the structure can
+ * be disposed or reused.
+ * @param[in] par a parameter that will be passed to the callback
+ * function
+ *
+ * @iclass
+ */
+static inline void chVTSetI(virtual_timer_t *vtp, systime_t delay,
+ vtfunc_t vtfunc, void *par) {
+
+ chVTResetI(vtp);
+ chVTDoSetI(vtp, delay, vtfunc, par);
+}
+
+/**
+ * @brief Enables a virtual timer.
+ * @details If the virtual timer was already enabled then it is re-enabled
+ * using the new parameters.
+ * @pre The timer must have been initialized using @p chVTObjectInit()
+ * or @p chVTDoSetI().
+ *
+ * @param[in] vtp the @p virtual_timer_t structure pointer
+ * @param[in] delay the number of ticks before the operation timeouts, the
+ * special values are handled as follow:
+ * - @a TIME_INFINITE is allowed but interpreted as a
+ * normal time specification.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ * @param[in] vtfunc the timer callback function. After invoking the
+ * callback the timer is disabled and the structure can
+ * be disposed or reused.
+ * @param[in] par a parameter that will be passed to the callback
+ * function
+ *
+ * @api
+ */
+static inline void chVTSet(virtual_timer_t *vtp, systime_t delay,
+ vtfunc_t vtfunc, void *par) {
+
+ chSysLock();
+ chVTSetI(vtp, delay, vtfunc, par);
+ chSysUnlock();
+}
+
+/**
+ * @brief Virtual timers ticker.
+ * @note The system lock is released before entering the callback and
+ * re-acquired immediately after. It is callback's responsibility
+ * to acquire the lock if needed. This is done in order to reduce
+ * interrupts jitter when many timers are in use.
+ *
+ * @iclass
+ */
+static inline void chVTDoTickI(void) {
+
+ chDbgCheckClassI();
+
+#if CH_CFG_ST_TIMEDELTA == 0
+ ch.vtlist.vt_systime++;
+ if (&ch.vtlist != (virtual_timers_list_t *)ch.vtlist.vt_next) {
+ virtual_timer_t *vtp;
+
+ --ch.vtlist.vt_next->vt_delta;
+ while (!(vtp = ch.vtlist.vt_next)->vt_delta) {
+ vtfunc_t fn = vtp->vt_func;
+ vtp->vt_func = (vtfunc_t)NULL;
+ vtp->vt_next->vt_prev = (virtual_timer_t *)&ch.vtlist;
+ ch.vtlist.vt_next = vtp->vt_next;
+ chSysUnlockFromISR();
+ fn(vtp->vt_par);
+ chSysLockFromISR();
+ }
+ }
+#else /* CH_CFG_ST_TIMEDELTA > 0 */
+ virtual_timer_t *vtp;
+ systime_t now = chVTGetSystemTimeX();
+ systime_t delta = now - ch.vtlist.vt_lasttime;
+
+ while ((vtp = ch.vtlist.vt_next)->vt_delta <= delta) {
+ delta -= vtp->vt_delta;
+ ch.vtlist.vt_lasttime += vtp->vt_delta;
+ vtfunc_t fn = vtp->vt_func;
+ vtp->vt_func = (vtfunc_t)NULL;
+ vtp->vt_next->vt_prev = (virtual_timer_t *)&ch.vtlist;
+ ch.vtlist.vt_next = vtp->vt_next;
+ chSysUnlockFromISR();
+ fn(vtp->vt_par);
+ chSysLockFromISR();
+ }
+ if (&ch.vtlist == (virtual_timers_list_t *)ch.vtlist.vt_next) {
+ /* The list is empty, no tick event needed so the alarm timer
+ is stopped.*/
+ port_timer_stop_alarm();
+ }
+ else {
+ /* Updating the alarm to the next deadline.*/
+ port_timer_set_alarm(now + vtp->vt_delta);
+ }
+#endif /* CH_CFG_ST_TIMEDELTA > 0 */
+}
+
+#endif /* _CHVT_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore.c b/os/rt/ports/ARMCMx/chcore.c new file mode 100644 index 000000000..c66ce160c --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore.c @@ -0,0 +1,55 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ARMCMx/chcore.c
+ * @brief ARM Cortex-Mx port code.
+ *
+ * @addtogroup ARMCMx_CORE
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore.h b/os/rt/ports/ARMCMx/chcore.h new file mode 100644 index 000000000..0e5ed6933 --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore.h @@ -0,0 +1,255 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ARMCMx/chcore.h
+ * @brief ARM Cortex-Mx port macros and structures.
+ *
+ * @addtogroup ARMCMx_CORE
+ * @{
+ */
+
+#ifndef _CHCORE_H_
+#define _CHCORE_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Architecture and Compiler
+ * @{
+ */
+/**
+ * @brief Macro defining a generic ARM architecture.
+ */
+#define PORT_ARCHITECTURE_ARM
+
+/* The following code is not processed when the file is included from an
+ asm module because those intrinsic macros are not necessarily defined
+ by the assembler too.*/
+#if !defined(_FROM_ASM_)
+
+/**
+ * @brief Compiler name and version.
+ */
+#if defined(__GNUC__) || defined(__DOXYGEN__)
+#define PORT_COMPILER_NAME "GCC " __VERSION__
+
+#elif defined(__ICCARM__)
+#define PORT_COMPILER_NAME "IAR"
+
+#elif defined(__CC_ARM)
+#define PORT_COMPILER_NAME "RVCT"
+
+#else
+#error "unsupported compiler"
+#endif
+
+#endif /* !defined(_FROM_ASM_) */
+
+/** @} */
+
+/**
+ * @name Cortex-M variants
+ * @{
+ */
+#define CORTEX_M0 0 /**< @brief Cortex-M0 variant. */
+#define CORTEX_M0PLUS 1 /**< @brief Cortex-M0+ variant. */
+#define CORTEX_M1 2 /**< @brief Cortex-M1 variant. */
+#define CORTEX_M3 3 /**< @brief Cortex-M3 variant. */
+#define CORTEX_M4 4 /**< @brief Cortex-M4 variant. */
+/** @} */
+
+/* Inclusion of the Cortex-Mx implementation specific parameters.*/
+#include "cmparams.h"
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/**
+ * @brief Enables an alternative timer implementation.
+ * @details Usually the port uses a timer interface defined in the file
+ * @p chcore_timer.h, if this option is enabled then the file
+ * @p chcore_timer_alt.h is included instead.
+ */
+#if !defined(PORT_USE_ALT_TIMER)
+#define PORT_USE_ALT_TIMER FALSE
+#endif
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/* The following code is not processed when the file is included from an
+ asm module.*/
+#if !defined(_FROM_ASM_)
+
+/*
+ * Inclusion of the appropriate CMSIS header for the selected device.
+ */
+#if CORTEX_MODEL == CORTEX_M0
+#include "core_cm0.h"
+#elif CORTEX_MODEL == CORTEX_M0PLUS
+#include "core_cm0plus.h"
+#elif CORTEX_MODEL == CORTEX_M3
+#include "core_cm3.h"
+#elif CORTEX_MODEL == CORTEX_M4
+#include "core_cm4.h"
+#else
+#error "unknown or unsupported Cortex-M model"
+#endif
+
+#endif /* !defined(_FROM_ASM_) */
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/* The following code is not processed when the file is included from an
+ asm module.*/
+#if !defined(_FROM_ASM_)
+
+/**
+ * @brief Type of system time.
+ */
+#if (CH_CFG_ST_RESOLUTION == 32) || defined(__DOXYGEN__)
+typedef uint32_t systime_t;
+#else
+typedef uint16_t systime_t;
+#endif
+
+/**
+ * @brief Type of a generic ARM register.
+ */
+typedef void *regarm_t;
+
+/**
+ * @brief Type of stack and memory alignment enforcement.
+ * @note In this architecture the stack alignment is enforced to 64 bits,
+ * 32 bits alignment is supported by hardware but deprecated by ARM,
+ * the implementation choice is to not offer the option.
+ */
+typedef uint64_t stkalign_t;
+
+/* The following declarations are there just for Doxygen documentation, the
+ real declarations are inside the sub-headers being specific for the
+ sub-architectures.*/
+#if defined(__DOXYGEN__)
+/**
+ * @brief Interrupt saved context.
+ * @details This structure represents the stack frame saved during a
+ * preemption-capable interrupt handler.
+ * @note It is implemented to match the Cortex-Mx exception context.
+ */
+struct port_extctx {};
+
+/**
+ * @brief System saved context.
+ * @details This structure represents the inner stack frame during a context
+ * switching.
+ */
+struct port_intctx {};
+#endif /* defined(__DOXYGEN__) */
+
+/**
+ * @brief Platform dependent part of the @p thread_t structure.
+ * @details In this port the structure just holds a pointer to the
+ * @p port_intctx structure representing the stack pointer
+ * at context switch time.
+ */
+struct context {
+ struct port_intctx *r13;
+};
+
+#endif /* !defined(_FROM_ASM_) */
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Total priority levels.
+ */
+#define CORTEX_PRIORITY_LEVELS (1 << CORTEX_PRIORITY_BITS)
+
+/**
+ * @brief Minimum priority level.
+ * @details This minimum priority level is calculated from the number of
+ * priority bits supported by the specific Cortex-Mx implementation.
+ */
+#define CORTEX_MINIMUM_PRIORITY (CORTEX_PRIORITY_LEVELS - 1)
+
+/**
+ * @brief Maximum priority level.
+ * @details The maximum allowed priority level is always zero.
+ */
+#define CORTEX_MAXIMUM_PRIORITY 0
+
+/**
+ * @brief Priority level verification macro.
+ */
+#define CORTEX_IS_VALID_PRIORITY(n) \
+ (((n) >= 0) && ((n) < CORTEX_PRIORITY_LEVELS))
+
+/**
+ * @brief Priority level verification macro.
+ */
+#define CORTEX_IS_VALID_KERNEL_PRIORITY(n) \
+ (((n) >= CORTEX_MAX_KERNEL_PRIORITY) && ((n) < CORTEX_PRIORITY_LEVELS))
+
+/**
+ * @brief Priority level to priority mask conversion macro.
+ */
+#define CORTEX_PRIO_MASK(n) \
+ ((n) << (8 - CORTEX_PRIORITY_BITS))
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/* Includes the sub-architecture-specific part.*/
+#if (CORTEX_MODEL == CORTEX_M0) || (CORTEX_MODEL == CORTEX_M0PLUS) || \
+ (CORTEX_MODEL == CORTEX_M1)
+#include "chcore_v6m.h"
+#elif (CORTEX_MODEL == CORTEX_M3) || (CORTEX_MODEL == CORTEX_M4)
+#include "chcore_v7m.h"
+#endif
+
+#if !defined(_FROM_ASM_)
+
+#if CH_CFG_ST_TIMEDELTA > 0
+#if !PORT_USE_ALT_TIMER
+#include "chcore_timer.h"
+#else /* PORT_USE_ALT_TIMER */
+#include "chcore_timer_alt.h"
+#endif /* PORT_USE_ALT_TIMER */
+#endif /* CH_CFG_ST_TIMEDELTA > 0 */
+
+#endif /* !defined(_FROM_ASM_) */
+
+#endif /* _CHCORE_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore_timer.h b/os/rt/ports/ARMCMx/chcore_timer.h new file mode 100644 index 000000000..8df7ac97e --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore_timer.h @@ -0,0 +1,125 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chcore_timer.h
+ * @brief System timer header file.
+ *
+ * @addtogroup ARMCMx_TIMER
+ * @{
+ */
+
+#ifndef _CHCORE_TIMER_H_
+#define _CHCORE_TIMER_H_
+
+/* This is the only header in the HAL designed to be include-able alone.*/
+#include "st.h"
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Starts the alarm.
+ * @note Makes sure that no spurious alarms are triggered after
+ * this call.
+ *
+ * @param[in] time the time to be set for the first alarm
+ *
+ * @notapi
+ */
+static inline void port_timer_start_alarm(systime_t time) {
+
+ stStartAlarm(time);
+}
+
+/**
+ * @brief Stops the alarm interrupt.
+ *
+ * @notapi
+ */
+static inline void port_timer_stop_alarm(void) {
+
+ stStopAlarm();
+}
+
+/**
+ * @brief Sets the alarm time.
+ *
+ * @param[in] time the time to be set for the next alarm
+ *
+ * @notapi
+ */
+static inline void port_timer_set_alarm(systime_t time) {
+
+ stSetAlarm(time);
+}
+
+/**
+ * @brief Returns the system time.
+ *
+ * @return The system time.
+ *
+ * @notapi
+ */
+static inline systime_t port_timer_get_time(void) {
+
+ return stGetCounter();
+}
+
+/**
+ * @brief Returns the current alarm time.
+ *
+ * @return The currently set alarm time.
+ *
+ * @notapi
+ */
+static inline systime_t port_timer_get_alarm(void) {
+
+ return stGetAlarm();
+}
+
+#endif /* _CHCORE_TIMER_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore_v6m.c b/os/rt/ports/ARMCMx/chcore_v6m.c new file mode 100644 index 000000000..9548c2a8e --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore_v6m.c @@ -0,0 +1,144 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chcore_v6m.c
+ * @brief ARMv6-M architecture port code.
+ *
+ * @addtogroup ARMCMx_V6M_CORE
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module interrupt handlers. */
+/*===========================================================================*/
+
+#if !CORTEX_ALTERNATE_SWITCH || defined(__DOXYGEN__)
+/**
+ * @brief NMI vector.
+ * @details The NMI vector is used for exception mode re-entering after a
+ * context switch.
+ */
+void NMI_Handler(void) {
+
+ /* The port_extctx structure is pointed by the PSP register.*/
+ struct port_extctx *ctxp = (struct port_extctx *)__get_PSP();
+
+ /* Discarding the current exception context and positioning the stack to
+ point to the real one.*/
+ ctxp++;
+
+ /* Writing back the modified PSP value.*/
+ __set_PSP((uint32_t)ctxp);
+
+ /* Restoring the normal interrupts status.*/
+ port_unlock_from_isr();
+}
+#endif /* !CORTEX_ALTERNATE_SWITCH */
+
+#if CORTEX_ALTERNATE_SWITCH || defined(__DOXYGEN__)
+/**
+ * @brief PendSV vector.
+ * @details The PendSV vector is used for exception mode re-entering after a
+ * context switch.
+ */
+void PendSV_Handler(void) {
+
+ /* The port_extctx structure is pointed by the PSP register.*/
+ struct port_extctx *ctxp = (struct port_extctx *)__get_PSP();
+
+ /* Discarding the current exception context and positioning the stack to
+ point to the real one.*/
+ ctxp++;
+
+ /* Writing back the modified PSP value.*/
+ __set_PSP((uint32_t)ctxp);
+}
+#endif /* CORTEX_ALTERNATE_SWITCH */
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief IRQ epilogue code.
+ *
+ * @param[in] lr value of the @p LR register on ISR entry
+ */
+void _port_irq_epilogue(regarm_t lr) {
+
+ if (lr != (regarm_t)0xFFFFFFF1) {
+ struct port_extctx *ctxp;
+
+ port_lock_from_isr();
+
+ /* The extctx structure is pointed by the PSP register.*/
+ ctxp = (struct port_extctx *)__get_PSP();
+
+ /* Adding an artificial exception return context, there is no need to
+ populate it fully.*/
+ ctxp--;
+
+ /* Writing back the modified PSP value.*/
+ __set_PSP((uint32_t)ctxp);
+
+ /* Setting up a fake XPSR register value.*/
+ ctxp->xpsr = (regarm_t)0x01000000;
+
+ /* The exit sequence is different depending on if a preemption is
+ required or not.*/
+ if (chSchIsPreemptionRequired()) {
+ /* Preemption is required we need to enforce a context switch.*/
+ ctxp->pc = (regarm_t)_port_switch_from_isr;
+ }
+ else {
+ /* Preemption not required, we just need to exit the exception
+ atomically.*/
+ ctxp->pc = (regarm_t)_port_exit_from_isr;
+ }
+
+ /* Note, returning without unlocking is intentional, this is done in
+ order to keep the rest of the context switch atomic.*/
+ }
+}
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore_v6m.h b/os/rt/ports/ARMCMx/chcore_v6m.h new file mode 100644 index 000000000..7e74df03f --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore_v6m.h @@ -0,0 +1,406 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chcore_v6m.h
+ * @brief ARMv6-M architecture port macros and structures.
+ *
+ * @addtogroup ARMCMx_V6M_CORE
+ * @{
+ */
+
+#ifndef _CHCORE_V6M_H_
+#define _CHCORE_V6M_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Architecture and Compiler
+ * @{
+ */
+#if (CORTEX_MODEL == CORTEX_M0) || defined(__DOXYGEN__)
+/**
+ * @brief Macro defining the specific ARM architecture.
+ */
+#define PORT_ARCHITECTURE_ARM_v6M
+
+/**
+ * @brief Name of the implemented architecture.
+ */
+#define PORT_ARCHITECTURE_NAME "ARMv6-M"
+
+/**
+ * @brief Name of the architecture variant.
+ */
+#define PORT_CORE_VARIANT_NAME "Cortex-M0"
+
+#elif (CORTEX_MODEL == CORTEX_M0PLUS)
+#define PORT_ARCHITECTURE_ARM_v6M
+#define PORT_ARCHITECTURE_NAME "ARMv6-M"
+#define PORT_CORE_VARIANT_NAME "Cortex-M0+"
+#endif
+
+/**
+ * @brief Port-specific information string.
+ */
+#if !CORTEX_ALTERNATE_SWITCH || defined(__DOXYGEN__)
+#define PORT_INFO "Preemption through NMI"
+#else
+#define PORT_INFO "Preemption through PendSV"
+#endif
+/** @} */
+
+/**
+ * @brief This port does not support a realtime counter.
+ */
+#define PORT_SUPPORTS_RT FALSE
+
+/**
+ * @brief PendSV priority level.
+ * @note This priority is enforced to be equal to @p 0,
+ * this handler always has the highest priority that cannot preempt
+ * the kernel.
+ */
+#define CORTEX_PRIORITY_PENDSV 0
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/**
+ * @brief Stack size for the system idle thread.
+ * @details This size depends on the idle thread implementation, usually
+ * the idle thread should take no more space than those reserved
+ * by @p PORT_INT_REQUIRED_STACK.
+ * @note In this port it is set to 16 because the idle thread does have
+ * a stack frame when compiling without optimizations. You may
+ * reduce this value to zero when compiling with optimizations.
+ */
+#if !defined(PORT_IDLE_THREAD_STACK_SIZE)
+#define PORT_IDLE_THREAD_STACK_SIZE 16
+#endif
+
+/**
+ * @brief Per-thread stack overhead for interrupts servicing.
+ * @details This constant is used in the calculation of the correct working
+ * area size.
+ * @note In this port this value is conservatively set to 64 because the
+ * function @p chSchDoReschedule() can have a stack frame, especially
+ * with compiler optimizations disabled. The value can be reduced
+ * when compiler optimizations are enabled.
+ */
+#if !defined(PORT_INT_REQUIRED_STACK)
+#define PORT_INT_REQUIRED_STACK 64
+#endif
+
+/**
+ * @brief Enables the use of the WFI instruction in the idle thread loop.
+ */
+#if !defined(CORTEX_ENABLE_WFI_IDLE)
+#define CORTEX_ENABLE_WFI_IDLE FALSE
+#endif
+
+/**
+ * @brief Alternate preemption method.
+ * @details Activating this option will make the Kernel use the PendSV
+ * handler for preemption instead of the NMI handler.
+ */
+#ifndef CORTEX_ALTERNATE_SWITCH
+#define CORTEX_ALTERNATE_SWITCH FALSE
+#endif
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/**
+ * @brief Maximum usable priority for normal ISRs.
+ */
+#if CORTEX_ALTERNATE_SWITCH || defined(__DOXYGEN__)
+#define CORTEX_MAX_KERNEL_PRIORITY 1
+#else
+#define CORTEX_MAX_KERNEL_PRIORITY 0
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+#if !defined(_FROM_ASM_)
+
+ /* The documentation of the following declarations is in chconf.h in order
+ to not have duplicated structure names into the documentation.*/
+#if !defined(__DOXYGEN__)
+struct port_extctx {
+ regarm_t r0;
+ regarm_t r1;
+ regarm_t r2;
+ regarm_t r3;
+ regarm_t r12;
+ regarm_t lr_thd;
+ regarm_t pc;
+ regarm_t xpsr;
+};
+
+struct port_intctx {
+ regarm_t r8;
+ regarm_t r9;
+ regarm_t r10;
+ regarm_t r11;
+ regarm_t r4;
+ regarm_t r5;
+ regarm_t r6;
+ regarm_t r7;
+ regarm_t lr;
+};
+#endif /* !defined(__DOXYGEN__) */
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Platform dependent part of the @p chThdCreateI() API.
+ * @details This code usually setup the context switching frame represented
+ * by an @p port_intctx structure.
+ */
+#define PORT_SETUP_CONTEXT(tp, workspace, wsize, pf, arg) { \
+ (tp)->p_ctx.r13 = (struct port_intctx *)((uint8_t *)(workspace) + \
+ (wsize) - \
+ sizeof(struct port_intctx)); \
+ (tp)->p_ctx.r13->r4 = (regarm_t)(pf); \
+ (tp)->p_ctx.r13->r5 = (regarm_t)(arg); \
+ (tp)->p_ctx.r13->lr = (regarm_t)(_port_thread_start); \
+}
+
+/**
+ * @brief Computes the thread working area global size.
+ * @note There is no need to perform alignments in this macro.
+ */
+#define PORT_WA_SIZE(n) (sizeof(struct port_intctx) + \
+ sizeof(struct port_extctx) + \
+ (n) + (PORT_INT_REQUIRED_STACK))
+
+/**
+ * @brief IRQ prologue code.
+ * @details This macro must be inserted at the start of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#if defined(__GNUC__) || defined(__DOXYGEN__)
+#define PORT_IRQ_PROLOGUE() \
+ regarm_t _saved_lr = (regarm_t)__builtin_return_address(0)
+#elif defined(__ICCARM__)
+#define PORT_IRQ_PROLOGUE() \
+ regarm_t _saved_lr = (regarm_t)__get_LR()
+#elif defined(__CC_ARM)
+#define PORT_IRQ_PROLOGUE() \
+ regarm_t _saved_lr = (regarm_t)__return_address()
+#endif
+
+/**
+ * @brief IRQ epilogue code.
+ * @details This macro must be inserted at the end of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_EPILOGUE() _port_irq_epilogue(_saved_lr)
+
+/**
+ * @brief IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Fast IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_FAST_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Performs a context switch between two threads.
+ * @details This is the most critical code in any port, this function
+ * is responsible for the context switch between 2 threads.
+ * @note The implementation of this code affects <b>directly</b> the context
+ * switch performance so optimize here as much as you can.
+ *
+ * @param[in] ntp the thread to be switched in
+ * @param[in] otp the thread to be switched out
+ */
+#if !CH_DBG_ENABLE_STACK_CHECK || defined(__DOXYGEN__)
+#define port_switch(ntp, otp) _port_switch(ntp, otp)
+#else
+#define port_switch(ntp, otp) { \
+ struct port_intctx *r13 = (struct port_intctx *)__get_PSP(); \
+ if ((stkalign_t *)(r13 - 1) < (otp)->p_stklimit) \
+ chSysHalt("stack overflow"); \
+ _port_switch(ntp, otp); \
+}
+#endif
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _port_irq_epilogue(regarm_t lr);
+ void _port_switch(thread_t *ntp, thread_t *otp);
+ void _port_thread_start(void);
+ void _port_switch_from_isr(void);
+ void _port_exit_from_isr(void);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Port-related initialization code.
+ */
+static inline void port_init(void) {
+
+ NVIC_SetPriority(PendSV_IRQn, CORTEX_PRIORITY_PENDSV);
+}
+
+/**
+ * @brief Returns a word encoding the current interrupts status.
+ *
+ * @return The interrupts status.
+ */
+static inline syssts_t port_get_irq_status(void) {
+
+ return __get_PRIMASK();
+}
+
+/**
+ * @brief Checks the interrupt status.
+ *
+ * @param[in] sts the interrupt status word
+ *
+ * @return The interrupt status.
+ * @retvel false the word specified a disabled interrupts status.
+ * @retvel true the word specified an enabled interrupts status.
+ */
+static inline bool port_irq_enabled(syssts_t sts) {
+
+ return (sts & 1) == 0;
+}
+
+/**
+ * @brief Determines the current execution context.
+ *
+ * @return The execution context.
+ * @retval false not running in ISR mode.
+ * @retval true running in ISR mode.
+ */
+static inline bool port_is_isr_context(void) {
+
+ return (bool)((__get_IPSR() & 0x1FF) != 0);
+}
+
+/**
+ * @brief Kernel-lock action.
+ * @details In this port this function disables interrupts globally.
+ */
+static inline void port_lock(void) {
+
+ __disable_irq();
+}
+
+/**
+ * @brief Kernel-unlock action.
+ * @details In this port this function enables interrupts globally.
+ */
+static inline void port_unlock(void) {
+
+ __enable_irq();
+}
+
+/**
+ * @brief Kernel-lock action from an interrupt handler.
+ * @details In this port this function disables interrupts globally.
+ * @note Same as @p port_lock() in this port.
+ */
+static inline void port_lock_from_isr(void) {
+
+ port_lock();
+}
+
+/**
+ * @brief Kernel-unlock action from an interrupt handler.
+ * @details In this port this function enables interrupts globally.
+ * @note Same as @p port_lock() in this port.
+ */
+static inline void port_unlock_from_isr(void) {
+
+ port_unlock();
+}
+
+/**
+ * @brief Disables all the interrupt sources.
+ */
+static inline void port_disable(void) {
+
+ __disable_irq();
+}
+
+/**
+ * @brief Disables the interrupt sources below kernel-level priority.
+ */
+static inline void port_suspend(void) {
+
+ __disable_irq();
+}
+
+/**
+ * @brief Enables all the interrupt sources.
+ */
+static inline void port_enable(void) {
+
+ __enable_irq();
+}
+
+/**
+ * @brief Enters an architecture-dependent IRQ-waiting mode.
+ * @details The function is meant to return when an interrupt becomes pending.
+ * The simplest implementation is an empty function or macro but this
+ * would not take advantage of architecture-specific power saving
+ * modes.
+ * @note Implemented as an inlined @p WFI instruction.
+ */
+static inline void port_wait_for_interrupt(void) {
+
+#if CORTEX_ENABLE_WFI_IDLE
+ __WFI();
+#endif
+}
+
+#endif /* _FROM_ASM_ */
+
+#endif /* _CHCORE_V6M_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore_v7m.c b/os/rt/ports/ARMCMx/chcore_v7m.c new file mode 100644 index 000000000..29add3fb1 --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore_v7m.c @@ -0,0 +1,174 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chcore_v7m.c
+ * @brief ARMv7-M architecture port code.
+ *
+ * @addtogroup ARMCMx_V7M_CORE
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module interrupt handlers. */
+/*===========================================================================*/
+
+#if !CORTEX_SIMPLIFIED_PRIORITY || defined(__DOXYGEN__)
+/**
+ * @brief SVC vector.
+ * @details The SVC vector is used for exception mode re-entering after a
+ * context switch.
+ * @note The PendSV vector is only used in advanced kernel mode.
+ */
+void SVC_Handler(void) {
+
+ /* The port_extctx structure is pointed by the PSP register.*/
+ struct port_extctx *ctxp = (struct port_extctx *)__get_PSP();
+
+ /* Discarding the current exception context and positioning the stack to
+ point to the real one.*/
+ ctxp++;
+
+#if CORTEX_USE_FPU
+ /* Restoring the special register FPCCR.*/
+ FPU->FPCCR = (uint32_t)ctxp->fpccr;
+ FPU->FPCAR = FPU->FPCAR + sizeof (struct port_extctx);
+#endif
+
+ /* Writing back the modified PSP value.*/
+ __set_PSP((uint32_t)ctxp);
+
+ /* Restoring the normal interrupts status.*/
+ port_unlock_from_isr();
+}
+#endif /* !CORTEX_SIMPLIFIED_PRIORITY */
+
+#if CORTEX_SIMPLIFIED_PRIORITY || defined(__DOXYGEN__)
+/**
+ * @brief PendSV vector.
+ * @details The PendSV vector is used for exception mode re-entering after a
+ * context switch.
+ * @note The PendSV vector is only used in compact kernel mode.
+ */
+void PendSV_Handler(void) {
+
+ /* The port_extctx structure is pointed by the PSP register.*/
+ struct port_extctx *ctxp = (struct port_extctx *)__get_PSP();
+
+ /* Discarding the current exception context and positioning the stack to
+ point to the real one.*/
+ ctxp++;
+
+#if CORTEX_USE_FPU
+ /* Restoring the special register FPCCR.*/
+ FPU->FPCCR = (uint32_t)ctxp->fpccr;
+ FPU->FPCAR = FPU->FPCAR + sizeof (struct port_extctx);
+#endif
+
+ /* Writing back the modified PSP value.*/
+ __set_PSP((uint32_t)ctxp);
+}
+#endif /* CORTEX_SIMPLIFIED_PRIORITY */
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Exception exit redirection to _port_switch_from_isr().
+ */
+void _port_irq_epilogue(void) {
+
+ port_lock_from_isr();
+ if ((SCB->ICSR & SCB_ICSR_RETTOBASE_Msk) != 0) {
+
+ /* The port_extctx structure is pointed by the PSP register.*/
+ struct port_extctx *ctxp = (struct port_extctx *)__get_PSP();
+
+ /* Adding an artificial exception return context, there is no need to
+ populate it fully.*/
+ ctxp--;
+
+ /* Writing back the modified PSP value.*/
+ __set_PSP((uint32_t)ctxp);
+
+ /* Setting up a fake XPSR register value.*/
+ ctxp->xpsr = (regarm_t)0x01000000;
+
+ /* The exit sequence is different depending on if a preemption is
+ required or not.*/
+ if (chSchIsPreemptionRequired()) {
+ /* Preemption is required we need to enforce a context switch.*/
+ ctxp->pc = (regarm_t)_port_switch_from_isr;
+#if CORTEX_USE_FPU
+ /* Enforcing a lazy FPU state save by accessing the FPCSR register.*/
+ (void) __get_FPSCR();
+#endif
+ }
+ else {
+ /* Preemption not required, we just need to exit the exception
+ atomically.*/
+ ctxp->pc = (regarm_t)_port_exit_from_isr;
+ }
+
+#if CORTEX_USE_FPU
+ {
+ uint32_t fpccr;
+
+ /* Saving the special register SCB_FPCCR into the reserved offset of
+ the Cortex-M4 exception frame.*/
+ (ctxp + 1)->fpccr = (regarm_t)(fpccr = FPU->FPCCR);
+
+ /* Now the FPCCR is modified in order to not restore the FPU status
+ from the artificial return context.*/
+ FPU->FPCCR = fpccr | FPU_FPCCR_LSPACT_Msk;
+ }
+#endif
+
+ /* Note, returning without unlocking is intentional, this is done in
+ order to keep the rest of the context switch atomic.*/
+ return;
+ }
+ port_unlock_from_isr();
+}
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/chcore_v7m.h b/os/rt/ports/ARMCMx/chcore_v7m.h new file mode 100644 index 000000000..db8d71d92 --- /dev/null +++ b/os/rt/ports/ARMCMx/chcore_v7m.h @@ -0,0 +1,555 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chcore_v7m.h
+ * @brief ARMv7-M architecture port macros and structures.
+ *
+ * @addtogroup ARMCMx_V7M_CORE
+ * @{
+ */
+
+#ifndef _CHCORE_V7M_H_
+#define _CHCORE_V7M_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Architecture and Compiler
+ * @{
+ */
+#if (CORTEX_MODEL == CORTEX_M3) || defined(__DOXYGEN__)
+/**
+ * @brief Macro defining the specific ARM architecture.
+ */
+#define PORT_ARCHITECTURE_ARM_v7M
+
+/**
+ * @brief Name of the implemented architecture.
+ */
+#define PORT_ARCHITECTURE_NAME "ARMv7-M"
+
+/**
+ * @brief Name of the architecture variant.
+ */
+#define PORT_CORE_VARIANT_NAME "Cortex-M3"
+
+#elif (CORTEX_MODEL == CORTEX_M4)
+#define PORT_ARCHITECTURE_ARM_v7ME
+#define PORT_ARCHITECTURE_NAME "ARMv7-ME"
+#if CORTEX_USE_FPU
+#define PORT_CORE_VARIANT_NAME "Cortex-M4F"
+#else
+#define PORT_CORE_VARIANT_NAME "Cortex-M4"
+#endif
+#endif
+
+/**
+ * @brief Port-specific information string.
+ */
+#if !CORTEX_SIMPLIFIED_PRIORITY || defined(__DOXYGEN__)
+#define PORT_INFO "Advanced kernel mode"
+#else
+#define PORT_INFO "Compact kernel mode"
+#endif
+/** @} */
+
+/**
+ * @brief This port supports a realtime counter.
+ */
+#define PORT_SUPPORTS_RT TRUE
+
+/**
+ * @brief Disabled value for BASEPRI register.
+ */
+#define CORTEX_BASEPRI_DISABLED 0
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/**
+ * @brief Stack size for the system idle thread.
+ * @details This size depends on the idle thread implementation, usually
+ * the idle thread should take no more space than those reserved
+ * by @p PORT_INT_REQUIRED_STACK.
+ * @note In this port it is set to 16 because the idle thread does have
+ * a stack frame when compiling without optimizations. You may
+ * reduce this value to zero when compiling with optimizations.
+ */
+#if !defined(PORT_IDLE_THREAD_STACK_SIZE) || defined(__DOXYGEN__)
+#define PORT_IDLE_THREAD_STACK_SIZE 16
+#endif
+
+/**
+ * @brief Per-thread stack overhead for interrupts servicing.
+ * @details This constant is used in the calculation of the correct working
+ * area size.
+ * @note In this port this value is conservatively set to 64 because the
+ * function @p chSchDoReschedule() can have a stack frame, especially
+ * with compiler optimizations disabled. The value can be reduced
+ * when compiler optimizations are enabled.
+ */
+#if !defined(PORT_INT_REQUIRED_STACK) || defined(__DOXYGEN__)
+#define PORT_INT_REQUIRED_STACK 64
+#endif
+
+/**
+ * @brief Enables the use of the WFI instruction in the idle thread loop.
+ */
+#if !defined(CORTEX_ENABLE_WFI_IDLE)
+#define CORTEX_ENABLE_WFI_IDLE FALSE
+#endif
+
+/**
+ * @brief FPU support in context switch.
+ * @details Activating this option activates the FPU support in the kernel.
+ */
+#if !defined(CORTEX_USE_FPU)
+#define CORTEX_USE_FPU CORTEX_HAS_FPU
+#elif CORTEX_USE_FPU && !CORTEX_HAS_FPU
+/* This setting requires an FPU presence check in case it is externally
+ redefined.*/
+#error "the selected core does not have an FPU"
+#endif
+
+/**
+ * @brief Simplified priority handling flag.
+ * @details Activating this option makes the Kernel work in compact mode.
+ * In compact mode interrupts are disabled globally instead of
+ * raising the priority mask to some intermediate level.
+ */
+#if !defined(CORTEX_SIMPLIFIED_PRIORITY)
+#define CORTEX_SIMPLIFIED_PRIORITY FALSE
+#endif
+
+/**
+ * @brief SVCALL handler priority.
+ * @note The default SVCALL handler priority is defaulted to
+ * @p CORTEX_MAXIMUM_PRIORITY+1, this reserves the
+ * @p CORTEX_MAXIMUM_PRIORITY priority level as fast interrupts
+ * priority level.
+ */
+#if !defined(CORTEX_PRIORITY_SVCALL)
+#define CORTEX_PRIORITY_SVCALL (CORTEX_MAXIMUM_PRIORITY + 1)
+#elif !CORTEX_IS_VALID_PRIORITY(CORTEX_PRIORITY_SVCALL)
+/* If it is externally redefined then better perform a validity check on it.*/
+#error "invalid priority level specified for CORTEX_PRIORITY_SVCALL"
+#endif
+
+/**
+ * @brief NVIC VTOR initialization expression.
+ */
+#if !defined(CORTEX_VTOR_INIT) || defined(__DOXYGEN__)
+#define CORTEX_VTOR_INIT 0x00000000
+#endif
+
+/**
+ * @brief NVIC PRIGROUP initialization expression.
+ * @details The default assigns all available priority bits as preemption
+ * priority with no sub-priority.
+ */
+#if !defined(CORTEX_PRIGROUP_INIT) || defined(__DOXYGEN__)
+#define CORTEX_PRIGROUP_INIT (7 - CORTEX_PRIORITY_BITS)
+#endif
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if !CORTEX_SIMPLIFIED_PRIORITY || defined(__DOXYGEN__)
+/**
+ * @brief Maximum usable priority for normal ISRs.
+ */
+#define CORTEX_MAX_KERNEL_PRIORITY (CORTEX_PRIORITY_SVCALL + 1)
+
+/**
+ * @brief BASEPRI level within kernel lock.
+ */
+#define CORTEX_BASEPRI_KERNEL \
+ CORTEX_PRIO_MASK(CORTEX_MAX_KERNEL_PRIORITY)
+#else
+
+#define CORTEX_MAX_KERNEL_PRIORITY 0
+#endif
+
+/**
+ * @brief PendSV priority level.
+ * @note This priority is enforced to be equal to
+ * @p CORTEX_MAX_KERNEL_PRIORITY, this handler always have the
+ * highest priority that cannot preempt the kernel.
+ */
+#define CORTEX_PRIORITY_PENDSV CORTEX_MAX_KERNEL_PRIORITY
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/* The following code is not processed when the file is included from an
+ asm module.*/
+#if !defined(_FROM_ASM_)
+
+/* The documentation of the following declarations is in chconf.h in order
+ to not have duplicated structure names into the documentation.*/
+#if !defined(__DOXYGEN__)
+struct port_extctx {
+ regarm_t r0;
+ regarm_t r1;
+ regarm_t r2;
+ regarm_t r3;
+ regarm_t r12;
+ regarm_t lr_thd;
+ regarm_t pc;
+ regarm_t xpsr;
+#if CORTEX_USE_FPU
+ regarm_t s0;
+ regarm_t s1;
+ regarm_t s2;
+ regarm_t s3;
+ regarm_t s4;
+ regarm_t s5;
+ regarm_t s6;
+ regarm_t s7;
+ regarm_t s8;
+ regarm_t s9;
+ regarm_t s10;
+ regarm_t s11;
+ regarm_t s12;
+ regarm_t s13;
+ regarm_t s14;
+ regarm_t s15;
+ regarm_t fpscr;
+ regarm_t fpccr;
+#endif /* CORTEX_USE_FPU */
+};
+
+struct port_intctx {
+#if CORTEX_USE_FPU
+ regarm_t s16;
+ regarm_t s17;
+ regarm_t s18;
+ regarm_t s19;
+ regarm_t s20;
+ regarm_t s21;
+ regarm_t s22;
+ regarm_t s23;
+ regarm_t s24;
+ regarm_t s25;
+ regarm_t s26;
+ regarm_t s27;
+ regarm_t s28;
+ regarm_t s29;
+ regarm_t s30;
+ regarm_t s31;
+#endif /* CORTEX_USE_FPU */
+ regarm_t r4;
+ regarm_t r5;
+ regarm_t r6;
+ regarm_t r7;
+ regarm_t r8;
+ regarm_t r9;
+ regarm_t r10;
+ regarm_t r11;
+ regarm_t lr;
+};
+#endif /* !defined(__DOXYGEN__) */
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Platform dependent part of the @p chThdCreateI() API.
+ * @details This code usually setup the context switching frame represented
+ * by an @p port_intctx structure.
+ */
+#define PORT_SETUP_CONTEXT(tp, workspace, wsize, pf, arg) { \
+ (tp)->p_ctx.r13 = (struct port_intctx *)((uint8_t *)(workspace) + \
+ (wsize) - \
+ sizeof(struct port_intctx)); \
+ (tp)->p_ctx.r13->r4 = (regarm_t)(pf); \
+ (tp)->p_ctx.r13->r5 = (regarm_t)(arg); \
+ (tp)->p_ctx.r13->lr = (regarm_t)(_port_thread_start); \
+}
+
+/**
+ * @brief Computes the thread working area global size.
+ * @note There is no need to perform alignments in this macro.
+ */
+#define PORT_WA_SIZE(n) (sizeof(struct port_intctx) + \
+ sizeof(struct port_extctx) + \
+ (n) + (PORT_INT_REQUIRED_STACK))
+
+/**
+ * @brief IRQ prologue code.
+ * @details This macro must be inserted at the start of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_PROLOGUE()
+
+/**
+ * @brief IRQ epilogue code.
+ * @details This macro must be inserted at the end of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_EPILOGUE() _port_irq_epilogue()
+
+/**
+ * @brief IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Fast IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_FAST_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Performs a context switch between two threads.
+ * @details This is the most critical code in any port, this function
+ * is responsible for the context switch between 2 threads.
+ * @note The implementation of this code affects <b>directly</b> the context
+ * switch performance so optimize here as much as you can.
+ *
+ * @param[in] ntp the thread to be switched in
+ * @param[in] otp the thread to be switched out
+ */
+#if !CH_DBG_ENABLE_STACK_CHECK || defined(__DOXYGEN__)
+#define port_switch(ntp, otp) _port_switch(ntp, otp)
+#else
+#define port_switch(ntp, otp) { \
+ struct port_intctx *r13 = (struct port_intctx *)__get_PSP(); \
+ if ((stkalign_t *)(r13 - 1) < (otp)->p_stklimit) \
+ chSysHalt("stack overflow"); \
+ _port_switch(ntp, otp); \
+}
+#endif
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _port_irq_epilogue(void);
+ void _port_switch(thread_t *ntp, thread_t *otp);
+ void _port_thread_start(void);
+ void _port_switch_from_isr(void);
+ void _port_exit_from_isr(void);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Port-related initialization code.
+ */
+static inline void port_init(void) {
+
+ /* Initialization of the vector table and priority related settings.*/
+ SCB->VTOR = CORTEX_VTOR_INIT;
+
+ /* Initializing priority grouping.*/
+ NVIC_SetPriorityGrouping(CORTEX_PRIGROUP_INIT);
+
+ /* DWT cycle counter enable.*/
+ CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
+ DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
+
+ /* Initialization of the system vectors used by the port.*/
+#if !CORTEX_SIMPLIFIED_PRIORITY
+ NVIC_SetPriority(SVCall_IRQn, CORTEX_PRIORITY_SVCALL);
+#endif
+ NVIC_SetPriority(PendSV_IRQn, CORTEX_PRIORITY_PENDSV);
+}
+
+/**
+ * @brief Returns a word encoding the current interrupts status.
+ *
+ * @return The interrupts status.
+ */
+static inline syssts_t port_get_irq_status(void) {
+ uint32_t sts;
+
+#if !CORTEX_SIMPLIFIED_PRIORITY
+ sts = __get_BASEPRI();
+#else /* CORTEX_SIMPLIFIED_PRIORITY */
+ sts = __get_PRIMASK();
+#endif /* CORTEX_SIMPLIFIED_PRIORITY */
+ return sts;
+}
+
+/**
+ * @brief Checks the interrupt status.
+ *
+ * @param[in] sts the interrupt status word
+ *
+ * @return The interrupt status.
+ * @retvel false the word specified a disabled interrupts status.
+ * @retvel true the word specified an enabled interrupts status.
+ */
+static inline bool port_irq_enabled(syssts_t sts) {
+
+#if !CORTEX_SIMPLIFIED_PRIORITY
+ return sts == CORTEX_BASEPRI_DISABLED;
+#else /* CORTEX_SIMPLIFIED_PRIORITY */
+ return (sts & 1) == 0;
+#endif /* CORTEX_SIMPLIFIED_PRIORITY */
+}
+
+/**
+ * @brief Determines the current execution context.
+ *
+ * @return The execution context.
+ * @retval false not running in ISR mode.
+ * @retval true running in ISR mode.
+ */
+static inline bool port_is_isr_context(void) {
+
+ return (bool)((__get_IPSR() & 0x1FF) != 0);
+}
+
+/**
+ * @brief Kernel-lock action.
+ * @details In this port this function raises the base priority to kernel
+ * level.
+ */
+static inline void port_lock(void) {
+
+#if !CORTEX_SIMPLIFIED_PRIORITY
+ __set_BASEPRI(CORTEX_BASEPRI_KERNEL);
+#else /* CORTEX_SIMPLIFIED_PRIORITY */
+ __disable_irq();
+#endif /* CORTEX_SIMPLIFIED_PRIORITY */
+}
+
+/**
+ * @brief Kernel-unlock action.
+ * @details In this port this function lowers the base priority to user
+ * level.
+ */
+static inline void port_unlock(void) {
+
+#if !CORTEX_SIMPLIFIED_PRIORITY
+ __set_BASEPRI(CORTEX_BASEPRI_DISABLED);
+#else /* CORTEX_SIMPLIFIED_PRIORITY */
+ __enable_irq();
+#endif /* CORTEX_SIMPLIFIED_PRIORITY */
+}
+
+/**
+ * @brief Kernel-lock action from an interrupt handler.
+ * @details In this port this function raises the base priority to kernel
+ * level.
+ * @note Same as @p port_lock() in this port.
+ */
+static inline void port_lock_from_isr(void) {
+
+ port_lock();
+}
+
+/**
+ * @brief Kernel-unlock action from an interrupt handler.
+ * @details In this port this function lowers the base priority to user
+ * level.
+ * @note Same as @p port_unlock() in this port.
+ */
+static inline void port_unlock_from_isr(void) {
+
+ port_unlock();
+}
+
+/**
+ * @brief Disables all the interrupt sources.
+ * @note In this port it disables all the interrupt sources by raising
+ * the priority mask to level 0.
+ */
+static inline void port_disable(void) {
+
+ __disable_irq();
+}
+
+/**
+ * @brief Disables the interrupt sources below kernel-level priority.
+ * @note Interrupt sources above kernel level remains enabled.
+ * @note In this port it raises/lowers the base priority to kernel level.
+ */
+static inline void port_suspend(void) {
+
+#if !CORTEX_SIMPLIFIED_PRIORITY || defined(__DOXYGEN__)
+ __set_BASEPRI(CORTEX_BASEPRI_KERNEL);
+ __enable_irq();
+#else
+ __disable_irq();
+#endif
+}
+
+/**
+ * @brief Enables all the interrupt sources.
+ * @note In this port it lowers the base priority to user level.
+ */
+static inline void port_enable(void) {
+
+#if !CORTEX_SIMPLIFIED_PRIORITY || defined(__DOXYGEN__)
+ __set_BASEPRI(CORTEX_BASEPRI_DISABLED);
+#endif
+ __enable_irq();
+}
+
+/**
+ * @brief Enters an architecture-dependent IRQ-waiting mode.
+ * @details The function is meant to return when an interrupt becomes pending.
+ * The simplest implementation is an empty function or macro but this
+ * would not take advantage of architecture-specific power saving
+ * modes.
+ * @note Implemented as an inlined @p WFI instruction.
+ */
+static inline void port_wait_for_interrupt(void) {
+
+#if CORTEX_ENABLE_WFI_IDLE
+ __WFI();
+#endif
+}
+
+/**
+ * @brief Returns the current value of the realtime counter.
+ *
+ * @return The realtime counter value.
+ */
+static inline rtcnt_t port_rt_get_counter_value(void) {
+
+ return DWT->CYCCNT;
+}
+
+#endif /* !defined(_FROM_ASM_) */
+
+#endif /* _CHCORE_V7M_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v6m.s b/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v6m.s new file mode 100644 index 000000000..f745d82e6 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v6m.s @@ -0,0 +1,140 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file compilers/GCC/chcoreasm_v6m.s
+ * @brief ARMv6-M architecture port low level code.
+ *
+ * @addtogroup ARMCMx_GCC_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+
+ .set CONTEXT_OFFSET, 12
+ .set SCB_ICSR, 0xE000ED04
+ .set ICSR_PENDSVSET, 0x10000000
+ .set ICSR_NMIPENDSET, 0x80000000
+
+ .cpu cortex-m0
+ .fpu softvfp
+
+ .thumb
+ .text
+
+/*--------------------------------------------------------------------------*
+ * Performs a context switch between two threads.
+ *--------------------------------------------------------------------------*/
+ .thumb_func
+ .globl _port_switch
+_port_switch:
+ push {r4, r5, r6, r7, lr}
+ mov r4, r8
+ mov r5, r9
+ mov r6, r10
+ mov r7, r11
+ push {r4, r5, r6, r7}
+ mov r3, sp
+ str r3, [r1, #CONTEXT_OFFSET]
+ ldr r3, [r0, #CONTEXT_OFFSET]
+ mov sp, r3
+ pop {r4, r5, r6, r7}
+ mov r8, r4
+ mov r9, r5
+ mov r10, r6
+ mov r11, r7
+ pop {r4, r5, r6, r7, pc}
+
+/*--------------------------------------------------------------------------*
+ * Start a thread by invoking its work function.
+ *
+ * Threads execution starts here, the code leaves the system critical zone
+ * and then jumps into the thread function passed in register R4. The
+ * register R5 contains the thread parameter. The function chThdExit() is
+ * called on thread function return.
+ *--------------------------------------------------------------------------*/
+ .thumb_func
+ .globl _port_thread_start
+_port_thread_start:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl _dbg_check_unlock
+#endif
+#if CH_DBG_STATISTICS
+ bl _stats_stop_measure_crit_thd
+#endif
+ cpsie i
+ mov r0, r5
+ blx r4
+ bl chThdExit
+
+/*--------------------------------------------------------------------------*
+ * Post-IRQ switch code.
+ *
+ * Exception handlers return here for context switching.
+ *--------------------------------------------------------------------------*/
+ .thumb_func
+ .globl _port_switch_from_isr
+_port_switch_from_isr:
+#if CH_DBG_STATISTICS
+ bl _stats_start_measure_crit_thd
+#endif
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl _dbg_check_lock
+#endif
+ bl chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl _dbg_check_unlock
+#endif
+#if CH_DBG_STATISTICS
+ bl _stats_stop_measure_crit_thd
+#endif
+ .globl _port_exit_from_isr
+_port_exit_from_isr:
+ ldr r2, .L2
+ ldr r3, .L3
+ str r3, [r2, #0]
+#if CORTEX_ALTERNATE_SWITCH
+ cpsie i
+#endif
+.L1: b .L1
+
+ .align 2
+.L2: .word SCB_ICSR
+#if CORTEX_ALTERNATE_SWITCH
+.L3: .word ICSR_PENDSVSET
+#else
+.L3: .word ICSR_NMIPENDSET
+#endif
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s b/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s new file mode 100644 index 000000000..36567e0b4 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s @@ -0,0 +1,138 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file compilers/GCC/chcoreasm_v7m.s
+ * @brief ARMv7-M architecture port low level code.
+ *
+ * @addtogroup ARMCMx_GCC_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+
+ .set CONTEXT_OFFSET, 12
+ .set SCB_ICSR, 0xE000ED04
+ .set ICSR_PENDSVSET, 0x10000000
+
+ .syntax unified
+ .cpu cortex-m4
+#if CORTEX_USE_FPU
+ .fpu fpv4-sp-d16
+#else
+ .fpu softvfp
+#endif
+
+ .thumb
+ .text
+
+/*--------------------------------------------------------------------------*
+ * Performs a context switch between two threads.
+ *--------------------------------------------------------------------------*/
+ .thumb_func
+ .globl _port_switch
+_port_switch:
+ push {r4, r5, r6, r7, r8, r9, r10, r11, lr}
+#if CORTEX_USE_FPU
+ vpush {s16-s31}
+#endif
+ str sp, [r1, #CONTEXT_OFFSET]
+ ldr sp, [r0, #CONTEXT_OFFSET]
+#if CORTEX_USE_FPU
+ vpop {s16-s31}
+#endif
+ pop {r4, r5, r6, r7, r8, r9, r10, r11, pc}
+
+/*--------------------------------------------------------------------------*
+ * Start a thread by invoking its work function.
+ *
+ * Threads execution starts here, the code leaves the system critical zone
+ * and then jumps into the thread function passed in register R4. The
+ * register R5 contains the thread parameter. The function chThdExit() is
+ * called on thread function return.
+ *--------------------------------------------------------------------------*/
+ .thumb_func
+ .globl _port_thread_start
+_port_thread_start:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl _dbg_check_unlock
+#endif
+#if CH_DBG_STATISTICS
+ bl _stats_stop_measure_crit_thd
+#endif
+#if !CORTEX_SIMPLIFIED_PRIORITY
+ movs r3, #0
+ msr BASEPRI, r3
+#else /* CORTEX_SIMPLIFIED_PRIORITY */
+ cpsie i
+#endif /* CORTEX_SIMPLIFIED_PRIORITY */
+ mov r0, r5
+ blx r4
+ bl chThdExit
+
+/*--------------------------------------------------------------------------*
+ * Post-IRQ switch code.
+ *
+ * Exception handlers return here for context switching.
+ *--------------------------------------------------------------------------*/
+ .thumb_func
+ .globl _port_switch_from_isr
+_port_switch_from_isr:
+#if CH_DBG_STATISTICS
+ bl _stats_start_measure_crit_thd
+#endif
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl _dbg_check_lock
+#endif
+ bl chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl _dbg_check_unlock
+#endif
+#if CH_DBG_STATISTICS
+ bl _stats_stop_measure_crit_thd
+#endif
+ .globl _port_exit_from_isr
+_port_exit_from_isr:
+#if CORTEX_SIMPLIFIED_PRIORITY
+ movw r3, #:lower16:SCB_ICSR
+ movt r3, #:upper16:SCB_ICSR
+ mov r2, ICSR_PENDSVSET
+ str r2, [r3, #0]
+ cpsie i
+#else /* !CORTEX_SIMPLIFIED_PRIORITY */
+ svc #0
+#endif /* !CORTEX_SIMPLIFIED_PRIORITY */
+.L1: b .L1
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/chtypes.h b/os/rt/ports/ARMCMx/compilers/GCC/chtypes.h new file mode 100644 index 000000000..e6f7b21e1 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/chtypes.h @@ -0,0 +1,111 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ARMCMx/compilers/GCC/chtypes.h
+ * @brief ARM Cortex-Mx port system types.
+ *
+ * @addtogroup ARMCMx_GCC_CORE
+ * @{
+ */
+
+#ifndef _CHTYPES_H_
+#define _CHTYPES_H_
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * @name Common constants
+ */
+/**
+ * @brief Generic 'false' boolean constant.
+ */
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+/**
+ * @brief Generic 'true' boolean constant.
+ */
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE (!FALSE)
+#endif
+/** @} */
+
+/**
+ * @name Derived generic types
+ * @{
+ */
+typedef volatile int8_t vint8_t; /**< Volatile signed 8 bits. */
+typedef volatile uint8_t vuint8_t; /**< Volatile unsigned 8 bits. */
+typedef volatile int16_t vint16_t; /**< Volatile signed 16 bits. */
+typedef volatile uint16_t vuint16_t; /**< Volatile unsigned 16 bits. */
+typedef volatile int32_t vint32_t; /**< Volatile signed 32 bits. */
+typedef volatile uint32_t vuint32_t; /**< Volatile unsigned 32 bits. */
+/** @} */
+
+/**
+ * @name Kernel types
+ * @{
+ */
+typedef uint32_t rtcnt_t; /**< Realtime counter. */
+typedef uint64_t rttime_t; /**< Realtime accumulator. */
+typedef uint32_t syssts_t; /**< System status word. */
+typedef uint8_t tmode_t; /**< Thread flags. */
+typedef uint8_t tstate_t; /**< Thread state. */
+typedef uint8_t trefs_t; /**< Thread references counter. */
+typedef uint8_t tslices_t; /**< Thread time slices counter.*/
+typedef uint32_t tprio_t; /**< Thread priority. */
+typedef int32_t msg_t; /**< Inter-thread message. */
+typedef int32_t eventid_t; /**< Numeric event identifier. */
+typedef uint32_t eventmask_t; /**< Mask of event identifiers. */
+typedef uint32_t eventflags_t; /**< Mask of event flags. */
+typedef int32_t cnt_t; /**< Generic signed counter. */
+typedef uint32_t ucnt_t; /**< Generic unsigned counter. */
+/** @} */
+
+/**
+ * @brief ROM constant modifier.
+ * @note It is set to use the "const" keyword in this port.
+ */
+#define ROMCONST const
+
+/**
+ * @brief Makes functions not inlineable.
+ * @note If the compiler does not support such attribute then the
+ * realtime counter precision could be degraded.
+ */
+#define NOINLINE __attribute__((noinline))
+
+/**
+ * @brief Optimized thread function declaration macro.
+ */
+#define PORT_THD_FUNCTION(tname, arg) msg_t tname(void *arg)
+
+/**
+ * @brief Packed variable specifier.
+ */
+#define PACKED_VAR __attribute__((packed))
+
+#endif /* _CHTYPES_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f0xx.mk b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f0xx.mk new file mode 100644 index 000000000..43131fc6b --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f0xx.mk @@ -0,0 +1,15 @@ +# List of the ChibiOS/RT Cortex-M0 STM32F0xx port files.
+PORTSRC = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/crt0.c \
+ $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/vectors.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore_v6m.c
+
+PORTASM = $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v6m.s
+
+PORTINC = ${CHIBIOS}/os/ext/CMSIS/include \
+ ${CHIBIOS}/os/ext/CMSIS/ST \
+ ${CHIBIOS}/os/common/ports/ARMCMx/devices/STM32F0xx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/ARMCMx/compilers/GCC/ld
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f1xx.mk b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f1xx.mk new file mode 100644 index 000000000..6317c2e0b --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f1xx.mk @@ -0,0 +1,15 @@ +# List of the ChibiOS/RT Cortex-M3 STM32F1xx port files.
+PORTSRC = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/crt0.c \
+ $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/vectors.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore_v7m.c
+
+PORTASM = $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s
+
+PORTINC = ${CHIBIOS}/os/ext/CMSIS/include \
+ ${CHIBIOS}/os/ext/CMSIS/ST \
+ ${CHIBIOS}/os/common/ports/ARMCMx/devices/STM32F1xx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/ARMCMx/compilers/GCC/ld
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f30x.mk b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f30x.mk new file mode 100644 index 000000000..e3d87f411 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f30x.mk @@ -0,0 +1,15 @@ +# List of the ChibiOS/RT Cortex-M4 STM32F30x port files.
+PORTSRC = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/crt0.c \
+ $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/vectors.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore_v7m.c
+
+PORTASM = $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s
+
+PORTINC = ${CHIBIOS}/os/ext/CMSIS/include \
+ ${CHIBIOS}/os/ext/CMSIS/ST \
+ ${CHIBIOS}/os/common/ports/ARMCMx/devices/STM32F30x \
+ ${CHIBIOS}/os/rt/ports/ARMCMx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/ARMCMx/compilers/GCC/ld
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f37x.mk b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f37x.mk new file mode 100644 index 000000000..4b38231bb --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f37x.mk @@ -0,0 +1,15 @@ +# List of the ChibiOS/RT Cortex-M4 STM32F37x port files.
+PORTSRC = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/crt0.c \
+ $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/vectors.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore_v7m.c
+
+PORTASM = $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s
+
+PORTINC = ${CHIBIOS}/os/ext/CMSIS/include \
+ ${CHIBIOS}/os/ext/CMSIS/ST \
+ ${CHIBIOS}/os/common/ports/ARMCMx/devices/STM32F37x \
+ ${CHIBIOS}/os/rt/ports/ARMCMx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/ARMCMx/compilers/GCC/ld
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f4xx.mk b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f4xx.mk new file mode 100644 index 000000000..9d168c2d8 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32f4xx.mk @@ -0,0 +1,15 @@ +# List of the ChibiOS/RT Cortex-M4 STM32F4xx port files.
+PORTSRC = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/crt0.c \
+ $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/vectors.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore_v7m.c
+
+PORTASM = $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s
+
+PORTINC = ${CHIBIOS}/os/ext/CMSIS/include \
+ ${CHIBIOS}/os/ext/CMSIS/ST \
+ ${CHIBIOS}/os/common/ports/ARMCMx/devices/STM32F4xx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/ARMCMx/compilers/GCC/ld
diff --git a/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32l1xx.mk b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32l1xx.mk new file mode 100644 index 000000000..812c0d24c --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/GCC/mk/port_stm32l1xx.mk @@ -0,0 +1,15 @@ +# List of the ChibiOS/RT Cortex-M3 STM32L1xx port files.
+PORTSRC = $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/crt0.c \
+ $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/vectors.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore.c \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/chcore_v7m.c
+
+PORTASM = $(CHIBIOS)/os/rt/ports/ARMCMx/compilers/GCC/chcoreasm_v7m.s
+
+PORTINC = ${CHIBIOS}/os/ext/CMSIS/include \
+ ${CHIBIOS}/os/ext/CMSIS/ST \
+ ${CHIBIOS}/os/common/ports/ARMCMx/devices/STM32L1xx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx \
+ ${CHIBIOS}/os/rt/ports/ARMCMx/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/ARMCMx/compilers/GCC/ld
diff --git a/os/rt/ports/ARMCMx/compilers/IAR/chcoreasm_v6m.s b/os/rt/ports/ARMCMx/compilers/IAR/chcoreasm_v6m.s new file mode 100644 index 000000000..81f61214a --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/IAR/chcoreasm_v6m.s @@ -0,0 +1,130 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file compilers/IAR/chcoreasm_v6m.s
+ * @brief ARMv6-M architecture port low level code.
+ *
+ * @addtogroup ARMCMx_IAR_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+
+ MODULE ?chcoreasm_v6m
+
+ AAPCS INTERWORK, VFP_COMPATIBLE
+ PRESERVE8
+
+CONTEXT_OFFSET SET 12
+SCB_ICSR SET 0xE000ED04
+
+ SECTION .text:CODE:NOROOT(2)
+
+ EXTERN chThdExit
+ EXTERN chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ EXTERN dbg_check_unlock
+ EXTERN dbg_check_lock
+#endif
+
+ THUMB
+
+/*
+ * Performs a context switch between two threads.
+ */
+ PUBLIC _port_switch
+_port_switch:
+ push {r4, r5, r6, r7, lr}
+ mov r4, r8
+ mov r5, r9
+ mov r6, r10
+ mov r7, r11
+ push {r4, r5, r6, r7}
+ mov r3, sp
+ str r3, [r1, #CONTEXT_OFFSET]
+ ldr r3, [r0, #CONTEXT_OFFSET]
+ mov sp, r3
+ pop {r4, r5, r6, r7}
+ mov r8, r4
+ mov r9, r5
+ mov r10, r6
+ mov r11, r7
+ pop {r4, r5, r6, r7, pc}
+
+/*
+ * Start a thread by invoking its work function.
+ * If the work function returns @p chThdExit() is automatically invoked.
+ */
+ PUBLIC _port_thread_start
+_port_thread_start:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+ cpsie i
+ mov r0, r5
+ blx r4
+ bl chThdExit
+
+/*
+ * Post-IRQ switch code.
+ * Exception handlers return here for context switching.
+ */
+ PUBLIC _port_switch_from_isr
+ PUBLIC _port_exit_from_isr
+_port_switch_from_isr:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_lock
+#endif
+ bl chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+_port_exit_from_isr:
+ ldr r2, =SCB_ICSR
+ movs r3, #128
+#if CORTEX_ALTERNATE_SWITCH
+ lsls r3, r3, #21
+ str r3, [r2, #0]
+ cpsie i
+#else
+ lsls r3, r3, #24
+ str r3, [r2, #0]
+#endif
+waithere:
+ b waithere
+
+ END
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/IAR/chcoreasm_v7m.s b/os/rt/ports/ARMCMx/compilers/IAR/chcoreasm_v7m.s new file mode 100644 index 000000000..6a83a8f3d --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/IAR/chcoreasm_v7m.s @@ -0,0 +1,128 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file compilers/IAR/chcoreasm_v7m.s
+ * @brief ARMv7-M architecture port low level code.
+ *
+ * @addtogroup ARMCMx_IAR_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+
+ MODULE ?chcoreasm_v7m
+
+ AAPCS INTERWORK, VFP_COMPATIBLE
+ PRESERVE8
+
+CONTEXT_OFFSET SET 12
+SCB_ICSR SET 0xE000ED04
+ICSR_PENDSVSET SET 0x10000000
+
+ SECTION .text:CODE:NOROOT(2)
+
+ EXTERN chThdExit
+ EXTERN chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ EXTERN dbg_check_unlock
+ EXTERN dbg_check_lock
+#endif
+
+ THUMB
+
+/*
+ * Performs a context switch between two threads.
+ */
+ PUBLIC _port_switch
+_port_switch:
+ push {r4, r5, r6, r7, r8, r9, r10, r11, lr}
+#if CORTEX_USE_FPU
+ vpush {s16-s31}
+#endif
+ str sp, [r1, #CONTEXT_OFFSET]
+ ldr sp, [r0, #CONTEXT_OFFSET]
+#if CORTEX_USE_FPU
+ vpop {s16-s31}
+#endif
+ pop {r4, r5, r6, r7, r8, r9, r10, r11, pc}
+
+/*
+ * Start a thread by invoking its work function.
+ * If the work function returns @p chThdExit() is automatically invoked.
+ */
+ PUBLIC _port_thread_start
+_port_thread_start:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+#if CORTEX_SIMPLIFIED_PRIORITY
+ cpsie i
+#else
+ movs r3, #CORTEX_BASEPRI_DISABLED
+ msr BASEPRI, r3
+#endif
+ mov r0, r5
+ blx r4
+ bl chThdExit
+
+/*
+ * Post-IRQ switch code.
+ * Exception handlers return here for context switching.
+ */
+ PUBLIC _port_switch_from_isr
+ PUBLIC _port_exit_from_isr
+_port_switch_from_isr:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_lock
+#endif
+ bl chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+_port_exit_from_isr:
+#if CORTEX_SIMPLIFIED_PRIORITY
+ mov r3, #LWRD SCB_ICSR
+ movt r3, #HWRD SCB_ICSR
+ mov r2, #ICSR_PENDSVSET
+ str r2, [r3]
+ cpsie i
+.L3: b .L3
+#else
+ svc #0
+#endif
+
+ END
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/IAR/chtypes.h b/os/rt/ports/ARMCMx/compilers/IAR/chtypes.h new file mode 100644 index 000000000..386d7203b --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/IAR/chtypes.h @@ -0,0 +1,111 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ARMCMx/compilers/IAR/chtypes.h
+ * @brief ARM Cortex-Mx port system types.
+ *
+ * @addtogroup ARMCMx_IAR_CORE
+ * @{
+ */
+
+#ifndef _CHTYPES_H_
+#define _CHTYPES_H_
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * @name Common constants
+ */
+/**
+ * @brief Generic 'false' boolean constant.
+ */
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+/**
+ * @brief Generic 'true' boolean constant.
+ */
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE (!FALSE)
+#endif
+/** @} */
+
+/**
+ * @name Derived generic types
+ * @{
+ */
+typedef volatile int8_t vint8_t; /**< Volatile signed 8 bits. */
+typedef volatile uint8_t vuint8_t; /**< Volatile unsigned 8 bits. */
+typedef volatile int16_t vint16_t; /**< Volatile signed 16 bits. */
+typedef volatile uint16_t vuint16_t; /**< Volatile unsigned 16 bits. */
+typedef volatile int32_t vint32_t; /**< Volatile signed 32 bits. */
+typedef volatile uint32_t vuint32_t; /**< Volatile unsigned 32 bits. */
+/** @} */
+
+/**
+ * @name Kernel types
+ * @{
+ */
+typedef uint32_t rtcnt_t; /**< Realtime counter. */
+typedef uint64_t rttime_t; /**< Realtime accumulator. */
+typedef uint32_t syssts_t; /**< System status word. */
+typedef uint8_t tmode_t; /**< Thread flags. */
+typedef uint8_t tstate_t; /**< Thread state. */
+typedef uint8_t trefs_t; /**< Thread references counter. */
+typedef uint8_t tslices_t; /**< Thread time slices counter.*/
+typedef uint32_t tprio_t; /**< Thread priority. */
+typedef int32_t msg_t; /**< Inter-thread message. */
+typedef int32_t eventid_t; /**< Numeric event identifier. */
+typedef uint32_t eventmask_t; /**< Mask of event identifiers. */
+typedef uint32_t eventflags_t; /**< Mask of event flags. */
+typedef int32_t cnt_t; /**< Generic signed counter. */
+typedef uint32_t ucnt_t; /**< Generic unsigned counter. */
+/** @} */
+
+/**
+ * @brief ROM constant modifier.
+ * @note It is set to use the "const" keyword in this port.
+ */
+#define ROMCONST const
+
+/**
+ * @brief Makes functions not inlineable.
+ * @note If the compiler does not support such attribute then the
+ * realtime counter precision could be degraded.
+ */
+#define NOINLINE
+
+/**
+ * @brief Optimized thread function declaration macro.
+ */
+#define PORT_THD_FUNCTION(tname, arg) msg_t tname(void *arg)
+
+/**
+ * @brief Packed variable specifier.
+ */
+#define PACKED_VAR __packed
+
+#endif /* _CHTYPES_H_ */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/RVCT/chcoreasm_v6m.s b/os/rt/ports/ARMCMx/compilers/RVCT/chcoreasm_v6m.s new file mode 100644 index 000000000..15b0fb4c3 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/RVCT/chcoreasm_v6m.s @@ -0,0 +1,127 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file compilers/RVCT/chcoreasm_v6m.s
+ * @brief ARMv6-M architecture port low level code.
+ *
+ * @addtogroup ARMCMx_RVCT_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+
+CONTEXT_OFFSET EQU 12
+SCB_ICSR EQU 0xE000ED04
+
+ PRESERVE8
+ THUMB
+ AREA |.text|, CODE, READONLY
+
+ IMPORT chThdExit
+ IMPORT chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ IMPORT dbg_check_unlock
+ IMPORT dbg_check_lock
+#endif
+
+/*
+ * Performs a context switch between two threads.
+ */
+ EXPORT _port_switch
+_port_switch PROC
+ push {r4, r5, r6, r7, lr}
+ mov r4, r8
+ mov r5, r9
+ mov r6, r10
+ mov r7, r11
+ push {r4, r5, r6, r7}
+ mov r3, sp
+ str r3, [r1, #CONTEXT_OFFSET]
+ ldr r3, [r0, #CONTEXT_OFFSET]
+ mov sp, r3
+ pop {r4, r5, r6, r7}
+ mov r8, r4
+ mov r9, r5
+ mov r10, r6
+ mov r11, r7
+ pop {r4, r5, r6, r7, pc}
+ ENDP
+
+/*
+ * Start a thread by invoking its work function.
+ * If the work function returns @p chThdExit() is automatically invoked.
+ */
+ EXPORT _port_thread_start
+_port_thread_start PROC
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+ cpsie i
+ mov r0, r5
+ blx r4
+ bl chThdExit
+ ENDP
+
+/*
+ * Post-IRQ switch code.
+ * Exception handlers return here for context switching.
+ */
+ EXPORT _port_switch_from_isr
+ EXPORT _port_exit_from_isr
+_port_switch_from_isr PROC
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_lock
+#endif
+ bl chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+_port_exit_from_isr
+ ldr r2, =SCB_ICSR
+ movs r3, #128
+#if CORTEX_ALTERNATE_SWITCH
+ lsls r3, r3, #21
+ str r3, [r2, #0]
+ cpsie i
+#else
+ lsls r3, r3, #24
+ str r3, [r2, #0]
+#endif
+waithere b waithere
+ ENDP
+
+ END
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/RVCT/chcoreasm_v7m.s b/os/rt/ports/ARMCMx/compilers/RVCT/chcoreasm_v7m.s new file mode 100644 index 000000000..254624708 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/RVCT/chcoreasm_v7m.s @@ -0,0 +1,126 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file compilers/RVCT/chcoreasm_v7m.s
+ * @brief ARMv7-M architecture port low level code.
+ *
+ * @addtogroup ARMCMx_RVCT_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+
+CONTEXT_OFFSET EQU 12
+SCB_ICSR EQU 0xE000ED04
+ICSR_PENDSVSET EQU 0x10000000
+
+ PRESERVE8
+ THUMB
+ AREA |.text|, CODE, READONLY
+
+ IMPORT chThdExit
+ IMPORT chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ IMPORT dbg_check_unlock
+ IMPORT dbg_check_lock
+#endif
+
+/*
+ * Performs a context switch between two threads.
+ */
+ EXPORT _port_switch
+_port_switch PROC
+ push {r4, r5, r6, r7, r8, r9, r10, r11, lr}
+#if CORTEX_USE_FPU
+ vpush {s16-s31}
+#endif
+ str sp, [r1, #CONTEXT_OFFSET]
+ ldr sp, [r0, #CONTEXT_OFFSET]
+#if CORTEX_USE_FPU
+ vpop {s16-s31}
+#endif
+ pop {r4, r5, r6, r7, r8, r9, r10, r11, pc}
+ ENDP
+
+/*
+ * Start a thread by invoking its work function.
+ * If the work function returns @p chThdExit() is automatically invoked.
+ */
+ EXPORT _port_thread_start
+_port_thread_start PROC
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+#if CORTEX_SIMPLIFIED_PRIORITY
+ cpsie i
+#else
+ movs r3, #CORTEX_BASEPRI_DISABLED
+ msr BASEPRI, r3
+#endif
+ mov r0, r5
+ blx r4
+ bl chThdExit
+ ENDP
+
+/*
+ * Post-IRQ switch code.
+ * Exception handlers return here for context switching.
+ */
+ EXPORT _port_switch_from_isr
+ EXPORT _port_exit_from_isr
+_port_switch_from_isr PROC
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_lock
+#endif
+ bl chSchDoReschedule
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+_port_exit_from_isr
+#if CORTEX_SIMPLIFIED_PRIORITY
+ mov r3, #SCB_ICSR :AND: 0xFFFF
+ movt r3, #SCB_ICSR :SHR: 16
+ mov r2, #ICSR_PENDSVSET
+ str r2, [r3, #0]
+ cpsie i
+waithere b waithere
+#else
+ svc #0
+#endif
+ ENDP
+
+ END
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/ARMCMx/compilers/RVCT/chtypes.h b/os/rt/ports/ARMCMx/compilers/RVCT/chtypes.h new file mode 100644 index 000000000..3fe32d065 --- /dev/null +++ b/os/rt/ports/ARMCMx/compilers/RVCT/chtypes.h @@ -0,0 +1,111 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ARMCMx/compilers/RVCT/chtypes.h
+ * @brief ARM Cortex-Mx port system types.
+ *
+ * @addtogroup ARMCMx_RVCT_CORE
+ * @{
+ */
+
+#ifndef _CHTYPES_H_
+#define _CHTYPES_H_
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * @name Common constants
+ */
+/**
+ * @brief Generic 'false' boolean constant.
+ */
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+/**
+ * @brief Generic 'true' boolean constant.
+ */
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE (!FALSE)
+#endif
+/** @} */
+
+/**
+ * @name Derived generic types
+ * @{
+ */
+typedef volatile int8_t vint8_t; /**< Volatile signed 8 bits. */
+typedef volatile uint8_t vuint8_t; /**< Volatile unsigned 8 bits. */
+typedef volatile int16_t vint16_t; /**< Volatile signed 16 bits. */
+typedef volatile uint16_t vuint16_t; /**< Volatile unsigned 16 bits. */
+typedef volatile int32_t vint32_t; /**< Volatile signed 32 bits. */
+typedef volatile uint32_t vuint32_t; /**< Volatile unsigned 32 bits. */
+/** @} */
+
+/**
+ * @name Kernel types
+ * @{
+ */
+typedef uint32_t rtcnt_t; /**< Realtime counter. */
+typedef uint64_t rttime_t; /**< Realtime accumulator. */
+typedef uint32_t syssts_t; /**< System status word. */
+typedef uint8_t tmode_t; /**< Thread flags. */
+typedef uint8_t tstate_t; /**< Thread state. */
+typedef uint8_t trefs_t; /**< Thread references counter. */
+typedef uint8_t tslices_t; /**< Thread time slices counter.*/
+typedef uint32_t tprio_t; /**< Thread priority. */
+typedef int32_t msg_t; /**< Inter-thread message. */
+typedef int32_t eventid_t; /**< Numeric event identifier. */
+typedef uint32_t eventmask_t; /**< Mask of event identifiers. */
+typedef uint32_t eventflags_t; /**< Mask of event flags. */
+typedef int32_t cnt_t; /**< Generic signed counter. */
+typedef uint32_t ucnt_t; /**< Generic unsigned counter. */
+/** @} */
+
+/**
+ * @brief ROM constant modifier.
+ * @note It is set to use the "const" keyword in this port.
+ */
+#define ROMCONST const
+
+/**
+ * @brief Makes functions not inlineable.
+ * @note If the compiler does not support such attribute then the
+ * realtime counter precision could be degraded.
+ */
+#define NOINLINE
+
+/**
+ * @brief Optimized thread function declaration macro.
+ */
+#define PORT_THD_FUNCTION(tname, arg) msg_t tname(void *arg)
+
+/**
+ * @brief Packed variable specifier.
+ */
+#define PACKED_VAR __packed
+
+#endif /* _CHTYPES_H_ */
+
+/** @} */
diff --git a/os/rt/ports/e200/chcore.c b/os/rt/ports/e200/chcore.c new file mode 100644 index 000000000..a74c76cad --- /dev/null +++ b/os/rt/ports/e200/chcore.c @@ -0,0 +1,107 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file PPC/chcore.c
+ * @brief PowerPC architecture port code.
+ *
+ * @addtogroup PPC_CORE
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Performs a context switch between two threads.
+ * @details This is the most critical code in any port, this function
+ * is responsible for the context switch between 2 threads.
+ * @note The implementation of this code affects <b>directly</b> the context
+ * switch performance so optimize here as much as you can.
+ */
+#if !defined(__DOXYGEN__)
+__attribute__((naked))
+#endif
+void port_dummy1(void) {
+
+ asm (".global _port_switch");
+ asm ("_port_switch:");
+ asm ("subi %sp, %sp, 80"); /* Size of the intctx structure. */
+ asm ("mflr %r0");
+ asm ("stw %r0, 84(%sp)"); /* LR into the caller frame. */
+ asm ("mfcr %r0");
+ asm ("stw %r0, 0(%sp)"); /* CR. */
+ asm ("stmw %r14, 4(%sp)"); /* GPR14...GPR31. */
+
+ asm ("stw %sp, 12(%r4)"); /* Store swapped-out stack. */
+ asm ("lwz %sp, 12(%r3)"); /* Load swapped-in stack. */
+
+ asm ("lmw %r14, 4(%sp)"); /* GPR14...GPR31. */
+ asm ("lwz %r0, 0(%sp)"); /* CR. */
+ asm ("mtcr %r0");
+ asm ("lwz %r0, 84(%sp)"); /* LR from the caller frame. */
+ asm ("mtlr %r0");
+ asm ("addi %sp, %sp, 80"); /* Size of the intctx structure. */
+ asm ("blr");
+}
+
+/**
+ * @brief Start a thread by invoking its work function.
+ * @details If the work function returns @p chThdExit() is automatically
+ * invoked.
+ */
+#if !defined(__DOXYGEN__)
+__attribute__((naked))
+#endif
+void port_dummy2(void) {
+
+ asm (".global _port_thread_start");
+ asm ("_port_thread_start:");
+ chSysUnlock();
+ asm ("mr %r3, %r31"); /* Thread parameter. */
+ asm ("mtctr %r30");
+ asm ("bctrl"); /* Invoke thread function. */
+ asm ("bl chThdExit"); /* Thread termination on exit. */
+}
+
+/** @} */
diff --git a/os/rt/ports/e200/chcore.h b/os/rt/ports/e200/chcore.h new file mode 100644 index 000000000..0255a0f1d --- /dev/null +++ b/os/rt/ports/e200/chcore.h @@ -0,0 +1,550 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file PPC/chcore.h
+ * @brief PowerPC architecture port macros and structures.
+ *
+ * @addtogroup PPC_CORE
+ * @{
+ */
+
+#ifndef _CHCORE_H_
+#define _CHCORE_H_
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/**
+ * @name Architecture and Compiler
+ * @{
+ */
+/**
+ * @brief Macro defining an PPC architecture.
+ */
+#define PORT_ARCHITECTURE_PPC
+
+/**
+ * @brief Macro defining the specific PPC architecture.
+ */
+#define PORT_ARCHITECTURE_PPC_E200
+
+/**
+ * @brief Name of the implemented architecture.
+ */
+#define PORT_ARCHITECTURE_NAME "Power Architecture"
+
+/**
+ * @brief Compiler name and version.
+ */
+#if defined(__GNUC__) || defined(__DOXYGEN__)
+#define PORT_COMPILER_NAME "GCC " __VERSION__
+
+#else
+#error "unsupported compiler"
+#endif
+/** @} */
+
+/**
+ * @name E200 core variants
+ * @{
+ */
+#define PPC_VARIANT_e200z0 200
+#define PPC_VARIANT_e200z2 202
+#define PPC_VARIANT_e200z3 203
+#define PPC_VARIANT_e200z4 204
+/** @} */
+
+/* Inclusion of the PPC implementation specific parameters.*/
+#include "ppcparams.h"
+#include "vectors.h"
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/**
+ * @brief Stack size for the system idle thread.
+ * @details This size depends on the idle thread implementation, usually
+ * the idle thread should take no more space than those reserved
+ * by @p PORT_INT_REQUIRED_STACK.
+ * @note In this port it is set to 32 because the idle thread does have
+ * a stack frame when compiling without optimizations. You may
+ * reduce this value to zero when compiling with optimizations.
+ */
+#if !defined(PORT_IDLE_THREAD_STACK_SIZE) || defined(__DOXYGEN__)
+#define PORT_IDLE_THREAD_STACK_SIZE 32
+#endif
+
+/**
+ * @brief Per-thread stack overhead for interrupts servicing.
+ * @details This constant is used in the calculation of the correct working
+ * area size.
+ * @note In this port this value is conservatively is set to 256 because
+ * there is no separate interrupts stack (yet).
+ */
+#if !defined(PORT_INT_REQUIRED_STACK) || defined(__DOXYGEN__)
+#define PORT_INT_REQUIRED_STACK 256
+#endif
+
+/**
+ * @brief Use VLE instruction set.
+ * @note This parameter is usually set in the Makefile.
+ */
+#if !defined(PPC_USE_VLE)
+#define PPC_USE_VLE TRUE
+#endif
+
+/**
+ * @brief Enables the use of the @p WFI instruction.
+ */
+#if !defined(PPC_ENABLE_WFI_IDLE)
+#define PPC_ENABLE_WFI_IDLE FALSE
+#endif
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+#if PPC_USE_VLE && !PPC_SUPPORTS_VLE
+#error "the selected MCU does not support VLE instructions set"
+#endif
+
+#if !PPC_USE_VLE && !PPC_SUPPORTS_BOOKE
+#error "the selected MCU does not support BookE instructions set"
+#endif
+
+/**
+ * @brief Name of the architecture variant.
+ */
+#if (PPC_VARIANT == PPC_VARIANT_e200z0) || defined(__DOXYGEN__)
+#define PORT_CORE_VARIANT_NAME "e200z0"
+#elif PPC_VARIANT == PPC_VARIANT_e200z2
+#define PORT_CORE_VARIANT_NAME "e200z2"
+#elif PPC_VARIANT == PPC_VARIANT_e200z3
+#define PORT_CORE_VARIANT_NAME "e200z3"
+#elif PPC_VARIANT == PPC_VARIANT_e200z4
+#define PORT_CORE_VARIANT_NAME "e200z4"
+#else
+#error "unknown or unsupported PowerPC variant specified"
+#endif
+
+/**
+ * @brief Port-specific information string.
+ */
+#if PPC_USE_VLE
+#define PORT_INFO "VLE mode"
+#else
+#define PORT_INFO "Book-E mode"
+#endif
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/* The following code is not processed when the file is included from an
+ asm module.*/
+#if !defined(_FROM_ASM_)
+
+/**
+ * @brief Type of system time.
+ */
+#if (CH_CFG_ST_RESOLUTION == 32) || defined(__DOXYGEN__)
+typedef uint32_t systime_t;
+#else
+typedef uint16_t systime_t;
+#endif
+
+/**
+ * @brief Type of stack and memory alignment enforcement.
+ * @note In this architecture the stack alignment is enforced to 64 bits.
+ */
+typedef uint64_t stkalign_t;
+
+/**
+ * @brief Generic PPC register.
+ */
+typedef void *regppc_t;
+
+/**
+ * @brief Mandatory part of a stack frame.
+ */
+struct port_eabi_frame {
+ uint32_t slink; /**< Stack back link. */
+ uint32_t shole; /**< Stack hole for LR storage. */
+};
+
+/**
+ * @brief Interrupt saved context.
+ * @details This structure represents the stack frame saved during a
+ * preemption-capable interrupt handler.
+ * @note R2 and R13 are not saved because those are assumed to be immutable
+ * during the system life cycle.
+ */
+struct port_extctx {
+ struct port_eabi_frame frame;
+ /* Start of the e_stmvsrrw frame (offset 8).*/
+ regppc_t pc;
+ regppc_t msr;
+ /* Start of the e_stmvsprw frame (offset 16).*/
+ regppc_t cr;
+ regppc_t lr;
+ regppc_t ctr;
+ regppc_t xer;
+ /* Start of the e_stmvgprw frame (offset 32).*/
+ regppc_t r0;
+ regppc_t r3;
+ regppc_t r4;
+ regppc_t r5;
+ regppc_t r6;
+ regppc_t r7;
+ regppc_t r8;
+ regppc_t r9;
+ regppc_t r10;
+ regppc_t r11;
+ regppc_t r12;
+ regppc_t padding;
+ };
+
+/**
+ * @brief System saved context.
+ * @details This structure represents the inner stack frame during a context
+ * switching.
+ * @note R2 and R13 are not saved because those are assumed to be immutable
+ * during the system life cycle.
+ * @note LR is stored in the caller contex so it is not present in this
+ * structure.
+ */
+struct port_intctx {
+ regppc_t cr; /* Part of it is not volatile... */
+ regppc_t r14;
+ regppc_t r15;
+ regppc_t r16;
+ regppc_t r17;
+ regppc_t r18;
+ regppc_t r19;
+ regppc_t r20;
+ regppc_t r21;
+ regppc_t r22;
+ regppc_t r23;
+ regppc_t r24;
+ regppc_t r25;
+ regppc_t r26;
+ regppc_t r27;
+ regppc_t r28;
+ regppc_t r29;
+ regppc_t r30;
+ regppc_t r31;
+ regppc_t padding;
+};
+
+/**
+ * @brief Platform dependent part of the @p Thread structure.
+ * @details This structure usually contains just the saved stack pointer
+ * defined as a pointer to a @p port_intctx structure.
+ */
+struct context {
+ struct port_intctx *sp;
+};
+
+#endif /* !defined(_FROM_ASM_) */
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/**
+ * @brief Platform dependent part of the @p chThdCreateI() API.
+ * @details This code usually setup the context switching frame represented
+ * by an @p port_intctx structure.
+ */
+#define PORT_SETUP_CONTEXT(tp, workspace, wsize, pf, arg) { \
+ uint8_t *sp = (uint8_t *)(workspace) + \
+ (wsize) - \
+ sizeof(struct port_eabi_frame); \
+ ((struct port_eabi_frame *)sp)->slink = 0; \
+ ((struct port_eabi_frame *)sp)->shole = (uint32_t)_port_thread_start; \
+ (tp)->p_ctx.sp = (struct port_intctx *)(sp - sizeof(struct port_intctx)); \
+ (tp)->p_ctx.sp->r31 = (regppc_t)(arg); \
+ (tp)->p_ctx.sp->r30 = (regppc_t)(pf); \
+}
+
+/**
+ * @brief Computes the thread working area global size.
+ * @note There is no need to perform alignments in this macro.
+ */
+#define PORT_WA_SIZE(n) (sizeof(struct port_intctx) + \
+ sizeof(struct port_extctx) + \
+ (n) + (PORT_INT_REQUIRED_STACK))
+
+/**
+ * @brief IRQ prologue code.
+ * @details This macro must be inserted at the start of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_PROLOGUE()
+
+/**
+ * @brief IRQ epilogue code.
+ * @details This macro must be inserted at the end of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_EPILOGUE()
+
+/**
+ * @brief IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Fast IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_FAST_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Performs a context switch between two threads.
+ * @details This is the most critical code in any port, this function
+ * is responsible for the context switch between 2 threads.
+ * @note The implementation of this code affects <b>directly</b> the context
+ * switch performance so optimize here as much as you can.
+ *
+ * @param[in] ntp the thread to be switched in
+ * @param[in] otp the thread to be switched out
+ */
+#if !CH_DBG_ENABLE_STACK_CHECK || defined(__DOXYGEN__)
+#define port_switch(ntp, otp) _port_switch(ntp, otp)
+#else
+#define port_switch(ntp, otp) { \
+ register struct port_intctx *sp asm ("%r1"); \
+ if ((stkalign_t *)(sp - 1) < otp->p_stklimit) \
+ chDbgPanic("stack overflow"); \
+ _port_switch(ntp, otp); \
+}
+#endif
+
+/**
+ * @brief Writes to a special register.
+ *
+ * @param[in] spr special register number
+ * @param[in] val value to be written, must be an automatic variable
+ */
+#define port_write_spr(spr, val) \
+ asm volatile ("mtspr %[p0], %[p1]" : : [p0] "n" (spr), [p1] "r" (val))
+
+/**
+ * @brief Writes to a special register.
+ *
+ * @param[in] spr special register number
+ * @param[in] val returned value, must be an automatic variable
+ */
+#define port_read_spr(spr, val) \
+ asm volatile ("mfspr %[p0], %[p1]" : [p0] "=r" (val) : [p1] "n" (spr))
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+/* The following code is not processed when the file is included from an
+ asm module.*/
+#if !defined(_FROM_ASM_)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void _port_switch(thread_t *ntp, thread_t *otp);
+ void _port_thread_start(void);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !defined(_FROM_ASM_) */
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+/* The following code is not processed when the file is included from an
+ asm module.*/
+#if !defined(_FROM_ASM_)
+
+/**
+ * @brief Kernel port layer initialization.
+ * @details IVOR4 and IVOR10 initialization.
+ */
+static inline void port_init(void) {
+ uint32_t n;
+
+ /* Initializing the SPRG0 register to zero, it is required for interrupts
+ handling.*/
+ n = 0;
+ port_write_spr(272, n);
+
+#if PPC_SUPPORTS_IVORS
+ /* The CPU supports IVOR registers, the kernel requires IVOR4 and IVOR10
+ and the initialization is performed here.*/
+ asm volatile ("li %%r3, _IVOR4@l \t\n"
+ "mtIVOR4 %%r3 \t\n"
+ "li %%r3, _IVOR10@l \t\n"
+ "mtIVOR10 %%r3" : : : "r3", "memory");
+#endif
+
+ /* Interrupt controller initialization.*/
+ intc_init();
+}
+
+/**
+ * @brief Returns a word encoding the current interrupts status.
+ *
+ * @return The interrupts status.
+ */
+static inline syssts_t port_get_irq_status(void) {
+ uint32_t sts;
+
+ asm volatile ("mfmsr %[p0]" : [p0] "=r" (sts) :);
+ return sts;
+}
+
+/**
+ * @brief Checks the interrupt status.
+ *
+ * @param[in] sts the interrupt status word
+ *
+ * @return The interrupt status.
+ * @retvel false the word specified a disabled interrupts status.
+ * @retvel true the word specified an enabled interrupts status.
+ */
+static inline bool port_irq_enabled(syssts_t sts) {
+
+ return (bool)((sts & (1 << 15)) != 0);
+}
+
+/**
+ * @brief Determines the current execution context.
+ *
+ * @return The execution context.
+ * @retval false not running in ISR mode.
+ * @retval true running in ISR mode.
+ */
+static inline bool port_is_isr_context(void) {
+ uint32_t sprg0;
+
+ /* The SPRG0 register is increased before entering interrupt handlers and
+ decreased at the end.*/
+ port_read_spr(272, sprg0);
+ return (bool)(sprg0 > 0);
+}
+
+/**
+ * @brief Kernel-lock action.
+ * @note Implemented as global interrupt disable.
+ */
+static inline void port_lock(void) {
+
+ asm volatile ("wrteei 0" : : : "memory");
+}
+
+/**
+ * @brief Kernel-unlock action.
+ * @note Implemented as global interrupt enable.
+ */
+static inline void port_unlock(void) {
+
+ asm volatile("wrteei 1" : : : "memory");
+}
+
+/**
+ * @brief Kernel-lock action from an interrupt handler.
+ * @note Implementation not needed.
+ */
+static inline void port_lock_from_isr(void) {
+
+}
+
+/**
+ * @brief Kernel-unlock action from an interrupt handler.
+ * @note Implementation not needed.
+ */
+static inline void port_unlock_from_isr(void) {
+
+}
+
+/**
+ * @brief Disables all the interrupt sources.
+ * @note Implemented as global interrupt disable.
+ */
+static inline void port_disable(void) {
+
+ asm volatile ("wrteei 0" : : : "memory");
+}
+
+/**
+ * @brief Disables the interrupt sources below kernel-level priority.
+ * @note Same as @p port_disable() in this port, there is no difference
+ * between the two states.
+ */
+static inline void port_suspend(void) {
+
+ asm volatile ("wrteei 0" : : : "memory");
+}
+
+/**
+ * @brief Enables all the interrupt sources.
+ * @note Implemented as global interrupt enable.
+ */
+static inline void port_enable(void) {
+
+ asm volatile ("wrteei 1" : : : "memory");
+}
+
+/**
+ * @brief Enters an architecture-dependent IRQ-waiting mode.
+ * @details The function is meant to return when an interrupt becomes pending.
+ * The simplest implementation is an empty function or macro but this
+ * would not take advantage of architecture-specific power saving
+ * modes.
+ * @note Implemented as an inlined @p wait instruction.
+ */
+static inline void port_wait_for_interrupt(void) {
+
+#if PPC_ENABLE_WFI_IDLE
+ asm volatile ("wait" : : : "memory");
+#endif
+}
+
+/**
+ * @brief Returns the current value of the realtime counter.
+ *
+ * @return The realtime counter value.
+ */
+static inline rtcnt_t port_rt_get_counter_value(void) {
+
+ return 0;
+}
+
+#endif /* !defined(_FROM_ASM_) */
+
+#endif /* _CHCORE_H_ */
+
+/** @} */
diff --git a/os/rt/ports/e200/compilers/GCC/chtypes.h b/os/rt/ports/e200/compilers/GCC/chtypes.h new file mode 100644 index 000000000..074d33c14 --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/chtypes.h @@ -0,0 +1,106 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file PPC/chtypes.h
+ * @brief PowerPC architecture port system types.
+ *
+ * @addtogroup PPC_CORE
+ * @{
+ */
+
+#ifndef _CHTYPES_H_
+#define _CHTYPES_H_
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+/**
+ * @name Common constants
+ */
+/**
+ * @brief Generic 'false' boolean constant.
+ */
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+/**
+ * @brief Generic 'true' boolean constant.
+ */
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE (!FALSE)
+#endif
+/** @} */
+
+/**
+ * @name Derived generic types
+ * @{
+ */
+typedef volatile int8_t vint8_t; /**< Volatile signed 8 bits. */
+typedef volatile uint8_t vuint8_t; /**< Volatile unsigned 8 bits. */
+typedef volatile int16_t vint16_t; /**< Volatile signed 16 bits. */
+typedef volatile uint16_t vuint16_t; /**< Volatile unsigned 16 bits. */
+typedef volatile int32_t vint32_t; /**< Volatile signed 32 bits. */
+typedef volatile uint32_t vuint32_t; /**< Volatile unsigned 32 bits. */
+/** @} */
+
+/**
+ * @name Kernel types
+ * @{
+ */
+typedef uint32_t rtcnt_t; /**< Realtime counter. */
+typedef uint64_t rttime_t; /**< Realtime accumulator. */
+typedef uint32_t syssts_t; /**< System status word. */
+typedef uint8_t tmode_t; /**< Thread flags. */
+typedef uint8_t tstate_t; /**< Thread state. */
+typedef uint8_t trefs_t; /**< Thread references counter. */
+typedef uint8_t tslices_t; /**< Thread time slices counter.*/
+typedef uint32_t tprio_t; /**< Thread priority. */
+typedef int32_t msg_t; /**< Inter-thread message. */
+typedef int32_t eventid_t; /**< Numeric event identifier. */
+typedef uint32_t eventmask_t; /**< Mask of event identifiers. */
+typedef uint32_t eventflags_t; /**< Mask of event flags. */
+typedef int32_t cnt_t; /**< Generic signed counter. */
+typedef uint32_t ucnt_t; /**< Generic unsigned counter. */
+/** @} */
+
+/**
+ * @brief ROM constant modifier.
+ * @note It is set to use the "const" keyword in this port.
+ */
+#define ROMCONST const
+
+/**
+ * @brief Makes functions not inlineable.
+ * @note If the compiler does not support such attribute then the
+ * realtime counter precision could be degraded.
+ */
+#define NOINLINE __attribute__((noinline))
+
+/**
+ * @brief Optimized thread function declaration macro.
+ */
+#define PORT_THD_FUNCTION(tname, arg) msg_t tname(void *arg)
+
+#endif /* _CHTYPES_H_ */
+
+/** @} */
diff --git a/os/rt/ports/e200/compilers/GCC/ivor.s b/os/rt/ports/e200/compilers/GCC/ivor.s new file mode 100644 index 000000000..ae478b49f --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/ivor.s @@ -0,0 +1,252 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file ivor.s
+ * @brief Kernel ISRs.
+ *
+ * @addtogroup PPC_CORE
+ * @{
+ */
+
+#if !defined(FALSE) || defined(__DOXYGEN__)
+#define FALSE 0
+#endif
+
+#if !defined(TRUE) || defined(__DOXYGEN__)
+#define TRUE 1
+#endif
+
+/*
+ * Imports the PPC configuration headers.
+ */
+#define _FROM_ASM_
+#include "chconf.h"
+#include "chcore.h"
+
+#if !defined(__DOXYGEN__)
+ /*
+ * INTC registers address.
+ */
+ .equ INTC_IACKR, 0xfff48010
+ .equ INTC_EOIR, 0xfff48018
+
+ .section .handlers, "ax"
+
+#if PPC_SUPPORTS_DECREMENTER
+ /*
+ * _IVOR10 handler (Book-E decrementer).
+ */
+ .align 4
+ .globl _IVOR10
+ .type _IVOR10, @function
+_IVOR10:
+ /* Saving the external context (port_extctx structure).*/
+ stwu %sp, -80(%sp)
+#if PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI
+ e_stmvsrrw 8(%sp) /* Saves PC, MSR. */
+ e_stmvsprw 16(%sp) /* Saves CR, LR, CTR, XER. */
+ e_stmvgprw 32(%sp) /* Saves GPR0, GPR3...GPR12. */
+#else /* !(PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI) */
+ stw %r0, 32(%sp) /* Saves GPR0. */
+ mfSRR0 %r0
+ stw %r0, 8(%sp) /* Saves PC. */
+ mfSRR1 %r0
+ stw %r0, 12(%sp) /* Saves MSR. */
+ mfCR %r0
+ stw %r0, 16(%sp) /* Saves CR. */
+ mfLR %r0
+ stw %r0, 20(%sp) /* Saves LR. */
+ mfCTR %r0
+ stw %r0, 24(%sp) /* Saves CTR. */
+ mfXER %r0
+ stw %r0, 28(%sp) /* Saves XER. */
+ stw %r3, 36(%sp) /* Saves GPR3...GPR12. */
+ stw %r4, 40(%sp)
+ stw %r5, 44(%sp)
+ stw %r6, 48(%sp)
+ stw %r7, 52(%sp)
+ stw %r8, 56(%sp)
+ stw %r9, 60(%sp)
+ stw %r10, 64(%sp)
+ stw %r11, 68(%sp)
+ stw %r12, 72(%sp)
+#endif /* !(PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI) */
+
+ /* Increasing the SPGR0 register.*/
+ mfspr %r0, 272
+ eaddi %r0, %r0, 1
+ mtspr 272, %r0
+
+ /* Reset DIE bit in TSR register.*/
+ lis %r3, 0x0800 /* DIS bit mask. */
+ mtspr 336, %r3 /* TSR register. */
+
+#if PPC_USE_IRQ_PREEMPTION
+ /* Allows preemption while executing the software handler.*/
+ wrteei 1
+#endif
+
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_enter_isr
+ bl dbg_check_lock_from_isr
+#endif
+ /* System tick handler invocation.*/
+ bl chSysTimerHandlerI
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock_from_isr
+ bl dbg_check_leave_isr
+#endif
+
+#if PPC_USE_IRQ_PREEMPTION
+ /* Prevents preemption again.*/
+ wrteei 0
+#endif
+
+ /* Jumps to the common IVOR epilogue code.*/
+ b _ivor_exit
+#endif /* PPC_SUPPORTS_DECREMENTER */
+
+ /*
+ * _IVOR4 handler (Book-E external interrupt).
+ */
+ .align 4
+ .globl _IVOR4
+ .type _IVOR4, @function
+_IVOR4:
+ /* Saving the external context (port_extctx structure).*/
+ stwu %sp, -80(%sp)
+#if PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI
+ e_stmvsrrw 8(%sp) /* Saves PC, MSR. */
+ e_stmvsprw 16(%sp) /* Saves CR, LR, CTR, XER. */
+ e_stmvgprw 32(%sp) /* Saves GPR0, GPR3...GPR12. */
+#else /* !(PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI) */
+ stw %r0, 32(%sp) /* Saves GPR0. */
+ mfSRR0 %r0
+ stw %r0, 8(%sp) /* Saves PC. */
+ mfSRR1 %r0
+ stw %r0, 12(%sp) /* Saves MSR. */
+ mfCR %r0
+ stw %r0, 16(%sp) /* Saves CR. */
+ mfLR %r0
+ stw %r0, 20(%sp) /* Saves LR. */
+ mfCTR %r0
+ stw %r0, 24(%sp) /* Saves CTR. */
+ mfXER %r0
+ stw %r0, 28(%sp) /* Saves XER. */
+ stw %r3, 36(%sp) /* Saves GPR3...GPR12. */
+ stw %r4, 40(%sp)
+ stw %r5, 44(%sp)
+ stw %r6, 48(%sp)
+ stw %r7, 52(%sp)
+ stw %r8, 56(%sp)
+ stw %r9, 60(%sp)
+ stw %r10, 64(%sp)
+ stw %r11, 68(%sp)
+ stw %r12, 72(%sp)
+#endif /* !(PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI) */
+
+ /* Increasing the SPGR0 register.*/
+ mfspr %r0, 272
+ eaddi %r0, %r0, 1
+ mtspr 272, %r0
+
+ /* Software vector address from the INTC register.*/
+ lis %r3, INTC_IACKR@h
+ ori %r3, %r3, INTC_IACKR@l /* IACKR register address. */
+ lwz %r3, 0(%r3) /* IACKR register value. */
+ lwz %r3, 0(%r3)
+ mtCTR %r3 /* Software handler address. */
+
+#if PPC_USE_IRQ_PREEMPTION
+ /* Allows preemption while executing the software handler.*/
+ wrteei 1
+#endif
+
+ /* Exectes the software handler.*/
+ bctrl
+
+#if PPC_USE_IRQ_PREEMPTION
+ /* Prevents preemption again.*/
+ wrteei 0
+#endif
+
+ /* Informs the INTC that the interrupt has been served.*/
+ mbar 0
+ lis %r3, INTC_EOIR@h
+ ori %r3, %r3, INTC_EOIR@l
+ stw %r3, 0(%r3) /* Writing any value should do. */
+
+ /* Common IVOR epilogue code, context restore.*/
+ .globl _ivor_exit
+_ivor_exit:
+ /* Decreasing the SPGR0 register.*/
+ mfspr %r0, 272
+ eaddi %r0, %r0, -1
+ mtspr 272, %r0
+
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_lock
+#endif
+ bl chSchIsPreemptionRequired
+ cmpli cr0, %r3, 0
+ beq cr0, .noresch
+ bl chSchDoReschedule
+.noresch:
+#if CH_DBG_SYSTEM_STATE_CHECK
+ bl dbg_check_unlock
+#endif
+
+ /* Restoring the external context.*/
+#if PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI
+ e_lmvgprw 32(%sp) /* Restores GPR0, GPR3...GPR12. */
+ e_lmvsprw 16(%sp) /* Restores CR, LR, CTR, XER. */
+ e_lmvsrrw 8(%sp) /* Restores PC, MSR. */
+#else /*!(PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI) */
+ lwz %r3, 36(%sp) /* Restores GPR3...GPR12. */
+ lwz %r4, 40(%sp)
+ lwz %r5, 44(%sp)
+ lwz %r6, 48(%sp)
+ lwz %r7, 52(%sp)
+ lwz %r8, 56(%sp)
+ lwz %r9, 60(%sp)
+ lwz %r10, 64(%sp)
+ lwz %r11, 68(%sp)
+ lwz %r12, 72(%sp)
+ lwz %r0, 8(%sp)
+ mtSRR0 %r0 /* Restores PC. */
+ lwz %r0, 12(%sp)
+ mtSRR1 %r0 /* Restores MSR. */
+ lwz %r0, 16(%sp)
+ mtCR %r0 /* Restores CR. */
+ lwz %r0, 20(%sp)
+ mtLR %r0 /* Restores LR. */
+ lwz %r0, 24(%sp)
+ mtCTR %r0 /* Restores CTR. */
+ lwz %r0, 28(%sp)
+ mtXER %r0 /* Restores XER. */
+ lwz %r0, 32(%sp) /* Restores GPR0. */
+#endif /* !(PPC_USE_VLE && PPC_SUPPORTS_VLE_MULTI) */
+ addi %sp, %sp, 80 /* Back to the previous frame. */
+ rfi
+
+#endif /* !defined(__DOXYGEN__) */
+
+/** @} */
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc560bcxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc560bcxx.mk new file mode 100644 index 000000000..cdd0b9c0e --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc560bcxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z0 SPC560BCxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC560BCxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC560BCxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc560bxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc560bxx.mk new file mode 100644 index 000000000..c1b8447cf --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc560bxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z0 SPC560Bxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC560Bxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC560Bxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc560dxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc560dxx.mk new file mode 100644 index 000000000..9959e375c --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc560dxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z0 SPC560Dxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC560Dxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC560Dxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc560pxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc560pxx.mk new file mode 100644 index 000000000..e9d078aff --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc560pxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z0 SPC560Pxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC560Pxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC560Pxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc563mxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc563mxx.mk new file mode 100644 index 000000000..02b8069ad --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc563mxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z3 SPC563Mxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC563Mxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC563Mxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc564axx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc564axx.mk new file mode 100644 index 000000000..8364e0ce8 --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc564axx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z4 SPC564Axx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC564Axx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC564Axx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc56ecxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc56ecxx.mk new file mode 100644 index 000000000..4a951d1c2 --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc56ecxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z4 SPC56ECxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC56ECxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC56ECxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/ports/e200/compilers/GCC/mk/port_spc56elxx.mk b/os/rt/ports/e200/compilers/GCC/mk/port_spc56elxx.mk new file mode 100644 index 000000000..adf2d5cb8 --- /dev/null +++ b/os/rt/ports/e200/compilers/GCC/mk/port_spc56elxx.mk @@ -0,0 +1,14 @@ +# List of the ChibiOS/RT e200z4 SPC56ELxx port files.
+PORTSRC = ${CHIBIOS}/os/rt/ports/e200/chcore.c
+
+PORTASM = $(CHIBIOS)/os/common/ports/e200/devices/SPC56ELxx/boot.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/vectors.s \
+ $(CHIBIOS)/os/common/ports/e200/compilers/GCC/crt0.s \
+ $(CHIBIOS)/os/rt/ports/e200/compilers/GCC/ivor.s
+
+PORTINC = ${CHIBIOS}/os/common/ports/e200/compilers/GCC \
+ ${CHIBIOS}/os/common/ports/e200/devices/SPC56ELxx \
+ ${CHIBIOS}/os/rt/ports/e200 \
+ ${CHIBIOS}/os/rt/ports/e200/compilers/GCC
+
+PORTLD = ${CHIBIOS}/os/common/ports/e200/compilers/GCC/ld
diff --git a/os/rt/rt.dox b/os/rt/rt.dox new file mode 100644 index 000000000..05753a8f6 --- /dev/null +++ b/os/rt/rt.dox @@ -0,0 +1,173 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @defgroup kernel Kernel
+ * @details The kernel is the portable part of ChibiOS/RT, this section
+ * documents the various kernel subsystems.
+ */
+
+/**
+ * @defgroup kernel_info Version Numbers and Identification
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup config Configuration
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup types Types
+ * @details The system types are defined into the port layer, please refer to
+ * the core port implementation section.
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup base Base Kernel Services
+ * @details Base kernel services, the base subsystems are always included in
+ * the OS builds.
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup system System Management
+ * @ingroup base
+ */
+
+/**
+ * @defgroup scheduler Scheduler
+ * @ingroup base
+ */
+
+/**
+ * @defgroup threads Threads
+ * @ingroup base
+ */
+
+/**
+ * @defgroup time Time and Virtual Timers
+ * @ingroup base
+ */
+
+/**
+ * @defgroup synchronization Synchronization
+ * @details Synchronization services.
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup semaphores Counting Semaphores
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup binary_semaphores Binary Semaphores
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup mutexes Mutexes
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup condvars Condition Variables
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup events Event Flags
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup messages Synchronous Messages
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup mailboxes Mailboxes
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup io_queues I/O Queues
+ * @ingroup synchronization
+ */
+
+/**
+ * @defgroup memory Memory Management
+ * @details Memory Management services.
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup memcore Core Memory Manager
+ * @ingroup memory
+ */
+
+/**
+ * @defgroup heaps Heaps
+ * @ingroup memory
+ */
+
+/**
+ * @defgroup pools Memory Pools
+ * @ingroup memory
+ */
+
+/**
+ * @defgroup dynamic_threads Dynamic Threads
+ * @ingroup memory
+ */
+
+ /**
+ * @defgroup streams Streams and Files
+ * @details Stream and Files interfaces.
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup data_streams Abstract Sequential Streams
+ * @ingroup streams
+ */
+
+/**
+ * @defgroup data_files Abstract File Streams
+ * @ingroup streams
+ */
+
+/**
+ * @defgroup registry Registry
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup debug Debug
+ * @ingroup kernel
+ */
+
+/**
+ * @defgroup internals Internals
+ * @ingroup kernel
+ */
+
diff --git a/os/rt/rt.mk b/os/rt/rt.mk new file mode 100644 index 000000000..55a189f75 --- /dev/null +++ b/os/rt/rt.mk @@ -0,0 +1,24 @@ +# List of all the ChibiOS/RT kernel files, there is no need to remove the files
+# from this list, you can disable parts of the kernel by editing chconf.h.
+KERNSRC = ${CHIBIOS}/os/rt/src/chsys.c \
+ ${CHIBIOS}/os/rt/src/chdebug.c \
+ ${CHIBIOS}/os/rt/src/chtm.c \
+ ${CHIBIOS}/os/rt/src/chstats.c \
+ ${CHIBIOS}/os/rt/src/chschd.c \
+ ${CHIBIOS}/os/rt/src/chvt.c \
+ ${CHIBIOS}/os/rt/src/chthreads.c \
+ ${CHIBIOS}/os/rt/src/chdynamic.c \
+ ${CHIBIOS}/os/rt/src/chregistry.c \
+ ${CHIBIOS}/os/rt/src/chsem.c \
+ ${CHIBIOS}/os/rt/src/chmtx.c \
+ ${CHIBIOS}/os/rt/src/chcond.c \
+ ${CHIBIOS}/os/rt/src/chevents.c \
+ ${CHIBIOS}/os/rt/src/chmsg.c \
+ ${CHIBIOS}/os/rt/src/chmboxes.c \
+ ${CHIBIOS}/os/rt/src/chqueues.c \
+ ${CHIBIOS}/os/rt/src/chmemcore.c \
+ ${CHIBIOS}/os/rt/src/chheap.c \
+ ${CHIBIOS}/os/rt/src/chmempools.c
+
+# Required include directories
+KERNINC = ${CHIBIOS}/os/rt/include
diff --git a/os/rt/src/chcond.c b/os/rt/src/chcond.c new file mode 100644 index 000000000..f56f508b0 --- /dev/null +++ b/os/rt/src/chcond.c @@ -0,0 +1,310 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+/*
+ Concepts and parts of this file have been contributed by Leon Woestenberg.
+ */
+
+/**
+ * @file chcond.c
+ * @brief Condition Variables code.
+ *
+ * @addtogroup condition variables Condition Variables
+ * @details This module implements the Condition Variables mechanism. Condition
+ * variables are an extensions to the mutex subsystem and cannot
+ * work alone.
+ * <h2>Operation mode</h2>
+ * The condition variable is a synchronization object meant to be
+ * used inside a zone protected by a mutex. Mutexes and condition
+ * variables together can implement a Monitor construct.
+ * @pre In order to use the condition variable APIs the @p CH_CFG_USE_CONDVARS
+ * option must be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_CONDVARS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes s @p condition_variable_t structure.
+ *
+ * @param[out] cp pointer to a @p condition_variable_t structure
+ *
+ * @init
+ */
+void chCondObjectInit(condition_variable_t *cp) {
+
+ chDbgCheck(cp != NULL);
+
+ queue_init(&cp->c_queue);
+}
+
+/**
+ * @brief Signals one thread that is waiting on the condition variable.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ *
+ * @api
+ */
+void chCondSignal(condition_variable_t *cp) {
+
+ chDbgCheck(cp != NULL);
+
+ chSysLock();
+ if (queue_notempty(&cp->c_queue))
+ chSchWakeupS(queue_fifo_remove(&cp->c_queue), MSG_OK);
+ chSysUnlock();
+}
+
+/**
+ * @brief Signals one thread that is waiting on the condition variable.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ *
+ * @iclass
+ */
+void chCondSignalI(condition_variable_t *cp) {
+
+ chDbgCheckClassI();
+ chDbgCheck(cp != NULL);
+
+ if (queue_notempty(&cp->c_queue)) {
+ thread_t *tp = queue_fifo_remove(&cp->c_queue);
+ tp->p_u.rdymsg = MSG_OK;
+ chSchReadyI(tp);
+ }
+}
+
+/**
+ * @brief Signals all threads that are waiting on the condition variable.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ *
+ * @api
+ */
+void chCondBroadcast(condition_variable_t *cp) {
+
+ chSysLock();
+ chCondBroadcastI(cp);
+ chSchRescheduleS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Signals all threads that are waiting on the condition variable.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ *
+ * @iclass
+ */
+void chCondBroadcastI(condition_variable_t *cp) {
+
+ chDbgCheckClassI();
+ chDbgCheck(cp != NULL);
+
+ /* Empties the condition variable queue and inserts all the threads into the
+ ready list in FIFO order. The wakeup message is set to @p MSG_RESET in
+ order to make a chCondBroadcast() detectable from a chCondSignal().*/
+ while (cp->c_queue.p_next != (void *)&cp->c_queue)
+ chSchReadyI(queue_fifo_remove(&cp->c_queue))->p_u.rdymsg = MSG_RESET;
+}
+
+/**
+ * @brief Waits on the condition variable releasing the mutex lock.
+ * @details Releases the currently owned mutex, waits on the condition
+ * variable, and finally acquires the mutex again. All the sequence
+ * is performed atomically.
+ * @pre The invoking thread <b>must</b> have at least one owned mutex.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ * @return A message specifying how the invoking thread has been
+ * released from the condition variable.
+ * @retval MSG_OK if the condition variable has been signaled using
+ * @p chCondSignal().
+ * @retval MSG_RESET if the condition variable has been signaled using
+ * @p chCondBroadcast().
+ *
+ * @api
+ */
+msg_t chCondWait(condition_variable_t *cp) {
+ msg_t msg;
+
+ chSysLock();
+ msg = chCondWaitS(cp);
+ chSysUnlock();
+ return msg;
+}
+
+/**
+ * @brief Waits on the condition variable releasing the mutex lock.
+ * @details Releases the currently owned mutex, waits on the condition
+ * variable, and finally acquires the mutex again. All the sequence
+ * is performed atomically.
+ * @pre The invoking thread <b>must</b> have at least one owned mutex.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ * @return A message specifying how the invoking thread has been
+ * released from the condition variable.
+ * @retval MSG_OK if the condition variable has been signaled using
+ * @p chCondSignal().
+ * @retval MSG_RESET if the condition variable has been signaled using
+ * @p chCondBroadcast().
+ *
+ * @sclass
+ */
+msg_t chCondWaitS(condition_variable_t *cp) {
+ thread_t *ctp = currp;
+ mutex_t *mp;
+ msg_t msg;
+
+ chDbgCheckClassS();
+ chDbgCheck(cp != NULL);
+ chDbgAssert(ctp->p_mtxlist != NULL, "not owning a mutex");
+
+ mp = chMtxGetNextMutexS();
+ chMtxUnlockS(mp);
+ ctp->p_u.wtobjp = cp;
+ queue_prio_insert(ctp, &cp->c_queue);
+ chSchGoSleepS(CH_STATE_WTCOND);
+ msg = ctp->p_u.rdymsg;
+ chMtxLockS(mp);
+ return msg;
+}
+
+#if CH_CFG_USE_CONDVARS_TIMEOUT || defined(__DOXYGEN__)
+/**
+ * @brief Waits on the condition variable releasing the mutex lock.
+ * @details Releases the currently owned mutex, waits on the condition
+ * variable, and finally acquires the mutex again. All the sequence
+ * is performed atomically.
+ * @pre The invoking thread <b>must</b> have at least one owned mutex.
+ * @pre The configuration option @p CH_CFG_USE_CONDVARS_TIMEOUT must be enabled
+ * in order to use this function.
+ * @post Exiting the function because a timeout does not re-acquire the
+ * mutex, the mutex ownership is lost.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ * @param[in] time the number of ticks before the operation timeouts, the
+ * special values are handled as follow:
+ * - @a TIME_INFINITE no timeout.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ * @return A message specifying how the invoking thread has been
+ * released from the condition variable.
+ * @retval MSG_OK if the condition variable has been signaled using
+ * @p chCondSignal().
+ * @retval MSG_RESET if the condition variable has been signaled using
+ * @p chCondBroadcast().
+ * @retval MSG_TIMEOUT if the condition variable has not been signaled within
+ * the specified timeout.
+ *
+ * @api
+ */
+msg_t chCondWaitTimeout(condition_variable_t *cp, systime_t time) {
+ msg_t msg;
+
+ chSysLock();
+ msg = chCondWaitTimeoutS(cp, time);
+ chSysUnlock();
+ return msg;
+}
+
+/**
+ * @brief Waits on the condition variable releasing the mutex lock.
+ * @details Releases the currently owned mutex, waits on the condition
+ * variable, and finally acquires the mutex again. All the sequence
+ * is performed atomically.
+ * @pre The invoking thread <b>must</b> have at least one owned mutex.
+ * @pre The configuration option @p CH_CFG_USE_CONDVARS_TIMEOUT must be enabled
+ * in order to use this function.
+ * @post Exiting the function because a timeout does not re-acquire the
+ * mutex, the mutex ownership is lost.
+ *
+ * @param[in] cp pointer to the @p condition_variable_t structure
+ * @param[in] time the number of ticks before the operation timeouts, the
+ * special values are handled as follow:
+ * - @a TIME_INFINITE no timeout.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ * @return A message specifying how the invoking thread has been
+ * released from the condition variable.
+ * @retval MSG_OK if the condition variable has been signaled using
+ * @p chCondSignal().
+ * @retval MSG_RESET if the condition variable has been signaled using
+ * @p chCondBroadcast().
+ * @retval MSG_TIMEOUT if the condition variable has not been signaled within
+ * the specified timeout.
+ *
+ * @sclass
+ */
+msg_t chCondWaitTimeoutS(condition_variable_t *cp, systime_t time) {
+ mutex_t *mp;
+ msg_t msg;
+
+ chDbgCheckClassS();
+ chDbgCheck((cp != NULL) && (time != TIME_IMMEDIATE));
+ chDbgAssert(currp->p_mtxlist != NULL, "not owning a mutex");
+
+ mp = chMtxGetNextMutexS();
+ chMtxUnlockS(mp);
+ currp->p_u.wtobjp = cp;
+ queue_prio_insert(currp, &cp->c_queue);
+ msg = chSchGoSleepTimeoutS(CH_STATE_WTCOND, time);
+ if (msg != MSG_TIMEOUT)
+ chMtxLockS(mp);
+ return msg;
+}
+#endif /* CH_CFG_USE_CONDVARS_TIMEOUT */
+
+#endif /* CH_CFG_USE_CONDVARS */
+
+/** @} */
diff --git a/os/rt/src/chdebug.c b/os/rt/src/chdebug.c new file mode 100644 index 000000000..696a293cd --- /dev/null +++ b/os/rt/src/chdebug.c @@ -0,0 +1,247 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chdebug.c
+ * @brief ChibiOS/RT Debug code.
+ *
+ * @addtogroup debug
+ * @details Debug APIs and services:
+ * - Runtime system state and call protocol check. The following
+ * panic messages can be generated:
+ * - SV#1, misplaced @p chSysDisable().
+ * - SV#2, misplaced @p chSysSuspend()
+ * - SV#3, misplaced @p chSysEnable().
+ * - SV#4, misplaced @p chSysLock().
+ * - SV#5, misplaced @p chSysUnlock().
+ * - SV#6, misplaced @p chSysLockFromIsr().
+ * - SV#7, misplaced @p chSysUnlockFromIsr().
+ * - SV#8, misplaced @p CH_IRQ_PROLOGUE().
+ * - SV#9, misplaced @p CH_IRQ_EPILOGUE().
+ * - SV#10, misplaced I-class function.
+ * - SV#11, misplaced S-class function.
+ * .
+ * - Trace buffer.
+ * - Parameters check.
+ * - Kernel assertions.
+ * - Kernel panics.
+ * .
+ * @note Stack checks are not implemented in this module but in the port
+ * layer in an architecture-dependent way.
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+#if CH_DBG_SYSTEM_STATE_CHECK || defined(__DOXYGEN__)
+/**
+ * @brief Guard code for @p chSysDisable().
+ *
+ * @notapi
+ */
+void _dbg_check_disable(void) {
+
+ if ((ch.dbg_isr_cnt != 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#1");
+}
+
+/**
+ * @brief Guard code for @p chSysSuspend().
+ *
+ * @notapi
+ */
+void _dbg_check_suspend(void) {
+
+ if ((ch.dbg_isr_cnt != 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#2");
+}
+
+/**
+ * @brief Guard code for @p chSysEnable().
+ *
+ * @notapi
+ */
+void _dbg_check_enable(void) {
+
+ if ((ch.dbg_isr_cnt != 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#3");
+}
+
+/**
+ * @brief Guard code for @p chSysLock().
+ *
+ * @notapi
+ */
+void _dbg_check_lock(void) {
+
+ if ((ch.dbg_isr_cnt != 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#4");
+ _dbg_enter_lock();
+}
+
+/**
+ * @brief Guard code for @p chSysUnlock().
+ *
+ * @notapi
+ */
+void _dbg_check_unlock(void) {
+
+ if ((ch.dbg_isr_cnt != 0) || (ch.dbg_lock_cnt <= 0))
+ chSysHalt("SV#5");
+ _dbg_leave_lock();
+}
+
+/**
+ * @brief Guard code for @p chSysLockFromIsr().
+ *
+ * @notapi
+ */
+void _dbg_check_lock_from_isr(void) {
+
+ if ((ch.dbg_isr_cnt <= 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#6");
+ _dbg_enter_lock();
+}
+
+/**
+ * @brief Guard code for @p chSysUnlockFromIsr().
+ *
+ * @notapi
+ */
+void _dbg_check_unlock_from_isr(void) {
+
+ if ((ch.dbg_isr_cnt <= 0) || (ch.dbg_lock_cnt <= 0))
+ chSysHalt("SV#7");
+ _dbg_leave_lock();
+}
+
+/**
+ * @brief Guard code for @p CH_IRQ_PROLOGUE().
+ *
+ * @notapi
+ */
+void _dbg_check_enter_isr(void) {
+
+ port_lock_from_isr();
+ if ((ch.dbg_isr_cnt < 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#8");
+ ch.dbg_isr_cnt++;
+ port_unlock_from_isr();
+}
+
+/**
+ * @brief Guard code for @p CH_IRQ_EPILOGUE().
+ *
+ * @notapi
+ */
+void _dbg_check_leave_isr(void) {
+
+ port_lock_from_isr();
+ if ((ch.dbg_isr_cnt <= 0) || (ch.dbg_lock_cnt != 0))
+ chSysHalt("SV#9");
+ ch.dbg_isr_cnt--;
+ port_unlock_from_isr();
+}
+
+/**
+ * @brief I-class functions context check.
+ * @details Verifies that the system is in an appropriate state for invoking
+ * an I-class API function. A panic is generated if the state is
+ * not compatible.
+ *
+ * @api
+ */
+void chDbgCheckClassI(void) {
+
+ if ((ch.dbg_isr_cnt < 0) || (ch.dbg_lock_cnt <= 0))
+ chSysHalt("SV#10");
+}
+
+/**
+ * @brief S-class functions context check.
+ * @details Verifies that the system is in an appropriate state for invoking
+ * an S-class API function. A panic is generated if the state is
+ * not compatible.
+ *
+ * @api
+ */
+void chDbgCheckClassS(void) {
+
+ if ((ch.dbg_isr_cnt != 0) || (ch.dbg_lock_cnt <= 0))
+ chSysHalt("SV#11");
+}
+
+#endif /* CH_DBG_SYSTEM_STATE_CHECK */
+
+#if CH_DBG_ENABLE_TRACE || defined(__DOXYGEN__)
+/**
+ * @brief Trace circular buffer subsystem initialization.
+ * @note Internal use only.
+ */
+void _trace_init(void) {
+
+ ch.dbg_trace_buffer.tb_size = CH_DBG_TRACE_BUFFER_SIZE;
+ ch.dbg_trace_buffer.tb_ptr = &ch.dbg_trace_buffer.tb_buffer[0];
+}
+
+/**
+ * @brief Inserts in the circular debug trace buffer a context switch record.
+ *
+ * @param[in] otp the thread being switched out
+ *
+ * @notapi
+ */
+void _dbg_trace(thread_t *otp) {
+
+ ch.dbg_trace_buffer.tb_ptr->se_time = chVTGetSystemTimeX();
+ ch.dbg_trace_buffer.tb_ptr->se_tp = currp;
+ ch.dbg_trace_buffer.tb_ptr->se_wtobjp = otp->p_u.wtobjp;
+ ch.dbg_trace_buffer.tb_ptr->se_state = (uint8_t)otp->p_state;
+ if (++ch.dbg_trace_buffer.tb_ptr >=
+ &ch.dbg_trace_buffer.tb_buffer[CH_DBG_TRACE_BUFFER_SIZE])
+ ch.dbg_trace_buffer.tb_ptr = &ch.dbg_trace_buffer.tb_buffer[0];
+}
+#endif /* CH_DBG_ENABLE_TRACE */
+
+/** @} */
diff --git a/os/rt/src/chdynamic.c b/os/rt/src/chdynamic.c new file mode 100644 index 000000000..5dbea6c7e --- /dev/null +++ b/os/rt/src/chdynamic.c @@ -0,0 +1,228 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chdynamic.c
+ * @brief Dynamic threads code.
+ *
+ * @addtogroup dynamic_threads
+ * @details Dynamic threads related APIs and services.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_DYNAMIC || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Adds a reference to a thread object.
+ * @pre The configuration option @p CH_CFG_USE_DYNAMIC must be enabled in order
+ * to use this function.
+ *
+ * @param[in] tp pointer to the thread
+ * @return The same thread pointer passed as parameter
+ * representing the new reference.
+ *
+ * @api
+ */
+thread_t *chThdAddRef(thread_t *tp) {
+
+ chSysLock();
+ chDbgAssert(tp->p_refs < 255, "too many references");
+ tp->p_refs++;
+ chSysUnlock();
+ return tp;
+}
+
+/**
+ * @brief Releases a reference to a thread object.
+ * @details If the references counter reaches zero <b>and</b> the thread
+ * is in the @p CH_STATE_FINAL state then the thread's memory is
+ * returned to the proper allocator.
+ * @pre The configuration option @p CH_CFG_USE_DYNAMIC must be enabled in order
+ * to use this function.
+ * @note Static threads are not affected.
+ *
+ * @param[in] tp pointer to the thread
+ *
+ * @api
+ */
+void chThdRelease(thread_t *tp) {
+ trefs_t refs;
+
+ chSysLock();
+ chDbgAssert(tp->p_refs > 0, "not referenced");
+ refs = --tp->p_refs;
+ chSysUnlock();
+
+ /* If the references counter reaches zero and the thread is in its
+ terminated state then the memory can be returned to the proper
+ allocator. Of course static threads are not affected.*/
+ if ((refs == 0) && (tp->p_state == CH_STATE_FINAL)) {
+ switch (tp->p_flags & CH_FLAG_MODE_MASK) {
+#if CH_CFG_USE_HEAP
+ case CH_FLAG_MODE_HEAP:
+#if CH_CFG_USE_REGISTRY
+ REG_REMOVE(tp);
+#endif
+ chHeapFree(tp);
+ break;
+#endif
+#if CH_CFG_USE_MEMPOOLS
+ case CH_FLAG_MODE_MEMPOOL:
+#if CH_CFG_USE_REGISTRY
+ REG_REMOVE(tp);
+#endif
+ chPoolFree(tp->p_mpool, tp);
+ break;
+#endif
+ }
+ }
+}
+
+#if CH_CFG_USE_HEAP || defined(__DOXYGEN__)
+/**
+ * @brief Creates a new thread allocating the memory from the heap.
+ * @pre The configuration options @p CH_CFG_USE_DYNAMIC and @p CH_CFG_USE_HEAP
+ * must be enabled in order to use this function.
+ * @note A thread can terminate by calling @p chThdExit() or by simply
+ * returning from its main function.
+ * @note The memory allocated for the thread is not released when the thread
+ * terminates but when a @p chThdWait() is performed.
+ *
+ * @param[in] heapp heap from which allocate the memory or @p NULL for the
+ * default heap
+ * @param[in] size size of the working area to be allocated
+ * @param[in] prio the priority level for the new thread
+ * @param[in] pf the thread function
+ * @param[in] arg an argument passed to the thread function. It can be
+ * @p NULL.
+ * @return The pointer to the @p thread_t structure allocated for
+ * the thread into the working space area.
+ * @retval NULL if the memory cannot be allocated.
+ *
+ * @api
+ */
+thread_t *chThdCreateFromHeap(memory_heap_t *heapp, size_t size,
+ tprio_t prio, tfunc_t pf, void *arg) {
+ void *wsp;
+ thread_t *tp;
+
+ wsp = chHeapAlloc(heapp, size);
+ if (wsp == NULL)
+ return NULL;
+
+#if CH_DBG_FILL_THREADS
+ _thread_memfill((uint8_t *)wsp,
+ (uint8_t *)wsp + sizeof(thread_t),
+ CH_DBG_THREAD_FILL_VALUE);
+ _thread_memfill((uint8_t *)wsp + sizeof(thread_t),
+ (uint8_t *)wsp + size,
+ CH_DBG_STACK_FILL_VALUE);
+#endif
+
+ chSysLock();
+ tp = chThdCreateI(wsp, size, prio, pf, arg);
+ tp->p_flags = CH_FLAG_MODE_HEAP;
+ chSchWakeupS(tp, MSG_OK);
+ chSysUnlock();
+ return tp;
+}
+#endif /* CH_CFG_USE_HEAP */
+
+#if CH_CFG_USE_MEMPOOLS || defined(__DOXYGEN__)
+/**
+ * @brief Creates a new thread allocating the memory from the specified
+ * memory pool.
+ * @pre The configuration options @p CH_CFG_USE_DYNAMIC and @p CH_CFG_USE_MEMPOOLS
+ * must be enabled in order to use this function.
+ * @note A thread can terminate by calling @p chThdExit() or by simply
+ * returning from its main function.
+ * @note The memory allocated for the thread is not released when the thread
+ * terminates but when a @p chThdWait() is performed.
+ *
+ * @param[in] mp pointer to the memory pool object
+ * @param[in] prio the priority level for the new thread
+ * @param[in] pf the thread function
+ * @param[in] arg an argument passed to the thread function. It can be
+ * @p NULL.
+ * @return The pointer to the @p thread_t structure allocated for
+ * the thread into the working space area.
+ * @retval NULL if the memory pool is empty.
+ *
+ * @api
+ */
+thread_t *chThdCreateFromMemoryPool(memory_pool_t *mp, tprio_t prio,
+ tfunc_t pf, void *arg) {
+ void *wsp;
+ thread_t *tp;
+
+ chDbgCheck(mp != NULL);
+
+ wsp = chPoolAlloc(mp);
+ if (wsp == NULL)
+ return NULL;
+
+#if CH_DBG_FILL_THREADS
+ _thread_memfill((uint8_t *)wsp,
+ (uint8_t *)wsp + sizeof(thread_t),
+ CH_DBG_THREAD_FILL_VALUE);
+ _thread_memfill((uint8_t *)wsp + sizeof(thread_t),
+ (uint8_t *)wsp + mp->mp_object_size,
+ CH_DBG_STACK_FILL_VALUE);
+#endif
+
+ chSysLock();
+ tp = chThdCreateI(wsp, mp->mp_object_size, prio, pf, arg);
+ tp->p_flags = CH_FLAG_MODE_MEMPOOL;
+ tp->p_mpool = mp;
+ chSchWakeupS(tp, MSG_OK);
+ chSysUnlock();
+ return tp;
+}
+#endif /* CH_CFG_USE_MEMPOOLS */
+
+#endif /* CH_CFG_USE_DYNAMIC */
+
+/** @} */
diff --git a/os/rt/src/chevents.c b/os/rt/src/chevents.c new file mode 100644 index 000000000..389e2505b --- /dev/null +++ b/os/rt/src/chevents.c @@ -0,0 +1,575 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+/*
+ Concepts and parts of this file have been contributed by Scott (skute).
+ */
+
+/**
+ * @file chevents.c
+ * @brief Events code.
+ *
+ * @addtogroup events
+ * @details Event Flags, Event Sources and Event Listeners.
+ * <h2>Operation mode</h2>
+ * Each thread has a mask of pending event flags inside its
+ * @p thread_t structure.
+ * Operations defined for event flags:
+ * - <b>Wait</b>, the invoking thread goes to sleep until a certain
+ * AND/OR combination of event flags becomes pending.
+ * - <b>Clear</b>, a mask of event flags is cleared from the pending
+ * events mask, the cleared event flags mask is returned (only the
+ * flags that were actually pending and then cleared).
+ * - <b>Signal</b>, an event mask is directly ORed to the mask of the
+ * signaled thread.
+ * - <b>Broadcast</b>, each thread registered on an Event Source is
+ * signaled with the event flags specified in its Event Listener.
+ * - <b>Dispatch</b>, an events mask is scanned and for each bit set
+ * to one an associated handler function is invoked. Bit masks are
+ * scanned from bit zero upward.
+ * .
+ * An Event Source is a special object that can be "broadcasted" by
+ * a thread or an interrupt service routine. Broadcasting an Event
+ * Source has the effect that all the threads registered on the
+ * Event Source will be signaled with an events mask.<br>
+ * An unlimited number of Event Sources can exists in a system and
+ * each thread can be listening on an unlimited number of
+ * them.
+ * @pre In order to use the Events APIs the @p CH_CFG_USE_EVENTS option must be
+ * enabled in @p chconf.h.
+ * @post Enabling events requires 1-4 (depending on the architecture)
+ * extra bytes in the @p thread_t structure.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_EVENTS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Registers an Event Listener on an Event Source.
+ * @details Once a thread has registered as listener on an event source it
+ * will be notified of all events broadcasted there.
+ * @note Multiple Event Listeners can specify the same bits to be ORed to
+ * different threads.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ * @param[in] elp pointer to the @p event_listener_t structure
+ * @param[in] mask the mask of event flags to be ORed to the thread when
+ * the event source is broadcasted
+ *
+ * @api
+ */
+void chEvtRegisterMask(event_source_t *esp,
+ event_listener_t *elp,
+ eventmask_t mask) {
+
+ chDbgCheck((esp != NULL) && (elp != NULL));
+
+ chSysLock();
+ elp->el_next = esp->es_next;
+ esp->es_next = elp;
+ elp->el_listener = currp;
+ elp->el_mask = mask;
+ elp->el_flags = 0;
+ chSysUnlock();
+}
+
+/**
+ * @brief Unregisters an Event Listener from its Event Source.
+ * @note If the event listener is not registered on the specified event
+ * source then the function does nothing.
+ * @note For optimal performance it is better to perform the unregister
+ * operations in inverse order of the register operations (elements
+ * are found on top of the list).
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ * @param[in] elp pointer to the @p event_listener_t structure
+ *
+ * @api
+ */
+void chEvtUnregister(event_source_t *esp, event_listener_t *elp) {
+ event_listener_t *p;
+
+ chDbgCheck((esp != NULL) && (elp != NULL));
+
+ p = (event_listener_t *)esp;
+ chSysLock();
+ while (p->el_next != (event_listener_t *)esp) {
+ if (p->el_next == elp) {
+ p->el_next = elp->el_next;
+ break;
+ }
+ p = p->el_next;
+ }
+ chSysUnlock();
+}
+
+/**
+ * @brief Clears the pending events specified in the mask.
+ *
+ * @param[in] mask the events to be cleared
+ * @return The pending events that were cleared.
+ *
+ * @api
+ */
+eventmask_t chEvtGetAndClearEvents(eventmask_t mask) {
+ eventmask_t m;
+
+ chSysLock();
+
+ m = currp->p_epending & mask;
+ currp->p_epending &= ~mask;
+
+ chSysUnlock();
+ return m;
+}
+
+/**
+ * @brief Adds (OR) a set of event flags on the current thread, this is
+ * @b much faster than using @p chEvtBroadcast() or @p chEvtSignal().
+ *
+ * @param[in] mask the event flags to be added
+ * @return The current pending events mask.
+ *
+ * @api
+ */
+eventmask_t chEvtAddEvents(eventmask_t mask) {
+
+ chSysLock();
+
+ mask = (currp->p_epending |= mask);
+
+ chSysUnlock();
+ return mask;
+}
+
+/**
+ * @brief Signals all the Event Listeners registered on the specified Event
+ * Source.
+ * @details This function variants ORs the specified event flags to all the
+ * threads registered on the @p event_source_t in addition to the
+ * event flags specified by the threads themselves in the
+ * @p event_listener_t objects.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ * @param[in] flags the flags set to be added to the listener flags mask
+ *
+ * @iclass
+ */
+void chEvtBroadcastFlagsI(event_source_t *esp, eventflags_t flags) {
+ event_listener_t *elp;
+
+ chDbgCheckClassI();
+ chDbgCheck(esp != NULL);
+
+ elp = esp->es_next;
+ while (elp != (event_listener_t *)esp) {
+ elp->el_flags |= flags;
+ chEvtSignalI(elp->el_listener, elp->el_mask);
+ elp = elp->el_next;
+ }
+}
+
+/**
+ * @brief Returns the flags associated to an @p event_listener_t.
+ * @details The flags are returned and the @p event_listener_t flags mask is
+ * cleared.
+ *
+ * @param[in] elp pointer to the @p event_listener_t structure
+ * @return The flags added to the listener by the associated
+ * event source.
+ *
+ * @api
+ */
+eventflags_t chEvtGetAndClearFlags(event_listener_t *elp) {
+ eventflags_t flags;
+
+ chSysLock();
+
+ flags = elp->el_flags;
+ elp->el_flags = 0;
+
+ chSysUnlock();
+ return flags;
+}
+
+/**
+ * @brief Adds a set of event flags directly to the specified @p thread_t.
+ *
+ * @param[in] tp the thread to be signaled
+ * @param[in] mask the event flags set to be ORed
+ *
+ * @api
+ */
+void chEvtSignal(thread_t *tp, eventmask_t mask) {
+
+ chDbgCheck(tp != NULL);
+
+ chSysLock();
+ chEvtSignalI(tp, mask);
+ chSchRescheduleS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Adds a set of event flags directly to the specified @p thread_t.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] tp the thread to be signaled
+ * @param[in] mask the event flags set to be ORed
+ *
+ * @iclass
+ */
+void chEvtSignalI(thread_t *tp, eventmask_t mask) {
+
+ chDbgCheckClassI();
+ chDbgCheck(tp != NULL);
+
+ tp->p_epending |= mask;
+ /* Test on the AND/OR conditions wait states.*/
+ if (((tp->p_state == CH_STATE_WTOREVT) &&
+ ((tp->p_epending & tp->p_u.ewmask) != 0)) ||
+ ((tp->p_state == CH_STATE_WTANDEVT) &&
+ ((tp->p_epending & tp->p_u.ewmask) == tp->p_u.ewmask))) {
+ tp->p_u.rdymsg = MSG_OK;
+ chSchReadyI(tp);
+ }
+}
+
+/**
+ * @brief Signals all the Event Listeners registered on the specified Event
+ * Source.
+ * @details This function variants ORs the specified event flags to all the
+ * threads registered on the @p event_source_t in addition to the
+ * event flags specified by the threads themselves in the
+ * @p event_listener_t objects.
+ *
+ * @param[in] esp pointer to the @p event_source_t structure
+ * @param[in] flags the flags set to be added to the listener flags mask
+ *
+ * @api
+ */
+void chEvtBroadcastFlags(event_source_t *esp, eventflags_t flags) {
+
+ chSysLock();
+ chEvtBroadcastFlagsI(esp, flags);
+ chSchRescheduleS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Returns the flags associated to an @p event_listener_t.
+ * @details The flags are returned and the @p event_listener_t flags mask is
+ * cleared.
+ *
+ * @param[in] elp pointer to the @p event_listener_t structure
+ * @return The flags added to the listener by the associated
+ * event source.
+ *
+ * @iclass
+ */
+eventflags_t chEvtGetAndClearFlagsI(event_listener_t *elp) {
+ eventflags_t flags;
+
+ flags = elp->el_flags;
+ elp->el_flags = 0;
+
+ return flags;
+}
+
+/**
+ * @brief Invokes the event handlers associated to an event flags mask.
+ *
+ * @param[in] mask mask of the event flags to be dispatched
+ * @param[in] handlers an array of @p evhandler_t. The array must have size
+ * equal to the number of bits in eventmask_t.
+ *
+ * @api
+ */
+void chEvtDispatch(const evhandler_t *handlers, eventmask_t mask) {
+ eventid_t eid;
+
+ chDbgCheck(handlers != NULL);
+
+ eid = 0;
+ while (mask) {
+ if (mask & EVENT_MASK(eid)) {
+ chDbgAssert(handlers[eid] != NULL, "null handler");
+ mask &= ~EVENT_MASK(eid);
+ handlers[eid](eid);
+ }
+ eid++;
+ }
+}
+
+#if CH_CFG_OPTIMIZE_SPEED || !CH_CFG_USE_EVENTS_TIMEOUT || defined(__DOXYGEN__)
+/**
+ * @brief Waits for exactly one of the specified events.
+ * @details The function waits for one event among those specified in
+ * @p mask to become pending then the event is cleared and returned.
+ * @note One and only one event is served in the function, the one with the
+ * lowest event id. The function is meant to be invoked into a loop in
+ * order to serve all the pending events.<br>
+ * This means that Event Listeners with a lower event identifier have
+ * an higher priority.
+ *
+ * @param[in] mask mask of the event flags that the function should wait
+ * for, @p ALL_EVENTS enables all the events
+ * @return The mask of the lowest id served and cleared event.
+ *
+ * @api
+ */
+eventmask_t chEvtWaitOne(eventmask_t mask) {
+ thread_t *ctp = currp;
+ eventmask_t m;
+
+ chSysLock();
+
+ if ((m = (ctp->p_epending & mask)) == 0) {
+ ctp->p_u.ewmask = mask;
+ chSchGoSleepS(CH_STATE_WTOREVT);
+ m = ctp->p_epending & mask;
+ }
+ m &= -m;
+ ctp->p_epending &= ~m;
+
+ chSysUnlock();
+ return m;
+}
+
+/**
+ * @brief Waits for any of the specified events.
+ * @details The function waits for any event among those specified in
+ * @p mask to become pending then the events are cleared and returned.
+ *
+ * @param[in] mask mask of the event flags that the function should wait
+ * for, @p ALL_EVENTS enables all the events
+ * @return The mask of the served and cleared events.
+ *
+ * @api
+ */
+eventmask_t chEvtWaitAny(eventmask_t mask) {
+ thread_t *ctp = currp;
+ eventmask_t m;
+
+ chSysLock();
+
+ if ((m = (ctp->p_epending & mask)) == 0) {
+ ctp->p_u.ewmask = mask;
+ chSchGoSleepS(CH_STATE_WTOREVT);
+ m = ctp->p_epending & mask;
+ }
+ ctp->p_epending &= ~m;
+
+ chSysUnlock();
+ return m;
+}
+
+/**
+ * @brief Waits for all the specified events.
+ * @details The function waits for all the events specified in @p mask to
+ * become pending then the events are cleared and returned.
+ *
+ * @param[in] mask mask of the event flags that the function should wait
+ * for, @p ALL_EVENTS requires all the events
+ * @return The mask of the served and cleared events.
+ *
+ * @api
+ */
+eventmask_t chEvtWaitAll(eventmask_t mask) {
+ thread_t *ctp = currp;
+
+ chSysLock();
+
+ if ((ctp->p_epending & mask) != mask) {
+ ctp->p_u.ewmask = mask;
+ chSchGoSleepS(CH_STATE_WTANDEVT);
+ }
+ ctp->p_epending &= ~mask;
+
+ chSysUnlock();
+ return mask;
+}
+#endif /* CH_CFG_OPTIMIZE_SPEED || !CH_CFG_USE_EVENTS_TIMEOUT */
+
+#if CH_CFG_USE_EVENTS_TIMEOUT || defined(__DOXYGEN__)
+/**
+ * @brief Waits for exactly one of the specified events.
+ * @details The function waits for one event among those specified in
+ * @p mask to become pending then the event is cleared and returned.
+ * @note One and only one event is served in the function, the one with the
+ * lowest event id. The function is meant to be invoked into a loop
+ * in order to serve all the pending events.<br>
+ * This means that Event Listeners with a lower event identifier have
+ * an higher priority.
+ *
+ * @param[in] mask mask of the event flags that the function should wait
+ * for, @p ALL_EVENTS enables all the events
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The mask of the lowest id served and cleared event.
+ * @retval 0 if the operation has timed out.
+ *
+ * @api
+ */
+eventmask_t chEvtWaitOneTimeout(eventmask_t mask, systime_t time) {
+ thread_t *ctp = currp;
+ eventmask_t m;
+
+ chSysLock();
+
+ if ((m = (ctp->p_epending & mask)) == 0) {
+ if (TIME_IMMEDIATE == time) {
+ chSysUnlock();
+ return (eventmask_t)0;
+ }
+ ctp->p_u.ewmask = mask;
+ if (chSchGoSleepTimeoutS(CH_STATE_WTOREVT, time) < MSG_OK) {
+ chSysUnlock();
+ return (eventmask_t)0;
+ }
+ m = ctp->p_epending & mask;
+ }
+ m &= -m;
+ ctp->p_epending &= ~m;
+
+ chSysUnlock();
+ return m;
+}
+
+/**
+ * @brief Waits for any of the specified events.
+ * @details The function waits for any event among those specified in
+ * @p mask to become pending then the events are cleared and
+ * returned.
+ *
+ * @param[in] mask mask of the event flags that the function should wait
+ * for, @p ALL_EVENTS enables all the events
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The mask of the served and cleared events.
+ * @retval 0 if the operation has timed out.
+ *
+ * @api
+ */
+eventmask_t chEvtWaitAnyTimeout(eventmask_t mask, systime_t time) {
+ thread_t *ctp = currp;
+ eventmask_t m;
+
+ chSysLock();
+
+ if ((m = (ctp->p_epending & mask)) == 0) {
+ if (TIME_IMMEDIATE == time) {
+ chSysUnlock();
+ return (eventmask_t)0;
+ }
+ ctp->p_u.ewmask = mask;
+ if (chSchGoSleepTimeoutS(CH_STATE_WTOREVT, time) < MSG_OK) {
+ chSysUnlock();
+ return (eventmask_t)0;
+ }
+ m = ctp->p_epending & mask;
+ }
+ ctp->p_epending &= ~m;
+
+ chSysUnlock();
+ return m;
+}
+
+/**
+ * @brief Waits for all the specified events.
+ * @details The function waits for all the events specified in @p mask to
+ * become pending then the events are cleared and returned.
+ *
+ * @param[in] mask mask of the event flags that the function should wait
+ * for, @p ALL_EVENTS requires all the events
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The mask of the served and cleared events.
+ * @retval 0 if the operation has timed out.
+ *
+ * @api
+ */
+eventmask_t chEvtWaitAllTimeout(eventmask_t mask, systime_t time) {
+ thread_t *ctp = currp;
+
+ chSysLock();
+
+ if ((ctp->p_epending & mask) != mask) {
+ if (TIME_IMMEDIATE == time) {
+ chSysUnlock();
+ return (eventmask_t)0;
+ }
+ ctp->p_u.ewmask = mask;
+ if (chSchGoSleepTimeoutS(CH_STATE_WTANDEVT, time) < MSG_OK) {
+ chSysUnlock();
+ return (eventmask_t)0;
+ }
+ }
+ ctp->p_epending &= ~mask;
+
+ chSysUnlock();
+ return mask;
+}
+#endif /* CH_CFG_USE_EVENTS_TIMEOUT */
+
+#endif /* CH_CFG_USE_EVENTS */
+
+/** @} */
diff --git a/os/rt/src/chheap.c b/os/rt/src/chheap.c new file mode 100644 index 000000000..5e1e20c3c --- /dev/null +++ b/os/rt/src/chheap.c @@ -0,0 +1,276 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chheap.c
+ * @brief Heaps code.
+ *
+ * @addtogroup heaps
+ * @details Heap Allocator related APIs.
+ * <h2>Operation mode</h2>
+ * The heap allocator implements a first-fit strategy and its APIs
+ * are functionally equivalent to the usual @p malloc() and @p free()
+ * library functions. The main difference is that the OS heap APIs
+ * are guaranteed to be thread safe.<br>
+ * @pre In order to use the heap APIs the @p CH_CFG_USE_HEAP option must
+ * be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_HEAP || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*
+ * Defaults on the best synchronization mechanism available.
+ */
+#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
+#define H_LOCK(h) chMtxLock(&(h)->h_mtx)
+#define H_UNLOCK(h) chMtxUnlock(&(h)->h_mtx)
+#else
+#define H_LOCK(h) chSemWait(&(h)->h_sem)
+#define H_UNLOCK(h) chSemSignal(&(h)->h_sem)
+#endif
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/**
+ * @brief Default heap descriptor.
+ */
+static memory_heap_t default_heap;
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes the default heap.
+ *
+ * @notapi
+ */
+void _heap_init(void) {
+ default_heap.h_provider = chCoreAlloc;
+ default_heap.h_free.h.u.next = (union heap_header *)NULL;
+ default_heap.h_free.h.size = 0;
+#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
+ chMtxObjectInit(&default_heap.h_mtx);
+#else
+ chSemObjectInit(&default_heap.h_sem, 1);
+#endif
+}
+
+/**
+ * @brief Initializes a memory heap from a static memory area.
+ * @pre Both the heap buffer base and the heap size must be aligned to
+ * the @p stkalign_t type size.
+ *
+ * @param[out] heapp pointer to the memory heap descriptor to be initialized
+ * @param[in] buf heap buffer base
+ * @param[in] size heap size
+ *
+ * @init
+ */
+void chHeapObjectInit(memory_heap_t *heapp, void *buf, size_t size) {
+ union heap_header *hp;
+
+ chDbgCheck(MEM_IS_ALIGNED(buf) && MEM_IS_ALIGNED(size));
+
+ heapp->h_provider = (memgetfunc_t)NULL;
+ heapp->h_free.h.u.next = hp = buf;
+ heapp->h_free.h.size = 0;
+ hp->h.u.next = NULL;
+ hp->h.size = size - sizeof(union heap_header);
+#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
+ chMtxObjectInit(&heapp->h_mtx);
+#else
+ chSemObjectInit(&heapp->h_sem, 1);
+#endif
+}
+
+/**
+ * @brief Allocates a block of memory from the heap by using the first-fit
+ * algorithm.
+ * @details The allocated block is guaranteed to be properly aligned for a
+ * pointer data type (@p stkalign_t).
+ *
+ * @param[in] heapp pointer to a heap descriptor or @p NULL in order to
+ * access the default heap.
+ * @param[in] size the size of the block to be allocated. Note that the
+ * allocated block may be a bit bigger than the requested
+ * size for alignment and fragmentation reasons.
+ * @return A pointer to the allocated block.
+ * @retval NULL if the block cannot be allocated.
+ *
+ * @api
+ */
+void *chHeapAlloc(memory_heap_t *heapp, size_t size) {
+ union heap_header *qp, *hp, *fp;
+
+ if (heapp == NULL)
+ heapp = &default_heap;
+
+ size = MEM_ALIGN_NEXT(size);
+ qp = &heapp->h_free;
+ H_LOCK(heapp);
+
+ while (qp->h.u.next != NULL) {
+ hp = qp->h.u.next;
+ if (hp->h.size >= size) {
+ if (hp->h.size < size + sizeof(union heap_header)) {
+ /* Gets the whole block even if it is slightly bigger than the
+ requested size because the fragment would be too small to be
+ useful.*/
+ qp->h.u.next = hp->h.u.next;
+ }
+ else {
+ /* Block bigger enough, must split it.*/
+ fp = (void *)((uint8_t *)(hp) + sizeof(union heap_header) + size);
+ fp->h.u.next = hp->h.u.next;
+ fp->h.size = hp->h.size - sizeof(union heap_header) - size;
+ qp->h.u.next = fp;
+ hp->h.size = size;
+ }
+ hp->h.u.heap = heapp;
+
+ H_UNLOCK(heapp);
+ return (void *)(hp + 1);
+ }
+ qp = hp;
+ }
+
+ H_UNLOCK(heapp);
+
+ /* More memory is required, tries to get it from the associated provider
+ else fails.*/
+ if (heapp->h_provider) {
+ hp = heapp->h_provider(size + sizeof(union heap_header));
+ if (hp != NULL) {
+ hp->h.u.heap = heapp;
+ hp->h.size = size;
+ hp++;
+ return (void *)hp;
+ }
+ }
+ return NULL;
+}
+
+#define LIMIT(p) (union heap_header *)((uint8_t *)(p) + \
+ sizeof(union heap_header) + \
+ (p)->h.size)
+
+/**
+ * @brief Frees a previously allocated memory block.
+ *
+ * @param[in] p pointer to the memory block to be freed
+ *
+ * @api
+ */
+void chHeapFree(void *p) {
+ union heap_header *qp, *hp;
+ memory_heap_t *heapp;
+
+ chDbgCheck(p != NULL);
+
+ hp = (union heap_header *)p - 1;
+ heapp = hp->h.u.heap;
+ qp = &heapp->h_free;
+ H_LOCK(heapp);
+
+ while (true) {
+ chDbgAssert((hp < qp) || (hp >= LIMIT(qp)), "within free block");
+
+ if (((qp == &heapp->h_free) || (hp > qp)) &&
+ ((qp->h.u.next == NULL) || (hp < qp->h.u.next))) {
+ /* Insertion after qp.*/
+ hp->h.u.next = qp->h.u.next;
+ qp->h.u.next = hp;
+ /* Verifies if the newly inserted block should be merged.*/
+ if (LIMIT(hp) == hp->h.u.next) {
+ /* Merge with the next block.*/
+ hp->h.size += hp->h.u.next->h.size + sizeof(union heap_header);
+ hp->h.u.next = hp->h.u.next->h.u.next;
+ }
+ if ((LIMIT(qp) == hp)) {
+ /* Merge with the previous block.*/
+ qp->h.size += hp->h.size + sizeof(union heap_header);
+ qp->h.u.next = hp->h.u.next;
+ }
+ break;
+ }
+ qp = qp->h.u.next;
+ }
+
+ H_UNLOCK(heapp);
+ return;
+}
+
+/**
+ * @brief Reports the heap status.
+ * @note This function is meant to be used in the test suite, it should
+ * not be really useful for the application code.
+ *
+ * @param[in] heapp pointer to a heap descriptor or @p NULL in order to
+ * access the default heap.
+ * @param[in] sizep pointer to a variable that will receive the total
+ * fragmented free space
+ * @return The number of fragments in the heap.
+ *
+ * @api
+ */
+size_t chHeapStatus(memory_heap_t *heapp, size_t *sizep) {
+ union heap_header *qp;
+ size_t n, sz;
+
+ if (heapp == NULL)
+ heapp = &default_heap;
+
+ H_LOCK(heapp);
+
+ sz = 0;
+ for (n = 0, qp = &heapp->h_free; qp->h.u.next; n++, qp = qp->h.u.next)
+ sz += qp->h.u.next->h.size;
+ if (sizep)
+ *sizep = sz;
+
+ H_UNLOCK(heapp);
+ return n;
+}
+
+#endif /* CH_CFG_USE_HEAP */
+
+/** @} */
diff --git a/os/rt/src/chmboxes.c b/os/rt/src/chmboxes.c new file mode 100644 index 000000000..8e9e2bb40 --- /dev/null +++ b/os/rt/src/chmboxes.c @@ -0,0 +1,398 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmboxes.c
+ * @brief Mailboxes code.
+ *
+ * @addtogroup mailboxes
+ * @details Asynchronous messages.
+ * <h2>Operation mode</h2>
+ * A mailbox is an asynchronous communication mechanism.<br>
+ * Operations defined for mailboxes:
+ * - <b>Post</b>: Posts a message on the mailbox in FIFO order.
+ * - <b>Post Ahead</b>: Posts a message on the mailbox with urgent
+ * priority.
+ * - <b>Fetch</b>: A message is fetched from the mailbox and removed
+ * from the queue.
+ * - <b>Reset</b>: The mailbox is emptied and all the stored messages
+ * are lost.
+ * .
+ * A message is a variable of type msg_t that is guaranteed to have
+ * the same size of and be compatible with (data) pointers (anyway an
+ * explicit cast is needed).
+ * If larger messages need to be exchanged then a pointer to a
+ * structure can be posted in the mailbox but the posting side has
+ * no predefined way to know when the message has been processed. A
+ * possible approach is to allocate memory (from a memory pool for
+ * example) from the posting side and free it on the fetching side.
+ * Another approach is to set a "done" flag into the structure pointed
+ * by the message.
+ * @pre In order to use the mailboxes APIs the @p CH_CFG_USE_MAILBOXES option
+ * must be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_MAILBOXES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes a @p mailbox_t object.
+ *
+ * @param[out] mbp the pointer to the @p mailbox_t structure to be
+ * initialized
+ * @param[in] buf pointer to the messages buffer as an array of @p msg_t
+ * @param[in] n number of elements in the buffer array
+ *
+ * @init
+ */
+void chMBObjectInit(mailbox_t *mbp, msg_t *buf, cnt_t n) {
+
+ chDbgCheck((mbp != NULL) && (buf != NULL) && (n > 0));
+
+ mbp->mb_buffer = mbp->mb_wrptr = mbp->mb_rdptr = buf;
+ mbp->mb_top = &buf[n];
+ chSemObjectInit(&mbp->mb_emptysem, n);
+ chSemObjectInit(&mbp->mb_fullsem, 0);
+}
+
+/**
+ * @brief Resets a @p mailbox_t object.
+ * @details All the waiting threads are resumed with status @p MSG_RESET and
+ * the queued messages are lost.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ *
+ * @api
+ */
+void chMBReset(mailbox_t *mbp) {
+
+ chDbgCheck(mbp != NULL);
+
+ chSysLock();
+ mbp->mb_wrptr = mbp->mb_rdptr = mbp->mb_buffer;
+ chSemResetI(&mbp->mb_emptysem, mbp->mb_top - mbp->mb_buffer);
+ chSemResetI(&mbp->mb_fullsem, 0);
+ chSchRescheduleS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Posts a message into a mailbox.
+ * @details The invoking thread waits until a empty slot in the mailbox becomes
+ * available or the specified time runs out.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[in] msg the message to be posted on the mailbox
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly posted.
+ * @retval MSG_RESET if the mailbox has been reset while waiting.
+ * @retval MSG_TIMEOUT if the operation has timed out.
+ *
+ * @api
+ */
+msg_t chMBPost(mailbox_t *mbp, msg_t msg, systime_t time) {
+ msg_t rdymsg;
+
+ chSysLock();
+ rdymsg = chMBPostS(mbp, msg, time);
+ chSysUnlock();
+ return rdymsg;
+}
+
+/**
+ * @brief Posts a message into a mailbox.
+ * @details The invoking thread waits until a empty slot in the mailbox becomes
+ * available or the specified time runs out.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[in] msg the message to be posted on the mailbox
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly posted.
+ * @retval MSG_RESET if the mailbox has been reset while waiting.
+ * @retval MSG_TIMEOUT if the operation has timed out.
+ *
+ * @sclass
+ */
+msg_t chMBPostS(mailbox_t *mbp, msg_t msg, systime_t time) {
+ msg_t rdymsg;
+
+ chDbgCheckClassS();
+ chDbgCheck(mbp != NULL);
+
+ rdymsg = chSemWaitTimeoutS(&mbp->mb_emptysem, time);
+ if (rdymsg == MSG_OK) {
+ *mbp->mb_wrptr++ = msg;
+ if (mbp->mb_wrptr >= mbp->mb_top)
+ mbp->mb_wrptr = mbp->mb_buffer;
+ chSemSignalI(&mbp->mb_fullsem);
+ chSchRescheduleS();
+ }
+ return rdymsg;
+}
+
+/**
+ * @brief Posts a message into a mailbox.
+ * @details This variant is non-blocking, the function returns a timeout
+ * condition if the queue is full.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[in] msg the message to be posted on the mailbox
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly posted.
+ * @retval MSG_TIMEOUT if the mailbox is full and the message cannot be
+ * posted.
+ *
+ * @iclass
+ */
+msg_t chMBPostI(mailbox_t *mbp, msg_t msg) {
+
+ chDbgCheckClassI();
+ chDbgCheck(mbp != NULL);
+
+ if (chSemGetCounterI(&mbp->mb_emptysem) <= 0)
+ return MSG_TIMEOUT;
+ chSemFastWaitI(&mbp->mb_emptysem);
+ *mbp->mb_wrptr++ = msg;
+ if (mbp->mb_wrptr >= mbp->mb_top)
+ mbp->mb_wrptr = mbp->mb_buffer;
+ chSemSignalI(&mbp->mb_fullsem);
+ return MSG_OK;
+}
+
+/**
+ * @brief Posts an high priority message into a mailbox.
+ * @details The invoking thread waits until a empty slot in the mailbox becomes
+ * available or the specified time runs out.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[in] msg the message to be posted on the mailbox
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly posted.
+ * @retval MSG_RESET if the mailbox has been reset while waiting.
+ * @retval MSG_TIMEOUT if the operation has timed out.
+ *
+ * @api
+ */
+msg_t chMBPostAhead(mailbox_t *mbp, msg_t msg, systime_t time) {
+ msg_t rdymsg;
+
+ chSysLock();
+ rdymsg = chMBPostAheadS(mbp, msg, time);
+ chSysUnlock();
+ return rdymsg;
+}
+
+/**
+ * @brief Posts an high priority message into a mailbox.
+ * @details The invoking thread waits until a empty slot in the mailbox becomes
+ * available or the specified time runs out.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[in] msg the message to be posted on the mailbox
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly posted.
+ * @retval MSG_RESET if the mailbox has been reset while waiting.
+ * @retval MSG_TIMEOUT if the operation has timed out.
+ *
+ * @sclass
+ */
+msg_t chMBPostAheadS(mailbox_t *mbp, msg_t msg, systime_t time) {
+ msg_t rdymsg;
+
+ chDbgCheckClassS();
+ chDbgCheck(mbp != NULL);
+
+ rdymsg = chSemWaitTimeoutS(&mbp->mb_emptysem, time);
+ if (rdymsg == MSG_OK) {
+ if (--mbp->mb_rdptr < mbp->mb_buffer)
+ mbp->mb_rdptr = mbp->mb_top - 1;
+ *mbp->mb_rdptr = msg;
+ chSemSignalI(&mbp->mb_fullsem);
+ chSchRescheduleS();
+ }
+ return rdymsg;
+}
+
+/**
+ * @brief Posts an high priority message into a mailbox.
+ * @details This variant is non-blocking, the function returns a timeout
+ * condition if the queue is full.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[in] msg the message to be posted on the mailbox
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly posted.
+ * @retval MSG_TIMEOUT if the mailbox is full and the message cannot be
+ * posted.
+ *
+ * @iclass
+ */
+msg_t chMBPostAheadI(mailbox_t *mbp, msg_t msg) {
+
+ chDbgCheckClassI();
+ chDbgCheck(mbp != NULL);
+
+ if (chSemGetCounterI(&mbp->mb_emptysem) <= 0)
+ return MSG_TIMEOUT;
+ chSemFastWaitI(&mbp->mb_emptysem);
+ if (--mbp->mb_rdptr < mbp->mb_buffer)
+ mbp->mb_rdptr = mbp->mb_top - 1;
+ *mbp->mb_rdptr = msg;
+ chSemSignalI(&mbp->mb_fullsem);
+ return MSG_OK;
+}
+
+/**
+ * @brief Retrieves a message from a mailbox.
+ * @details The invoking thread waits until a message is posted in the mailbox
+ * or the specified time runs out.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[out] msgp pointer to a message variable for the received message
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly fetched.
+ * @retval MSG_RESET if the mailbox has been reset while waiting.
+ * @retval MSG_TIMEOUT if the operation has timed out.
+ *
+ * @api
+ */
+msg_t chMBFetch(mailbox_t *mbp, msg_t *msgp, systime_t time) {
+ msg_t rdymsg;
+
+ chSysLock();
+ rdymsg = chMBFetchS(mbp, msgp, time);
+ chSysUnlock();
+ return rdymsg;
+}
+
+/**
+ * @brief Retrieves a message from a mailbox.
+ * @details The invoking thread waits until a message is posted in the mailbox
+ * or the specified time runs out.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[out] msgp pointer to a message variable for the received message
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly fetched.
+ * @retval MSG_RESET if the mailbox has been reset while waiting.
+ * @retval MSG_TIMEOUT if the operation has timed out.
+ *
+ * @sclass
+ */
+msg_t chMBFetchS(mailbox_t *mbp, msg_t *msgp, systime_t time) {
+ msg_t rdymsg;
+
+ chDbgCheckClassS();
+ chDbgCheck((mbp != NULL) && (msgp != NULL));
+
+ rdymsg = chSemWaitTimeoutS(&mbp->mb_fullsem, time);
+ if (rdymsg == MSG_OK) {
+ *msgp = *mbp->mb_rdptr++;
+ if (mbp->mb_rdptr >= mbp->mb_top)
+ mbp->mb_rdptr = mbp->mb_buffer;
+ chSemSignalI(&mbp->mb_emptysem);
+ chSchRescheduleS();
+ }
+ return rdymsg;
+}
+
+/**
+ * @brief Retrieves a message from a mailbox.
+ * @details This variant is non-blocking, the function returns a timeout
+ * condition if the queue is empty.
+ *
+ * @param[in] mbp the pointer to an initialized @p mailbox_t object
+ * @param[out] msgp pointer to a message variable for the received message
+ * @return The operation status.
+ * @retval MSG_OK if a message has been correctly fetched.
+ * @retval MSG_TIMEOUT if the mailbox is empty and a message cannot be
+ * fetched.
+ *
+ * @iclass
+ */
+msg_t chMBFetchI(mailbox_t *mbp, msg_t *msgp) {
+
+ chDbgCheckClassI();
+ chDbgCheck((mbp != NULL) && (msgp != NULL));
+
+ if (chSemGetCounterI(&mbp->mb_fullsem) <= 0)
+ return MSG_TIMEOUT;
+ chSemFastWaitI(&mbp->mb_fullsem);
+ *msgp = *mbp->mb_rdptr++;
+ if (mbp->mb_rdptr >= mbp->mb_top)
+ mbp->mb_rdptr = mbp->mb_buffer;
+ chSemSignalI(&mbp->mb_emptysem);
+ return MSG_OK;
+}
+#endif /* CH_CFG_USE_MAILBOXES */
+
+/** @} */
diff --git a/os/rt/src/chmemcore.c b/os/rt/src/chmemcore.c new file mode 100644 index 000000000..d5e7ed79c --- /dev/null +++ b/os/rt/src/chmemcore.c @@ -0,0 +1,153 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmemcore.c
+ * @brief Core memory manager code.
+ *
+ * @addtogroup memcore
+ * @details Core Memory Manager related APIs and services.
+ * <h2>Operation mode</h2>
+ * The core memory manager is a simplified allocator that only
+ * allows to allocate memory blocks without the possibility to
+ * free them.<br>
+ * This allocator is meant as a memory blocks provider for the
+ * other allocators such as:
+ * - C-Runtime allocator (through a compiler specific adapter module).
+ * - Heap allocator (see @ref heaps).
+ * - Memory pools allocator (see @ref pools).
+ * .
+ * By having a centralized memory provider the various allocators
+ * can coexist and share the main memory.<br>
+ * This allocator, alone, is also useful for very simple
+ * applications that just require a simple way to get memory
+ * blocks.
+ * @pre In order to use the core memory manager APIs the @p CH_CFG_USE_MEMCORE
+ * option must be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_MEMCORE || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+static uint8_t *nextmem;
+static uint8_t *endmem;
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Low level memory manager initialization.
+ *
+ * @notapi
+ */
+void _core_init(void) {
+#if CH_CFG_MEMCORE_SIZE == 0
+ extern uint8_t __heap_base__[];
+ extern uint8_t __heap_end__[];
+
+ nextmem = (uint8_t *)MEM_ALIGN_NEXT(__heap_base__);
+ endmem = (uint8_t *)MEM_ALIGN_PREV(__heap_end__);
+#else
+ static stkalign_t buffer[MEM_ALIGN_NEXT(CH_CFG_MEMCORE_SIZE)/MEM_ALIGN_SIZE];
+
+ nextmem = (uint8_t *)&buffer[0];
+ endmem = (uint8_t *)&buffer[MEM_ALIGN_NEXT(CH_CFG_MEMCORE_SIZE)/MEM_ALIGN_SIZE];
+#endif
+}
+
+/**
+ * @brief Allocates a memory block.
+ * @details The size of the returned block is aligned to the alignment
+ * type so it is not possible to allocate less
+ * than <code>MEM_ALIGN_SIZE</code>.
+ *
+ * @param[in] size the size of the block to be allocated
+ * @return A pointer to the allocated memory block.
+ * @retval NULL allocation failed, core memory exhausted.
+ *
+ * @api
+ */
+void *chCoreAlloc(size_t size) {
+ void *p;
+
+ chSysLock();
+ p = chCoreAllocI(size);
+ chSysUnlock();
+ return p;
+}
+
+/**
+ * @brief Allocates a memory block.
+ * @details The size of the returned block is aligned to the alignment
+ * type so it is not possible to allocate less than
+ * <code>MEM_ALIGN_SIZE</code>.
+ *
+ * @param[in] size the size of the block to be allocated.
+ * @return A pointer to the allocated memory block.
+ * @retval NULL allocation failed, core memory exhausted.
+ *
+ * @iclass
+ */
+void *chCoreAllocI(size_t size) {
+ void *p;
+
+ chDbgCheckClassI();
+
+ size = MEM_ALIGN_NEXT(size);
+ if ((size_t)(endmem - nextmem) < size)
+ return NULL;
+ p = nextmem;
+ nextmem += size;
+ return p;
+}
+
+/**
+ * @brief Core memory status.
+ *
+ * @return The size, in bytes, of the free core memory.
+ *
+ * @api
+ */
+size_t chCoreStatus(void) {
+
+ return (size_t)(endmem - nextmem);
+}
+#endif /* CH_CFG_USE_MEMCORE */
+
+/** @} */
diff --git a/os/rt/src/chmempools.c b/os/rt/src/chmempools.c new file mode 100644 index 000000000..d92ea7517 --- /dev/null +++ b/os/rt/src/chmempools.c @@ -0,0 +1,194 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmempools.c
+ * @brief Memory Pools code.
+ *
+ * @addtogroup pools
+ * @details Memory Pools related APIs and services.
+ * <h2>Operation mode</h2>
+ * The Memory Pools APIs allow to allocate/free fixed size objects in
+ * <b>constant time</b> and reliably without memory fragmentation
+ * problems.<br>
+ * Memory Pools do not enforce any alignment constraint on the
+ * contained object however the objects must be properly aligned
+ * to contain a pointer to void.
+ * @pre In order to use the memory pools APIs the @p CH_CFG_USE_MEMPOOLS option
+ * must be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_MEMPOOLS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes an empty memory pool.
+ *
+ * @param[out] mp pointer to a @p memory_pool_t structure
+ * @param[in] size the size of the objects contained in this memory pool,
+ * the minimum accepted size is the size of a pointer to
+ * void.
+ * @param[in] provider memory provider function for the memory pool or
+ * @p NULL if the pool is not allowed to grow
+ * automatically
+ *
+ * @init
+ */
+void chPoolObjectInit(memory_pool_t *mp, size_t size, memgetfunc_t provider) {
+
+ chDbgCheck((mp != NULL) && (size >= sizeof(void *)));
+
+ mp->mp_next = NULL;
+ mp->mp_object_size = size;
+ mp->mp_provider = provider;
+}
+
+/**
+ * @brief Loads a memory pool with an array of static objects.
+ * @pre The memory pool must be already been initialized.
+ * @pre The array elements must be of the right size for the specified
+ * memory pool.
+ * @post The memory pool contains the elements of the input array.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @param[in] p pointer to the array first element
+ * @param[in] n number of elements in the array
+ *
+ * @api
+ */
+void chPoolLoadArray(memory_pool_t *mp, void *p, size_t n) {
+
+ chDbgCheck((mp != NULL) && (n != 0));
+
+ while (n) {
+ chPoolAdd(mp, p);
+ p = (void *)(((uint8_t *)p) + mp->mp_object_size);
+ n--;
+ }
+}
+
+/**
+ * @brief Allocates an object from a memory pool.
+ * @pre The memory pool must be already been initialized.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @return The pointer to the allocated object.
+ * @retval NULL if pool is empty.
+ *
+ * @iclass
+ */
+void *chPoolAllocI(memory_pool_t *mp) {
+ void *objp;
+
+ chDbgCheckClassI();
+ chDbgCheck(mp != NULL);
+
+ if ((objp = mp->mp_next) != NULL)
+ mp->mp_next = mp->mp_next->ph_next;
+ else if (mp->mp_provider != NULL)
+ objp = mp->mp_provider(mp->mp_object_size);
+ return objp;
+}
+
+/**
+ * @brief Allocates an object from a memory pool.
+ * @pre The memory pool must be already been initialized.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @return The pointer to the allocated object.
+ * @retval NULL if pool is empty.
+ *
+ * @api
+ */
+void *chPoolAlloc(memory_pool_t *mp) {
+ void *objp;
+
+ chSysLock();
+ objp = chPoolAllocI(mp);
+ chSysUnlock();
+ return objp;
+}
+
+/**
+ * @brief Releases an object into a memory pool.
+ * @pre The memory pool must be already been initialized.
+ * @pre The freed object must be of the right size for the specified
+ * memory pool.
+ * @pre The object must be properly aligned to contain a pointer to void.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @param[in] objp the pointer to the object to be released
+ *
+ * @iclass
+ */
+void chPoolFreeI(memory_pool_t *mp, void *objp) {
+ struct pool_header *php = objp;
+
+ chDbgCheckClassI();
+ chDbgCheck((mp != NULL) && (objp != NULL));
+
+ php->ph_next = mp->mp_next;
+ mp->mp_next = php;
+}
+
+/**
+ * @brief Releases an object into a memory pool.
+ * @pre The memory pool must be already been initialized.
+ * @pre The freed object must be of the right size for the specified
+ * memory pool.
+ * @pre The object must be properly aligned to contain a pointer to void.
+ *
+ * @param[in] mp pointer to a @p memory_pool_t structure
+ * @param[in] objp the pointer to the object to be released
+ *
+ * @api
+ */
+void chPoolFree(memory_pool_t *mp, void *objp) {
+
+ chSysLock();
+ chPoolFreeI(mp, objp);
+ chSysUnlock();
+}
+
+#endif /* CH_CFG_USE_MEMPOOLS */
+
+/** @} */
diff --git a/os/rt/src/chmsg.c b/os/rt/src/chmsg.c new file mode 100644 index 000000000..335b46c61 --- /dev/null +++ b/os/rt/src/chmsg.c @@ -0,0 +1,151 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmsg.c
+ * @brief Messages code.
+ *
+ * @addtogroup messages
+ * @details Synchronous inter-thread messages APIs and services.
+ * <h2>Operation Mode</h2>
+ * Synchronous messages are an easy to use and fast IPC mechanism,
+ * threads can both act as message servers and/or message clients,
+ * the mechanism allows data to be carried in both directions. Note
+ * that messages are not copied between the client and server threads
+ * but just a pointer passed so the exchange is very time
+ * efficient.<br>
+ * Messages are scalar data types of type @p msg_t that are guaranteed
+ * to be size compatible with data pointers. Note that on some
+ * architectures function pointers can be larger that @p msg_t.<br>
+ * Messages are usually processed in FIFO order but it is possible to
+ * process them in priority order by enabling the
+ * @p CH_CFG_USE_MESSAGES_PRIORITY option in @p chconf.h.<br>
+ * @pre In order to use the message APIs the @p CH_CFG_USE_MESSAGES option
+ * must be enabled in @p chconf.h.
+ * @post Enabling messages requires 6-12 (depending on the architecture)
+ * extra bytes in the @p thread_t structure.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_MESSAGES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+#if CH_CFG_USE_MESSAGES_PRIORITY
+#define msg_insert(tp, qp) prio_insert(tp, qp)
+#else
+#define msg_insert(tp, qp) queue_insert(tp, qp)
+#endif
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Sends a message to the specified thread.
+ * @details The sender is stopped until the receiver executes a
+ * @p chMsgRelease()after receiving the message.
+ *
+ * @param[in] tp the pointer to the thread
+ * @param[in] msg the message
+ * @return The answer message from @p chMsgRelease().
+ *
+ * @api
+ */
+msg_t chMsgSend(thread_t *tp, msg_t msg) {
+ thread_t *ctp = currp;
+
+ chDbgCheck(tp != NULL);
+
+ chSysLock();
+ ctp->p_msg = msg;
+ ctp->p_u.wtobjp = &tp->p_msgqueue;
+ msg_insert(ctp, &tp->p_msgqueue);
+ if (tp->p_state == CH_STATE_WTMSG)
+ chSchReadyI(tp);
+ chSchGoSleepS(CH_STATE_SNDMSGQ);
+ msg = ctp->p_u.rdymsg;
+ chSysUnlock();
+ return msg;
+}
+
+/**
+ * @brief Suspends the thread and waits for an incoming message.
+ * @post After receiving a message the function @p chMsgGet() must be
+ * called in order to retrieve the message and then @p chMsgRelease()
+ * must be invoked in order to acknowledge the reception and send
+ * the answer.
+ * @note If the message is a pointer then you can assume that the data
+ * pointed by the message is stable until you invoke @p chMsgRelease()
+ * because the sending thread is suspended until then.
+ *
+ * @return A reference to the thread carrying the message.
+ *
+ * @api
+ */
+thread_t *chMsgWait(void) {
+ thread_t *tp;
+
+ chSysLock();
+ if (!chMsgIsPendingI(currp))
+ chSchGoSleepS(CH_STATE_WTMSG);
+ tp = queue_fifo_remove(&currp->p_msgqueue);
+ tp->p_state = CH_STATE_SNDMSG;
+ chSysUnlock();
+ return tp;
+}
+
+/**
+ * @brief Releases a sender thread specifying a response message.
+ * @pre Invoke this function only after a message has been received
+ * using @p chMsgWait().
+ *
+ * @param[in] tp pointer to the thread
+ * @param[in] msg message to be returned to the sender
+ *
+ * @api
+ */
+void chMsgRelease(thread_t *tp, msg_t msg) {
+
+ chSysLock();
+ chDbgAssert(tp->p_state == CH_STATE_SNDMSG, "invalid state");
+ chMsgReleaseS(tp, msg);
+ chSysUnlock();
+}
+
+#endif /* CH_CFG_USE_MESSAGES */
+
+/** @} */
diff --git a/os/rt/src/chmtx.c b/os/rt/src/chmtx.c new file mode 100644 index 000000000..45e884204 --- /dev/null +++ b/os/rt/src/chmtx.c @@ -0,0 +1,501 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chmtx.c
+ * @brief Mutexes code.
+ *
+ * @addtogroup mutexes
+ * @details Mutexes related APIs and services.
+ *
+ * <h2>Operation mode</h2>
+ * A mutex is a threads synchronization object that can be in two
+ * distinct states:
+ * - Not owned (unlocked).
+ * - Owned by a thread (locked).
+ * .
+ * Operations defined for mutexes:
+ * - <b>Lock</b>: The mutex is checked, if the mutex is not owned by
+ * some other thread then it is associated to the locking thread
+ * else the thread is queued on the mutex in a list ordered by
+ * priority.
+ * - <b>Unlock</b>: The mutex is released by the owner and the highest
+ * priority thread waiting in the queue, if any, is resumed and made
+ * owner of the mutex.
+ * .
+ * <h2>Constraints</h2>
+ * In ChibiOS/RT the Unlock operations must always be performed
+ * in lock-reverse order. This restriction both improves the
+ * performance and is required for an efficient implementation
+ * of the priority inheritance mechanism.<br>
+ * Operating under this restriction also ensures that deadlocks
+ * are no possible.
+ *
+ * <h2>Recursive mode</h2>
+ * By default mutexes are not recursive, this mean that it is not
+ * possible to take a mutex already owned by the same thread.
+ * It is possible to enable the recursive behavior by enabling the
+ * option @p CH_CFG_USE_MUTEXES_RECURSIVE.
+ *
+ * <h2>The priority inversion problem</h2>
+ * The mutexes in ChibiOS/RT implements the <b>full</b> priority
+ * inheritance mechanism in order handle the priority inversion
+ * problem.<br>
+ * When a thread is queued on a mutex, any thread, directly or
+ * indirectly, holding the mutex gains the same priority of the
+ * waiting thread (if their priority was not already equal or higher).
+ * The mechanism works with any number of nested mutexes and any
+ * number of involved threads. The algorithm complexity (worst case)
+ * is N with N equal to the number of nested mutexes.
+ * @pre In order to use the mutex APIs the @p CH_CFG_USE_MUTEXES option
+ * must be enabled in @p chconf.h.
+ * @post Enabling mutexes requires 5-12 (depending on the architecture)
+ * extra bytes in the @p thread_t structure.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_MUTEXES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes s @p mutex_t structure.
+ *
+ * @param[out] mp pointer to a @p mutex_t structure
+ *
+ * @init
+ */
+void chMtxObjectInit(mutex_t *mp) {
+
+ chDbgCheck(mp != NULL);
+
+ queue_init(&mp->m_queue);
+ mp->m_owner = NULL;
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ mp->m_cnt = 0;
+#endif
+}
+
+/**
+ * @brief Locks the specified mutex.
+ * @post The mutex is locked and inserted in the per-thread stack of owned
+ * mutexes.
+ *
+ * @param[in] mp pointer to the @p mutex_t structure
+ *
+ * @api
+ */
+void chMtxLock(mutex_t *mp) {
+
+ chSysLock();
+
+ chMtxLockS(mp);
+
+ chSysUnlock();
+}
+
+/**
+ * @brief Locks the specified mutex.
+ * @post The mutex is locked and inserted in the per-thread stack of owned
+ * mutexes.
+ *
+ * @param[in] mp pointer to the @p mutex_t structure
+ *
+ * @sclass
+ */
+void chMtxLockS(mutex_t *mp) {
+ thread_t *ctp = currp;
+
+ chDbgCheckClassS();
+ chDbgCheck(mp != NULL);
+
+ /* Is the mutex already locked? */
+ if (mp->m_owner != NULL) {
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+
+ chDbgAssert(mp->m_cnt >= 1, "counter is not positive");
+
+ /* If the mutex is already owned by this thread, the counter is increased
+ and there is no need of more actions.*/
+ if (mp->m_owner == ctp)
+ mp->m_cnt++;
+ else {
+#endif
+ /* Priority inheritance protocol; explores the thread-mutex dependencies
+ boosting the priority of all the affected threads to equal the
+ priority of the running thread requesting the mutex.*/
+ thread_t *tp = mp->m_owner;
+
+ /* Does the running thread have higher priority than the mutex
+ owning thread? */
+ while (tp->p_prio < ctp->p_prio) {
+ /* Make priority of thread tp match the running thread's priority.*/
+ tp->p_prio = ctp->p_prio;
+
+ /* The following states need priority queues reordering.*/
+ switch (tp->p_state) {
+ case CH_STATE_WTMTX:
+ /* Re-enqueues the mutex owner with its new priority.*/
+ queue_prio_insert(queue_dequeue(tp),
+ (threads_queue_t *)tp->p_u.wtobjp);
+ tp = ((mutex_t *)tp->p_u.wtobjp)->m_owner;
+ continue;
+ #if CH_CFG_USE_CONDVARS | \
+ (CH_CFG_USE_SEMAPHORES && CH_CFG_USE_SEMAPHORES_PRIORITY) | \
+ (CH_CFG_USE_MESSAGES && CH_CFG_USE_MESSAGES_PRIORITY)
+ #if CH_CFG_USE_CONDVARS
+ case CH_STATE_WTCOND:
+ #endif
+ #if CH_CFG_USE_SEMAPHORES && CH_CFG_USE_SEMAPHORES_PRIORITY
+ case CH_STATE_WTSEM:
+ #endif
+ #if CH_CFG_USE_MESSAGES && CH_CFG_USE_MESSAGES_PRIORITY
+ case CH_STATE_SNDMSGQ:
+ #endif
+ /* Re-enqueues tp with its new priority on the queue.*/
+ queue_prio_insert(queue_dequeue(tp),
+ (threads_queue_t *)tp->p_u.wtobjp);
+ break;
+ #endif
+ case CH_STATE_READY:
+ #if CH_DBG_ENABLE_ASSERTS
+ /* Prevents an assertion in chSchReadyI().*/
+ tp->p_state = CH_STATE_CURRENT;
+ #endif
+ /* Re-enqueues tp with its new priority on the ready list.*/
+ chSchReadyI(queue_dequeue(tp));
+ break;
+ }
+ break;
+ }
+
+ /* Sleep on the mutex.*/
+ queue_prio_insert(ctp, &mp->m_queue);
+ ctp->p_u.wtobjp = mp;
+ chSchGoSleepS(CH_STATE_WTMTX);
+
+ /* It is assumed that the thread performing the unlock operation assigns
+ the mutex to this thread.*/
+ chDbgAssert(mp->m_owner == ctp, "not owner");
+ chDbgAssert(ctp->p_mtxlist == mp, "not owned");
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ chDbgAssert(mp->m_cnt == 1, "counter is not one");
+ }
+#endif
+ }
+ else {
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ chDbgAssert(mp->m_cnt == 0, "counter is not zero");
+
+ mp->m_cnt++;
+#endif
+ /* It was not owned, inserted in the owned mutexes list.*/
+ mp->m_owner = ctp;
+ mp->m_next = ctp->p_mtxlist;
+ ctp->p_mtxlist = mp;
+ }
+}
+
+/**
+ * @brief Tries to lock a mutex.
+ * @details This function attempts to lock a mutex, if the mutex is already
+ * locked by another thread then the function exits without waiting.
+ * @post The mutex is locked and inserted in the per-thread stack of owned
+ * mutexes.
+ * @note This function does not have any overhead related to the
+ * priority inheritance mechanism because it does not try to
+ * enter a sleep state.
+ *
+ * @param[in] mp pointer to the @p mutex_t structure
+ * @return The operation status.
+ * @retval true if the mutex has been successfully acquired
+ * @retval false if the lock attempt failed.
+ *
+ * @api
+ */
+bool chMtxTryLock(mutex_t *mp) {
+ bool b;
+
+ chSysLock();
+
+ b = chMtxTryLockS(mp);
+
+ chSysUnlock();
+ return b;
+}
+
+/**
+ * @brief Tries to lock a mutex.
+ * @details This function attempts to lock a mutex, if the mutex is already
+ * taken by another thread then the function exits without waiting.
+ * @post The mutex is locked and inserted in the per-thread stack of owned
+ * mutexes.
+ * @note This function does not have any overhead related to the
+ * priority inheritance mechanism because it does not try to
+ * enter a sleep state.
+ *
+ * @param[in] mp pointer to the @p mutex_t structure
+ * @return The operation status.
+ * @retval true if the mutex has been successfully acquired
+ * @retval false if the lock attempt failed.
+ *
+ * @sclass
+ */
+bool chMtxTryLockS(mutex_t *mp) {
+
+ chDbgCheckClassS();
+ chDbgCheck(mp != NULL);
+
+ if (mp->m_owner != NULL) {
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+
+ chDbgAssert(mp->m_cnt >= 1, "counter is not positive");
+
+ if (mp->m_owner == currp) {
+ mp->m_cnt++;
+ return true;
+ }
+#endif
+ return false;
+ }
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+
+ chDbgAssert(mp->m_cnt == 0, "counter is not zero");
+
+ mp->m_cnt++;
+#endif
+ mp->m_owner = currp;
+ mp->m_next = currp->p_mtxlist;
+ currp->p_mtxlist = mp;
+ return true;
+}
+
+/**
+ * @brief Unlocks the next owned mutex in reverse lock order.
+ * @pre The invoking thread <b>must</b> have at least one owned mutex.
+ * @post The mutex is unlocked and removed from the per-thread stack of
+ * owned mutexes.
+ *
+ * @param[in] mp pointer to the @p mutex_t structure
+ *
+ * @api
+ */
+void chMtxUnlock(mutex_t *mp) {
+ thread_t *ctp = currp;
+ mutex_t *lmp;
+
+ chDbgCheck(mp != NULL);
+
+ chSysLock();
+
+ chDbgAssert(ctp->p_mtxlist != NULL, "owned mutexes list empty");
+ chDbgAssert(ctp->p_mtxlist->m_owner == ctp, "ownership failure");
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ chDbgAssert(mp->m_cnt >= 1, "counter is not positive");
+
+ if (--mp->m_cnt == 0) {
+#endif
+
+ chDbgAssert(ctp->p_mtxlist == mp, "not next in list");
+
+ /* Removes the top mutex from the thread's owned mutexes list and marks
+ it as not owned. Note, it is assumed to be the same mutex passed as
+ parameter of this function.*/
+ ctp->p_mtxlist = mp->m_next;
+
+ /* If a thread is waiting on the mutex then the fun part begins.*/
+ if (chMtxQueueNotEmptyS(mp)) {
+ thread_t *tp;
+
+ /* Recalculates the optimal thread priority by scanning the owned
+ mutexes list.*/
+ tprio_t newprio = ctp->p_realprio;
+ lmp = ctp->p_mtxlist;
+ while (lmp != NULL) {
+ /* If the highest priority thread waiting in the mutexes list has a
+ greater priority than the current thread base priority then the
+ final priority will have at least that priority.*/
+ if (chMtxQueueNotEmptyS(lmp) && (lmp->m_queue.p_next->p_prio > newprio))
+ newprio = lmp->m_queue.p_next->p_prio;
+ lmp = lmp->m_next;
+ }
+
+ /* Assigns to the current thread the highest priority among all the
+ waiting threads.*/
+ ctp->p_prio = newprio;
+
+ /* Awakens the highest priority thread waiting for the unlocked mutex and
+ assigns the mutex to it.*/
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ mp->m_cnt = 1;
+#endif
+ tp = queue_fifo_remove(&mp->m_queue);
+ mp->m_owner = tp;
+ mp->m_next = tp->p_mtxlist;
+ tp->p_mtxlist = mp;
+ chSchWakeupS(tp, MSG_OK);
+ }
+ else
+ mp->m_owner = NULL;
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ }
+#endif
+
+ chSysUnlock();
+}
+
+/**
+ * @brief Unlocks the next owned mutex in reverse lock order.
+ * @pre The invoking thread <b>must</b> have at least one owned mutex.
+ * @post The mutex is unlocked and removed from the per-thread stack of
+ * owned mutexes.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel.
+ *
+ * @param[in] mp pointer to the @p mutex_t structure
+ *
+ * @sclass
+ */
+void chMtxUnlockS(mutex_t *mp) {
+ thread_t *ctp = currp;
+ mutex_t *lmp;
+
+ chDbgCheckClassS();
+ chDbgCheck(mp != NULL);
+
+ chDbgAssert(ctp->p_mtxlist != NULL, "owned mutexes list empty");
+ chDbgAssert(ctp->p_mtxlist->m_owner == ctp, "ownership failure");
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ chDbgAssert(mp->m_cnt >= 1, "counter is not positive");
+
+ if (--mp->m_cnt == 0) {
+#endif
+
+ chDbgAssert(ctp->p_mtxlist == mp, "not next in list");
+
+ /* Removes the top mutex from the thread's owned mutexes list and marks
+ it as not owned. Note, it is assumed to be the same mutex passed as
+ parameter of this function.*/
+ ctp->p_mtxlist = mp->m_next;
+
+ /* If a thread is waiting on the mutex then the fun part begins.*/
+ if (chMtxQueueNotEmptyS(mp)) {
+ thread_t *tp;
+
+ /* Recalculates the optimal thread priority by scanning the owned
+ mutexes list.*/
+ tprio_t newprio = ctp->p_realprio;
+ lmp = ctp->p_mtxlist;
+ while (lmp != NULL) {
+ /* If the highest priority thread waiting in the mutexes list has a
+ greater priority than the current thread base priority then the
+ final priority will have at least that priority.*/
+ if (chMtxQueueNotEmptyS(lmp) && (lmp->m_queue.p_next->p_prio > newprio))
+ newprio = lmp->m_queue.p_next->p_prio;
+ lmp = lmp->m_next;
+ }
+
+ /* Assigns to the current thread the highest priority among all the
+ waiting threads.*/
+ ctp->p_prio = newprio;
+
+ /* Awakens the highest priority thread waiting for the unlocked mutex and
+ assigns the mutex to it.*/
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ mp->m_cnt = 1;
+#endif
+ tp = queue_fifo_remove(&mp->m_queue);
+ mp->m_owner = tp;
+ mp->m_next = tp->p_mtxlist;
+ tp->p_mtxlist = mp;
+ chSchReadyI(tp);
+ }
+ else
+ mp->m_owner = NULL;
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ }
+#endif
+}
+
+/**
+ * @brief Unlocks all the mutexes owned by the invoking thread.
+ * @post The stack of owned mutexes is emptied and all the found
+ * mutexes are unlocked.
+ * @note This function is <b>MUCH MORE</b> efficient than releasing the
+ * mutexes one by one and not just because the call overhead,
+ * this function does not have any overhead related to the priority
+ * inheritance mechanism.
+ *
+ * @api
+ */
+void chMtxUnlockAll(void) {
+ thread_t *ctp = currp;
+
+ chSysLock();
+ if (ctp->p_mtxlist != NULL) {
+ do {
+ mutex_t *mp = ctp->p_mtxlist;
+ ctp->p_mtxlist = mp->m_next;
+ if (chMtxQueueNotEmptyS(mp)) {
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ mp->m_cnt = 1;
+#endif
+ thread_t *tp = queue_fifo_remove(&mp->m_queue);
+ mp->m_owner = tp;
+ mp->m_next = tp->p_mtxlist;
+ tp->p_mtxlist = mp;
+ chSchReadyI(tp);
+ }
+ else {
+#if CH_CFG_USE_MUTEXES_RECURSIVE
+ mp->m_cnt = 0;
+#endif
+ mp->m_owner = NULL;
+ }
+ } while (ctp->p_mtxlist != NULL);
+ ctp->p_prio = ctp->p_realprio;
+ chSchRescheduleS();
+ }
+ chSysUnlock();
+}
+
+#endif /* CH_CFG_USE_MUTEXES */
+
+/** @} */
diff --git a/os/rt/src/chqueues.c b/os/rt/src/chqueues.c new file mode 100644 index 000000000..c0b0f8256 --- /dev/null +++ b/os/rt/src/chqueues.c @@ -0,0 +1,427 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chqueues.c
+ * @brief I/O Queues code.
+ *
+ * @addtogroup io_queues
+ * @details ChibiOS/RT queues are mostly used in serial-like device drivers.
+ * The device drivers are usually designed to have a lower side
+ * (lower driver, it is usually an interrupt service routine) and an
+ * upper side (upper driver, accessed by the application threads).<br>
+ * There are several kind of queues:<br>
+ * - <b>Input queue</b>, unidirectional queue where the writer is the
+ * lower side and the reader is the upper side.
+ * - <b>Output queue</b>, unidirectional queue where the writer is the
+ * upper side and the reader is the lower side.
+ * - <b>Full duplex queue</b>, bidirectional queue. Full duplex queues
+ * are implemented by pairing an input queue and an output queue
+ * together.
+ * .
+ * @pre In order to use the I/O queues the @p CH_CFG_USE_QUEUES option must
+ * be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_QUEUES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes an input queue.
+ * @details A Semaphore is internally initialized and works as a counter of
+ * the bytes contained in the queue.
+ * @note The callback is invoked from within the S-Locked system state,
+ * see @ref system_states.
+ *
+ * @param[out] iqp pointer to an @p input_queue_t structure
+ * @param[in] bp pointer to a memory area allocated as queue buffer
+ * @param[in] size size of the queue buffer
+ * @param[in] infy pointer to a callback function that is invoked when
+ * data is read from the queue. The value can be @p NULL.
+ * @param[in] link application defined pointer
+ *
+ * @init
+ */
+void chIQObjectInit(input_queue_t *iqp, uint8_t *bp, size_t size,
+ qnotify_t infy, void *link) {
+
+ chThdQueueObjectInit(&iqp->q_waiting);
+ iqp->q_counter = 0;
+ iqp->q_buffer = iqp->q_rdptr = iqp->q_wrptr = bp;
+ iqp->q_top = bp + size;
+ iqp->q_notify = infy;
+ iqp->q_link = link;
+}
+
+/**
+ * @brief Resets an input queue.
+ * @details All the data in the input queue is erased and lost, any waiting
+ * thread is resumed with status @p Q_RESET.
+ * @note A reset operation can be used by a low level driver in order to
+ * obtain immediate attention from the high level layers.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ *
+ * @iclass
+ */
+void chIQResetI(input_queue_t *iqp) {
+
+ chDbgCheckClassI();
+
+ iqp->q_rdptr = iqp->q_wrptr = iqp->q_buffer;
+ iqp->q_counter = 0;
+ chThdDequeueAllI(&iqp->q_waiting, Q_RESET);
+}
+
+/**
+ * @brief Input queue write.
+ * @details A byte value is written into the low end of an input queue.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ * @param[in] b the byte value to be written in the queue
+ * @return The operation status.
+ * @retval Q_OK if the operation has been completed with success.
+ * @retval Q_FULL if the queue is full and the operation cannot be
+ * completed.
+ *
+ * @iclass
+ */
+msg_t chIQPutI(input_queue_t *iqp, uint8_t b) {
+
+ chDbgCheckClassI();
+
+ if (chIQIsFullI(iqp))
+ return Q_FULL;
+
+ iqp->q_counter++;
+ *iqp->q_wrptr++ = b;
+ if (iqp->q_wrptr >= iqp->q_top)
+ iqp->q_wrptr = iqp->q_buffer;
+
+ chThdDequeueNextI(&iqp->q_waiting, Q_OK);
+
+ return Q_OK;
+}
+
+/**
+ * @brief Input queue read with timeout.
+ * @details This function reads a byte value from an input queue. If the queue
+ * is empty then the calling thread is suspended until a byte arrives
+ * in the queue or a timeout occurs.
+ * @note The callback is invoked before reading the character from the
+ * buffer or before entering the state @p CH_STATE_WTQUEUE.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return A byte value from the queue.
+ * @retval Q_TIMEOUT if the specified time expired.
+ * @retval Q_RESET if the queue has been reset.
+ *
+ * @api
+ */
+msg_t chIQGetTimeout(input_queue_t *iqp, systime_t time) {
+ uint8_t b;
+
+ chSysLock();
+ if (iqp->q_notify)
+ iqp->q_notify(iqp);
+
+ while (chIQIsEmptyI(iqp)) {
+ msg_t msg;
+ if ((msg = chThdEnqueueTimeoutS(&iqp->q_waiting, time)) < Q_OK) {
+ chSysUnlock();
+ return msg;
+ }
+ }
+
+ iqp->q_counter--;
+ b = *iqp->q_rdptr++;
+ if (iqp->q_rdptr >= iqp->q_top)
+ iqp->q_rdptr = iqp->q_buffer;
+
+ chSysUnlock();
+ return b;
+}
+
+/**
+ * @brief Input queue read with timeout.
+ * @details The function reads data from an input queue into a buffer. The
+ * operation completes when the specified amount of data has been
+ * transferred or after the specified timeout or if the queue has
+ * been reset.
+ * @note The function is not atomic, if you need atomicity it is suggested
+ * to use a semaphore or a mutex for mutual exclusion.
+ * @note The callback is invoked before reading each character from the
+ * buffer or before entering the state @p CH_STATE_WTQUEUE.
+ *
+ * @param[in] iqp pointer to an @p input_queue_t structure
+ * @param[out] bp pointer to the data buffer
+ * @param[in] n the maximum amount of data to be transferred, the
+ * value 0 is reserved
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The number of bytes effectively transferred.
+ *
+ * @api
+ */
+size_t chIQReadTimeout(input_queue_t *iqp, uint8_t *bp,
+ size_t n, systime_t time) {
+ qnotify_t nfy = iqp->q_notify;
+ size_t r = 0;
+
+ chDbgCheck(n > 0);
+
+ chSysLock();
+ while (true) {
+ if (nfy)
+ nfy(iqp);
+
+ while (chIQIsEmptyI(iqp)) {
+ if (chThdEnqueueTimeoutS(&iqp->q_waiting, time) != Q_OK) {
+ chSysUnlock();
+ return r;
+ }
+ }
+
+ iqp->q_counter--;
+ *bp++ = *iqp->q_rdptr++;
+ if (iqp->q_rdptr >= iqp->q_top)
+ iqp->q_rdptr = iqp->q_buffer;
+
+ chSysUnlock(); /* Gives a preemption chance in a controlled point.*/
+ r++;
+ if (--n == 0)
+ return r;
+
+ chSysLock();
+ }
+}
+
+/**
+ * @brief Initializes an output queue.
+ * @details A Semaphore is internally initialized and works as a counter of
+ * the free bytes in the queue.
+ * @note The callback is invoked from within the S-Locked system state,
+ * see @ref system_states.
+ *
+ * @param[out] oqp pointer to an @p output_queue_t structure
+ * @param[in] bp pointer to a memory area allocated as queue buffer
+ * @param[in] size size of the queue buffer
+ * @param[in] onfy pointer to a callback function that is invoked when
+ * data is written to the queue. The value can be @p NULL.
+ * @param[in] link application defined pointer
+ *
+ * @init
+ */
+void chOQObjectInit(output_queue_t *oqp, uint8_t *bp, size_t size,
+ qnotify_t onfy, void *link) {
+
+ chThdQueueObjectInit(&oqp->q_waiting);
+ oqp->q_counter = size;
+ oqp->q_buffer = oqp->q_rdptr = oqp->q_wrptr = bp;
+ oqp->q_top = bp + size;
+ oqp->q_notify = onfy;
+ oqp->q_link = link;
+}
+
+/**
+ * @brief Resets an output queue.
+ * @details All the data in the output queue is erased and lost, any waiting
+ * thread is resumed with status @p Q_RESET.
+ * @note A reset operation can be used by a low level driver in order to
+ * obtain immediate attention from the high level layers.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ *
+ * @iclass
+ */
+void chOQResetI(output_queue_t *oqp) {
+
+ chDbgCheckClassI();
+
+ oqp->q_rdptr = oqp->q_wrptr = oqp->q_buffer;
+ oqp->q_counter = chQSizeI(oqp);
+ chThdDequeueAllI(&oqp->q_waiting, Q_RESET);
+}
+
+/**
+ * @brief Output queue write with timeout.
+ * @details This function writes a byte value to an output queue. If the queue
+ * is full then the calling thread is suspended until there is space
+ * in the queue or a timeout occurs.
+ * @note The callback is invoked after writing the character into the
+ * buffer.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ * @param[in] b the byte value to be written in the queue
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The operation status.
+ * @retval Q_OK if the operation succeeded.
+ * @retval Q_TIMEOUT if the specified time expired.
+ * @retval Q_RESET if the queue has been reset.
+ *
+ * @api
+ */
+msg_t chOQPutTimeout(output_queue_t *oqp, uint8_t b, systime_t time) {
+
+ chSysLock();
+ while (chOQIsFullI(oqp)) {
+ msg_t msg;
+
+ if ((msg = chThdEnqueueTimeoutS(&oqp->q_waiting, time)) < Q_OK) {
+ chSysUnlock();
+ return msg;
+ }
+ }
+
+ oqp->q_counter--;
+ *oqp->q_wrptr++ = b;
+ if (oqp->q_wrptr >= oqp->q_top)
+ oqp->q_wrptr = oqp->q_buffer;
+
+ if (oqp->q_notify)
+ oqp->q_notify(oqp);
+
+ chSysUnlock();
+ return Q_OK;
+}
+
+/**
+ * @brief Output queue read.
+ * @details A byte value is read from the low end of an output queue.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ * @return The byte value from the queue.
+ * @retval Q_EMPTY if the queue is empty.
+ *
+ * @iclass
+ */
+msg_t chOQGetI(output_queue_t *oqp) {
+ uint8_t b;
+
+ chDbgCheckClassI();
+
+ if (chOQIsEmptyI(oqp))
+ return Q_EMPTY;
+
+ oqp->q_counter++;
+ b = *oqp->q_rdptr++;
+ if (oqp->q_rdptr >= oqp->q_top)
+ oqp->q_rdptr = oqp->q_buffer;
+
+ chThdDequeueNextI(&oqp->q_waiting, Q_OK);
+
+ return b;
+}
+
+/**
+ * @brief Output queue write with timeout.
+ * @details The function writes data from a buffer to an output queue. The
+ * operation completes when the specified amount of data has been
+ * transferred or after the specified timeout or if the queue has
+ * been reset.
+ * @note The function is not atomic, if you need atomicity it is suggested
+ * to use a semaphore or a mutex for mutual exclusion.
+ * @note The callback is invoked after writing each character into the
+ * buffer.
+ *
+ * @param[in] oqp pointer to an @p output_queue_t structure
+ * @param[out] bp pointer to the data buffer
+ * @param[in] n the maximum amount of data to be transferred, the
+ * value 0 is reserved
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return The number of bytes effectively transferred.
+ *
+ * @api
+ */
+size_t chOQWriteTimeout(output_queue_t *oqp, const uint8_t *bp,
+ size_t n, systime_t time) {
+ qnotify_t nfy = oqp->q_notify;
+ size_t w = 0;
+
+ chDbgCheck(n > 0);
+
+ chSysLock();
+ while (true) {
+ while (chOQIsFullI(oqp)) {
+ if (chThdEnqueueTimeoutS(&oqp->q_waiting, time) != Q_OK) {
+ chSysUnlock();
+ return w;
+ }
+ }
+ oqp->q_counter--;
+ *oqp->q_wrptr++ = *bp++;
+ if (oqp->q_wrptr >= oqp->q_top)
+ oqp->q_wrptr = oqp->q_buffer;
+
+ if (nfy)
+ nfy(oqp);
+
+ chSysUnlock(); /* Gives a preemption chance in a controlled point.*/
+ w++;
+ if (--n == 0)
+ return w;
+ chSysLock();
+ }
+}
+#endif /* CH_CFG_USE_QUEUES */
+
+/** @} */
diff --git a/os/rt/src/chregistry.c b/os/rt/src/chregistry.c new file mode 100644 index 000000000..685d0c109 --- /dev/null +++ b/os/rt/src/chregistry.c @@ -0,0 +1,175 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chregistry.c
+ * @brief Threads registry code.
+ *
+ * @addtogroup registry
+ * @details Threads Registry related APIs and services.
+ *
+ * <h2>Operation mode</h2>
+ * The Threads Registry is a double linked list that holds all the
+ * active threads in the system.<br>
+ * Operations defined for the registry:
+ * - <b>First</b>, returns the first, in creation order, active thread
+ * in the system.
+ * - <b>Next</b>, returns the next, in creation order, active thread
+ * in the system.
+ * .
+ * The registry is meant to be mainly a debug feature, for example,
+ * using the registry a debugger can enumerate the active threads
+ * in any given moment or the shell can print the active threads
+ * and their state.<br>
+ * Another possible use is for centralized threads memory management,
+ * terminating threads can pulse an event source and an event handler
+ * can perform a scansion of the registry in order to recover the
+ * memory.
+ * @pre In order to use the threads registry the @p CH_CFG_USE_REGISTRY
+ * option must be enabled in @p chconf.h.
+ * @{
+ */
+#include "ch.h"
+
+#if CH_CFG_USE_REGISTRY || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+#define _offsetof(st, m) \
+ ((size_t)((char *)&((st *)0)->m - (char *)0))
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/*
+ * OS signature in ROM plus debug-related information.
+ */
+ROMCONST chdebug_t ch_debug = {
+ "main",
+ (uint8_t)0,
+ (uint8_t)sizeof (chdebug_t),
+ (uint16_t)((CH_KERNEL_MAJOR << 11) |
+ (CH_KERNEL_MINOR << 6) |
+ (CH_KERNEL_PATCH) << 0),
+ (uint8_t)sizeof (void *),
+ (uint8_t)sizeof (systime_t),
+ (uint8_t)sizeof (thread_t),
+ (uint8_t)_offsetof(thread_t, p_prio),
+ (uint8_t)_offsetof(thread_t, p_ctx),
+ (uint8_t)_offsetof(thread_t, p_newer),
+ (uint8_t)_offsetof(thread_t, p_older),
+ (uint8_t)_offsetof(thread_t, p_name),
+#if CH_DBG_ENABLE_STACK_CHECK
+ (uint8_t)_offsetof(thread_t, p_stklimit),
+#else
+ (uint8_t)0,
+#endif
+ (uint8_t)_offsetof(thread_t, p_state),
+ (uint8_t)_offsetof(thread_t, p_flags),
+#if CH_CFG_USE_DYNAMIC
+ (uint8_t)_offsetof(thread_t, p_refs),
+#else
+ (uint8_t)0,
+#endif
+#if CH_CFG_TIME_QUANTUM > 0
+ (uint8_t)_offsetof(thread_t, p_preempt),
+#else
+ (uint8_t)0,
+#endif
+#if CH_DBG_THREADS_PROFILING
+ (uint8_t)_offsetof(thread_t, p_time)
+#else
+ (uint8_t)0
+#endif
+};
+
+/**
+ * @brief Returns the first thread in the system.
+ * @details Returns the most ancient thread in the system, usually this is
+ * the main thread unless it terminated. A reference is added to the
+ * returned thread in order to make sure its status is not lost.
+ * @note This function cannot return @p NULL because there is always at
+ * least one thread in the system.
+ *
+ * @return A reference to the most ancient thread.
+ *
+ * @api
+ */
+thread_t *chRegFirstThread(void) {
+ thread_t *tp;
+
+ chSysLock();
+ tp = ch.rlist.r_newer;
+#if CH_CFG_USE_DYNAMIC
+ tp->p_refs++;
+#endif
+ chSysUnlock();
+ return tp;
+}
+
+/**
+ * @brief Returns the thread next to the specified one.
+ * @details The reference counter of the specified thread is decremented and
+ * the reference counter of the returned thread is incremented.
+ *
+ * @param[in] tp pointer to the thread
+ * @return A reference to the next thread.
+ * @retval NULL if there is no next thread.
+ *
+ * @api
+ */
+thread_t *chRegNextThread(thread_t *tp) {
+ thread_t *ntp;
+
+ chSysLock();
+ ntp = tp->p_newer;
+ if (ntp == (thread_t *)&ch.rlist)
+ ntp = NULL;
+#if CH_CFG_USE_DYNAMIC
+ else {
+ chDbgAssert(ntp->p_refs < 255, "too many references");
+ ntp->p_refs++;
+ }
+#endif
+ chSysUnlock();
+#if CH_CFG_USE_DYNAMIC
+ chThdRelease(tp);
+#endif
+ return ntp;
+}
+
+#endif /* CH_CFG_USE_REGISTRY */
+
+/** @} */
diff --git a/os/rt/src/chschd.c b/os/rt/src/chschd.c new file mode 100644 index 000000000..acf65fb85 --- /dev/null +++ b/os/rt/src/chschd.c @@ -0,0 +1,521 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chschd.c
+ * @brief Scheduler code.
+ *
+ * @addtogroup scheduler
+ * @details This module provides the default portable scheduler code.
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/**
+ * @brief System data structures.
+ */
+ch_system_t ch;
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Scheduler initialization.
+ *
+ * @notapi
+ */
+void _scheduler_init(void) {
+
+ queue_init(&ch.rlist.r_queue);
+ ch.rlist.r_prio = NOPRIO;
+#if CH_CFG_USE_REGISTRY
+ ch.rlist.r_newer = ch.rlist.r_older = (thread_t *)&ch.rlist;
+#endif
+}
+
+#if !CH_CFG_OPTIMIZE_SPEED || defined(__DOXYGEN__)
+/**
+ * @brief Inserts a thread into a priority ordered queue.
+ * @note The insertion is done by scanning the list from the highest
+ * priority toward the lowest.
+ *
+ * @param[in] tp the pointer to the thread to be inserted in the list
+ * @param[in] tqp the pointer to the threads list header
+ *
+ * @notapi
+ */
+void queue_prio_insert(thread_t *tp, threads_queue_t *tqp) {
+
+ /* cp iterates over the queue.*/
+ thread_t *cp = (thread_t *)tqp;
+ do {
+ /* Iterate to next thread in queue.*/
+ cp = cp->p_next;
+ /* Not end of queue? and cp has equal or higher priority than tp?.*/
+ } while ((cp != (thread_t *)tqp) && (cp->p_prio >= tp->p_prio));
+ /* Insertion on p_prev.*/
+ tp->p_next = cp;
+ tp->p_prev = cp->p_prev;
+ tp->p_prev->p_next = cp->p_prev = tp;
+}
+
+/**
+ * @brief Inserts a thread into a queue.
+ *
+ * @param[in] tp the pointer to the thread to be inserted in the list
+ * @param[in] tqp the pointer to the threads list header
+ *
+ * @notapi
+ */
+void queue_insert(thread_t *tp, threads_queue_t *tqp) {
+
+ tp->p_next = (thread_t *)tqp;
+ tp->p_prev = tqp->p_prev;
+ tp->p_prev->p_next = tqp->p_prev = tp;
+}
+
+/**
+ * @brief Removes the first-out thread from a queue and returns it.
+ * @note If the queue is priority ordered then this function returns the
+ * thread with the highest priority.
+ *
+ * @param[in] tqp the pointer to the threads list header
+ * @return The removed thread pointer.
+ *
+ * @notapi
+ */
+thread_t *queue_fifo_remove(threads_queue_t *tqp) {
+ thread_t *tp = tqp->p_next;
+
+ (tqp->p_next = tp->p_next)->p_prev = (thread_t *)tqp;
+ return tp;
+}
+
+/**
+ * @brief Removes the last-out thread from a queue and returns it.
+ * @note If the queue is priority ordered then this function returns the
+ * thread with the lowest priority.
+ *
+ * @param[in] tqp the pointer to the threads list header
+ * @return The removed thread pointer.
+ *
+ * @notapi
+ */
+thread_t *queue_lifo_remove(threads_queue_t *tqp) {
+ thread_t *tp = tqp->p_prev;
+
+ (tqp->p_prev = tp->p_prev)->p_next = (thread_t *)tqp;
+ return tp;
+}
+
+/**
+ * @brief Removes a thread from a queue and returns it.
+ * @details The thread is removed from the queue regardless of its relative
+ * position and regardless the used insertion method.
+ *
+ * @param[in] tp the pointer to the thread to be removed from the queue
+ * @return The removed thread pointer.
+ *
+ * @notapi
+ */
+thread_t *queue_dequeue(thread_t *tp) {
+
+ tp->p_prev->p_next = tp->p_next;
+ tp->p_next->p_prev = tp->p_prev;
+ return tp;
+}
+
+/**
+ * @brief Pushes a thread_t on top of a stack list.
+ *
+ * @param[in] tp the pointer to the thread to be inserted in the list
+ * @param[in] tlp the pointer to the threads list header
+ *
+ * @notapi
+ */
+void list_insert(thread_t *tp, threads_list_t *tlp) {
+
+ tp->p_next = tlp->p_next;
+ tlp->p_next = tp;
+}
+
+/**
+ * @brief Pops a thread from the top of a stack list and returns it.
+ * @pre The list must be non-empty before calling this function.
+ *
+ * @param[in] tlp the pointer to the threads list header
+ * @return The removed thread pointer.
+ *
+ * @notapi
+ */
+thread_t *list_remove(threads_list_t *tlp) {
+
+ thread_t *tp = tlp->p_next;
+ tlp->p_next = tp->p_next;
+ return tp;
+}
+#endif /* CH_CFG_OPTIMIZE_SPEED */
+
+/**
+ * @brief Inserts a thread in the Ready List.
+ * @details The thread is positioned behind all threads with higher or equal
+ * priority.
+ * @pre The thread must not be already inserted in any list through its
+ * @p p_next and @p p_prev or list corruption would occur.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] tp the thread to be made ready
+ * @return The thread pointer.
+ *
+ * @iclass
+ */
+thread_t *chSchReadyI(thread_t *tp) {
+ thread_t *cp;
+
+ chDbgCheckClassI();
+ chDbgCheck(tp != NULL);
+ chDbgAssert((tp->p_state != CH_STATE_READY) &&
+ (tp->p_state != CH_STATE_FINAL),
+ "invalid state");
+
+ tp->p_state = CH_STATE_READY;
+ cp = (thread_t *)&ch.rlist.r_queue;
+ do {
+ cp = cp->p_next;
+ } while (cp->p_prio >= tp->p_prio);
+ /* Insertion on p_prev.*/
+ tp->p_next = cp;
+ tp->p_prev = cp->p_prev;
+ tp->p_prev->p_next = cp->p_prev = tp;
+ return tp;
+}
+
+/**
+ * @brief Puts the current thread to sleep into the specified state.
+ * @details The thread goes into a sleeping state. The possible
+ * @ref thread_states are defined into @p threads.h.
+ *
+ * @param[in] newstate the new thread state
+ *
+ * @sclass
+ */
+void chSchGoSleepS(tstate_t newstate) {
+ thread_t *otp;
+
+ chDbgCheckClassS();
+
+ (otp = currp)->p_state = newstate;
+#if CH_CFG_TIME_QUANTUM > 0
+ /* The thread is renouncing its remaining time slices so it will have a new
+ time quantum when it will wakeup.*/
+ otp->p_preempt = CH_CFG_TIME_QUANTUM;
+#endif
+ setcurrp(queue_fifo_remove(&ch.rlist.r_queue));
+#if defined(CH_CFG_IDLE_ENTER_HOOK)
+ if (currp->p_prio == IDLEPRIO) {
+ CH_CFG_IDLE_ENTER_HOOK();
+ }
+#endif
+ currp->p_state = CH_STATE_CURRENT;
+ chSysSwitch(currp, otp);
+}
+
+/*
+ * Timeout wakeup callback.
+ */
+static void wakeup(void *p) {
+ thread_t *tp = (thread_t *)p;
+
+ chSysLockFromISR();
+ switch (tp->p_state) {
+ case CH_STATE_READY:
+ /* Handling the special case where the thread has been made ready by
+ another thread with higher priority.*/
+ chSysUnlockFromISR();
+ return;
+ case CH_STATE_SUSPENDED:
+ *(thread_reference_t *)tp->p_u.wtobjp = NULL;
+ break;
+#if CH_CFG_USE_SEMAPHORES
+ case CH_STATE_WTSEM:
+ chSemFastSignalI((semaphore_t *)tp->p_u.wtobjp);
+ /* Falls into, intentional. */
+#endif
+#if CH_CFG_USE_CONDVARS && CH_CFG_USE_CONDVARS_TIMEOUT
+ case CH_STATE_WTCOND:
+#endif
+ case CH_STATE_QUEUED:
+ /* States requiring dequeuing.*/
+ queue_dequeue(tp);
+ }
+ tp->p_u.rdymsg = MSG_TIMEOUT;
+ chSchReadyI(tp);
+ chSysUnlockFromISR();
+}
+
+/**
+ * @brief Puts the current thread to sleep into the specified state with
+ * timeout specification.
+ * @details The thread goes into a sleeping state, if it is not awakened
+ * explicitly within the specified timeout then it is forcibly
+ * awakened with a @p MSG_TIMEOUT low level message. The possible
+ * @ref thread_states are defined into @p threads.h.
+ *
+ * @param[in] newstate the new thread state
+ * @param[in] time the number of ticks before the operation timeouts, the
+ * special values are handled as follow:
+ * - @a TIME_INFINITE the thread enters an infinite sleep
+ * state, this is equivalent to invoking
+ * @p chSchGoSleepS() but, of course, less efficient.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ * @return The wakeup message.
+ * @retval MSG_TIMEOUT if a timeout occurs.
+ *
+ * @sclass
+ */
+msg_t chSchGoSleepTimeoutS(tstate_t newstate, systime_t time) {
+
+ chDbgCheckClassS();
+
+ if (TIME_INFINITE != time) {
+ virtual_timer_t vt;
+
+ chVTDoSetI(&vt, time, wakeup, currp);
+ chSchGoSleepS(newstate);
+ if (chVTIsArmedI(&vt))
+ chVTDoResetI(&vt);
+ }
+ else
+ chSchGoSleepS(newstate);
+ return currp->p_u.rdymsg;
+}
+
+/**
+ * @brief Wakes up a thread.
+ * @details The thread is inserted into the ready list or immediately made
+ * running depending on its relative priority compared to the current
+ * thread.
+ * @pre The thread must not be already inserted in any list through its
+ * @p p_next and @p p_prev or list corruption would occur.
+ * @note It is equivalent to a @p chSchReadyI() followed by a
+ * @p chSchRescheduleS() but much more efficient.
+ * @note The function assumes that the current thread has the highest
+ * priority.
+ *
+ * @param[in] ntp the thread to be made ready
+ * @param[in] msg the wakeup message
+ *
+ * @sclass
+ */
+void chSchWakeupS(thread_t *ntp, msg_t msg) {
+
+ chDbgCheckClassS();
+
+ /* Storing the message to be retrieved by the target thread when it will
+ restart execution.*/
+ ntp->p_u.rdymsg = msg;
+
+ /* If the waken thread has a not-greater priority than the current
+ one then it is just inserted in the ready list else it made
+ running immediately and the invoking thread goes in the ready
+ list instead.*/
+ if (ntp->p_prio <= currp->p_prio) {
+ chSchReadyI(ntp);
+ }
+ else {
+ thread_t *otp = chSchReadyI(currp);
+ setcurrp(ntp);
+#if defined(CH_CFG_IDLE_LEAVE_HOOK)
+ if (otp->p_prio == IDLEPRIO) {
+ CH_CFG_IDLE_LEAVE_HOOK();
+ }
+#endif
+ ntp->p_state = CH_STATE_CURRENT;
+ chSysSwitch(ntp, otp);
+ }
+}
+
+/**
+ * @brief Performs a reschedule if a higher priority thread is runnable.
+ * @details If a thread with a higher priority than the current thread is in
+ * the ready list then make the higher priority thread running.
+ *
+ * @sclass
+ */
+void chSchRescheduleS(void) {
+
+ chDbgCheckClassS();
+
+ if (chSchIsRescRequiredI())
+ chSchDoRescheduleAhead();
+}
+
+/**
+ * @brief Evaluates if preemption is required.
+ * @details The decision is taken by comparing the relative priorities and
+ * depending on the state of the round robin timeout counter.
+ * @note Not a user function, it is meant to be invoked by the scheduler
+ * itself or from within the port layer.
+ *
+ * @retval true if there is a thread that must go in running state
+ * immediately.
+ * @retval false if preemption is not required.
+ *
+ * @special
+ */
+bool chSchIsPreemptionRequired(void) {
+ tprio_t p1 = firstprio(&ch.rlist.r_queue);
+ tprio_t p2 = currp->p_prio;
+#if CH_CFG_TIME_QUANTUM > 0
+ /* If the running thread has not reached its time quantum, reschedule only
+ if the first thread on the ready queue has a higher priority.
+ Otherwise, if the running thread has used up its time quantum, reschedule
+ if the first thread on the ready queue has equal or higher priority.*/
+ return currp->p_preempt ? p1 > p2 : p1 >= p2;
+#else
+ /* If the round robin preemption feature is not enabled then performs a
+ simpler comparison.*/
+ return p1 > p2;
+#endif
+}
+
+/**
+ * @brief Switches to the first thread on the runnable queue.
+ * @details The current thread is positioned in the ready list behind all
+ * threads having the same priority. The thread regains its time
+ * quantum.
+ * @note Not a user function, it is meant to be invoked by the scheduler
+ * itself or from within the port layer.
+ *
+ * @special
+ */
+void chSchDoRescheduleBehind(void) {
+ thread_t *otp;
+
+ otp = currp;
+ /* Picks the first thread from the ready queue and makes it current.*/
+ setcurrp(queue_fifo_remove(&ch.rlist.r_queue));
+#if defined(CH_CFG_IDLE_LEAVE_HOOK)
+ if (otp->p_prio == IDLEPRIO) {
+ CH_CFG_IDLE_LEAVE_HOOK();
+ }
+#endif
+ currp->p_state = CH_STATE_CURRENT;
+#if CH_CFG_TIME_QUANTUM > 0
+ otp->p_preempt = CH_CFG_TIME_QUANTUM;
+#endif
+ chSchReadyI(otp);
+ chSysSwitch(currp, otp);
+}
+
+/**
+ * @brief Switches to the first thread on the runnable queue.
+ * @details The current thread is positioned in the ready list ahead of all
+ * threads having the same priority.
+ * @note Not a user function, it is meant to be invoked by the scheduler
+ * itself or from within the port layer.
+ *
+ * @special
+ */
+void chSchDoRescheduleAhead(void) {
+ thread_t *otp, *cp;
+
+ otp = currp;
+ /* Picks the first thread from the ready queue and makes it current.*/
+ setcurrp(queue_fifo_remove(&ch.rlist.r_queue));
+#if defined(CH_CFG_IDLE_LEAVE_HOOK)
+ if (otp->p_prio == IDLEPRIO) {
+ CH_CFG_IDLE_LEAVE_HOOK();
+ }
+#endif
+ currp->p_state = CH_STATE_CURRENT;
+
+ otp->p_state = CH_STATE_READY;
+ cp = (thread_t *)&ch.rlist.r_queue;
+ do {
+ cp = cp->p_next;
+ } while (cp->p_prio > otp->p_prio);
+ /* Insertion on p_prev.*/
+ otp->p_next = cp;
+ otp->p_prev = cp->p_prev;
+ otp->p_prev->p_next = cp->p_prev = otp;
+
+ chSysSwitch(currp, otp);
+}
+
+/**
+ * @brief Switches to the first thread on the runnable queue.
+ * @details The current thread is positioned in the ready list behind or
+ * ahead of all threads having the same priority depending on
+ * if it used its whole time slice.
+ * @note Not a user function, it is meant to be invoked by the scheduler
+ * itself or from within the port layer.
+ *
+ * @special
+ */
+void chSchDoReschedule(void) {
+
+#if CH_CFG_TIME_QUANTUM > 0
+ /* If CH_CFG_TIME_QUANTUM is enabled then there are two different scenarios
+ to handle on preemption: time quantum elapsed or not.*/
+ if (currp->p_preempt == 0) {
+ /* The thread consumed its time quantum so it is enqueued behind threads
+ with same priority level, however, it acquires a new time quantum.*/
+ chSchDoRescheduleBehind();
+ }
+ else {
+ /* The thread didn't consume all its time quantum so it is put ahead of
+ threads with equal priority and does not acquire a new time quantum.*/
+ chSchDoRescheduleAhead();
+ }
+#else /* !(CH_CFG_TIME_QUANTUM > 0) */
+ /* If the round-robin mechanism is disabled then the thread goes always
+ ahead of its peers.*/
+ chSchDoRescheduleAhead();
+#endif /* !(CH_CFG_TIME_QUANTUM > 0) */
+}
+
+/** @} */
diff --git a/os/rt/src/chsem.c b/os/rt/src/chsem.c new file mode 100644 index 000000000..22e4413b6 --- /dev/null +++ b/os/rt/src/chsem.c @@ -0,0 +1,401 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chsem.c
+ * @brief Semaphores code.
+ *
+ * @addtogroup semaphores
+ * @details Semaphores related APIs and services.
+ *
+ * <h2>Operation mode</h2>
+ * Semaphores are a flexible synchronization primitive, ChibiOS/RT
+ * implements semaphores in their "counting semaphores" variant as
+ * defined by Edsger Dijkstra plus several enhancements like:
+ * - Wait operation with timeout.
+ * - Reset operation.
+ * - Atomic wait+signal operation.
+ * - Return message from the wait operation (OK, RESET, TIMEOUT).
+ * .
+ * The binary semaphores variant can be easily implemented using
+ * counting semaphores.<br>
+ * Operations defined for semaphores:
+ * - <b>Signal</b>: The semaphore counter is increased and if the
+ * result is non-positive then a waiting thread is removed from
+ * the semaphore queue and made ready for execution.
+ * - <b>Wait</b>: The semaphore counter is decreased and if the result
+ * becomes negative the thread is queued in the semaphore and
+ * suspended.
+ * - <b>Reset</b>: The semaphore counter is reset to a non-negative
+ * value and all the threads in the queue are released.
+ * .
+ * Semaphores can be used as guards for mutual exclusion zones
+ * (note that mutexes are recommended for this kind of use) but
+ * also have other uses, queues guards and counters for example.<br>
+ * Semaphores usually use a FIFO queuing strategy but it is possible
+ * to make them order threads by priority by enabling
+ * @p CH_CFG_USE_SEMAPHORES_PRIORITY in @p chconf.h.
+ * @pre In order to use the semaphore APIs the @p CH_CFG_USE_SEMAPHORES
+ * option must be enabled in @p chconf.h.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_SEMAPHORES || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+#if CH_CFG_USE_SEMAPHORES_PRIORITY
+#define sem_insert(tp, qp) prio_insert(tp, qp)
+#else
+#define sem_insert(tp, qp) queue_insert(tp, qp)
+#endif
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes a semaphore with the specified counter value.
+ *
+ * @param[out] sp pointer to a @p semaphore_t structure
+ * @param[in] n initial value of the semaphore counter. Must be
+ * non-negative.
+ *
+ * @init
+ */
+void chSemObjectInit(semaphore_t *sp, cnt_t n) {
+
+ chDbgCheck((sp != NULL) && (n >= 0));
+
+ queue_init(&sp->s_queue);
+ sp->s_cnt = n;
+}
+
+/**
+ * @brief Performs a reset operation on the semaphore.
+ * @post After invoking this function all the threads waiting on the
+ * semaphore, if any, are released and the semaphore counter is set
+ * to the specified, non negative, value.
+ * @note The released threads can recognize they were waked up by a reset
+ * rather than a signal because the @p chSemWait() will return
+ * @p MSG_RESET instead of @p MSG_OK.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @param[in] n the new value of the semaphore counter. The value must
+ * be non-negative.
+ *
+ * @api
+ */
+void chSemReset(semaphore_t *sp, cnt_t n) {
+
+ chSysLock();
+ chSemResetI(sp, n);
+ chSchRescheduleS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Performs a reset operation on the semaphore.
+ * @post After invoking this function all the threads waiting on the
+ * semaphore, if any, are released and the semaphore counter is set
+ * to the specified, non negative, value.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ * @note The released threads can recognize they were waked up by a reset
+ * rather than a signal because the @p chSemWait() will return
+ * @p MSG_RESET instead of @p MSG_OK.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @param[in] n the new value of the semaphore counter. The value must
+ * be non-negative.
+ *
+ * @iclass
+ */
+void chSemResetI(semaphore_t *sp, cnt_t n) {
+ cnt_t cnt;
+
+ chDbgCheckClassI();
+ chDbgCheck((sp != NULL) && (n >= 0));
+ chDbgAssert(((sp->s_cnt >= 0) && queue_isempty(&sp->s_queue)) ||
+ ((sp->s_cnt < 0) && queue_notempty(&sp->s_queue)),
+ "inconsistent semaphore");
+
+ cnt = sp->s_cnt;
+ sp->s_cnt = n;
+ while (++cnt <= 0)
+ chSchReadyI(queue_lifo_remove(&sp->s_queue))->p_u.rdymsg = MSG_RESET;
+}
+
+/**
+ * @brief Performs a wait operation on a semaphore.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval MSG_OK if the thread has not stopped on the semaphore or the
+ * semaphore has been signaled.
+ * @retval MSG_RESET if the semaphore has been reset using @p chSemReset().
+ *
+ * @api
+ */
+msg_t chSemWait(semaphore_t *sp) {
+ msg_t msg;
+
+ chSysLock();
+ msg = chSemWaitS(sp);
+ chSysUnlock();
+ return msg;
+}
+
+/**
+ * @brief Performs a wait operation on a semaphore.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval MSG_OK if the thread has not stopped on the semaphore or the
+ * semaphore has been signaled.
+ * @retval MSG_RESET if the semaphore has been reset using @p chSemReset().
+ *
+ * @sclass
+ */
+msg_t chSemWaitS(semaphore_t *sp) {
+
+ chDbgCheckClassS();
+ chDbgCheck(sp != NULL);
+ chDbgAssert(((sp->s_cnt >= 0) && queue_isempty(&sp->s_queue)) ||
+ ((sp->s_cnt < 0) && queue_notempty(&sp->s_queue)),
+ "inconsistent semaphore");
+
+ if (--sp->s_cnt < 0) {
+ currp->p_u.wtobjp = sp;
+ sem_insert(currp, &sp->s_queue);
+ chSchGoSleepS(CH_STATE_WTSEM);
+ return currp->p_u.rdymsg;
+ }
+ return MSG_OK;
+}
+
+/**
+ * @brief Performs a wait operation on a semaphore with timeout specification.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval MSG_OK if the thread has not stopped on the semaphore or the
+ * semaphore has been signaled.
+ * @retval MSG_RESET if the semaphore has been reset using @p chSemReset().
+ * @retval MSG_TIMEOUT if the semaphore has not been signaled or reset within
+ * the specified timeout.
+ *
+ * @api
+ */
+msg_t chSemWaitTimeout(semaphore_t *sp, systime_t time) {
+ msg_t msg;
+
+ chSysLock();
+ msg = chSemWaitTimeoutS(sp, time);
+ chSysUnlock();
+ return msg;
+}
+
+/**
+ * @brief Performs a wait operation on a semaphore with timeout specification.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @param[in] time the number of ticks before the operation timeouts,
+ * the following special values are allowed:
+ * - @a TIME_IMMEDIATE immediate timeout.
+ * - @a TIME_INFINITE no timeout.
+ * .
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval MSG_OK if the thread has not stopped on the semaphore or the
+ * semaphore has been signaled.
+ * @retval MSG_RESET if the semaphore has been reset using @p chSemReset().
+ * @retval MSG_TIMEOUT if the semaphore has not been signaled or reset within
+ * the specified timeout.
+ *
+ * @sclass
+ */
+msg_t chSemWaitTimeoutS(semaphore_t *sp, systime_t time) {
+
+ chDbgCheckClassS();
+ chDbgCheck(sp != NULL);
+ chDbgAssert(((sp->s_cnt >= 0) && queue_isempty(&sp->s_queue)) ||
+ ((sp->s_cnt < 0) && queue_notempty(&sp->s_queue)),
+ "inconsistent semaphore");
+
+ if (--sp->s_cnt < 0) {
+ if (TIME_IMMEDIATE == time) {
+ sp->s_cnt++;
+ return MSG_TIMEOUT;
+ }
+ currp->p_u.wtobjp = sp;
+ sem_insert(currp, &sp->s_queue);
+ return chSchGoSleepTimeoutS(CH_STATE_WTSEM, time);
+ }
+ return MSG_OK;
+}
+
+/**
+ * @brief Performs a signal operation on a semaphore.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ *
+ * @api
+ */
+void chSemSignal(semaphore_t *sp) {
+
+ chDbgCheck(sp != NULL);
+ chDbgAssert(((sp->s_cnt >= 0) && queue_isempty(&sp->s_queue)) ||
+ ((sp->s_cnt < 0) && queue_notempty(&sp->s_queue)),
+ "inconsistent semaphore");
+
+ chSysLock();
+ if (++sp->s_cnt <= 0)
+ chSchWakeupS(queue_fifo_remove(&sp->s_queue), MSG_OK);
+ chSysUnlock();
+}
+
+/**
+ * @brief Performs a signal operation on a semaphore.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ *
+ * @iclass
+ */
+void chSemSignalI(semaphore_t *sp) {
+
+ chDbgCheckClassI();
+ chDbgCheck(sp != NULL);
+ chDbgAssert(((sp->s_cnt >= 0) && queue_isempty(&sp->s_queue)) ||
+ ((sp->s_cnt < 0) && queue_notempty(&sp->s_queue)),
+ "inconsistent semaphore");
+
+ if (++sp->s_cnt <= 0) {
+ /* Note, it is done this way in order to allow a tail call on
+ chSchReadyI().*/
+ thread_t *tp = queue_fifo_remove(&sp->s_queue);
+ tp->p_u.rdymsg = MSG_OK;
+ chSchReadyI(tp);
+ }
+}
+
+/**
+ * @brief Adds the specified value to the semaphore counter.
+ * @post This function does not reschedule so a call to a rescheduling
+ * function must be performed before unlocking the kernel. Note that
+ * interrupt handlers always reschedule on exit so an explicit
+ * reschedule must not be performed in ISRs.
+ *
+ * @param[in] sp pointer to a @p semaphore_t structure
+ * @param[in] n value to be added to the semaphore counter. The value
+ * must be positive.
+ *
+ * @iclass
+ */
+void chSemAddCounterI(semaphore_t *sp, cnt_t n) {
+
+ chDbgCheckClassI();
+ chDbgCheck((sp != NULL) && (n > 0));
+ chDbgAssert(((sp->s_cnt >= 0) && queue_isempty(&sp->s_queue)) ||
+ ((sp->s_cnt < 0) && queue_notempty(&sp->s_queue)),
+ "inconsistent semaphore");
+
+ while (n > 0) {
+ if (++sp->s_cnt <= 0)
+ chSchReadyI(queue_fifo_remove(&sp->s_queue))->p_u.rdymsg = MSG_OK;
+ n--;
+ }
+}
+
+/**
+ * @brief Performs atomic signal and wait operations on two semaphores.
+ *
+ * @param[in] sps pointer to a @p semaphore_t structure to be signaled
+ * @param[in] spw pointer to a @p semaphore_t structure to wait on
+ * @return A message specifying how the invoking thread has been
+ * released from the semaphore.
+ * @retval MSG_OK if the thread has not stopped on the semaphore or the
+ * semaphore has been signaled.
+ * @retval MSG_RESET if the semaphore has been reset using @p chSemReset().
+ *
+ * @api
+ */
+msg_t chSemSignalWait(semaphore_t *sps, semaphore_t *spw) {
+ msg_t msg;
+
+ chDbgCheck((sps != NULL) && (spw != NULL));
+ chDbgAssert(((sps->s_cnt >= 0) && queue_isempty(&sps->s_queue)) ||
+ ((sps->s_cnt < 0) && queue_notempty(&sps->s_queue)),
+ "inconsistent semaphore");
+ chDbgAssert(((spw->s_cnt >= 0) && queue_isempty(&spw->s_queue)) ||
+ ((spw->s_cnt < 0) && queue_notempty(&spw->s_queue)),
+ "inconsistent semaphore");
+
+ chSysLock();
+ if (++sps->s_cnt <= 0)
+ chSchReadyI(queue_fifo_remove(&sps->s_queue))->p_u.rdymsg = MSG_OK;
+ if (--spw->s_cnt < 0) {
+ thread_t *ctp = currp;
+ sem_insert(ctp, &spw->s_queue);
+ ctp->p_u.wtobjp = spw;
+ chSchGoSleepS(CH_STATE_WTSEM);
+ msg = ctp->p_u.rdymsg;
+ }
+ else {
+ chSchRescheduleS();
+ msg = MSG_OK;
+ }
+ chSysUnlock();
+ return msg;
+}
+
+#endif /* CH_CFG_USE_SEMAPHORES */
+
+/** @} */
diff --git a/os/rt/src/chstats.c b/os/rt/src/chstats.c new file mode 100644 index 000000000..653d8da77 --- /dev/null +++ b/os/rt/src/chstats.c @@ -0,0 +1,122 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chstats.c
+ * @brief Statistics module code.
+ *
+ * @addtogroup statistics
+ * @details Statistics services.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_DBG_STATISTICS || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes the statistics module.
+ *
+ * @init
+ */
+void _stats_init(void) {
+
+ ch.kernel_stats.n_irq = 0;
+ ch.kernel_stats.n_ctxswc = 0;
+ chTMObjectInit(&ch.kernel_stats.m_crit_thd);
+ chTMObjectInit(&ch.kernel_stats.m_crit_isr);
+}
+
+/**
+ * @brief Increases the IRQ counter.
+ */
+void _stats_increase_irq(void) {
+
+ ch.kernel_stats.n_irq++;
+}
+
+/**
+ * @brief Updates context switch related statistics.
+ */
+void _stats_ctxswc(thread_t *ntp, thread_t *otp) {
+
+ ch.kernel_stats.n_ctxswc++;
+ chTMChainMeasurementToX(&otp->p_stats, &ntp->p_stats);
+}
+
+/**
+ * @brief Starts the measurement of a thread critical zone.
+ */
+void _stats_start_measure_crit_thd(void) {
+
+ chTMStartMeasurementX(&ch.kernel_stats.m_crit_thd);
+}
+
+/**
+ * @brief Stops the measurement of a thread critical zone.
+ */
+void _stats_stop_measure_crit_thd(void) {
+
+ chTMStopMeasurementX(&ch.kernel_stats.m_crit_thd);
+}
+
+/**
+ * @brief Starts the measurement of an ISR critical zone.
+ */
+void _stats_start_measure_crit_isr(void) {
+
+ chTMStartMeasurementX(&ch.kernel_stats.m_crit_isr);
+}
+
+/**
+ * @brief Stops the measurement of an ISR critical zone.
+ */
+void _stats_stop_measure_crit_isr(void) {
+
+ chTMStopMeasurementX(&ch.kernel_stats.m_crit_isr);
+}
+
+#endif /* CH_DBG_STATISTICS */
+
+/** @} */
diff --git a/os/rt/src/chsys.c b/os/rt/src/chsys.c new file mode 100644 index 000000000..f7fd6766b --- /dev/null +++ b/os/rt/src/chsys.c @@ -0,0 +1,303 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chsys.c
+ * @brief System related code.
+ *
+ * @addtogroup system
+ * @details System related APIs and services:
+ * - Initialization.
+ * - Locks.
+ * - Interrupt Handling.
+ * - Power Management.
+ * - Abnormal Termination.
+ * - Realtime counter.
+ * .
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+#if !CH_CFG_NO_IDLE_THREAD || defined(__DOXYGEN__)
+/**
+ * @brief Idle thread working area.
+ */
+static THD_WORKING_AREA(_idle_thread_wa, PORT_IDLE_THREAD_STACK_SIZE);
+#endif /* CH_CFG_NO_IDLE_THREAD */
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+#if !CH_CFG_NO_IDLE_THREAD || defined(__DOXYGEN__)
+/**
+ * @brief This function implements the idle thread infinite loop.
+ * @details The function puts the processor in the lowest power mode capable
+ * to serve interrupts.<br>
+ * The priority is internally set to the minimum system value so
+ * that this thread is executed only if there are no other ready
+ * threads in the system.
+ *
+ * @param[in] p the thread parameter, unused in this scenario
+ */
+static void _idle_thread(void *p) {
+
+ (void)p;
+ chRegSetThreadName("idle");
+ while (true) {
+ port_wait_for_interrupt();
+ CH_CFG_IDLE_LOOP_HOOK();
+ }
+}
+#endif /* CH_CFG_NO_IDLE_THREAD */
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief ChibiOS/RT initialization.
+ * @details After executing this function the current instructions stream
+ * becomes the main thread.
+ * @pre Interrupts must be still disabled when @p chSysInit() is invoked
+ * and are internally enabled.
+ * @post The main thread is created with priority @p NORMALPRIO.
+ * @note This function has special, architecture-dependent, requirements,
+ * see the notes into the various port reference manuals.
+ *
+ * @special
+ */
+void chSysInit(void) {
+ static thread_t mainthread;
+#if CH_DBG_ENABLE_STACK_CHECK
+ extern stkalign_t __main_thread_stack_base__;
+#endif
+
+ port_init();
+ _scheduler_init();
+ _vt_init();
+#if CH_CFG_USE_TM
+ _tm_init();
+#endif
+#if CH_CFG_USE_MEMCORE
+ _core_init();
+#endif
+#if CH_CFG_USE_HEAP
+ _heap_init();
+#endif
+#if CH_DBG_STATISTICS
+ _stats_init();
+#endif
+#if CH_DBG_ENABLE_TRACE
+ _trace_init();
+#endif
+
+#if !CH_CFG_NO_IDLE_THREAD
+ /* Now this instructions flow becomes the main thread.*/
+ setcurrp(_thread_init(&mainthread, NORMALPRIO));
+#else
+ /* Now this instructions flow becomes the main thread.*/
+ setcurrp(_thread_init(&mainthread, IDLEPRIO));
+#endif
+
+ currp->p_state = CH_STATE_CURRENT;
+#if CH_DBG_ENABLE_STACK_CHECK
+ /* This is a special case because the main thread thread_t structure is not
+ adjacent to its stack area.*/
+ currp->p_stklimit = &__main_thread_stack_base__;
+#endif
+ chSysEnable();
+
+ /* Note, &ch_debug points to the string "main" if the registry is
+ active, else the parameter is ignored.*/
+ chRegSetThreadName((const char *)&ch_debug);
+
+#if !CH_CFG_NO_IDLE_THREAD
+ /* This thread has the lowest priority in the system, its role is just to
+ serve interrupts in its context while keeping the lowest energy saving
+ mode compatible with the system status.*/
+ chThdCreateStatic(_idle_thread_wa, sizeof(_idle_thread_wa), IDLEPRIO,
+ (tfunc_t)_idle_thread, NULL);
+#endif
+}
+
+/**
+ * @brief Halts the system.
+ * @details This function is invoked by the operating system when an
+ * unrecoverable error is detected, for example because a programming
+ * error in the application code that triggers an assertion while
+ * in debug mode.
+ * @note Can be invoked from any system state.
+ *
+ * @special
+ */
+void chSysHalt(const char *reason) {
+
+ port_disable();
+
+#if CH_DBG_ENABLED
+ ch.dbg_panic_msg = reason;
+#else
+ (void)reason;
+#endif
+
+#if defined(CH_CFG_SYSTEM_HALT_HOOK) || defined(__DOXYGEN__)
+ CH_CFG_SYSTEM_HALT_HOOK(reason);
+#endif
+
+ /* Harmless infinite loop.*/
+ while (true)
+ ;
+}
+
+/**
+ * @brief Handles time ticks for round robin preemption and timer increments.
+ * @details Decrements the remaining time quantum of the running thread
+ * and preempts it when the quantum is used up. Increments system
+ * time and manages the timers.
+ * @note The frequency of the timer determines the system tick granularity
+ * and, together with the @p CH_CFG_TIME_QUANTUM macro, the round robin
+ * interval.
+ *
+ * @iclass
+ */
+void chSysTimerHandlerI(void) {
+
+ chDbgCheckClassI();
+
+#if CH_CFG_TIME_QUANTUM > 0
+ /* Running thread has not used up quantum yet? */
+ if (currp->p_preempt > 0)
+ /* Decrement remaining quantum.*/
+ currp->p_preempt--;
+#endif
+#if CH_DBG_THREADS_PROFILING
+ currp->p_time++;
+#endif
+ chVTDoTickI();
+#if defined(CH_CFG_SYSTEM_TICK_HOOK)
+ CH_CFG_SYSTEM_TICK_HOOK();
+#endif
+}
+
+/**
+ * @brief Returns the execution status and enters a critical zone.
+ * @details This functions enters into a critical zone and can be called
+ * from any context. Because its flexibility it is less efficient
+ * than @p chSysLock() which is preferable when the calling context
+ * is known.
+ * @post The system is in a critical zone.
+ *
+ * @return The previous system status, the encoding of this
+ * status word is architecture-dependent and opaque.
+ *
+ * @xclass
+ */
+syssts_t chSysGetStatusAndLockX(void) {
+
+ syssts_t sts = port_get_irq_status();
+ if (port_irq_enabled(sts)) {
+ if (port_is_isr_context())
+ chSysLockFromISR();
+ else
+ chSysLock();
+ }
+ return sts;
+}
+
+/**
+ * @brief Restores the specified execution status and leaves a critical zone.
+ * @note A call to @p chSchRescheduleS() is automatically performed
+ * if exiting the critical zone and if not in ISR context.
+ *
+ * @param[in] sts the system status to be restored.
+ *
+ * @xclass
+ */
+void chSysRestoreStatusX(syssts_t sts) {
+
+ if (port_irq_enabled(sts)) {
+ if (port_is_isr_context())
+ chSysUnlockFromISR();
+ else {
+ chSchRescheduleS();
+ chSysUnlock();
+ }
+ }
+}
+
+#if PORT_SUPPORTS_RT || defined(__DOXYGEN__)
+/**
+ * @brief Realtime window test.
+ * @details This function verifies if the current realtime counter value
+ * lies within the specified range or not. The test takes care
+ * of the realtime counter wrapping to zero on overflow.
+ * @note When start==end then the function returns always true because the
+ * whole time range is specified.
+ * @note This function is only available if the port layer supports the
+ * option @p PORT_SUPPORTS_RT.
+ *
+ * @param[in] cnt the counter value to be tested
+ * @param[in] start the start of the time window (inclusive)
+ * @param[in] end the end of the time window (non inclusive)
+ * @retval true current time within the specified time window.
+ * @retval false current time not within the specified time window.
+ *
+ * @xclass
+ */
+bool chSysIsCounterWithinX(rtcnt_t cnt, rtcnt_t start, rtcnt_t end) {
+
+ return end > start ? (cnt >= start) && (cnt < end) :
+ (cnt >= start) || (cnt < end);
+}
+
+/**
+ * @brief Polled delay.
+ * @note The real delay is always few cycles in excess of the specified
+ * value.
+ * @note This function is only available if the port layer supports the
+ * option @p PORT_SUPPORTS_RT.
+ *
+ * @param[in] cycles number of cycles
+ *
+ * @xclass
+ */
+void chSysPolledDelayX(rtcnt_t cycles) {
+ rtcnt_t start = chSysGetRealtimeCounterX();
+ rtcnt_t end = start + cycles;
+ while (chSysIsCounterWithinX(chSysGetRealtimeCounterX(), start, end))
+ ;
+}
+#endif /* PORT_SUPPORTS_RT */
+
+/** @} */
diff --git a/os/rt/src/chthreads.c b/os/rt/src/chthreads.c new file mode 100644 index 000000000..c10ccb70c --- /dev/null +++ b/os/rt/src/chthreads.c @@ -0,0 +1,645 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chthreads.c
+ * @brief Threads code.
+ *
+ * @addtogroup threads
+ * @details Threads related APIs and services.
+ *
+ * <h2>Operation mode</h2>
+ * A thread is an abstraction of an independent instructions flow.
+ * In ChibiOS/RT a thread is represented by a "C" function owning
+ * a processor context, state informations and a dedicated stack
+ * area. In this scenario static variables are shared among all
+ * threads while automatic variables are local to the thread.<br>
+ * Operations defined for threads:
+ * - <b>Create</b>, a thread is started on the specified thread
+ * function. This operation is available in multiple variants,
+ * both static and dynamic.
+ * - <b>Exit</b>, a thread terminates by returning from its top
+ * level function or invoking a specific API, the thread can
+ * return a value that can be retrieved by other threads.
+ * - <b>Wait</b>, a thread waits for the termination of another
+ * thread and retrieves its return value.
+ * - <b>Resume</b>, a thread created in suspended state is started.
+ * - <b>Sleep</b>, the execution of a thread is suspended for the
+ * specified amount of time or the specified future absolute time
+ * is reached.
+ * - <b>SetPriority</b>, a thread changes its own priority level.
+ * - <b>Yield</b>, a thread voluntarily renounces to its time slot.
+ * .
+ * The threads subsystem is implicitly included in kernel however
+ * some of its part may be excluded by disabling them in @p chconf.h,
+ * see the @p CH_CFG_USE_WAITEXIT and @p CH_CFG_USE_DYNAMIC configuration
+ * options.
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes a thread structure.
+ * @note This is an internal functions, do not use it in application code.
+ *
+ * @param[in] tp pointer to the thread
+ * @param[in] prio the priority level for the new thread
+ * @return The same thread pointer passed as parameter.
+ *
+ * @notapi
+ */
+thread_t *_thread_init(thread_t *tp, tprio_t prio) {
+
+ tp->p_prio = prio;
+ tp->p_state = CH_STATE_WTSTART;
+ tp->p_flags = CH_FLAG_MODE_STATIC;
+#if CH_CFG_TIME_QUANTUM > 0
+ tp->p_preempt = CH_CFG_TIME_QUANTUM;
+#endif
+#if CH_CFG_USE_MUTEXES
+ tp->p_realprio = prio;
+ tp->p_mtxlist = NULL;
+#endif
+#if CH_CFG_USE_EVENTS
+ tp->p_epending = 0;
+#endif
+#if CH_DBG_THREADS_PROFILING
+ tp->p_time = 0;
+#endif
+#if CH_CFG_USE_DYNAMIC
+ tp->p_refs = 1;
+#endif
+#if CH_CFG_USE_REGISTRY
+ tp->p_name = NULL;
+ REG_INSERT(tp);
+#endif
+#if CH_CFG_USE_WAITEXIT
+ list_init(&tp->p_waiting);
+#endif
+#if CH_CFG_USE_MESSAGES
+ queue_init(&tp->p_msgqueue);
+#endif
+#if CH_DBG_ENABLE_STACK_CHECK
+ tp->p_stklimit = (stkalign_t *)(tp + 1);
+#endif
+#if CH_DBG_STATISTICS || defined(__DOXYGEN__)
+ chTMObjectInit(&tp->p_stats);
+ chTMStartMeasurementX(&tp->p_stats);
+#endif
+#if defined(CH_CFG_THREAD_INIT_HOOK)
+ CH_CFG_THREAD_INIT_HOOK(tp);
+#endif
+ return tp;
+}
+
+#if CH_DBG_FILL_THREADS || defined(__DOXYGEN__)
+/**
+ * @brief Memory fill utility.
+ *
+ * @param[in] startp first address to fill
+ * @param[in] endp last address to fill +1
+ * @param[in] v filler value
+ *
+ * @notapi
+ */
+void _thread_memfill(uint8_t *startp, uint8_t *endp, uint8_t v) {
+
+ while (startp < endp)
+ *startp++ = v;
+}
+#endif /* CH_DBG_FILL_THREADS */
+
+/**
+ * @brief Creates a new thread into a static memory area.
+ * @details The new thread is initialized but not inserted in the ready list,
+ * the initial state is @p CH_STATE_WTSTART.
+ * @post The initialized thread can be subsequently started by invoking
+ * @p chThdStart(), @p chThdStartI() or @p chSchWakeupS()
+ * depending on the execution context.
+ * @note A thread can terminate by calling @p chThdExit() or by simply
+ * returning from its main function.
+ * @note Threads created using this function do not obey to the
+ * @p CH_DBG_FILL_THREADS debug option because it would keep
+ * the kernel locked for too much time.
+ *
+ * @param[out] wsp pointer to a working area dedicated to the thread stack
+ * @param[in] size size of the working area
+ * @param[in] prio the priority level for the new thread
+ * @param[in] pf the thread function
+ * @param[in] arg an argument passed to the thread function. It can be
+ * @p NULL.
+ * @return The pointer to the @p thread_t structure allocated for
+ * the thread into the working space area.
+ *
+ * @iclass
+ */
+thread_t *chThdCreateI(void *wsp, size_t size,
+ tprio_t prio, tfunc_t pf, void *arg) {
+ /* The thread structure is laid out in the lower part of the thread
+ workspace.*/
+ thread_t *tp = wsp;
+
+ chDbgCheckClassI();
+ chDbgCheck((wsp != NULL) && (size >= THD_WORKING_AREA_SIZE(0)) &&
+ (prio <= HIGHPRIO) && (pf != NULL));
+
+ PORT_SETUP_CONTEXT(tp, wsp, size, pf, arg);
+ return _thread_init(tp, prio);
+}
+
+/**
+ * @brief Creates a new thread into a static memory area.
+ * @note A thread can terminate by calling @p chThdExit() or by simply
+ * returning from its main function.
+ *
+ * @param[out] wsp pointer to a working area dedicated to the thread stack
+ * @param[in] size size of the working area
+ * @param[in] prio the priority level for the new thread
+ * @param[in] pf the thread function
+ * @param[in] arg an argument passed to the thread function. It can be
+ * @p NULL.
+ * @return The pointer to the @p thread_t structure allocated for
+ * the thread into the working space area.
+ *
+ * @api
+ */
+thread_t *chThdCreateStatic(void *wsp, size_t size,
+ tprio_t prio, tfunc_t pf, void *arg) {
+ thread_t *tp;
+
+#if CH_DBG_FILL_THREADS
+ _thread_memfill((uint8_t *)wsp,
+ (uint8_t *)wsp + sizeof(thread_t),
+ CH_DBG_THREAD_FILL_VALUE);
+ _thread_memfill((uint8_t *)wsp + sizeof(thread_t),
+ (uint8_t *)wsp + size,
+ CH_DBG_STACK_FILL_VALUE);
+#endif
+ chSysLock();
+ chSchWakeupS(tp = chThdCreateI(wsp, size, prio, pf, arg), MSG_OK);
+ chSysUnlock();
+ return tp;
+}
+
+/**
+ * @brief Resumes a thread created with @p chThdCreateI().
+ *
+ * @param[in] tp pointer to the thread
+ *
+ * @api
+ */
+thread_t *chThdStart(thread_t *tp) {
+
+ chSysLock();
+ tp = chThdStartI(tp);
+ chSysUnlock();
+ return tp;
+}
+
+/**
+ * @brief Changes the running thread priority level then reschedules if
+ * necessary.
+ * @note The function returns the real thread priority regardless of the
+ * current priority that could be higher than the real priority
+ * because the priority inheritance mechanism.
+ *
+ * @param[in] newprio the new priority level of the running thread
+ * @return The old priority level.
+ *
+ * @api
+ */
+tprio_t chThdSetPriority(tprio_t newprio) {
+ tprio_t oldprio;
+
+ chDbgCheck(newprio <= HIGHPRIO);
+
+ chSysLock();
+#if CH_CFG_USE_MUTEXES
+ oldprio = currp->p_realprio;
+ if ((currp->p_prio == currp->p_realprio) || (newprio > currp->p_prio))
+ currp->p_prio = newprio;
+ currp->p_realprio = newprio;
+#else
+ oldprio = currp->p_prio;
+ currp->p_prio = newprio;
+#endif
+ chSchRescheduleS();
+ chSysUnlock();
+ return oldprio;
+}
+
+/**
+ * @brief Requests a thread termination.
+ * @pre The target thread must be written to invoke periodically
+ * @p chThdShouldTerminate() and terminate cleanly if it returns
+ * @p true.
+ * @post The specified thread will terminate after detecting the termination
+ * condition.
+ *
+ * @param[in] tp pointer to the thread
+ *
+ * @api
+ */
+void chThdTerminate(thread_t *tp) {
+
+ chSysLock();
+ tp->p_flags |= CH_FLAG_TERMINATE;
+ chSysUnlock();
+}
+
+/**
+ * @brief Suspends the invoking thread for the specified time.
+ *
+ * @param[in] time the delay in system ticks, the special values are
+ * handled as follow:
+ * - @a TIME_INFINITE the thread enters an infinite sleep
+ * state.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ *
+ * @api
+ */
+void chThdSleep(systime_t time) {
+
+ chSysLock();
+ chThdSleepS(time);
+ chSysUnlock();
+}
+
+/**
+ * @brief Suspends the invoking thread until the system time arrives to the
+ * specified value.
+ *
+ * @param[in] time absolute system time
+ *
+ * @api
+ */
+void chThdSleepUntil(systime_t time) {
+
+ chSysLock();
+ if ((time -= chVTGetSystemTimeX()) > 0)
+ chThdSleepS(time);
+ chSysUnlock();
+}
+
+/**
+ * @brief Yields the time slot.
+ * @details Yields the CPU control to the next thread in the ready list with
+ * equal priority, if any.
+ *
+ * @api
+ */
+void chThdYield(void) {
+
+ chSysLock();
+ chSchDoYieldS();
+ chSysUnlock();
+}
+
+/**
+ * @brief Terminates the current thread.
+ * @details The thread goes in the @p CH_STATE_FINAL state holding the
+ * specified exit status code, other threads can retrieve the
+ * exit status code by invoking the function @p chThdWait().
+ * @post Eventual code after this function will never be executed,
+ * this function never returns. The compiler has no way to
+ * know this so do not assume that the compiler would remove
+ * the dead code.
+ *
+ * @param[in] msg thread exit code
+ *
+ * @api
+ */
+void chThdExit(msg_t msg) {
+
+ chSysLock();
+ chThdExitS(msg);
+ /* The thread never returns here.*/
+}
+
+/**
+ * @brief Terminates the current thread.
+ * @details The thread goes in the @p CH_STATE_FINAL state holding the
+ * specified exit status code, other threads can retrieve the
+ * exit status code by invoking the function @p chThdWait().
+ * @post Eventual code after this function will never be executed,
+ * this function never returns. The compiler has no way to
+ * know this so do not assume that the compiler would remove
+ * the dead code.
+ *
+ * @param[in] msg thread exit code
+ *
+ * @sclass
+ */
+void chThdExitS(msg_t msg) {
+ thread_t *tp = currp;
+
+ tp->p_u.exitcode = msg;
+#if defined(CH_CFG_THREAD_EXIT_HOOK)
+ CH_CFG_THREAD_EXIT_HOOK(tp);
+#endif
+#if CH_CFG_USE_WAITEXIT
+ while (list_notempty(&tp->p_waiting))
+ chSchReadyI(list_remove(&tp->p_waiting));
+#endif
+#if CH_CFG_USE_REGISTRY
+ /* Static threads are immediately removed from the registry because
+ there is no memory to recover.*/
+ if ((tp->p_flags & CH_FLAG_MODE_MASK) == CH_FLAG_MODE_STATIC)
+ REG_REMOVE(tp);
+#endif
+ chSchGoSleepS(CH_STATE_FINAL);
+ /* The thread never returns here.*/
+ chDbgAssert(false, "zombies apocalypse");
+}
+
+#if CH_CFG_USE_WAITEXIT || defined(__DOXYGEN__)
+/**
+ * @brief Blocks the execution of the invoking thread until the specified
+ * thread terminates then the exit code is returned.
+ * @details This function waits for the specified thread to terminate then
+ * decrements its reference counter, if the counter reaches zero then
+ * the thread working area is returned to the proper allocator.<br>
+ * The memory used by the exited thread is handled in different ways
+ * depending on the API that spawned the thread:
+ * - If the thread was spawned by @p chThdCreateStatic() or by
+ * @p chThdCreateI() then nothing happens and the thread working
+ * area is not released or modified in any way. This is the
+ * default, totally static, behavior.
+ * - If the thread was spawned by @p chThdCreateFromHeap() then
+ * the working area is returned to the system heap.
+ * - If the thread was spawned by @p chThdCreateFromMemoryPool()
+ * then the working area is returned to the owning memory pool.
+ * .
+ * @pre The configuration option @p CH_CFG_USE_WAITEXIT must be enabled in
+ * order to use this function.
+ * @post Enabling @p chThdWait() requires 2-4 (depending on the
+ * architecture) extra bytes in the @p thread_t structure.
+ * @post After invoking @p chThdWait() the thread pointer becomes invalid
+ * and must not be used as parameter for further system calls.
+ * @note If @p CH_CFG_USE_DYNAMIC is not specified this function just waits for
+ * the thread termination, no memory allocators are involved.
+ *
+ * @param[in] tp pointer to the thread
+ * @return The exit code from the terminated thread.
+ *
+ * @api
+ */
+msg_t chThdWait(thread_t *tp) {
+ msg_t msg;
+
+ chDbgCheck(tp != NULL);
+
+ chSysLock();
+ chDbgAssert(tp != currp, "waiting self");
+#if CH_CFG_USE_DYNAMIC
+ chDbgAssert(tp->p_refs > 0, "not referenced");
+#endif
+ if (tp->p_state != CH_STATE_FINAL) {
+ list_insert(currp, &tp->p_waiting);
+ chSchGoSleepS(CH_STATE_WTEXIT);
+ }
+ msg = tp->p_u.exitcode;
+ chSysUnlock();
+#if CH_CFG_USE_DYNAMIC
+ chThdRelease(tp);
+#endif
+ return msg;
+}
+#endif /* CH_CFG_USE_WAITEXIT */
+
+/**
+ * @brief Sends the current thread sleeping and sets a reference variable.
+ * @note This function must reschedule, it can only be called from thread
+ * context.
+ *
+ * @param[in] trp a pointer to a thread reference object
+ * @return The wake up message.
+ *
+ * @sclass
+ */
+msg_t chThdSuspendS(thread_reference_t *trp) {
+ thread_t *tp = chThdGetSelfX();
+
+ chDbgAssert(*trp == NULL, "not NULL");
+
+ *trp = tp;
+ tp->p_u.wtobjp = &trp;
+ chSchGoSleepS(CH_STATE_SUSPENDED);
+ return chThdGetSelfX()->p_msg;
+}
+
+/**
+ * @brief Sends the current thread sleeping and sets a reference variable.
+ * @note This function must reschedule, it can only be called from thread
+ * context.
+ *
+ * @param[in] trp a pointer to a thread reference object
+ * @param[in] timeout the timeout in system ticks, the special values are
+ * handled as follow:
+ * - @a TIME_INFINITE the thread enters an infinite sleep
+ * state.
+ * - @a TIME_IMMEDIATE the thread is not enqueued and
+ * the function returns @p MSG_TIMEOUT as if a timeout
+ * occurred.
+ * .
+ * @return The wake up message.
+ * @retval MSG_TIMEOUT if the operation timed out.
+ *
+ * @sclass
+ */
+msg_t chThdSuspendTimeoutS(thread_reference_t *trp, systime_t timeout) {
+ thread_t *tp = chThdGetSelfX();
+
+ chDbgAssert(*trp == NULL, "not NULL");
+
+ if (TIME_IMMEDIATE == timeout)
+ return MSG_TIMEOUT;
+
+ *trp = tp;
+ tp->p_u.wtobjp = &trp;
+ return chSchGoSleepTimeoutS(CH_STATE_SUSPENDED, timeout);
+}
+
+/**
+ * @brief Wakes up a thread waiting on a thread reference object.
+ * @note This function must not reschedule because it can be called from
+ * ISR context.
+ *
+ * @param[in] trp a pointer to a thread reference object
+ * @param[in] msg the message code
+ *
+ * @iclass
+ */
+void chThdResumeI(thread_reference_t *trp, msg_t msg) {
+
+ if (*trp != NULL) {
+ thread_t *tp = *trp;
+
+ chDbgAssert(tp->p_state == CH_STATE_SUSPENDED,
+ "not THD_STATE_SUSPENDED");
+
+ *trp = NULL;
+ tp->p_u.rdymsg = msg;
+ chSchReadyI(tp);
+ }
+}
+
+/**
+ * @brief Wakes up a thread waiting on a thread reference object.
+ * @note This function must reschedule, it can only be called from thread
+ * context.
+ *
+ * @param[in] trp a pointer to a thread reference object
+ * @param[in] msg the message code
+ *
+ * @iclass
+ */
+void chThdResumeS(thread_reference_t *trp, msg_t msg) {
+
+ if (*trp != NULL) {
+ thread_t *tp = *trp;
+
+ chDbgAssert(tp->p_state == CH_STATE_SUSPENDED,
+ "not THD_STATE_SUSPENDED");
+
+ *trp = NULL;
+ chSchWakeupS(tp, msg);
+ }
+}
+
+/**
+ * @brief Wakes up a thread waiting on a thread reference object.
+ * @note This function must reschedule, it can only be called from thread
+ * context.
+ *
+ * @param[in] trp a pointer to a thread reference object
+ * @param[in] msg the message code
+ *
+ * @api
+ */
+void chThdResume(thread_reference_t *trp, msg_t msg) {
+
+ chSysLock();
+ chThdResumeS(trp, msg);
+ chSysUnlock();
+}
+
+/**
+ * @brief Enqueues the caller thread on a threads queue object.
+ * @details The caller thread is enqueued and put to sleep until it is
+ * dequeued or the specified timeouts expires.
+ *
+ * @param[in] tqp pointer to the threads queue object
+ * @param[in] timeout the timeout in system ticks, the special values are
+ * handled as follow:
+ * - @a TIME_INFINITE the thread enters an infinite sleep
+ * state.
+ * - @a TIME_IMMEDIATE the thread is not enqueued and
+ * the function returns @p MSG_TIMEOUT as if a timeout
+ * occurred.
+ * .
+ * @return The message from @p osalQueueWakeupOneI() or
+ * @p osalQueueWakeupAllI() functions.
+ * @retval MSG_TIMEOUT if the thread has not been dequeued within the
+ * specified timeout or if the function has been
+ * invoked with @p TIME_IMMEDIATE as timeout
+ * specification.
+ *
+ * @sclass
+ */
+msg_t chThdEnqueueTimeoutS(threads_queue_t *tqp, systime_t timeout) {
+
+ if (TIME_IMMEDIATE == timeout)
+ return MSG_TIMEOUT;
+
+ queue_insert(currp, tqp);
+ return chSchGoSleepTimeoutS(CH_STATE_QUEUED, timeout);
+}
+
+/**
+ * @brief Dequeues and wakes up one thread from the threads queue object,
+ * if any.
+ *
+ * @param[in] tqp pointer to the threads queue object
+ * @param[in] msg the message code
+ *
+ * @iclass
+ */
+void chThdDequeueNextI(threads_queue_t *tqp, msg_t msg) {
+
+ if (queue_notempty(tqp)) {
+ thread_t *tp = queue_fifo_remove(tqp);
+
+ chDbgAssert(tp->p_state == CH_STATE_QUEUED,
+ "not CH_STATE_QUEUED");
+
+ tp->p_u.rdymsg = msg;
+ chSchReadyI(tp);
+ }
+}
+
+/**
+ * @brief Dequeues and wakes up all threads from the threads queue object.
+ *
+ * @param[in] tqp pointer to the threads queue object
+ * @param[in] msg the message code
+ *
+ * @iclass
+ */
+void chThdDequeueAllI(threads_queue_t *tqp, msg_t msg) {
+
+ while (queue_notempty(tqp)) {
+ thread_t *tp = queue_fifo_remove(tqp);
+
+ chDbgAssert(tp->p_state == CH_STATE_QUEUED,
+ "not CH_STATE_QUEUED");
+
+ tp->p_u.rdymsg = msg;
+ chSchReadyI(tp);
+ }
+}
+
+/** @} */
diff --git a/os/rt/src/chtm.c b/os/rt/src/chtm.c new file mode 100644 index 000000000..c001dd7e3 --- /dev/null +++ b/os/rt/src/chtm.c @@ -0,0 +1,155 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chtm.c
+ * @brief Time Measurement module code.
+ *
+ * @addtogroup time_measurement
+ * @details Time Measurement APIs and services.
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_TM || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+static inline void tm_stop(time_measurement_t *tmp,
+ rtcnt_t now,
+ rtcnt_t offset) {
+
+ tmp->n++;
+ tmp->last = now - tmp->last - offset;
+ tmp->cumulative += (rttime_t)tmp->last;
+ if (tmp->last > tmp->worst)
+ tmp->worst = tmp->last;
+ else if (tmp->last < tmp->best)
+ tmp->best = tmp->last;
+}
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Initializes the time measurement unit.
+ *
+ * @init
+ */
+void _tm_init(void) {
+ time_measurement_t tm;
+
+ /* Time Measurement subsystem calibration, it does a null measurement
+ and calculates the call overhead which is subtracted to real
+ measurements.*/
+ ch.measurement_offset = 0;
+ chTMObjectInit(&tm);
+ chTMStartMeasurementX(&tm);
+ chTMStopMeasurementX(&tm);
+ ch.measurement_offset = tm.last;
+}
+
+/**
+ * @brief Initializes a @p TimeMeasurement object.
+ *
+ * @param[out] tmp pointer to a @p TimeMeasurement structure
+ *
+ * @init
+ */
+void chTMObjectInit(time_measurement_t *tmp) {
+
+ tmp->best = (rtcnt_t)-1;
+ tmp->worst = (rtcnt_t)0;
+ tmp->last = (rtcnt_t)0;
+ tmp->n = (ucnt_t)0;
+ tmp->cumulative = (rttime_t)0;
+}
+
+/**
+ * @brief Starts a measurement.
+ * @pre The @p time_measurement_t structure must be initialized.
+ *
+ * @param[in,out] tmp pointer to a @p TimeMeasurement structure
+ *
+ * @xclass
+ */
+NOINLINE void chTMStartMeasurementX(time_measurement_t *tmp) {
+
+ tmp->last = chSysGetRealtimeCounterX();
+}
+
+/**
+ * @brief Stops a measurement.
+ * @pre The @p time_measurement_t structure must be initialized.
+ *
+ * @param[in,out] tmp pointer to a @p time_measurement_t structure
+ *
+ * @xclass
+ */
+NOINLINE void chTMStopMeasurementX(time_measurement_t *tmp) {
+
+ tm_stop(tmp, chSysGetRealtimeCounterX(), ch.measurement_offset);
+}
+
+/**
+ * @brief Stops a measurement and chains to the next one using the same time
+ * stamp.
+ *
+ * @param[in,out] tmp1 pointer to the @p time_measurement_t structure to be
+ * stopped
+ * @param[in,out] tmp2 pointer to the @p time_measurement_t structure to be
+ * started
+ *
+ *
+ * @xclass
+ */
+NOINLINE void chTMChainMeasurementToX(time_measurement_t *tmp1,
+ time_measurement_t *tmp2) {
+
+ /* Starts new measurement.*/
+ tmp2->last = chSysGetRealtimeCounterX();
+
+ /* Stops previous measurement using the same time stamp.*/
+ tm_stop(tmp1, tmp2->last, 0);
+}
+
+#endif /* CH_CFG_USE_TM */
+
+/** @} */
diff --git a/os/rt/src/chvt.c b/os/rt/src/chvt.c new file mode 100644 index 000000000..d20e20d91 --- /dev/null +++ b/os/rt/src/chvt.c @@ -0,0 +1,191 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chvt.c
+ * @brief Time and Virtual Timers module code.
+ *
+ * @addtogroup time
+ * @details Time and Virtual Timers related APIs and services.
+ * @{
+ */
+
+#include "ch.h"
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief Virtual Timers initialization.
+ * @note Internal use only.
+ *
+ * @notapi
+ */
+void _vt_init(void) {
+
+ ch.vtlist.vt_next = ch.vtlist.vt_prev = (void *)&ch.vtlist;
+ ch.vtlist.vt_delta = (systime_t)-1;
+#if CH_CFG_ST_TIMEDELTA == 0
+ ch.vtlist.vt_systime = 0;
+#else /* CH_CFG_ST_TIMEDELTA > 0 */
+ ch.vtlist.vt_lasttime = 0;
+#endif /* CH_CFG_ST_TIMEDELTA > 0 */
+}
+
+/**
+ * @brief Enables a virtual timer.
+ * @details The timer is enabled and programmed to trigger after the delay
+ * specified as parameter.
+ * @pre The timer must not be already armed before calling this function.
+ * @note The callback function is invoked from interrupt context.
+ *
+ * @param[out] vtp the @p virtual_timer_t structure pointer
+ * @param[in] delay the number of ticks before the operation timeouts, the
+ * special values are handled as follow:
+ * - @a TIME_INFINITE is allowed but interpreted as a
+ * normal time specification.
+ * - @a TIME_IMMEDIATE this value is not allowed.
+ * .
+ * @param[in] vtfunc the timer callback function. After invoking the
+ * callback the timer is disabled and the structure can
+ * be disposed or reused.
+ * @param[in] par a parameter that will be passed to the callback
+ * function
+ *
+ * @iclass
+ */
+void chVTDoSetI(virtual_timer_t *vtp, systime_t delay,
+ vtfunc_t vtfunc, void *par) {
+ virtual_timer_t *p;
+
+ chDbgCheckClassI();
+ chDbgCheck((vtp != NULL) && (vtfunc != NULL) && (delay != TIME_IMMEDIATE));
+
+ vtp->vt_par = par;
+ vtp->vt_func = vtfunc;
+ p = ch.vtlist.vt_next;
+
+#if CH_CFG_ST_TIMEDELTA > 0 || defined(__DOXYGEN__)
+ {
+ systime_t now = port_timer_get_time();
+
+ /* If the requested delay is lower than the minimum safe delta then it
+ is raised to the minimum safe value.*/
+ if (delay < CH_CFG_ST_TIMEDELTA)
+ delay = CH_CFG_ST_TIMEDELTA;
+
+ if (&ch.vtlist == (virtual_timers_list_t *)p) {
+ /* The delta list is empty, the current time becomes the new
+ delta list base time.*/
+ ch.vtlist.vt_lasttime = now;
+ port_timer_start_alarm(ch.vtlist.vt_lasttime + delay);
+ }
+ else {
+ /* Now the delay is calculated as delta from the last tick interrupt
+ time.*/
+ delay += now - ch.vtlist.vt_lasttime;
+
+ /* If the specified delay is closer in time than the first element
+ in the delta list then it becomes the next alarm event in time.*/
+ if (delay < p->vt_delta)
+ port_timer_set_alarm(ch.vtlist.vt_lasttime + delay);
+ }
+ }
+#endif /* CH_CFG_ST_TIMEDELTA > 0 */
+
+ /* The delta list is scanned in order to find the correct position for
+ this timer. */
+ while (p->vt_delta < delay) {
+ delay -= p->vt_delta;
+ p = p->vt_next;
+ }
+
+ /* The timer is inserted in the delta list.*/
+ vtp->vt_prev = (vtp->vt_next = p)->vt_prev;
+ vtp->vt_prev->vt_next = p->vt_prev = vtp;
+ vtp->vt_delta = delay
+
+ /* Special case when the timer is in last position in the list, the
+ value in the header must be restored.*/;
+ p->vt_delta -= delay;
+ ch.vtlist.vt_delta = (systime_t)-1;
+}
+
+/**
+ * @brief Disables a Virtual Timer.
+ * @pre The timer must be in armed state before calling this function.
+ *
+ * @param[in] vtp the @p virtual_timer_t structure pointer
+ *
+ * @iclass
+ */
+void chVTDoResetI(virtual_timer_t *vtp) {
+
+ chDbgCheckClassI();
+ chDbgCheck(vtp != NULL);
+ chDbgAssert(vtp->vt_func != NULL, "timer not set or already triggered");
+
+ /* Removing the element from the delta list.*/
+ vtp->vt_next->vt_delta += vtp->vt_delta;
+ vtp->vt_prev->vt_next = vtp->vt_next;
+ vtp->vt_next->vt_prev = vtp->vt_prev;
+ vtp->vt_func = (vtfunc_t)NULL;
+
+ /* The above code changes the value in the header when the removed element
+ is the last of the list, restoring it.*/
+ ch.vtlist.vt_delta = (systime_t)-1;
+
+#if CH_CFG_ST_TIMEDELTA > 0 || defined(__DOXYGEN__)
+ {
+ if (&ch.vtlist == (virtual_timers_list_t *)ch.vtlist.vt_next) {
+ /* Just removed the last element in the list, alarm timer stopped.*/
+ port_timer_stop_alarm();
+ }
+ else {
+ /* The alarm is set to the next element in the delta list.*/
+ port_timer_set_alarm(ch.vtlist.vt_lasttime +
+ ch.vtlist.vt_next->vt_delta);
+ }
+ }
+#endif /* CH_CFG_ST_TIMEDELTA > 0 */
+}
+
+/** @} */
diff --git a/os/rt/templates/chconf.h b/os/rt/templates/chconf.h new file mode 100644 index 000000000..09b91db5c --- /dev/null +++ b/os/rt/templates/chconf.h @@ -0,0 +1,497 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+/**
+ * @file templates/chconf.h
+ * @brief Configuration file template.
+ * @details A copy of this file must be placed in each project directory, it
+ * contains the application specific kernel settings.
+ *
+ * @addtogroup config
+ * @details Kernel related settings and hooks.
+ * @{
+ */
+
+#ifndef _CHCONF_H_
+#define _CHCONF_H_
+
+/*===========================================================================*/
+/**
+ * @name System timers settings
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief System time counter resolution.
+ * @note Allowed values are 16 or 32 bits.
+ */
+#define CH_CFG_ST_RESOLUTION 32
+
+/**
+ * @brief System tick frequency.
+ * @details Frequency of the system timer that drives the system ticks. This
+ * setting also defines the system tick time unit.
+ */
+#define CH_CFG_ST_FREQUENCY 10000
+
+/**
+ * @brief Time delta constant for the tick-less mode.
+ * @note If this value is zero then the system uses the classic
+ * periodic tick. This value represents the minimum number
+ * of ticks that is safe to specify in a timeout directive.
+ * The value one is not valid, timeouts are rounded up to
+ * this value.
+ */
+#define CH_CFG_ST_TIMEDELTA 2
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Kernel parameters and options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief Round robin interval.
+ * @details This constant is the number of system ticks allowed for the
+ * threads before preemption occurs. Setting this value to zero
+ * disables the preemption for threads with equal priority and the
+ * round robin becomes cooperative. Note that higher priority
+ * threads can still preempt, the kernel is always preemptive.
+ * @note Disabling the round robin preemption makes the kernel more compact
+ * and generally faster.
+ * @note The round robin preemption is not supported in tickless mode and
+ * must be set to zero in that case.
+ */
+#define CH_CFG_TIME_QUANTUM 0
+
+/**
+ * @brief Managed RAM size.
+ * @details Size of the RAM area to be managed by the OS. If set to zero
+ * then the whole available RAM is used. The core memory is made
+ * available to the heap allocator and/or can be used directly through
+ * the simplified core memory allocator.
+ *
+ * @note In order to let the OS manage the whole RAM the linker script must
+ * provide the @p __heap_base__ and @p __heap_end__ symbols.
+ * @note Requires @p CH_CFG_USE_MEMCORE.
+ */
+#define CH_CFG_MEMCORE_SIZE 0
+
+/**
+ * @brief Idle thread automatic spawn suppression.
+ * @details When this option is activated the function @p chSysInit()
+ * does not spawn the idle thread. The application @p main()
+ * function becomes the idle thread and must implement an
+ * infinite loop. */
+#define CH_CFG_NO_IDLE_THREAD FALSE
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Performance options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief OS optimization.
+ * @details If enabled then time efficient rather than space efficient code
+ * is used when two possible implementations exist.
+ *
+ * @note This is not related to the compiler optimization options.
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_OPTIMIZE_SPEED TRUE
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Subsystem options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief Time Measurement APIs.
+ * @details If enabled then the time measurement APIs are included in
+ * the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_TM TRUE
+
+/**
+ * @brief Threads registry APIs.
+ * @details If enabled then the registry APIs are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_REGISTRY TRUE
+
+/**
+ * @brief Threads synchronization APIs.
+ * @details If enabled then the @p chThdWait() function is included in
+ * the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_WAITEXIT TRUE
+
+/**
+ * @brief Semaphores APIs.
+ * @details If enabled then the Semaphores APIs are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_SEMAPHORES TRUE
+
+/**
+ * @brief Semaphores queuing mode.
+ * @details If enabled then the threads are enqueued on semaphores by
+ * priority rather than in FIFO order.
+ *
+ * @note The default is @p FALSE. Enable this if you have special
+ * requirements.
+ * @note Requires @p CH_CFG_USE_SEMAPHORES.
+ */
+#define CH_CFG_USE_SEMAPHORES_PRIORITY FALSE
+
+/**
+ * @brief Mutexes APIs.
+ * @details If enabled then the mutexes APIs are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_MUTEXES TRUE
+
+/**
+ * @brief Enables recursive behavior on mutexes.
+ * @note Recursive mutexes are heavier and have an increased
+ * memory footprint.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_CFG_USE_MUTEXES_RECURSIVE FALSE
+
+/**
+ * @brief Conditional Variables APIs.
+ * @details If enabled then the conditional variables APIs are included
+ * in the kernel.
+ *
+ * @note The default is @p TRUE.
+ * @note Requires @p CH_CFG_USE_MUTEXES.
+ */
+#define CH_CFG_USE_CONDVARS TRUE
+
+/**
+ * @brief Conditional Variables APIs with timeout.
+ * @details If enabled then the conditional variables APIs with timeout
+ * specification are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ * @note Requires @p CH_CFG_USE_CONDVARS.
+ */
+#define CH_CFG_USE_CONDVARS_TIMEOUT TRUE
+
+/**
+ * @brief Events Flags APIs.
+ * @details If enabled then the event flags APIs are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_EVENTS TRUE
+
+/**
+ * @brief Events Flags APIs with timeout.
+ * @details If enabled then the events APIs with timeout specification
+ * are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ * @note Requires @p CH_CFG_USE_EVENTS.
+ */
+#define CH_CFG_USE_EVENTS_TIMEOUT TRUE
+
+/**
+ * @brief Synchronous Messages APIs.
+ * @details If enabled then the synchronous messages APIs are included
+ * in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_MESSAGES TRUE
+
+/**
+ * @brief Synchronous Messages queuing mode.
+ * @details If enabled then messages are served by priority rather than in
+ * FIFO order.
+ *
+ * @note The default is @p FALSE. Enable this if you have special
+ * requirements.
+ * @note Requires @p CH_CFG_USE_MESSAGES.
+ */
+#define CH_CFG_USE_MESSAGES_PRIORITY FALSE
+
+/**
+ * @brief Mailboxes APIs.
+ * @details If enabled then the asynchronous messages (mailboxes) APIs are
+ * included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ * @note Requires @p CH_CFG_USE_SEMAPHORES.
+ */
+#define CH_CFG_USE_MAILBOXES TRUE
+
+/**
+ * @brief I/O Queues APIs.
+ * @details If enabled then the I/O queues APIs are included in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_QUEUES TRUE
+
+/**
+ * @brief Core Memory Manager APIs.
+ * @details If enabled then the core memory manager APIs are included
+ * in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_MEMCORE TRUE
+
+/**
+ * @brief Heap Allocator APIs.
+ * @details If enabled then the memory heap allocator APIs are included
+ * in the kernel.
+ *
+ * @note The default is @p TRUE.
+ * @note Requires @p CH_CFG_USE_MEMCORE and either @p CH_CFG_USE_MUTEXES or
+ * @p CH_CFG_USE_SEMAPHORES.
+ * @note Mutexes are recommended.
+ */
+#define CH_CFG_USE_HEAP TRUE
+
+/**
+ * @brief Memory Pools Allocator APIs.
+ * @details If enabled then the memory pools allocator APIs are included
+ * in the kernel.
+ *
+ * @note The default is @p TRUE.
+ */
+#define CH_CFG_USE_MEMPOOLS TRUE
+
+/**
+ * @brief Dynamic Threads APIs.
+ * @details If enabled then the dynamic threads creation APIs are included
+ * in the kernel.
+ *
+ * @note The default is @p TRUE.
+ * @note Requires @p CH_CFG_USE_WAITEXIT.
+ * @note Requires @p CH_CFG_USE_HEAP and/or @p CH_CFG_USE_MEMPOOLS.
+ */
+#define CH_CFG_USE_DYNAMIC TRUE
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Debug options
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief Debug option, kernel statistics.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_DBG_STATISTICS FALSE
+
+/**
+ * @brief Debug option, system state check.
+ * @details If enabled the correct call protocol for system APIs is checked
+ * at runtime.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_DBG_SYSTEM_STATE_CHECK FALSE
+
+/**
+ * @brief Debug option, parameters checks.
+ * @details If enabled then the checks on the API functions input
+ * parameters are activated.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_DBG_ENABLE_CHECKS FALSE
+
+/**
+ * @brief Debug option, consistency checks.
+ * @details If enabled then all the assertions in the kernel code are
+ * activated. This includes consistency checks inside the kernel,
+ * runtime anomalies and port-defined checks.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_DBG_ENABLE_ASSERTS FALSE
+
+/**
+ * @brief Debug option, trace buffer.
+ * @details If enabled then the context switch circular trace buffer is
+ * activated.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_DBG_ENABLE_TRACE FALSE
+
+/**
+ * @brief Debug option, stack checks.
+ * @details If enabled then a runtime stack check is performed.
+ *
+ * @note The default is @p FALSE.
+ * @note The stack check is performed in a architecture/port dependent way.
+ * It may not be implemented or some ports.
+ * @note The default failure mode is to halt the system with the global
+ * @p panic_msg variable set to @p NULL.
+ */
+#define CH_DBG_ENABLE_STACK_CHECK FALSE
+
+/**
+ * @brief Debug option, stacks initialization.
+ * @details If enabled then the threads working area is filled with a byte
+ * value when a thread is created. This can be useful for the
+ * runtime measurement of the used stack.
+ *
+ * @note The default is @p FALSE.
+ */
+#define CH_DBG_FILL_THREADS FALSE
+
+/**
+ * @brief Debug option, threads profiling.
+ * @details If enabled then a field is added to the @p thread_t structure that
+ * counts the system ticks occurred while executing the thread.
+ *
+ * @note The default is @p FALSE.
+ * @note This debug option is not currently compatible with the
+ * tickless mode.
+ */
+#define CH_DBG_THREADS_PROFILING FALSE
+
+/** @} */
+
+/*===========================================================================*/
+/**
+ * @name Kernel hooks
+ * @{
+ */
+/*===========================================================================*/
+
+/**
+ * @brief Threads descriptor structure extension.
+ * @details User fields added to the end of the @p thread_t structure.
+ */
+#define CH_CFG_THREAD_EXTRA_FIELDS \
+ /* Add threads custom fields here.*/
+
+/**
+ * @brief Threads initialization hook.
+ * @details User initialization code added to the @p chThdInit() API.
+ *
+ * @note It is invoked from within @p chThdInit() and implicitly from all
+ * the threads creation APIs.
+ */
+#define CH_CFG_THREAD_INIT_HOOK(tp) { \
+ /* Add threads initialization code here.*/ \
+}
+
+/**
+ * @brief Threads finalization hook.
+ * @details User finalization code added to the @p chThdExit() API.
+ *
+ * @note It is inserted into lock zone.
+ * @note It is also invoked when the threads simply return in order to
+ * terminate.
+ */
+#define CH_CFG_THREAD_EXIT_HOOK(tp) { \
+ /* Add threads finalization code here.*/ \
+}
+
+/**
+ * @brief Context switch hook.
+ * @details This hook is invoked just before switching between threads.
+ */
+#define CH_CFG_CONTEXT_SWITCH_HOOK(ntp, otp) { \
+ /* System halt code here.*/ \
+}
+
+/**
+ * @brief Idle thread enter hook.
+ * @note This hook is invoked within a critical zone, no OS functions
+ * should be invoked from here.
+ * @note This macro can be used to activate a power saving mode.
+ */
+#define CH_CFG_IDLE_ENTER_HOOK() { \
+}
+
+/**
+ * @brief Idle thread leave hook.
+ * @note This hook is invoked within a critical zone, no OS functions
+ * should be invoked from here.
+ * @note This macro can be used to deactivate a power saving mode.
+ */
+#define CH_CFG_IDLE_LEAVE_HOOK() { \
+}
+
+/**
+ * @brief Idle Loop hook.
+ * @details This hook is continuously invoked by the idle thread loop.
+ */
+#define CH_CFG_IDLE_LOOP_HOOK() { \
+ /* Idle loop code here.*/ \
+}
+
+/**
+ * @brief System tick event hook.
+ * @details This hook is invoked in the system tick handler immediately
+ * after processing the virtual timers queue.
+ */
+#define CH_CFG_SYSTEM_TICK_HOOK() { \
+ /* System tick event code here.*/ \
+}
+
+/**
+ * @brief System halt hook.
+ * @details This hook is invoked in case to a system halting error before
+ * the system is halted.
+ */
+#define CH_CFG_SYSTEM_HALT_HOOK(reason) { \
+ /* System halt code here.*/ \
+}
+
+/** @} */
+
+/*===========================================================================*/
+/* Port-specific settings (override port settings defaulted in chcore.h). */
+/*===========================================================================*/
+
+#endif /* _CHCONF_H_ */
+
+/** @} */
diff --git a/os/rt/templates/chcore.c b/os/rt/templates/chcore.c new file mode 100644 index 000000000..1f7db903c --- /dev/null +++ b/os/rt/templates/chcore.c @@ -0,0 +1,134 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file templates/chcore.c
+ * @brief Port related template code.
+ * @details This file is a template of the system driver functions provided by
+ * a port. Some of the following functions may be implemented as
+ * macros in chcore.h if the implementer decides that there is an
+ * advantage in doing so, for example because performance concerns.
+ *
+ * @addtogroup core
+ * @details Non portable code templates.
+ * @{
+ */
+
+#include "ch.h"
+
+/**
+ * @brief Port-related initialization code.
+ * @note This function is usually empty.
+ */
+void port_init(void) {
+}
+
+/**
+ * @brief Kernel-lock action.
+ * @details Usually this function just disables interrupts but may perform more
+ * actions.
+ */
+void port_lock(void) {
+}
+
+/**
+ * @brief Kernel-unlock action.
+ * @details Usually this function just enables interrupts but may perform more
+ * actions.
+ */
+void port_unlock(void) {
+}
+
+/**
+ * @brief Kernel-lock action from an interrupt handler.
+ * @details This function is invoked before invoking I-class APIs from
+ * interrupt handlers. The implementation is architecture dependent,
+ * in its simplest form it is void.
+ */
+void port_lock_from_isr(void) {
+}
+
+/**
+ * @brief Kernel-unlock action from an interrupt handler.
+ * @details This function is invoked after invoking I-class APIs from interrupt
+ * handlers. The implementation is architecture dependent, in its
+ * simplest form it is void.
+ */
+void port_unlock_from_isr(void) {
+}
+
+/**
+ * @brief Disables all the interrupt sources.
+ * @note Of course non-maskable interrupt sources are not included.
+ */
+void port_disable(void) {
+}
+
+/**
+ * @brief Disables the interrupt sources below kernel-level priority.
+ * @note Interrupt sources above kernel level remains enabled.
+ */
+void port_suspend(void) {
+}
+
+/**
+ * @brief Enables all the interrupt sources.
+ */
+void port_enable(void) {
+}
+
+/**
+ * @brief Enters an architecture-dependent IRQ-waiting mode.
+ * @details The function is meant to return when an interrupt becomes pending.
+ * The simplest implementation is an empty function or macro but this
+ * would not take advantage of architecture-specific power saving
+ * modes.
+ */
+void port_wait_for_interrupt(void) {
+}
+
+/**
+ * @brief Halts the system.
+ * @details This function is invoked by the operating system when an
+ * unrecoverable error is detected (for example because a programming
+ * error in the application code that triggers an assertion while in
+ * debug mode).
+ */
+void port_halt(void) {
+
+ port_disable();
+ while (TRUE) {
+ }
+}
+
+/**
+ * @brief Performs a context switch between two threads.
+ * @details This is the most critical code in any port, this function
+ * is responsible for the context switch between 2 threads.
+ * @note The implementation of this code affects <b>directly</b> the context
+ * switch performance so optimize here as much as you can.
+ *
+ * @param[in] ntp the thread to be switched in
+ * @param[in] otp the thread to be switched out
+ */
+void port_switch(thread_t *ntp, thread_t *otp) {
+}
+
+/** @} */
diff --git a/os/rt/templates/chcore.h b/os/rt/templates/chcore.h new file mode 100644 index 000000000..c993c724e --- /dev/null +++ b/os/rt/templates/chcore.h @@ -0,0 +1,213 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file templates/chcore.h
+ * @brief Port related template macros and structures.
+ * @details This file is a template of the system driver macros provided by
+ * a port.
+ *
+ * @addtogroup core
+ * @{
+ */
+
+#ifndef _CHCORE_H_
+#define _CHCORE_H_
+
+/*===========================================================================*/
+/* Port constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Port macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Port configurable parameters. */
+/*===========================================================================*/
+
+/**
+ * @brief Stack size for the system idle thread.
+ * @details This size depends on the idle thread implementation, usually
+ * the idle thread should take no more space than those reserved
+ * by @p PORT_INT_REQUIRED_STACK.
+ */
+#ifndef PORT_IDLE_THREAD_STACK_SIZE
+#define PORT_IDLE_THREAD_STACK_SIZE 0
+#endif
+
+/**
+ * @brief Per-thread stack overhead for interrupts servicing.
+ * @details This constant is used in the calculation of the correct working
+ * area size.
+ * This value can be zero on those architecture where there is a
+ * separate interrupt stack and the stack space between @p intctx and
+ * @p extctx is known to be zero.
+ */
+#ifndef PORT_INT_REQUIRED_STACK
+#define PORT_INT_REQUIRED_STACK 0
+#endif
+
+/*===========================================================================*/
+/* Port derived parameters. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Port exported info. */
+/*===========================================================================*/
+
+/**
+ * @brief Unique macro for the implemented architecture.
+ */
+#define CH_ARCHITECTURE_XXX
+
+/**
+ * @brief Name of the implemented architecture.
+ */
+#define CH_ARCHITECTURE_NAME ""
+
+/**
+ * @brief Name of the architecture variant (optional).
+ */
+#define CH_ARCHITECTURE_VARIANT_NAME ""
+
+/**
+ * @brief Name of the compiler supported by this port.
+ */
+#define CH_COMPILER_NAME "GCC"
+
+/**
+ * @brief Port-specific information string.
+ */
+#define CH_PORT_INFO ""
+
+/*===========================================================================*/
+/* Port implementation part. */
+/*===========================================================================*/
+
+/**
+ * @brief Base type for stack and memory alignment.
+ */
+typedef uint8_t stkalign_t;
+
+/**
+ * @brief Interrupt saved context.
+ * @details This structure represents the stack frame saved during a
+ * preemption-capable interrupt handler.
+ */
+struct extctx {
+};
+
+/**
+ * @brief System saved context.
+ * @details This structure represents the inner stack frame during a context
+ * switching.
+ */
+struct intctx {
+};
+
+/**
+ * @brief Platform dependent part of the @p thread_t structure.
+ * @details This structure usually contains just the saved stack pointer
+ * defined as a pointer to a @p intctx structure.
+ */
+struct context {
+ struct intctx *sp;
+};
+
+/**
+ * @brief Platform dependent part of the @p chThdCreateI() API.
+ * @details This code usually setup the context switching frame represented
+ * by an @p intctx structure.
+ */
+#define SETUP_CONTEXT(workspace, wsize, pf, arg) { \
+}
+
+/**
+ * @brief Enforces a correct alignment for a stack area size value.
+ */
+#define STACK_ALIGN(n) ((((n) - 1) | (sizeof(stkalign_t) - 1)) + 1)
+
+/**
+ * @brief Computes the thread working area global size.
+ */
+#define THD_WA_SIZE(n) STACK_ALIGN(sizeof(thread_t) + \
+ sizeof(struct intctx) + \
+ sizeof(struct extctx) + \
+ (n) + (PORT_INT_REQUIRED_STACK))
+
+/**
+ * @brief Static working area allocation.
+ * @details This macro is used to allocate a static thread working area
+ * aligned as both position and size.
+ */
+#define WORKING_AREA(s, n) stkalign_t s[THD_WA_SIZE(n) / sizeof(stkalign_t)]
+
+/**
+ * @brief IRQ prologue code.
+ * @details This macro must be inserted at the start of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_PROLOGUE()
+
+/**
+ * @brief IRQ epilogue code.
+ * @details This macro must be inserted at the end of all IRQ handlers
+ * enabled to invoke system APIs.
+ */
+#define PORT_IRQ_EPILOGUE()
+
+/**
+ * @brief IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ */
+#define PORT_IRQ_HANDLER(id) void id(void)
+
+/**
+ * @brief Fast IRQ handler function declaration.
+ * @note @p id can be a function name or a vector number depending on the
+ * port implementation.
+ * @note Not all architectures support fast interrupts, in this case this
+ * macro must be omitted.
+ */
+#define PORT_FAST_IRQ_HANDLER(id) void id(void)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void port_init(void);
+ void port_lock(void);
+ void port_unlock(void);
+ void port_lock_from_isr(void);
+ void port_unlock_from_isr(void);
+ void port_disable(void);
+ void port_suspend(void);
+ void port_enable(void);
+ void port_wait_for_interrupt(void);
+ void port_halt(void);
+ void port_switch(thread_t *ntp, thread_t *otp);
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _CHCORE_H_ */
+
+/** @} */
diff --git a/os/rt/templates/chtypes.h b/os/rt/templates/chtypes.h new file mode 100644 index 000000000..d13e837c4 --- /dev/null +++ b/os/rt/templates/chtypes.h @@ -0,0 +1,97 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file templates/chtypes.h
+ * @brief System types template.
+ * @details The types defined in this file may change depending on the target
+ * architecture. You may also try to optimize the size of the various
+ * types in order to privilege size or performance, be careful in
+ * doing so.
+ *
+ * @addtogroup types
+ * @details System types and macros.
+ * @{
+ */
+
+#ifndef _CHTYPES_H_
+#define _CHTYPES_H_
+
+#define __need_NULL
+#define __need_size_t
+#include <stddef.h>
+
+#if !defined(_STDINT_H) && !defined(__STDINT_H_)
+#include <stdint.h>
+#endif
+
+/**
+ * @brief Thread mode flags, uint8_t is ok.
+ */
+typedef uint8_t tmode_t;
+
+/**
+ * @brief Thread state, uint8_t is ok.
+ */
+typedef uint8_t tstate_t;
+
+/**
+ * @brief Thread references counter, uint8_t is ok.
+ */
+typedef uint8_t trefs_t;
+
+/**
+ * @brief Priority, use the fastest unsigned type.
+ */
+typedef uint32_t tprio_t;
+
+/**
+ * @brief Message, use signed pointer equivalent.
+ */
+typedef int32_t msg_t;
+
+/**
+ * @brief Numeric event identifier, use fastest signed.
+ */
+typedef int32_t eventid_t;
+
+/**
+ * @brief Mask of event identifiers, recommended fastest unsigned.
+ */
+typedef uint32_t eventmask_t;
+
+/**
+ * @brief Mask of event flags, recommended fastest unsigned.
+ */
+typedef uint32_t eventflags_t;
+
+/**
+ * @brief System Time, recommended fastest unsigned.
+ */
+typedef uint32_t systime_t;
+
+/**
+ * @brief Counter, recommended fastest signed.
+ */
+typedef int32_t cnt_t;
+
+#endif /* _CHTYPES_H_ */
+
+/** @} */
diff --git a/os/rt/templates/module.c b/os/rt/templates/module.c new file mode 100644 index 000000000..6a93bf4aa --- /dev/null +++ b/os/rt/templates/module.c @@ -0,0 +1,81 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chXxx.c
+ * @brief XXX module code.
+ *
+ * @addtogroup XXX
+ * @{
+ */
+
+#include "ch.h"
+
+#if CH_CFG_USE_XXX || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module local definitions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local variables. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module local functions. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module exported functions. */
+/*===========================================================================*/
+
+/**
+ * @brief XXX Module initialization.
+ * @note This function is implicitly invoked on system initialization,
+ * there is no need to explicitly initialize the module.
+ *
+ * @notapi
+ */
+void _xxx_init(void) {
+
+}
+
+/**
+ * @brief Initializes a @p xxx_t object.
+ *
+ * @param[out] xxxp pointer to the @p xxx_t object
+ *
+ * @init
+ */
+void chXxxObjectInit(xxx_t *xxxp) {
+
+}
+
+#endif /* CH_CFG_USE_XXX */
+
+/** @} */
diff --git a/os/rt/templates/module.h b/os/rt/templates/module.h new file mode 100644 index 000000000..261311f84 --- /dev/null +++ b/os/rt/templates/module.h @@ -0,0 +1,77 @@ +/*
+ ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010,
+ 2011,2012,2013 Giovanni Di Sirio.
+
+ This file is part of ChibiOS/RT.
+
+ ChibiOS/RT is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ ChibiOS/RT is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/**
+ * @file chXxx.h
+ * @brief XXX Module macros and structures.
+ *
+ * @addtogroup XXX
+ * @{
+ */
+
+#ifndef _CHXXX_H_
+#define _CHXXX_H_
+
+#include "ch.h"
+
+#if CH_CFG_USE_XXX || defined(__DOXYGEN__)
+
+/*===========================================================================*/
+/* Module constants. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module pre-compile time settings. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Derived constants and error checks. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module data structures and types. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* Module macros. */
+/*===========================================================================*/
+
+/*===========================================================================*/
+/* External declarations. */
+/*===========================================================================*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+ void chXxxInit(void);
+ void chXxxObjectInit(xxx_t *xxxp);
+#ifdef __cplusplus
+}
+#endif
+
+/*===========================================================================*/
+/* Module inline functions. */
+/*===========================================================================*/
+
+#endif /* CH_CFG_USE_XXX */
+
+#endif /* _CHXXX_H_ */
+
+/** @} */
|