]> git.sur5r.net Git - freertos/blob - Source/timers.c
Continue adding some tick interrupt overflow protection to the timers module. This...
[freertos] / Source / timers.c
1 /*\r
2     FreeRTOS V6.1.1 - Copyright (C) 2011 Real Time Engineers Ltd.\r
3 \r
4     ***************************************************************************\r
5     *                                                                         *\r
6     * If you are:                                                             *\r
7     *                                                                         *\r
8     *    + New to FreeRTOS,                                                   *\r
9     *    + Wanting to learn FreeRTOS or multitasking in general quickly       *\r
10     *    + Looking for basic training,                                        *\r
11     *    + Wanting to improve your FreeRTOS skills and productivity           *\r
12     *                                                                         *\r
13     * then take a look at the FreeRTOS books - available as PDF or paperback  *\r
14     *                                                                         *\r
15     *        "Using the FreeRTOS Real Time Kernel - a Practical Guide"        *\r
16     *                  http://www.FreeRTOS.org/Documentation                  *\r
17     *                                                                         *\r
18     * A pdf reference manual is also available.  Both are usually delivered   *\r
19     * to your inbox within 20 minutes to two hours when purchased between 8am *\r
20     * and 8pm GMT (although please allow up to 24 hours in case of            *\r
21     * exceptional circumstances).  Thank you for your support!                *\r
22     *                                                                         *\r
23     ***************************************************************************\r
24 \r
25     This file is part of the FreeRTOS distribution.\r
26 \r
27     FreeRTOS is free software; you can redistribute it and/or modify it under\r
28     the terms of the GNU General Public License (version 2) as published by the\r
29     Free Software Foundation AND MODIFIED BY the FreeRTOS exception.\r
30     ***NOTE*** The exception to the GPL is included to allow you to distribute\r
31     a combined work that includes FreeRTOS without being obliged to provide the\r
32     source code for proprietary components outside of the FreeRTOS kernel.\r
33     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT\r
34     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\r
35     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for\r
36     more details. You should have received a copy of the GNU General Public\r
37     License and the FreeRTOS license exception along with FreeRTOS; if not it\r
38     can be viewed here: http://www.freertos.org/a00114.html and also obtained\r
39     by writing to Richard Barry, contact details for whom are available on the\r
40     FreeRTOS WEB site.\r
41 \r
42     1 tab == 4 spaces!\r
43 \r
44     http://www.FreeRTOS.org - Documentation, latest information, license and\r
45     contact details.\r
46 \r
47     http://www.SafeRTOS.com - A version that is certified for use in safety\r
48     critical systems.\r
49 \r
50     http://www.OpenRTOS.com - Commercial support, development, porting,\r
51     licensing and training services.\r
52 */\r
53 \r
54 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining\r
55 all the API functions to use the MPU wrappers.  That should only be done when\r
56 task.h is included from an application file. */\r
57 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
58 \r
59 #include "FreeRTOS.h"\r
60 #include "task.h"\r
61 #include "queue.h"\r
62 #include "timers.h"\r
63 \r
64 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
65 \r
66 /* Misc definitions. */\r
67 #define tmrNO_DELAY             ( portTickType ) 0U\r
68 \r
69 /* The definition of the timers themselves. */\r
70 typedef struct tmrTimerControl\r
71 {\r
72         const signed char               *pcTimerName;           /*<< Text name.  This is not used by the kernel, it is included simply to make debugging easier. */\r
73         xListItem                               xTimerListItem;         /*<< Standard linked list item as used by all kernel features for event management. */\r
74         portTickType                    xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */\r
75         unsigned portBASE_TYPE  uxAutoReload;           /*<< Set to pdTRUE if the timer should be automatically restarted once expired.  Set to pdFALSE if the timer is, in effect, a one shot timer. */\r
76         void                                    *pvTimerID;                     /*<< An ID to identify the timer.  This allows the timer to be identified when the same callback is used for multiple timers. */\r
77         tmrTIMER_CALLBACK               pxCallbackFunction;     /*<< The function that will be called when the timer expires. */\r
78 } xTIMER;\r
79 \r
80 /* The definition of messages that can be sent and received on the timer\r
81 queue. */\r
82 typedef struct tmrTimerQueueMessage\r
83 {\r
84         portBASE_TYPE                   xMessageID;                     /*<< The command being sent to the timer service task. */\r
85         portTickType                    xMessageValue;          /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */\r
86         xTIMER *                                pxTimer;                        /*<< The timer to which the command will be applied. */\r
87 } xTIMER_MESSAGE;\r
88 \r
89 \r
90 /* The list in which active timers are stored.  Timers are referenced in expire\r
91 time order, with the nearest expiry time at the front of the list.  Only the\r
92 timer service task is allowed to access xActiveTimerList. */\r
93 PRIVILEGED_DATA static xList xActiveTimerList1;\r
94 PRIVILEGED_DATA static xList xActiveTimerList2;\r
95 PRIVILEGED_DATA static xList *pxCurrentTimerList;\r
96 PRIVILEGED_DATA static xList *pxOverflowTimerList;\r
97 \r
98 /* A queue that is used to send commands to the timer service task. */\r
99 PRIVILEGED_DATA static xQueueHandle xTimerQueue = NULL;\r
100 \r
101 /*-----------------------------------------------------------*/\r
102 \r
103 /*\r
104  * Initialise the infrastructure used by the timer service task if it has not\r
105  * been initialised already.\r
106  */\r
107 static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;\r
108 \r
109 /*\r
110  * The timer service task (daemon).  Timer functionality is controlled by this\r
111  * task.  Other tasks communicate with the timer service task using the\r
112  * xTimerQueue queue.\r
113  */\r
114 static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION;\r
115 \r
116 /*\r
117  * Called by the timer service task to interpret and process a command it\r
118  * received on the timer queue.\r
119  */\r
120 static void     prvProcessReceivedCommands( portTickType xAssumedTimeNow ) PRIVILEGED_FUNCTION;\r
121 \r
122 /*\r
123  * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, \r
124  * depending on if the expire time causes a timer counter overflow. \r
125  */\r
126 static void prvInsertTimerInActiveList( xTIMER *pxTimer, portTickType xNextExpiryTime, portTickType xAssumedTimeNow ) PRIVILEGED_FUNCTION;\r
127 \r
128 /*\r
129  * An active timer has reached its expire time.  Reload the timer if it is an\r
130  * auto reload timer, then call its callback.\r
131  */\r
132 static void prvProcessExpiredTimer( portTickType xNextExpireTime, portTickType xAssumedTimeNow ) PRIVILEGED_FUNCTION;\r
133 \r
134 /*\r
135  * The tick count has overflowed.  Switch the timer lists after ensuring the\r
136  * current timer list does not still reference some timers.\r
137  */\r
138 static void prvSwitchTimerLists( portTickType xAssumedTimeNow ) PRIVILEGED_FUNCTION;\r
139 \r
140 /*-----------------------------------------------------------*/\r
141 \r
142 portBASE_TYPE xTimerCreateTimerTask( void )\r
143 {\r
144 portBASE_TYPE xReturn = pdFAIL;\r
145 \r
146         /* This function is called when the scheduler is started if\r
147         configUSE_TIMERS is set to 1.  Check that the infrastructure used by the\r
148         timer service task has been created/initialised.  If timers have already\r
149         been created then the initialisation will already have been performed. */\r
150         prvCheckForValidListAndQueue();\r
151 \r
152         if( xTimerQueue != NULL )\r
153         {\r
154                 xReturn = xTaskCreate( prvTimerTask, ( const signed char * ) "Timer Service", configTIMER_TASK_STACK_DEPTH, NULL, configTIMER_TASK_PRIORITY, NULL );\r
155         }\r
156 \r
157         return xReturn;\r
158 }\r
159 /*-----------------------------------------------------------*/\r
160 \r
161 xTimerHandle xTimerCreate( const signed char *pcTimerName, portTickType xTimerPeriodInTicks, unsigned portBASE_TYPE uxAutoReload, void *pvTimerID, tmrTIMER_CALLBACK pxCallbackFunction )\r
162 {\r
163 xTIMER *pxNewTimer;\r
164 \r
165         /* Allocate the timer structure. */\r
166         pxNewTimer = ( xTIMER * ) pvPortMalloc( sizeof( xTIMER ) );\r
167         if( pxNewTimer != NULL )\r
168         {\r
169                 /* Ensure the infrastructure used by the timer service task has been\r
170                 created/initialised. */\r
171                 prvCheckForValidListAndQueue();\r
172 \r
173                 /* Initialise the timer structure members using the function parameters. */\r
174                 pxNewTimer->pcTimerName = pcTimerName;\r
175                 pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;\r
176                 pxNewTimer->uxAutoReload = uxAutoReload;\r
177                 pxNewTimer->pvTimerID = pvTimerID;\r
178                 pxNewTimer->pxCallbackFunction = pxCallbackFunction;\r
179                 vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );\r
180         }\r
181 \r
182         return ( xTimerHandle ) pxNewTimer;\r
183 }\r
184 /*-----------------------------------------------------------*/\r
185 \r
186 portBASE_TYPE xTimerGenericCommand( xTimerHandle xTimer, portBASE_TYPE xCommandID, portTickType xOptionalValue, portTickType xBlockTime )\r
187 {\r
188 portBASE_TYPE xReturn = pdFAIL;\r
189 xTIMER_MESSAGE xMessage;\r
190 \r
191         /* Send a message to the timer service task to perform a particular action\r
192         on a particular timer definition. */\r
193         if( xTimerQueue != NULL )\r
194         {\r
195                 /* Send a command to the timer service task to start the xTimer timer. */\r
196                 xMessage.xMessageID = xCommandID;\r
197                 xMessage.xMessageValue = xOptionalValue;\r
198                 xMessage.pxTimer = ( xTIMER * ) xTimer;\r
199 \r
200                 if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )\r
201                 {\r
202                         xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xBlockTime );\r
203                 }\r
204                 else\r
205                 {\r
206                         xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );\r
207                 }\r
208         }\r
209 \r
210         return xReturn;\r
211 }\r
212 /*-----------------------------------------------------------*/\r
213 \r
214 static void prvProcessExpiredTimer( portTickType xNextExpireTime, portTickType xAssumedTimeNow )\r
215 {\r
216 xTIMER *pxTimer;\r
217 \r
218         if( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )\r
219         {\r
220                 /* Remove the timer from the list of active timers. */\r
221                 pxTimer = ( xTIMER * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );\r
222                 vListRemove( &( pxTimer->xTimerListItem ) );\r
223 \r
224                 /* If the timer is an auto reload timer then calculate the next\r
225                 expiry time and re-insert the timer in the list of active timers. */\r
226                 if( pxTimer->uxAutoReload == pdTRUE )\r
227                 {\r
228                         /* This is the only time a timer is inserted into a list using\r
229                         a time relative to anything other than the current time.  It\r
230                         will therefore be inserted into the correct list relative to\r
231                         the time this task thinks it is now, even if a command to\r
232                         switch lists due to a tick count overflow is already waiting in\r
233                         the timer queue. */\r
234                         prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xAssumedTimeNow );\r
235                 }\r
236 \r
237                 /* Call the timer callback. */\r
238                 pxTimer->pxCallbackFunction( ( xTimerHandle ) pxTimer );\r
239         }\r
240 }\r
241 /*-----------------------------------------------------------*/\r
242 \r
243 static void prvTimerTask( void *pvParameters )\r
244 {\r
245 portTickType xNextExpireTime, xTimeNow, xFrozenTimeNow;\r
246 \r
247         /* Just to avoid compiler warnings. */\r
248         ( void ) pvParameters;\r
249 \r
250         for( ;; )\r
251         {\r
252                 /* Take a snapshot of the time to use while assessing expiry and auto\r
253                 reload times. */\r
254                 xFrozenTimeNow = xTaskGetTickCount();\r
255 \r
256                 /* Timers are listed in expiry time order, with the head of the list\r
257                 referencing the task that will expire first.  Obtain the time at which\r
258                 the timer with the nearest expiry time will expire.  If there are no\r
259                 active timers then just set the next expire time to the maximum possible\r
260                 time to ensure this task does not run unnecessarily.  */\r
261                 if( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )\r
262                 {\r
263                         xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );\r
264                 }\r
265                 else\r
266                 {\r
267                         xNextExpireTime = portMAX_DELAY;\r
268                 }\r
269 \r
270                 /* Has the timer expired?  This expiry time is relative to the snapshot\r
271                 of the time taken to be used in this loop iteration - so it doesn't \r
272                 matter at this point if a tick count overflows here. */\r
273                 if( xNextExpireTime <= xFrozenTimeNow )\r
274                 {\r
275                         prvProcessExpiredTimer( xNextExpireTime, xFrozenTimeNow );\r
276                 }\r
277                 else\r
278                 {\r
279                         /* Block this task until the next timer expires, or a command is\r
280                         received. */\r
281                         vTaskSuspendAll();\r
282                         {\r
283                                 /* Has the tick overflowed since a time snapshot was taken? */\r
284                                 xTimeNow = xTaskGetTickCount();\r
285                                 if( xTimeNow >= xFrozenTimeNow )\r
286                                 {\r
287                                         /* Has the expire not still not been met?  The tick count\r
288                                         may be greater now than when the time snapshot was taken. */\r
289                                         if( xNextExpireTime <= xTimeNow )\r
290                                         {\r
291                                                 prvProcessExpiredTimer( xNextExpireTime, xFrozenTimeNow );\r
292                                         }\r
293                                         else\r
294                                         {\r
295                                                 /* The tick count has not overflowed since the time \r
296                                                 snapshot, and the next expire time has not been reached\r
297                                                 since the last snapshot was taken.  This task should\r
298                                                 therefore block to wait for the next expire time. */\r
299                                                 vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ) );\r
300                                         }\r
301                                 }\r
302                                 else\r
303                                 {\r
304                                         /* The tick count has overflowed since the time snapshot\r
305                                         was taken, therefore, the task should not block but continue\r
306                                         with another loop.  The command queue should contain a\r
307                                         command to switch lists. */\r
308                                 }\r
309                         }\r
310                         if( xTaskResumeAll() == pdFALSE )\r
311                         {\r
312                                 /* Yield to wait for either a command to arrive, or the block time\r
313                                 to expire.  If a command arrived between the critical section being\r
314                                 exited and this yield then the yield will just return to the same\r
315                                 task. */\r
316                                 portYIELD_WITHIN_API();\r
317                         }\r
318 \r
319                         /* Take a snapshot of the time now for use in this iteration of the\r
320                         task loop. */\r
321                         xFrozenTimeNow = xTaskGetTickCount();\r
322 \r
323                         /* Empty the command queue, if it contains any commands. */\r
324                         prvProcessReceivedCommands( xFrozenTimeNow );\r
325                 }\r
326         }\r
327 }\r
328 /*-----------------------------------------------------------*/\r
329 \r
330 static void prvInsertTimerInActiveList( xTIMER *pxTimer, portTickType xNextExpiryTime, portTickType xAssumedTimeNow )\r
331 {\r
332         listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );\r
333         listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );\r
334         \r
335         if( xNextExpiryTime < xAssumedTimeNow )\r
336         {\r
337                 vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );\r
338         }\r
339         else\r
340         {\r
341                 vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );\r
342         }\r
343 }\r
344 /*-----------------------------------------------------------*/\r
345 \r
346 static void     prvProcessReceivedCommands( portTickType xAssumedTimeNow )\r
347 {\r
348 xTIMER_MESSAGE xMessage;\r
349 xTIMER *pxTimer;\r
350 portBASE_TYPE xSwitchListsOnExit = pdFALSE;\r
351 \r
352         while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL )\r
353         {\r
354                 pxTimer = xMessage.pxTimer;\r
355 \r
356                 /* Is the timer already in a list of active timers?  When the command\r
357                 is trmCOMMAND_PROCESS_TIMER_OVERFLOW, the timer will be NULL as the\r
358                 command is to the task rather than to an individual timer. */\r
359                 if( pxTimer != NULL )\r
360                 {\r
361                         if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE )\r
362                         {\r
363                                 /* The timer is in a list, remove it. */\r
364                                 vListRemove( &( pxTimer->xTimerListItem ) );\r
365                         }\r
366                 }\r
367 \r
368                 switch( xMessage.xMessageID )\r
369                 {\r
370                         case tmrCOMMAND_START : \r
371                                 /* Start or restart a timer. */\r
372                                 prvInsertTimerInActiveList( pxTimer,  xAssumedTimeNow + pxTimer->xTimerPeriodInTicks, xAssumedTimeNow );\r
373                                 break;\r
374 \r
375                         case tmrCOMMAND_STOP :  \r
376                                 /* The timer has already been removed from the active list.\r
377                                 There is nothing to do here. */\r
378                                 break;\r
379 \r
380                         case tmrCOMMAND_CHANGE_PERIOD :\r
381                                 pxTimer->xTimerPeriodInTicks = xMessage.xMessageValue;\r
382                                 prvInsertTimerInActiveList( pxTimer, ( xAssumedTimeNow + pxTimer->xTimerPeriodInTicks ), xAssumedTimeNow );\r
383                                 break;\r
384 \r
385                         case tmrCOMMAND_DELETE :\r
386                                 /* The timer has already been removed from the active list,\r
387                                 just free up the memory. */\r
388                                 vPortFree( pxTimer );\r
389                                 break;\r
390                                 \r
391                         case trmCOMMAND_PROCESS_TIMER_OVERFLOW :\r
392                                 /* Hold this pending until all the other messages have been \r
393                                 processed. */\r
394                                 xSwitchListsOnExit = pdTRUE;\r
395                                 break;\r
396 \r
397                         default :                       \r
398                                 /* Don't expect to get here. */\r
399                                 break;\r
400                 }\r
401         }\r
402 \r
403         if( xSwitchListsOnExit == pdTRUE )\r
404         {\r
405                 prvSwitchTimerLists( xAssumedTimeNow );\r
406         }\r
407 }\r
408 /*-----------------------------------------------------------*/\r
409 \r
410 static void prvSwitchTimerLists( portTickType xAssumedTimeNow )\r
411 {\r
412 portTickType xNextExpireTime;\r
413 xList *pxTemp;\r
414 \r
415         /* The tick count has overflowed.  The timer lists must be switched.  \r
416         If there are any timers still referenced from the current timer list \r
417         then they must have expired and should be processed before the lists \r
418         are switched. */\r
419         while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )\r
420         {\r
421                 xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );\r
422                 prvProcessExpiredTimer( xNextExpireTime, xAssumedTimeNow );\r
423         }\r
424 \r
425         pxTemp = pxCurrentTimerList;\r
426         pxCurrentTimerList = pxOverflowTimerList;\r
427         pxOverflowTimerList = pxTemp;\r
428 }\r
429 /*-----------------------------------------------------------*/\r
430 \r
431 static void prvCheckForValidListAndQueue( void )\r
432 {\r
433         /* Check that the list from which active timers are referenced, and the\r
434         queue used to communicate with the timer service, have been\r
435         initialised. */\r
436         taskENTER_CRITICAL();\r
437         {\r
438                 if( xTimerQueue == NULL )\r
439                 {\r
440                         vListInitialise( &xActiveTimerList1 );\r
441                         vListInitialise( &xActiveTimerList2 );\r
442                         pxCurrentTimerList = &xActiveTimerList1;\r
443                         pxOverflowTimerList = &xActiveTimerList2;\r
444                         xTimerQueue = xQueueCreate( configTIMER_QUEUE_LENGTH, sizeof( xTIMER_MESSAGE ) );\r
445                 }\r
446         }\r
447         taskEXIT_CRITICAL();\r
448 }\r
449 /*-----------------------------------------------------------*/\r
450 \r
451 portBASE_TYPE xTimerIsTimerActive( xTimerHandle xTimer )\r
452 {\r
453 portBASE_TYPE xTimerIsInActiveList;\r
454 xTIMER *pxTimer = ( xTIMER * ) xTimer;\r
455 \r
456         /* Is the timer in the list of active timers? */\r
457         taskENTER_CRITICAL();\r
458         {\r
459                 /* Checking to see if it is in the NULL list in effect checks to see if\r
460                 it is referenced from either the current or the overflow timer lists in\r
461                 one go, but the logic has to be reversed, hence the '!'. */\r
462                 xTimerIsInActiveList = !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) );\r
463         }\r
464         taskEXIT_CRITICAL();\r
465 \r
466         return xTimerIsInActiveList;\r
467 }\r
468 /*-----------------------------------------------------------*/\r
469 \r
470 void *pvTimerGetTimerID( xTimerHandle xTimer )\r
471 {\r
472 xTIMER *pxTimer = ( xTIMER * ) xTimer;\r
473 \r
474         return pxTimer->pvTimerID;\r
475 }\r
476 /*-----------------------------------------------------------*/\r
477 \r
478 \r
479 \r
480 \r