1 /*
2 * FreeRTOS Kernel V11.1.0
3 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 *
5 * SPDX-License-Identifier: MIT
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy of
8 * this software and associated documentation files (the "Software"), to deal in
9 * the Software without restriction, including without limitation the rights to
10 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11 * the Software, and to permit persons to whom the Software is furnished to do so,
12 * subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 *
24 * https://www.FreeRTOS.org
25 * https://github.com/FreeRTOS
26 *
27 */
28
29 /*-----------------------------------------------------------
30 * Implementation of functions defined in portable.h for the ARM CM4F port.
31 *----------------------------------------------------------*/
32
33 /* IAR includes. */
34 #include <intrinsics.h>
35
36 /* Scheduler includes. */
37 #include "FreeRTOS.h"
38 #include "task.h"
39
40 #ifndef __ARMVFP__
41 #error This port can only be used when the project options are configured to enable hardware floating point support.
42 #endif
43
44 #if ( configMAX_SYSCALL_INTERRUPT_PRIORITY == 0 )
45 #error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. See http: /*www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
46 #endif
47
48 /* Prototype of all Interrupt Service Routines (ISRs). */
49 typedef void ( * portISR_t )( void );
50
51 /* Constants required to manipulate the core. Registers first... */
52 #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
53 #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
54 #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
55 #define portNVIC_SHPR2_REG ( *( ( volatile uint32_t * ) 0xe000ed1c ) )
56 #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
57 /* ...then bits in the registers. */
58 #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
59 #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
60 #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
61 #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
62 #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
63 #define portNVIC_PEND_SYSTICK_SET_BIT ( 1UL << 26UL )
64 #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
65
66 /* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7
67 * r0p1 port. */
68 #define portCPUID ( *( ( volatile uint32_t * ) 0xE000ed00 ) )
69 #define portCORTEX_M7_r0p1_ID ( 0x410FC271UL )
70 #define portCORTEX_M7_r0p0_ID ( 0x410FC270UL )
71
72 #define portMIN_INTERRUPT_PRIORITY ( 255UL )
73 #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
74 #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
75
76 /* Constants used to check the installation of the FreeRTOS interrupt handlers. */
77 #define portSCB_VTOR_REG ( *( ( portISR_t ** ) 0xE000ED08 ) )
78 #define portVECTOR_INDEX_SVC ( 11 )
79 #define portVECTOR_INDEX_PENDSV ( 14 )
80
81 /* Constants required to check the validity of an interrupt priority. */
82 #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
83 #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
84 #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
85 #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
86 #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
87 #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
88 #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
89 #define portPRIGROUP_SHIFT ( 8UL )
90
91 /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
92 #define portVECTACTIVE_MASK ( 0xFFUL )
93
94 /* Constants required to manipulate the VFP. */
95 #define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
96 #define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL )
97
98 /* Constants required to set up the initial stack. */
99 #define portINITIAL_XPSR ( 0x01000000 )
100 #define portINITIAL_EXC_RETURN ( 0xfffffffd )
101
102 /* The systick is a 24-bit counter. */
103 #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
104
105 /* A fiddle factor to estimate the number of SysTick counts that would have
106 * occurred while the SysTick counter is stopped during tickless idle
107 * calculations. */
108 #define portMISSED_COUNTS_FACTOR ( 94UL )
109
110 /* For strict compliance with the Cortex-M spec the task start address should
111 * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
112 #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
113
114 /* Let the user override the default SysTick clock rate. If defined by the
115 * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
116 * configuration register. */
117 #ifndef configSYSTICK_CLOCK_HZ
118 #define configSYSTICK_CLOCK_HZ ( configCPU_CLOCK_HZ )
119 /* Ensure the SysTick is clocked at the same frequency as the core. */
120 #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( portNVIC_SYSTICK_CLK_BIT )
121 #else
122 /* Select the option to clock SysTick not at the same frequency as the core. */
123 #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( 0 )
124 #endif
125
126 /*
127 * Setup the timer to generate the tick interrupts. The implementation in this
128 * file is weak to allow application writers to change the timer used to
129 * generate the tick interrupt.
130 */
131 void vPortSetupTimerInterrupt( void );
132
133 /*
134 * Exception handlers.
135 */
136 void xPortSysTickHandler( void );
137
138 /*
139 * Start first task is a separate function so it can be tested in isolation.
140 */
141 extern void vPortStartFirstTask( void );
142
143 /*
144 * Turn the VFP on.
145 */
146 extern void vPortEnableVFP( void );
147
148 /*
149 * Used to catch tasks that attempt to return from their implementing function.
150 */
151 static void prvTaskExitError( void );
152
153 /*
154 * FreeRTOS handlers implemented in assembly.
155 */
156 extern void vPortSVCHandler( void );
157 extern void xPortPendSVHandler( void );
158 /*-----------------------------------------------------------*/
159
160 /* Each task maintains its own interrupt status in the critical nesting
161 * variable. */
162 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
163
164 /*
165 * The number of SysTick increments that make up one tick period.
166 */
167 #if ( configUSE_TICKLESS_IDLE == 1 )
168 static uint32_t ulTimerCountsForOneTick = 0;
169 #endif /* configUSE_TICKLESS_IDLE */
170
171 /*
172 * The maximum number of tick periods that can be suppressed is limited by the
173 * 24 bit resolution of the SysTick timer.
174 */
175 #if ( configUSE_TICKLESS_IDLE == 1 )
176 static uint32_t xMaximumPossibleSuppressedTicks = 0;
177 #endif /* configUSE_TICKLESS_IDLE */
178
179 /*
180 * Compensate for the CPU cycles that pass while the SysTick is stopped (low
181 * power functionality only.
182 */
183 #if ( configUSE_TICKLESS_IDLE == 1 )
184 static uint32_t ulStoppedTimerCompensation = 0;
185 #endif /* configUSE_TICKLESS_IDLE */
186
187 /*
188 * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
189 * FreeRTOS API functions are not called from interrupts that have been assigned
190 * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
191 */
192 #if ( configASSERT_DEFINED == 1 )
193 static uint8_t ucMaxSysCallPriority = 0;
194 static uint32_t ulMaxPRIGROUPValue = 0;
195 static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
196 #endif /* configASSERT_DEFINED */
197
198 /*-----------------------------------------------------------*/
199
200 /*
201 * See header file for description.
202 */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)203 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
204 TaskFunction_t pxCode,
205 void * pvParameters )
206 {
207 /* Simulate the stack frame as it would be created by a context switch
208 * interrupt. */
209
210 /* Offset added to account for the way the MCU uses the stack on entry/exit
211 * of interrupts, and to ensure alignment. */
212 pxTopOfStack--;
213
214 *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
215 pxTopOfStack--;
216 *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
217 pxTopOfStack--;
218 *pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
219
220 /* Save code space by skipping register initialisation. */
221 pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
222 *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
223
224 /* A save method is being used that requires each task to maintain its
225 * own exec return value. */
226 pxTopOfStack--;
227 *pxTopOfStack = portINITIAL_EXC_RETURN;
228
229 pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
230
231 return pxTopOfStack;
232 }
233 /*-----------------------------------------------------------*/
234
prvTaskExitError(void)235 static void prvTaskExitError( void )
236 {
237 /* A function that implements a task must not exit or attempt to return to
238 * its caller as there is nothing to return to. If a task wants to exit it
239 * should instead call vTaskDelete( NULL ).
240 *
241 * Artificially force an assert() to be triggered if configASSERT() is
242 * defined, then stop here so application writers can catch the error. */
243 configASSERT( uxCriticalNesting == ~0UL );
244 portDISABLE_INTERRUPTS();
245
246 for( ; ; )
247 {
248 }
249 }
250 /*-----------------------------------------------------------*/
251
252 /*
253 * See header file for description.
254 */
xPortStartScheduler(void)255 BaseType_t xPortStartScheduler( void )
256 {
257 /* This port can be used on all revisions of the Cortex-M7 core other than
258 * the r0p1 parts. r0p1 parts should use the port from the
259 * /source/portable/GCC/ARM_CM7/r0p1 directory. */
260 configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
261 configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
262
263 /* An application can install FreeRTOS interrupt handlers in one of the
264 * following ways:
265 * 1. Direct Routing - Install the functions vPortSVCHandler and
266 * xPortPendSVHandler for SVCall and PendSV interrupts respectively.
267 * 2. Indirect Routing - Install separate handlers for SVCall and PendSV
268 * interrupts and route program control from those handlers to
269 * vPortSVCHandler and xPortPendSVHandler functions.
270 *
271 * Applications that use Indirect Routing must set
272 * configCHECK_HANDLER_INSTALLATION to 0 in their FreeRTOSConfig.h. Direct
273 * routing, which is validated here when configCHECK_HANDLER_INSTALLATION
274 * is 1, should be preferred when possible. */
275 #if ( configCHECK_HANDLER_INSTALLATION == 1 )
276 {
277 const portISR_t * const pxVectorTable = portSCB_VTOR_REG;
278
279 /* Validate that the application has correctly installed the FreeRTOS
280 * handlers for SVCall and PendSV interrupts. We do not check the
281 * installation of the SysTick handler because the application may
282 * choose to drive the RTOS tick using a timer other than the SysTick
283 * timer by overriding the weak function vPortSetupTimerInterrupt().
284 *
285 * Assertion failures here indicate incorrect installation of the
286 * FreeRTOS handlers. For help installing the FreeRTOS handlers, see
287 * https://www.FreeRTOS.org/FAQHelp.html.
288 *
289 * Systems with a configurable address for the interrupt vector table
290 * can also encounter assertion failures or even system faults here if
291 * VTOR is not set correctly to point to the application's vector table. */
292 configASSERT( pxVectorTable[ portVECTOR_INDEX_SVC ] == vPortSVCHandler );
293 configASSERT( pxVectorTable[ portVECTOR_INDEX_PENDSV ] == xPortPendSVHandler );
294 }
295 #endif /* configCHECK_HANDLER_INSTALLATION */
296
297 #if ( configASSERT_DEFINED == 1 )
298 {
299 volatile uint8_t ucOriginalPriority;
300 volatile uint32_t ulImplementedPrioBits = 0;
301 volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
302 volatile uint8_t ucMaxPriorityValue;
303
304 /* Determine the maximum priority from which ISR safe FreeRTOS API
305 * functions can be called. ISR safe functions are those that end in
306 * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
307 * ensure interrupt entry is as fast and simple as possible.
308 *
309 * Save the interrupt priority value that is about to be clobbered. */
310 ucOriginalPriority = *pucFirstUserPriorityRegister;
311
312 /* Determine the number of priority bits available. First write to all
313 * possible bits. */
314 *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
315
316 /* Read the value back to see how many bits stuck. */
317 ucMaxPriorityValue = *pucFirstUserPriorityRegister;
318
319 /* Use the same mask on the maximum system call priority. */
320 ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
321
322 /* Check that the maximum system call priority is nonzero after
323 * accounting for the number of priority bits supported by the
324 * hardware. A priority of 0 is invalid because setting the BASEPRI
325 * register to 0 unmasks all interrupts, and interrupts with priority 0
326 * cannot be masked using BASEPRI.
327 * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
328 configASSERT( ucMaxSysCallPriority );
329
330 /* Check that the bits not implemented in hardware are zero in
331 * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
332 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( uint8_t ) ( ~( uint32_t ) ucMaxPriorityValue ) ) == 0U );
333
334 /* Calculate the maximum acceptable priority group value for the number
335 * of bits read back. */
336
337 while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
338 {
339 ulImplementedPrioBits++;
340 ucMaxPriorityValue <<= ( uint8_t ) 0x01;
341 }
342
343 if( ulImplementedPrioBits == 8 )
344 {
345 /* When the hardware implements 8 priority bits, there is no way for
346 * the software to configure PRIGROUP to not have sub-priorities. As
347 * a result, the least significant bit is always used for sub-priority
348 * and there are 128 preemption priorities and 2 sub-priorities.
349 *
350 * This may cause some confusion in some cases - for example, if
351 * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
352 * priority interrupts will be masked in Critical Sections as those
353 * are at the same preemption priority. This may appear confusing as
354 * 4 is higher (numerically lower) priority than
355 * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
356 * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
357 * to 4, this confusion does not happen and the behaviour remains the same.
358 *
359 * The following assert ensures that the sub-priority bit in the
360 * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
361 * confusion. */
362 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
363 ulMaxPRIGROUPValue = 0;
364 }
365 else
366 {
367 ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
368 }
369
370 /* Shift the priority group value back to its position within the AIRCR
371 * register. */
372 ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
373 ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
374
375 /* Restore the clobbered interrupt priority register to its original
376 * value. */
377 *pucFirstUserPriorityRegister = ucOriginalPriority;
378 }
379 #endif /* configASSERT_DEFINED */
380
381 /* Make PendSV and SysTick the lowest priority interrupts, and make SVCall
382 * the highest priority. */
383 portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
384 portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
385 portNVIC_SHPR2_REG = 0;
386
387 /* Start the timer that generates the tick ISR. Interrupts are disabled
388 * here already. */
389 vPortSetupTimerInterrupt();
390
391 /* Initialise the critical nesting count ready for the first task. */
392 uxCriticalNesting = 0;
393
394 /* Ensure the VFP is enabled - it should be anyway. */
395 vPortEnableVFP();
396
397 /* Lazy save always. */
398 *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
399
400 /* Start the first task. */
401 vPortStartFirstTask();
402
403 /* Should not get here! */
404 return 0;
405 }
406 /*-----------------------------------------------------------*/
407
vPortEndScheduler(void)408 void vPortEndScheduler( void )
409 {
410 /* Not implemented in ports where there is nothing to return to.
411 * Artificially force an assert. */
412 configASSERT( uxCriticalNesting == 1000UL );
413 }
414 /*-----------------------------------------------------------*/
415
vPortEnterCritical(void)416 void vPortEnterCritical( void )
417 {
418 portDISABLE_INTERRUPTS();
419 uxCriticalNesting++;
420
421 /* This is not the interrupt safe version of the enter critical function so
422 * assert() if it is being called from an interrupt context. Only API
423 * functions that end in "FromISR" can be used in an interrupt. Only assert if
424 * the critical nesting count is 1 to protect against recursive calls if the
425 * assert function also uses a critical section. */
426 if( uxCriticalNesting == 1 )
427 {
428 configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
429 }
430 }
431 /*-----------------------------------------------------------*/
432
vPortExitCritical(void)433 void vPortExitCritical( void )
434 {
435 configASSERT( uxCriticalNesting );
436 uxCriticalNesting--;
437
438 if( uxCriticalNesting == 0 )
439 {
440 portENABLE_INTERRUPTS();
441 }
442 }
443 /*-----------------------------------------------------------*/
444
xPortSysTickHandler(void)445 void xPortSysTickHandler( void )
446 {
447 /* The SysTick runs at the lowest interrupt priority, so when this interrupt
448 * executes all interrupts must be unmasked. There is therefore no need to
449 * save and then restore the interrupt mask value as its value is already
450 * known. */
451 portDISABLE_INTERRUPTS();
452 traceISR_ENTER();
453 {
454 /* Increment the RTOS tick. */
455 if( xTaskIncrementTick() != pdFALSE )
456 {
457 traceISR_EXIT_TO_SCHEDULER();
458
459 /* A context switch is required. Context switching is performed in
460 * the PendSV interrupt. Pend the PendSV interrupt. */
461 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
462 }
463 else
464 {
465 traceISR_EXIT();
466 }
467 }
468 portENABLE_INTERRUPTS();
469 }
470 /*-----------------------------------------------------------*/
471
472 #if ( configUSE_TICKLESS_IDLE == 1 )
473
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)474 __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
475 {
476 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
477 TickType_t xModifiableIdleTime;
478
479 /* Make sure the SysTick reload value does not overflow the counter. */
480 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
481 {
482 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
483 }
484
485 /* Enter a critical section but don't use the taskENTER_CRITICAL()
486 * method as that will mask interrupts that should exit sleep mode. */
487 __disable_interrupt();
488 __DSB();
489 __ISB();
490
491 /* If a context switch is pending or a task is waiting for the scheduler
492 * to be unsuspended then abandon the low power entry. */
493 if( eTaskConfirmSleepModeStatus() == eAbortSleep )
494 {
495 /* Re-enable interrupts - see comments above the __disable_interrupt()
496 * call above. */
497 __enable_interrupt();
498 }
499 else
500 {
501 /* Stop the SysTick momentarily. The time the SysTick is stopped for
502 * is accounted for as best it can be, but using the tickless mode will
503 * inevitably result in some tiny drift of the time maintained by the
504 * kernel with respect to calendar time. */
505 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
506
507 /* Use the SysTick current-value register to determine the number of
508 * SysTick decrements remaining until the next tick interrupt. If the
509 * current-value register is zero, then there are actually
510 * ulTimerCountsForOneTick decrements remaining, not zero, because the
511 * SysTick requests the interrupt when decrementing from 1 to 0. */
512 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
513
514 if( ulSysTickDecrementsLeft == 0 )
515 {
516 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
517 }
518
519 /* Calculate the reload value required to wait xExpectedIdleTime
520 * tick periods. -1 is used because this code normally executes part
521 * way through the first tick period. But if the SysTick IRQ is now
522 * pending, then clear the IRQ, suppressing the first tick, and correct
523 * the reload value to reflect that the second tick period is already
524 * underway. The expected idle time is always at least two ticks. */
525 ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
526
527 if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
528 {
529 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
530 ulReloadValue -= ulTimerCountsForOneTick;
531 }
532
533 if( ulReloadValue > ulStoppedTimerCompensation )
534 {
535 ulReloadValue -= ulStoppedTimerCompensation;
536 }
537
538 /* Set the new reload value. */
539 portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
540
541 /* Clear the SysTick count flag and set the count value back to
542 * zero. */
543 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
544
545 /* Restart SysTick. */
546 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
547
548 /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
549 * set its parameter to 0 to indicate that its implementation contains
550 * its own wait for interrupt or wait for event instruction, and so wfi
551 * should not be executed again. However, the original expected idle
552 * time variable must remain unmodified, so a copy is taken. */
553 xModifiableIdleTime = xExpectedIdleTime;
554 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
555
556 if( xModifiableIdleTime > 0 )
557 {
558 __DSB();
559 __WFI();
560 __ISB();
561 }
562
563 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
564
565 /* Re-enable interrupts to allow the interrupt that brought the MCU
566 * out of sleep mode to execute immediately. See comments above
567 * the __disable_interrupt() call above. */
568 __enable_interrupt();
569 __DSB();
570 __ISB();
571
572 /* Disable interrupts again because the clock is about to be stopped
573 * and interrupts that execute while the clock is stopped will increase
574 * any slippage between the time maintained by the RTOS and calendar
575 * time. */
576 __disable_interrupt();
577 __DSB();
578 __ISB();
579
580 /* Disable the SysTick clock without reading the
581 * portNVIC_SYSTICK_CTRL_REG register to ensure the
582 * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
583 * the time the SysTick is stopped for is accounted for as best it can
584 * be, but using the tickless mode will inevitably result in some tiny
585 * drift of the time maintained by the kernel with respect to calendar
586 * time*/
587 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
588
589 /* Determine whether the SysTick has already counted to zero. */
590 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
591 {
592 uint32_t ulCalculatedLoadValue;
593
594 /* The tick interrupt ended the sleep (or is now pending), and
595 * a new tick period has started. Reset portNVIC_SYSTICK_LOAD_REG
596 * with whatever remains of the new tick period. */
597 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
598
599 /* Don't allow a tiny value, or values that have somehow
600 * underflowed because the post sleep hook did something
601 * that took too long or because the SysTick current-value register
602 * is zero. */
603 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
604 {
605 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
606 }
607
608 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
609
610 /* As the pending tick will be processed as soon as this
611 * function exits, the tick value maintained by the tick is stepped
612 * forward by one less than the time spent waiting. */
613 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
614 }
615 else
616 {
617 /* Something other than the tick interrupt ended the sleep. */
618
619 /* Use the SysTick current-value register to determine the
620 * number of SysTick decrements remaining until the expected idle
621 * time would have ended. */
622 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
623 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
624 {
625 /* If the SysTick is not using the core clock, the current-
626 * value register might still be zero here. In that case, the
627 * SysTick didn't load from the reload register, and there are
628 * ulReloadValue decrements remaining in the expected idle
629 * time, not zero. */
630 if( ulSysTickDecrementsLeft == 0 )
631 {
632 ulSysTickDecrementsLeft = ulReloadValue;
633 }
634 }
635 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
636
637 /* Work out how long the sleep lasted rounded to complete tick
638 * periods (not the ulReload value which accounted for part
639 * ticks). */
640 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
641
642 /* How many complete tick periods passed while the processor
643 * was waiting? */
644 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
645
646 /* The reload value is set to whatever fraction of a single tick
647 * period remains. */
648 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
649 }
650
651 /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
652 * then set portNVIC_SYSTICK_LOAD_REG back to its standard value. If
653 * the SysTick is not using the core clock, temporarily configure it to
654 * use the core clock. This configuration forces the SysTick to load
655 * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
656 * cycle of the other clock. Then portNVIC_SYSTICK_LOAD_REG is ready
657 * to receive the standard value immediately. */
658 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
659 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
660 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
661 {
662 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
663 }
664 #else
665 {
666 /* The temporary usage of the core clock has served its purpose,
667 * as described above. Resume usage of the other clock. */
668 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
669
670 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
671 {
672 /* The partial tick period already ended. Be sure the SysTick
673 * counts it only once. */
674 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
675 }
676
677 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
678 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
679 }
680 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
681
682 /* Step the tick to account for any tick periods that elapsed. */
683 vTaskStepTick( ulCompleteTickPeriods );
684
685 /* Exit with interrupts enabled. */
686 __enable_interrupt();
687 }
688 }
689
690 #endif /* configUSE_TICKLESS_IDLE */
691 /*-----------------------------------------------------------*/
692
693 /*
694 * Setup the systick timer to generate the tick interrupts at the required
695 * frequency.
696 */
vPortSetupTimerInterrupt(void)697 __weak void vPortSetupTimerInterrupt( void )
698 {
699 /* Calculate the constants required to configure the tick interrupt. */
700 #if ( configUSE_TICKLESS_IDLE == 1 )
701 {
702 ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
703 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
704 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
705 }
706 #endif /* configUSE_TICKLESS_IDLE */
707
708 /* Stop and clear the SysTick. */
709 portNVIC_SYSTICK_CTRL_REG = 0UL;
710 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
711
712 /* Configure SysTick to interrupt at the requested rate. */
713 portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
714 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
715 }
716 /*-----------------------------------------------------------*/
717
718 #if ( configASSERT_DEFINED == 1 )
719
vPortValidateInterruptPriority(void)720 void vPortValidateInterruptPriority( void )
721 {
722 uint32_t ulCurrentInterrupt;
723 uint8_t ucCurrentPriority;
724
725 /* Obtain the number of the currently executing interrupt. */
726 __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
727
728 /* Is the interrupt number a user defined interrupt? */
729 if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
730 {
731 /* Look up the interrupt's priority. */
732 ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
733
734 /* The following assertion will fail if a service routine (ISR) for
735 * an interrupt that has been assigned a priority above
736 * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
737 * function. ISR safe FreeRTOS API functions must *only* be called
738 * from interrupts that have been assigned a priority at or below
739 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
740 *
741 * Numerically low interrupt priority numbers represent logically high
742 * interrupt priorities, therefore the priority of the interrupt must
743 * be set to a value equal to or numerically *higher* than
744 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
745 *
746 * Interrupts that use the FreeRTOS API must not be left at their
747 * default priority of zero as that is the highest possible priority,
748 * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
749 * and therefore also guaranteed to be invalid.
750 *
751 * FreeRTOS maintains separate thread and ISR API functions to ensure
752 * interrupt entry is as fast and simple as possible.
753 *
754 * The following links provide detailed information:
755 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
756 * https://www.FreeRTOS.org/FAQHelp.html */
757 configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
758 }
759
760 /* Priority grouping: The interrupt controller (NVIC) allows the bits
761 * that define each interrupt's priority to be split between bits that
762 * define the interrupt's pre-emption priority bits and bits that define
763 * the interrupt's sub-priority. For simplicity all bits must be defined
764 * to be pre-emption priority bits. The following assertion will fail if
765 * this is not the case (if some bits represent a sub-priority).
766 *
767 * If the application only uses CMSIS libraries for interrupt
768 * configuration then the correct setting can be achieved on all Cortex-M
769 * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
770 * scheduler. Note however that some vendor specific peripheral libraries
771 * assume a non-zero priority group setting, in which cases using a value
772 * of zero will result in unpredictable behaviour. */
773 configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
774 }
775
776 #endif /* configASSERT_DEFINED */
777