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