]> begriffs open source - cmsis-freertos/blob - Source/timers.c
osEventFlagsSet in correctly handles status return from xEventGroupSetBitsFromISR
[cmsis-freertos] / Source / timers.c
1 /*
2  * FreeRTOS Kernel V10.0.1
3  * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9  * the Software, and to permit persons to whom the Software is furnished to do so,
10  * subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * http://www.FreeRTOS.org
23  * http://aws.amazon.com/freertos
24  *
25  * 1 tab == 4 spaces!
26  */
27
28 /* Standard includes. */
29 #include <stdlib.h>
30
31 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
32 all the API functions to use the MPU wrappers.  That should only be done when
33 task.h is included from an application file. */
34 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
35
36 #include "FreeRTOS.h"
37 #include "task.h"
38 #include "queue.h"
39 #include "timers.h"
40
41 #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 )
42         #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
43 #endif
44
45 /* Lint e961 and e750 are suppressed as a MISRA exception justified because the
46 MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
47 header files above, but not in this file, in order to generate the correct
48 privileged Vs unprivileged linkage and placement. */
49 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
50
51
52 /* This entire source file will be skipped if the application is not configured
53 to include software timer functionality.  This #if is closed at the very bottom
54 of this file.  If you want to include software timer functionality then ensure
55 configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
56 #if ( configUSE_TIMERS == 1 )
57
58 /* Misc definitions. */
59 #define tmrNO_DELAY             ( TickType_t ) 0U
60
61 /* The name assigned to the timer service task.  This can be overridden by
62 defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */
63 #ifndef configTIMER_SERVICE_TASK_NAME
64         #define configTIMER_SERVICE_TASK_NAME "Tmr Svc"
65 #endif
66
67 /* The definition of the timers themselves. */
68 typedef struct tmrTimerControl
69 {
70         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. */
71         ListItem_t                              xTimerListItem;         /*<< Standard linked list item as used by all kernel features for event management. */
72         TickType_t                              xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */
73         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. */
74         void                                    *pvTimerID;                     /*<< An ID to identify the timer.  This allows the timer to be identified when the same callback is used for multiple timers. */
75         TimerCallbackFunction_t pxCallbackFunction;     /*<< The function that will be called when the timer expires. */
76         #if( configUSE_TRACE_FACILITY == 1 )
77                 UBaseType_t                     uxTimerNumber;          /*<< An ID assigned by trace tools such as FreeRTOS+Trace */
78         #endif
79
80         #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
81                 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. */
82         #endif
83 } xTIMER;
84
85 /* The old xTIMER name is maintained above then typedefed to the new Timer_t
86 name below to enable the use of older kernel aware debuggers. */
87 typedef xTIMER Timer_t;
88
89 /* The definition of messages that can be sent and received on the timer queue.
90 Two types of message can be queued - messages that manipulate a software timer,
91 and messages that request the execution of a non-timer related callback.  The
92 two message types are defined in two separate structures, xTimerParametersType
93 and xCallbackParametersType respectively. */
94 typedef struct tmrTimerParameters
95 {
96         TickType_t                      xMessageValue;          /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
97         Timer_t *                       pxTimer;                        /*<< The timer to which the command will be applied. */
98 } TimerParameter_t;
99
100
101 typedef struct tmrCallbackParameters
102 {
103         PendedFunction_t        pxCallbackFunction;     /* << The callback function to execute. */
104         void *pvParameter1;                                             /* << The value that will be used as the callback functions first parameter. */
105         uint32_t ulParameter2;                                  /* << The value that will be used as the callback functions second parameter. */
106 } CallbackParameters_t;
107
108 /* The structure that contains the two message types, along with an identifier
109 that is used to determine which message type is valid. */
110 typedef struct tmrTimerQueueMessage
111 {
112         BaseType_t                      xMessageID;                     /*<< The command being sent to the timer service task. */
113         union
114         {
115                 TimerParameter_t xTimerParameters;
116
117                 /* Don't include xCallbackParameters if it is not going to be used as
118                 it makes the structure (and therefore the timer queue) larger. */
119                 #if ( INCLUDE_xTimerPendFunctionCall == 1 )
120                         CallbackParameters_t xCallbackParameters;
121                 #endif /* INCLUDE_xTimerPendFunctionCall */
122         } u;
123 } DaemonTaskMessage_t;
124
125 /*lint -save -e956 A manual analysis and inspection has been used to determine
126 which static variables must be declared volatile. */
127
128 /* The list in which active timers are stored.  Timers are referenced in expire
129 time order, with the nearest expiry time at the front of the list.  Only the
130 timer service task is allowed to access these lists. */
131 PRIVILEGED_DATA static List_t xActiveTimerList1;
132 PRIVILEGED_DATA static List_t xActiveTimerList2;
133 PRIVILEGED_DATA static List_t *pxCurrentTimerList;
134 PRIVILEGED_DATA static List_t *pxOverflowTimerList;
135
136 /* A queue that is used to send commands to the timer service task. */
137 PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
138 PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
139
140 /*lint -restore */
141
142 /*-----------------------------------------------------------*/
143
144 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
145
146         /* If static allocation is supported then the application must provide the
147         following callback function - which enables the application to optionally
148         provide the memory that will be used by the timer task as the task's stack
149         and TCB. */
150         extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize );
151
152 #endif
153
154 /*
155  * Initialise the infrastructure used by the timer service task if it has not
156  * been initialised already.
157  */
158 static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;
159
160 /*
161  * The timer service task (daemon).  Timer functionality is controlled by this
162  * task.  Other tasks communicate with the timer service task using the
163  * xTimerQueue queue.
164  */
165 static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION;
166
167 /*
168  * Called by the timer service task to interpret and process a command it
169  * received on the timer queue.
170  */
171 static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;
172
173 /*
174  * Insert the timer into either xActiveTimerList1, or xActiveTimerList2,
175  * depending on if the expire time causes a timer counter overflow.
176  */
177 static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION;
178
179 /*
180  * An active timer has reached its expire time.  Reload the timer if it is an
181  * auto reload timer, then call its callback.
182  */
183 static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION;
184
185 /*
186  * The tick count has overflowed.  Switch the timer lists after ensuring the
187  * current timer list does not still reference some timers.
188  */
189 static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION;
190
191 /*
192  * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE
193  * if a tick count overflow occurred since prvSampleTimeNow() was last called.
194  */
195 static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;
196
197 /*
198  * If the timer list contains any active timers then return the expire time of
199  * the timer that will expire first and set *pxListWasEmpty to false.  If the
200  * timer list does not contain any timers then return 0 and set *pxListWasEmpty
201  * to pdTRUE.
202  */
203 static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION;
204
205 /*
206  * If a timer has expired, process it.  Otherwise, block the timer service task
207  * until either a timer does expire or a command is received.
208  */
209 static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION;
210
211 /*
212  * Called after a Timer_t structure has been allocated either statically or
213  * dynamically to fill in the structure's members.
214  */
215 static void prvInitialiseNewTimer(      const char * const pcTimerName,                 /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
216                                                                         const TickType_t xTimerPeriodInTicks,
217                                                                         const UBaseType_t uxAutoReload,
218                                                                         void * const pvTimerID,
219                                                                         TimerCallbackFunction_t pxCallbackFunction,
220                                                                         Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION;
221 /*-----------------------------------------------------------*/
222
223 BaseType_t xTimerCreateTimerTask( void )
224 {
225 BaseType_t xReturn = pdFAIL;
226
227         /* This function is called when the scheduler is started if
228         configUSE_TIMERS is set to 1.  Check that the infrastructure used by the
229         timer service task has been created/initialised.  If timers have already
230         been created then the initialisation will already have been performed. */
231         prvCheckForValidListAndQueue();
232
233         if( xTimerQueue != NULL )
234         {
235                 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
236                 {
237                         StaticTask_t *pxTimerTaskTCBBuffer = NULL;
238                         StackType_t *pxTimerTaskStackBuffer = NULL;
239                         uint32_t ulTimerTaskStackSize;
240
241                         vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize );
242                         xTimerTaskHandle = xTaskCreateStatic(   prvTimerTask,
243                                                                                                         configTIMER_SERVICE_TASK_NAME,
244                                                                                                         ulTimerTaskStackSize,
245                                                                                                         NULL,
246                                                                                                         ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT,
247                                                                                                         pxTimerTaskStackBuffer,
248                                                                                                         pxTimerTaskTCBBuffer );
249
250                         if( xTimerTaskHandle != NULL )
251                         {
252                                 xReturn = pdPASS;
253                         }
254                 }
255                 #else
256                 {
257                         xReturn = xTaskCreate(  prvTimerTask,
258                                                                         configTIMER_SERVICE_TASK_NAME,
259                                                                         configTIMER_TASK_STACK_DEPTH,
260                                                                         NULL,
261                                                                         ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT,
262                                                                         &xTimerTaskHandle );
263                 }
264                 #endif /* configSUPPORT_STATIC_ALLOCATION */
265         }
266         else
267         {
268                 mtCOVERAGE_TEST_MARKER();
269         }
270
271         configASSERT( xReturn );
272         return xReturn;
273 }
274 /*-----------------------------------------------------------*/
275
276 #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
277
278         TimerHandle_t xTimerCreate(     const char * const pcTimerName,                 /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
279                                                                 const TickType_t xTimerPeriodInTicks,
280                                                                 const UBaseType_t uxAutoReload,
281                                                                 void * const pvTimerID,
282                                                                 TimerCallbackFunction_t pxCallbackFunction )
283         {
284         Timer_t *pxNewTimer;
285
286                 pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) );
287
288                 if( pxNewTimer != NULL )
289                 {
290                         prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
291
292                         #if( configSUPPORT_STATIC_ALLOCATION == 1 )
293                         {
294                                 /* Timers can be created statically or dynamically, so note this
295                                 timer was created dynamically in case the timer is later
296                                 deleted. */
297                                 pxNewTimer->ucStaticallyAllocated = pdFALSE;
298                         }
299                         #endif /* configSUPPORT_STATIC_ALLOCATION */
300                 }
301
302                 return pxNewTimer;
303         }
304
305 #endif /* configSUPPORT_STATIC_ALLOCATION */
306 /*-----------------------------------------------------------*/
307
308 #if( configSUPPORT_STATIC_ALLOCATION == 1 )
309
310         TimerHandle_t xTimerCreateStatic(       const char * const pcTimerName,         /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
311                                                                                 const TickType_t xTimerPeriodInTicks,
312                                                                                 const UBaseType_t uxAutoReload,
313                                                                                 void * const pvTimerID,
314                                                                                 TimerCallbackFunction_t pxCallbackFunction,
315                                                                                 StaticTimer_t *pxTimerBuffer )
316         {
317         Timer_t *pxNewTimer;
318
319                 #if( configASSERT_DEFINED == 1 )
320                 {
321                         /* Sanity check that the size of the structure used to declare a
322                         variable of type StaticTimer_t equals the size of the real timer
323                         structure. */
324                         volatile size_t xSize = sizeof( StaticTimer_t );
325                         configASSERT( xSize == sizeof( Timer_t ) );
326                 }
327                 #endif /* configASSERT_DEFINED */
328
329                 /* A pointer to a StaticTimer_t structure MUST be provided, use it. */
330                 configASSERT( pxTimerBuffer );
331                 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. */
332
333                 if( pxNewTimer != NULL )
334                 {
335                         prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
336
337                         #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
338                         {
339                                 /* Timers can be created statically or dynamically so note this
340                                 timer was created statically in case it is later deleted. */
341                                 pxNewTimer->ucStaticallyAllocated = pdTRUE;
342                         }
343                         #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
344                 }
345
346                 return pxNewTimer;
347         }
348
349 #endif /* configSUPPORT_STATIC_ALLOCATION */
350 /*-----------------------------------------------------------*/
351
352 static void prvInitialiseNewTimer(      const char * const pcTimerName,                 /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
353                                                                         const TickType_t xTimerPeriodInTicks,
354                                                                         const UBaseType_t uxAutoReload,
355                                                                         void * const pvTimerID,
356                                                                         TimerCallbackFunction_t pxCallbackFunction,
357                                                                         Timer_t *pxNewTimer )
358 {
359         /* 0 is not a valid value for xTimerPeriodInTicks. */
360         configASSERT( ( xTimerPeriodInTicks > 0 ) );
361
362         if( pxNewTimer != NULL )
363         {
364                 /* Ensure the infrastructure used by the timer service task has been
365                 created/initialised. */
366                 prvCheckForValidListAndQueue();
367
368                 /* Initialise the timer structure members using the function
369                 parameters. */
370                 pxNewTimer->pcTimerName = pcTimerName;
371                 pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
372                 pxNewTimer->uxAutoReload = uxAutoReload;
373                 pxNewTimer->pvTimerID = pvTimerID;
374                 pxNewTimer->pxCallbackFunction = pxCallbackFunction;
375                 vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );
376                 traceTIMER_CREATE( pxNewTimer );
377         }
378 }
379 /*-----------------------------------------------------------*/
380
381 BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait )
382 {
383 BaseType_t xReturn = pdFAIL;
384 DaemonTaskMessage_t xMessage;
385
386         configASSERT( xTimer );
387
388         /* Send a message to the timer service task to perform a particular action
389         on a particular timer definition. */
390         if( xTimerQueue != NULL )
391         {
392                 /* Send a command to the timer service task to start the xTimer timer. */
393                 xMessage.xMessageID = xCommandID;
394                 xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
395                 xMessage.u.xTimerParameters.pxTimer = ( Timer_t * ) xTimer;
396
397                 if( xCommandID < tmrFIRST_FROM_ISR_COMMAND )
398                 {
399                         if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
400                         {
401                                 xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
402                         }
403                         else
404                         {
405                                 xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
406                         }
407                 }
408                 else
409                 {
410                         xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
411                 }
412
413                 traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
414         }
415         else
416         {
417                 mtCOVERAGE_TEST_MARKER();
418         }
419
420         return xReturn;
421 }
422 /*-----------------------------------------------------------*/
423
424 TaskHandle_t xTimerGetTimerDaemonTaskHandle( void )
425 {
426         /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
427         started, then xTimerTaskHandle will be NULL. */
428         configASSERT( ( xTimerTaskHandle != NULL ) );
429         return xTimerTaskHandle;
430 }
431 /*-----------------------------------------------------------*/
432
433 TickType_t xTimerGetPeriod( TimerHandle_t xTimer )
434 {
435 Timer_t *pxTimer = ( Timer_t * ) xTimer;
436
437         configASSERT( xTimer );
438         return pxTimer->xTimerPeriodInTicks;
439 }
440 /*-----------------------------------------------------------*/
441
442 TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer )
443 {
444 Timer_t * pxTimer = ( Timer_t * ) xTimer;
445 TickType_t xReturn;
446
447         configASSERT( xTimer );
448         xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
449         return xReturn;
450 }
451 /*-----------------------------------------------------------*/
452
453 const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
454 {
455 Timer_t *pxTimer = ( Timer_t * ) xTimer;
456
457         configASSERT( xTimer );
458         return pxTimer->pcTimerName;
459 }
460 /*-----------------------------------------------------------*/
461
462 static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow )
463 {
464 BaseType_t xResult;
465 Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
466
467         /* Remove the timer from the list of active timers.  A check has already
468         been performed to ensure the list is not empty. */
469         ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
470         traceTIMER_EXPIRED( pxTimer );
471
472         /* If the timer is an auto reload timer then calculate the next
473         expiry time and re-insert the timer in the list of active timers. */
474         if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
475         {
476                 /* The timer is inserted into a list using a time relative to anything
477                 other than the current time.  It will therefore be inserted into the
478                 correct list relative to the time this task thinks it is now. */
479                 if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE )
480                 {
481                         /* The timer expired before it was added to the active timer
482                         list.  Reload it now.  */
483                         xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
484                         configASSERT( xResult );
485                         ( void ) xResult;
486                 }
487                 else
488                 {
489                         mtCOVERAGE_TEST_MARKER();
490                 }
491         }
492         else
493         {
494                 mtCOVERAGE_TEST_MARKER();
495         }
496
497         /* Call the timer callback. */
498         pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
499 }
500 /*-----------------------------------------------------------*/
501
502 static void prvTimerTask( void *pvParameters )
503 {
504 TickType_t xNextExpireTime;
505 BaseType_t xListWasEmpty;
506
507         /* Just to avoid compiler warnings. */
508         ( void ) pvParameters;
509
510         #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 )
511         {
512                 extern void vApplicationDaemonTaskStartupHook( void );
513
514                 /* Allow the application writer to execute some code in the context of
515                 this task at the point the task starts executing.  This is useful if the
516                 application includes initialisation code that would benefit from
517                 executing after the scheduler has been started. */
518                 vApplicationDaemonTaskStartupHook();
519         }
520         #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */
521
522         for( ;; )
523         {
524                 /* Query the timers list to see if it contains any timers, and if so,
525                 obtain the time at which the next timer will expire. */
526                 xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
527
528                 /* If a timer has expired, process it.  Otherwise, block this task
529                 until either a timer does expire, or a command is received. */
530                 prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
531
532                 /* Empty the command queue. */
533                 prvProcessReceivedCommands();
534         }
535 }
536 /*-----------------------------------------------------------*/
537
538 static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty )
539 {
540 TickType_t xTimeNow;
541 BaseType_t xTimerListsWereSwitched;
542
543         vTaskSuspendAll();
544         {
545                 /* Obtain the time now to make an assessment as to whether the timer
546                 has expired or not.  If obtaining the time causes the lists to switch
547                 then don't process this timer as any timers that remained in the list
548                 when the lists were switched will have been processed within the
549                 prvSampleTimeNow() function. */
550                 xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
551                 if( xTimerListsWereSwitched == pdFALSE )
552                 {
553                         /* The tick count has not overflowed, has the timer expired? */
554                         if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
555                         {
556                                 ( void ) xTaskResumeAll();
557                                 prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
558                         }
559                         else
560                         {
561                                 /* The tick count has not overflowed, and the next expire
562                                 time has not been reached yet.  This task should therefore
563                                 block to wait for the next expire time or a command to be
564                                 received - whichever comes first.  The following line cannot
565                                 be reached unless xNextExpireTime > xTimeNow, except in the
566                                 case when the current timer list is empty. */
567                                 if( xListWasEmpty != pdFALSE )
568                                 {
569                                         /* The current timer list is empty - is the overflow list
570                                         also empty? */
571                                         xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList );
572                                 }
573
574                                 vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty );
575
576                                 if( xTaskResumeAll() == pdFALSE )
577                                 {
578                                         /* Yield to wait for either a command to arrive, or the
579                                         block time to expire.  If a command arrived between the
580                                         critical section being exited and this yield then the yield
581                                         will not cause the task to block. */
582                                         portYIELD_WITHIN_API();
583                                 }
584                                 else
585                                 {
586                                         mtCOVERAGE_TEST_MARKER();
587                                 }
588                         }
589                 }
590                 else
591                 {
592                         ( void ) xTaskResumeAll();
593                 }
594         }
595 }
596 /*-----------------------------------------------------------*/
597
598 static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty )
599 {
600 TickType_t xNextExpireTime;
601
602         /* Timers are listed in expiry time order, with the head of the list
603         referencing the task that will expire first.  Obtain the time at which
604         the timer with the nearest expiry time will expire.  If there are no
605         active timers then just set the next expire time to 0.  That will cause
606         this task to unblock when the tick count overflows, at which point the
607         timer lists will be switched and the next expiry time can be
608         re-assessed.  */
609         *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );
610         if( *pxListWasEmpty == pdFALSE )
611         {
612                 xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
613         }
614         else
615         {
616                 /* Ensure the task unblocks when the tick count rolls over. */
617                 xNextExpireTime = ( TickType_t ) 0U;
618         }
619
620         return xNextExpireTime;
621 }
622 /*-----------------------------------------------------------*/
623
624 static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched )
625 {
626 TickType_t xTimeNow;
627 PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */
628
629         xTimeNow = xTaskGetTickCount();
630
631         if( xTimeNow < xLastTime )
632         {
633                 prvSwitchTimerLists();
634                 *pxTimerListsWereSwitched = pdTRUE;
635         }
636         else
637         {
638                 *pxTimerListsWereSwitched = pdFALSE;
639         }
640
641         xLastTime = xTimeNow;
642
643         return xTimeNow;
644 }
645 /*-----------------------------------------------------------*/
646
647 static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime )
648 {
649 BaseType_t xProcessTimerNow = pdFALSE;
650
651         listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
652         listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
653
654         if( xNextExpiryTime <= xTimeNow )
655         {
656                 /* Has the expiry time elapsed between the command to start/reset a
657                 timer was issued, and the time the command was processed? */
658                 if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
659                 {
660                         /* The time between a command being issued and the command being
661                         processed actually exceeds the timers period.  */
662                         xProcessTimerNow = pdTRUE;
663                 }
664                 else
665                 {
666                         vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
667                 }
668         }
669         else
670         {
671                 if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
672                 {
673                         /* If, since the command was issued, the tick count has overflowed
674                         but the expiry time has not, then the timer must have already passed
675                         its expiry time and should be processed immediately. */
676                         xProcessTimerNow = pdTRUE;
677                 }
678                 else
679                 {
680                         vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
681                 }
682         }
683
684         return xProcessTimerNow;
685 }
686 /*-----------------------------------------------------------*/
687
688 static void     prvProcessReceivedCommands( void )
689 {
690 DaemonTaskMessage_t xMessage;
691 Timer_t *pxTimer;
692 BaseType_t xTimerListsWereSwitched, xResult;
693 TickType_t xTimeNow;
694
695         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. */
696         {
697                 #if ( INCLUDE_xTimerPendFunctionCall == 1 )
698                 {
699                         /* Negative commands are pended function calls rather than timer
700                         commands. */
701                         if( xMessage.xMessageID < ( BaseType_t ) 0 )
702                         {
703                                 const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
704
705                                 /* The timer uses the xCallbackParameters member to request a
706                                 callback be executed.  Check the callback is not NULL. */
707                                 configASSERT( pxCallback );
708
709                                 /* Call the function. */
710                                 pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
711                         }
712                         else
713                         {
714                                 mtCOVERAGE_TEST_MARKER();
715                         }
716                 }
717                 #endif /* INCLUDE_xTimerPendFunctionCall */
718
719                 /* Commands that are positive are timer commands rather than pended
720                 function calls. */
721                 if( xMessage.xMessageID >= ( BaseType_t ) 0 )
722                 {
723                         /* The messages uses the xTimerParameters member to work on a
724                         software timer. */
725                         pxTimer = xMessage.u.xTimerParameters.pxTimer;
726
727                         if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */
728                         {
729                                 /* The timer is in a list, remove it. */
730                                 ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
731                         }
732                         else
733                         {
734                                 mtCOVERAGE_TEST_MARKER();
735                         }
736
737                         traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
738
739                         /* In this case the xTimerListsWereSwitched parameter is not used, but
740                         it must be present in the function call.  prvSampleTimeNow() must be
741                         called after the message is received from xTimerQueue so there is no
742                         possibility of a higher priority task adding a message to the message
743                         queue with a time that is ahead of the timer daemon task (because it
744                         pre-empted the timer daemon task after the xTimeNow value was set). */
745                         xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
746
747                         switch( xMessage.xMessageID )
748                         {
749                                 case tmrCOMMAND_START :
750                             case tmrCOMMAND_START_FROM_ISR :
751                             case tmrCOMMAND_RESET :
752                             case tmrCOMMAND_RESET_FROM_ISR :
753                                 case tmrCOMMAND_START_DONT_TRACE :
754                                         /* Start or restart a timer. */
755                                         if( prvInsertTimerInActiveList( pxTimer,  xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE )
756                                         {
757                                                 /* The timer expired before it was added to the active
758                                                 timer list.  Process it now. */
759                                                 pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
760                                                 traceTIMER_EXPIRED( pxTimer );
761
762                                                 if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
763                                                 {
764                                                         xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
765                                                         configASSERT( xResult );
766                                                         ( void ) xResult;
767                                                 }
768                                                 else
769                                                 {
770                                                         mtCOVERAGE_TEST_MARKER();
771                                                 }
772                                         }
773                                         else
774                                         {
775                                                 mtCOVERAGE_TEST_MARKER();
776                                         }
777                                         break;
778
779                                 case tmrCOMMAND_STOP :
780                                 case tmrCOMMAND_STOP_FROM_ISR :
781                                         /* The timer has already been removed from the active list.
782                                         There is nothing to do here. */
783                                         break;
784
785                                 case tmrCOMMAND_CHANGE_PERIOD :
786                                 case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR :
787                                         pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
788                                         configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
789
790                                         /* The new period does not really have a reference, and can
791                                         be longer or shorter than the old one.  The command time is
792                                         therefore set to the current time, and as the period cannot
793                                         be zero the next expiry time can only be in the future,
794                                         meaning (unlike for the xTimerStart() case above) there is
795                                         no fail case that needs to be handled here. */
796                                         ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
797                                         break;
798
799                                 case tmrCOMMAND_DELETE :
800                                         /* The timer has already been removed from the active list,
801                                         just free up the memory if the memory was dynamically
802                                         allocated. */
803                                         #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) )
804                                         {
805                                                 /* The timer can only have been allocated dynamically -
806                                                 free it again. */
807                                                 vPortFree( pxTimer );
808                                         }
809                                         #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
810                                         {
811                                                 /* The timer could have been allocated statically or
812                                                 dynamically, so check before attempting to free the
813                                                 memory. */
814                                                 if( pxTimer->ucStaticallyAllocated == ( uint8_t ) pdFALSE )
815                                                 {
816                                                         vPortFree( pxTimer );
817                                                 }
818                                                 else
819                                                 {
820                                                         mtCOVERAGE_TEST_MARKER();
821                                                 }
822                                         }
823                                         #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
824                                         break;
825
826                                 default :
827                                         /* Don't expect to get here. */
828                                         break;
829                         }
830                 }
831         }
832 }
833 /*-----------------------------------------------------------*/
834
835 static void prvSwitchTimerLists( void )
836 {
837 TickType_t xNextExpireTime, xReloadTime;
838 List_t *pxTemp;
839 Timer_t *pxTimer;
840 BaseType_t xResult;
841
842         /* The tick count has overflowed.  The timer lists must be switched.
843         If there are any timers still referenced from the current timer list
844         then they must have expired and should be processed before the lists
845         are switched. */
846         while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )
847         {
848                 xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
849
850                 /* Remove the timer from the list. */
851                 pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
852                 ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
853                 traceTIMER_EXPIRED( pxTimer );
854
855                 /* Execute its callback, then send a command to restart the timer if
856                 it is an auto-reload timer.  It cannot be restarted here as the lists
857                 have not yet been switched. */
858                 pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
859
860                 if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
861                 {
862                         /* Calculate the reload value, and if the reload value results in
863                         the timer going into the same timer list then it has already expired
864                         and the timer should be re-inserted into the current list so it is
865                         processed again within this loop.  Otherwise a command should be sent
866                         to restart the timer to ensure it is only inserted into a list after
867                         the lists have been swapped. */
868                         xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
869                         if( xReloadTime > xNextExpireTime )
870                         {
871                                 listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
872                                 listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
873                                 vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
874                         }
875                         else
876                         {
877                                 xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
878                                 configASSERT( xResult );
879                                 ( void ) xResult;
880                         }
881                 }
882                 else
883                 {
884                         mtCOVERAGE_TEST_MARKER();
885                 }
886         }
887
888         pxTemp = pxCurrentTimerList;
889         pxCurrentTimerList = pxOverflowTimerList;
890         pxOverflowTimerList = pxTemp;
891 }
892 /*-----------------------------------------------------------*/
893
894 static void prvCheckForValidListAndQueue( void )
895 {
896         /* Check that the list from which active timers are referenced, and the
897         queue used to communicate with the timer service, have been
898         initialised. */
899         taskENTER_CRITICAL();
900         {
901                 if( xTimerQueue == NULL )
902                 {
903                         vListInitialise( &xActiveTimerList1 );
904                         vListInitialise( &xActiveTimerList2 );
905                         pxCurrentTimerList = &xActiveTimerList1;
906                         pxOverflowTimerList = &xActiveTimerList2;
907
908                         #if( configSUPPORT_STATIC_ALLOCATION == 1 )
909                         {
910                                 /* The timer queue is allocated statically in case
911                                 configSUPPORT_DYNAMIC_ALLOCATION is 0. */
912                                 static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
913                                 static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
914
915                                 xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue );
916                         }
917                         #else
918                         {
919                                 xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) );
920                         }
921                         #endif
922
923                         #if ( configQUEUE_REGISTRY_SIZE > 0 )
924                         {
925                                 if( xTimerQueue != NULL )
926                                 {
927                                         vQueueAddToRegistry( xTimerQueue, "TmrQ" );
928                                 }
929                                 else
930                                 {
931                                         mtCOVERAGE_TEST_MARKER();
932                                 }
933                         }
934                         #endif /* configQUEUE_REGISTRY_SIZE */
935                 }
936                 else
937                 {
938                         mtCOVERAGE_TEST_MARKER();
939                 }
940         }
941         taskEXIT_CRITICAL();
942 }
943 /*-----------------------------------------------------------*/
944
945 BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer )
946 {
947 BaseType_t xTimerIsInActiveList;
948 Timer_t *pxTimer = ( Timer_t * ) xTimer;
949
950         configASSERT( xTimer );
951
952         /* Is the timer in the list of active timers? */
953         taskENTER_CRITICAL();
954         {
955                 /* Checking to see if it is in the NULL list in effect checks to see if
956                 it is referenced from either the current or the overflow timer lists in
957                 one go, but the logic has to be reversed, hence the '!'. */
958                 xTimerIsInActiveList = ( BaseType_t ) !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) ); /*lint !e961. Cast is only redundant when NULL is passed into the macro. */
959         }
960         taskEXIT_CRITICAL();
961
962         return xTimerIsInActiveList;
963 } /*lint !e818 Can't be pointer to const due to the typedef. */
964 /*-----------------------------------------------------------*/
965
966 void *pvTimerGetTimerID( const TimerHandle_t xTimer )
967 {
968 Timer_t * const pxTimer = ( Timer_t * ) xTimer;
969 void *pvReturn;
970
971         configASSERT( xTimer );
972
973         taskENTER_CRITICAL();
974         {
975                 pvReturn = pxTimer->pvTimerID;
976         }
977         taskEXIT_CRITICAL();
978
979         return pvReturn;
980 }
981 /*-----------------------------------------------------------*/
982
983 void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID )
984 {
985 Timer_t * const pxTimer = ( Timer_t * ) xTimer;
986
987         configASSERT( xTimer );
988
989         taskENTER_CRITICAL();
990         {
991                 pxTimer->pvTimerID = pvNewID;
992         }
993         taskEXIT_CRITICAL();
994 }
995 /*-----------------------------------------------------------*/
996
997 #if( INCLUDE_xTimerPendFunctionCall == 1 )
998
999         BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken )
1000         {
1001         DaemonTaskMessage_t xMessage;
1002         BaseType_t xReturn;
1003
1004                 /* Complete the message with the function parameters and post it to the
1005                 daemon task. */
1006                 xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
1007                 xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
1008                 xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
1009                 xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
1010
1011                 xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
1012
1013                 tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
1014
1015                 return xReturn;
1016         }
1017
1018 #endif /* INCLUDE_xTimerPendFunctionCall */
1019 /*-----------------------------------------------------------*/
1020
1021 #if( INCLUDE_xTimerPendFunctionCall == 1 )
1022
1023         BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait )
1024         {
1025         DaemonTaskMessage_t xMessage;
1026         BaseType_t xReturn;
1027
1028                 /* This function can only be called after a timer has been created or
1029                 after the scheduler has been started because, until then, the timer
1030                 queue does not exist. */
1031                 configASSERT( xTimerQueue );
1032
1033                 /* Complete the message with the function parameters and post it to the
1034                 daemon task. */
1035                 xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
1036                 xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
1037                 xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
1038                 xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
1039
1040                 xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
1041
1042                 tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
1043
1044                 return xReturn;
1045         }
1046
1047 #endif /* INCLUDE_xTimerPendFunctionCall */
1048 /*-----------------------------------------------------------*/
1049
1050 #if ( configUSE_TRACE_FACILITY == 1 )
1051
1052         UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer )
1053         {
1054                 return ( ( Timer_t * ) xTimer )->uxTimerNumber;
1055         }
1056
1057 #endif /* configUSE_TRACE_FACILITY */
1058 /*-----------------------------------------------------------*/
1059
1060 #if ( configUSE_TRACE_FACILITY == 1 )
1061
1062         void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber )
1063         {
1064                 ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber;
1065         }
1066
1067 #endif /* configUSE_TRACE_FACILITY */
1068 /*-----------------------------------------------------------*/
1069
1070 /* This entire source file will be skipped if the application is not configured
1071 to include software timer functionality.  If you want to include software timer
1072 functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
1073 #endif /* configUSE_TIMERS == 1 */
1074
1075
1076