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