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