]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_EFM32_Gecko_Starter_Kit_Simplicity_Studio/Source/Low_Power_Demo/low_power_tick_management.c
Baseline the Giant Gecko demo, which now has the first pass at a low power tickless...
[freertos] / FreeRTOS / Demo / CORTEX_EFM32_Gecko_Starter_Kit_Simplicity_Studio / Source / Low_Power_Demo / low_power_tick_management.c
1 /*\r
2     FreeRTOS V8.2.3 - Copyright (C) 2015 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     This file is part of the FreeRTOS distribution.\r
8 \r
9     FreeRTOS is free software; you can redistribute it and/or modify it under\r
10     the terms of the GNU General Public License (version 2) as published by the\r
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.\r
12 \r
13     ***************************************************************************\r
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<\r
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<\r
16     >>!   obliged to provide the source code for proprietary components     !<<\r
17     >>!   outside of the FreeRTOS kernel.                                   !<<\r
18     ***************************************************************************\r
19 \r
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following\r
23     link: http://www.freertos.org/a00114.html\r
24 \r
25     ***************************************************************************\r
26      *                                                                       *\r
27      *    FreeRTOS provides completely free yet professionally developed,    *\r
28      *    robust, strictly quality controlled, supported, and cross          *\r
29      *    platform software that is more than just the market leader, it     *\r
30      *    is the industry's de facto standard.                               *\r
31      *                                                                       *\r
32      *    Help yourself get started quickly while simultaneously helping     *\r
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *\r
34      *    tutorial book, reference manual, or both:                          *\r
35      *    http://www.FreeRTOS.org/Documentation                              *\r
36      *                                                                       *\r
37     ***************************************************************************\r
38 \r
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading\r
40     the FAQ page "My application does not run, what could be wrong?".  Have you\r
41     defined configASSERT()?\r
42 \r
43     http://www.FreeRTOS.org/support - In return for receiving this top quality\r
44     embedded software for free we request you assist our global community by\r
45     participating in the support forum.\r
46 \r
47     http://www.FreeRTOS.org/training - Investing in training allows your team to\r
48     be as productive as possible as early as possible.  Now you can receive\r
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers\r
50     Ltd, and the world's leading authority on the world's leading RTOS.\r
51 \r
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
55 \r
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.\r
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.\r
58 \r
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High\r
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
61     licenses offer ticketed support, indemnification and commercial middleware.\r
62 \r
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
64     engineered and independently SIL3 certified version for use in safety and\r
65     mission critical applications that require provable dependability.\r
66 \r
67     1 tab == 4 spaces!\r
68 */\r
69 \r
70 /* Standard includes. */\r
71 #include "limits.h"\r
72 \r
73 /* FreeRTOS includes. */\r
74 #include "FreeRTOS.h"\r
75 #include "task.h"\r
76 \r
77 /* SiLabs library includes. */\r
78 #include "em_cmu.h"\r
79 #include "em_burtc.h"\r
80 #include "em_rmu.h"\r
81 #include "em_int.h"\r
82 #include "sleep.h"\r
83 \r
84 /* This file contains functions that will override the default implementations\r
85 in the RTOS port layer.  Therefore only build this file if the low power demo\r
86 is being built. */\r
87 #if( configCREATE_LOW_POWER_DEMO == 1 )\r
88 \r
89 #define mainTIMER_FREQUENCY_HZ  ( 2000UL )\r
90 \r
91 /*\r
92  * The low power demo does not use the SysTick, so override the\r
93  * vPortSetupTickInterrupt() function with an implementation that configures\r
94  * a low power clock source.  NOTE:  This function name must not be changed as\r
95  * it is called from the RTOS portable layer.\r
96  */\r
97 void vPortSetupTimerInterrupt( void );\r
98 \r
99 /* Override the default definition of vPortSuppressTicksAndSleep() that is\r
100  * weakly defined in the FreeRTOS Cortex-M port layer with a version that\r
101  * manages the BURTC clock, as the tick is generated from the low power BURTC\r
102  * and not the SysTick as would normally be the case on a Cortex-M.\r
103  */\r
104 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime );\r
105 \r
106 /*-----------------------------------------------------------*/\r
107 \r
108 /* Calculate how many clock increments make up a single tick period. */\r
109 static const uint32_t ulReloadValueForOneTick = ( mainTIMER_FREQUENCY_HZ / configTICK_RATE_HZ );\r
110 \r
111 /* Calculate the maximum number of ticks that can be suppressed when using the\r
112 high resolution clock and low resolution clock respectively. */\r
113 static uint32_t xMaximumPossibleSuppressedTicks = 0;\r
114 \r
115 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
116 sleep mode was exited because of an timer interrupt or a different interrupt. */\r
117 static volatile uint32_t ulTickFlag = pdFALSE;\r
118 \r
119 /* As the clock is only 2KHz, it is likely a value of 1 will be too much, so\r
120 use zero - but leave the value here to assist porting to different clock\r
121 speeds. */\r
122 static const uint32_t ulStoppedTimerCompensation = 0UL;\r
123 \r
124 /*-----------------------------------------------------------*/\r
125 \r
126 void vPortSetupTimerInterrupt( void )\r
127 {\r
128 BURTC_Init_TypeDef xBURTCInitStruct = BURTC_INIT_DEFAULT;\r
129 \r
130         xMaximumPossibleSuppressedTicks = ULONG_MAX / ulReloadValueForOneTick;\r
131 \r
132         /* Ensure LE modules are accessible. */\r
133         CMU_ClockEnable( cmuClock_CORELE, true );\r
134 \r
135         /* Enable access to BURTC registers. */\r
136         RMU_ResetControl( rmuResetBU, false );\r
137 \r
138         /* Generate the tick interrupt from BURTC. */\r
139         xBURTCInitStruct.mode   = burtcModeEM3;         /* Operational in EM3. */\r
140         xBURTCInitStruct.clkSel = burtcClkSelULFRCO;/* ULFRCO clock. */\r
141         xBURTCInitStruct.clkDiv = burtcClkDiv_1;        /* 2kHz ULFRCO clock. */\r
142         xBURTCInitStruct.compare0Top = true;            /* Wrap on COMP0. */\r
143         BURTC_IntDisable( BURTC_IF_COMP0 );\r
144         BURTC_Init( &xBURTCInitStruct );\r
145 \r
146         /* The tick interrupt must be set to the lowest possible. */\r
147         NVIC_SetPriority( BURTC_IRQn, configKERNEL_INTERRUPT_PRIORITY );\r
148         NVIC_ClearPendingIRQ( BURTC_IRQn );\r
149         NVIC_EnableIRQ( BURTC_IRQn );\r
150         BURTC_CompareSet( 0, ulReloadValueForOneTick );\r
151         BURTC_IntClear( BURTC_IF_COMP0 );\r
152         BURTC_IntEnable( BURTC_IF_COMP0 );\r
153         BURTC_CounterReset();\r
154 }\r
155 /*-----------------------------------------------------------*/\r
156 \r
157 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
158 {\r
159 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCurrentCount;\r
160 eSleepModeStatus eSleepAction;\r
161 TickType_t xModifiableIdleTime;\r
162 \r
163         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
164 \r
165         /* Make sure the BURTC reload value does not overflow the counter. */\r
166         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
167         {\r
168                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
169         }\r
170 \r
171         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
172         periods. */\r
173         ulReloadValue = ulReloadValueForOneTick * xExpectedIdleTime;\r
174         if( ulReloadValue > ulStoppedTimerCompensation )\r
175         {\r
176                 /* Compensate for the fact that the BURTC is going to be stopped\r
177                 momentarily. */\r
178                 ulReloadValue -= ulStoppedTimerCompensation;\r
179         }\r
180 \r
181         /* Stop the BURTC momentarily.  The time the BURTC is stopped for is\r
182         accounted for as best it can be, but using the tickless mode will inevitably\r
183         result in some tiny drift of the time maintained by the kernel with respect\r
184         to calendar time.  The count is latched before stopping the timer as\r
185         stopping the timer appears to clear the count. */\r
186         ulCurrentCount = BURTC_CounterGet();\r
187         BURTC_Enable( false );\r
188 \r
189         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
190         that will mask interrupts that should exit sleep mode. */\r
191         INT_Disable();\r
192 \r
193         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
194         mode is exited then sleep mode was probably exited because the tick was\r
195         suppressed for the entire xExpectedIdleTime period. */\r
196         ulTickFlag = pdFALSE;\r
197 \r
198         /* If a context switch is pending then abandon the low power entry as the\r
199         context switch might have been pended by an external interrupt that     requires\r
200         processing. */\r
201         eSleepAction = eTaskConfirmSleepModeStatus();\r
202         if( eSleepAction == eAbortSleep )\r
203         {\r
204                 /* Restart tick and count up to whatever was left of the current time\r
205                 slice. */\r
206                 BURTC_CompareSet( 0, ulReloadValueForOneTick - ulCurrentCount );\r
207                 BURTC_Enable( true );\r
208 \r
209                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
210                 above. */\r
211                 INT_Enable();\r
212         }\r
213         else\r
214         {\r
215                 /* Adjust the reload value to take into account that the current time\r
216                 slice is already partially complete. */\r
217                 ulReloadValue -= ulCurrentCount;\r
218                 BURTC_CompareSet( 0, ulReloadValue );\r
219 \r
220                 /* Restart the BURTC. */\r
221                 BURTC_Enable( true );\r
222 \r
223                 /* Allow the application to define some pre-sleep processing. */\r
224                 xModifiableIdleTime = xExpectedIdleTime;\r
225                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
226 \r
227                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
228                 means the application defined code has already executed the WAIT\r
229                 instruction. */\r
230                 if( xModifiableIdleTime > 0 )\r
231                 {\r
232                         __asm volatile( "dsb" );\r
233                         SLEEP_Sleep();\r
234                         __asm volatile( "isb" );\r
235                 }\r
236 \r
237                 /* Allow the application to define some post sleep processing. */\r
238                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
239 \r
240                 /* Stop BURTC.  Again, the time the SysTick is stopped for is accounted\r
241                 for as best it can be, but using the tickless mode will inevitably\r
242                 result in some tiny drift of the time maintained by the kernel with\r
243                 respect to calendar time.  The count value is latched before stopping\r
244                 the timer as stopping the timer appears to clear the count. */\r
245                 ulCurrentCount = BURTC_CounterGet();\r
246                 BURTC_Enable( false );\r
247 \r
248                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
249                 above. */\r
250                 INT_Enable();\r
251 \r
252                 if( ulTickFlag != pdFALSE )\r
253                 {\r
254                         /* The tick interrupt has already executed, although because this\r
255                         function is called with the scheduler suspended the actual tick\r
256                         processing will not occur until after this function has exited.\r
257                         Reset the reload value with whatever remains of this tick period. */\r
258                         ulReloadValue = ulReloadValueForOneTick - ulCurrentCount;\r
259                         BURTC_CompareSet( 0, ulReloadValue );\r
260 \r
261                         /* The tick interrupt handler will already have pended the tick\r
262                         processing in the kernel.  As the pending tick will be processed as\r
263                         soon as this function exits, the tick value     maintained by the tick\r
264                         is stepped forward by one less than the time spent sleeping.  The\r
265                         actual stepping of the tick appears later in this function. */\r
266                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
267                 }\r
268                 else\r
269                 {\r
270                         /* Something other than the tick interrupt ended the sleep.  How\r
271                         many complete tick periods passed while the processor was\r
272                         sleeping? */\r
273                         ulCompleteTickPeriods = ulCurrentCount / ulReloadValueForOneTick;\r
274 \r
275                         /* The reload value is set to whatever fraction of a single tick\r
276                         period remains. */\r
277                         ulReloadValue = ulCurrentCount - ( ulCompleteTickPeriods * ulReloadValueForOneTick );\r
278                         if( ulReloadValue == 0 )\r
279                         {\r
280                                 /* There is no fraction remaining. */\r
281                                 ulReloadValue = ulReloadValueForOneTick;\r
282                                 ulCompleteTickPeriods++;\r
283                         }\r
284 \r
285                         BURTC_CompareSet( 0, ulReloadValue );\r
286                 }\r
287 \r
288                 /* Restart the BURTC so it runs up to the alarm value.  The alarm value\r
289                 will get set to the value required to generate exactly one tick period\r
290                 the next time the BURTC interrupt executes. */\r
291                 BURTC_Enable( true );\r
292 \r
293                 /* Wind the tick forward by the number of tick periods that the CPU\r
294                 remained in a low power state. */\r
295                 vTaskStepTick( ulCompleteTickPeriods );\r
296         }\r
297 }\r
298 /*-----------------------------------------------------------*/\r
299 \r
300 void BURTC_IRQHandler(void)\r
301 {\r
302         if( ulTickFlag == pdFALSE )\r
303         {\r
304                 /* Set BURTC interrupt to one system tick period*/\r
305                 BURTC_Enable( false );\r
306                 BURTC_CompareSet( 0, ulReloadValueForOneTick );\r
307                 ulTickFlag = pdTRUE;\r
308                 BURTC_Enable( true );\r
309         }\r
310 \r
311         BURTC_IntClear( _RTC_IFC_MASK );\r
312 \r
313         /* Critical section which protect incrementing the tick*/\r
314         ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
315         {\r
316                 if( xTaskIncrementTick() != pdFALSE )\r
317                 {\r
318                         /* Pend a context switch. */\r
319                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
320                 }\r
321         }\r
322         portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
323 }\r
324 \r
325 #endif /* ( configCREATE_LOW_POWER_DEMO == 1 ) */\r
326 \r