]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_M4_ATSAM4L_Atmel_Studio/src/SAM4L_low_power_tick_management.c
Update version number to V8.0.0 (without the release candidate number).
[freertos] / FreeRTOS / Demo / CORTEX_M4_ATSAM4L_Atmel_Studio / src / SAM4L_low_power_tick_management.c
1 /*\r
2     FreeRTOS V8.0.0 - Copyright (C) 2014 Real Time Engineers Ltd.\r
3     All rights reserved\r
4 \r
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     ***************************************************************************\r
8      *                                                                       *\r
9      *    FreeRTOS provides completely free yet professionally developed,    *\r
10      *    robust, strictly quality controlled, supported, and cross          *\r
11      *    platform software that has become a de facto standard.             *\r
12      *                                                                       *\r
13      *    Help yourself get started quickly and support the FreeRTOS         *\r
14      *    project by purchasing a FreeRTOS tutorial book, reference          *\r
15      *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
16      *                                                                       *\r
17      *    Thank you!                                                         *\r
18      *                                                                       *\r
19     ***************************************************************************\r
20 \r
21     This file is part of the FreeRTOS distribution.\r
22 \r
23     FreeRTOS is free software; you can redistribute it and/or modify it under\r
24     the terms of the GNU General Public License (version 2) as published by the\r
25     Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
26 \r
27     >>! NOTE: The modification to the GPL is included to allow you to distribute\r
28     >>! a combined work that includes FreeRTOS without being obliged to provide\r
29     >>! the source code for proprietary components outside of the FreeRTOS\r
30     >>! kernel.\r
31 \r
32     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
33     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
34     FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
35     link: http://www.freertos.org/a00114.html\r
36 \r
37     1 tab == 4 spaces!\r
38 \r
39     ***************************************************************************\r
40      *                                                                       *\r
41      *    Having a problem?  Start by reading the FAQ "My application does   *\r
42      *    not run, what could be wrong?"                                     *\r
43      *                                                                       *\r
44      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
45      *                                                                       *\r
46     ***************************************************************************\r
47 \r
48     http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
49     license and Real Time Engineers Ltd. contact details.\r
50 \r
51     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
52     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
53     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
54 \r
55     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
56     Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
57     licenses offer ticketed support, indemnification and middleware.\r
58 \r
59     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
60     engineered and independently SIL3 certified version for use in safety and\r
61     mission critical applications that require provable dependability.\r
62 \r
63     1 tab == 4 spaces!\r
64 */\r
65 \r
66 /* Standard includes. */\r
67 #include "limits.h"\r
68 \r
69 /* FreeRTOS includes. */\r
70 #include "FreeRTOS.h"\r
71 #include "task.h"\r
72 \r
73 /* Library includes. */\r
74 #include <asf.h>\r
75 \r
76 \r
77 /*\r
78  * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt\r
79  * is generated by the AST.  The AST configuration and handling functions are\r
80  * defined in this file.\r
81  *\r
82  * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is\r
83  * generated by the standard FreeRTOS Cortex-M port layer, which uses the\r
84  * SysTick timer.\r
85  */\r
86 #if configCREATE_LOW_POWER_DEMO == 1\r
87 \r
88 /* Constants required to pend a PendSV interrupt from the tick ISR if the\r
89 preemptive scheduler is being used.  These are just standard bits and registers\r
90 within the Cortex-M core itself. */\r
91 #define portNVIC_PENDSVSET_BIT  ( 1UL << 28UL )\r
92 \r
93 /* The alarm used to generate interrupts in the asynchronous timer. */\r
94 #define portAST_ALARM_CHANNEL   0\r
95 \r
96 /*-----------------------------------------------------------*/\r
97 \r
98 /*\r
99  * The tick interrupt is generated by the asynchronous timer.  The default tick\r
100  * interrupt handler cannot be used (even with the AST being handled from the\r
101  * tick hook function) because the default tick interrupt accesses the SysTick\r
102  * registers when configUSE_TICKLESS_IDLE set to 1.  AST_ALARM_Handler() is the\r
103  * default name for the AST alarm interrupt.  This definition overrides the\r
104  * default implementation that is weakly defined in the interrupt vector table\r
105  * file.\r
106  */\r
107 void AST_ALARM_Handler(void);\r
108 \r
109 /*\r
110  * Functions that disable and enable the AST respectively, not returning until\r
111  * the operation is known to have taken effect.\r
112  */\r
113 static void prvDisableAST( void );\r
114 static void prvEnableAST( void );\r
115 \r
116 /*-----------------------------------------------------------*/\r
117 \r
118 /* Calculate how many clock increments make up a single tick period. */\r
119 static const uint32_t ulAlarmValueForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );\r
120 \r
121 /* Holds the maximum number of ticks that can be suppressed - which is\r
122 basically how far into the future an interrupt can be generated. Set\r
123 during initialisation. */\r
124 static TickType_t xMaximumPossibleSuppressedTicks = 0;\r
125 \r
126 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
127 sleep mode was exited because of an AST interrupt or a different interrupt. */\r
128 static volatile uint32_t ulTickFlag = pdFALSE;\r
129 \r
130 /* The AST counter is stopped temporarily each time it is re-programmed.  The\r
131 following variable offsets the AST counter alarm value by the number of AST\r
132 counts that would typically be missed while the counter was stopped to compensate\r
133 for the lost time.  _RB_ Value needs calculating correctly. */\r
134 static uint32_t ulStoppedTimerCompensation = 2 / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );\r
135 \r
136 /*-----------------------------------------------------------*/\r
137 \r
138 /* The tick interrupt handler.  This is always the same other than the part that\r
139 clears the interrupt, which is specific to the clock being used to generate the\r
140 tick. */\r
141 void AST_ALARM_Handler(void)\r
142 {\r
143         /* Protect incrementing the tick with an interrupt safe critical section. */\r
144         ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
145         {\r
146                 if( xTaskIncrementTick() != pdFALSE )\r
147                 {\r
148                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
149                 }\r
150 \r
151                 /* Just completely clear the interrupt mask on exit by passing 0 because\r
152                 it is known that this interrupt will only ever execute with the lowest\r
153                 possible interrupt priority. */\r
154         }\r
155         portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
156 \r
157         /* The CPU woke because of a tick. */\r
158         ulTickFlag = pdTRUE;\r
159 \r
160         /* If this is the first tick since exiting tickless mode then the AST needs\r
161         to be reconfigured to generate interrupts at the defined tick frequency. */\r
162         ast_write_alarm0_value( AST, ulAlarmValueForOneTick );\r
163 \r
164         /* Ensure the interrupt is clear before exiting. */\r
165         ast_clear_interrupt_flag( AST, AST_INTERRUPT_ALARM );\r
166 }\r
167 /*-----------------------------------------------------------*/\r
168 \r
169 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly\r
170 defined in the FreeRTOS Cortex-M3 port layer with a version that configures the\r
171 asynchronous timer (AST) to generate the tick interrupt. */\r
172 void vPortSetupTimerInterrupt( void )\r
173 {\r
174 struct ast_config ast_conf;\r
175 \r
176         /* Ensure the AST can bring the CPU out of sleep mode. */\r
177         sleepmgr_lock_mode( SLEEPMGR_RET );\r
178 \r
179         /* Ensure the 32KHz oscillator is enabled. */\r
180         if( osc_is_ready( OSC_ID_OSC32 ) == pdFALSE )\r
181         {\r
182                 osc_enable( OSC_ID_OSC32 );\r
183                 osc_wait_ready( OSC_ID_OSC32 );\r
184         }\r
185 \r
186         /* Enable the AST itself. */\r
187         ast_enable( AST );\r
188 \r
189         ast_conf.mode = AST_COUNTER_MODE;  /* Simple up counter. */\r
190         ast_conf.osc_type = AST_OSC_32KHZ;\r
191         ast_conf.psel = 0; /* No prescale so the actual frequency is 32KHz/2. */\r
192         ast_conf.counter = 0;\r
193         ast_set_config( AST, &ast_conf );\r
194 \r
195         /* The AST alarm interrupt is used as the tick interrupt.  Ensure the alarm\r
196         status starts clear. */\r
197         ast_clear_interrupt_flag( AST, AST_INTERRUPT_ALARM );\r
198 \r
199         /* Enable wakeup from alarm 0 in the AST and power manager.  */\r
200         ast_enable_wakeup( AST, AST_WAKEUP_ALARM );\r
201         bpm_enable_wakeup_source( BPM, ( 1 << BPM_BKUPWEN_AST ) );\r
202 \r
203         /* Tick interrupt MUST execute at the lowest interrupt priority. */\r
204         NVIC_SetPriority( AST_ALARM_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY);\r
205         ast_enable_interrupt( AST, AST_INTERRUPT_ALARM );\r
206         NVIC_ClearPendingIRQ( AST_ALARM_IRQn );\r
207         NVIC_EnableIRQ( AST_ALARM_IRQn );\r
208 \r
209         /* Automatically clear the counter on interrupt. */\r
210         ast_enable_counter_clear_on_alarm( AST, portAST_ALARM_CHANNEL );\r
211 \r
212         /* Start with the tick active and generating a tick with regular period. */\r
213         ast_write_alarm0_value( AST, ulAlarmValueForOneTick );\r
214         ast_write_counter_value( AST, 0 );\r
215 \r
216         /* See the comments where xMaximumPossibleSuppressedTicks is declared. */\r
217         xMaximumPossibleSuppressedTicks = ULONG_MAX / ulAlarmValueForOneTick;\r
218 }\r
219 /*-----------------------------------------------------------*/\r
220 \r
221 static void prvDisableAST( void )\r
222 {\r
223         while( ast_is_busy( AST ) )\r
224         {\r
225                 /* Nothing to do here, just waiting. */\r
226         }\r
227         AST->AST_CR &= ~( AST_CR_EN );\r
228         while( ast_is_busy( AST ) )\r
229         {\r
230                 /* Nothing to do here, just waiting. */\r
231         }\r
232 }\r
233 /*-----------------------------------------------------------*/\r
234 \r
235 static void prvEnableAST( void )\r
236 {\r
237         while( ast_is_busy( AST ) )\r
238         {\r
239                 /* Nothing to do here, just waiting. */\r
240         }\r
241         AST->AST_CR |= AST_CR_EN;\r
242         while( ast_is_busy( AST ) )\r
243         {\r
244                 /* Nothing to do here, just waiting. */\r
245         }\r
246 }\r
247 /*-----------------------------------------------------------*/\r
248 \r
249 /* Override the default definition of vPortSuppressTicksAndSleep() that is weakly\r
250 defined in the FreeRTOS Cortex-M3 port layer with a version that manages the\r
251 asynchronous timer (AST), as the tick is generated from the low power AST and\r
252 not the SysTick as would normally be the case on a Cortex-M. */\r
253 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
254 {\r
255 uint32_t ulAlarmValue, ulCompleteTickPeriods, ulInterruptStatus;\r
256 eSleepModeStatus eSleepAction;\r
257 TickType_t xModifiableIdleTime;\r
258 enum sleepmgr_mode xSleepMode;\r
259 \r
260         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
261 \r
262         /* Make sure the AST reload value does not overflow the counter. */\r
263         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
264         {\r
265                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
266         }\r
267 \r
268         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
269         periods. */\r
270         ulAlarmValue = ulAlarmValueForOneTick * xExpectedIdleTime;\r
271         if( ulAlarmValue > ulStoppedTimerCompensation )\r
272         {\r
273                 /* Compensate for the fact that the AST is going to be stopped\r
274                 momentarily. */\r
275                 ulAlarmValue -= ulStoppedTimerCompensation;\r
276         }\r
277 \r
278         /* Stop the AST momentarily.  The time the AST is stopped for is accounted\r
279         for as best it can be, but using the tickless mode will inevitably result in\r
280         some tiny drift of the time maintained by the kernel with respect to\r
281         calendar time. */\r
282         prvDisableAST();\r
283 \r
284         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
285         that will mask interrupts that should exit sleep mode. */\r
286         ulInterruptStatus = cpu_irq_save();\r
287 \r
288         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
289         mode is exited then sleep mode was probably exited because the tick was\r
290         suppressed for the entire xExpectedIdleTime period. */\r
291         ulTickFlag = pdFALSE;\r
292 \r
293         /* If a context switch is pending then abandon the low power entry as\r
294         the context switch might have been pended by an external interrupt that\r
295         requires processing. */\r
296         eSleepAction = eTaskConfirmSleepModeStatus();\r
297         if( eSleepAction == eAbortSleep )\r
298         {\r
299                 /* Restart tick. */\r
300                 prvEnableAST();\r
301 \r
302                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
303                 above. */\r
304                 cpu_irq_restore( ulInterruptStatus );\r
305         }\r
306         else\r
307         {\r
308                 /* Adjust the alarm value to take into account that the current time\r
309                 slice is already partially complete. */\r
310                 ulAlarmValue -= ast_read_counter_value( AST );\r
311                 ast_write_alarm0_value( AST, ulAlarmValue );\r
312 \r
313                 /* Restart the AST. */\r
314                 prvEnableAST();\r
315 \r
316                 /* Allow the application to define some pre-sleep processing. */\r
317                 xModifiableIdleTime = xExpectedIdleTime;\r
318                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
319 \r
320                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
321                 means the application defined code has already executed the WAIT\r
322                 instruction. */\r
323                 if( xModifiableIdleTime > 0 )\r
324                 {\r
325                         /* Find the deepest allowable sleep mode. */\r
326                         xSleepMode = sleepmgr_get_sleep_mode();\r
327 \r
328                         if( xSleepMode != SLEEPMGR_ACTIVE )\r
329                         {\r
330                                 /* Sleep until something happens. */\r
331                                 bpm_sleep( BPM, xSleepMode );\r
332                         }\r
333                 }\r
334 \r
335                 /* Allow the application to define some post sleep processing. */\r
336                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
337 \r
338                 /* Stop AST.  Again, the time the SysTick is stopped for is     accounted\r
339                 for as best it can be, but using the tickless mode will inevitably\r
340                 result in some tiny drift of the time maintained by the kernel with\r
341                 respect to calendar time. */\r
342                 prvDisableAST();\r
343 \r
344                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
345                 above. */\r
346                 cpu_irq_restore( ulInterruptStatus );\r
347 \r
348                 if( ulTickFlag != pdFALSE )\r
349                 {\r
350                         /* The tick interrupt has already executed, although because this\r
351                         function is called with the scheduler suspended the actual tick\r
352                         processing will not occur until after this function has exited.\r
353                         Reset the alarm value with whatever remains of this tick period. */\r
354                         ulAlarmValue = ulAlarmValueForOneTick - ast_read_counter_value( AST );\r
355                         ast_write_alarm0_value( AST, ulAlarmValue );\r
356 \r
357                         /* The tick interrupt handler will already have pended the tick\r
358                         processing in the kernel.  As the pending tick will be processed as\r
359                         soon as this function exits, the tick value     maintained by the tick\r
360                         is stepped forward by one less than the time spent sleeping.  The\r
361                         actual stepping of the tick appears later in this function. */\r
362                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
363                 }\r
364                 else\r
365                 {\r
366                         /* Something other than the tick interrupt ended the sleep.  How\r
367                         many complete tick periods passed while the processor was\r
368                         sleeping? */\r
369                         ulCompleteTickPeriods = ast_read_counter_value( AST ) / ulAlarmValueForOneTick;\r
370 \r
371                         /* The alarm value is set to whatever fraction of a single tick\r
372                         period remains. */\r
373                         ulAlarmValue = ast_read_counter_value( AST ) - ( ulCompleteTickPeriods * ulAlarmValueForOneTick );\r
374                         if( ulAlarmValue == 0 )\r
375                         {\r
376                                 /* There is no fraction remaining. */\r
377                                 ulAlarmValue = ulAlarmValueForOneTick;\r
378                                 ulCompleteTickPeriods++;\r
379                         }\r
380                         ast_write_alarm0_value( AST, ulAlarmValue );\r
381                 }\r
382 \r
383                 /* Restart the AST so it runs up to the alarm value.  The alarm value\r
384                 will get set to the value required to generate exactly one tick period\r
385                 the next time the AST interrupt executes. */\r
386                 prvEnableAST();\r
387 \r
388                 /* Wind the tick forward by the number of tick periods that the CPU\r
389                 remained in a low power state. */\r
390                 vTaskStepTick( ulCompleteTickPeriods );\r
391         }\r
392 }\r
393 \r
394 \r
395 #endif /* configCREATE_LOW_POWER_DEMO == 1 */\r
396 \r