xref: /Kernel-v10.6.2/portable/RVDS/ARM_CM4F/port.c (revision ef7b253b56c9788077f5ecd6c9deb4021923d646)
1 /*
2  * FreeRTOS Kernel V10.6.2
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     {
549         /* Increment the RTOS tick. */
550         if( xTaskIncrementTick() != pdFALSE )
551         {
552             /* A context switch is required.  Context switching is performed in
553              * the PendSV interrupt.  Pend the PendSV interrupt. */
554             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
555         }
556     }
557 
558     vPortClearBASEPRIFromISR();
559 }
560 /*-----------------------------------------------------------*/
561 
562 #if ( configUSE_TICKLESS_IDLE == 1 )
563 
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)564     __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
565     {
566         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
567         TickType_t xModifiableIdleTime;
568 
569         /* Make sure the SysTick reload value does not overflow the counter. */
570         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
571         {
572             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
573         }
574 
575         /* Enter a critical section but don't use the taskENTER_CRITICAL()
576          * method as that will mask interrupts that should exit sleep mode. */
577         __disable_irq();
578         __dsb( portSY_FULL_READ_WRITE );
579         __isb( portSY_FULL_READ_WRITE );
580 
581         /* If a context switch is pending or a task is waiting for the scheduler
582          * to be unsuspended then abandon the low power entry. */
583         if( eTaskConfirmSleepModeStatus() == eAbortSleep )
584         {
585             /* Re-enable interrupts - see comments above the __disable_irq()
586              * call above. */
587             __enable_irq();
588         }
589         else
590         {
591             /* Stop the SysTick momentarily.  The time the SysTick is stopped for
592              * is accounted for as best it can be, but using the tickless mode will
593              * inevitably result in some tiny drift of the time maintained by the
594              * kernel with respect to calendar time. */
595             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
596 
597             /* Use the SysTick current-value register to determine the number of
598              * SysTick decrements remaining until the next tick interrupt.  If the
599              * current-value register is zero, then there are actually
600              * ulTimerCountsForOneTick decrements remaining, not zero, because the
601              * SysTick requests the interrupt when decrementing from 1 to 0. */
602             ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
603 
604             if( ulSysTickDecrementsLeft == 0 )
605             {
606                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
607             }
608 
609             /* Calculate the reload value required to wait xExpectedIdleTime
610              * tick periods.  -1 is used because this code normally executes part
611              * way through the first tick period.  But if the SysTick IRQ is now
612              * pending, then clear the IRQ, suppressing the first tick, and correct
613              * the reload value to reflect that the second tick period is already
614              * underway.  The expected idle time is always at least two ticks. */
615             ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
616 
617             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
618             {
619                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
620                 ulReloadValue -= ulTimerCountsForOneTick;
621             }
622 
623             if( ulReloadValue > ulStoppedTimerCompensation )
624             {
625                 ulReloadValue -= ulStoppedTimerCompensation;
626             }
627 
628             /* Set the new reload value. */
629             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
630 
631             /* Clear the SysTick count flag and set the count value back to
632              * zero. */
633             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
634 
635             /* Restart SysTick. */
636             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
637 
638             /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
639              * set its parameter to 0 to indicate that its implementation contains
640              * its own wait for interrupt or wait for event instruction, and so wfi
641              * should not be executed again.  However, the original expected idle
642              * time variable must remain unmodified, so a copy is taken. */
643             xModifiableIdleTime = xExpectedIdleTime;
644             configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
645 
646             if( xModifiableIdleTime > 0 )
647             {
648                 __dsb( portSY_FULL_READ_WRITE );
649                 __wfi();
650                 __isb( portSY_FULL_READ_WRITE );
651             }
652 
653             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
654 
655             /* Re-enable interrupts to allow the interrupt that brought the MCU
656              * out of sleep mode to execute immediately.  See comments above
657              * the __disable_irq() call above. */
658             __enable_irq();
659             __dsb( portSY_FULL_READ_WRITE );
660             __isb( portSY_FULL_READ_WRITE );
661 
662             /* Disable interrupts again because the clock is about to be stopped
663              * and interrupts that execute while the clock is stopped will increase
664              * any slippage between the time maintained by the RTOS and calendar
665              * time. */
666             __disable_irq();
667             __dsb( portSY_FULL_READ_WRITE );
668             __isb( portSY_FULL_READ_WRITE );
669 
670             /* Disable the SysTick clock without reading the
671              * portNVIC_SYSTICK_CTRL_REG register to ensure the
672              * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,
673              * the time the SysTick is stopped for is accounted for as best it can
674              * be, but using the tickless mode will inevitably result in some tiny
675              * drift of the time maintained by the kernel with respect to calendar
676              * time*/
677             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
678 
679             /* Determine whether the SysTick has already counted to zero. */
680             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
681             {
682                 uint32_t ulCalculatedLoadValue;
683 
684                 /* The tick interrupt ended the sleep (or is now pending), and
685                  * a new tick period has started.  Reset portNVIC_SYSTICK_LOAD_REG
686                  * with whatever remains of the new tick period. */
687                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
688 
689                 /* Don't allow a tiny value, or values that have somehow
690                  * underflowed because the post sleep hook did something
691                  * that took too long or because the SysTick current-value register
692                  * is zero. */
693                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
694                 {
695                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
696                 }
697 
698                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
699 
700                 /* As the pending tick will be processed as soon as this
701                  * function exits, the tick value maintained by the tick is stepped
702                  * forward by one less than the time spent waiting. */
703                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
704             }
705             else
706             {
707                 /* Something other than the tick interrupt ended the sleep. */
708 
709                 /* Use the SysTick current-value register to determine the
710                  * number of SysTick decrements remaining until the expected idle
711                  * time would have ended. */
712                 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
713                 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
714                 {
715                     /* If the SysTick is not using the core clock, the current-
716                      * value register might still be zero here.  In that case, the
717                      * SysTick didn't load from the reload register, and there are
718                      * ulReloadValue decrements remaining in the expected idle
719                      * time, not zero. */
720                     if( ulSysTickDecrementsLeft == 0 )
721                     {
722                         ulSysTickDecrementsLeft = ulReloadValue;
723                     }
724                 }
725                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
726 
727                 /* Work out how long the sleep lasted rounded to complete tick
728                  * periods (not the ulReload value which accounted for part
729                  * ticks). */
730                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
731 
732                 /* How many complete tick periods passed while the processor
733                  * was waiting? */
734                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
735 
736                 /* The reload value is set to whatever fraction of a single tick
737                  * period remains. */
738                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
739             }
740 
741             /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
742              * then set portNVIC_SYSTICK_LOAD_REG back to its standard value.  If
743              * the SysTick is not using the core clock, temporarily configure it to
744              * use the core clock.  This configuration forces the SysTick to load
745              * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
746              * cycle of the other clock.  Then portNVIC_SYSTICK_LOAD_REG is ready
747              * to receive the standard value immediately. */
748             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
749             portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
750             #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
751             {
752                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
753             }
754             #else
755             {
756                 /* The temporary usage of the core clock has served its purpose,
757                  * as described above.  Resume usage of the other clock. */
758                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
759 
760                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
761                 {
762                     /* The partial tick period already ended.  Be sure the SysTick
763                      * counts it only once. */
764                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
765                 }
766 
767                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
768                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
769             }
770             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
771 
772             /* Step the tick to account for any tick periods that elapsed. */
773             vTaskStepTick( ulCompleteTickPeriods );
774 
775             /* Exit with interrupts enabled. */
776             __enable_irq();
777         }
778     }
779 
780 #endif /* #if configUSE_TICKLESS_IDLE */
781 
782 /*-----------------------------------------------------------*/
783 
784 /*
785  * Setup the SysTick timer to generate the tick interrupts at the required
786  * frequency.
787  */
788 #if ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 )
789 
vPortSetupTimerInterrupt(void)790     __weak void vPortSetupTimerInterrupt( void )
791     {
792         /* Calculate the constants required to configure the tick interrupt. */
793         #if ( configUSE_TICKLESS_IDLE == 1 )
794         {
795             ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
796             xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
797             ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
798         }
799         #endif /* configUSE_TICKLESS_IDLE */
800 
801         /* Stop and clear the SysTick. */
802         portNVIC_SYSTICK_CTRL_REG = 0UL;
803         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
804 
805         /* Configure SysTick to interrupt at the requested rate. */
806         portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
807         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
808     }
809 
810 #endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
811 /*-----------------------------------------------------------*/
812 
vPortGetIPSR(void)813 __asm uint32_t vPortGetIPSR( void )
814 {
815 /* *INDENT-OFF* */
816     PRESERVE8
817 
818     mrs r0, ipsr
819     bx r14
820 /* *INDENT-ON* */
821 }
822 /*-----------------------------------------------------------*/
823 
824 #if ( configASSERT_DEFINED == 1 )
825 
vPortValidateInterruptPriority(void)826     void vPortValidateInterruptPriority( void )
827     {
828         uint32_t ulCurrentInterrupt;
829         uint8_t ucCurrentPriority;
830 
831         /* Obtain the number of the currently executing interrupt. */
832         ulCurrentInterrupt = vPortGetIPSR();
833 
834         /* Is the interrupt number a user defined interrupt? */
835         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
836         {
837             /* Look up the interrupt's priority. */
838             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
839 
840             /* The following assertion will fail if a service routine (ISR) for
841              * an interrupt that has been assigned a priority above
842              * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
843              * function.  ISR safe FreeRTOS API functions must *only* be called
844              * from interrupts that have been assigned a priority at or below
845              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
846              *
847              * Numerically low interrupt priority numbers represent logically high
848              * interrupt priorities, therefore the priority of the interrupt must
849              * be set to a value equal to or numerically *higher* than
850              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
851              *
852              * Interrupts that use the FreeRTOS API must not be left at their
853              * default priority of zero as that is the highest possible priority,
854              * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
855              * and therefore also guaranteed to be invalid.
856              *
857              * FreeRTOS maintains separate thread and ISR API functions to ensure
858              * interrupt entry is as fast and simple as possible.
859              *
860              * The following links provide detailed information:
861              * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
862              * https://www.FreeRTOS.org/FAQHelp.html */
863             configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
864         }
865 
866         /* Priority grouping:  The interrupt controller (NVIC) allows the bits
867          * that define each interrupt's priority to be split between bits that
868          * define the interrupt's pre-emption priority bits and bits that define
869          * the interrupt's sub-priority.  For simplicity all bits must be defined
870          * to be pre-emption priority bits.  The following assertion will fail if
871          * this is not the case (if some bits represent a sub-priority).
872          *
873          * If the application only uses CMSIS libraries for interrupt
874          * configuration then the correct setting can be achieved on all Cortex-M
875          * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
876          * scheduler.  Note however that some vendor specific peripheral libraries
877          * assume a non-zero priority group setting, in which cases using a value
878          * of zero will result in unpredictable behaviour. */
879         configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
880     }
881 
882 #endif /* configASSERT_DEFINED */
883