]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_M4F_CEC1302_Keil/main_low_power/low_power_tick_config.c
e9bd14c0f1292262c83fbe952858b4cdb1b6a8b7
[freertos] / FreeRTOS / Demo / CORTEX_M4F_CEC1302_Keil / main_low_power / low_power_tick_config.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 /* Library includes. */\r
78 #include "common_lib.h"\r
79 \r
80 #define prvDisableInterrupts()   __asm volatile ( "cpsid i" );          \\r
81                                                                 __dsb( portSY_FULL_READ_WRITE );        \\r
82                                                                 __isb( portSY_FULL_READ_WRITE );\r
83 \r
84 #define prvSleep()                               __dsb( portSY_FULL_READ_WRITE );       \\r
85                                                                 __wfi();                                                        \\r
86                                                                 __isb( portSY_FULL_READ_WRITE );\r
87 \r
88 #define prvEnableInterrupts()    __asm volatile ( "cpsie i" );          \\r
89                                                                 __dsb( portSY_FULL_READ_WRITE );        \\r
90                                                                 __isb( portSY_FULL_READ_WRITE );\r
91 \r
92 /* This file contains functions that will override the default implementations\r
93 in the RTOS port layer.  Therefore only build this file if the low power demo\r
94 is being built. */\r
95 #if( configCREATE_LOW_POWER_DEMO == 1 )\r
96 \r
97 /* ID of the hibernation timer used to generate the tick. */\r
98 #define mainTICK_HTIMER_ID      0\r
99 \r
100 /* Written to the hibernation timer control register to configure the timer for\r
101 its higher resolution. */\r
102 #define mainHTIMER_HIGH_RESOLUTION      0\r
103 \r
104 /* The frequency of the hibernation timer when it is running at its higher\r
105 resolution and low resolution respectively. */\r
106 #define mainHIGHER_RESOLUTION_TIMER_HZ  ( 32787UL ) /* (1000000us / 30.5us) as each LSB is 30.5us. */\r
107 #define mainLOW_RESOLUTION_TIMER_HZ             ( 8UL )  /* ( 1000ms / 125ms ) as each LSB is 0.125s. */\r
108 \r
109 /* When lpINCLUDE_TEST_TIMER is set to 1 a basic timer is used to generate\r
110 interrupts at a low frequency.  The purpose being to bring the CPU out of its\r
111 sleep mode by an interrupt other than the tick interrupt, and therefore\r
112 allowing an additional paths through the code to be tested. */\r
113 #define lpINCLUDE_TEST_TIMER                    0\r
114 \r
115 /* Some registers are accessed directly as the library is not compatible with\r
116 all the compilers used. */\r
117 #define lpHTIMER_PRELOAD_REGISTER               ( * ( volatile uint16_t * ) 0x40009800 )\r
118 #define lpHTIMER_CONTROL_REGISTER               ( * ( volatile uint16_t * ) 0x40009804 )\r
119 #define lpHTIMER_COUNT_REGISTER                 ( * ( volatile uint16_t * ) 0x40009808 )\r
120 #define lpEC_GIRQ17_ENABLE_SET                  ( * ( volatile uint32_t * ) 0x4000C0B8 )\r
121 #define lpHTIMER_INTERRUPT_CONTROL_BIT  ( 1UL << 20UL )\r
122 \r
123 /*\r
124  * The low power demo does not use the SysTick, so override the\r
125  * vPortSetupTickInterrupt() function with an implementation that configures\r
126  * the low power clock.  NOTE:  This function name must not be changed as it\r
127  * is called from the RTOS portable layer.\r
128  */\r
129 void vPortSetupTimerInterrupt( void );\r
130 \r
131 /*\r
132  * To fully test the low power tick processing it is necessary to sometimes\r
133  * bring the MCU out of its sleep state by a method other than the tick\r
134  * interrupt.  Interrupts generated from a basic timer are used for this\r
135  * purpose.\r
136  */\r
137 #if( lpINCLUDE_TEST_TIMER == 1 )\r
138         static void prvSetupBasicTimer( void );\r
139 #endif\r
140 \r
141 /*-----------------------------------------------------------*/\r
142 \r
143 /* The reload value to use in the timer to generate the tick interrupt -\r
144 assumes the timer is running at its higher resolution. */\r
145 static const uint32_t ulHighResolutionReloadValue = ( mainHIGHER_RESOLUTION_TIMER_HZ / configTICK_RATE_HZ );\r
146 \r
147 /* Calculate how many clock increments make up a single tick period. */\r
148 static const uint32_t ulReloadValueForOneHighResolutionTick = ( mainHIGHER_RESOLUTION_TIMER_HZ / configTICK_RATE_HZ );\r
149 //static const uint32_t usReloadValueForOneLowResolutionTick = ( mainLOW_RESOLUTION_TIMER_HZ / configTICK_RATE_HZ );\r
150 \r
151 /* Calculate the maximum number of ticks that can be suppressed when using the\r
152 high resolution clock and low resolution clock respectively. */\r
153 static uint32_t ulMaximumPossibleSuppressedHighResolutionTicks = 0;\r
154 //static const uint16_t usMaximumPossibleSuppressedLowResolutionTicks = USHRT_MAX / usReloadValueForOneLowResolutionTick;\r
155 \r
156 /* As the clock is only 2KHz, it is likely a value of 1 will be too much, so\r
157 use zero - but leave the value here to assist porting to different clock\r
158 speeds. */\r
159 static const uint32_t ulStoppedTimerCompensation = 0UL;\r
160 \r
161 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
162 sleep mode was exited because of an timer interrupt or a different interrupt. */\r
163 static volatile uint32_t ulTickFlag = pdFALSE;\r
164 \r
165 /*-----------------------------------------------------------*/\r
166 \r
167 void NVIC_Handler_HIB_TMR( void )\r
168 {\r
169         lpHTIMER_PRELOAD_REGISTER = ulHighResolutionReloadValue;\r
170 \r
171         /* Increment the RTOS tick. */\r
172         if( xTaskIncrementTick() != pdFALSE )\r
173         {\r
174                 /* A context switch is required.  Context switching is performed in\r
175                 the PendSV interrupt.  Pend the PendSV interrupt. */\r
176                 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
177         }\r
178 \r
179         /* The CPU woke because of a tick. */\r
180         ulTickFlag = pdTRUE;\r
181 }\r
182 /*-----------------------------------------------------------*/\r
183 \r
184 #if( lpINCLUDE_TEST_TIMER == 1 )\r
185 \r
186         #define GIRQ23_ENABLE_SET               ( * ( uint32_t * ) 0x4000C130 )\r
187 \r
188         static void prvSetupBasicTimer( void )\r
189         {\r
190         const uint8_t ucTimerChannel = 0;\r
191         const uint32_t ulTimer0Count = configCPU_CLOCK_HZ / 10;\r
192 \r
193                 GIRQ23_ENABLE_SET = 0x03;\r
194                 *(unsigned int*)0x4000FC18 = 1;\r
195 \r
196                 /* To fully test the low power tick processing it is necessary to sometimes\r
197                 bring the MCU out of its sleep state by a method other than the tick\r
198                 interrupt.  Interrupts generated from a basic timer are used for this\r
199                 purpose. */\r
200                 btimer_init( ucTimerChannel, BTIMER_AUTO_RESTART | BTIMER_COUNT_DOWN | BTIMER_INT_EN, 0, ulTimer0Count, ulTimer0Count );\r
201                 btimer_interrupt_status_get_clr( ucTimerChannel );\r
202                 enable_timer0_irq();\r
203                 NVIC_SetPriority( TIMER0_IRQn, ucTimerChannel );\r
204                 NVIC_ClearPendingIRQ( TIMER0_IRQn );\r
205                 NVIC_EnableIRQ( TIMER0_IRQn );\r
206                 btimer_start( ucTimerChannel );\r
207         }\r
208 \r
209 #endif /* lpINCLUDE_TEST_TIMER */\r
210 /*-----------------------------------------------------------*/\r
211 \r
212 void vPortSetupTimerInterrupt( void )\r
213 {\r
214         ulMaximumPossibleSuppressedHighResolutionTicks = ( ( uint32_t ) USHRT_MAX ) / ulReloadValueForOneHighResolutionTick;\r
215 \r
216         /* Set up the hibernation timer to start at the value required by the\r
217         tick interrupt.  Equivalent to the following libarary call.  The library\r
218         is not used as it is not compatible with all the compilers used:\r
219         htimer_enable( mainTICK_HTIMER_ID, ulHighResolutionReloadValue, mainHTIMER_HIGH_RESOLUTION ); */\r
220         lpHTIMER_PRELOAD_REGISTER = ulHighResolutionReloadValue;\r
221         lpHTIMER_CONTROL_REGISTER = mainHTIMER_HIGH_RESOLUTION;\r
222 \r
223         /* Enable the HTIMER interrupt.  Equivalent to enable_htimer0_irq(); */\r
224         lpEC_GIRQ17_ENABLE_SET |= lpHTIMER_INTERRUPT_CONTROL_BIT;\r
225 \r
226         /* The hibernation timer is not an auto-reload timer, so gets reset\r
227         from within the ISR itself.  For that reason it's interrupt is set\r
228         to the highest possible priority to ensure clock slippage is minimised. */\r
229         NVIC_SetPriority( HTIMER_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY );\r
230         NVIC_ClearPendingIRQ( HTIMER_IRQn );\r
231         NVIC_EnableIRQ( HTIMER_IRQn );\r
232 \r
233         /* A basic timer is also started, purely for test purposes.  Its only\r
234         purpose is to bring the CPU out of its sleep mode by an interrupt other\r
235         than the tick interrupt in order to get more code test coverage. */\r
236         #if( lpINCLUDE_TEST_TIMER == 1 )\r
237         {\r
238                 prvSetupBasicTimer();\r
239         }\r
240         #endif\r
241 }\r
242 /*-----------------------------------------------------------*/\r
243 \r
244 /* Override the default definition of vPortSuppressTicksAndSleep() that is\r
245 weakly defined in the FreeRTOS Cortex-M port layer with a version that manages\r
246 the hibernation timer, as the tick is generated from the low power hibernation\r
247 timer and not the SysTick as would normally be the case on a Cortex-M. */\r
248 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
249 {\r
250 uint32_t ulCompleteTickPeriods, ulReloadValue, ulCompletedTimerDecrements, ulCountAfterSleep, ulCountBeforeSleep;\r
251 eSleepModeStatus eSleepAction;\r
252 TickType_t xModifiableIdleTime;\r
253 \r
254         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
255 \r
256         /* Make sure the hibernation timer reload value does not overflow the\r
257         counter. */\r
258         if( xExpectedIdleTime > ( TickType_t ) ulMaximumPossibleSuppressedHighResolutionTicks )\r
259         {\r
260                 xExpectedIdleTime = ( TickType_t ) ulMaximumPossibleSuppressedHighResolutionTicks;\r
261         }\r
262 \r
263         /* Stop the timer momentarily.  The time the timer is stopped for is\r
264         accounted for as best it can be, but using the tickless mode will\r
265         inevitably result in some tiny drift of the time maintained by the kernel\r
266         with respect to calendar time.  Take the count value first as clearing\r
267         the preload value also seems to clear the count. */\r
268         ulCountBeforeSleep = ( uint32_t ) lpHTIMER_COUNT_REGISTER;\r
269         lpHTIMER_PRELOAD_REGISTER = 0;\r
270 \r
271         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
272         periods.  -1 is used as the current time slice will already be part way\r
273         through, the part value coming from the current timer count value. */\r
274         ulReloadValue = ulCountBeforeSleep + ( ulReloadValueForOneHighResolutionTick * ( xExpectedIdleTime - 1UL ) );\r
275 \r
276         if( ulReloadValue > ulStoppedTimerCompensation )\r
277         {\r
278                 /* Compensate for the fact that the timer is going to be stopped\r
279                 momentarily. */\r
280                 ulReloadValue -= ulStoppedTimerCompensation;\r
281         }\r
282 \r
283         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
284         that will mask interrupts that should exit sleep mode. */\r
285         prvDisableInterrupts();\r
286 \r
287         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
288         mode is exited then sleep mode was probably exited because the tick was\r
289         suppressed for the entire xExpectedIdleTime period. */\r
290         ulTickFlag = pdFALSE;\r
291 \r
292         /* If a context switch is pending then abandon the low power entry as\r
293         the context switch might have been pended by an external interrupt that\r
294         requires processing. */\r
295         eSleepAction = eTaskConfirmSleepModeStatus();\r
296         if( eSleepAction == eAbortSleep )\r
297         {\r
298                 /* Resetart the timer from whatever remains in the counter register,\r
299                 but 0 is not a valid value. */\r
300                 ulReloadValue = ulCountBeforeSleep - ulStoppedTimerCompensation;\r
301 \r
302                 if( ulReloadValue == 0 )\r
303                 {\r
304                         ulReloadValue = ulReloadValueForOneHighResolutionTick;\r
305                         ulCompleteTickPeriods = 1UL;\r
306                 }\r
307                 else\r
308                 {\r
309                         ulCompleteTickPeriods = 0UL;\r
310                 }\r
311 \r
312                 lpHTIMER_PRELOAD_REGISTER = ( uint16_t ) ulReloadValue;\r
313 \r
314                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
315                 above. */\r
316                 prvEnableInterrupts();\r
317         }\r
318         else\r
319         {\r
320                 /* Write the calculated reload value, which will also start the\r
321                 timer. */\r
322                 lpHTIMER_PRELOAD_REGISTER = ( uint16_t ) ulReloadValue;\r
323 \r
324                 /* Allow the application to define some pre-sleep processing. */\r
325                 xModifiableIdleTime = xExpectedIdleTime;\r
326                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
327 \r
328                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
329                 means the application defined code has already executed the sleep\r
330                 instructions. */\r
331                 if( xModifiableIdleTime > 0 )\r
332                 {\r
333                         prvSleep();\r
334                 }\r
335 \r
336                 /* Allow the application to define some post sleep processing. */\r
337                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
338 \r
339                 /* Stop the hibernation timer.  Again, the time the tiemr is stopped\r
340                 for is accounted for as best it can be, but using the tickless mode\r
341                 will inevitably result in some tiny drift of the time maintained by the\r
342                 kernel with respect to calendar time.  Take the count value first as\r
343                 setting the preload to zero also seems to clear the count. */\r
344                 ulCountAfterSleep = lpHTIMER_COUNT_REGISTER;\r
345                 lpHTIMER_PRELOAD_REGISTER = 0;\r
346 \r
347                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
348                 above. */\r
349                 prvEnableInterrupts();\r
350 \r
351                 if( ulTickFlag != pdFALSE )\r
352                 {\r
353                         /* The tick interrupt has already executed, although because this\r
354                         function is called with the scheduler suspended the actual tick\r
355                         processing will not occur until after this function has exited.\r
356                         The timer has already been reloaded to count in ticks, and can just\r
357                         continue counting down from its current value. */\r
358                         ulReloadValue = ulCountAfterSleep;\r
359 \r
360                         /* Sanity check that the timer's reload value has indeed been\r
361                         reset. */\r
362                         configASSERT( ( uint32_t ) lpHTIMER_PRELOAD_REGISTER == ulReloadValueForOneHighResolutionTick );\r
363 \r
364                         /* The tick interrupt handler will already have pended the tick\r
365                         processing in the kernel.  As the pending tick will be processed as\r
366                         soon as this function exits, the tick value     maintained by the tick\r
367                         is stepped forward by one less than the time spent sleeping.  The\r
368                         actual stepping of the tick appears later in this function. */\r
369                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
370                 }\r
371                 else\r
372                 {\r
373                         /* Something other than the tick interrupt ended the sleep.  How\r
374                         many complete tick periods passed while the processor was\r
375                         sleeping? */\r
376                         ulCompletedTimerDecrements = ulReloadValue - ulCountAfterSleep;\r
377 \r
378                         /* Undo the adjustment that was made to the reload value to account\r
379                         for the fact that a time slice was part way through when this\r
380                         function was called before working out how many complete tick\r
381                         periods this represents.  (could have used [ulExpectedIdleTime *\r
382                         ulReloadValueForOneHighResolutionTick] instead of ulReloadValue on\r
383                         the previous line, but this way avoids the multiplication). */\r
384                         ulCompletedTimerDecrements += ( ulReloadValueForOneHighResolutionTick - ulCountBeforeSleep );\r
385                         ulCompleteTickPeriods = ulCompletedTimerDecrements / ulReloadValueForOneHighResolutionTick;\r
386 \r
387                         /* The reload value is set to whatever fraction of a single tick\r
388                         period remains. */\r
389                         ulReloadValue = ( ( ulCompleteTickPeriods + 1UL ) * ulReloadValueForOneHighResolutionTick ) - ulCompletedTimerDecrements;\r
390                 }\r
391 \r
392                 /* Cannot use a reload value of 0 - it will not start the timer. */\r
393                 if( ulReloadValue == 0 )\r
394                 {\r
395                         /* There is no fraction remaining. */\r
396                         ulReloadValue = ulReloadValueForOneHighResolutionTick;\r
397                         ulCompleteTickPeriods++;\r
398                 }\r
399 \r
400                 /* Restart the timer so it runs down from the reload value.  The reload\r
401                 value will get set to the value required to generate exactly one tick\r
402                 period the next time the tick interrupt executes. */\r
403                 lpHTIMER_PRELOAD_REGISTER = ( uint16_t ) ulReloadValue;\r
404         }\r
405 \r
406         /* Wind the tick forward by the number of tick periods that the CPU\r
407         remained in a low power state. */\r
408         vTaskStepTick( ulCompleteTickPeriods );\r
409 }\r
410 /*-----------------------------------------------------------*/\r
411 \r
412 void NVIC_Handler_TMR0( void )\r
413 {\r
414         /* This timer is used for test purposes.  Its only function is to\r
415         generate interrupts while the MCU is sleeping, so the MCU is sometimes\r
416         brought out of sleep by a means other than the tick interrupt. */\r
417 }\r
418 /*-----------------------------------------------------------*/\r
419 \r
420 \r
421 #endif /* configCREATE_LOW_POWER_DEMO */\r
422 \r