timers.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /*
  2. FreeRTOS V8.2.3 - 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. #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 )
  66. #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
  67. #endif
  68. /* Lint e961 and e750 are suppressed as a MISRA exception justified because the
  69. MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
  70. header files above, but not in this file, in order to generate the correct
  71. privileged Vs unprivileged linkage and placement. */
  72. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
  73. /* This entire source file will be skipped if the application is not configured
  74. to include software timer functionality. This #if is closed at the very bottom
  75. of this file. If you want to include software timer functionality then ensure
  76. configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
  77. #if ( configUSE_TIMERS == 1 )
  78. /* Misc definitions. */
  79. #define tmrNO_DELAY ( TickType_t ) 0U
  80. /* The definition of the timers themselves. */
  81. typedef struct tmrTimerControl
  82. {
  83. 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. */
  84. ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */
  85. TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */
  86. 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. */
  87. void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */
  88. TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */
  89. #if( configUSE_TRACE_FACILITY == 1 )
  90. UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */
  91. #endif
  92. } xTIMER;
  93. /* The old xTIMER name is maintained above then typedefed to the new Timer_t
  94. name below to enable the use of older kernel aware debuggers. */
  95. typedef xTIMER Timer_t;
  96. /* The definition of messages that can be sent and received on the timer queue.
  97. Two types of message can be queued - messages that manipulate a software timer,
  98. and messages that request the execution of a non-timer related callback. The
  99. two message types are defined in two separate structures, xTimerParametersType
  100. and xCallbackParametersType respectively. */
  101. typedef struct tmrTimerParameters
  102. {
  103. TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
  104. Timer_t * pxTimer; /*<< The timer to which the command will be applied. */
  105. } TimerParameter_t;
  106. typedef struct tmrCallbackParameters
  107. {
  108. PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */
  109. void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */
  110. uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */
  111. } CallbackParameters_t;
  112. /* The structure that contains the two message types, along with an identifier
  113. that is used to determine which message type is valid. */
  114. typedef struct tmrTimerQueueMessage
  115. {
  116. BaseType_t xMessageID; /*<< The command being sent to the timer service task. */
  117. union
  118. {
  119. TimerParameter_t xTimerParameters;
  120. /* Don't include xCallbackParameters if it is not going to be used as
  121. it makes the structure (and therefore the timer queue) larger. */
  122. #if ( INCLUDE_xTimerPendFunctionCall == 1 )
  123. CallbackParameters_t xCallbackParameters;
  124. #endif /* INCLUDE_xTimerPendFunctionCall */
  125. } u;
  126. } DaemonTaskMessage_t;
  127. /*lint -e956 A manual analysis and inspection has been used to determine which
  128. static variables must be declared volatile. */
  129. /* The list in which active timers are stored. Timers are referenced in expire
  130. time order, with the nearest expiry time at the front of the list. Only the
  131. timer service task is allowed to access these lists. */
  132. PRIVILEGED_DATA static List_t xActiveTimerList1;
  133. PRIVILEGED_DATA static List_t xActiveTimerList2;
  134. PRIVILEGED_DATA static List_t *pxCurrentTimerList;
  135. PRIVILEGED_DATA static List_t *pxOverflowTimerList;
  136. /* A queue that is used to send commands to the timer service task. */
  137. PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
  138. #if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
  139. PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
  140. #endif
  141. /*lint +e956 */
  142. /*-----------------------------------------------------------*/
  143. /*
  144. * Initialise the infrastructure used by the timer service task if it has not
  145. * been initialised already.
  146. */
  147. static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;
  148. /*
  149. * The timer service task (daemon). Timer functionality is controlled by this
  150. * task. Other tasks communicate with the timer service task using the
  151. * xTimerQueue queue.
  152. */
  153. static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION;
  154. /*
  155. * Called by the timer service task to interpret and process a command it
  156. * received on the timer queue.
  157. */
  158. static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;
  159. /*
  160. * Insert the timer into either xActiveTimerList1, or xActiveTimerList2,
  161. * depending on if the expire time causes a timer counter overflow.
  162. */
  163. static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION;
  164. /*
  165. * An active timer has reached its expire time. Reload the timer if it is an
  166. * auto reload timer, then call its callback.
  167. */
  168. static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION;
  169. /*
  170. * The tick count has overflowed. Switch the timer lists after ensuring the
  171. * current timer list does not still reference some timers.
  172. */
  173. static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION;
  174. /*
  175. * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE
  176. * if a tick count overflow occurred since prvSampleTimeNow() was last called.
  177. */
  178. static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;
  179. /*
  180. * If the timer list contains any active timers then return the expire time of
  181. * the timer that will expire first and set *pxListWasEmpty to false. If the
  182. * timer list does not contain any timers then return 0 and set *pxListWasEmpty
  183. * to pdTRUE.
  184. */
  185. static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION;
  186. /*
  187. * If a timer has expired, process it. Otherwise, block the timer service task
  188. * until either a timer does expire or a command is received.
  189. */
  190. static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION;
  191. /*-----------------------------------------------------------*/
  192. BaseType_t xTimerCreateTimerTask( void )
  193. {
  194. BaseType_t xReturn = pdFAIL;
  195. /* This function is called when the scheduler is started if
  196. configUSE_TIMERS is set to 1. Check that the infrastructure used by the
  197. timer service task has been created/initialised. If timers have already
  198. been created then the initialisation will already have been performed. */
  199. prvCheckForValidListAndQueue();
  200. if( xTimerQueue != NULL )
  201. {
  202. #if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
  203. {
  204. /* Create the timer task, storing its handle in xTimerTaskHandle so
  205. it can be returned by the xTimerGetTimerDaemonTaskHandle() function. */
  206. xReturn = xTaskCreate( prvTimerTask, "Tmr Svc", ( uint16_t ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, &xTimerTaskHandle );
  207. }
  208. #else
  209. {
  210. /* Create the timer task without storing its handle. */
  211. xReturn = xTaskCreate( prvTimerTask, "Tmr Svc", ( uint16_t ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, NULL);
  212. }
  213. #endif
  214. }
  215. else
  216. {
  217. mtCOVERAGE_TEST_MARKER();
  218. }
  219. configASSERT( xReturn );
  220. return xReturn;
  221. }
  222. /*-----------------------------------------------------------*/
  223. TimerHandle_t xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
  224. {
  225. Timer_t *pxNewTimer;
  226. /* Allocate the timer structure. */
  227. if( xTimerPeriodInTicks == ( TickType_t ) 0U )
  228. {
  229. pxNewTimer = NULL;
  230. }
  231. else
  232. {
  233. pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) );
  234. if( pxNewTimer != NULL )
  235. {
  236. /* Ensure the infrastructure used by the timer service task has been
  237. created/initialised. */
  238. prvCheckForValidListAndQueue();
  239. /* Initialise the timer structure members using the function parameters. */
  240. pxNewTimer->pcTimerName = pcTimerName;
  241. pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
  242. pxNewTimer->uxAutoReload = uxAutoReload;
  243. pxNewTimer->pvTimerID = pvTimerID;
  244. pxNewTimer->pxCallbackFunction = pxCallbackFunction;
  245. vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );
  246. traceTIMER_CREATE( pxNewTimer );
  247. }
  248. else
  249. {
  250. traceTIMER_CREATE_FAILED();
  251. }
  252. }
  253. /* 0 is not a valid value for xTimerPeriodInTicks. */
  254. configASSERT( ( xTimerPeriodInTicks > 0 ) );
  255. return ( TimerHandle_t ) pxNewTimer;
  256. }
  257. /*-----------------------------------------------------------*/
  258. BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait )
  259. {
  260. BaseType_t xReturn = pdFAIL;
  261. DaemonTaskMessage_t xMessage;
  262. configASSERT( xTimer );
  263. /* Send a message to the timer service task to perform a particular action
  264. on a particular timer definition. */
  265. if( xTimerQueue != NULL )
  266. {
  267. /* Send a command to the timer service task to start the xTimer timer. */
  268. xMessage.xMessageID = xCommandID;
  269. xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
  270. xMessage.u.xTimerParameters.pxTimer = ( Timer_t * ) xTimer;
  271. if( xCommandID < tmrFIRST_FROM_ISR_COMMAND )
  272. {
  273. if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
  274. {
  275. xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
  276. }
  277. else
  278. {
  279. xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
  280. }
  281. }
  282. else
  283. {
  284. xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
  285. }
  286. traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
  287. }
  288. else
  289. {
  290. mtCOVERAGE_TEST_MARKER();
  291. }
  292. return xReturn;
  293. }
  294. /*-----------------------------------------------------------*/
  295. #if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
  296. TaskHandle_t xTimerGetTimerDaemonTaskHandle( void )
  297. {
  298. /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
  299. started, then xTimerTaskHandle will be NULL. */
  300. configASSERT( ( xTimerTaskHandle != NULL ) );
  301. return xTimerTaskHandle;
  302. }
  303. #endif
  304. /*-----------------------------------------------------------*/
  305. const char * pcTimerGetTimerName( TimerHandle_t xTimer )
  306. {
  307. Timer_t *pxTimer = ( Timer_t * ) xTimer;
  308. configASSERT( xTimer );
  309. return pxTimer->pcTimerName;
  310. }
  311. /*-----------------------------------------------------------*/
  312. static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow )
  313. {
  314. BaseType_t xResult;
  315. Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
  316. /* Remove the timer from the list of active timers. A check has already
  317. been performed to ensure the list is not empty. */
  318. ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
  319. traceTIMER_EXPIRED( pxTimer );
  320. /* If the timer is an auto reload timer then calculate the next
  321. expiry time and re-insert the timer in the list of active timers. */
  322. if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
  323. {
  324. /* The timer is inserted into a list using a time relative to anything
  325. other than the current time. It will therefore be inserted into the
  326. correct list relative to the time this task thinks it is now. */
  327. if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) == pdTRUE )
  328. {
  329. /* The timer expired before it was added to the active timer
  330. list. Reload it now. */
  331. xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
  332. configASSERT( xResult );
  333. ( void ) xResult;
  334. }
  335. else
  336. {
  337. mtCOVERAGE_TEST_MARKER();
  338. }
  339. }
  340. else
  341. {
  342. mtCOVERAGE_TEST_MARKER();
  343. }
  344. /* Call the timer callback. */
  345. pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
  346. }
  347. /*-----------------------------------------------------------*/
  348. static void prvTimerTask( void *pvParameters )
  349. {
  350. TickType_t xNextExpireTime;
  351. BaseType_t xListWasEmpty;
  352. /* Just to avoid compiler warnings. */
  353. ( void ) pvParameters;
  354. for( ;; )
  355. {
  356. /* Query the timers list to see if it contains any timers, and if so,
  357. obtain the time at which the next timer will expire. */
  358. xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
  359. /* If a timer has expired, process it. Otherwise, block this task
  360. until either a timer does expire, or a command is received. */
  361. prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
  362. /* Empty the command queue. */
  363. prvProcessReceivedCommands();
  364. }
  365. }
  366. /*-----------------------------------------------------------*/
  367. static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty )
  368. {
  369. TickType_t xTimeNow;
  370. BaseType_t xTimerListsWereSwitched;
  371. vTaskSuspendAll();
  372. {
  373. /* Obtain the time now to make an assessment as to whether the timer
  374. has expired or not. If obtaining the time causes the lists to switch
  375. then don't process this timer as any timers that remained in the list
  376. when the lists were switched will have been processed within the
  377. prvSampleTimeNow() function. */
  378. xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
  379. if( xTimerListsWereSwitched == pdFALSE )
  380. {
  381. /* The tick count has not overflowed, has the timer expired? */
  382. if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
  383. {
  384. ( void ) xTaskResumeAll();
  385. prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
  386. }
  387. else
  388. {
  389. /* The tick count has not overflowed, and the next expire
  390. time has not been reached yet. This task should therefore
  391. block to wait for the next expire time or a command to be
  392. received - whichever comes first. The following line cannot
  393. be reached unless xNextExpireTime > xTimeNow, except in the
  394. case when the current timer list is empty. */
  395. if( xListWasEmpty != pdFALSE )
  396. {
  397. /* The current timer list is empty - is the overflow list
  398. also empty? */
  399. xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList );
  400. }
  401. vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty );
  402. if( xTaskResumeAll() == pdFALSE )
  403. {
  404. /* Yield to wait for either a command to arrive, or the
  405. block time to expire. If a command arrived between the
  406. critical section being exited and this yield then the yield
  407. will not cause the task to block. */
  408. portYIELD_WITHIN_API();
  409. }
  410. else
  411. {
  412. mtCOVERAGE_TEST_MARKER();
  413. }
  414. }
  415. }
  416. else
  417. {
  418. ( void ) xTaskResumeAll();
  419. }
  420. }
  421. }
  422. /*-----------------------------------------------------------*/
  423. static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty )
  424. {
  425. TickType_t xNextExpireTime;
  426. /* Timers are listed in expiry time order, with the head of the list
  427. referencing the task that will expire first. Obtain the time at which
  428. the timer with the nearest expiry time will expire. If there are no
  429. active timers then just set the next expire time to 0. That will cause
  430. this task to unblock when the tick count overflows, at which point the
  431. timer lists will be switched and the next expiry time can be
  432. re-assessed. */
  433. *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );
  434. if( *pxListWasEmpty == pdFALSE )
  435. {
  436. xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
  437. }
  438. else
  439. {
  440. /* Ensure the task unblocks when the tick count rolls over. */
  441. xNextExpireTime = ( TickType_t ) 0U;
  442. }
  443. return xNextExpireTime;
  444. }
  445. /*-----------------------------------------------------------*/
  446. static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched )
  447. {
  448. TickType_t xTimeNow;
  449. PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */
  450. xTimeNow = xTaskGetTickCount();
  451. if( xTimeNow < xLastTime )
  452. {
  453. prvSwitchTimerLists();
  454. *pxTimerListsWereSwitched = pdTRUE;
  455. }
  456. else
  457. {
  458. *pxTimerListsWereSwitched = pdFALSE;
  459. }
  460. xLastTime = xTimeNow;
  461. return xTimeNow;
  462. }
  463. /*-----------------------------------------------------------*/
  464. static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime )
  465. {
  466. BaseType_t xProcessTimerNow = pdFALSE;
  467. listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
  468. listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
  469. if( xNextExpiryTime <= xTimeNow )
  470. {
  471. /* Has the expiry time elapsed between the command to start/reset a
  472. timer was issued, and the time the command was processed? */
  473. if( ( xTimeNow - xCommandTime ) >= pxTimer->xTimerPeriodInTicks )
  474. {
  475. /* The time between a command being issued and the command being
  476. processed actually exceeds the timers period. */
  477. xProcessTimerNow = pdTRUE;
  478. }
  479. else
  480. {
  481. vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
  482. }
  483. }
  484. else
  485. {
  486. if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
  487. {
  488. /* If, since the command was issued, the tick count has overflowed
  489. but the expiry time has not, then the timer must have already passed
  490. its expiry time and should be processed immediately. */
  491. xProcessTimerNow = pdTRUE;
  492. }
  493. else
  494. {
  495. vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
  496. }
  497. }
  498. return xProcessTimerNow;
  499. }
  500. /*-----------------------------------------------------------*/
  501. static void prvProcessReceivedCommands( void )
  502. {
  503. DaemonTaskMessage_t xMessage;
  504. Timer_t *pxTimer;
  505. BaseType_t xTimerListsWereSwitched, xResult;
  506. TickType_t xTimeNow;
  507. 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. */
  508. {
  509. #if ( INCLUDE_xTimerPendFunctionCall == 1 )
  510. {
  511. /* Negative commands are pended function calls rather than timer
  512. commands. */
  513. if( xMessage.xMessageID < ( BaseType_t ) 0 )
  514. {
  515. const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
  516. /* The timer uses the xCallbackParameters member to request a
  517. callback be executed. Check the callback is not NULL. */
  518. configASSERT( pxCallback );
  519. /* Call the function. */
  520. pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
  521. }
  522. else
  523. {
  524. mtCOVERAGE_TEST_MARKER();
  525. }
  526. }
  527. #endif /* INCLUDE_xTimerPendFunctionCall */
  528. /* Commands that are positive are timer commands rather than pended
  529. function calls. */
  530. if( xMessage.xMessageID >= ( BaseType_t ) 0 )
  531. {
  532. /* The messages uses the xTimerParameters member to work on a
  533. software timer. */
  534. pxTimer = xMessage.u.xTimerParameters.pxTimer;
  535. if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE )
  536. {
  537. /* The timer is in a list, remove it. */
  538. ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
  539. }
  540. else
  541. {
  542. mtCOVERAGE_TEST_MARKER();
  543. }
  544. traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
  545. /* In this case the xTimerListsWereSwitched parameter is not used, but
  546. it must be present in the function call. prvSampleTimeNow() must be
  547. called after the message is received from xTimerQueue so there is no
  548. possibility of a higher priority task adding a message to the message
  549. queue with a time that is ahead of the timer daemon task (because it
  550. pre-empted the timer daemon task after the xTimeNow value was set). */
  551. xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
  552. switch( xMessage.xMessageID )
  553. {
  554. case tmrCOMMAND_START :
  555. case tmrCOMMAND_START_FROM_ISR :
  556. case tmrCOMMAND_RESET :
  557. case tmrCOMMAND_RESET_FROM_ISR :
  558. case tmrCOMMAND_START_DONT_TRACE :
  559. /* Start or restart a timer. */
  560. if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) == pdTRUE )
  561. {
  562. /* The timer expired before it was added to the active
  563. timer list. Process it now. */
  564. pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
  565. traceTIMER_EXPIRED( pxTimer );
  566. if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
  567. {
  568. xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
  569. configASSERT( xResult );
  570. ( void ) xResult;
  571. }
  572. else
  573. {
  574. mtCOVERAGE_TEST_MARKER();
  575. }
  576. }
  577. else
  578. {
  579. mtCOVERAGE_TEST_MARKER();
  580. }
  581. break;
  582. case tmrCOMMAND_STOP :
  583. case tmrCOMMAND_STOP_FROM_ISR :
  584. /* The timer has already been removed from the active list.
  585. There is nothing to do here. */
  586. break;
  587. case tmrCOMMAND_CHANGE_PERIOD :
  588. case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR :
  589. pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
  590. configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
  591. /* The new period does not really have a reference, and can be
  592. longer or shorter than the old one. The command time is
  593. therefore set to the current time, and as the period cannot be
  594. zero the next expiry time can only be in the future, meaning
  595. (unlike for the xTimerStart() case above) there is no fail case
  596. that needs to be handled here. */
  597. ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
  598. break;
  599. case tmrCOMMAND_DELETE :
  600. /* The timer has already been removed from the active list,
  601. just free up the memory. */
  602. vPortFree( pxTimer );
  603. break;
  604. default :
  605. /* Don't expect to get here. */
  606. break;
  607. }
  608. }
  609. }
  610. }
  611. /*-----------------------------------------------------------*/
  612. static void prvSwitchTimerLists( void )
  613. {
  614. TickType_t xNextExpireTime, xReloadTime;
  615. List_t *pxTemp;
  616. Timer_t *pxTimer;
  617. BaseType_t xResult;
  618. /* The tick count has overflowed. The timer lists must be switched.
  619. If there are any timers still referenced from the current timer list
  620. then they must have expired and should be processed before the lists
  621. are switched. */
  622. while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )
  623. {
  624. xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
  625. /* Remove the timer from the list. */
  626. pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
  627. ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
  628. traceTIMER_EXPIRED( pxTimer );
  629. /* Execute its callback, then send a command to restart the timer if
  630. it is an auto-reload timer. It cannot be restarted here as the lists
  631. have not yet been switched. */
  632. pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
  633. if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
  634. {
  635. /* Calculate the reload value, and if the reload value results in
  636. the timer going into the same timer list then it has already expired
  637. and the timer should be re-inserted into the current list so it is
  638. processed again within this loop. Otherwise a command should be sent
  639. to restart the timer to ensure it is only inserted into a list after
  640. the lists have been swapped. */
  641. xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
  642. if( xReloadTime > xNextExpireTime )
  643. {
  644. listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
  645. listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
  646. vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
  647. }
  648. else
  649. {
  650. xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
  651. configASSERT( xResult );
  652. ( void ) xResult;
  653. }
  654. }
  655. else
  656. {
  657. mtCOVERAGE_TEST_MARKER();
  658. }
  659. }
  660. pxTemp = pxCurrentTimerList;
  661. pxCurrentTimerList = pxOverflowTimerList;
  662. pxOverflowTimerList = pxTemp;
  663. }
  664. /*-----------------------------------------------------------*/
  665. static void prvCheckForValidListAndQueue( void )
  666. {
  667. /* Check that the list from which active timers are referenced, and the
  668. queue used to communicate with the timer service, have been
  669. initialised. */
  670. taskENTER_CRITICAL();
  671. {
  672. if( xTimerQueue == NULL )
  673. {
  674. vListInitialise( &xActiveTimerList1 );
  675. vListInitialise( &xActiveTimerList2 );
  676. pxCurrentTimerList = &xActiveTimerList1;
  677. pxOverflowTimerList = &xActiveTimerList2;
  678. xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) );
  679. configASSERT( xTimerQueue );
  680. #if ( configQUEUE_REGISTRY_SIZE > 0 )
  681. {
  682. if( xTimerQueue != NULL )
  683. {
  684. vQueueAddToRegistry( xTimerQueue, "TmrQ" );
  685. }
  686. else
  687. {
  688. mtCOVERAGE_TEST_MARKER();
  689. }
  690. }
  691. #endif /* configQUEUE_REGISTRY_SIZE */
  692. }
  693. else
  694. {
  695. mtCOVERAGE_TEST_MARKER();
  696. }
  697. }
  698. taskEXIT_CRITICAL();
  699. }
  700. /*-----------------------------------------------------------*/
  701. BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer )
  702. {
  703. BaseType_t xTimerIsInActiveList;
  704. Timer_t *pxTimer = ( Timer_t * ) xTimer;
  705. configASSERT( xTimer );
  706. /* Is the timer in the list of active timers? */
  707. taskENTER_CRITICAL();
  708. {
  709. /* Checking to see if it is in the NULL list in effect checks to see if
  710. it is referenced from either the current or the overflow timer lists in
  711. one go, but the logic has to be reversed, hence the '!'. */
  712. xTimerIsInActiveList = ( BaseType_t ) !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) );
  713. }
  714. taskEXIT_CRITICAL();
  715. return xTimerIsInActiveList;
  716. } /*lint !e818 Can't be pointer to const due to the typedef. */
  717. /*-----------------------------------------------------------*/
  718. void *pvTimerGetTimerID( const TimerHandle_t xTimer )
  719. {
  720. Timer_t * const pxTimer = ( Timer_t * ) xTimer;
  721. void *pvReturn;
  722. configASSERT( xTimer );
  723. taskENTER_CRITICAL();
  724. {
  725. pvReturn = pxTimer->pvTimerID;
  726. }
  727. taskEXIT_CRITICAL();
  728. return pvReturn;
  729. }
  730. /*-----------------------------------------------------------*/
  731. void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID )
  732. {
  733. Timer_t * const pxTimer = ( Timer_t * ) xTimer;
  734. configASSERT( xTimer );
  735. taskENTER_CRITICAL();
  736. {
  737. pxTimer->pvTimerID = pvNewID;
  738. }
  739. taskEXIT_CRITICAL();
  740. }
  741. /*-----------------------------------------------------------*/
  742. #if( INCLUDE_xTimerPendFunctionCall == 1 )
  743. BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken )
  744. {
  745. DaemonTaskMessage_t xMessage;
  746. BaseType_t xReturn;
  747. /* Complete the message with the function parameters and post it to the
  748. daemon task. */
  749. xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
  750. xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
  751. xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
  752. xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
  753. xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
  754. tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
  755. return xReturn;
  756. }
  757. #endif /* INCLUDE_xTimerPendFunctionCall */
  758. /*-----------------------------------------------------------*/
  759. #if( INCLUDE_xTimerPendFunctionCall == 1 )
  760. BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait )
  761. {
  762. DaemonTaskMessage_t xMessage;
  763. BaseType_t xReturn;
  764. /* This function can only be called after a timer has been created or
  765. after the scheduler has been started because, until then, the timer
  766. queue does not exist. */
  767. configASSERT( xTimerQueue );
  768. /* Complete the message with the function parameters and post it to the
  769. daemon task. */
  770. xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
  771. xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
  772. xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
  773. xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
  774. xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
  775. tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
  776. return xReturn;
  777. }
  778. #endif /* INCLUDE_xTimerPendFunctionCall */
  779. /*-----------------------------------------------------------*/
  780. /* This entire source file will be skipped if the application is not configured
  781. to include software timer functionality. If you want to include software timer
  782. functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
  783. #endif /* configUSE_TIMERS == 1 */