]> git.sur5r.net Git - freertos/blob - FreeRTOS/Demo/CORTEX_M4_ATSAM4L_Atmel_Studio/src/SAM4L_low_power_tick_management.c
Update version number in preparation for official V8.2.0 release.
[freertos] / FreeRTOS / Demo / CORTEX_M4_ATSAM4L_Atmel_Studio / src / SAM4L_low_power_tick_management.c
1 /*\r
2     FreeRTOS V8.2.0 - 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 <asf.h>\r
79 \r
80 \r
81 /*\r
82  * When configCREATE_LOW_POWER_DEMO is set to 1 then the tick interrupt\r
83  * is generated by the AST.  The AST configuration and handling functions are\r
84  * defined in this file.\r
85  *\r
86  * When configCREATE_LOW_POWER_DEMO is set to 0 the tick interrupt is\r
87  * generated by the standard FreeRTOS Cortex-M port layer, which uses the\r
88  * SysTick timer.\r
89  */\r
90 #if configCREATE_LOW_POWER_DEMO == 1\r
91 \r
92 /* Constants required to pend a PendSV interrupt from the tick ISR if the\r
93 preemptive scheduler is being used.  These are just standard bits and registers\r
94 within the Cortex-M core itself. */\r
95 #define portNVIC_PENDSVSET_BIT  ( 1UL << 28UL )\r
96 \r
97 /* The alarm used to generate interrupts in the asynchronous timer. */\r
98 #define portAST_ALARM_CHANNEL   0\r
99 \r
100 /*-----------------------------------------------------------*/\r
101 \r
102 /*\r
103  * The tick interrupt is generated by the asynchronous timer.  The default tick\r
104  * interrupt handler cannot be used (even with the AST being handled from the\r
105  * tick hook function) because the default tick interrupt accesses the SysTick\r
106  * registers when configUSE_TICKLESS_IDLE set to 1.  AST_ALARM_Handler() is the\r
107  * default name for the AST alarm interrupt.  This definition overrides the\r
108  * default implementation that is weakly defined in the interrupt vector table\r
109  * file.\r
110  */\r
111 void AST_ALARM_Handler(void);\r
112 \r
113 /*\r
114  * Functions that disable and enable the AST respectively, not returning until\r
115  * the operation is known to have taken effect.\r
116  */\r
117 static void prvDisableAST( void );\r
118 static void prvEnableAST( void );\r
119 \r
120 /*-----------------------------------------------------------*/\r
121 \r
122 /* Calculate how many clock increments make up a single tick period. */\r
123 static const uint32_t ulAlarmValueForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );\r
124 \r
125 /* Holds the maximum number of ticks that can be suppressed - which is\r
126 basically how far into the future an interrupt can be generated. Set\r
127 during initialisation. */\r
128 static TickType_t xMaximumPossibleSuppressedTicks = 0;\r
129 \r
130 /* Flag set from the tick interrupt to allow the sleep processing to know if\r
131 sleep mode was exited because of an AST interrupt or a different interrupt. */\r
132 static volatile uint32_t ulTickFlag = pdFALSE;\r
133 \r
134 /* The AST counter is stopped temporarily each time it is re-programmed.  The\r
135 following variable offsets the AST counter alarm value by the number of AST\r
136 counts that would typically be missed while the counter was stopped to compensate\r
137 for the lost time.  _RB_ Value needs calculating correctly. */\r
138 static uint32_t ulStoppedTimerCompensation = 2 / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );\r
139 \r
140 /*-----------------------------------------------------------*/\r
141 \r
142 /* The tick interrupt handler.  This is always the same other than the part that\r
143 clears the interrupt, which is specific to the clock being used to generate the\r
144 tick. */\r
145 void AST_ALARM_Handler(void)\r
146 {\r
147         /* Protect incrementing the tick with an interrupt safe critical section. */\r
148         ( void ) portSET_INTERRUPT_MASK_FROM_ISR();\r
149         {\r
150                 if( xTaskIncrementTick() != pdFALSE )\r
151                 {\r
152                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
153                 }\r
154 \r
155                 /* Just completely clear the interrupt mask on exit by passing 0 because\r
156                 it is known that this interrupt will only ever execute with the lowest\r
157                 possible interrupt priority. */\r
158         }\r
159         portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );\r
160 \r
161         /* The CPU woke because of a tick. */\r
162         ulTickFlag = pdTRUE;\r
163 \r
164         /* If this is the first tick since exiting tickless mode then the AST needs\r
165         to be reconfigured to generate interrupts at the defined tick frequency. */\r
166         ast_write_alarm0_value( AST, ulAlarmValueForOneTick );\r
167 \r
168         /* Ensure the interrupt is clear before exiting. */\r
169         ast_clear_interrupt_flag( AST, AST_INTERRUPT_ALARM );\r
170 }\r
171 /*-----------------------------------------------------------*/\r
172 \r
173 /* Override the default definition of vPortSetupTimerInterrupt() that is weakly\r
174 defined in the FreeRTOS Cortex-M3 port layer with a version that configures the\r
175 asynchronous timer (AST) to generate the tick interrupt. */\r
176 void vPortSetupTimerInterrupt( void )\r
177 {\r
178 struct ast_config ast_conf;\r
179 \r
180         /* Ensure the AST can bring the CPU out of sleep mode. */\r
181         sleepmgr_lock_mode( SLEEPMGR_RET );\r
182 \r
183         /* Ensure the 32KHz oscillator is enabled. */\r
184         if( osc_is_ready( OSC_ID_OSC32 ) == pdFALSE )\r
185         {\r
186                 osc_enable( OSC_ID_OSC32 );\r
187                 osc_wait_ready( OSC_ID_OSC32 );\r
188         }\r
189 \r
190         /* Enable the AST itself. */\r
191         ast_enable( AST );\r
192 \r
193         ast_conf.mode = AST_COUNTER_MODE;  /* Simple up counter. */\r
194         ast_conf.osc_type = AST_OSC_32KHZ;\r
195         ast_conf.psel = 0; /* No prescale so the actual frequency is 32KHz/2. */\r
196         ast_conf.counter = 0;\r
197         ast_set_config( AST, &ast_conf );\r
198 \r
199         /* The AST alarm interrupt is used as the tick interrupt.  Ensure the alarm\r
200         status starts clear. */\r
201         ast_clear_interrupt_flag( AST, AST_INTERRUPT_ALARM );\r
202 \r
203         /* Enable wakeup from alarm 0 in the AST and power manager.  */\r
204         ast_enable_wakeup( AST, AST_WAKEUP_ALARM );\r
205         bpm_enable_wakeup_source( BPM, ( 1 << BPM_BKUPWEN_AST ) );\r
206 \r
207         /* Tick interrupt MUST execute at the lowest interrupt priority. */\r
208         NVIC_SetPriority( AST_ALARM_IRQn, configLIBRARY_LOWEST_INTERRUPT_PRIORITY);\r
209         ast_enable_interrupt( AST, AST_INTERRUPT_ALARM );\r
210         NVIC_ClearPendingIRQ( AST_ALARM_IRQn );\r
211         NVIC_EnableIRQ( AST_ALARM_IRQn );\r
212 \r
213         /* Automatically clear the counter on interrupt. */\r
214         ast_enable_counter_clear_on_alarm( AST, portAST_ALARM_CHANNEL );\r
215 \r
216         /* Start with the tick active and generating a tick with regular period. */\r
217         ast_write_alarm0_value( AST, ulAlarmValueForOneTick );\r
218         ast_write_counter_value( AST, 0 );\r
219 \r
220         /* See the comments where xMaximumPossibleSuppressedTicks is declared. */\r
221         xMaximumPossibleSuppressedTicks = ULONG_MAX / ulAlarmValueForOneTick;\r
222 }\r
223 /*-----------------------------------------------------------*/\r
224 \r
225 static void prvDisableAST( void )\r
226 {\r
227         while( ast_is_busy( AST ) )\r
228         {\r
229                 /* Nothing to do here, just waiting. */\r
230         }\r
231         AST->AST_CR &= ~( AST_CR_EN );\r
232         while( ast_is_busy( AST ) )\r
233         {\r
234                 /* Nothing to do here, just waiting. */\r
235         }\r
236 }\r
237 /*-----------------------------------------------------------*/\r
238 \r
239 static void prvEnableAST( void )\r
240 {\r
241         while( ast_is_busy( AST ) )\r
242         {\r
243                 /* Nothing to do here, just waiting. */\r
244         }\r
245         AST->AST_CR |= AST_CR_EN;\r
246         while( ast_is_busy( AST ) )\r
247         {\r
248                 /* Nothing to do here, just waiting. */\r
249         }\r
250 }\r
251 /*-----------------------------------------------------------*/\r
252 \r
253 /* Override the default definition of vPortSuppressTicksAndSleep() that is weakly\r
254 defined in the FreeRTOS Cortex-M3 port layer with a version that manages the\r
255 asynchronous timer (AST), as the tick is generated from the low power AST and\r
256 not the SysTick as would normally be the case on a Cortex-M. */\r
257 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
258 {\r
259 uint32_t ulAlarmValue, ulCompleteTickPeriods, ulInterruptStatus;\r
260 eSleepModeStatus eSleepAction;\r
261 TickType_t xModifiableIdleTime;\r
262 enum sleepmgr_mode xSleepMode;\r
263 \r
264         /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */\r
265 \r
266         /* Make sure the AST reload value does not overflow the counter. */\r
267         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
268         {\r
269                 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
270         }\r
271 \r
272         /* Calculate the reload value required to wait xExpectedIdleTime tick\r
273         periods. */\r
274         ulAlarmValue = ulAlarmValueForOneTick * xExpectedIdleTime;\r
275         if( ulAlarmValue > ulStoppedTimerCompensation )\r
276         {\r
277                 /* Compensate for the fact that the AST is going to be stopped\r
278                 momentarily. */\r
279                 ulAlarmValue -= ulStoppedTimerCompensation;\r
280         }\r
281 \r
282         /* Stop the AST momentarily.  The time the AST is stopped for is accounted\r
283         for as best it can be, but using the tickless mode will inevitably result in\r
284         some tiny drift of the time maintained by the kernel with respect to\r
285         calendar time. */\r
286         prvDisableAST();\r
287 \r
288         /* Enter a critical section but don't use the taskENTER_CRITICAL() method as\r
289         that will mask interrupts that should exit sleep mode. */\r
290         ulInterruptStatus = cpu_irq_save();\r
291 \r
292         /* The tick flag is set to false before sleeping.  If it is true when sleep\r
293         mode is exited then sleep mode was probably exited because the tick was\r
294         suppressed for the entire xExpectedIdleTime period. */\r
295         ulTickFlag = pdFALSE;\r
296 \r
297         /* If a context switch is pending then abandon the low power entry as\r
298         the context switch might have been pended by an external interrupt that\r
299         requires processing. */\r
300         eSleepAction = eTaskConfirmSleepModeStatus();\r
301         if( eSleepAction == eAbortSleep )\r
302         {\r
303                 /* Restart tick. */\r
304                 prvEnableAST();\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         else\r
311         {\r
312                 /* Adjust the alarm value to take into account that the current time\r
313                 slice is already partially complete. */\r
314                 ulAlarmValue -= ast_read_counter_value( AST );\r
315                 ast_write_alarm0_value( AST, ulAlarmValue );\r
316 \r
317                 /* Restart the AST. */\r
318                 prvEnableAST();\r
319 \r
320                 /* Allow the application to define some pre-sleep processing. */\r
321                 xModifiableIdleTime = xExpectedIdleTime;\r
322                 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
323 \r
324                 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()\r
325                 means the application defined code has already executed the WAIT\r
326                 instruction. */\r
327                 if( xModifiableIdleTime > 0 )\r
328                 {\r
329                         /* Find the deepest allowable sleep mode. */\r
330                         xSleepMode = sleepmgr_get_sleep_mode();\r
331 \r
332                         if( xSleepMode != SLEEPMGR_ACTIVE )\r
333                         {\r
334                                 /* Sleep until something happens. */\r
335                                 bpm_sleep( BPM, xSleepMode );\r
336                         }\r
337                 }\r
338 \r
339                 /* Allow the application to define some post sleep processing. */\r
340                 configPOST_SLEEP_PROCESSING( xModifiableIdleTime );\r
341 \r
342                 /* Stop AST.  Again, the time the SysTick is stopped for is     accounted\r
343                 for as best it can be, but using the tickless mode will inevitably\r
344                 result in some tiny drift of the time maintained by the kernel with\r
345                 respect to calendar time. */\r
346                 prvDisableAST();\r
347 \r
348                 /* Re-enable interrupts - see comments above the cpsid instruction()\r
349                 above. */\r
350                 cpu_irq_restore( ulInterruptStatus );\r
351 \r
352                 if( ulTickFlag != pdFALSE )\r
353                 {\r
354                         /* The tick interrupt has already executed, although because this\r
355                         function is called with the scheduler suspended the actual tick\r
356                         processing will not occur until after this function has exited.\r
357                         Reset the alarm value with whatever remains of this tick period. */\r
358                         ulAlarmValue = ulAlarmValueForOneTick - ast_read_counter_value( AST );\r
359                         ast_write_alarm0_value( AST, ulAlarmValue );\r
360 \r
361                         /* The tick interrupt handler will already have pended the tick\r
362                         processing in the kernel.  As the pending tick will be processed as\r
363                         soon as this function exits, the tick value     maintained by the tick\r
364                         is stepped forward by one less than the time spent sleeping.  The\r
365                         actual stepping of the tick appears later in this function. */\r
366                         ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
367                 }\r
368                 else\r
369                 {\r
370                         /* Something other than the tick interrupt ended the sleep.  How\r
371                         many complete tick periods passed while the processor was\r
372                         sleeping? */\r
373                         ulCompleteTickPeriods = ast_read_counter_value( AST ) / ulAlarmValueForOneTick;\r
374 \r
375                         /* The alarm value is set to whatever fraction of a single tick\r
376                         period remains. */\r
377                         ulAlarmValue = ast_read_counter_value( AST ) - ( ulCompleteTickPeriods * ulAlarmValueForOneTick );\r
378                         if( ulAlarmValue == 0 )\r
379                         {\r
380                                 /* There is no fraction remaining. */\r
381                                 ulAlarmValue = ulAlarmValueForOneTick;\r
382                                 ulCompleteTickPeriods++;\r
383                         }\r
384                         ast_write_counter_value( AST, 0 );\r
385                         ast_write_alarm0_value( AST, ulAlarmValue );\r
386                 }\r
387 \r
388                 /* Restart the AST so it runs up to the alarm value.  The alarm value\r
389                 will get set to the value required to generate exactly one tick period\r
390                 the next time the AST interrupt executes. */\r
391                 prvEnableAST();\r
392 \r
393                 /* Wind the tick forward by the number of tick periods that the CPU\r
394                 remained in a low power state. */\r
395                 vTaskStepTick( ulCompleteTickPeriods );\r
396         }\r
397 }\r
398 \r
399 \r
400 #endif /* configCREATE_LOW_POWER_DEMO == 1 */\r
401 \r