import ChibiOS 2.0.8

This commit is contained in:
NIIBE Yutaka
2010-11-30 13:54:43 +09:00
parent 27543cfeca
commit c560d0ad0c
1982 changed files with 5318 additions and 4046 deletions

View File

@@ -0,0 +1,252 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/*
Concepts and parts of this file have been contributed by Leon Woestenberg.
*/
/**
* @file chcond.c
* @brief Condition Variables code.
*
* @addtogroup condvars 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 @p Mutex. Mutexes and CondVars
* together can implement a Monitor construct.<br>
* In order to use the Condition Variables APIs the @p CH_USE_CONDVARS
* option must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_CONDVARS && CH_USE_MUTEXES
/**
* @brief Initializes s @p CondVar structure.
* @note This function can be invoked from within an interrupt handler even
* if it is not an I-Class API because it does not touch any critical
* kernel data structure.
*
* @param[out] cp pointer to a @p CondVar structure
*/
void chCondInit(CondVar *cp) {
chDbgCheck(cp != NULL, "chCondInit");
queue_init(&cp->c_queue);
}
/**
* @brief Signals one thread that is waiting on the condition variable.
*
* @param[in] cp pointer to the @p CondVar structure
*/
void chCondSignal(CondVar *cp) {
chDbgCheck(cp != NULL, "chCondSignal");
chSysLock();
if (notempty(&cp->c_queue))
chSchWakeupS(fifo_remove(&cp->c_queue), RDY_OK);
chSysUnlock();
}
/**
* @brief Signals one thread that is waiting on the condition variable.
*
* @param[in] cp pointer to the @p CondVar structure
*/
void chCondSignalI(CondVar *cp) {
chDbgCheck(cp != NULL, "chCondSignalI");
if (notempty(&cp->c_queue))
chSchReadyI(fifo_remove(&cp->c_queue))->p_u.rdymsg = RDY_OK;
}
/**
* @brief Signals all threads that are waiting on the condition variable.
*
* @param[in] cp pointer to the @p CondVar structure
*/
void chCondBroadcast(CondVar *cp) {
chSysLock();
chCondBroadcastI(cp);
chSchRescheduleS();
chSysUnlock();
}
/**
* @brief Signals all threads that are waiting on the condition variable.
*
* @param[in] cp pointer to the @p CondVar structure
*/
void chCondBroadcastI(CondVar *cp) {
chDbgCheck(cp != NULL, "chCondBroadcastI");
/* Empties the condition variable queue and inserts all the Threads into the
ready list in FIFO order. The wakeup message is set to @p RDY_RESET in
order to make a chCondBroadcast() detectable from a chCondSignal().*/
while (cp->c_queue.p_next != (void *)&cp->c_queue)
chSchReadyI(fifo_remove(&cp->c_queue))->p_u.rdymsg = RDY_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.
* @note The invoking thread <b>must</b> have at least one owned mutex on
* entry.
*
* @param[in] cp pointer to the @p CondVar structure
* @return The wakep mode.
* @retval RDY_OK if the condvar was signaled using @p chCondSignal().
* @retval RDY_RESET if the condvar was signaled using @p chCondBroadcast().
*/
msg_t chCondWait(CondVar *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.
* @note The invoking thread <b>must</b> have at least one owned mutex on
* entry.
*
* @param[in] cp pointer to the @p CondVar structure
* @return The wakep mode.
* @retval RDY_OK if the condvar was signaled using @p chCondSignal().
* @retval RDY_RESET if the condvar was signaled using @p chCondBroadcast().
*/
msg_t chCondWaitS(CondVar *cp) {
Thread *ctp = currp;
Mutex *mp;
msg_t msg;
chDbgCheck(cp != NULL, "chCondWaitS");
chDbgAssert(ctp->p_mtxlist != NULL,
"chCondWaitS(), #1",
"not owning a mutex");
mp = chMtxUnlockS();
ctp->p_u.wtobjp = cp;
prio_insert(ctp, &cp->c_queue);
chSchGoSleepS(THD_STATE_WTCOND);
msg = ctp->p_u.rdymsg;
chMtxLockS(mp);
return msg;
}
#if CH_USE_CONDVARS_TIMEOUT
/**
* @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.
* @note The invoking thread <b>must</b> have at least one owned mutex on
* entry.
* @note Exiting the function because a timeout does not re-acquire the
* mutex, the mutex ownership is lost.
*
* @param[in] cp pointer to the @p CondVar structure
* @param[in] time the number of ticks before the operation timeouts,
* the special value @p TIME_INFINITE is allowed.
* It is not possible to specify zero @p TIME_IMMEDIATE
* as timeout specification because it would make no sense
* in this function.
* @return The wakep mode.
* @retval RDY_OK if the condvar was signaled using @p chCondSignal().
* @retval RDY_RESET if the condvar was signaled using @p chCondBroadcast().
* @retval RDY_TIMEOUT if the condvar was not signaled @p within the specified
* timeout.
*/
msg_t chCondWaitTimeout(CondVar *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.
* @note The invoking thread <b>must</b> have at least one owned mutex on
* entry.
* @note Exiting the function because a timeout does not re-acquire the
* mutex, the mutex ownership is lost.
*
* @param[in] cp pointer to the @p CondVar structure
* @param[in] time the number of ticks before the operation timeouts,
* the special value @p TIME_INFINITE is allowed.
* It is not possible to specify zero @p TIME_IMMEDIATE
* as timeout specification because it would make no sense
* in this function.
* @return The wakep mode.
* @retval RDY_OK if the condvar was signaled using @p chCondSignal().
* @retval RDY_RESET if the condvar was signaled using @p chCondBroadcast().
* @retval RDY_TIMEOUT if the condvar was not signaled within the specified
* timeout.
*/
msg_t chCondWaitTimeoutS(CondVar *cp, systime_t time) {
Mutex *mp;
msg_t msg;
chDbgCheck(cp != NULL, "chCondWaitTimeoutS");
chDbgAssert(currp->p_mtxlist != NULL,
"chCondWaitTimeoutS(), #1",
"not owning a mutex");
mp = chMtxUnlockS();
currp->p_u.wtobjp = cp;
prio_insert(currp, &cp->c_queue);
msg = chSchGoSleepTimeoutS(THD_STATE_WTCOND, time);
if (msg != RDY_TIMEOUT)
chMtxLockS(mp);
return msg;
}
#endif /* CH_USE_CONDVARS_TIMEOUT */
#endif /* CH_USE_CONDVARS && CH_USE_MUTEXES */
/** @} */

View File

@@ -0,0 +1,94 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @file chdebug.c
* @brief ChibiOS/RT Debug code.
*
* @addtogroup debug
* @details Debug APIs and services:
* - Trace buffer.
* - Parameters check.
* - Kernel assertions.
* .
* @{
*/
#include "ch.h"
#if CH_DBG_ENABLE_TRACE
/**
* @brief Public trace buffer.
*/
TraceBuffer trace_buffer;
/**
* @brief Trace circular buffer subsystem initialization.
*/
void trace_init(void) {
trace_buffer.tb_size = TRACE_BUFFER_SIZE;
trace_buffer.tb_ptr = &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
*/
void chDbgTrace(Thread *otp) {
trace_buffer.tb_ptr->cse_wtobjp = otp->p_u.wtobjp;
trace_buffer.tb_ptr->cse_time = chTimeNow();
trace_buffer.tb_ptr->cse_state = otp->p_state;
trace_buffer.tb_ptr->cse_tid = (unsigned)currp >> 6;
if (++trace_buffer.tb_ptr >= &trace_buffer.tb_buffer[TRACE_BUFFER_SIZE])
trace_buffer.tb_ptr = &trace_buffer.tb_buffer[0];
}
#endif /* CH_DBG_ENABLE_TRACE */
#if CH_DBG_ENABLE_ASSERTS || CH_DBG_ENABLE_CHECKS || CH_DBG_ENABLE_STACK_CHECK
/**
* @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. This variable can be
* set to @p NULL if the halt is caused by a stack overflow.
*/
char *panic_msg;
/**
* @brief Prints a panic message on the console and then halts the system.
*
* @param[in] msg the pointer to the panic message string
*/
void chDbgPanic(char *msg) {
panic_msg = msg;
chSysHalt();
}
#endif /* CH_DBG_ENABLE_ASSERTS || CH_DBG_ENABLE_CHECKS || CH_DBG_ENABLE_STACK_CHECK */
/** @} */

View File

@@ -0,0 +1,449 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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
* 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.<br><br>
* In order to use the Events APIs the @p CH_USE_EVENTS option must be
* enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_EVENTS
/**
* @brief Registers an Event Listener on an Event Source.
* @note Multiple Event Listeners can specify the same bits to be pended.
*
* @param[in] esp pointer to the @p EventSource structure
* @param[in] elp pointer to the @p EventListener structure
* @param[in] mask the mask of event flags to be pended to the thread when
* the event source is broadcasted
*/
void chEvtRegisterMask(EventSource *esp, EventListener *elp, eventmask_t mask) {
chDbgCheck((esp != NULL) && (elp != NULL), "chEvtRegisterMask");
chSysLock();
elp->el_next = esp->es_next;
esp->es_next = elp;
elp->el_listener = currp;
elp->el_mask = mask;
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 EventSource structure
* @param[in] elp pointer to the @p EventListener structure
*/
void chEvtUnregister(EventSource *esp, EventListener *elp) {
EventListener *p;
chDbgCheck((esp != NULL) && (elp != NULL), "chEvtUnregister");
p = (EventListener *)esp;
chSysLock();
while (p->el_next != (EventListener *)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.
*/
eventmask_t chEvtClear(eventmask_t mask) {
eventmask_t m;
chSysLock();
m = currp->p_epending & mask;
currp->p_epending &= ~mask;
chSysUnlock();
return m;
}
/**
* @brief Pends 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 events to be pended
* @return The current pending events mask.
*/
eventmask_t chEvtPend(eventmask_t mask) {
chSysLock();
mask = (currp->p_epending |= mask);
chSysUnlock();
return mask;
}
/**
* @brief Pends a set of event flags on the specified @p Thread.
*
* @param[in] tp the thread to be signaled
* @param[in] mask the event flags set to be pended
*/
void chEvtSignal(Thread *tp, eventmask_t mask) {
chDbgCheck(tp != NULL, "chEvtSignal");
chSysLock();
chEvtSignalI(tp, mask);
chSchRescheduleS();
chSysUnlock();
}
/**
* @brief Pends a set of event flags on the specified @p Thread.
*
* @param[in] tp the thread to be signaled
* @param[in] mask the event flags set to be pended
*/
void chEvtSignalI(Thread *tp, eventmask_t mask) {
chDbgCheck(tp != NULL, "chEvtSignalI");
tp->p_epending |= mask;
/* Test on the AND/OR conditions wait states.*/
if (((tp->p_state == THD_STATE_WTOREVT) &&
((tp->p_epending & tp->p_u.ewmask) != 0)) ||
((tp->p_state == THD_STATE_WTANDEVT) &&
((tp->p_epending & tp->p_u.ewmask) == tp->p_u.ewmask)))
chSchReadyI(tp)->p_u.rdymsg = RDY_OK;
}
/**
* @brief Signals all the Event Listeners registered on the specified Event
* Source.
*
* @param[in] esp pointer to the @p EventSource structure
*/
void chEvtBroadcast(EventSource *esp) {
chSysLock();
chEvtBroadcastI(esp);
chSchRescheduleS();
chSysUnlock();
}
/**
* @brief Signals all the Event Listeners registered on the specified Event
* Source.
*
* @param[in] esp pointer to the @p EventSource structure
*/
void chEvtBroadcastI(EventSource *esp) {
EventListener *elp;
chDbgCheck(esp != NULL, "chEvtBroadcastI");
elp = esp->es_next;
while (elp != (EventListener *)esp) {
chEvtSignalI(elp->el_listener, elp->el_mask);
elp = elp->el_next;
}
}
/**
* @brief Invokes the event handlers associated to an event flags mask.
*
* @param[in] mask mask of the events 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.
*/
void chEvtDispatch(const evhandler_t *handlers, eventmask_t mask) {
eventid_t eid;
chDbgCheck(handlers != NULL, "chEvtDispatch");
eid = 0;
while (mask) {
if (mask & EVENT_MASK(eid)) {
chDbgAssert(handlers[eid] != NULL,
"chEvtDispatch(), #1",
"null handler");
mask &= ~EVENT_MASK(eid);
handlers[eid](eid);
}
eid++;
}
}
#if CH_OPTIMIZE_SPEED || !CH_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 events that the function should wait for,
* @p ALL_EVENTS enables all the events
* @return The mask of the lowest id served and cleared event.
*/
eventmask_t chEvtWaitOne(eventmask_t mask) {
Thread *ctp = currp;
eventmask_t m;
chSysLock();
if ((m = (ctp->p_epending & mask)) == 0) {
ctp->p_u.ewmask = mask;
chSchGoSleepS(THD_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 events that the function should wait for,
* @p ALL_EVENTS enables all the events
* @return The mask of the served and cleared events.
*/
eventmask_t chEvtWaitAny(eventmask_t mask) {
Thread *ctp = currp;
eventmask_t m;
chSysLock();
if ((m = (ctp->p_epending & mask)) == 0) {
ctp->p_u.ewmask = mask;
chSchGoSleepS(THD_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 ids that the function should wait for
* @return The mask of the served and cleared events.
*/
eventmask_t chEvtWaitAll(eventmask_t mask) {
Thread *ctp = currp;
chSysLock();
if ((ctp->p_epending & mask) != mask) {
ctp->p_u.ewmask = mask;
chSchGoSleepS(THD_STATE_WTANDEVT);
}
ctp->p_epending &= ~mask;
chSysUnlock();
return mask;
}
#endif /* CH_OPTIMIZE_SPEED || !CH_USE_EVENTS_TIMEOUT */
#if CH_USE_EVENTS_TIMEOUT
/**
* @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 events 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 specified timeout expired.
*/
eventmask_t chEvtWaitOneTimeout(eventmask_t mask, systime_t time) {
Thread *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(THD_STATE_WTOREVT, time) < RDY_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 events 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 specified timeout expired.
*/
eventmask_t chEvtWaitAnyTimeout(eventmask_t mask, systime_t time) {
Thread *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(THD_STATE_WTOREVT, time) < RDY_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 ids that the function should wait for
* @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 specified timeout expired.
*/
eventmask_t chEvtWaitAllTimeout(eventmask_t mask, systime_t time) {
Thread *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(THD_STATE_WTANDEVT, time) < RDY_OK) {
chSysUnlock();
return (eventmask_t)0;
}
}
ctp->p_epending &= ~mask;
chSysUnlock();
return mask;
}
#endif /* CH_USE_EVENTS_TIMEOUT */
#endif /* CH_USE_EVENTS */
/** @} */

View File

@@ -0,0 +1,313 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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>
* By enabling the @p CH_USE_MALLOC_HEAP option the heap manager
* will use the runtime-provided @p malloc() and @p free() as
* backend for the heap APIs instead of the system provided
* allocator.<br>
* In order to use the heap APIs the @p CH_USE_HEAP option must
* be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_HEAP
#if !CH_USE_MALLOC_HEAP
/*
* Defaults on the best synchronization mechanism available.
*/
#if CH_USE_MUTEXES
#define H_LOCK(h) chMtxLock(&(h)->h_mtx)
#define H_UNLOCK(h) chMtxUnlock()
#else
#define H_LOCK(h) chSemWait(&(h)->h_sem)
#define H_UNLOCK(h) chSemSignal(&(h)->h_sem)
#endif
/**
* @brief Default heap descriptor.
*/
static MemoryHeap default_heap;
/**
* @brief Initializes the default heap.
* @note Internal use only.
*/
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_USE_MUTEXES
chMtxInit(&default_heap.h_mtx);
#else
chSemInit(&default_heap.h_sem, 1);
#endif
}
/**
* @brief Initializes a memory heap from a static memory area.
* @note Both the heap buffer base and the heap size must be aligned to
* the @p align_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
*/
void chHeapInit(MemoryHeap *heapp, void *buf, size_t size) {
union heap_header *hp;
chDbgCheck(MEM_IS_ALIGNED(buf) && MEM_IS_ALIGNED(size), "chHeapInit");
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_USE_MUTEXES
chMtxInit(&heapp->h_mtx);
#else
chSemInit(&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 align_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.
*/
void *chHeapAlloc(MemoryHeap *heapp, size_t size) {
union heap_header *qp, *hp, *fp;
if (heapp == NULL)
heapp = &default_heap;
size = MEM_ALIGN_SIZE(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
*/
void chHeapFree(void *p) {
union heap_header *qp, *hp;
MemoryHeap *heapp;
chDbgCheck(p != NULL, "chHeapFree");
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)),
"chHeapFree(), #1",
"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.
* @note This function is not implemented when the @p CH_USE_MALLOC_HEAP
* configuration option is used (it always returns zero).
*
* @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.
*/
size_t chHeapStatus(MemoryHeap *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;
}
#else /* CH_USE_MALLOC_HEAP */
#include <stdlib.h>
#if CH_USE_MUTEXES
#define H_LOCK() chMtxLock(&hmtx)
#define H_UNLOCK() chMtxUnlock()
static Mutex hmtx;
#elif CH_USE_SEMAPHORES
#define H_LOCK() chSemWait(&hsem)
#define H_UNLOCK() chSemSignal(&hsem)
static Semaphore hsem;
#endif
void heap_init(void) {
#if CH_USE_MUTEXES
chMtxInit(&hmtx);
#else
chSemInit(&hsem, 1);
#endif
}
void *chHeapAlloc(MemoryHeap *heapp, size_t size) {
void *p;
chDbgCheck(heapp == NULL, "chHeapAlloc");
H_LOCK();
p = malloc(size);
H_UNLOCK();
return p;
}
void chHeapFree(void *p) {
chDbgCheck(p != NULL, "chHeapFree");
H_LOCK();
free(p);
H_UNLOCK();
}
size_t chHeapStatus(MemoryHeap *heapp, size_t *sizep) {
chDbgCheck(heapp == NULL, "chHeapStatus");
if (sizep)
*sizep = 0;
return 0;
}
#endif /* CH_USE_MALLOC_HEAP */
#endif /* CH_USE_HEAP */
/** @} */

View File

@@ -0,0 +1,155 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @file chlists.c
* @brief Thread queues/lists code.
*
* @addtogroup internals
* @details All the functions present in this module, while public, are not
* an OS API and should not be directly used in the user applications
* code.
* @{
*/
#include "ch.h"
#if !CH_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.
* @note This function is @b not an API.
*
* @param[in] tp the pointer to the thread to be inserted in the list
* @param[in] tqp the pointer to the threads list header
*/
void prio_insert(Thread *tp, ThreadsQueue *tqp) {
/* cp iterates over the queue.*/
Thread *cp = (Thread *)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 *)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.
* @note This function is @b not an API.
*
* @param[in] tp the pointer to the thread to be inserted in the list
* @param[in] tqp the pointer to the threads list header
*/
void queue_insert(Thread *tp, ThreadsQueue *tqp) {
tp->p_next = (Thread *)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.
* @note This function is @b not an API.
*
* @param[in] tqp the pointer to the threads list header
* @return The removed thread pointer.
*/
Thread *fifo_remove(ThreadsQueue *tqp) {
Thread *tp = tqp->p_next;
(tqp->p_next = tp->p_next)->p_prev = (Thread *)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.
* @note This function is @b not an API.
*
* @param[in] tqp the pointer to the threads list header
* @return The removed thread pointer.
*/
Thread *lifo_remove(ThreadsQueue *tqp) {
Thread *tp = tqp->p_prev;
(tqp->p_prev = tp->p_prev)->p_next = (Thread *)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.
* @note This function is @b not an API.
*
* @param[in] tp the pointer to the thread to be removed from the queue
* @return The removed thread pointer.
*/
Thread *dequeue(Thread *tp) {
tp->p_prev->p_next = tp->p_next;
tp->p_next->p_prev = tp->p_prev;
return tp;
}
/**
* @brief Pushes a Thread on top of a stack list.
* @note This function is @b not an API.
*
* @param[in] tp the pointer to the thread to be inserted in the list
* @param[in] tlp the pointer to the threads list header
*/
void list_insert(Thread *tp, ThreadsList *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.
* @note The list must be non-empty before calling this function.
* @note This function is @b not an API.
*
* @param[in] tlp the pointer to the threads list header
* @return The removed thread pointer.
*/
Thread *list_remove(ThreadsList *tlp) {
Thread *tp = tlp->p_next;
tlp->p_next = tp->p_next;
return tp;
}
#endif /* CH_OPTIMIZE_SPEED */
/** @} */

View File

@@ -0,0 +1,276 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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 as
* 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.<br>
* In order to use the mailboxes APIs the @p CH_USE_MAILBOXES option
* must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_MAILBOXES
/**
* @brief Initializes a Mailbox object.
*
* @param[out] mbp the pointer to the Mailbox structure to be initialized
* @param[in] buf the circular messages buffer
* @param[in] n the buffer size as number of @p msg_t
*/
void chMBInit(Mailbox *mbp, msg_t *buf, cnt_t n) {
chDbgCheck((mbp != NULL) && (buf != NULL) && (n > 0), "chMBInit");
mbp->mb_buffer = mbp->mb_wrptr = mbp->mb_rdptr = buf;
mbp->mb_top = &buf[n];
chSemInit(&mbp->mb_emptysem, n);
chSemInit(&mbp->mb_fullsem, 0);
}
/**
* @brief Resets a Mailbox object.
* @details All the waiting threads are resumed with status @p RDY_RESET and
* the queued messages are lost.
*
* @param[in] mbp the pointer to an initialized Mailbox object
*/
void chMBReset(Mailbox *mbp) {
chDbgCheck(mbp != NULL, "chMBReset");
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 Mailbox 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 RDY_OK if the message was correctly posted.
* @retval RDY_RESET if the mailbox was reset while waiting.
* @retval RDY_TIMEOUT if the operation timed out.
*/
msg_t chMBPost(Mailbox *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 Mailbox 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 RDY_OK if the message was correctly posted.
* @retval RDY_RESET if the mailbox was reset while waiting.
* @retval RDY_TIMEOUT if the operation timed out.
*/
msg_t chMBPostS(Mailbox *mbp, msg_t msg, systime_t time) {
msg_t rdymsg;
chDbgCheck(mbp != NULL, "chMBPostS");
rdymsg = chSemWaitTimeoutS(&mbp->mb_emptysem, time);
if (rdymsg == RDY_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 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 Mailbox 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 RDY_OK if the message was correctly posted.
* @retval RDY_RESET if the mailbox was reset while waiting.
* @retval RDY_TIMEOUT if the operation timed out.
*/
msg_t chMBPostAhead(Mailbox *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 Mailbox 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 RDY_OK if the message was correctly posted.
* @retval RDY_RESET if the mailbox was reset while waiting.
* @retval RDY_TIMEOUT if the operation timed out.
*/
msg_t chMBPostAheadS(Mailbox *mbp, msg_t msg, systime_t time) {
msg_t rdymsg;
chDbgCheck(mbp != NULL, "chMBPostAheadS");
rdymsg = chSemWaitTimeoutS(&mbp->mb_emptysem, time);
if (rdymsg == RDY_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 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 Mailbox 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 RDY_OK if a message was correctly fetched.
* @retval RDY_RESET if the mailbox was reset while waiting.
* @retval RDY_TIMEOUT if the operation timed out.
*/
msg_t chMBFetch(Mailbox *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 Mailbox 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 RDY_OK if a message was correctly fetched.
* @retval RDY_RESET if the mailbox was reset while waiting.
* @retval RDY_TIMEOUT if the operation timed out.
*/
msg_t chMBFetchS(Mailbox *mbp, msg_t *msgp, systime_t time) {
msg_t rdymsg;
chDbgCheck((mbp != NULL) && (msgp != NULL), "chMBFetchS");
rdymsg = chSemWaitTimeoutS(&mbp->mb_fullsem, time);
if (rdymsg == RDY_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;
}
#endif /* CH_USE_MAILBOXES */
/** @} */

View File

@@ -0,0 +1,129 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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.<br>
* In order to use the core memory manager APIs the @p CH_USE_MEMCORE
* option must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_MEMCORE
static uint8_t *nextmem;
static uint8_t *endmem;
/**
* @brief Low level memory manager initialization.
* @note Internal use only.
*/
void core_init(void) {
#if CH_MEMCORE_SIZE == 0
extern uint8_t __heap_base__;
extern uint8_t __heap_end__;
nextmem = &__heap_base__;
endmem = &__heap_end__;
#else
static stkalign_t buffer[MEM_ALIGN_SIZE(CH_MEMCORE_SIZE) /
sizeof(stkalign_t)];
nextmem = (uint8_t *)&buffer[0];
endmem = (uint8_t *)&buffer[MEM_ALIGN_SIZE(CH_MEMCORE_SIZE) /
sizeof(stkalign_t)];
#endif
}
/**
* @brief Allocates a memory block.
* @details The size of the returned block is aligned to the alignment
* type @p stkalign_t so it is not possible to allocate less
* than <code>sizeof(stkalign_t)</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.
*/
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 @p align_t so it is not possible to allocate less than
* <code>sizeof(align_t)</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.
*/
void *chCoreAllocI(size_t size) {
void *p;
size = MEM_ALIGN_SIZE(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.
*/
size_t chCoreStatus(void) {
return (size_t)(endmem - nextmem);
}
#endif /* CH_USE_MEMCORE */
/** @} */

View File

@@ -0,0 +1,140 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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>
* In order to use the memory pools APIs the @p CH_USE_MEMPOOLS option
* must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_MEMPOOLS
/**
* @brief Initializes an empty memory pool.
* @note The size is internally aligned to be a multiple of the @p align_t
* type size.
*
* @param[out] mp pointer to a @p MemoryPool 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
*/
void chPoolInit(MemoryPool *mp, size_t size, memgetfunc_t provider) {
chDbgCheck((mp != NULL) && (size >= sizeof(void *)), "chPoolInit");
mp->mp_next = NULL;
mp->mp_object_size = MEM_ALIGN_SIZE(size);
mp->mp_provider = provider;
}
/**
* @brief Allocates an object from a memory pool.
*
* @param[in] mp pointer to a @p MemoryPool structure
* @return The pointer to the allocated object.
* @retval NULL if pool is empty.
*/
void *chPoolAllocI(MemoryPool *mp) {
void *objp;
chDbgCheck(mp != NULL, "chPoolAllocI");
if ((objp = mp->mp_next) != NULL)
mp->mp_next = mp->mp_next->ph_next;
#if CH_USE_MEMCORE
else if (mp->mp_provider != NULL)
objp = mp->mp_provider(mp->mp_object_size);
#endif
return objp;
}
/**
* @brief Allocates an object from a memory pool.
*
* @param[in] mp pointer to a @p MemoryPool structure
* @return The pointer to the allocated object.
* @retval NULL if pool is empty.
*/
void *chPoolAlloc(MemoryPool *mp) {
void *objp;
chSysLock();
objp = chPoolAllocI(mp);
chSysUnlock();
return objp;
}
/**
* @brief Releases (or adds) an object into (to) a memory pool.
* @note The object is assumed to be of the right size for the specified
* memory pool.
* @note The object is assumed to be memory aligned to the size of @p align_t
* type.
*
* @param[in] mp pointer to a @p MemoryPool structure
* @param[in] objp the pointer to the object to be released or added
*/
void chPoolFreeI(MemoryPool *mp, void *objp) {
struct pool_header *php = objp;
chDbgCheck((mp != NULL) && (objp != NULL) && MEM_IS_ALIGNED(objp),
"chPoolFreeI");
php->ph_next = mp->mp_next;
mp->mp_next = php;
}
/**
* @brief Releases (or adds) an object into (to) a memory pool.
* @note The object is assumed to be of the right size for the specified
* memory pool.
*
* @param[in] mp pointer to a @p MemoryPool structure
* @param[in] objp the pointer to the object to be released or added
*/
void chPoolFree(MemoryPool *mp, void *objp) {
chSysLock();
chPoolFreeI(mp, objp);
chSysUnlock();
}
#endif /* CH_USE_MEMPOOLS */
/** @} */

View File

@@ -0,0 +1,157 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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 usually processed in FIFO order but it is possible to
* process them in priority order by enabling the
* @p CH_USE_MESSAGES_PRIORITY option in @p chconf.h.<br>
* Applications do not need to allocate buffers for synchronous
* message queues, the mechanism just requires two extra pointers in
* the @p Thread structure (the message queue header).<br>
* In order to use the Messages APIs the @p CH_USE_MESSAGES option
* must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_MESSAGES
#if CH_USE_MESSAGES_PRIORITY
#define msg_insert(tp, qp) prio_insert(tp, qp)
#else
#define msg_insert(tp, qp) queue_insert(tp, qp)
#endif
/**
* @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().
*/
msg_t chMsgSend(Thread *tp, msg_t msg) {
Thread *ctp = currp;
chDbgCheck(tp != NULL, "chMsgSend");
chSysLock();
ctp->p_msg = msg;
ctp->p_u.wtobjp = &tp->p_msgqueue;
msg_insert(ctp, &tp->p_msgqueue);
if (tp->p_state == THD_STATE_WTMSG)
chSchReadyI(tp);
chSchGoSleepS(THD_STATE_SNDMSG);
msg = ctp->p_u.rdymsg;
chSysUnlock();
return msg;
}
/**
* @brief Suspends the thread and waits for an incoming message.
* @note You can assume that the data contained in the message is stable
* until you invoke @p chMsgRelease() because the sending thread is
* suspended until then.
*
* @return The pointer to the message structure. Note, it is
* always the message associated to the thread on the
* top of the messages queue.
*/
msg_t chMsgWait(void) {
msg_t msg;
chSysLock();
if (!chMsgIsPendingI(currp))
chSchGoSleepS(THD_STATE_WTMSG);
#if defined(CH_ARCHITECTURE_STM8)
msg = chMsgGetI((volatile Thread *)currp); /* Temporary hack.*/
#else
msg = chMsgGetI(currp);
#endif
chSysUnlock();
return msg;
}
/**
* @brief Returns the next message in the queue.
* @note 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. Always remember that the message data is not
* copied between the sender and the receiver, just a pointer is
* passed.
*
* @return The pointer to the message structure. Note, it is
* always the message associated to the thread on the
* top of the messages queue.
* @retval NULL if the queue is empty.
*/
msg_t chMsgGet(void) {
msg_t msg;
chSysLock();
msg = chMsgIsPendingI(currp) ? chMsgGetI(currp) : (msg_t)NULL;
chSysUnlock();
return msg;
}
/**
* @brief Releases the thread waiting on top of the messages queue.
* @note You can call this function only if there is a message already in
* the queue else the result will be unpredictable (a crash most likely).
* Exiting from the @p chMsgWait() ensures you have at least one
* message in the queue so it is not a big deal.<br>
* The condition is only tested in debug mode in order to make this
* code as fast as possible.
*
* @param[in] msg the message returned to the message sender
*/
void chMsgRelease(msg_t msg) {
chSysLock();
chDbgAssert(chMsgIsPendingI(currp),
"chMsgRelease(), #1",
"no message pending");
chSchWakeupS(fifo_remove(&currp->p_msgqueue), msg);
chSysUnlock();
}
#endif /* CH_USE_MESSAGES */
/** @} */

View File

@@ -0,0 +1,348 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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.
* - Owned by a thread.
* .
* 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.
* .
* In order to use the Mutexes APIs the @p CH_USE_MUTEXES option must
* be enabled in @p chconf.h.
* <h2>Constraints</h2>
* In ChibiOS/RT the Unlock operations are always performed in
* lock-reverse order. The unlock API does not even have a parameter,
* the mutex to unlock is selected from an internal, per-thread, stack
* of owned mutexes. This both improves the performance and is
* required for an efficient implementation of the priority
* inheritance mechanism.
*
* <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.
* @{
*/
#include "ch.h"
#if CH_USE_MUTEXES
/**
* @brief Initializes s @p Mutex structure.
*
* @param[out] mp pointer to a @p Mutex structure
*/
void chMtxInit(Mutex *mp) {
chDbgCheck(mp != NULL, "chMtxInit");
queue_init(&mp->m_queue);
mp->m_owner = NULL;
}
/**
* @brief Locks the specified mutex.
*
* @param[in] mp pointer to the @p Mutex structure
*/
void chMtxLock(Mutex *mp) {
chSysLock();
chMtxLockS(mp);
chSysUnlock();
}
/**
* @brief Locks the specified mutex.
*
* @param[in] mp pointer to the @p Mutex structure
*/
void chMtxLockS(Mutex *mp) {
Thread *ctp = currp;
chDbgCheck(mp != NULL, "chMtxLockS");
/* Ia the mutex already locked? */
if (mp->m_owner != NULL) {
/* 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 *tp = mp->m_owner;
/* Does the running thread have higher priority than the mutex
ownning 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 THD_STATE_WTMTX:
/* Re-enqueues the mutex owner with its new priority.*/
prio_insert(dequeue(tp), (ThreadsQueue *)tp->p_u.wtobjp);
tp = ((Mutex *)tp->p_u.wtobjp)->m_owner;
continue;
#if CH_USE_CONDVARS | CH_USE_SEMAPHORES_PRIORITY | CH_USE_MESSAGES_PRIORITY
#if CH_USE_CONDVARS
case THD_STATE_WTCOND:
#endif
#if CH_USE_SEMAPHORES_PRIORITY
case THD_STATE_WTSEM:
#endif
#if CH_USE_MESSAGES_PRIORITY
case THD_STATE_SNDMSG:
#endif
/* Re-enqueues tp with its new priority on the queue.*/
prio_insert(dequeue(tp), (ThreadsQueue *)tp->p_u.wtobjp);
break;
#endif
case THD_STATE_READY:
/* Re-enqueues tp with its new priority on the ready list.*/
chSchReadyI(dequeue(tp));
}
break;
}
/* Sleep on the mutex.*/
prio_insert(ctp, &mp->m_queue);
ctp->p_u.wtobjp = mp;
chSchGoSleepS(THD_STATE_WTMTX);
/* It is assumed that the thread performing the unlock operation assigns
the mutex to this thread.*/
chDbgAssert(mp->m_owner == ctp, "chMtxLockS(), #1", "not owner");
chDbgAssert(ctp->p_mtxlist == mp, "chMtxLockS(), #2", "not owned");
}
else {
/* 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 does not have any overhead related to
* the priority inheritance mechanism because it does not try to
* enter a sleep state on the mutex.
*
* @param[in] mp pointer to the @p Mutex structure
* @retval TRUE if the mutex was successfully acquired
* @retval FALSE if the lock attempt failed.
*/
bool_t chMtxTryLock(Mutex *mp) {
bool_t b;
chSysLock();
b = chMtxTryLockS(mp);
chSysUnlock();
return b;
}
/**
* @brief Tries to lock a mutex.
* @details This function does not have any overhead related to
* the priority inheritance mechanism because it does not try to
* enter a sleep state on the mutex.
*
* @param[in] mp pointer to the @p Mutex structure
* @retval TRUE if the mutex was successfully acquired
* @retval FALSE if the lock attempt failed.
*/
bool_t chMtxTryLockS(Mutex *mp) {
chDbgCheck(mp != NULL, "chMtxTryLockS");
if (mp->m_owner != NULL)
return FALSE;
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.
*
* @return The pointer to the unlocked mutex.
*/
Mutex *chMtxUnlock(void) {
Thread *ctp = currp;
Mutex *ump, *mp;
chSysLock();
chDbgAssert(ctp->p_mtxlist != NULL,
"chMtxUnlock(), #1",
"owned mutexes list empty");
chDbgAssert(ctp->p_mtxlist->m_owner == ctp,
"chMtxUnlock(), #2",
"ownership failure");
/* Removes the top Mutex from the Threads's owned mutexes list and matk it
as not owned.*/
ump = ctp->p_mtxlist;
ctp->p_mtxlist = ump->m_next;
/* If a thread is waiting on the mutex then the fun part begins.*/
if (chMtxQueueNotEmptyS(ump)) {
Thread *tp;
/* Recalculates the optimal thread priority by scanning the owned
mutexes list.*/
tprio_t newprio = ctp->p_realprio;
mp = ctp->p_mtxlist;
while (mp != 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(mp) && (mp->m_queue.p_next->p_prio > newprio))
newprio = mp->m_queue.p_next->p_prio;
mp = mp->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.*/
tp = fifo_remove(&ump->m_queue);
ump->m_owner = tp;
ump->m_next = tp->p_mtxlist;
tp->p_mtxlist = ump;
chSchWakeupS(tp, RDY_OK);
}
else
ump->m_owner = NULL;
chSysUnlock();
return ump;
}
/**
* @brief Unlocks the next owned mutex in reverse lock order.
* @note This function does not reschedule internally.
*
* @return The pointer to the unlocked mutex.
*/
Mutex *chMtxUnlockS(void) {
Thread *ctp = currp;
Mutex *ump, *mp;
chDbgAssert(ctp->p_mtxlist != NULL,
"chMtxUnlockS(), #1",
"owned mutexes list empty");
chDbgAssert(ctp->p_mtxlist->m_owner == ctp,
"chMtxUnlockS(), #2",
"ownership failure");
/* Removes the top Mutex from the owned mutexes list and marks it as not
owned.*/
ump = ctp->p_mtxlist;
ctp->p_mtxlist = ump->m_next;
/* If a thread is waiting on the mutex then the fun part begins.*/
if (chMtxQueueNotEmptyS(ump)) {
Thread *tp;
/* Recalculates the optimal thread priority by scanning the owned
mutexes list.*/
tprio_t newprio = ctp->p_realprio;
mp = ctp->p_mtxlist;
while (mp != 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(mp) && (mp->m_queue.p_next->p_prio > newprio))
newprio = mp->m_queue.p_next->p_prio;
mp = mp->m_next;
}
ctp->p_prio = newprio;
/* Awakens the highest priority thread waiting for the unlocked mutex and
assigns the mutex to it.*/
tp = fifo_remove(&ump->m_queue);
ump->m_owner = tp;
ump->m_next = tp->p_mtxlist;
tp->p_mtxlist = ump;
chSchReadyI(tp);
}
else
ump->m_owner = NULL;
return ump;
}
/**
* @brief Unlocks all the mutexes owned by the invoking thread.
* @details 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.
*/
void chMtxUnlockAll(void) {
Thread *ctp = currp;
chSysLock();
if (ctp->p_mtxlist != NULL) {
do {
Mutex *ump = ctp->p_mtxlist;
ctp->p_mtxlist = ump->m_next;
if (chMtxQueueNotEmptyS(ump)) {
Thread *tp = fifo_remove(&ump->m_queue);
ump->m_owner = tp;
ump->m_next = tp->p_mtxlist;
tp->p_mtxlist = ump;
chSchReadyI(tp);
}
else
ump->m_owner = NULL;
} while (ctp->p_mtxlist != NULL);
ctp->p_prio = ctp->p_realprio;
chSchRescheduleS();
}
chSysUnlock();
}
#endif /* CH_USE_MUTEXES */
/** @} */

View File

@@ -0,0 +1,363 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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.
* .
* In order to use the I/O queues the @p CH_USE_QUEUES option must
* be enabled in @p chconf.h.<br>
* I/O queues are usually used as an implementation layer for the I/O
* channels interface, also see @ref io_channels.
* @{
*/
#include "ch.h"
#if CH_USE_QUEUES
/**
* @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 InputQueue 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.
*/
void chIQInit(InputQueue *iqp, uint8_t *bp, size_t size, qnotify_t infy) {
iqp->q_buffer = iqp->q_rdptr = iqp->q_wrptr = bp;
iqp->q_top = bp + size;
iqp->q_notify = infy;
chSemInit(&iqp->q_sem, 0);
}
/**
* @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 InputQueue structure
*/
void chIQResetI(InputQueue *iqp) {
iqp->q_rdptr = iqp->q_wrptr = iqp->q_buffer;
chSemResetI(&iqp->q_sem, 0);
}
/**
* @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 InputQueue structure
* @param[in] b the byte value to be written in the queue
* @return The operation status, it can be one of:
* @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.
*/
msg_t chIQPutI(InputQueue *iqp, uint8_t b) {
if (chIQIsFull(iqp))
return Q_FULL;
*iqp->q_wrptr++ = b;
if (iqp->q_wrptr >= iqp->q_top)
iqp->q_wrptr = iqp->q_buffer;
chSemSignalI(&iqp->q_sem);
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.
*
* @param[in] iqp pointer to an @p InputQueue 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 or:
* @retval Q_TIMEOUT if the specified time expired.
* @retval Q_RESET if the queue was reset.
*/
msg_t chIQGetTimeout(InputQueue *iqp, systime_t time) {
uint8_t b;
msg_t msg;
chSysLock();
if (iqp->q_notify)
iqp->q_notify();
if ((msg = chSemWaitTimeoutS(&iqp->q_sem, time)) < RDY_OK) {
chSysUnlock();
return msg;
}
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 queue callback is invoked before entering a sleep state and at
* the end of the transfer.
*
* @param[in] iqp pointer to an @p InputQueue 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.
*/
size_t chIQReadTimeout(InputQueue *iqp, uint8_t *bp,
size_t n, systime_t time) {
qnotify_t nfy = iqp->q_notify;
size_t r = 0;
chDbgCheck(n > 0, "chIQReadTimeout");
chSysLock();
while (TRUE) {
if (chIQIsEmpty(iqp)) {
if (nfy)
nfy();
if ((chSemWaitTimeoutS(&iqp->q_sem, time) != RDY_OK)) {
chSysUnlock();
return r;
}
}
else
chSemFastWaitI(&iqp->q_sem);
*bp++ = *iqp->q_rdptr++;
if (iqp->q_rdptr >= iqp->q_top)
iqp->q_rdptr = iqp->q_buffer;
if (nfy)
nfy();
chSysUnlock(); /* Gives a preemption chance in a controlled point.*/
r++;
if (--n == 0) {
chSysLock();
if (nfy)
nfy();
chSysUnlock();
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 OutputQueue 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.
*/
void chOQInit(OutputQueue *oqp, uint8_t *bp, size_t size, qnotify_t onfy) {
oqp->q_buffer = oqp->q_rdptr = oqp->q_wrptr = bp;
oqp->q_top = bp + size;
oqp->q_notify = onfy;
chSemInit(&oqp->q_sem, (cnt_t)size);
}
/**
* @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 OutputQueue structure
*/
void chOQResetI(OutputQueue *oqp) {
oqp->q_rdptr = oqp->q_wrptr = oqp->q_buffer;
chSemResetI(&oqp->q_sem, (cnt_t)(oqp->q_top - oqp->q_buffer));
}
/**
* @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.
*
* @param[in] oqp pointer to an @p OutputQueue 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 was reset.
*/
msg_t chOQPutTimeout(OutputQueue *oqp, uint8_t b, systime_t time) {
msg_t msg;
chSysLock();
if ((msg = chSemWaitTimeoutS(&oqp->q_sem, time)) < RDY_OK) {
chSysUnlock();
return msg;
}
*oqp->q_wrptr++ = b;
if (oqp->q_wrptr >= oqp->q_top)
oqp->q_wrptr = oqp->q_buffer;
if (oqp->q_notify)
oqp->q_notify();
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 OutputQueue structure
* @return The byte value from the queue or:
* @retval Q_EMPTY if the queue is empty.
*/
msg_t chOQGetI(OutputQueue *oqp) {
uint8_t b;
if (chOQIsEmpty(oqp))
return Q_EMPTY;
b = *oqp->q_rdptr++;
if (oqp->q_rdptr >= oqp->q_top)
oqp->q_rdptr = oqp->q_buffer;
chSemSignalI(&oqp->q_sem);
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 queue callback is invoked before entering a sleep state and at
* the end of the transfer.
*
* @param[in] oqp pointer to an @p OutputQueue 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.
*/
size_t chOQWriteTimeout(OutputQueue *oqp, const uint8_t *bp,
size_t n, systime_t time) {
qnotify_t nfy = oqp->q_notify;
size_t w = 0;
chDbgCheck(n > 0, "chOQWriteTimeout");
chSysLock();
while (TRUE) {
if (chOQIsFull(oqp)) {
if (nfy)
nfy();
if ((chSemWaitTimeoutS(&oqp->q_sem, time) != RDY_OK)) {
chSysUnlock();
return w;
}
}
else
chSemFastWaitI(&oqp->q_sem);
*oqp->q_wrptr++ = *bp++;
if (oqp->q_wrptr >= oqp->q_top)
oqp->q_wrptr = oqp->q_buffer;
chSysUnlock(); /* Gives a preemption chance in a controlled point.*/
w++;
if (--n == 0) {
chSysLock();
if (nfy)
nfy();
chSysUnlock();
return w;
}
chSysLock();
}
}
#endif /* CH_USE_QUEUES */
/** @} */

View File

@@ -0,0 +1,114 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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, as 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.<br>
* In order to use the threads registry the @p CH_USE_REGISTRY option
* must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_REGISTRY
/**
* @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.
* @note A reference is added to the returned thread in order to make sure
* it 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 first thread.
*/
Thread *chRegFirstThread(void) {
Thread *tp;
chSysLock();
tp = rlist.r_newer;
#if CH_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.
*/
Thread *chRegNextThread(Thread *tp) {
Thread *ntp;
chSysLock();
ntp = tp->p_newer;
if (ntp == (Thread *)&rlist)
ntp = NULL;
#if CH_USE_DYNAMIC
else {
chDbgAssert(ntp->p_refs < 255, "chRegNextThread(), #1",
"too many references");
ntp->p_refs++;
}
#endif
chSysUnlock();
#if CH_USE_DYNAMIC
chThdRelease(tp);
#endif
return ntp;
}
#endif /* CH_USE_REGISTRY */
/** @} */

View File

@@ -0,0 +1,282 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @file chschd.c
* @brief Scheduler code.
*
* @addtogroup scheduler
* @details This module provides the default portable scheduler code,
* scheduler functions can be individually captured by the port
* layer in order to provide architecture optimized equivalents.
* When a function is captured its default code is not built into
* the OS image, the optimized version is included instead.
* @{
*/
#include "ch.h"
/**
* @brief Ready list header.
*/
#if !defined(PORT_OPTIMIZED_RLIST_VAR) || defined(__DOXYGEN__)
ReadyList rlist;
#endif /* !defined(PORT_OPTIMIZED_RLIST_VAR) */
/**
* @brief Scheduler initialization.
* @note Internally invoked by the @p chSysInit(), not an API.
*/
void scheduler_init(void) {
queue_init(&rlist.r_queue);
rlist.r_prio = NOPRIO;
#if CH_TIME_QUANTUM > 0
rlist.r_preempt = CH_TIME_QUANTUM;
#endif
#if CH_USE_REGISTRY
rlist.r_newer = rlist.r_older = (Thread *)&rlist;
#endif
}
/**
* @brief Inserts a thread in the Ready List.
* @note The function does not reschedule, the @p chSchRescheduleS() should
* be called soon after.
*
* @param[in] tp the Thread to be made ready
* @return The Thread pointer.
*/
#if !defined(PORT_OPTIMIZED_READYI) || defined(__DOXYGEN__)
#if CH_OPTIMIZE_SPEED
/* NOTE: it is inlined in this module only.*/
INLINE Thread *chSchReadyI(Thread *tp) {
#else
Thread *chSchReadyI(Thread *tp) {
#endif
Thread *cp;
tp->p_state = THD_STATE_READY;
cp = (Thread *)&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;
}
#endif /* !defined(PORT_OPTIMIZED_READYI) */
/**
* @brief Puts the current thread to sleep into the specified state.
* @details The thread goes into a sleeping state. The @ref thread_states are
* described into @p threads.h.
*
* @param[in] newstate the new thread state
*/
#if !defined(PORT_OPTIMIZED_GOSLEEPS) || defined(__DOXYGEN__)
void chSchGoSleepS(tstate_t newstate) {
Thread *otp;
(otp = currp)->p_state = newstate;
#if CH_TIME_QUANTUM > 0
rlist.r_preempt = CH_TIME_QUANTUM;
#endif
setcurrp(fifo_remove(&rlist.r_queue));
currp->p_state = THD_STATE_CURRENT;
chDbgTrace(otp);
chSysSwitchI(currp, otp);
}
#endif /* !defined(PORT_OPTIMIZED_GOSLEEPS) */
#if !defined(PORT_OPTIMIZED_GOSLEEPTIMEOUTS) || defined(__DOXYGEN__)
/*
* Timeout wakeup callback.
*/
static void wakeup(void *p) {
Thread *tp = (Thread *)p;
switch (tp->p_state) {
case THD_STATE_READY:
/* Handling the special case where the thread has been made ready by
another thread with higher priority.*/
return;
#if CH_USE_SEMAPHORES || (CH_USE_CONDVARS && CH_USE_CONDVARS_TIMEOUT)
#if CH_USE_SEMAPHORES
case THD_STATE_WTSEM:
chSemFastSignalI((Semaphore *)tp->p_u.wtobjp);
/* Falls into, intentional. */
#endif
#if CH_USE_CONDVARS && CH_USE_CONDVARS_TIMEOUT
case THD_STATE_WTCOND:
#endif
/* States requiring dequeuing.*/
dequeue(tp);
#endif
}
tp->p_u.rdymsg = RDY_TIMEOUT;
chSchReadyI(tp);
}
/**
* @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 RDY_TIMEOUT low level message. The @ref
* thread_states are described 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 accepted but
* interpreted as a normal time specification not as an
* immediate timeout specification.
* .
* @return The wakeup message.
* @retval RDY_TIMEOUT if a timeout occurs.
*/
msg_t chSchGoSleepTimeoutS(tstate_t newstate, systime_t time) {
if (TIME_INFINITE != time) {
VirtualTimer vt;
chVTSetI(&vt, time, wakeup, currp);
chSchGoSleepS(newstate);
if (chVTIsArmedI(&vt))
chVTResetI(&vt);
}
else
chSchGoSleepS(newstate);
return currp->p_u.rdymsg;
}
#endif /* !defined(PORT_OPTIMIZED_GOSLEEPTIMEOUTS) */
/**
* @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.
* @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 message to the awakened thread
*/
#if !defined(PORT_OPTIMIZED_WAKEUPS) || defined(__DOXYGEN__)
void chSchWakeupS(Thread *ntp, msg_t msg) {
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 *otp = chSchReadyI(currp);
#if CH_TIME_QUANTUM > 0
rlist.r_preempt = CH_TIME_QUANTUM;
#endif
setcurrp(ntp);
ntp->p_state = THD_STATE_CURRENT;
chDbgTrace(otp);
chSysSwitchI(ntp, otp);
}
}
#endif /* !defined(PORT_OPTIMIZED_WAKEUPS) */
/**
* @brief Switches to the first thread on the runnable queue.
* @note It is intended to be called if @p chSchRescRequiredI() evaluates
* to @p TRUE.
*/
#if !defined(PORT_OPTIMIZED_DORESCHEDULEI) || defined(__DOXYGEN__)
void chSchDoRescheduleI(void) {
Thread *otp;
#if CH_TIME_QUANTUM > 0
rlist.r_preempt = CH_TIME_QUANTUM;
#endif
otp = currp;
/* Picks the first thread from the ready queue and makes it current.*/
setcurrp(fifo_remove(&rlist.r_queue));
currp->p_state = THD_STATE_CURRENT;
chSchReadyI(otp);
chDbgTrace(otp);
chSysSwitchI(currp, otp);
}
#endif /* !defined(PORT_OPTIMIZED_DORESCHEDULEI) */
/**
* @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.
*/
#if !defined(PORT_OPTIMIZED_RESCHEDULES) || defined(__DOXYGEN__)
void chSchRescheduleS(void) {
if (chSchIsRescRequiredI())
chSchDoRescheduleI();
}
#endif /* !defined(PORT_OPTIMIZED_RESCHEDULES) */
/**
* @brief Evaluates if a reschedule is required.
* @details The decision is taken by comparing the relative priorities and
* depending on the state of the round robin timeout counter.
* @note This function is meant to be used in the timer interrupt handler
* where @p chVTDoTickI() is invoked.
*
* @retval TRUE if there is a thread that should go in running state.
* @retval FALSE if a reschedule is not required.
*/
#if !defined(PORT_OPTIMIZED_ISRESCHREQUIREDEXI) || defined(__DOXYGEN__)
bool_t chSchIsRescRequiredExI(void) {
tprio_t p1 = firstprio(&rlist.r_queue);
tprio_t p2 = currp->p_prio;
#if CH_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 rlist.r_preempt ? p1 > p2 : p1 >= p2;
#else
/* If the round robin preemption feature is not enabled then performs a
simpler comparison.*/
return p1 > p2;
#endif
}
#endif /* !defined(PORT_OPTIMIZED_ISRESCHREQUIREDEXI) */
/** @} */

View File

@@ -0,0 +1,291 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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 as example.<br>
* Semaphores usually use a FIFO queuing strategy but it is possible
* to make them order threads by priority by enabling
* @p CH_USE_SEMAPHORES_PRIORITY in @p chconf.h.<br>
* In order to use the Semaphores APIs the @p CH_USE_SEMAPHORES
* option must be enabled in @p chconf.h.
* @{
*/
#include "ch.h"
#if CH_USE_SEMAPHORES
#if CH_USE_SEMAPHORES_PRIORITY
#define sem_insert(tp, qp) prio_insert(tp, qp)
#else
#define sem_insert(tp, qp) queue_insert(tp, qp)
#endif
/**
* @brief Initializes a semaphore with the specified counter value.
*
* @param[out] sp pointer to a @p Semaphore structure
* @param[in] n initial value of the semaphore counter. Must be
* non-negative.
*/
void chSemInit(Semaphore *sp, cnt_t n) {
chDbgCheck((sp != NULL) && (n >= 0), "chSemInit");
queue_init(&sp->s_queue);
sp->s_cnt = n;
}
/**
* @brief Performs a reset operation on the semaphore.
* @note The released threads can recognize they were waked up by a reset
* rather than a signal because the @p chSemWait() will return
* @p RDY_RESET instead of @p RDY_OK.
*
* @param[in] sp pointer to a @p Semaphore structure
* @param[in] n the new value of the semaphore counter. The value must
* be non-negative.
*/
void chSemReset(Semaphore *sp, cnt_t n) {
chSysLock();
chSemResetI(sp, n);
chSchRescheduleS();
chSysUnlock();
}
/**
* @brief Performs a reset operation on the semaphore.
* @note The released threads can recognize they were waked up by a reset
* rather than a signal because the @p chSemWait() will return
* @p RDY_RESET instead of @p RDY_OK.
* @note This function does not reschedule.
*
* @param[in] sp pointer to a @p Semaphore structure
* @param[in] n the new value of the semaphore counter. The value must
* be non-negative.
*/
void chSemResetI(Semaphore *sp, cnt_t n) {
cnt_t cnt;
chDbgCheck((sp != NULL) && (n >= 0), "chSemResetI");
cnt = sp->s_cnt;
sp->s_cnt = n;
while (++cnt <= 0)
chSchReadyI(lifo_remove(&sp->s_queue))->p_u.rdymsg = RDY_RESET;
}
/**
* @brief Performs a wait operation on a semaphore.
*
* @param[in] sp pointer to a @p Semaphore structure
* @retval RDY_OK if the semaphore was signaled or not taken.
* @retval RDY_RESET if the semaphore was reset using @p chSemReset().
*/
msg_t chSemWait(Semaphore *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 structure
* @retval RDY_OK if the semaphore was signaled or not taken.
* @retval RDY_RESET if the semaphore was reset using @p chSemReset().
*/
msg_t chSemWaitS(Semaphore *sp) {
chDbgCheck(sp != NULL, "chSemWaitS");
if (--sp->s_cnt < 0) {
currp->p_u.wtobjp = sp;
sem_insert(currp, &sp->s_queue);
chSchGoSleepS(THD_STATE_WTSEM);
return currp->p_u.rdymsg;
}
return RDY_OK;
}
/**
* @brief Performs a wait operation on a semaphore with timeout specification.
*
* @param[in] sp pointer to a @p Semaphore 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.
* .
* @retval RDY_OK if the semaphore was signaled or not taken.
* @retval RDY_RESET if the semaphore was reset using @p chSemReset().
* @retval RDY_TIMEOUT if the semaphore was not signaled or reset within the
* specified timeout.
*/
msg_t chSemWaitTimeout(Semaphore *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 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.
* .
* @retval RDY_OK if the semaphore was signaled or not taken.
* @retval RDY_RESET if the semaphore was reset using @p chSemReset().
* @retval RDY_TIMEOUT if the semaphore was not signaled or reset within the
* specified timeout.
*/
msg_t chSemWaitTimeoutS(Semaphore *sp, systime_t time) {
chDbgCheck(sp != NULL, "chSemWaitTimeoutS");
if (--sp->s_cnt < 0) {
if (TIME_IMMEDIATE == time) {
sp->s_cnt++;
return RDY_TIMEOUT;
}
currp->p_u.wtobjp = sp;
sem_insert(currp, &sp->s_queue);
return chSchGoSleepTimeoutS(THD_STATE_WTSEM, time);
}
return RDY_OK;
}
/**
* @brief Performs a signal operation on a semaphore.
*
* @param[in] sp pointer to a @p Semaphore structure
*/
void chSemSignal(Semaphore *sp) {
chDbgCheck(sp != NULL, "chSemSignal");
chSysLock();
if (++sp->s_cnt <= 0)
chSchWakeupS(fifo_remove(&sp->s_queue), RDY_OK);
chSysUnlock();
}
/**
* @brief Performs a signal operation on a semaphore.
* @note This function does not reschedule.
*
* @param[in] sp pointer to a @p Semaphore structure
*/
void chSemSignalI(Semaphore *sp) {
chDbgCheck(sp != NULL, "chSemSignalI");
if (++sp->s_cnt <= 0) {
/* note, it is done this way in order to allow a tail call on
chSchReadyI().*/
Thread *tp = fifo_remove(&sp->s_queue);
tp->p_u.rdymsg = RDY_OK;
chSchReadyI(tp);
}
}
#if CH_USE_SEMSW
/**
* @brief Performs atomic signal and wait operations on two semaphores.
* @note The function is available only if the @p CH_USE_SEMSW
* option is enabled in @p chconf.h.
*
* @param[in] sps pointer to a @p Semaphore structure to be signaled
* @param[in] spw pointer to a @p Semaphore structure to be wait on
* @retval RDY_OK if the semaphore was signaled or not taken.
* @retval RDY_RESET if the semaphore was reset using @p chSemReset().
*/
msg_t chSemSignalWait(Semaphore *sps, Semaphore *spw) {
msg_t msg;
chDbgCheck((sps != NULL) && (spw != NULL), "chSemSignalWait");
chSysLock();
if (++sps->s_cnt <= 0)
chSchReadyI(fifo_remove(&sps->s_queue))->p_u.rdymsg = RDY_OK;
if (--spw->s_cnt < 0) {
Thread *ctp = currp;
sem_insert(ctp, &spw->s_queue);
ctp->p_u.wtobjp = spw;
chSchGoSleepS(THD_STATE_WTSEM);
msg = ctp->p_u.rdymsg;
}
else {
chSchRescheduleS();
msg = RDY_OK;
}
chSysUnlock();
return msg;
}
#endif /* CH_USE_SEMSW */
#endif /* CH_USE_SEMAPHORES */
/** @} */

View File

@@ -0,0 +1,145 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @file chsys.c
* @brief System related code.
*
* @addtogroup system
* @details System related APIs and services:
* - Initialization.
* - Locks.
* - Interrupt Handling.
* - Power Management.
* - Abnormal Termination.
* .
* @{
*/
#include "ch.h"
static WORKING_AREA(idle_thread_wa, IDLE_THREAD_STACK_SIZE);
/**
* @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;
while (TRUE) {
port_wait_for_interrupt();
IDLE_LOOP_HOOK();
}
}
/**
* @brief ChibiOS/RT initialization.
* @details After executing this function the current instructions stream
* becomes the main thread.
* @note Interrupts should be still disabled when @p chSysInit() is invoked
* and are internally enabled.
* @note The main thread is created with priority @p NORMALPRIO.
*/
void chSysInit(void) {
static Thread mainthread;
port_init();
scheduler_init();
vt_init();
#if CH_USE_MEMCORE
core_init();
#endif
#if CH_USE_HEAP
heap_init();
#endif
#if CH_DBG_ENABLE_TRACE
trace_init();
#endif
/* Now this instructions flow becomes the main thread.*/
setcurrp(init_thread(&mainthread, NORMALPRIO));
currp->p_state = THD_STATE_CURRENT;
chSysEnable();
/* 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);
}
/**
* @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_TIME_QUANTUM macro, the round robin
* interval.
*/
void chSysTimerHandlerI(void) {
#if CH_TIME_QUANTUM > 0
/* Running thread has not used up quantum yet? */
if (rlist.r_preempt > 0)
/* Decrement remaining quantum.*/
rlist.r_preempt--;
#endif
#if CH_DBG_THREADS_PROFILING
currp->p_time++;
#endif
chVTDoTickI();
}
#if CH_USE_NESTED_LOCKS && !CH_OPTIMIZE_SPEED
void chSysLock(void) {
chDbgAssert(currp->p_locks >= 0,
"chSysLock(), #1",
"negative nesting counter");
if (currp->p_locks++ == 0)
port_lock();
}
void chSysUnlock(void) {
chDbgAssert(currp->p_locks > 0,
"chSysUnlock(), #1",
"non-positive nesting counter");
if (--currp->p_locks == 0)
port_unlock();
}
#endif /* CH_USE_NESTED_LOCKS && !CH_OPTIMIZE_SPEED */
/** @} */

View File

@@ -0,0 +1,522 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @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>Init</b>, a thread is prepared and put in the suspended
* state.
* - <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_USE_WAITEXIT and @p CH_USE_DYNAMIC configuration
* options.
* @{
*/
#include "ch.h"
/**
* @brief Initializes a thread structure.
*
* @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.
*/
Thread *init_thread(Thread *tp, tprio_t prio) {
tp->p_prio = prio;
tp->p_state = THD_STATE_SUSPENDED;
tp->p_flags = THD_MEM_MODE_STATIC;
#if CH_USE_MUTEXES
tp->p_realprio = prio;
tp->p_mtxlist = NULL;
#endif
#if CH_USE_EVENTS
tp->p_epending = 0;
#endif
#if CH_USE_NESTED_LOCKS
tp->p_locks = 0;
#endif
#if CH_DBG_THREADS_PROFILING
tp->p_time = 0;
#endif
#if CH_USE_DYNAMIC
tp->p_refs = 1;
#endif
#if CH_USE_WAITEXIT
list_init(&tp->p_waiting);
#endif
#if CH_USE_MESSAGES
queue_init(&tp->p_msgqueue);
#endif
#if CH_USE_REGISTRY
REG_INSERT(tp);
#endif
#if defined(THREAD_EXT_INIT)
THREAD_EXT_INIT(tp);
#endif
return tp;
}
#if CH_DBG_FILL_THREADS
static void memfill(uint8_t *startp, uint8_t *endp, uint8_t v) {
while (startp < endp)
*startp++ = v;
}
#endif
/**
* @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 THD_STATE_SUSPENDED.
* @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 structure allocated for
* the thread into the working space area.
*/
Thread *chThdCreateI(void *wsp, size_t size,
tprio_t prio, tfunc_t pf, void *arg) {
/* Thread structure is layed out in the lower part of the thread workspace */
Thread *tp = wsp;
chDbgCheck((wsp != NULL) && (size >= THD_WA_SIZE(0)) &&
(prio <= HIGHPRIO) && (pf != NULL),
"chThdCreateI");
SETUP_CONTEXT(wsp, size, pf, arg);
return init_thread(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 structure allocated for
* the thread into the working space area.
*/
Thread *chThdCreateStatic(void *wsp, size_t size,
tprio_t prio, tfunc_t pf, void *arg) {
Thread *tp;
#if CH_DBG_FILL_THREADS
memfill((uint8_t *)wsp, (uint8_t *)wsp + sizeof(Thread), THREAD_FILL_VALUE);
memfill((uint8_t *)wsp + sizeof(Thread),
(uint8_t *)wsp + size, STACK_FILL_VALUE);
#endif
chSysLock();
chSchWakeupS(tp = chThdCreateI(wsp, size, prio, pf, arg), RDY_OK);
chSysUnlock();
return tp;
}
#if CH_USE_DYNAMIC && CH_USE_HEAP
/**
* @brief Creates a new thread allocating the memory from the heap.
* @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.
* @note The function is available only if the @p CH_USE_DYNAMIC,
* @p CH_USE_HEAP and @p CH_USE_WAITEXIT options are enabled
* in @p chconf.h.
*
* @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 structure allocated for
* the thread into the working space area.
* @retval NULL if the memory cannot be allocated.
*/
Thread *chThdCreateFromHeap(MemoryHeap *heapp, size_t size,
tprio_t prio, tfunc_t pf, void *arg) {
void *wsp;
Thread *tp;
wsp = chHeapAlloc(heapp, size);
if (wsp == NULL)
return NULL;
#if CH_DBG_FILL_THREADS
memfill((uint8_t *)wsp, (uint8_t *)wsp + sizeof(Thread), THREAD_FILL_VALUE);
memfill((uint8_t *)wsp + sizeof(Thread),
(uint8_t *)wsp + size, STACK_FILL_VALUE);
#endif
chSysLock();
tp = chThdCreateI(wsp, size, prio, pf, arg);
tp->p_flags = THD_MEM_MODE_HEAP;
chSchWakeupS(tp, RDY_OK);
chSysUnlock();
return tp;
}
#endif /* CH_USE_DYNAMIC && CH_USE_HEAP */
#if CH_USE_DYNAMIC && CH_USE_MEMPOOLS
/**
* @brief Creates a new thread allocating the memory from the specified
* memory pool.
* @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.
* @note The function is available only if the @p CH_USE_DYNAMIC,
* @p CH_USE_MEMPOOLS and @p CH_USE_WAITEXIT options are enabled
* in @p chconf.h.
*
* @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 structure allocated for
* the thread into the working space area.
* @retval NULL if the memory pool is empty.
*/
Thread *chThdCreateFromMemoryPool(MemoryPool *mp, tprio_t prio,
tfunc_t pf, void *arg) {
void *wsp;
Thread *tp;
chDbgCheck(mp != NULL, "chThdCreateFromMemoryPool");
wsp = chPoolAlloc(mp);
if (wsp == NULL)
return NULL;
#if CH_DBG_FILL_THREADS
memfill((uint8_t *)wsp, (uint8_t *)wsp + sizeof(Thread), THREAD_FILL_VALUE);
memfill((uint8_t *)wsp + sizeof(Thread),
(uint8_t *)wsp + mp->mp_object_size, STACK_FILL_VALUE);
#endif
chSysLock();
tp = chThdCreateI(wsp, mp->mp_object_size, prio, pf, arg);
tp->p_flags = THD_MEM_MODE_MEMPOOL;
tp->p_mpool = mp;
chSchWakeupS(tp, RDY_OK);
chSysUnlock();
return tp;
}
#endif /* CH_USE_DYNAMIC && CH_USE_MEMPOOLS */
/**
* @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.
*/
tprio_t chThdSetPriority(tprio_t newprio) {
tprio_t oldprio;
chDbgCheck((newprio >= LOWPRIO) && (newprio <= HIGHPRIO),
"chThdSetPriority");
chSysLock();
#if CH_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 Resumes a suspended thread.
* @note Use this function to resume threads created with @p chThdInit().
*
* @param[in] tp pointer to the thread
* @return The pointer to the thread.
*/
Thread *chThdResume(Thread *tp) {
chSysLock();
chDbgAssert(tp->p_state == THD_STATE_SUSPENDED,
"chThdResume(), #1",
"thread not in THD_STATE_SUSPENDED state");
chSchWakeupS(tp, RDY_OK);
chSysUnlock();
return tp;
}
/**
* @brief Requests a thread termination.
* @note The thread is not terminated but a termination request is added to
* its @p p_flags field. The thread can read this status by
* invoking @p chThdShouldTerminate() and then terminate cleanly.
*
* @param[in] tp pointer to the thread
*/
void chThdTerminate(Thread *tp) {
chSysLock();
tp->p_flags |= THD_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 accepted but
* interpreted as a normal time specification not as an
* immediate timeout specification.
* .
*/
void chThdSleep(systime_t time) {
chDbgCheck(time != TIME_INFINITE, "chThdSleep");
chSysLock();
chThdSleepS(time);
chSysUnlock();
}
/**
* @brief Suspends the invoking thread until the system time arrives to the
* specified value.
*
* @param[in] time absolute system time
*/
void chThdSleepUntil(systime_t time) {
chSysLock();
if ((time -= chTimeNow()) > 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.
*/
void chThdYield(void) {
chSysLock();
chSchDoYieldS();
chSysUnlock();
}
/**
* @brief Terminates the current thread by specifying an exit status code.
*
* @param[in] msg thread exit code. The code can be retrieved by using
* @p chThdWait().
*/
void chThdExit(msg_t msg) {
Thread *tp = currp;
chSysLock();
tp->p_u.exitcode = msg;
#if defined(THREAD_EXT_EXIT)
THREAD_EXT_EXIT(tp);
#endif
#if CH_USE_WAITEXIT
while (notempty(&tp->p_waiting))
chSchReadyI(list_remove(&tp->p_waiting));
#endif
#if CH_USE_REGISTRY
/* Static threads are immediately removed from the registry because
there is no memory to recover.*/
if ((tp->p_flags & THD_MEM_MODE_MASK) == THD_MEM_MODE_STATIC)
REG_REMOVE(tp);
#endif
chSchGoSleepS(THD_STATE_FINAL);
}
#if CH_USE_DYNAMIC || defined(__DOXYGEN__)
/**
* @brief Adds a reference to a thread object.
*
* @param[in] tp pointer to the thread
* @return The same thread pointer passed as parameter
* representing the new reference.
*/
Thread *chThdAddRef(Thread *tp) {
chSysLock();
chDbgAssert(tp->p_refs < 255, "chThdAddRef(), #1", "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 THD_STATE_FINAL state then the thread's memory is
* returned to the proper allocator.
* @note Static threads are not affected.
*
* @param[in] tp pointer to the thread
*/
void chThdRelease(Thread *tp) {
trefs_t refs;
chSysLock();
chDbgAssert(tp->p_refs > 0, "chThdRelease(), #1", "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 == THD_STATE_FINAL)) {
switch (tp->p_flags & THD_MEM_MODE_MASK) {
#if CH_USE_HEAP
case THD_MEM_MODE_HEAP:
#if CH_USE_REGISTRY
REG_REMOVE(tp);
#endif
chHeapFree(tp);
break;
#endif
#if CH_USE_MEMPOOLS
case THD_MEM_MODE_MEMPOOL:
#if CH_USE_REGISTRY
REG_REMOVE(tp);
#endif
chPoolFree(tp->p_mpool, tp);
break;
#endif
}
}
}
#endif /* CH_USE_DYNAMIC */
#if CH_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 chThdInit() 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.
* .
* Please read the @ref article_lifecycle article for more details.
* @note After invoking @p chThdWait() the thread pointer becomes invalid
* and must not be used as parameter for further system calls.
* @note The function is available only if the @p CH_USE_WAITEXIT
* option is enabled in @p chconf.h.
* @note If @p CH_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.
*/
msg_t chThdWait(Thread *tp) {
msg_t msg;
chDbgCheck(tp != NULL, "chThdWait");
chSysLock();
chDbgAssert(tp != currp, "chThdWait(), #1", "waiting self");
#if CH_USE_DYNAMIC
chDbgAssert(tp->p_refs > 0, "chThdWait(), #2", "not referenced");
#endif
if (tp->p_state != THD_STATE_FINAL) {
list_insert(currp, &tp->p_waiting);
chSchGoSleepS(THD_STATE_WTEXIT);
}
msg = tp->p_u.exitcode;
chSysUnlock();
#if CH_USE_DYNAMIC
chThdRelease(tp);
#endif
return msg;
}
#endif /* CH_USE_WAITEXIT */
/** @} */

View File

@@ -0,0 +1,129 @@
/*
ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010 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/>.
---
A special exception to the GPL can be applied should you wish to distribute
a combined work that includes ChibiOS/RT, without being obliged to provide
the source code for any proprietary components. See the file exception.txt
for full details of how and when the exception can be applied.
*/
/**
* @file chvt.c
* @brief Time and Virtual Timers related code.
*
* @addtogroup time
* @details Time and Virtual Timers related APIs and services.
* @{
*/
#include "ch.h"
/**
* @brief Virtual timers delta list header.
*/
VTList vtlist;
/**
* @brief Virtual Timers initialization.
* @note Internal use only.
*/
void vt_init(void) {
vtlist.vt_next = vtlist.vt_prev = (void *)&vtlist;
vtlist.vt_time = (systime_t)-1;
vtlist.vt_systime = 0;
}
/**
* @brief Enables a virtual timer.
* @note The associated function is invoked by an interrupt handler within
* the I-Locked state, see @ref system_states.
*
* @param[out] vtp the @p VirtualTimer structure pointer
* @param[in] time the number of time ticks, the value @p TIME_INFINITE
* is notallowed. The value @p TIME_IMMEDIATE is allowed
* but interpreted as a normal time specification not as
* an immediate timeout specification.
* @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
*/
void chVTSetI(VirtualTimer *vtp, systime_t time, vtfunc_t vtfunc, void *par) {
VirtualTimer *p;
chDbgCheck((vtp != NULL) && (vtfunc != NULL) && (time != TIME_INFINITE),
"chVTSetI");
vtp->vt_par = par;
vtp->vt_func = vtfunc;
p = vtlist.vt_next;
while (p->vt_time < time) {
time -= p->vt_time;
p = p->vt_next;
}
vtp->vt_prev = (vtp->vt_next = p)->vt_prev;
vtp->vt_prev->vt_next = p->vt_prev = vtp;
vtp->vt_time = time;
if (p != (void *)&vtlist)
p->vt_time -= time;
}
/**
* @brief Disables a Virtual Timer.
* @note The timer MUST be active when this function is invoked.
*
* @param[in] vtp the @p VirtualTimer structure pointer
*/
void chVTResetI(VirtualTimer *vtp) {
chDbgCheck(vtp != NULL, "chVTResetI");
chDbgAssert(vtp->vt_func != NULL,
"chVTResetI(), #1",
"timer not set or already triggered");
if (vtp->vt_next != (void *)&vtlist)
vtp->vt_next->vt_time += vtp->vt_time;
vtp->vt_prev->vt_next = vtp->vt_next;
vtp->vt_next->vt_prev = vtp->vt_prev;
vtp->vt_func = (vtfunc_t)NULL;
}
/**
* @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.
*/
bool_t chTimeIsWithin(systime_t start, systime_t end) {
systime_t time = chTimeNow();
return end > start ? (time >= start) && (time < end) :
(time >= start) || (time < end);
}
/** @} */