]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_EFM32_Giant_Gecko_Simplicity_Studio/Low_Power_Demo/low_power_tick_management_RTC.c
Roll up the minor changes checked into svn since V10.0.0 into new V10.0.1 ready for...
[freertos] / FreeRTOS / Demo / CORTEX_EFM32_Giant_Gecko_Simplicity_Studio / Low_Power_Demo / low_power_tick_management_RTC.c
1 /*\r
2  * FreeRTOS Kernel V10.0.1\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.\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 /* FreeRTOS includes. */\r
29 #include "FreeRTOS.h"\r
30 #include "task.h"\r
31 \r
32 /* SiLabs library includes. */\r
33 #include "em_cmu.h"\r
34 #include "em_rtc.h"\r
35 #include "em_burtc.h"\r
36 #include "em_rmu.h"\r
37 #include "em_int.h"\r
38 #include "sleep.h"\r
39 \r
40 #define lpINCLUDE_TEST_TIMER    1\r
41 \r
42 /* SEE THE COMMENTS ABOVE THE DEFINITION OF configCREATE_LOW_POWER_DEMO IN\r
43 FreeRTOSConfig.h\r
44 This file contains functions that will override the default implementations\r
45 in the RTOS port layer.  Therefore only build this file if the low power demo\r
46 is being built. */\r
47 #if( configCREATE_LOW_POWER_DEMO == 2 )\r
48 \r
49 #define mainTIMER_FREQUENCY_HZ  ( 4096UL ) /* 32768 clock divided by 8. */\r
50 \r
51 /*\r
52  * The low power demo does not use the SysTick, so override the\r
53  * vPortSetupTickInterrupt() function with an implementation that configures\r
54  * a low power clock source.  NOTE:  This function name must not be changed as\r
55  * it is called from the RTOS portable layer.\r
56  */\r
57 void vPortSetupTimerInterrupt( void );\r
58 \r
59 /*\r
60  * Override the default definition of vPortSuppressTicksAndSleep() that is\r
61  * weakly defined in the FreeRTOS Cortex-M port layer with a version that\r
62  * manages the RTC clock, as the tick is generated from the low power RTC\r
63  * and not the SysTick as would normally be the case on a Cortex-M.\r
64  */\r
65 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime );\r
66 \r
67 /* If lpINCLUDE_TEST_TIMER is defined then the BURTC is used to generate\r
68 interrupts that will wake the processor prior to the expected idle time\r
69 completing.  The timer interval can be altered to test different\r
70 scenarios. */\r
71 #if( lpINCLUDE_TEST_TIMER == 1 )\r
72         static void prvSetupTestTimer( void );\r
73 #endif\r
74 \r
75 /*-----------------------------------------------------------*/\r
76 \r
77 /* Calculate how many clock increments make up a single tick period. */\r
78 static const uint32_t ulReloadValueForOneTick = ( mainTIMER_FREQUENCY_HZ / configTICK_RATE_HZ );\r
79 \r
80 /* Will hold the maximum number of ticks that can be suppressed. */\r
81 static uint32_t xMaximumPossibleSuppressedTicks = 0;\r
82 \r
83 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
84 sleep mode was exited because of a timer interrupt or a different interrupt. */\r
85 static volatile uint32_t ulTickFlag = pdFALSE;\r
86 \r
87 /* As the clock is only 32KHz, it is likely a value of 1 will be enough. */\r
88 static const uint32_t ulStoppedTimerCompensation = 0UL;\r
89 \r
90 /*-----------------------------------------------------------*/\r
91 \r
92 void vPortSetupTimerInterrupt( void )\r
93 {\r
94 RTC_Init_TypeDef xRTCInitStruct;\r
95 const uint32_t ulMAX24BitValue = 0xffffffUL;\r
96 \r
97         xMaximumPossibleSuppressedTicks = ulMAX24BitValue / ulReloadValueForOneTick;\r
98 \r
99         /* Configure the RTC to generate the RTOS tick interrupt. */\r
100 \r
101         /* LXFO setup.  For rev D use 70% boost */\r
102         CMU->CTRL = ( CMU->CTRL & ~_CMU_CTRL_LFXOBOOST_MASK ) | CMU_CTRL_LFXOBOOST_70PCENT;\r
103         #if defined( EMU_AUXCTRL_REDLFXOBOOST )\r
104                 EMU->AUXCTRL = (EMU->AUXCTRL & ~_EMU_AUXCTRL_REDLFXOBOOST_MASK) | EMU_AUXCTRL_REDLFXOBOOST;\r
105         #endif\r
106 \r
107         /* Ensure LE modules are accessible. */\r
108         CMU_ClockEnable( cmuClock_CORELE, true );\r
109 \r
110         /* Use LFXO. */\r
111         CMU_ClockSelectSet( cmuClock_LFA, cmuSelect_LFXO );\r
112 \r
113         /* Use 8x divider to reduce energy. */\r
114         CMU_ClockDivSet( cmuClock_RTC, cmuClkDiv_8 );\r
115 \r
116         /* Enable clock to the RTC module. */\r
117         CMU_ClockEnable( cmuClock_RTC, true );\r
118         xRTCInitStruct.enable = false;\r
119         xRTCInitStruct.debugRun = false;\r
120         xRTCInitStruct.comp0Top = true;\r
121         RTC_Init( &xRTCInitStruct );\r
122 \r
123         /* Disable RTC0 interrupt. */\r
124         RTC_IntDisable( RTC_IFC_COMP0 );\r
125 \r
126         /* The tick interrupt must be set to the lowest priority possible. */\r
127         NVIC_SetPriority( RTC_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY );\r
128         NVIC_ClearPendingIRQ( RTC_IRQn );\r
129         NVIC_EnableIRQ( RTC_IRQn );\r
130         RTC_CompareSet( 0, ulReloadValueForOneTick );\r
131         RTC_IntClear( RTC_IFC_COMP0 );\r
132         RTC_IntEnable( RTC_IF_COMP0 );\r
133         RTC_Enable( true );\r
134 \r
135         /* If lpINCLUDE_TEST_TIMER is defined then the BURTC is used to generate\r
136         interrupts that will wake the processor prior to the expected idle time\r
137         completing.  The timer interval can be altered to test different\r
138         scenarios. */\r
139         #if( lpINCLUDE_TEST_TIMER == 1 )\r
140                 prvSetupTestTimer();\r
141         #endif\r
142 }\r
143 /*-----------------------------------------------------------*/\r
144 \r
145 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
146 {\r
147 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCountBeforeSleep, ulCountAfterSleep;\r
148 eSleepModeStatus eSleepAction;\r
149 TickType_t xModifiableIdleTime;\r
150 \r
151         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
152 \r
153         /* Make sure the RTC reload value does not overflow the counter. */\r
154         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
155         {\r
156                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
157         }\r
158 \r
159         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
160         periods. */\r
161         ulReloadValue = ulReloadValueForOneTick * xExpectedIdleTime;\r
162         if( ulReloadValue > ulStoppedTimerCompensation )\r
163         {\r
164                 /* Compensate for the fact that the RTC is going to be stopped\r
165                 momentarily. */\r
166                 ulReloadValue -= ulStoppedTimerCompensation;\r
167         }\r
168 \r
169         /* Stop the RTC momentarily.  The time the RTC is stopped for is accounted\r
170         for as best it can be, but using the tickless mode will inevitably result\r
171         in some tiny drift of the time maintained by the kernel with respect to\r
172         calendar time.  The count is latched before stopping the timer as stopping\r
173         the timer appears to clear the count. */\r
174         ulCountBeforeSleep = RTC_CounterGet();\r
175         RTC_Enable( false );\r
176 \r
177         /* If this function is re-entered before one complete tick period then the\r
178         reload value might be set to take into account a partial time slice, but\r
179         just reading the count assumes it is counting up to a full ticks worth - so\r
180         add in the difference if any. */\r
181         ulCountBeforeSleep += ( ulReloadValueForOneTick - RTC_CompareGet( 0 ) );\r
182 \r
183         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
184         that will mask interrupts that should exit sleep mode. */\r
185         INT_Disable();\r
186         __asm volatile( "dsb" );\r
187         __asm volatile( "isb" );\r
188 \r
189         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
190         mode is exited then sleep mode was probably exited because the tick was\r
191         suppressed for the entire xExpectedIdleTime period. */\r
192         ulTickFlag = pdFALSE;\r
193 \r
194         /* If a context switch is pending then abandon the low power entry as the\r
195         context switch might have been pended by an external interrupt that     requires\r
196         processing. */\r
197         eSleepAction = eTaskConfirmSleepModeStatus();\r
198         if( eSleepAction == eAbortSleep )\r
199         {\r
200                 /* Restart tick and count up to whatever was left of the current time\r
201                 slice. */\r
202                 RTC_CompareSet( 0, ( ulReloadValueForOneTick - ulCountBeforeSleep ) + ulStoppedTimerCompensation );\r
203                 RTC_Enable( true );\r
204 \r
205                 /* Re-enable interrupts - see comments above the INT_Enable() call\r
206                 above. */\r
207                 INT_Enable();\r
208         }\r
209         else\r
210         {\r
211                 /* Adjust the reload value to take into account that the current time\r
212                 slice is already partially complete. */\r
213                 ulReloadValue -= ulCountBeforeSleep;\r
214                 RTC_CompareSet( 0, ulReloadValue );\r
215 \r
216                 /* Restart the RTC. */\r
217                 RTC_Enable( true );\r
218 \r
219                 /* Allow the application to define some pre-sleep processing. */\r
220                 xModifiableIdleTime = xExpectedIdleTime;\r
221                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
222 \r
223                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
224                 means the application defined code has already executed the WAIT\r
225                 instruction. */\r
226                 if( xModifiableIdleTime > 0 )\r
227                 {\r
228                         __asm volatile( "dsb" );\r
229                         SLEEP_Sleep();\r
230                         __asm volatile( "isb" );\r
231                 }\r
232 \r
233                 /* Allow the application to define some post sleep processing. */\r
234                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
235 \r
236                 /* Stop RTC.  Again, the time the SysTick is stopped for is accounted\r
237                 for as best it can be, but using the tickless mode will inevitably\r
238                 result in some tiny drift of the time maintained by the kernel with\r
239                 respect to calendar time.  The count value is latched before stopping\r
240                 the timer as stopping the timer appears to clear the count. */\r
241                 ulCountAfterSleep = RTC_CounterGet();\r
242                 RTC_Enable( false );\r
243 \r
244                 /* Re-enable interrupts - see comments above the INT_Enable() call\r
245                 above. */\r
246                 INT_Enable();\r
247                 __asm volatile( "dsb" );\r
248                 __asm volatile( "isb" );\r
249 \r
250                 if( ulTickFlag != pdFALSE )\r
251                 {\r
252                         /* The tick interrupt has already executed, although because this\r
253                         function is called with the scheduler suspended the actual tick\r
254                         processing will not occur until after this function has exited.\r
255                         Reset the reload value with whatever remains of this tick period. */\r
256                         ulReloadValue = ulReloadValueForOneTick - ulCountAfterSleep;\r
257                         RTC_CompareSet( 0, ulReloadValue );\r
258 \r
259                         /* The tick interrupt handler will already have pended the tick\r
260                         processing in the kernel.  As the pending tick will be processed as\r
261                         soon as this function exits, the tick value     maintained by the tick\r
262                         is stepped forward by one less than the time spent sleeping.  The\r
263                         actual stepping of the tick appears later in this function. */\r
264                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
265                 }\r
266                 else\r
267                 {\r
268                         /* Something other than the tick interrupt ended the sleep.  How\r
269                         many complete tick periods passed while the processor was\r
270                         sleeping?  Add back in the adjustment that was made to the reload\r
271                         value to account for the fact that a time slice was part way through\r
272                         when this function was called. */\r
273                         ulCountAfterSleep += ulCountBeforeSleep;\r
274                         ulCompleteTickPeriods = ulCountAfterSleep / ulReloadValueForOneTick;\r
275 \r
276                         /* The reload value is set to whatever fraction of a single tick\r
277                         period remains. */\r
278                         ulCountAfterSleep -= ( ulCompleteTickPeriods * ulReloadValueForOneTick );\r
279                         ulReloadValue = ulReloadValueForOneTick - ulCountAfterSleep;\r
280 \r
281                         if( ulReloadValue == 0 )\r
282                         {\r
283                                 /* There is no fraction remaining. */\r
284                                 ulReloadValue = ulReloadValueForOneTick;\r
285                                 ulCompleteTickPeriods++;\r
286                         }\r
287 \r
288                         RTC_CompareSet( 0, ulReloadValue );\r
289                 }\r
290 \r
291                 /* Restart the RTC so it runs up to the alarm value.  The alarm value\r
292                 will get set to the value required to generate exactly one tick period\r
293                 the next time the RTC interrupt executes. */\r
294                 RTC_Enable( true );\r
295 \r
296                 /* Wind the tick forward by the number of tick periods that the CPU\r
297                 remained in a low power state. */\r
298                 vTaskStepTick( ulCompleteTickPeriods );\r
299         }\r
300 }\r
301 /*-----------------------------------------------------------*/\r
302 \r
303 void RTC_IRQHandler( void )\r
304 {\r
305         ulTickFlag = pdTRUE;\r
306 \r
307         if( RTC_CompareGet( 0 ) != ulReloadValueForOneTick )\r
308         {\r
309                 /* Set RTC interrupt to one RTOS tick period. */\r
310                 RTC_Enable( false );\r
311                 RTC_CompareSet( 0, ulReloadValueForOneTick );\r
312                 RTC_Enable( true );\r
313         }\r
314 \r
315         RTC_IntClear( _RTC_IFC_MASK );\r
316 \r
317         /* Critical section which protect incrementing the tick. */\r
318         portDISABLE_INTERRUPTS();\r
319         {\r
320                 if( xTaskIncrementTick() != pdFALSE )\r
321                 {\r
322                         /* Pend a context switch. */\r
323                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
324                 }\r
325         }\r
326         portENABLE_INTERRUPTS();\r
327 }\r
328 /*-----------------------------------------------------------*/\r
329 \r
330 #if( lpINCLUDE_TEST_TIMER == 1 )\r
331 \r
332         /* If lpINCLUDE_TEST_TIMER is defined then the BURTC is used to generate\r
333         interrupts that will wake the processor prior to the expected idle time\r
334         completing.  The timer interval can be altered to test different\r
335         scenarios. */\r
336         static void prvSetupTestTimer( void )\r
337         {\r
338         BURTC_Init_TypeDef xBURTCInitStruct = BURTC_INIT_DEFAULT;\r
339         const uint32_t ulBURTClockHz = 2000UL, ulInterruptFrequency = 1000UL;\r
340         const uint32_t ulReload = ( ulBURTClockHz / ulInterruptFrequency );\r
341 \r
342                 /* Ensure LE modules are accessible. */\r
343                 CMU_ClockEnable( cmuClock_CORELE, true );\r
344 \r
345                 /* Enable access to BURTC registers. */\r
346                 RMU_ResetControl( rmuResetBU, false );\r
347 \r
348                 /* Generate periodic interrupts from BURTC. */\r
349                 xBURTCInitStruct.mode   = burtcModeEM3;         /* Operational in EM3. */\r
350                 xBURTCInitStruct.clkSel = burtcClkSelULFRCO;/* ULFRCO clock. */\r
351                 xBURTCInitStruct.clkDiv = burtcClkDiv_1;        /* 2kHz ULFRCO clock. */\r
352                 xBURTCInitStruct.compare0Top = true;            /* Wrap on COMP0. */\r
353                 BURTC_IntDisable( BURTC_IF_COMP0 );\r
354                 BURTC_Init( &xBURTCInitStruct );\r
355 \r
356                 NVIC_SetPriority( BURTC_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY );\r
357                 NVIC_ClearPendingIRQ( BURTC_IRQn );\r
358                 NVIC_EnableIRQ( BURTC_IRQn );\r
359                 BURTC_CompareSet( 0, ulReload );\r
360                 BURTC_IntClear( BURTC_IF_COMP0 );\r
361                 BURTC_IntEnable( BURTC_IF_COMP0 );\r
362                 BURTC_CounterReset();\r
363         }\r
364 \r
365 #endif\r
366 /*-----------------------------------------------------------*/\r
367 \r
368 #if( lpINCLUDE_TEST_TIMER == 1 )\r
369 \r
370         /* If lpINCLUDE_TEST_TIMER is defined then the BURTC is used to generate\r
371         interrupts that will wake the processor prior to the expected idle time\r
372         completing.  The timer interval can be altered to test different\r
373         scenarios. */\r
374         volatile uint32_t ulTestTimerCounts = 0;\r
375 \r
376         void BURTC_IRQHandler( void )\r
377         {\r
378                 /* Nothing to do here - just testing the code in the scenario where a\r
379                 tickless idle period is ended prior to the expected maximum idle time\r
380                 expiring. */\r
381                 BURTC_IntClear( _RTC_IFC_MASK );\r
382                 ulTestTimerCounts++;\r
383         }\r
384 \r
385 #endif\r
386 /*-----------------------------------------------------------*/\r
387 \r
388 #endif /* ( configCREATE_LOW_POWER_DEMO == 2 ) */\r