]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_M4_ATSAM4L_Atmel_Studio/src/SAM4L_low_power_tick_management.c
a0ea49a5c94c920c44d8c597e82dcff81eff0ae0
[freertos] / FreeRTOS / Demo / CORTEX_M4_ATSAM4L_Atmel_Studio / src / SAM4L_low_power_tick_management.c
1 /*\r
2  * FreeRTOS Kernel V10.0.0\r
3  * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\r
4  *\r
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
6  * this software and associated documentation files (the "Software"), to deal in\r
7  * the Software without restriction, including without limitation the rights to\r
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
9  * the Software, and to permit persons to whom the Software is furnished to do so,\r
10  * subject to the following conditions:\r
11  *\r
12  * The above copyright notice and this permission notice shall be included in all\r
13  * copies or substantial portions of the Software. If you wish to use our Amazon\r
14  * FreeRTOS name, please do so in a fair use way that does not cause confusion.\r
15  *\r
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
18  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
19  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
20  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
22  *\r
23  * http://www.FreeRTOS.org\r
24  * http://aws.amazon.com/freertos\r
25  *\r
26  * 1 tab == 4 spaces!\r
27  */\r
28 \r
29 /* Standard includes. */\r
30 #include "limits.h"\r
31 \r
32 /* FreeRTOS includes. */\r
33 #include "FreeRTOS.h"\r
34 #include "task.h"\r
35 \r
36 /* Library includes. */\r
37 #include <asf.h>\r
38 \r
39 \r
40 /*\r
41  * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt\r
42  * is generated by the AST.  The AST configuration and handling functions are\r
43  * defined in this file.\r
44  *\r
45  * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is\r
46  * generated by the standard FreeRTOS Cortex-M port layer, which uses the\r
47  * SysTick timer.\r
48  */\r
49 #if configCREATE_LOW_POWER_DEMO == 1\r
50 \r
51 /* Constants required to pend a PendSV interrupt from the tick ISR if the\r
52 preemptive scheduler is being used.  These are just standard bits and registers\r
53 within the Cortex-M core itself. */\r
54 #define portNVIC_PENDSVSET_BIT  ( 1UL << 28UL )\r
55 \r
56 /* The alarm used to generate interrupts in the asynchronous timer. */\r
57 #define portAST_ALARM_CHANNEL   0\r
58 \r
59 /*-----------------------------------------------------------*/\r
60 \r
61 /*\r
62  * The tick interrupt is generated by the asynchronous timer.  The default tick\r
63  * interrupt handler cannot be used (even with the AST being handled from the\r
64  * tick hook function) because the default tick interrupt accesses the SysTick\r
65  * registers when configUSE_TICKLESS_IDLE set to 1.  AST_ALARM_Handler() is the\r
66  * default name for the AST alarm interrupt.  This definition overrides the\r
67  * default implementation that is weakly defined in the interrupt vector table\r
68  * file.\r
69  */\r
70 void AST_ALARM_Handler(void);\r
71 \r
72 /*\r
73  * Functions that disable and enable the AST respectively, not returning until\r
74  * the operation is known to have taken effect.\r
75  */\r
76 static void prvDisableAST( void );\r
77 static void prvEnableAST( void );\r
78 \r
79 /*-----------------------------------------------------------*/\r
80 \r
81 /* Calculate how many clock increments make up a single tick period. */\r
82 static const uint32_t ulAlarmValueForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );\r
83 \r
84 /* Holds the maximum number of ticks that can be suppressed - which is\r
85 basically how far into the future an interrupt can be generated. Set\r
86 during initialisation. */\r
87 static TickType_t xMaximumPossibleSuppressedTicks = 0;\r
88 \r
89 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
90 sleep mode was exited because of an AST interrupt or a different interrupt. */\r
91 static volatile uint32_t ulTickFlag = pdFALSE;\r
92 \r
93 /* The AST counter is stopped temporarily each time it is re-programmed.  The\r
94 following variable offsets the AST counter alarm value by the number of AST\r
95 counts that would typically be missed while the counter was stopped to compensate\r
96 for the lost time.  _RB_ Value needs calculating correctly. */\r
97 static uint32_t ulStoppedTimerCompensation = 2 / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );\r
98 \r
99 /*-----------------------------------------------------------*/\r
100 \r
101 /* The tick interrupt handler.  This is always the same other than the part that\r
102 clears the interrupt, which is specific to the clock being used to generate the\r
103 tick. */\r
104 void AST_ALARM_Handler(void)\r
105 {\r
106         /* Protect incrementing the tick with an interrupt safe critical section. */\r
107         ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
108         {\r
109                 if( xTaskIncrementTick() != pdFALSE )\r
110                 {\r
111                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
112                 }\r
113 \r
114                 /* Just completely clear the interrupt mask on exit by passing 0 because\r
115                 it is known that this interrupt will only ever execute with the lowest\r
116                 possible interrupt priority. */\r
117         }\r
118         portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
119 \r
120         /* The CPU woke because of a tick. */\r
121         ulTickFlag = pdTRUE;\r
122 \r
123         /* If this is the first tick since exiting tickless mode then the AST needs\r
124         to be reconfigured to generate interrupts at the defined tick frequency. */\r
125         ast_write_alarm0_value( AST, ulAlarmValueForOneTick );\r
126 \r
127         /* Ensure the interrupt is clear before exiting. */\r
128         ast_clear_interrupt_flag( AST, AST_INTERRUPT_ALARM );\r
129 }\r
130 /*-----------------------------------------------------------*/\r
131 \r
132 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly\r
133 defined in the FreeRTOS Cortex-M3 port layer with a version that configures the\r
134 asynchronous timer (AST) to generate the tick interrupt. */\r
135 void vPortSetupTimerInterrupt( void )\r
136 {\r
137 struct ast_config ast_conf;\r
138 \r
139         /* Ensure the AST can bring the CPU out of sleep mode. */\r
140         sleepmgr_lock_mode( SLEEPMGR_RET );\r
141 \r
142         /* Ensure the 32KHz oscillator is enabled. */\r
143         if( osc_is_ready( OSC_ID_OSC32 ) == pdFALSE )\r
144         {\r
145                 osc_enable( OSC_ID_OSC32 );\r
146                 osc_wait_ready( OSC_ID_OSC32 );\r
147         }\r
148 \r
149         /* Enable the AST itself. */\r
150         ast_enable( AST );\r
151 \r
152         ast_conf.mode = AST_COUNTER_MODE;  /* Simple up counter. */\r
153         ast_conf.osc_type = AST_OSC_32KHZ;\r
154         ast_conf.psel = 0; /* No prescale so the actual frequency is 32KHz/2. */\r
155         ast_conf.counter = 0;\r
156         ast_set_config( AST, &ast_conf );\r
157 \r
158         /* The AST alarm interrupt is used as the tick interrupt.  Ensure the alarm\r
159         status starts clear. */\r
160         ast_clear_interrupt_flag( AST, AST_INTERRUPT_ALARM );\r
161 \r
162         /* Enable wakeup from alarm 0 in the AST and power manager.  */\r
163         ast_enable_wakeup( AST, AST_WAKEUP_ALARM );\r
164         bpm_enable_wakeup_source( BPM, ( 1 << BPM_BKUPWEN_AST ) );\r
165 \r
166         /* Tick interrupt MUST execute at the lowest interrupt priority. */\r
167         NVIC_SetPriority( AST_ALARM_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY);\r
168         ast_enable_interrupt( AST, AST_INTERRUPT_ALARM );\r
169         NVIC_ClearPendingIRQ( AST_ALARM_IRQn );\r
170         NVIC_EnableIRQ( AST_ALARM_IRQn );\r
171 \r
172         /* Automatically clear the counter on interrupt. */\r
173         ast_enable_counter_clear_on_alarm( AST, portAST_ALARM_CHANNEL );\r
174 \r
175         /* Start with the tick active and generating a tick with regular period. */\r
176         ast_write_alarm0_value( AST, ulAlarmValueForOneTick );\r
177         ast_write_counter_value( AST, 0 );\r
178 \r
179         /* See the comments where xMaximumPossibleSuppressedTicks is declared. */\r
180         xMaximumPossibleSuppressedTicks = ULONG_MAX / ulAlarmValueForOneTick;\r
181 }\r
182 /*-----------------------------------------------------------*/\r
183 \r
184 static void prvDisableAST( void )\r
185 {\r
186         while( ast_is_busy( AST ) )\r
187         {\r
188                 /* Nothing to do here, just waiting. */\r
189         }\r
190         AST->AST_CR &= ~( AST_CR_EN );\r
191         while( ast_is_busy( AST ) )\r
192         {\r
193                 /* Nothing to do here, just waiting. */\r
194         }\r
195 }\r
196 /*-----------------------------------------------------------*/\r
197 \r
198 static void prvEnableAST( void )\r
199 {\r
200         while( ast_is_busy( AST ) )\r
201         {\r
202                 /* Nothing to do here, just waiting. */\r
203         }\r
204         AST->AST_CR |= AST_CR_EN;\r
205         while( ast_is_busy( AST ) )\r
206         {\r
207                 /* Nothing to do here, just waiting. */\r
208         }\r
209 }\r
210 /*-----------------------------------------------------------*/\r
211 \r
212 /* Override the default definition of vPortSuppressTicksAndSleep() that is weakly\r
213 defined in the FreeRTOS Cortex-M3 port layer with a version that manages the\r
214 asynchronous timer (AST), as the tick is generated from the low power AST and\r
215 not the SysTick as would normally be the case on a Cortex-M. */\r
216 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
217 {\r
218 uint32_t ulAlarmValue, ulCompleteTickPeriods, ulInterruptStatus;\r
219 eSleepModeStatus eSleepAction;\r
220 TickType_t xModifiableIdleTime;\r
221 enum sleepmgr_mode xSleepMode;\r
222 \r
223         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
224 \r
225         /* Make sure the AST reload value does not overflow the counter. */\r
226         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
227         {\r
228                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
229         }\r
230 \r
231         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
232         periods. */\r
233         ulAlarmValue = ulAlarmValueForOneTick * xExpectedIdleTime;\r
234         if( ulAlarmValue > ulStoppedTimerCompensation )\r
235         {\r
236                 /* Compensate for the fact that the AST is going to be stopped\r
237                 momentarily. */\r
238                 ulAlarmValue -= ulStoppedTimerCompensation;\r
239         }\r
240 \r
241         /* Stop the AST momentarily.  The time the AST is stopped for is accounted\r
242         for as best it can be, but using the tickless mode will inevitably result in\r
243         some tiny drift of the time maintained by the kernel with respect to\r
244         calendar time. */\r
245         prvDisableAST();\r
246 \r
247         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
248         that will mask interrupts that should exit sleep mode. */\r
249         ulInterruptStatus = cpu_irq_save();\r
250 \r
251         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
252         mode is exited then sleep mode was probably exited because the tick was\r
253         suppressed for the entire xExpectedIdleTime period. */\r
254         ulTickFlag = pdFALSE;\r
255 \r
256         /* If a context switch is pending then abandon the low power entry as\r
257         the context switch might have been pended by an external interrupt that\r
258         requires processing. */\r
259         eSleepAction = eTaskConfirmSleepModeStatus();\r
260         if( eSleepAction == eAbortSleep )\r
261         {\r
262                 /* Restart tick. */\r
263                 prvEnableAST();\r
264 \r
265                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
266                 above. */\r
267                 cpu_irq_restore( ulInterruptStatus );\r
268         }\r
269         else\r
270         {\r
271                 /* Adjust the alarm value to take into account that the current time\r
272                 slice is already partially complete. */\r
273                 ulAlarmValue -= ast_read_counter_value( AST );\r
274                 ast_write_alarm0_value( AST, ulAlarmValue );\r
275 \r
276                 /* Restart the AST. */\r
277                 prvEnableAST();\r
278 \r
279                 /* Allow the application to define some pre-sleep processing. */\r
280                 xModifiableIdleTime = xExpectedIdleTime;\r
281                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
282 \r
283                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
284                 means the application defined code has already executed the WAIT\r
285                 instruction. */\r
286                 if( xModifiableIdleTime > 0 )\r
287                 {\r
288                         /* Find the deepest allowable sleep mode. */\r
289                         xSleepMode = sleepmgr_get_sleep_mode();\r
290 \r
291                         if( xSleepMode != SLEEPMGR_ACTIVE )\r
292                         {\r
293                                 /* Sleep until something happens. */\r
294                                 bpm_sleep( BPM, xSleepMode );\r
295                         }\r
296                 }\r
297 \r
298                 /* Allow the application to define some post sleep processing. */\r
299                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
300 \r
301                 /* Stop AST.  Again, the time the SysTick is stopped for is     accounted\r
302                 for as best it can be, but using the tickless mode will inevitably\r
303                 result in some tiny drift of the time maintained by the kernel with\r
304                 respect to calendar time. */\r
305                 prvDisableAST();\r
306 \r
307                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
308                 above. */\r
309                 cpu_irq_restore( ulInterruptStatus );\r
310 \r
311                 if( ulTickFlag != pdFALSE )\r
312                 {\r
313                         /* The tick interrupt has already executed, although because this\r
314                         function is called with the scheduler suspended the actual tick\r
315                         processing will not occur until after this function has exited.\r
316                         Reset the alarm value with whatever remains of this tick period. */\r
317                         ulAlarmValue = ulAlarmValueForOneTick - ast_read_counter_value( AST );\r
318                         ast_write_alarm0_value( AST, ulAlarmValue );\r
319 \r
320                         /* The tick interrupt handler will already have pended the tick\r
321                         processing in the kernel.  As the pending tick will be processed as\r
322                         soon as this function exits, the tick value     maintained by the tick\r
323                         is stepped forward by one less than the time spent sleeping.  The\r
324                         actual stepping of the tick appears later in this function. */\r
325                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
326                 }\r
327                 else\r
328                 {\r
329                         /* Something other than the tick interrupt ended the sleep.  How\r
330                         many complete tick periods passed while the processor was\r
331                         sleeping? */\r
332                         ulCompleteTickPeriods = ast_read_counter_value( AST ) / ulAlarmValueForOneTick;\r
333 \r
334                         /* The alarm value is set to whatever fraction of a single tick\r
335                         period remains. */\r
336                         ulAlarmValue = ast_read_counter_value( AST ) - ( ulCompleteTickPeriods * ulAlarmValueForOneTick );\r
337                         if( ulAlarmValue == 0 )\r
338                         {\r
339                                 /* There is no fraction remaining. */\r
340                                 ulAlarmValue = ulAlarmValueForOneTick;\r
341                                 ulCompleteTickPeriods++;\r
342                         }\r
343                         ast_write_counter_value( AST, 0 );\r
344                         ast_write_alarm0_value( AST, ulAlarmValue );\r
345                 }\r
346 \r
347                 /* Restart the AST so it runs up to the alarm value.  The alarm value\r
348                 will get set to the value required to generate exactly one tick period\r
349                 the next time the AST interrupt executes. */\r
350                 prvEnableAST();\r
351 \r
352                 /* Wind the tick forward by the number of tick periods that the CPU\r
353                 remained in a low power state. */\r
354                 vTaskStepTick( ulCompleteTickPeriods );\r
355         }\r
356 }\r
357 \r
358 \r
359 #endif /* configCREATE_LOW_POWER_DEMO == 1 */\r
360 \r