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