2 * FreeRTOS SMP Kernel V202110.00
3 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
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.
22 * https://www.FreeRTOS.org
23 * https://github.com/FreeRTOS
27 /* Standard includes. */
30 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
31 * all the API functions to use the MPU wrappers. That should only be done when
32 * task.h is included from an application file. */
33 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
40 #if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 )
41 #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
44 /* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
45 * because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
46 * for the header files above, but not in this file, in order to generate the
47 * correct privileged Vs unprivileged linkage and placement. */
48 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e9021 !e961 !e750. */
51 /* This entire source file will be skipped if the application is not configured
52 * to include software timer functionality. This #if is closed at the very bottom
53 * of this file. If you want to include software timer functionality then ensure
54 * configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
55 #if ( configUSE_TIMERS == 1 )
57 /* Misc definitions. */
58 #define tmrNO_DELAY ( TickType_t ) 0U
60 /* The name assigned to the timer service task. This can be overridden by
61 * defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */
62 #ifndef configTIMER_SERVICE_TASK_NAME
63 #define configTIMER_SERVICE_TASK_NAME "Tmr Svc"
66 /* Bit definitions used in the ucStatus member of a timer structure. */
67 #define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 )
68 #define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 )
69 #define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 )
71 /* The definition of the timers themselves. */
72 typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */
74 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. */
75 ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */
76 TickType_t xTimerPeriodInTicks; /*<< How quickly and often the timer expires. */
77 void * pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */
78 portTIMER_CALLBACK_ATTRIBUTE
79 TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */
80 #if ( configUSE_TRACE_FACILITY == 1 )
81 UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */
83 uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */
86 /* The old xTIMER name is maintained above then typedefed to the new Timer_t
87 * name below to enable the use of older kernel aware debuggers. */
88 typedef xTIMER Timer_t;
90 /* The definition of messages that can be sent and received on the timer queue.
91 * Two types of message can be queued - messages that manipulate a software timer,
92 * and messages that request the execution of a non-timer related callback. The
93 * two message types are defined in two separate structures, xTimerParametersType
94 * and xCallbackParametersType respectively. */
95 typedef struct tmrTimerParameters
97 TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
98 Timer_t * pxTimer; /*<< The timer to which the command will be applied. */
102 typedef struct tmrCallbackParameters
104 portTIMER_CALLBACK_ATTRIBUTE
105 PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */
106 void * pvParameter1; /* << The value that will be used as the callback functions first parameter. */
107 uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */
108 } CallbackParameters_t;
110 /* The structure that contains the two message types, along with an identifier
111 * that is used to determine which message type is valid. */
112 typedef struct tmrTimerQueueMessage
114 BaseType_t xMessageID; /*<< The command being sent to the timer service task. */
117 TimerParameter_t xTimerParameters;
119 /* Don't include xCallbackParameters if it is not going to be used as
120 * it makes the structure (and therefore the timer queue) larger. */
121 #if ( INCLUDE_xTimerPendFunctionCall == 1 )
122 CallbackParameters_t xCallbackParameters;
123 #endif /* INCLUDE_xTimerPendFunctionCall */
125 } DaemonTaskMessage_t;
127 /*lint -save -e956 A manual analysis and inspection has been used to determine
128 * which static variables must be declared volatile. */
130 /* The list in which active timers are stored. Timers are referenced in expire
131 * time order, with the nearest expiry time at the front of the list. Only the
132 * timer service task is allowed to access these lists.
133 * xActiveTimerList1 and xActiveTimerList2 could be at function scope but that
134 * breaks some kernel aware debuggers, and debuggers that reply on removing the
135 * static qualifier. */
136 PRIVILEGED_DATA static List_t xActiveTimerList1;
137 PRIVILEGED_DATA static List_t xActiveTimerList2;
138 PRIVILEGED_DATA static List_t * pxCurrentTimerList;
139 PRIVILEGED_DATA static List_t * pxOverflowTimerList;
141 /* A queue that is used to send commands to the timer service task. */
142 PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
143 PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
147 /*-----------------------------------------------------------*/
150 * Initialise the infrastructure used by the timer service task if it has not
151 * been initialised already.
153 static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;
156 * The timer service task (daemon). Timer functionality is controlled by this
157 * task. Other tasks communicate with the timer service task using the
160 static portTASK_FUNCTION_PROTO( prvTimerTask, pvParameters ) PRIVILEGED_FUNCTION;
163 * Called by the timer service task to interpret and process a command it
164 * received on the timer queue.
166 static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;
169 * Insert the timer into either xActiveTimerList1, or xActiveTimerList2,
170 * depending on if the expire time causes a timer counter overflow.
172 static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer,
173 const TickType_t xNextExpiryTime,
174 const TickType_t xTimeNow,
175 const TickType_t xCommandTime ) PRIVILEGED_FUNCTION;
178 * An active timer has reached its expire time. Reload the timer if it is an
179 * auto-reload timer, then call its callback.
181 static void prvProcessExpiredTimer( const TickType_t xNextExpireTime,
182 const TickType_t xTimeNow ) PRIVILEGED_FUNCTION;
185 * The tick count has overflowed. Switch the timer lists after ensuring the
186 * current timer list does not still reference some timers.
188 static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION;
191 * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE
192 * if a tick count overflow occurred since prvSampleTimeNow() was last called.
194 static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;
197 * If the timer list contains any active timers then return the expire time of
198 * the timer that will expire first and set *pxListWasEmpty to false. If the
199 * timer list does not contain any timers then return 0 and set *pxListWasEmpty
202 static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION;
205 * If a timer has expired, process it. Otherwise, block the timer service task
206 * until either a timer does expire or a command is received.
208 static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime,
209 BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION;
212 * Called after a Timer_t structure has been allocated either statically or
213 * dynamically to fill in the structure's members.
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 /*-----------------------------------------------------------*/
223 BaseType_t xTimerCreateTimerTask( void )
225 BaseType_t xReturn = pdFAIL;
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();
233 if( xTimerQueue != NULL )
235 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
237 StaticTask_t * pxTimerTaskTCBBuffer = NULL;
238 StackType_t * pxTimerTaskStackBuffer = NULL;
239 uint32_t ulTimerTaskStackSize;
241 vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize );
242 xTimerTaskHandle = xTaskCreateStatic( prvTimerTask,
243 configTIMER_SERVICE_TASK_NAME,
244 ulTimerTaskStackSize,
246 ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT,
247 pxTimerTaskStackBuffer,
248 pxTimerTaskTCBBuffer );
250 if( xTimerTaskHandle != NULL )
255 #else /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
257 xReturn = xTaskCreate( prvTimerTask,
258 configTIMER_SERVICE_TASK_NAME,
259 configTIMER_TASK_STACK_DEPTH,
261 ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT,
264 #endif /* configSUPPORT_STATIC_ALLOCATION */
268 mtCOVERAGE_TEST_MARKER();
271 configASSERT( xReturn );
274 /*-----------------------------------------------------------*/
276 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
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 )
284 Timer_t * pxNewTimer;
286 pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */
288 if( pxNewTimer != NULL )
290 /* Status is thus far zero as the timer is not created statically
291 * and has not been started. The auto-reload bit may get set in
292 * prvInitialiseNewTimer. */
293 pxNewTimer->ucStatus = 0x00;
294 prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
300 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
301 /*-----------------------------------------------------------*/
303 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
305 TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
306 const TickType_t xTimerPeriodInTicks,
307 const UBaseType_t uxAutoReload,
308 void * const pvTimerID,
309 TimerCallbackFunction_t pxCallbackFunction,
310 StaticTimer_t * pxTimerBuffer )
312 Timer_t * pxNewTimer;
314 #if ( configASSERT_DEFINED == 1 )
316 /* Sanity check that the size of the structure used to declare a
317 * variable of type StaticTimer_t equals the size of the real timer
319 volatile size_t xSize = sizeof( StaticTimer_t );
320 configASSERT( xSize == sizeof( Timer_t ) );
321 ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */
323 #endif /* configASSERT_DEFINED */
325 /* A pointer to a StaticTimer_t structure MUST be provided, use it. */
326 configASSERT( pxTimerBuffer );
327 pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */
329 if( pxNewTimer != NULL )
331 /* Timers can be created statically or dynamically so note this
332 * timer was created statically in case it is later deleted. The
333 * auto-reload bit may get set in prvInitialiseNewTimer(). */
334 pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED;
336 prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
342 #endif /* configSUPPORT_STATIC_ALLOCATION */
343 /*-----------------------------------------------------------*/
345 static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
346 const TickType_t xTimerPeriodInTicks,
347 const UBaseType_t uxAutoReload,
348 void * const pvTimerID,
349 TimerCallbackFunction_t pxCallbackFunction,
350 Timer_t * pxNewTimer )
352 /* 0 is not a valid value for xTimerPeriodInTicks. */
353 configASSERT( ( xTimerPeriodInTicks > 0 ) );
355 if( pxNewTimer != NULL )
357 /* Ensure the infrastructure used by the timer service task has been
358 * created/initialised. */
359 prvCheckForValidListAndQueue();
361 /* Initialise the timer structure members using the function
363 pxNewTimer->pcTimerName = pcTimerName;
364 pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
365 pxNewTimer->pvTimerID = pvTimerID;
366 pxNewTimer->pxCallbackFunction = pxCallbackFunction;
367 vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );
369 if( uxAutoReload != pdFALSE )
371 pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD;
374 traceTIMER_CREATE( pxNewTimer );
377 /*-----------------------------------------------------------*/
379 BaseType_t xTimerGenericCommandFromTask( TimerHandle_t xTimer,
380 const BaseType_t xCommandID,
381 const TickType_t xOptionalValue,
382 BaseType_t * const pxHigherPriorityTaskWoken,
383 const TickType_t xTicksToWait )
385 BaseType_t xReturn = pdFAIL;
386 DaemonTaskMessage_t xMessage;
388 configASSERT( xTimer );
390 /* Send a message to the timer service task to perform a particular action
391 * on a particular timer definition. */
392 if( xTimerQueue != NULL )
394 /* Send a command to the timer service task to start the xTimer timer. */
395 xMessage.xMessageID = xCommandID;
396 xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
397 xMessage.u.xTimerParameters.pxTimer = xTimer;
399 configASSERT( xCommandID < tmrFIRST_FROM_ISR_COMMAND );
401 if( xCommandID < tmrFIRST_FROM_ISR_COMMAND )
403 if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
405 xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
409 xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
413 traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
417 mtCOVERAGE_TEST_MARKER();
422 /*-----------------------------------------------------------*/
424 BaseType_t xTimerGenericCommandFromISR( TimerHandle_t xTimer,
425 const BaseType_t xCommandID,
426 const TickType_t xOptionalValue,
427 BaseType_t * const pxHigherPriorityTaskWoken,
428 const TickType_t xTicksToWait )
430 BaseType_t xReturn = pdFAIL;
431 DaemonTaskMessage_t xMessage;
433 configASSERT( xTimer );
435 /* Send a message to the timer service task to perform a particular action
436 * on a particular timer definition. */
437 if( xTimerQueue != NULL )
439 /* Send a command to the timer service task to start the xTimer timer. */
440 xMessage.xMessageID = xCommandID;
441 xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
442 xMessage.u.xTimerParameters.pxTimer = xTimer;
444 configASSERT( xCommandID >= tmrFIRST_FROM_ISR_COMMAND );
446 if( xCommandID >= tmrFIRST_FROM_ISR_COMMAND )
448 xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
451 traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
455 mtCOVERAGE_TEST_MARKER();
460 /*-----------------------------------------------------------*/
462 TaskHandle_t xTimerGetTimerDaemonTaskHandle( void )
464 /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
465 * started, then xTimerTaskHandle will be NULL. */
466 configASSERT( ( xTimerTaskHandle != NULL ) );
467 return xTimerTaskHandle;
469 /*-----------------------------------------------------------*/
471 TickType_t xTimerGetPeriod( TimerHandle_t xTimer )
473 Timer_t * pxTimer = xTimer;
475 configASSERT( xTimer );
476 return pxTimer->xTimerPeriodInTicks;
478 /*-----------------------------------------------------------*/
480 void vTimerSetReloadMode( TimerHandle_t xTimer,
481 const UBaseType_t uxAutoReload )
483 Timer_t * pxTimer = xTimer;
485 configASSERT( xTimer );
486 taskENTER_CRITICAL();
488 if( uxAutoReload != pdFALSE )
490 pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD;
494 pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD;
499 /*-----------------------------------------------------------*/
501 UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer )
503 Timer_t * pxTimer = xTimer;
504 UBaseType_t uxReturn;
506 configASSERT( xTimer );
507 taskENTER_CRITICAL();
509 if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) == 0 )
511 /* Not an auto-reload timer. */
512 uxReturn = ( UBaseType_t ) pdFALSE;
516 /* Is an auto-reload timer. */
517 uxReturn = ( UBaseType_t ) pdTRUE;
524 /*-----------------------------------------------------------*/
526 TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer )
528 Timer_t * pxTimer = xTimer;
531 configASSERT( xTimer );
532 xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
535 /*-----------------------------------------------------------*/
537 const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
539 Timer_t * pxTimer = xTimer;
541 configASSERT( xTimer );
542 return pxTimer->pcTimerName;
544 /*-----------------------------------------------------------*/
546 static void prvProcessExpiredTimer( const TickType_t xNextExpireTime,
547 const TickType_t xTimeNow )
550 Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
552 /* Remove the timer from the list of active timers. A check has already
553 * been performed to ensure the list is not empty. */
555 ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
556 traceTIMER_EXPIRED( pxTimer );
558 /* If the timer is an auto-reload timer then calculate the next
559 * expiry time and re-insert the timer in the list of active timers. */
560 if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
562 /* The timer is inserted into a list using a time relative to anything
563 * other than the current time. It will therefore be inserted into the
564 * correct list relative to the time this task thinks it is now. */
565 if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE )
567 /* The timer expired before it was added to the active timer
568 * list. Reload it now. */
569 xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
570 configASSERT( xResult );
575 mtCOVERAGE_TEST_MARKER();
580 pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
581 mtCOVERAGE_TEST_MARKER();
584 /* Call the timer callback. */
585 pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
587 /*-----------------------------------------------------------*/
589 static portTASK_FUNCTION( prvTimerTask, pvParameters )
591 TickType_t xNextExpireTime;
592 BaseType_t xListWasEmpty;
594 /* Just to avoid compiler warnings. */
595 ( void ) pvParameters;
597 #if ( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 )
599 extern void vApplicationDaemonTaskStartupHook( void );
601 /* Allow the application writer to execute some code in the context of
602 * this task at the point the task starts executing. This is useful if the
603 * application includes initialisation code that would benefit from
604 * executing after the scheduler has been started. */
605 vApplicationDaemonTaskStartupHook();
607 #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */
611 /* Query the timers list to see if it contains any timers, and if so,
612 * obtain the time at which the next timer will expire. */
613 xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
615 /* If a timer has expired, process it. Otherwise, block this task
616 * until either a timer does expire, or a command is received. */
617 prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
619 /* Empty the command queue. */
620 prvProcessReceivedCommands();
623 /*-----------------------------------------------------------*/
625 static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime,
626 BaseType_t xListWasEmpty )
629 BaseType_t xTimerListsWereSwitched;
633 /* Obtain the time now to make an assessment as to whether the timer
634 * has expired or not. If obtaining the time causes the lists to switch
635 * then don't process this timer as any timers that remained in the list
636 * when the lists were switched will have been processed within the
637 * prvSampleTimeNow() function. */
638 xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
640 if( xTimerListsWereSwitched == pdFALSE )
642 /* The tick count has not overflowed, has the timer expired? */
643 if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
645 ( void ) xTaskResumeAll();
646 prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
650 /* The tick count has not overflowed, and the next expire
651 * time has not been reached yet. This task should therefore
652 * block to wait for the next expire time or a command to be
653 * received - whichever comes first. The following line cannot
654 * be reached unless xNextExpireTime > xTimeNow, except in the
655 * case when the current timer list is empty. */
656 if( xListWasEmpty != pdFALSE )
658 /* The current timer list is empty - is the overflow list
660 xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList );
663 vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty );
665 if( xTaskResumeAll() == pdFALSE )
667 /* Yield to wait for either a command to arrive, or the
668 * block time to expire. If a command arrived between the
669 * critical section being exited and this yield then the yield
670 * will not cause the task to block. */
671 vTaskYieldWithinAPI();
675 mtCOVERAGE_TEST_MARKER();
681 ( void ) xTaskResumeAll();
685 /*-----------------------------------------------------------*/
687 static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty )
689 TickType_t xNextExpireTime;
691 /* Timers are listed in expiry time order, with the head of the list
692 * referencing the task that will expire first. Obtain the time at which
693 * the timer with the nearest expiry time will expire. If there are no
694 * active timers then just set the next expire time to 0. That will cause
695 * this task to unblock when the tick count overflows, at which point the
696 * timer lists will be switched and the next expiry time can be
698 *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );
700 if( *pxListWasEmpty == pdFALSE )
702 xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
706 /* Ensure the task unblocks when the tick count rolls over. */
707 xNextExpireTime = ( TickType_t ) 0U;
710 return xNextExpireTime;
712 /*-----------------------------------------------------------*/
714 static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched )
717 PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */
719 xTimeNow = xTaskGetTickCount();
721 if( xTimeNow < xLastTime )
723 prvSwitchTimerLists();
724 *pxTimerListsWereSwitched = pdTRUE;
728 *pxTimerListsWereSwitched = pdFALSE;
731 xLastTime = xTimeNow;
735 /*-----------------------------------------------------------*/
737 static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer,
738 const TickType_t xNextExpiryTime,
739 const TickType_t xTimeNow,
740 const TickType_t xCommandTime )
742 BaseType_t xProcessTimerNow = pdFALSE;
744 listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
745 listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
747 if( xNextExpiryTime <= xTimeNow )
749 /* Has the expiry time elapsed between the command to start/reset a
750 * timer was issued, and the time the command was processed? */
751 if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
753 /* The time between a command being issued and the command being
754 * processed actually exceeds the timers period. */
755 xProcessTimerNow = pdTRUE;
759 vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
764 if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
766 /* If, since the command was issued, the tick count has overflowed
767 * but the expiry time has not, then the timer must have already passed
768 * its expiry time and should be processed immediately. */
769 xProcessTimerNow = pdTRUE;
773 vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
777 return xProcessTimerNow;
779 /*-----------------------------------------------------------*/
781 static void prvProcessReceivedCommands( void )
783 DaemonTaskMessage_t xMessage;
785 BaseType_t xTimerListsWereSwitched, xResult;
788 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. */
790 #if ( INCLUDE_xTimerPendFunctionCall == 1 )
792 /* Negative commands are pended function calls rather than timer
794 if( xMessage.xMessageID < ( BaseType_t ) 0 )
796 const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
798 /* The timer uses the xCallbackParameters member to request a
799 * callback be executed. Check the callback is not NULL. */
800 configASSERT( pxCallback );
802 /* Call the function. */
803 pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
807 mtCOVERAGE_TEST_MARKER();
810 #endif /* INCLUDE_xTimerPendFunctionCall */
812 /* Commands that are positive are timer commands rather than pended
814 if( xMessage.xMessageID >= ( BaseType_t ) 0 )
816 /* The messages uses the xTimerParameters member to work on a
818 pxTimer = xMessage.u.xTimerParameters.pxTimer;
820 if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */
822 /* The timer is in a list, remove it. */
823 ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
827 mtCOVERAGE_TEST_MARKER();
830 traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
832 /* In this case the xTimerListsWereSwitched parameter is not used, but
833 * it must be present in the function call. prvSampleTimeNow() must be
834 * called after the message is received from xTimerQueue so there is no
835 * possibility of a higher priority task adding a message to the message
836 * queue with a time that is ahead of the timer daemon task (because it
837 * pre-empted the timer daemon task after the xTimeNow value was set). */
838 xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
840 switch( xMessage.xMessageID )
842 case tmrCOMMAND_START:
843 case tmrCOMMAND_START_FROM_ISR:
844 case tmrCOMMAND_RESET:
845 case tmrCOMMAND_RESET_FROM_ISR:
846 case tmrCOMMAND_START_DONT_TRACE:
847 /* Start or restart a timer. */
848 pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
850 if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE )
852 /* The timer expired before it was added to the active
853 * timer list. Process it now. */
854 pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
855 traceTIMER_EXPIRED( pxTimer );
857 if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
859 xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
860 configASSERT( xResult );
865 mtCOVERAGE_TEST_MARKER();
870 mtCOVERAGE_TEST_MARKER();
875 case tmrCOMMAND_STOP:
876 case tmrCOMMAND_STOP_FROM_ISR:
877 /* The timer has already been removed from the active list. */
878 pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
881 case tmrCOMMAND_CHANGE_PERIOD:
882 case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR:
883 pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
884 pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
885 configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
887 /* The new period does not really have a reference, and can
888 * be longer or shorter than the old one. The command time is
889 * therefore set to the current time, and as the period cannot
890 * be zero the next expiry time can only be in the future,
891 * meaning (unlike for the xTimerStart() case above) there is
892 * no fail case that needs to be handled here. */
893 ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
896 case tmrCOMMAND_DELETE:
897 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
899 /* The timer has already been removed from the active list,
900 * just free up the memory if the memory was dynamically
902 if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 )
904 vPortFree( pxTimer );
908 pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
911 #else /* if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) */
913 /* If dynamic allocation is not enabled, the memory
914 * could not have been dynamically allocated. So there is
915 * no need to free the memory - just mark the timer as
917 pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
919 #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
923 /* Don't expect to get here. */
929 /*-----------------------------------------------------------*/
931 static void prvSwitchTimerLists( void )
933 TickType_t xNextExpireTime, xReloadTime;
938 /* The tick count has overflowed. The timer lists must be switched.
939 * If there are any timers still referenced from the current timer list
940 * then they must have expired and should be processed before the lists
942 while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )
944 xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
946 /* Remove the timer from the list. */
947 pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
948 ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
949 traceTIMER_EXPIRED( pxTimer );
951 /* Execute its callback, then send a command to restart the timer if
952 * it is an auto-reload timer. It cannot be restarted here as the lists
953 * have not yet been switched. */
954 pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
956 if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
958 /* Calculate the reload value, and if the reload value results in
959 * the timer going into the same timer list then it has already expired
960 * and the timer should be re-inserted into the current list so it is
961 * processed again within this loop. Otherwise a command should be sent
962 * to restart the timer to ensure it is only inserted into a list after
963 * the lists have been swapped. */
964 xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
966 if( xReloadTime > xNextExpireTime )
968 listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
969 listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
970 vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
974 xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
975 configASSERT( xResult );
981 mtCOVERAGE_TEST_MARKER();
985 pxTemp = pxCurrentTimerList;
986 pxCurrentTimerList = pxOverflowTimerList;
987 pxOverflowTimerList = pxTemp;
989 /*-----------------------------------------------------------*/
991 static void prvCheckForValidListAndQueue( void )
993 /* Check that the list from which active timers are referenced, and the
994 * queue used to communicate with the timer service, have been
996 taskENTER_CRITICAL();
998 if( xTimerQueue == NULL )
1000 vListInitialise( &xActiveTimerList1 );
1001 vListInitialise( &xActiveTimerList2 );
1002 pxCurrentTimerList = &xActiveTimerList1;
1003 pxOverflowTimerList = &xActiveTimerList2;
1005 #if ( configSUPPORT_STATIC_ALLOCATION == 1 )
1007 /* The timer queue is allocated statically in case
1008 * configSUPPORT_DYNAMIC_ALLOCATION is 0. */
1009 PRIVILEGED_DATA static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
1010 PRIVILEGED_DATA 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. */
1012 xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue );
1016 xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) );
1018 #endif /* if ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
1020 #if ( configQUEUE_REGISTRY_SIZE > 0 )
1022 if( xTimerQueue != NULL )
1024 vQueueAddToRegistry( xTimerQueue, "TmrQ" );
1028 mtCOVERAGE_TEST_MARKER();
1031 #endif /* configQUEUE_REGISTRY_SIZE */
1035 mtCOVERAGE_TEST_MARKER();
1038 taskEXIT_CRITICAL();
1040 /*-----------------------------------------------------------*/
1042 BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer )
1045 Timer_t * pxTimer = xTimer;
1047 configASSERT( xTimer );
1049 /* Is the timer in the list of active timers? */
1050 taskENTER_CRITICAL();
1052 if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 )
1061 taskEXIT_CRITICAL();
1064 } /*lint !e818 Can't be pointer to const due to the typedef. */
1065 /*-----------------------------------------------------------*/
1067 void * pvTimerGetTimerID( const TimerHandle_t xTimer )
1069 Timer_t * const pxTimer = xTimer;
1072 configASSERT( xTimer );
1074 taskENTER_CRITICAL();
1076 pvReturn = pxTimer->pvTimerID;
1078 taskEXIT_CRITICAL();
1082 /*-----------------------------------------------------------*/
1084 void vTimerSetTimerID( TimerHandle_t xTimer,
1087 Timer_t * const pxTimer = xTimer;
1089 configASSERT( xTimer );
1091 taskENTER_CRITICAL();
1093 pxTimer->pvTimerID = pvNewID;
1095 taskEXIT_CRITICAL();
1097 /*-----------------------------------------------------------*/
1099 #if ( INCLUDE_xTimerPendFunctionCall == 1 )
1101 BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend,
1102 void * pvParameter1,
1103 uint32_t ulParameter2,
1104 BaseType_t * pxHigherPriorityTaskWoken )
1106 DaemonTaskMessage_t xMessage;
1109 /* Complete the message with the function parameters and post it to the
1111 xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
1112 xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
1113 xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
1114 xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
1116 xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
1118 tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
1123 #endif /* INCLUDE_xTimerPendFunctionCall */
1124 /*-----------------------------------------------------------*/
1126 #if ( INCLUDE_xTimerPendFunctionCall == 1 )
1128 BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend,
1129 void * pvParameter1,
1130 uint32_t ulParameter2,
1131 TickType_t xTicksToWait )
1133 DaemonTaskMessage_t xMessage;
1136 /* This function can only be called after a timer has been created or
1137 * after the scheduler has been started because, until then, the timer
1138 * queue does not exist. */
1139 configASSERT( xTimerQueue );
1141 /* Complete the message with the function parameters and post it to the
1143 xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
1144 xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
1145 xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
1146 xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
1148 xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
1150 tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
1155 #endif /* INCLUDE_xTimerPendFunctionCall */
1156 /*-----------------------------------------------------------*/
1158 #if ( configUSE_TRACE_FACILITY == 1 )
1160 UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer )
1162 return ( ( Timer_t * ) xTimer )->uxTimerNumber;
1165 #endif /* configUSE_TRACE_FACILITY */
1166 /*-----------------------------------------------------------*/
1168 #if ( configUSE_TRACE_FACILITY == 1 )
1170 void vTimerSetTimerNumber( TimerHandle_t xTimer,
1171 UBaseType_t uxTimerNumber )
1173 ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber;
1176 #endif /* configUSE_TRACE_FACILITY */
1177 /*-----------------------------------------------------------*/
1179 /* This entire source file will be skipped if the application is not configured
1180 * to include software timer functionality. If you want to include software timer
1181 * functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
1182 #endif /* configUSE_TIMERS == 1 */