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 /* Scheduler includes. */
34 #include "FreeRTOS.h"
35 #include "task.h"
36 
37 #ifndef __TARGET_FPU_VFP
38     #error This port can only be used when the project options are configured to enable hardware floating point support.
39 #endif
40 
41 #if configMAX_SYSCALL_INTERRUPT_PRIORITY == 0
42     #error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.  See http: /*www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
43 #endif
44 
45 /* Legacy macro for backward compatibility only.  This macro used to be used to
46  * replace the function that configures the clock used to generate the tick
47  * interrupt (prvSetupTimerInterrupt()), but now the function is declared weak so
48  * the application writer can override it by simply defining a function of the
49  * same name (vApplicationSetupTickInterrupt()). */
50 #ifndef configOVERRIDE_DEFAULT_TICK_CONFIGURATION
51     #define configOVERRIDE_DEFAULT_TICK_CONFIGURATION    0
52 #endif
53 
54 /* Constants required to manipulate the core.  Registers first... */
55 #define portNVIC_SYSTICK_CTRL_REG             ( *( ( volatile uint32_t * ) 0xe000e010 ) )
56 #define portNVIC_SYSTICK_LOAD_REG             ( *( ( volatile uint32_t * ) 0xe000e014 ) )
57 #define portNVIC_SYSTICK_CURRENT_VALUE_REG    ( *( ( volatile uint32_t * ) 0xe000e018 ) )
58 #define portNVIC_SHPR3_REG                    ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
59 /* ...then bits in the registers. */
60 #define portNVIC_SYSTICK_CLK_BIT              ( 1UL << 2UL )
61 #define portNVIC_SYSTICK_INT_BIT              ( 1UL << 1UL )
62 #define portNVIC_SYSTICK_ENABLE_BIT           ( 1UL << 0UL )
63 #define portNVIC_SYSTICK_COUNT_FLAG_BIT       ( 1UL << 16UL )
64 #define portNVIC_PENDSVCLEAR_BIT              ( 1UL << 27UL )
65 #define portNVIC_PEND_SYSTICK_SET_BIT         ( 1UL << 26UL )
66 #define portNVIC_PEND_SYSTICK_CLEAR_BIT       ( 1UL << 25UL )
67 
68 /* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7
69  * r0p1 port. */
70 #define portCPUID                             ( *( ( volatile uint32_t * ) 0xE000ed00 ) )
71 #define portCORTEX_M7_r0p1_ID                 ( 0x410FC271UL )
72 #define portCORTEX_M7_r0p0_ID                 ( 0x410FC270UL )
73 
74 #define portMIN_INTERRUPT_PRIORITY            ( 255UL )
75 #define portNVIC_PENDSV_PRI                   ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
76 #define portNVIC_SYSTICK_PRI                  ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
77 
78 /* Constants required to check the validity of an interrupt priority. */
79 #define portFIRST_USER_INTERRUPT_NUMBER       ( 16 )
80 #define portNVIC_IP_REGISTERS_OFFSET_16       ( 0xE000E3F0 )
81 #define portAIRCR_REG                         ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
82 #define portMAX_8_BIT_VALUE                   ( ( uint8_t ) 0xff )
83 #define portTOP_BIT_OF_BYTE                   ( ( uint8_t ) 0x80 )
84 #define portMAX_PRIGROUP_BITS                 ( ( uint8_t ) 7 )
85 #define portPRIORITY_GROUP_MASK               ( 0x07UL << 8UL )
86 #define portPRIGROUP_SHIFT                    ( 8UL )
87 
88 /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
89 #define portVECTACTIVE_MASK                   ( 0xFFUL )
90 
91 /* Constants required to manipulate the VFP. */
92 #define portFPCCR                             ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */
93 #define portASPEN_AND_LSPEN_BITS              ( 0x3UL << 30UL )
94 
95 /* Constants required to set up the initial stack. */
96 #define portINITIAL_XPSR                      ( 0x01000000 )
97 #define portINITIAL_EXC_RETURN                ( 0xfffffffd )
98 
99 /* The systick is a 24-bit counter. */
100 #define portMAX_24_BIT_NUMBER                 ( 0xffffffUL )
101 
102 /* A fiddle factor to estimate the number of SysTick counts that would have
103  * occurred while the SysTick counter is stopped during tickless idle
104  * calculations. */
105 #define portMISSED_COUNTS_FACTOR              ( 94UL )
106 
107 /* For strict compliance with the Cortex-M spec the task start address should
108  * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
109 #define portSTART_ADDRESS_MASK                ( ( StackType_t ) 0xfffffffeUL )
110 
111 /* Let the user override the default SysTick clock rate.  If defined by the
112  * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
113  * configuration register. */
114 #ifndef configSYSTICK_CLOCK_HZ
115     #define configSYSTICK_CLOCK_HZ             ( configCPU_CLOCK_HZ )
116     /* Ensure the SysTick is clocked at the same frequency as the core. */
117     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( portNVIC_SYSTICK_CLK_BIT )
118 #else
119     /* Select the option to clock SysTick not at the same frequency as the core. */
120     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( 0 )
121 #endif
122 
123 /*
124  * Setup the timer to generate the tick interrupts.  The implementation in this
125  * file is weak to allow application writers to change the timer used to
126  * generate the tick interrupt.
127  */
128 void vPortSetupTimerInterrupt( void );
129 
130 /*
131  * Exception handlers.
132  */
133 void xPortPendSVHandler( void );
134 void xPortSysTickHandler( void );
135 void vPortSVCHandler( void );
136 
137 /*
138  * Start first task is a separate function so it can be tested in isolation.
139  */
140 static void prvStartFirstTask( void );
141 
142 /*
143  * Functions defined in portasm.s to enable the VFP.
144  */
145 static void prvEnableVFP( void );
146 
147 /*
148  * Used to catch tasks that attempt to return from their implementing function.
149  */
150 static void prvTaskExitError( void );
151 
152 /*-----------------------------------------------------------*/
153 
154 /* Each task maintains its own interrupt status in the critical nesting
155  * variable. */
156 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
157 
158 /*
159  * The number of SysTick increments that make up one tick period.
160  */
161 #if ( configUSE_TICKLESS_IDLE == 1 )
162     static uint32_t ulTimerCountsForOneTick = 0;
163 #endif /* configUSE_TICKLESS_IDLE */
164 
165 /*
166  * The maximum number of tick periods that can be suppressed is limited by the
167  * 24 bit resolution of the SysTick timer.
168  */
169 #if ( configUSE_TICKLESS_IDLE == 1 )
170     static uint32_t xMaximumPossibleSuppressedTicks = 0;
171 #endif /* configUSE_TICKLESS_IDLE */
172 
173 /*
174  * Compensate for the CPU cycles that pass while the SysTick is stopped (low
175  * power functionality only.
176  */
177 #if ( configUSE_TICKLESS_IDLE == 1 )
178     static uint32_t ulStoppedTimerCompensation = 0;
179 #endif /* configUSE_TICKLESS_IDLE */
180 
181 /*
182  * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
183  * FreeRTOS API functions are not called from interrupts that have been assigned
184  * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
185  */
186 #if ( configASSERT_DEFINED == 1 )
187     static uint8_t ucMaxSysCallPriority = 0;
188     static uint32_t ulMaxPRIGROUPValue = 0;
189     static const volatile uint8_t * const pcInterruptPriorityRegisters = ( uint8_t * ) portNVIC_IP_REGISTERS_OFFSET_16;
190 #endif /* configASSERT_DEFINED */
191 
192 /*-----------------------------------------------------------*/
193 
194 /*
195  * See header file for description.
196  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)197 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
198                                      TaskFunction_t pxCode,
199                                      void * pvParameters )
200 {
201     /* Simulate the stack frame as it would be created by a context switch
202      * interrupt. */
203 
204     /* Offset added to account for the way the MCU uses the stack on entry/exit
205      * of interrupts, and to ensure alignment. */
206     pxTopOfStack--;
207 
208     *pxTopOfStack = portINITIAL_XPSR;                                    /* xPSR */
209     pxTopOfStack--;
210     *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
211     pxTopOfStack--;
212     *pxTopOfStack = ( StackType_t ) prvTaskExitError;                    /* LR */
213 
214     /* Save code space by skipping register initialisation. */
215     pxTopOfStack -= 5;                            /* R12, R3, R2 and R1. */
216     *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
217 
218     /* A save method is being used that requires each task to maintain its
219      * own exec return value. */
220     pxTopOfStack--;
221     *pxTopOfStack = portINITIAL_EXC_RETURN;
222 
223     pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
224 
225     return pxTopOfStack;
226 }
227 /*-----------------------------------------------------------*/
228 
prvTaskExitError(void)229 static void prvTaskExitError( void )
230 {
231     /* A function that implements a task must not exit or attempt to return to
232      * its caller as there is nothing to return to.  If a task wants to exit it
233      * should instead call vTaskDelete( NULL ).
234      *
235      * Artificially force an assert() to be triggered if configASSERT() is
236      * defined, then stop here so application writers can catch the error. */
237     configASSERT( uxCriticalNesting == ~0UL );
238     portDISABLE_INTERRUPTS();
239 
240     for( ; ; )
241     {
242     }
243 }
244 /*-----------------------------------------------------------*/
245 
vPortSVCHandler(void)246 __asm void vPortSVCHandler( void )
247 {
248 /* *INDENT-OFF* */
249     PRESERVE8
250 
251     /* Get the location of the current TCB. */
252     ldr r3, =pxCurrentTCB
253     ldr r1, [ r3 ]
254     ldr r0, [ r1 ]
255     /* Pop the core registers. */
256     ldmia r0!, {r4-r11,r14}
257     msr psp, r0
258     isb
259     mov r0, #0
260     msr basepri, r0
261     bx r14
262 /* *INDENT-ON* */
263 }
264 /*-----------------------------------------------------------*/
265 
prvStartFirstTask(void)266 __asm void prvStartFirstTask( void )
267 {
268 /* *INDENT-OFF* */
269     PRESERVE8
270 
271     /* Use the NVIC offset register to locate the stack. */
272     ldr r0, =0xE000ED08
273     ldr r0, [ r0 ]
274     ldr r0, [ r0 ]
275     /* Set the msp back to the start of the stack. */
276     msr msp, r0
277 
278     /* Clear the bit that indicates the FPU is in use in case the FPU was used
279      * before the scheduler was started - which would otherwise result in the
280      * unnecessary leaving of space in the SVC stack for lazy saving of FPU
281      * registers. */
282     mov r0, #0
283     msr control, r0
284     /* Globally enable interrupts. */
285     cpsie i
286     cpsie f
287     dsb
288     isb
289     /* Call SVC to start the first task. */
290     svc 0
291     nop
292     nop
293 /* *INDENT-ON* */
294 }
295 /*-----------------------------------------------------------*/
296 
prvEnableVFP(void)297 __asm void prvEnableVFP( void )
298 {
299 /* *INDENT-OFF* */
300     PRESERVE8
301 
302     /* The FPU enable bits are in the CPACR. */
303     ldr.w r0, =0xE000ED88
304     ldr r1, [ r0 ]
305 
306     /* Enable CP10 and CP11 coprocessors, then save back. */
307     orr r1, r1, #( 0xf << 20 )
308     str r1, [ r0 ]
309     bx r14
310     nop
311 /* *INDENT-ON* */
312 }
313 /*-----------------------------------------------------------*/
314 
315 /*
316  * See header file for description.
317  */
xPortStartScheduler(void)318 BaseType_t xPortStartScheduler( void )
319 {
320     /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.
321      * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
322     configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY );
323 
324     /* This port can be used on all revisions of the Cortex-M7 core other than
325      * the r0p1 parts.  r0p1 parts should use the port from the
326      * /source/portable/GCC/ARM_CM7/r0p1 directory. */
327     configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
328     configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
329 
330     #if ( configASSERT_DEFINED == 1 )
331     {
332         volatile uint8_t ucOriginalPriority;
333         volatile uint32_t ulImplementedPrioBits = 0;
334         volatile uint8_t * const pucFirstUserPriorityRegister = ( uint8_t * ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
335         volatile uint8_t ucMaxPriorityValue;
336 
337         /* Determine the maximum priority from which ISR safe FreeRTOS API
338          * functions can be called.  ISR safe functions are those that end in
339          * "FromISR".  FreeRTOS maintains separate thread and ISR API functions to
340          * ensure interrupt entry is as fast and simple as possible.
341          *
342          * Save the interrupt priority value that is about to be clobbered. */
343         ucOriginalPriority = *pucFirstUserPriorityRegister;
344 
345         /* Determine the number of priority bits available.  First write to all
346          * possible bits. */
347         *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
348 
349         /* Read the value back to see how many bits stuck. */
350         ucMaxPriorityValue = *pucFirstUserPriorityRegister;
351 
352         /* Use the same mask on the maximum system call priority. */
353         ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
354 
355         /* Check that the maximum system call priority is nonzero after
356          * accounting for the number of priority bits supported by the
357          * hardware. A priority of 0 is invalid because setting the BASEPRI
358          * register to 0 unmasks all interrupts, and interrupts with priority 0
359          * cannot be masked using BASEPRI.
360          * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
361         configASSERT( ucMaxSysCallPriority );
362 
363         /* Check that the bits not implemented in hardware are zero in
364          * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
365         configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
366 
367         /* Calculate the maximum acceptable priority group value for the number
368          * of bits read back. */
369 
370         while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
371         {
372             ulImplementedPrioBits++;
373             ucMaxPriorityValue <<= ( uint8_t ) 0x01;
374         }
375 
376         if( ulImplementedPrioBits == 8 )
377         {
378             /* When the hardware implements 8 priority bits, there is no way for
379              * the software to configure PRIGROUP to not have sub-priorities. As
380              * a result, the least significant bit is always used for sub-priority
381              * and there are 128 preemption priorities and 2 sub-priorities.
382              *
383              * This may cause some confusion in some cases - for example, if
384              * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
385              * priority interrupts will be masked in Critical Sections as those
386              * are at the same preemption priority. This may appear confusing as
387              * 4 is higher (numerically lower) priority than
388              * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
389              * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
390              * to 4, this confusion does not happen and the behaviour remains the same.
391              *
392              * The following assert ensures that the sub-priority bit in the
393              * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
394              * confusion. */
395             configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
396             ulMaxPRIGROUPValue = 0;
397         }
398         else
399         {
400             ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
401         }
402 
403         /* Shift the priority group value back to its position within the AIRCR
404          * register. */
405         ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
406         ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
407 
408         /* Restore the clobbered interrupt priority register to its original
409          * value. */
410         *pucFirstUserPriorityRegister = ucOriginalPriority;
411     }
412     #endif /* configASSERT_DEFINED */
413 
414     /* Make PendSV and SysTick the lowest priority interrupts. */
415     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
416     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
417 
418     /* Start the timer that generates the tick ISR.  Interrupts are disabled
419      * here already. */
420     vPortSetupTimerInterrupt();
421 
422     /* Initialise the critical nesting count ready for the first task. */
423     uxCriticalNesting = 0;
424 
425     /* Ensure the VFP is enabled - it should be anyway. */
426     prvEnableVFP();
427 
428     /* Lazy save always. */
429     *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
430 
431     /* Start the first task. */
432     prvStartFirstTask();
433 
434     /* Should not get here! */
435     return 0;
436 }
437 /*-----------------------------------------------------------*/
438 
vPortEndScheduler(void)439 void vPortEndScheduler( void )
440 {
441     /* Not implemented in ports where there is nothing to return to.
442      * Artificially force an assert. */
443     configASSERT( uxCriticalNesting == 1000UL );
444 }
445 /*-----------------------------------------------------------*/
446 
vPortEnterCritical(void)447 void vPortEnterCritical( void )
448 {
449     portDISABLE_INTERRUPTS();
450     uxCriticalNesting++;
451 
452     /* This is not the interrupt safe version of the enter critical function so
453      * assert() if it is being called from an interrupt context.  Only API
454      * functions that end in "FromISR" can be used in an interrupt.  Only assert if
455      * the critical nesting count is 1 to protect against recursive calls if the
456      * assert function also uses a critical section. */
457     if( uxCriticalNesting == 1 )
458     {
459         configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
460     }
461 }
462 /*-----------------------------------------------------------*/
463 
vPortExitCritical(void)464 void vPortExitCritical( void )
465 {
466     configASSERT( uxCriticalNesting );
467     uxCriticalNesting--;
468 
469     if( uxCriticalNesting == 0 )
470     {
471         portENABLE_INTERRUPTS();
472     }
473 }
474 /*-----------------------------------------------------------*/
475 
xPortPendSVHandler(void)476 __asm void xPortPendSVHandler( void )
477 {
478     extern uxCriticalNesting;
479     extern pxCurrentTCB;
480     extern vTaskSwitchContext;
481 
482 /* *INDENT-OFF* */
483     PRESERVE8
484 
485     mrs r0, psp
486     isb
487     /* Get the location of the current TCB. */
488     ldr r3, =pxCurrentTCB
489     ldr r2, [ r3 ]
490 
491     /* Is the task using the FPU context?  If so, push high vfp registers. */
492     tst r14, #0x10
493     it eq
494     vstmdbeq r0!, {s16-s31}
495 
496     /* Save the core registers. */
497     stmdb r0!, {r4-r11, r14}
498 
499     /* Save the new top of stack into the first member of the TCB. */
500     str r0, [ r2 ]
501 
502     stmdb sp!, {r0, r3}
503     mov r0, #configMAX_SYSCALL_INTERRUPT_PRIORITY
504     msr basepri, r0
505     dsb
506     isb
507     bl vTaskSwitchContext
508     mov r0, #0
509     msr basepri, r0
510     ldmia sp!, {r0, r3}
511 
512     /* The first item in pxCurrentTCB is the task top of stack. */
513     ldr r1, [ r3 ]
514     ldr r0, [ r1 ]
515 
516     /* Pop the core registers. */
517     ldmia r0!, {r4-r11, r14}
518 
519     /* Is the task using the FPU context?  If so, pop the high vfp registers
520      * too. */
521     tst r14, #0x10
522     it eq
523     vldmiaeq r0!, {s16-s31}
524 
525     msr psp, r0
526     isb
527     #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata */
528         #if WORKAROUND_PMU_CM001 == 1
529             push { r14 }
530             pop { pc }
531             nop
532         #endif
533     #endif
534 
535     bx r14
536 /* *INDENT-ON* */
537 }
538 /*-----------------------------------------------------------*/
539 
xPortSysTickHandler(void)540 void xPortSysTickHandler( void )
541 {
542     /* The SysTick runs at the lowest interrupt priority, so when this interrupt
543      * executes all interrupts must be unmasked.  There is therefore no need to
544      * save and then restore the interrupt mask value as its value is already
545      * known - therefore the slightly faster vPortRaiseBASEPRI() function is used
546      * in place of portSET_INTERRUPT_MASK_FROM_ISR(). */
547     vPortRaiseBASEPRI();
548     traceISR_ENTER();
549     {
550         /* Increment the RTOS tick. */
551         if( xTaskIncrementTick() != pdFALSE )
552         {
553             traceISR_EXIT_TO_SCHEDULER();
554 
555             /* A context switch is required.  Context switching is performed in
556              * the PendSV interrupt.  Pend the PendSV interrupt. */
557             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
558         }
559         else
560         {
561             traceISR_EXIT();
562         }
563     }
564 
565     vPortClearBASEPRIFromISR();
566 }
567 /*-----------------------------------------------------------*/
568 
569 #if ( configUSE_TICKLESS_IDLE == 1 )
570 
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)571     __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
572     {
573         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
574         TickType_t xModifiableIdleTime;
575 
576         /* Make sure the SysTick reload value does not overflow the counter. */
577         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
578         {
579             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
580         }
581 
582         /* Enter a critical section but don't use the taskENTER_CRITICAL()
583          * method as that will mask interrupts that should exit sleep mode. */
584         __disable_irq();
585         __dsb( portSY_FULL_READ_WRITE );
586         __isb( portSY_FULL_READ_WRITE );
587 
588         /* If a context switch is pending or a task is waiting for the scheduler
589          * to be unsuspended then abandon the low power entry. */
590         if( eTaskConfirmSleepModeStatus() == eAbortSleep )
591         {
592             /* Re-enable interrupts - see comments above the __disable_irq()
593              * call above. */
594             __enable_irq();
595         }
596         else
597         {
598             /* Stop the SysTick momentarily.  The time the SysTick is stopped for
599              * is accounted for as best it can be, but using the tickless mode will
600              * inevitably result in some tiny drift of the time maintained by the
601              * kernel with respect to calendar time. */
602             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
603 
604             /* Use the SysTick current-value register to determine the number of
605              * SysTick decrements remaining until the next tick interrupt.  If the
606              * current-value register is zero, then there are actually
607              * ulTimerCountsForOneTick decrements remaining, not zero, because the
608              * SysTick requests the interrupt when decrementing from 1 to 0. */
609             ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
610 
611             if( ulSysTickDecrementsLeft == 0 )
612             {
613                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
614             }
615 
616             /* Calculate the reload value required to wait xExpectedIdleTime
617              * tick periods.  -1 is used because this code normally executes part
618              * way through the first tick period.  But if the SysTick IRQ is now
619              * pending, then clear the IRQ, suppressing the first tick, and correct
620              * the reload value to reflect that the second tick period is already
621              * underway.  The expected idle time is always at least two ticks. */
622             ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
623 
624             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
625             {
626                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
627                 ulReloadValue -= ulTimerCountsForOneTick;
628             }
629 
630             if( ulReloadValue > ulStoppedTimerCompensation )
631             {
632                 ulReloadValue -= ulStoppedTimerCompensation;
633             }
634 
635             /* Set the new reload value. */
636             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
637 
638             /* Clear the SysTick count flag and set the count value back to
639              * zero. */
640             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
641 
642             /* Restart SysTick. */
643             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
644 
645             /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
646              * set its parameter to 0 to indicate that its implementation contains
647              * its own wait for interrupt or wait for event instruction, and so wfi
648              * should not be executed again.  However, the original expected idle
649              * time variable must remain unmodified, so a copy is taken. */
650             xModifiableIdleTime = xExpectedIdleTime;
651             configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
652 
653             if( xModifiableIdleTime > 0 )
654             {
655                 __dsb( portSY_FULL_READ_WRITE );
656                 __wfi();
657                 __isb( portSY_FULL_READ_WRITE );
658             }
659 
660             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
661 
662             /* Re-enable interrupts to allow the interrupt that brought the MCU
663              * out of sleep mode to execute immediately.  See comments above
664              * the __disable_irq() call above. */
665             __enable_irq();
666             __dsb( portSY_FULL_READ_WRITE );
667             __isb( portSY_FULL_READ_WRITE );
668 
669             /* Disable interrupts again because the clock is about to be stopped
670              * and interrupts that execute while the clock is stopped will increase
671              * any slippage between the time maintained by the RTOS and calendar
672              * time. */
673             __disable_irq();
674             __dsb( portSY_FULL_READ_WRITE );
675             __isb( portSY_FULL_READ_WRITE );
676 
677             /* Disable the SysTick clock without reading the
678              * portNVIC_SYSTICK_CTRL_REG register to ensure the
679              * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,
680              * the time the SysTick is stopped for is accounted for as best it can
681              * be, but using the tickless mode will inevitably result in some tiny
682              * drift of the time maintained by the kernel with respect to calendar
683              * time*/
684             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
685 
686             /* Determine whether the SysTick has already counted to zero. */
687             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
688             {
689                 uint32_t ulCalculatedLoadValue;
690 
691                 /* The tick interrupt ended the sleep (or is now pending), and
692                  * a new tick period has started.  Reset portNVIC_SYSTICK_LOAD_REG
693                  * with whatever remains of the new tick period. */
694                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
695 
696                 /* Don't allow a tiny value, or values that have somehow
697                  * underflowed because the post sleep hook did something
698                  * that took too long or because the SysTick current-value register
699                  * is zero. */
700                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
701                 {
702                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
703                 }
704 
705                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
706 
707                 /* As the pending tick will be processed as soon as this
708                  * function exits, the tick value maintained by the tick is stepped
709                  * forward by one less than the time spent waiting. */
710                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
711             }
712             else
713             {
714                 /* Something other than the tick interrupt ended the sleep. */
715 
716                 /* Use the SysTick current-value register to determine the
717                  * number of SysTick decrements remaining until the expected idle
718                  * time would have ended. */
719                 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
720                 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
721                 {
722                     /* If the SysTick is not using the core clock, the current-
723                      * value register might still be zero here.  In that case, the
724                      * SysTick didn't load from the reload register, and there are
725                      * ulReloadValue decrements remaining in the expected idle
726                      * time, not zero. */
727                     if( ulSysTickDecrementsLeft == 0 )
728                     {
729                         ulSysTickDecrementsLeft = ulReloadValue;
730                     }
731                 }
732                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
733 
734                 /* Work out how long the sleep lasted rounded to complete tick
735                  * periods (not the ulReload value which accounted for part
736                  * ticks). */
737                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
738 
739                 /* How many complete tick periods passed while the processor
740                  * was waiting? */
741                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
742 
743                 /* The reload value is set to whatever fraction of a single tick
744                  * period remains. */
745                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
746             }
747 
748             /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
749              * then set portNVIC_SYSTICK_LOAD_REG back to its standard value.  If
750              * the SysTick is not using the core clock, temporarily configure it to
751              * use the core clock.  This configuration forces the SysTick to load
752              * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
753              * cycle of the other clock.  Then portNVIC_SYSTICK_LOAD_REG is ready
754              * to receive the standard value immediately. */
755             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
756             portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
757             #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
758             {
759                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
760             }
761             #else
762             {
763                 /* The temporary usage of the core clock has served its purpose,
764                  * as described above.  Resume usage of the other clock. */
765                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
766 
767                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
768                 {
769                     /* The partial tick period already ended.  Be sure the SysTick
770                      * counts it only once. */
771                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
772                 }
773 
774                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
775                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
776             }
777             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
778 
779             /* Step the tick to account for any tick periods that elapsed. */
780             vTaskStepTick( ulCompleteTickPeriods );
781 
782             /* Exit with interrupts enabled. */
783             __enable_irq();
784         }
785     }
786 
787 #endif /* #if configUSE_TICKLESS_IDLE */
788 
789 /*-----------------------------------------------------------*/
790 
791 /*
792  * Setup the SysTick timer to generate the tick interrupts at the required
793  * frequency.
794  */
795 #if ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 )
796 
vPortSetupTimerInterrupt(void)797     __weak void vPortSetupTimerInterrupt( void )
798     {
799         /* Calculate the constants required to configure the tick interrupt. */
800         #if ( configUSE_TICKLESS_IDLE == 1 )
801         {
802             ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
803             xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
804             ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
805         }
806         #endif /* configUSE_TICKLESS_IDLE */
807 
808         /* Stop and clear the SysTick. */
809         portNVIC_SYSTICK_CTRL_REG = 0UL;
810         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
811 
812         /* Configure SysTick to interrupt at the requested rate. */
813         portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
814         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
815     }
816 
817 #endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
818 /*-----------------------------------------------------------*/
819 
vPortGetIPSR(void)820 __asm uint32_t vPortGetIPSR( void )
821 {
822 /* *INDENT-OFF* */
823     PRESERVE8
824 
825     mrs r0, ipsr
826     bx r14
827 /* *INDENT-ON* */
828 }
829 /*-----------------------------------------------------------*/
830 
831 #if ( configASSERT_DEFINED == 1 )
832 
vPortValidateInterruptPriority(void)833     void vPortValidateInterruptPriority( void )
834     {
835         uint32_t ulCurrentInterrupt;
836         uint8_t ucCurrentPriority;
837 
838         /* Obtain the number of the currently executing interrupt. */
839         ulCurrentInterrupt = vPortGetIPSR();
840 
841         /* Is the interrupt number a user defined interrupt? */
842         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
843         {
844             /* Look up the interrupt's priority. */
845             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
846 
847             /* The following assertion will fail if a service routine (ISR) for
848              * an interrupt that has been assigned a priority above
849              * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
850              * function.  ISR safe FreeRTOS API functions must *only* be called
851              * from interrupts that have been assigned a priority at or below
852              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
853              *
854              * Numerically low interrupt priority numbers represent logically high
855              * interrupt priorities, therefore the priority of the interrupt must
856              * be set to a value equal to or numerically *higher* than
857              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
858              *
859              * Interrupts that use the FreeRTOS API must not be left at their
860              * default priority of zero as that is the highest possible priority,
861              * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
862              * and therefore also guaranteed to be invalid.
863              *
864              * FreeRTOS maintains separate thread and ISR API functions to ensure
865              * interrupt entry is as fast and simple as possible.
866              *
867              * The following links provide detailed information:
868              * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
869              * https://www.FreeRTOS.org/FAQHelp.html */
870             configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
871         }
872 
873         /* Priority grouping:  The interrupt controller (NVIC) allows the bits
874          * that define each interrupt's priority to be split between bits that
875          * define the interrupt's pre-emption priority bits and bits that define
876          * the interrupt's sub-priority.  For simplicity all bits must be defined
877          * to be pre-emption priority bits.  The following assertion will fail if
878          * this is not the case (if some bits represent a sub-priority).
879          *
880          * If the application only uses CMSIS libraries for interrupt
881          * configuration then the correct setting can be achieved on all Cortex-M
882          * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
883          * scheduler.  Note however that some vendor specific peripheral libraries
884          * assume a non-zero priority group setting, in which cases using a value
885          * of zero will result in unpredictable behaviour. */
886         configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
887     }
888 
889 #endif /* configASSERT_DEFINED */
890