2 * FreeRTOS Kernel <DEVELOPMENT BRANCH>
3 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * SPDX-License-Identifier: MIT
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:
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
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.
24 * https://www.FreeRTOS.org
25 * https://github.com/FreeRTOS
29 /*-----------------------------------------------------------
30 * Implementation of functions defined in portable.h for the ARM CM4F port.
31 *----------------------------------------------------------*/
33 /* Scheduler includes. */
38 #error This port can only be used when the project options are configured to enable hardware floating point support.
41 /* Constants required to manipulate the core. Registers first... */
42 #define portNVIC_SYSTICK_CTRL_REG ( *( ( volatile uint32_t * ) 0xe000e010 ) )
43 #define portNVIC_SYSTICK_LOAD_REG ( *( ( volatile uint32_t * ) 0xe000e014 ) )
44 #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( *( ( volatile uint32_t * ) 0xe000e018 ) )
45 #define portNVIC_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
46 /* ...then bits in the registers. */
47 #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
48 #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
49 #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
50 #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
51 #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
52 #define portNVIC_PEND_SYSTICK_SET_BIT ( 1UL << 26UL )
53 #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
55 /* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7
57 #define portCPUID ( *( ( volatile uint32_t * ) 0xE000ed00 ) )
58 #define portCORTEX_M7_r0p1_ID ( 0x410FC271UL )
59 #define portCORTEX_M7_r0p0_ID ( 0x410FC270UL )
61 #define portMIN_INTERRUPT_PRIORITY ( 255UL )
62 #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
63 #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
65 /* Constants required to check the validity of an interrupt priority. */
66 #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
67 #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
68 #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
69 #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
70 #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
71 #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
72 #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
73 #define portPRIGROUP_SHIFT ( 8UL )
75 /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
76 #define portVECTACTIVE_MASK ( 0xFFUL )
78 /* Constants required to manipulate the VFP. */
79 #define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
80 #define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL )
82 /* Constants required to set up the initial stack. */
83 #define portINITIAL_XPSR ( 0x01000000 )
84 #define portINITIAL_EXC_RETURN ( 0xfffffffd )
86 /* The systick is a 24-bit counter. */
87 #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
89 /* For strict compliance with the Cortex-M spec the task start address should
90 * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
91 #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
93 /* A fiddle factor to estimate the number of SysTick counts that would have
94 * occurred while the SysTick counter is stopped during tickless idle
96 #define portMISSED_COUNTS_FACTOR ( 94UL )
98 /* Let the user override the default SysTick clock rate. If defined by the
99 * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
100 * configuration register. */
101 #ifndef configSYSTICK_CLOCK_HZ
102 #define configSYSTICK_CLOCK_HZ ( configCPU_CLOCK_HZ )
103 /* Ensure the SysTick is clocked at the same frequency as the core. */
104 #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( portNVIC_SYSTICK_CLK_BIT )
106 /* Select the option to clock SysTick not at the same frequency as the core. */
107 #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( 0 )
110 /* Let the user override the pre-loading of the initial LR with the address of
111 * prvTaskExitError() in case it messes up unwinding of the stack in the
113 #ifdef configTASK_RETURN_ADDRESS
114 #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
116 #define portTASK_RETURN_ADDRESS prvTaskExitError
120 * Setup the timer to generate the tick interrupts. The implementation in this
121 * file is weak to allow application writers to change the timer used to
122 * generate the tick interrupt.
124 void vPortSetupTimerInterrupt( void );
127 * Exception handlers.
129 void xPortPendSVHandler( void ) __attribute__( ( naked ) );
130 void xPortSysTickHandler( void );
131 void vPortSVCHandler( void ) __attribute__( ( naked ) );
134 * Start first task is a separate function so it can be tested in isolation.
136 static void prvPortStartFirstTask( void ) __attribute__( ( naked ) );
139 * Function to enable the VFP.
141 static void vPortEnableVFP( void ) __attribute__( ( naked ) );
144 * Used to catch tasks that attempt to return from their implementing function.
146 static void prvTaskExitError( void );
148 /*-----------------------------------------------------------*/
150 /* Each task maintains its own interrupt status in the critical nesting
152 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
155 * The number of SysTick increments that make up one tick period.
157 #if ( configUSE_TICKLESS_IDLE == 1 )
158 static uint32_t ulTimerCountsForOneTick = 0;
159 #endif /* configUSE_TICKLESS_IDLE */
162 * The maximum number of tick periods that can be suppressed is limited by the
163 * 24 bit resolution of the SysTick timer.
165 #if ( configUSE_TICKLESS_IDLE == 1 )
166 static uint32_t xMaximumPossibleSuppressedTicks = 0;
167 #endif /* configUSE_TICKLESS_IDLE */
170 * Compensate for the CPU cycles that pass while the SysTick is stopped (low
171 * power functionality only.
173 #if ( configUSE_TICKLESS_IDLE == 1 )
174 static uint32_t ulStoppedTimerCompensation = 0;
175 #endif /* configUSE_TICKLESS_IDLE */
178 * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
179 * FreeRTOS API functions are not called from interrupts that have been assigned
180 * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
182 #if ( configASSERT_DEFINED == 1 )
183 static uint8_t ucMaxSysCallPriority = 0;
184 static uint32_t ulMaxPRIGROUPValue = 0;
185 static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
186 #endif /* configASSERT_DEFINED */
188 /*-----------------------------------------------------------*/
191 * See header file for description.
193 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
194 TaskFunction_t pxCode,
195 void * pvParameters )
197 /* Simulate the stack frame as it would be created by a context switch
200 /* Offset added to account for the way the MCU uses the stack on entry/exit
201 * of interrupts, and to ensure alignment. */
204 *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
206 *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
208 *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
210 /* Save code space by skipping register initialisation. */
211 pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
212 *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
214 /* A save method is being used that requires each task to maintain its
215 * own exec return value. */
217 *pxTopOfStack = portINITIAL_EXC_RETURN;
219 pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
223 /*-----------------------------------------------------------*/
225 static void prvTaskExitError( void )
227 volatile uint32_t ulDummy = 0;
229 /* A function that implements a task must not exit or attempt to return to
230 * its caller as there is nothing to return to. If a task wants to exit it
231 * should instead call vTaskDelete( NULL ).
233 * Artificially force an assert() to be triggered if configASSERT() is
234 * defined, then stop here so application writers can catch the error. */
235 configASSERT( uxCriticalNesting == ~0UL );
236 portDISABLE_INTERRUPTS();
238 while( ulDummy == 0 )
240 /* This file calls prvTaskExitError() after the scheduler has been
241 * started to remove a compiler warning about the function being defined
242 * but never called. ulDummy is used purely to quieten other warnings
243 * about code appearing after this function is called - making ulDummy
244 * volatile makes the compiler think the function could return and
245 * therefore not output an 'unreachable code' warning for code that appears
249 /*-----------------------------------------------------------*/
251 void vPortSVCHandler( void )
254 " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */
255 " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
256 " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
257 " ldmia r0!, {r4-r11, r14} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
258 " msr psp, r0 \n" /* Restore the task stack pointer. */
261 " msr basepri, r0 \n"
265 "pxCurrentTCBConst2: .word pxCurrentTCB \n"
268 /*-----------------------------------------------------------*/
270 static void prvPortStartFirstTask( void )
272 /* Start the first task. This also clears the bit that indicates the FPU is
273 * in use in case the FPU was used before the scheduler was started - which
274 * would otherwise result in the unnecessary leaving of space in the SVC stack
275 * for lazy saving of FPU registers. */
277 " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
280 " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
281 " mov r0, #0 \n" /* Clear the bit that indicates the FPU is in use, see comment above. */
282 " msr control, r0 \n"
283 " cpsie i \n" /* Globally enable interrupts. */
287 " svc 0 \n" /* System call to start first task. */
292 /*-----------------------------------------------------------*/
295 * See header file for description.
297 BaseType_t xPortStartScheduler( void )
299 /* This port can be used on all revisions of the Cortex-M7 core other than
300 * the r0p1 parts. r0p1 parts should use the port from the
301 * /source/portable/GCC/ARM_CM7/r0p1 directory. */
302 configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
303 configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
305 #if ( configASSERT_DEFINED == 1 )
307 volatile uint8_t ucOriginalPriority;
308 volatile uint32_t ulImplementedPrioBits = 0;
309 volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
310 volatile uint8_t ucMaxPriorityValue;
312 /* Determine the maximum priority from which ISR safe FreeRTOS API
313 * functions can be called. ISR safe functions are those that end in
314 * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
315 * ensure interrupt entry is as fast and simple as possible.
317 * Save the interrupt priority value that is about to be clobbered. */
318 ucOriginalPriority = *pucFirstUserPriorityRegister;
320 /* Determine the number of priority bits available. First write to all
322 *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
324 /* Read the value back to see how many bits stuck. */
325 ucMaxPriorityValue = *pucFirstUserPriorityRegister;
327 /* Use the same mask on the maximum system call priority. */
328 ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
330 /* Check that the maximum system call priority is nonzero after
331 * accounting for the number of priority bits supported by the
332 * hardware. A priority of 0 is invalid because setting the BASEPRI
333 * register to 0 unmasks all interrupts, and interrupts with priority 0
334 * cannot be masked using BASEPRI.
335 * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
336 configASSERT( ucMaxSysCallPriority );
338 /* Check that the bits not implemented in hardware are zero in
339 * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
340 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
342 /* Calculate the maximum acceptable priority group value for the number
343 * of bits read back. */
345 while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
347 ulImplementedPrioBits++;
348 ucMaxPriorityValue <<= ( uint8_t ) 0x01;
351 if( ulImplementedPrioBits == 8 )
353 /* When the hardware implements 8 priority bits, there is no way for
354 * the software to configure PRIGROUP to not have sub-priorities. As
355 * a result, the least significant bit is always used for sub-priority
356 * and there are 128 preemption priorities and 2 sub-priorities.
358 * This may cause some confusion in some cases - for example, if
359 * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
360 * priority interrupts will be masked in Critical Sections as those
361 * are at the same preemption priority. This may appear confusing as
362 * 4 is higher (numerically lower) priority than
363 * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
364 * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
365 * to 4, this confusion does not happen and the behaviour remains the same.
367 * The following assert ensures that the sub-priority bit in the
368 * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
370 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
371 ulMaxPRIGROUPValue = 0;
375 ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
378 /* Shift the priority group value back to its position within the AIRCR
380 ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
381 ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
383 /* Restore the clobbered interrupt priority register to its original
385 *pucFirstUserPriorityRegister = ucOriginalPriority;
387 #endif /* configASSERT_DEFINED */
389 /* Make PendSV and SysTick the lowest priority interrupts. */
390 portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
391 portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
393 /* Start the timer that generates the tick ISR. Interrupts are disabled
395 vPortSetupTimerInterrupt();
397 /* Initialise the critical nesting count ready for the first task. */
398 uxCriticalNesting = 0;
400 /* Ensure the VFP is enabled - it should be anyway. */
403 /* Lazy save always. */
404 *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
406 /* Start the first task. */
407 prvPortStartFirstTask();
409 /* Should never get here as the tasks will now be executing! Call the task
410 * exit error function to prevent compiler warnings about a static function
411 * not being called in the case that the application writer overrides this
412 * functionality by defining configTASK_RETURN_ADDRESS. Call
413 * vTaskSwitchContext() so link time optimisation does not remove the
415 vTaskSwitchContext();
418 /* Should not get here! */
421 /*-----------------------------------------------------------*/
423 void vPortEndScheduler( void )
425 /* Not implemented in ports where there is nothing to return to.
426 * Artificially force an assert. */
427 configASSERT( uxCriticalNesting == 1000UL );
429 /*-----------------------------------------------------------*/
431 void vPortEnterCritical( void )
433 portDISABLE_INTERRUPTS();
436 /* This is not the interrupt safe version of the enter critical function so
437 * assert() if it is being called from an interrupt context. Only API
438 * functions that end in "FromISR" can be used in an interrupt. Only assert if
439 * the critical nesting count is 1 to protect against recursive calls if the
440 * assert function also uses a critical section. */
441 if( uxCriticalNesting == 1 )
443 configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
446 /*-----------------------------------------------------------*/
448 void vPortExitCritical( void )
450 configASSERT( uxCriticalNesting );
453 if( uxCriticalNesting == 0 )
455 portENABLE_INTERRUPTS();
458 /*-----------------------------------------------------------*/
460 void xPortPendSVHandler( void )
462 /* This is a naked function. */
469 " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
472 " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, push high vfp registers. */
474 " vstmdbeq r0!, {s16-s31} \n"
476 " stmdb r0!, {r4-r11, r14} \n" /* Save the core registers. */
477 " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
479 " stmdb sp!, {r0, r3} \n"
481 " msr basepri, r0 \n"
484 " bl vTaskSwitchContext \n"
486 " msr basepri, r0 \n"
487 " ldmia sp!, {r0, r3} \n"
489 " ldr r1, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
492 " ldmia r0!, {r4-r11, r14} \n" /* Pop the core registers. */
494 " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, pop the high vfp registers too. */
496 " vldmiaeq r0!, {s16-s31} \n"
501 #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */
502 #if WORKAROUND_PMU_CM001 == 1
511 "pxCurrentTCBConst: .word pxCurrentTCB \n"
512 ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
515 /*-----------------------------------------------------------*/
517 void xPortSysTickHandler( void )
519 /* The SysTick runs at the lowest interrupt priority, so when this interrupt
520 * executes all interrupts must be unmasked. There is therefore no need to
521 * save and then restore the interrupt mask value as its value is already
523 portDISABLE_INTERRUPTS();
525 /* Increment the RTOS tick. */
526 if( xTaskIncrementTick() != pdFALSE )
528 /* A context switch is required. Context switching is performed in
529 * the PendSV interrupt. Pend the PendSV interrupt. */
530 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
533 portENABLE_INTERRUPTS();
535 /*-----------------------------------------------------------*/
537 #if ( configUSE_TICKLESS_IDLE == 1 )
539 __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
541 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
542 TickType_t xModifiableIdleTime;
544 /* Make sure the SysTick reload value does not overflow the counter. */
545 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
547 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
550 /* Enter a critical section but don't use the taskENTER_CRITICAL()
551 * method as that will mask interrupts that should exit sleep mode. */
552 __asm volatile ( "cpsid i" ::: "memory" );
553 __asm volatile ( "dsb" );
554 __asm volatile ( "isb" );
556 /* If a context switch is pending or a task is waiting for the scheduler
557 * to be unsuspended then abandon the low power entry. */
558 if( eTaskConfirmSleepModeStatus() == eAbortSleep )
560 /* Re-enable interrupts - see comments above the cpsid instruction
562 __asm volatile ( "cpsie i" ::: "memory" );
566 /* Stop the SysTick momentarily. The time the SysTick is stopped for
567 * is accounted for as best it can be, but using the tickless mode will
568 * inevitably result in some tiny drift of the time maintained by the
569 * kernel with respect to calendar time. */
570 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
572 /* Use the SysTick current-value register to determine the number of
573 * SysTick decrements remaining until the next tick interrupt. If the
574 * current-value register is zero, then there are actually
575 * ulTimerCountsForOneTick decrements remaining, not zero, because the
576 * SysTick requests the interrupt when decrementing from 1 to 0. */
577 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
579 if( ulSysTickDecrementsLeft == 0 )
581 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
584 /* Calculate the reload value required to wait xExpectedIdleTime
585 * tick periods. -1 is used because this code normally executes part
586 * way through the first tick period. But if the SysTick IRQ is now
587 * pending, then clear the IRQ, suppressing the first tick, and correct
588 * the reload value to reflect that the second tick period is already
589 * underway. The expected idle time is always at least two ticks. */
590 ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
592 if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
594 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
595 ulReloadValue -= ulTimerCountsForOneTick;
598 if( ulReloadValue > ulStoppedTimerCompensation )
600 ulReloadValue -= ulStoppedTimerCompensation;
603 /* Set the new reload value. */
604 portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
606 /* Clear the SysTick count flag and set the count value back to
608 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
610 /* Restart SysTick. */
611 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
613 /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
614 * set its parameter to 0 to indicate that its implementation contains
615 * its own wait for interrupt or wait for event instruction, and so wfi
616 * should not be executed again. However, the original expected idle
617 * time variable must remain unmodified, so a copy is taken. */
618 xModifiableIdleTime = xExpectedIdleTime;
619 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
621 if( xModifiableIdleTime > 0 )
623 __asm volatile ( "dsb" ::: "memory" );
624 __asm volatile ( "wfi" );
625 __asm volatile ( "isb" );
628 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
630 /* Re-enable interrupts to allow the interrupt that brought the MCU
631 * out of sleep mode to execute immediately. See comments above
632 * the cpsid instruction above. */
633 __asm volatile ( "cpsie i" ::: "memory" );
634 __asm volatile ( "dsb" );
635 __asm volatile ( "isb" );
637 /* Disable interrupts again because the clock is about to be stopped
638 * and interrupts that execute while the clock is stopped will increase
639 * any slippage between the time maintained by the RTOS and calendar
641 __asm volatile ( "cpsid i" ::: "memory" );
642 __asm volatile ( "dsb" );
643 __asm volatile ( "isb" );
645 /* Disable the SysTick clock without reading the
646 * portNVIC_SYSTICK_CTRL_REG register to ensure the
647 * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
648 * the time the SysTick is stopped for is accounted for as best it can
649 * be, but using the tickless mode will inevitably result in some tiny
650 * drift of the time maintained by the kernel with respect to calendar
652 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
654 /* Determine whether the SysTick has already counted to zero. */
655 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
657 uint32_t ulCalculatedLoadValue;
659 /* The tick interrupt ended the sleep (or is now pending), and
660 * a new tick period has started. Reset portNVIC_SYSTICK_LOAD_REG
661 * with whatever remains of the new tick period. */
662 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
664 /* Don't allow a tiny value, or values that have somehow
665 * underflowed because the post sleep hook did something
666 * that took too long or because the SysTick current-value register
668 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
670 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
673 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
675 /* As the pending tick will be processed as soon as this
676 * function exits, the tick value maintained by the tick is stepped
677 * forward by one less than the time spent waiting. */
678 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
682 /* Something other than the tick interrupt ended the sleep. */
684 /* Use the SysTick current-value register to determine the
685 * number of SysTick decrements remaining until the expected idle
686 * time would have ended. */
687 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
688 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
690 /* If the SysTick is not using the core clock, the current-
691 * value register might still be zero here. In that case, the
692 * SysTick didn't load from the reload register, and there are
693 * ulReloadValue decrements remaining in the expected idle
695 if( ulSysTickDecrementsLeft == 0 )
697 ulSysTickDecrementsLeft = ulReloadValue;
700 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
702 /* Work out how long the sleep lasted rounded to complete tick
703 * periods (not the ulReload value which accounted for part
705 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
707 /* How many complete tick periods passed while the processor
709 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
711 /* The reload value is set to whatever fraction of a single tick
713 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
716 /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
717 * then set portNVIC_SYSTICK_LOAD_REG back to its standard value. If
718 * the SysTick is not using the core clock, temporarily configure it to
719 * use the core clock. This configuration forces the SysTick to load
720 * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
721 * cycle of the other clock. Then portNVIC_SYSTICK_LOAD_REG is ready
722 * to receive the standard value immediately. */
723 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
724 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
725 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
727 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
731 /* The temporary usage of the core clock has served its purpose,
732 * as described above. Resume usage of the other clock. */
733 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
735 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
737 /* The partial tick period already ended. Be sure the SysTick
738 * counts it only once. */
739 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
742 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
743 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
745 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
747 /* Step the tick to account for any tick periods that elapsed. */
748 vTaskStepTick( ulCompleteTickPeriods );
750 /* Exit with interrupts enabled. */
751 __asm volatile ( "cpsie i" ::: "memory" );
755 #endif /* #if configUSE_TICKLESS_IDLE */
756 /*-----------------------------------------------------------*/
759 * Setup the systick timer to generate the tick interrupts at the required
762 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
764 /* Calculate the constants required to configure the tick interrupt. */
765 #if ( configUSE_TICKLESS_IDLE == 1 )
767 ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
768 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
769 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
771 #endif /* configUSE_TICKLESS_IDLE */
773 /* Stop and clear the SysTick. */
774 portNVIC_SYSTICK_CTRL_REG = 0UL;
775 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
777 /* Configure SysTick to interrupt at the requested rate. */
778 portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
779 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
781 /*-----------------------------------------------------------*/
783 /* This is a naked function. */
784 static void vPortEnableVFP( void )
788 " ldr.w r0, =0xE000ED88 \n" /* The FPU enable bits are in the CPACR. */
791 " orr r1, r1, #( 0xf << 20 ) \n" /* Enable CP10 and CP11 coprocessors, then save back. */
797 /*-----------------------------------------------------------*/
799 #if ( configASSERT_DEFINED == 1 )
801 void vPortValidateInterruptPriority( void )
803 uint32_t ulCurrentInterrupt;
804 uint8_t ucCurrentPriority;
806 /* Obtain the number of the currently executing interrupt. */
807 __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
809 /* Is the interrupt number a user defined interrupt? */
810 if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
812 /* Look up the interrupt's priority. */
813 ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
815 /* The following assertion will fail if a service routine (ISR) for
816 * an interrupt that has been assigned a priority above
817 * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
818 * function. ISR safe FreeRTOS API functions must *only* be called
819 * from interrupts that have been assigned a priority at or below
820 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
822 * Numerically low interrupt priority numbers represent logically high
823 * interrupt priorities, therefore the priority of the interrupt must
824 * be set to a value equal to or numerically *higher* than
825 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
827 * Interrupts that use the FreeRTOS API must not be left at their
828 * default priority of zero as that is the highest possible priority,
829 * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
830 * and therefore also guaranteed to be invalid.
832 * FreeRTOS maintains separate thread and ISR API functions to ensure
833 * interrupt entry is as fast and simple as possible.
835 * The following links provide detailed information:
836 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
837 * https://www.FreeRTOS.org/FAQHelp.html */
838 configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
841 /* Priority grouping: The interrupt controller (NVIC) allows the bits
842 * that define each interrupt's priority to be split between bits that
843 * define the interrupt's pre-emption priority bits and bits that define
844 * the interrupt's sub-priority. For simplicity all bits must be defined
845 * to be pre-emption priority bits. The following assertion will fail if
846 * this is not the case (if some bits represent a sub-priority).
848 * If the application only uses CMSIS libraries for interrupt
849 * configuration then the correct setting can be achieved on all Cortex-M
850 * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
851 * scheduler. Note however that some vendor specific peripheral libraries
852 * assume a non-zero priority group setting, in which cases using a value
853 * of zero will result in unpredictable behaviour. */
854 configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
857 #endif /* configASSERT_DEFINED */