timers.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. /*
  2. FreeRTOS V8.2.0 - Copyright (C) 2015 Real Time Engineers Ltd.
  3. All rights reserved
  4. VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
  5. This file is part of the FreeRTOS distribution.
  6. FreeRTOS is free software; you can redistribute it and/or modify it under
  7. the terms of the GNU General Public License (version 2) as published by the
  8. Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
  9. ***************************************************************************
  10. >>! NOTE: The modification to the GPL is included to allow you to !<<
  11. >>! distribute a combined work that includes FreeRTOS without being !<<
  12. >>! obliged to provide the source code for proprietary components !<<
  13. >>! outside of the FreeRTOS kernel. !<<
  14. ***************************************************************************
  15. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
  16. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  17. FOR A PARTICULAR PURPOSE. Full license text is available on the following
  18. link: http://www.freertos.org/a00114.html
  19. ***************************************************************************
  20. * *
  21. * FreeRTOS provides completely free yet professionally developed, *
  22. * robust, strictly quality controlled, supported, and cross *
  23. * platform software that is more than just the market leader, it *
  24. * is the industry's de facto standard. *
  25. * *
  26. * Help yourself get started quickly while simultaneously helping *
  27. * to support the FreeRTOS project by purchasing a FreeRTOS *
  28. * tutorial book, reference manual, or both: *
  29. * http://www.FreeRTOS.org/Documentation *
  30. * *
  31. ***************************************************************************
  32. http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
  33. the FAQ page "My application does not run, what could be wrong?". Have you
  34. defined configASSERT()?
  35. http://www.FreeRTOS.org/support - In return for receiving this top quality
  36. embedded software for free we request you assist our global community by
  37. participating in the support forum.
  38. http://www.FreeRTOS.org/training - Investing in training allows your team to
  39. be as productive as possible as early as possible. Now you can receive
  40. FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
  41. Ltd, and the world's leading authority on the world's leading RTOS.
  42. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
  43. including FreeRTOS+Trace - an indispensable productivity tool, a DOS
  44. compatible FAT file system, and our tiny thread aware UDP/IP stack.
  45. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
  46. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
  47. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
  48. Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
  49. licenses offer ticketed support, indemnification and commercial middleware.
  50. http://www.SafeRTOS.com - High Integrity Systems also provide a safety
  51. engineered and independently SIL3 certified version for use in safety and
  52. mission critical applications that require provable dependability.
  53. 1 tab == 4 spaces!
  54. */
  55. /* Standard includes. */
  56. #include <stdlib.h>
  57. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  58. all the API functions to use the MPU wrappers. That should only be done when
  59. task.h is included from an application file. */
  60. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  61. #include "FreeRTOS.h"
  62. #include "task.h"
  63. #include "queue.h"
  64. #include "timers.h"
  65. #include "portmacro.h"
  66. #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 )
  67. #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
  68. #endif
  69. /* Lint e961 and e750 are suppressed as a MISRA exception justified because the
  70. MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
  71. header files above, but not in this file, in order to generate the correct
  72. privileged Vs unprivileged linkage and placement. */
  73. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
  74. /* This entire source file will be skipped if the application is not configured
  75. to include software timer functionality. This #if is closed at the very bottom
  76. of this file. If you want to include software timer functionality then ensure
  77. configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
  78. #if ( configUSE_TIMERS == 1 )
  79. /* Misc definitions. */
  80. #define tmrNO_DELAY ( TickType_t ) 0U
  81. /* The definition of the timers themselves. */
  82. typedef struct tmrTimerControl
  83. {
  84. const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  85. ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */
  86. TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */
  87. UBaseType_t uxAutoReload; /*<< Set to pdTRUE if the timer should be automatically restarted once expired. Set to pdFALSE if the timer is, in effect, a one-shot timer. */
  88. void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */
  89. TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */
  90. #if( configUSE_TRACE_FACILITY == 1 )
  91. UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */
  92. #endif
  93. #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
  94. uint8_t ucStaticallyAllocated; /*<< Set to pdTRUE if the timer was created statically so no attempt is made to free the memory again if the timer is later deleted. */
  95. #endif
  96. } xTIMER;
  97. /* The old xTIMER name is maintained above then typedefed to the new Timer_t
  98. name below to enable the use of older kernel aware debuggers. */
  99. typedef xTIMER Timer_t;
  100. /* The definition of messages that can be sent and received on the timer queue.
  101. Two types of message can be queued - messages that manipulate a software timer,
  102. and messages that request the execution of a non-timer related callback. The
  103. two message types are defined in two separate structures, xTimerParametersType
  104. and xCallbackParametersType respectively. */
  105. typedef struct tmrTimerParameters
  106. {
  107. TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
  108. Timer_t * pxTimer; /*<< The timer to which the command will be applied. */
  109. } TimerParameter_t;
  110. typedef struct tmrCallbackParameters
  111. {
  112. PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */
  113. void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */
  114. uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */
  115. } CallbackParameters_t;
  116. /* The structure that contains the two message types, along with an identifier
  117. that is used to determine which message type is valid. */
  118. typedef struct tmrTimerQueueMessage
  119. {
  120. BaseType_t xMessageID; /*<< The command being sent to the timer service task. */
  121. union
  122. {
  123. TimerParameter_t xTimerParameters;
  124. /* Don't include xCallbackParameters if it is not going to be used as
  125. it makes the structure (and therefore the timer queue) larger. */
  126. #if ( INCLUDE_xTimerPendFunctionCall == 1 )
  127. CallbackParameters_t xCallbackParameters;
  128. #endif /* INCLUDE_xTimerPendFunctionCall */
  129. } u;
  130. } DaemonTaskMessage_t;
  131. /*lint -e956 A manual analysis and inspection has been used to determine which
  132. static variables must be declared volatile. */
  133. /* The list in which active timers are stored. Timers are referenced in expire
  134. time order, with the nearest expiry time at the front of the list. Only the
  135. timer service task is allowed to access these lists. */
  136. PRIVILEGED_DATA static List_t xActiveTimerList1;
  137. PRIVILEGED_DATA static List_t xActiveTimerList2;
  138. PRIVILEGED_DATA static List_t *pxCurrentTimerList;
  139. PRIVILEGED_DATA static List_t *pxOverflowTimerList;
  140. /* A queue that is used to send commands to the timer service task. */
  141. PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
  142. /* Mux. We use a single mux for all the timers for now. ToDo: maybe increase granularity here? */
  143. PRIVILEGED_DATA portMUX_TYPE xTimerMux = portMUX_INITIALIZER_UNLOCKED;
  144. #if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
  145. PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
  146. #endif
  147. /*lint +e956 */
  148. /*-----------------------------------------------------------*/
  149. /*
  150. * Initialise the infrastructure used by the timer service task if it has not
  151. * been initialised already.
  152. */
  153. static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;
  154. /*
  155. * The timer service task (daemon). Timer functionality is controlled by this
  156. * task. Other tasks communicate with the timer service task using the
  157. * xTimerQueue queue.
  158. */
  159. static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION;
  160. /*
  161. * Called by the timer service task to interpret and process a command it
  162. * received on the timer queue.
  163. */
  164. static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;
  165. /*
  166. * Insert the timer into either xActiveTimerList1, or xActiveTimerList2,
  167. * depending on if the expire time causes a timer counter overflow.
  168. */
  169. static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION;
  170. /*
  171. * An active timer has reached its expire time. Reload the timer if it is an
  172. * auto reload timer, then call its callback.
  173. */
  174. static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION;
  175. /*
  176. * The tick count has overflowed. Switch the timer lists after ensuring the
  177. * current timer list does not still reference some timers.
  178. */
  179. static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION;
  180. /*
  181. * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE
  182. * if a tick count overflow occurred since prvSampleTimeNow() was last called.
  183. */
  184. static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;
  185. /*
  186. * If the timer list contains any active timers then return the expire time of
  187. * the timer that will expire first and set *pxListWasEmpty to false. If the
  188. * timer list does not contain any timers then return 0 and set *pxListWasEmpty
  189. * to pdTRUE.
  190. */
  191. static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION;
  192. /*
  193. * If a timer has expired, process it. Otherwise, block the timer service task
  194. * until either a timer does expire or a command is received.
  195. */
  196. static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, const BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION;
  197. /*
  198. * Called after a Timer_t structure has been allocated either statically or
  199. * dynamically to fill in the structure's members.
  200. */
  201. static void prvInitialiseNewTimer( const char * const pcTimerName,
  202. const TickType_t xTimerPeriodInTicks,
  203. const UBaseType_t uxAutoReload,
  204. void * const pvTimerID,
  205. TimerCallbackFunction_t pxCallbackFunction,
  206. Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  207. /*-----------------------------------------------------------*/
  208. BaseType_t xTimerCreateTimerTask( void )
  209. {
  210. BaseType_t xReturn = pdFAIL;
  211. /* This function is called when the scheduler is started if
  212. configUSE_TIMERS is set to 1. Check that the infrastructure used by the
  213. timer service task has been created/initialised. If timers have already
  214. been created then the initialisation will already have been performed. */
  215. /* For now, the timer task will be fixed to core 0. This means whatever process
  216. running on whatever core schedules the timer, the timer callback function
  217. will *ALWAYS* run on core 0. */
  218. prvCheckForValidListAndQueue();
  219. if( xTimerQueue != NULL )
  220. {
  221. /* Although static allocation has been backported from FreeRTOS v9.0.0,
  222. the timer task is still allocated dynamically. The actual timers
  223. however can be allocated statically.*/
  224. #if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
  225. {
  226. /* Create the timer task, storing its handle in xTimerTaskHandle so
  227. it can be returned by the xTimerGetTimerDaemonTaskHandle() function. */
  228. xReturn = xTaskCreatePinnedToCore( prvTimerTask, "Tmr Svc", ( uint16_t ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, &xTimerTaskHandle, 0 );
  229. }
  230. #else
  231. {
  232. /* Create the timer task without storing its handle. */
  233. xReturn = xTaskCreatePinnedToCore( prvTimerTask, "Tmr Svc", ( uint16_t ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, NULL, 0 );
  234. }
  235. #endif
  236. }
  237. else
  238. {
  239. mtCOVERAGE_TEST_MARKER();
  240. }
  241. configASSERT( xReturn );
  242. return xReturn;
  243. }
  244. /*-----------------------------------------------------------*/
  245. #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
  246. TimerHandle_t xTimerCreate( const char * const pcTimerName,
  247. const TickType_t xTimerPeriodInTicks,
  248. const UBaseType_t uxAutoReload,
  249. void * const pvTimerID,
  250. TimerCallbackFunction_t pxCallbackFunction ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  251. {
  252. Timer_t *pxNewTimer;
  253. pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) );
  254. if( pxNewTimer != NULL )
  255. {
  256. prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
  257. #if( configSUPPORT_STATIC_ALLOCATION == 1 )
  258. {
  259. /* Timers can be created statically or dynamically, so note this
  260. timer was created dynamically in case the timer is later
  261. deleted. */
  262. pxNewTimer->ucStaticallyAllocated = pdFALSE;
  263. }
  264. #endif /* configSUPPORT_STATIC_ALLOCATION */
  265. }
  266. return pxNewTimer;
  267. }
  268. #endif /* configSUPPORT_STATIC_ALLOCATION */
  269. /*-----------------------------------------------------------*/
  270. #if( configSUPPORT_STATIC_ALLOCATION == 1 )
  271. TimerHandle_t xTimerCreateStatic( const char * const pcTimerName,
  272. const TickType_t xTimerPeriodInTicks,
  273. const UBaseType_t uxAutoReload,
  274. void * const pvTimerID,
  275. TimerCallbackFunction_t pxCallbackFunction,
  276. StaticTimer_t *pxTimerBuffer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  277. {
  278. Timer_t *pxNewTimer;
  279. #if( configASSERT_DEFINED == 1 )
  280. {
  281. /* Sanity check that the size of the structure used to declare a
  282. variable of type StaticTimer_t equals the size of the real timer
  283. structures. */
  284. volatile size_t xSize = sizeof( StaticTimer_t );
  285. configASSERT( xSize == sizeof( Timer_t ) );
  286. ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */
  287. }
  288. #endif /* configASSERT_DEFINED */
  289. /* A pointer to a StaticTimer_t structure MUST be provided, use it. */
  290. configASSERT( pxTimerBuffer );
  291. pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */
  292. if( pxNewTimer != NULL )
  293. {
  294. prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
  295. #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
  296. {
  297. /* Timers can be created statically or dynamically so note this
  298. timer was created statically in case it is later deleted. */
  299. pxNewTimer->ucStaticallyAllocated = pdTRUE;
  300. }
  301. #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
  302. }
  303. return pxNewTimer;
  304. }
  305. #endif /* configSUPPORT_STATIC_ALLOCATION */
  306. /*-----------------------------------------------------------*/
  307. static void prvInitialiseNewTimer( const char * const pcTimerName,
  308. const TickType_t xTimerPeriodInTicks,
  309. const UBaseType_t uxAutoReload,
  310. void * const pvTimerID,
  311. TimerCallbackFunction_t pxCallbackFunction,
  312. Timer_t *pxNewTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  313. {
  314. /* 0 is not a valid value for xTimerPeriodInTicks. */
  315. configASSERT( ( xTimerPeriodInTicks > 0 ) );
  316. if( pxNewTimer != NULL )
  317. {
  318. /* Ensure the infrastructure used by the timer service task has been
  319. created/initialised. */
  320. prvCheckForValidListAndQueue();
  321. /* Initialise the timer structure members using the function
  322. parameters. */
  323. pxNewTimer->pcTimerName = pcTimerName;
  324. pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
  325. pxNewTimer->uxAutoReload = uxAutoReload;
  326. pxNewTimer->pvTimerID = pvTimerID;
  327. pxNewTimer->pxCallbackFunction = pxCallbackFunction;
  328. vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );
  329. traceTIMER_CREATE( pxNewTimer );
  330. }
  331. }
  332. /*-----------------------------------------------------------*/
  333. BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait )
  334. {
  335. BaseType_t xReturn = pdFAIL;
  336. DaemonTaskMessage_t xMessage;
  337. /* Send a message to the timer service task to perform a particular action
  338. on a particular timer definition. */
  339. if( xTimerQueue != NULL )
  340. {
  341. /* Send a command to the timer service task to start the xTimer timer. */
  342. xMessage.xMessageID = xCommandID;
  343. xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
  344. xMessage.u.xTimerParameters.pxTimer = ( Timer_t * ) xTimer;
  345. if( xCommandID < tmrFIRST_FROM_ISR_COMMAND )
  346. {
  347. if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
  348. {
  349. xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
  350. }
  351. else
  352. {
  353. xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
  354. }
  355. }
  356. else
  357. {
  358. xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
  359. }
  360. traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
  361. }
  362. else
  363. {
  364. mtCOVERAGE_TEST_MARKER();
  365. }
  366. return xReturn;
  367. }
  368. /*-----------------------------------------------------------*/
  369. #if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
  370. TaskHandle_t xTimerGetTimerDaemonTaskHandle( void )
  371. {
  372. /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
  373. started, then xTimerTaskHandle will be NULL. */
  374. configASSERT( ( xTimerTaskHandle != NULL ) );
  375. return xTimerTaskHandle;
  376. }
  377. #endif
  378. /*-----------------------------------------------------------*/
  379. TickType_t xTimerGetPeriod( TimerHandle_t xTimer )
  380. {
  381. Timer_t *pxTimer = ( Timer_t * ) xTimer;
  382. configASSERT( xTimer );
  383. return pxTimer->xTimerPeriodInTicks;
  384. }
  385. /*-----------------------------------------------------------*/
  386. TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer )
  387. {
  388. Timer_t * pxTimer = ( Timer_t * ) xTimer;
  389. TickType_t xReturn;
  390. configASSERT( xTimer );
  391. xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
  392. return xReturn;
  393. }
  394. /*-----------------------------------------------------------*/
  395. const char * pcTimerGetTimerName( TimerHandle_t xTimer )
  396. {
  397. Timer_t *pxTimer = ( Timer_t * ) xTimer;
  398. return pxTimer->pcTimerName;
  399. }
  400. /*-----------------------------------------------------------*/
  401. static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow )
  402. {
  403. BaseType_t xResult;
  404. Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
  405. /* Remove the timer from the list of active timers. A check has already
  406. been performed to ensure the list is not empty. */
  407. ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
  408. traceTIMER_EXPIRED( pxTimer );
  409. /* If the timer is an auto reload timer then calculate the next
  410. expiry time and re-insert the timer in the list of active timers. */
  411. if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
  412. {
  413. /* The timer is inserted into a list using a time relative to anything
  414. other than the current time. It will therefore be inserted into the
  415. correct list relative to the time this task thinks it is now. */
  416. if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) == pdTRUE )
  417. {
  418. /* The timer expired before it was added to the active timer
  419. list. Reload it now. */
  420. xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
  421. configASSERT( xResult );
  422. ( void ) xResult;
  423. }
  424. else
  425. {
  426. mtCOVERAGE_TEST_MARKER();
  427. }
  428. }
  429. else
  430. {
  431. mtCOVERAGE_TEST_MARKER();
  432. }
  433. /* Call the timer callback. */
  434. pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
  435. }
  436. /*-----------------------------------------------------------*/
  437. static void prvTimerTask( void *pvParameters )
  438. {
  439. TickType_t xNextExpireTime;
  440. BaseType_t xListWasEmpty;
  441. /* Just to avoid compiler warnings. */
  442. ( void ) pvParameters;
  443. for( ;; )
  444. {
  445. /* Query the timers list to see if it contains any timers, and if so,
  446. obtain the time at which the next timer will expire. */
  447. xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
  448. /* If a timer has expired, process it. Otherwise, block this task
  449. until either a timer does expire, or a command is received. */
  450. prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
  451. /* Empty the command queue. */
  452. prvProcessReceivedCommands();
  453. }
  454. }
  455. /*-----------------------------------------------------------*/
  456. static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, const BaseType_t xListWasEmpty )
  457. {
  458. TickType_t xTimeNow;
  459. BaseType_t xTimerListsWereSwitched;
  460. vTaskSuspendAll();
  461. {
  462. /* Obtain the time now to make an assessment as to whether the timer
  463. has expired or not. If obtaining the time causes the lists to switch
  464. then don't process this timer as any timers that remained in the list
  465. when the lists were switched will have been processed within the
  466. prvSampleTimeNow() function. */
  467. xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
  468. if( xTimerListsWereSwitched == pdFALSE )
  469. {
  470. /* The tick count has not overflowed, has the timer expired? */
  471. if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
  472. {
  473. ( void ) xTaskResumeAll();
  474. prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
  475. }
  476. else
  477. {
  478. /* The tick count has not overflowed, and the next expire
  479. time has not been reached yet. This task should therefore
  480. block to wait for the next expire time or a command to be
  481. received - whichever comes first. The following line cannot
  482. be reached unless xNextExpireTime > xTimeNow, except in the
  483. case when the current timer list is empty. */
  484. vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ) );
  485. if( xTaskResumeAll() == pdFALSE )
  486. {
  487. /* Yield to wait for either a command to arrive, or the
  488. block time to expire. If a command arrived between the
  489. critical section being exited and this yield then the yield
  490. will not cause the task to block. */
  491. portYIELD_WITHIN_API();
  492. }
  493. else
  494. {
  495. mtCOVERAGE_TEST_MARKER();
  496. }
  497. }
  498. }
  499. else
  500. {
  501. ( void ) xTaskResumeAll();
  502. }
  503. }
  504. }
  505. /*-----------------------------------------------------------*/
  506. static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty )
  507. {
  508. TickType_t xNextExpireTime;
  509. /* Timers are listed in expiry time order, with the head of the list
  510. referencing the task that will expire first. Obtain the time at which
  511. the timer with the nearest expiry time will expire. If there are no
  512. active timers then just set the next expire time to 0. That will cause
  513. this task to unblock when the tick count overflows, at which point the
  514. timer lists will be switched and the next expiry time can be
  515. re-assessed. */
  516. *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );
  517. if( *pxListWasEmpty == pdFALSE )
  518. {
  519. xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
  520. }
  521. else
  522. {
  523. /* Ensure the task unblocks when the tick count rolls over. */
  524. xNextExpireTime = ( TickType_t ) 0U;
  525. }
  526. return xNextExpireTime;
  527. }
  528. /*-----------------------------------------------------------*/
  529. static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched )
  530. {
  531. TickType_t xTimeNow;
  532. PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */
  533. xTimeNow = xTaskGetTickCount();
  534. if( xTimeNow < xLastTime )
  535. {
  536. prvSwitchTimerLists();
  537. *pxTimerListsWereSwitched = pdTRUE;
  538. }
  539. else
  540. {
  541. *pxTimerListsWereSwitched = pdFALSE;
  542. }
  543. xLastTime = xTimeNow;
  544. return xTimeNow;
  545. }
  546. /*-----------------------------------------------------------*/
  547. static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime )
  548. {
  549. BaseType_t xProcessTimerNow = pdFALSE;
  550. listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
  551. listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
  552. if( xNextExpiryTime <= xTimeNow )
  553. {
  554. /* Has the expiry time elapsed between the command to start/reset a
  555. timer was issued, and the time the command was processed? */
  556. if( ( xTimeNow - xCommandTime ) >= pxTimer->xTimerPeriodInTicks )
  557. {
  558. /* The time between a command being issued and the command being
  559. processed actually exceeds the timers period. */
  560. xProcessTimerNow = pdTRUE;
  561. }
  562. else
  563. {
  564. vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
  565. }
  566. }
  567. else
  568. {
  569. if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
  570. {
  571. /* If, since the command was issued, the tick count has overflowed
  572. but the expiry time has not, then the timer must have already passed
  573. its expiry time and should be processed immediately. */
  574. xProcessTimerNow = pdTRUE;
  575. }
  576. else
  577. {
  578. vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
  579. }
  580. }
  581. return xProcessTimerNow;
  582. }
  583. /*-----------------------------------------------------------*/
  584. static void prvProcessReceivedCommands( void )
  585. {
  586. DaemonTaskMessage_t xMessage;
  587. Timer_t *pxTimer;
  588. BaseType_t xTimerListsWereSwitched, xResult;
  589. TickType_t xTimeNow;
  590. while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */
  591. {
  592. #if ( INCLUDE_xTimerPendFunctionCall == 1 )
  593. {
  594. /* Negative commands are pended function calls rather than timer
  595. commands. */
  596. if( xMessage.xMessageID < ( BaseType_t ) 0 )
  597. {
  598. const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
  599. /* The timer uses the xCallbackParameters member to request a
  600. callback be executed. Check the callback is not NULL. */
  601. configASSERT( pxCallback );
  602. /* Call the function. */
  603. pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
  604. }
  605. else
  606. {
  607. mtCOVERAGE_TEST_MARKER();
  608. }
  609. }
  610. #endif /* INCLUDE_xTimerPendFunctionCall */
  611. /* Commands that are positive are timer commands rather than pended
  612. function calls. */
  613. if( xMessage.xMessageID >= ( BaseType_t ) 0 )
  614. {
  615. /* The messages uses the xTimerParameters member to work on a
  616. software timer. */
  617. pxTimer = xMessage.u.xTimerParameters.pxTimer;
  618. if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE )
  619. {
  620. /* The timer is in a list, remove it. */
  621. ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
  622. }
  623. else
  624. {
  625. mtCOVERAGE_TEST_MARKER();
  626. }
  627. traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
  628. /* In this case the xTimerListsWereSwitched parameter is not used, but
  629. it must be present in the function call. prvSampleTimeNow() must be
  630. called after the message is received from xTimerQueue so there is no
  631. possibility of a higher priority task adding a message to the message
  632. queue with a time that is ahead of the timer daemon task (because it
  633. pre-empted the timer daemon task after the xTimeNow value was set). */
  634. xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
  635. switch( xMessage.xMessageID )
  636. {
  637. case tmrCOMMAND_START :
  638. case tmrCOMMAND_START_FROM_ISR :
  639. case tmrCOMMAND_RESET :
  640. case tmrCOMMAND_RESET_FROM_ISR :
  641. case tmrCOMMAND_START_DONT_TRACE :
  642. /* Start or restart a timer. */
  643. if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) == pdTRUE )
  644. {
  645. /* The timer expired before it was added to the active
  646. timer list. Process it now. */
  647. pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
  648. traceTIMER_EXPIRED( pxTimer );
  649. if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
  650. {
  651. xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
  652. configASSERT( xResult );
  653. ( void ) xResult;
  654. }
  655. else
  656. {
  657. mtCOVERAGE_TEST_MARKER();
  658. }
  659. }
  660. else
  661. {
  662. mtCOVERAGE_TEST_MARKER();
  663. }
  664. break;
  665. case tmrCOMMAND_STOP :
  666. case tmrCOMMAND_STOP_FROM_ISR :
  667. /* The timer has already been removed from the active list.
  668. There is nothing to do here. */
  669. break;
  670. case tmrCOMMAND_CHANGE_PERIOD :
  671. case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR :
  672. pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
  673. configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
  674. /* The new period does not really have a reference, and can be
  675. longer or shorter than the old one. The command time is
  676. therefore set to the current time, and as the period cannot be
  677. zero the next expiry time can only be in the future, meaning
  678. (unlike for the xTimerStart() case above) there is no fail case
  679. that needs to be handled here. */
  680. ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
  681. break;
  682. case tmrCOMMAND_DELETE :
  683. /* The timer has already been removed from the active list,
  684. just free up the memory if the memory was dynamically
  685. allocated. */
  686. #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) )
  687. {
  688. /* The timer can only have been allocated dynamically -
  689. free it again. */
  690. vPortFree( pxTimer );
  691. }
  692. #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
  693. {
  694. /* The timer could have been allocated statically or
  695. dynamically, so check before attempting to free the
  696. memory. */
  697. if( pxTimer->ucStaticallyAllocated == ( uint8_t ) pdFALSE )
  698. {
  699. vPortFree( pxTimer );
  700. }
  701. else
  702. {
  703. mtCOVERAGE_TEST_MARKER();
  704. }
  705. }
  706. #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
  707. break;
  708. default :
  709. /* Don't expect to get here. */
  710. break;
  711. }
  712. }
  713. }
  714. }
  715. /*-----------------------------------------------------------*/
  716. static void prvSwitchTimerLists( void )
  717. {
  718. TickType_t xNextExpireTime, xReloadTime;
  719. List_t *pxTemp;
  720. Timer_t *pxTimer;
  721. BaseType_t xResult;
  722. /* The tick count has overflowed. The timer lists must be switched.
  723. If there are any timers still referenced from the current timer list
  724. then they must have expired and should be processed before the lists
  725. are switched. */
  726. while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )
  727. {
  728. xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
  729. /* Remove the timer from the list. */
  730. pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
  731. ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
  732. traceTIMER_EXPIRED( pxTimer );
  733. /* Execute its callback, then send a command to restart the timer if
  734. it is an auto-reload timer. It cannot be restarted here as the lists
  735. have not yet been switched. */
  736. pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
  737. if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
  738. {
  739. /* Calculate the reload value, and if the reload value results in
  740. the timer going into the same timer list then it has already expired
  741. and the timer should be re-inserted into the current list so it is
  742. processed again within this loop. Otherwise a command should be sent
  743. to restart the timer to ensure it is only inserted into a list after
  744. the lists have been swapped. */
  745. xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
  746. if( xReloadTime > xNextExpireTime )
  747. {
  748. listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
  749. listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
  750. vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
  751. }
  752. else
  753. {
  754. xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
  755. configASSERT( xResult );
  756. ( void ) xResult;
  757. }
  758. }
  759. else
  760. {
  761. mtCOVERAGE_TEST_MARKER();
  762. }
  763. }
  764. pxTemp = pxCurrentTimerList;
  765. pxCurrentTimerList = pxOverflowTimerList;
  766. pxOverflowTimerList = pxTemp;
  767. }
  768. /*-----------------------------------------------------------*/
  769. static void prvCheckForValidListAndQueue( void )
  770. {
  771. /* Check that the list from which active timers are referenced, and the
  772. queue used to communicate with the timer service, have been
  773. initialised. */
  774. /* Erm, yes, this is a problem. We can't lock until the lock is initialized, and we can't initialize the lock
  775. atomically because we don't have a lock yet... I'm pretty sure doubly-initializing a lock on 2 cpus
  776. is no problem in the current implementation, but this is not a nice way to solve things. ToDo - improve. */
  777. if( xTimerQueue == NULL ) vPortCPUInitializeMutex( &xTimerMux );
  778. taskENTER_CRITICAL( &xTimerMux );
  779. {
  780. if( xTimerQueue == NULL )
  781. {
  782. vListInitialise( &xActiveTimerList1 );
  783. vListInitialise( &xActiveTimerList2 );
  784. pxCurrentTimerList = &xActiveTimerList1;
  785. pxOverflowTimerList = &xActiveTimerList2;
  786. xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) );
  787. configASSERT( xTimerQueue );
  788. #if ( configQUEUE_REGISTRY_SIZE > 0 )
  789. {
  790. if( xTimerQueue != NULL )
  791. {
  792. vQueueAddToRegistry( xTimerQueue, "TmrQ" );
  793. }
  794. else
  795. {
  796. mtCOVERAGE_TEST_MARKER();
  797. }
  798. }
  799. #endif /* configQUEUE_REGISTRY_SIZE */
  800. }
  801. else
  802. {
  803. mtCOVERAGE_TEST_MARKER();
  804. }
  805. }
  806. taskEXIT_CRITICAL( &xTimerMux );
  807. }
  808. /*-----------------------------------------------------------*/
  809. BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer )
  810. {
  811. BaseType_t xTimerIsInActiveList;
  812. Timer_t *pxTimer = ( Timer_t * ) xTimer;
  813. /* Is the timer in the list of active timers? */
  814. taskENTER_CRITICAL( &xTimerMux );
  815. {
  816. /* Checking to see if it is in the NULL list in effect checks to see if
  817. it is referenced from either the current or the overflow timer lists in
  818. one go, but the logic has to be reversed, hence the '!'. */
  819. xTimerIsInActiveList = ( BaseType_t ) !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) );
  820. }
  821. taskEXIT_CRITICAL( &xTimerMux );
  822. return xTimerIsInActiveList;
  823. } /*lint !e818 Can't be pointer to const due to the typedef. */
  824. /*-----------------------------------------------------------*/
  825. void *pvTimerGetTimerID( const TimerHandle_t xTimer )
  826. {
  827. Timer_t * const pxTimer = ( Timer_t * ) xTimer;
  828. return pxTimer->pvTimerID;
  829. }
  830. /*-----------------------------------------------------------*/
  831. void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID )
  832. {
  833. Timer_t * const pxTimer = ( Timer_t * ) xTimer;
  834. configASSERT( xTimer );
  835. //taskENTER_CRITICAL(); //Atomic instruction, critical not necessary
  836. //{
  837. pxTimer->pvTimerID = pvNewID;
  838. //}
  839. //taskEXIT_CRITICAL();
  840. }
  841. /*-----------------------------------------------------------*/
  842. #if( INCLUDE_xTimerPendFunctionCall == 1 )
  843. BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken )
  844. {
  845. DaemonTaskMessage_t xMessage;
  846. BaseType_t xReturn;
  847. /* Complete the message with the function parameters and post it to the
  848. daemon task. */
  849. xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
  850. xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
  851. xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
  852. xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
  853. xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
  854. tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
  855. return xReturn;
  856. }
  857. #endif /* INCLUDE_xTimerPendFunctionCall */
  858. /*-----------------------------------------------------------*/
  859. #if( INCLUDE_xTimerPendFunctionCall == 1 )
  860. BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait )
  861. {
  862. DaemonTaskMessage_t xMessage;
  863. BaseType_t xReturn;
  864. /* This function can only be called after a timer has been created or
  865. after the scheduler has been started because, until then, the timer
  866. queue does not exist. */
  867. configASSERT( xTimerQueue );
  868. /* Complete the message with the function parameters and post it to the
  869. daemon task. */
  870. xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
  871. xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
  872. xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
  873. xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
  874. xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
  875. tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
  876. return xReturn;
  877. }
  878. #endif /* INCLUDE_xTimerPendFunctionCall */
  879. /*-----------------------------------------------------------*/
  880. /* This entire source file will be skipped if the application is not configured
  881. to include software timer functionality. If you want to include software timer
  882. functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
  883. #endif /* configUSE_TIMERS == 1 */