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 __VFP_FP__
38     #error This port can only be used when the project options are configured to enable hardware floating point support.
39 #endif
40 
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 )
54 
55 /* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7
56  * r0p1 port. */
57 #define portCPUID                             ( *( ( volatile uint32_t * ) 0xE000ed00 ) )
58 #define portCORTEX_M7_r0p1_ID                 ( 0x410FC271UL )
59 #define portCORTEX_M7_r0p0_ID                 ( 0x410FC270UL )
60 
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 )
64 
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 )
74 
75 /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
76 #define portVECTACTIVE_MASK                   ( 0xFFUL )
77 
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 )
81 
82 /* Constants required to set up the initial stack. */
83 #define portINITIAL_XPSR                      ( 0x01000000 )
84 #define portINITIAL_EXC_RETURN                ( 0xfffffffd )
85 
86 /* The systick is a 24-bit counter. */
87 #define portMAX_24_BIT_NUMBER                 ( 0xffffffUL )
88 
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 )
92 
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
95  * calculations. */
96 #define portMISSED_COUNTS_FACTOR              ( 94UL )
97 
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 )
105 #else
106     /* Select the option to clock SysTick not at the same frequency as the core. */
107     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( 0 )
108 #endif
109 
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
112  * debugger. */
113 #ifdef configTASK_RETURN_ADDRESS
114     #define portTASK_RETURN_ADDRESS    configTASK_RETURN_ADDRESS
115 #else
116     #define portTASK_RETURN_ADDRESS    prvTaskExitError
117 #endif
118 
119 /*
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.
123  */
124 void vPortSetupTimerInterrupt( void );
125 
126 /*
127  * Exception handlers.
128  */
129 void xPortPendSVHandler( void ) __attribute__( ( naked ) );
130 void xPortSysTickHandler( void );
131 void vPortSVCHandler( void ) __attribute__( ( naked ) );
132 
133 /*
134  * Start first task is a separate function so it can be tested in isolation.
135  */
136 static void prvPortStartFirstTask( void ) __attribute__( ( naked ) );
137 
138 /*
139  * Function to enable the VFP.
140  */
141 static void vPortEnableVFP( void ) __attribute__( ( naked ) );
142 
143 /*
144  * Used to catch tasks that attempt to return from their implementing function.
145  */
146 static void prvTaskExitError( void );
147 
148 /*-----------------------------------------------------------*/
149 
150 /* Each task maintains its own interrupt status in the critical nesting
151  * variable. */
152 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
153 
154 /*
155  * The number of SysTick increments that make up one tick period.
156  */
157 #if ( configUSE_TICKLESS_IDLE == 1 )
158     static uint32_t ulTimerCountsForOneTick = 0;
159 #endif /* configUSE_TICKLESS_IDLE */
160 
161 /*
162  * The maximum number of tick periods that can be suppressed is limited by the
163  * 24 bit resolution of the SysTick timer.
164  */
165 #if ( configUSE_TICKLESS_IDLE == 1 )
166     static uint32_t xMaximumPossibleSuppressedTicks = 0;
167 #endif /* configUSE_TICKLESS_IDLE */
168 
169 /*
170  * Compensate for the CPU cycles that pass while the SysTick is stopped (low
171  * power functionality only.
172  */
173 #if ( configUSE_TICKLESS_IDLE == 1 )
174     static uint32_t ulStoppedTimerCompensation = 0;
175 #endif /* configUSE_TICKLESS_IDLE */
176 
177 /*
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.
181  */
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 */
187 
188 /*-----------------------------------------------------------*/
189 
190 /*
191  * See header file for description.
192  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)193 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
194                                      TaskFunction_t pxCode,
195                                      void * pvParameters )
196 {
197     /* Simulate the stack frame as it would be created by a context switch
198      * interrupt. */
199 
200     /* Offset added to account for the way the MCU uses the stack on entry/exit
201      * of interrupts, and to ensure alignment. */
202     pxTopOfStack--;
203 
204     *pxTopOfStack = portINITIAL_XPSR;                                    /* xPSR */
205     pxTopOfStack--;
206     *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
207     pxTopOfStack--;
208     *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS;             /* LR */
209 
210     /* Save code space by skipping register initialisation. */
211     pxTopOfStack -= 5;                            /* R12, R3, R2 and R1. */
212     *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
213 
214     /* A save method is being used that requires each task to maintain its
215      * own exec return value. */
216     pxTopOfStack--;
217     *pxTopOfStack = portINITIAL_EXC_RETURN;
218 
219     pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
220 
221     return pxTopOfStack;
222 }
223 /*-----------------------------------------------------------*/
224 
prvTaskExitError(void)225 static void prvTaskExitError( void )
226 {
227     volatile uint32_t ulDummy = 0;
228 
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 ).
232      *
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();
237 
238     while( ulDummy == 0 )
239     {
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
246          * after it. */
247     }
248 }
249 /*-----------------------------------------------------------*/
250 
vPortSVCHandler(void)251 void vPortSVCHandler( void )
252 {
253     __asm volatile (
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. */
259         "   isb                             \n"
260         "   mov r0, #0                      \n"
261         "   msr basepri, r0                 \n"
262         "   bx r14                          \n"
263         "                                   \n"
264         "   .align 4                        \n"
265         "pxCurrentTCBConst2: .word pxCurrentTCB             \n"
266         );
267 }
268 /*-----------------------------------------------------------*/
269 
prvPortStartFirstTask(void)270 static void prvPortStartFirstTask( void )
271 {
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. */
276     __asm volatile (
277         " ldr r0, =0xE000ED08   \n" /* Use the NVIC offset register to locate the stack. */
278         " ldr r0, [r0]          \n"
279         " ldr r0, [r0]          \n"
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. */
284         " cpsie f               \n"
285         " dsb                   \n"
286         " isb                   \n"
287         " svc 0                 \n" /* System call to start first task. */
288         " nop                   \n"
289         " .ltorg                \n"
290         );
291 }
292 /*-----------------------------------------------------------*/
293 
294 /*
295  * See header file for description.
296  */
xPortStartScheduler(void)297 BaseType_t xPortStartScheduler( void )
298 {
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 );
304 
305     #if ( configASSERT_DEFINED == 1 )
306     {
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;
311 
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.
316          *
317          * Save the interrupt priority value that is about to be clobbered. */
318         ucOriginalPriority = *pucFirstUserPriorityRegister;
319 
320         /* Determine the number of priority bits available.  First write to all
321          * possible bits. */
322         *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
323 
324         /* Read the value back to see how many bits stuck. */
325         ucMaxPriorityValue = *pucFirstUserPriorityRegister;
326 
327         /* Use the same mask on the maximum system call priority. */
328         ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
329 
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 );
337 
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 );
341 
342         /* Calculate the maximum acceptable priority group value for the number
343          * of bits read back. */
344 
345         while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
346         {
347             ulImplementedPrioBits++;
348             ucMaxPriorityValue <<= ( uint8_t ) 0x01;
349         }
350 
351         if( ulImplementedPrioBits == 8 )
352         {
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.
357             *
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.
366             *
367             * The following assert ensures that the sub-priority bit in the
368             * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
369             * confusion. */
370             configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
371             ulMaxPRIGROUPValue = 0;
372         }
373         else
374         {
375             ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
376         }
377 
378         /* Shift the priority group value back to its position within the AIRCR
379          * register. */
380         ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
381         ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
382 
383         /* Restore the clobbered interrupt priority register to its original
384          * value. */
385         *pucFirstUserPriorityRegister = ucOriginalPriority;
386     }
387     #endif /* configASSERT_DEFINED */
388 
389     /* Make PendSV and SysTick the lowest priority interrupts. */
390     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
391     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
392 
393     /* Start the timer that generates the tick ISR.  Interrupts are disabled
394      * here already. */
395     vPortSetupTimerInterrupt();
396 
397     /* Initialise the critical nesting count ready for the first task. */
398     uxCriticalNesting = 0;
399 
400     /* Ensure the VFP is enabled - it should be anyway. */
401     vPortEnableVFP();
402 
403     /* Lazy save always. */
404     *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
405 
406     /* Start the first task. */
407     prvPortStartFirstTask();
408 
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
414      * symbol. */
415     vTaskSwitchContext();
416     prvTaskExitError();
417 
418     /* Should not get here! */
419     return 0;
420 }
421 /*-----------------------------------------------------------*/
422 
vPortEndScheduler(void)423 void vPortEndScheduler( void )
424 {
425     /* Not implemented in ports where there is nothing to return to.
426      * Artificially force an assert. */
427     configASSERT( uxCriticalNesting == 1000UL );
428 }
429 /*-----------------------------------------------------------*/
430 
vPortEnterCritical(void)431 void vPortEnterCritical( void )
432 {
433     portDISABLE_INTERRUPTS();
434     uxCriticalNesting++;
435 
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 )
442     {
443         configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
444     }
445 }
446 /*-----------------------------------------------------------*/
447 
vPortExitCritical(void)448 void vPortExitCritical( void )
449 {
450     configASSERT( uxCriticalNesting );
451     uxCriticalNesting--;
452 
453     if( uxCriticalNesting == 0 )
454     {
455         portENABLE_INTERRUPTS();
456     }
457 }
458 /*-----------------------------------------------------------*/
459 
xPortPendSVHandler(void)460 void xPortPendSVHandler( void )
461 {
462     /* This is a naked function. */
463 
464     __asm volatile
465     (
466         "   mrs r0, psp                         \n"
467         "   isb                                 \n"
468         "                                       \n"
469         "   ldr r3, pxCurrentTCBConst           \n" /* Get the location of the current TCB. */
470         "   ldr r2, [r3]                        \n"
471         "                                       \n"
472         "   tst r14, #0x10                      \n" /* Is the task using the FPU context?  If so, push high vfp registers. */
473         "   it eq                               \n"
474         "   vstmdbeq r0!, {s16-s31}             \n"
475         "                                       \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. */
478         "                                       \n"
479         "   stmdb sp!, {r0, r3}                 \n"
480         "   mov r0, %0                          \n"
481         "   msr basepri, r0                     \n"
482         "   dsb                                 \n"
483         "   isb                                 \n"
484         "   bl vTaskSwitchContext               \n"
485         "   mov r0, #0                          \n"
486         "   msr basepri, r0                     \n"
487         "   ldmia sp!, {r0, r3}                 \n"
488         "                                       \n"
489         "   ldr r1, [r3]                        \n" /* The first item in pxCurrentTCB is the task top of stack. */
490         "   ldr r0, [r1]                        \n"
491         "                                       \n"
492         "   ldmia r0!, {r4-r11, r14}            \n" /* Pop the core registers. */
493         "                                       \n"
494         "   tst r14, #0x10                      \n" /* Is the task using the FPU context?  If so, pop the high vfp registers too. */
495         "   it eq                               \n"
496         "   vldmiaeq r0!, {s16-s31}             \n"
497         "                                       \n"
498         "   msr psp, r0                         \n"
499         "   isb                                 \n"
500         "                                       \n"
501         #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */
502             #if WORKAROUND_PMU_CM001 == 1
503                 "           push { r14 }                \n"
504                 "           pop { pc }                  \n"
505             #endif
506         #endif
507         "                                       \n"
508         "   bx r14                              \n"
509         "                                       \n"
510         "   .align 4                            \n"
511         "pxCurrentTCBConst: .word pxCurrentTCB  \n"
512         ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
513     );
514 }
515 /*-----------------------------------------------------------*/
516 
xPortSysTickHandler(void)517 void xPortSysTickHandler( void )
518 {
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
522      * known. */
523     portDISABLE_INTERRUPTS();
524     {
525         /* Increment the RTOS tick. */
526         if( xTaskIncrementTick() != pdFALSE )
527         {
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;
531         }
532     }
533     portENABLE_INTERRUPTS();
534 }
535 /*-----------------------------------------------------------*/
536 
537 #if ( configUSE_TICKLESS_IDLE == 1 )
538 
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)539     __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
540     {
541         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
542         TickType_t xModifiableIdleTime;
543 
544         /* Make sure the SysTick reload value does not overflow the counter. */
545         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
546         {
547             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
548         }
549 
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" );
555 
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 )
559         {
560             /* Re-enable interrupts - see comments above the cpsid instruction
561              * above. */
562             __asm volatile ( "cpsie i" ::: "memory" );
563         }
564         else
565         {
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 );
571 
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;
578 
579             if( ulSysTickDecrementsLeft == 0 )
580             {
581                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
582             }
583 
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 ) );
591 
592             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
593             {
594                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
595                 ulReloadValue -= ulTimerCountsForOneTick;
596             }
597 
598             if( ulReloadValue > ulStoppedTimerCompensation )
599             {
600                 ulReloadValue -= ulStoppedTimerCompensation;
601             }
602 
603             /* Set the new reload value. */
604             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
605 
606             /* Clear the SysTick count flag and set the count value back to
607              * zero. */
608             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
609 
610             /* Restart SysTick. */
611             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
612 
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 );
620 
621             if( xModifiableIdleTime > 0 )
622             {
623                 __asm volatile ( "dsb" ::: "memory" );
624                 __asm volatile ( "wfi" );
625                 __asm volatile ( "isb" );
626             }
627 
628             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
629 
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" );
636 
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
640              * time. */
641             __asm volatile ( "cpsid i" ::: "memory" );
642             __asm volatile ( "dsb" );
643             __asm volatile ( "isb" );
644 
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
651              * time*/
652             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
653 
654             /* Determine whether the SysTick has already counted to zero. */
655             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
656             {
657                 uint32_t ulCalculatedLoadValue;
658 
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 );
663 
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
667                  * is zero. */
668                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
669                 {
670                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
671                 }
672 
673                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
674 
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;
679             }
680             else
681             {
682                 /* Something other than the tick interrupt ended the sleep. */
683 
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 )
689                 {
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
694                      * time, not zero. */
695                     if( ulSysTickDecrementsLeft == 0 )
696                     {
697                         ulSysTickDecrementsLeft = ulReloadValue;
698                     }
699                 }
700                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
701 
702                 /* Work out how long the sleep lasted rounded to complete tick
703                  * periods (not the ulReload value which accounted for part
704                  * ticks). */
705                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
706 
707                 /* How many complete tick periods passed while the processor
708                  * was waiting? */
709                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
710 
711                 /* The reload value is set to whatever fraction of a single tick
712                  * period remains. */
713                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
714             }
715 
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 )
726             {
727                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
728             }
729             #else
730             {
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;
734 
735                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
736                 {
737                     /* The partial tick period already ended.  Be sure the SysTick
738                      * counts it only once. */
739                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
740                 }
741 
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;
744             }
745             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
746 
747             /* Step the tick to account for any tick periods that elapsed. */
748             vTaskStepTick( ulCompleteTickPeriods );
749 
750             /* Exit with interrupts enabled. */
751             __asm volatile ( "cpsie i" ::: "memory" );
752         }
753     }
754 
755 #endif /* #if configUSE_TICKLESS_IDLE */
756 /*-----------------------------------------------------------*/
757 
758 /*
759  * Setup the systick timer to generate the tick interrupts at the required
760  * frequency.
761  */
vPortSetupTimerInterrupt(void)762 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
763 {
764     /* Calculate the constants required to configure the tick interrupt. */
765     #if ( configUSE_TICKLESS_IDLE == 1 )
766     {
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 );
770     }
771     #endif /* configUSE_TICKLESS_IDLE */
772 
773     /* Stop and clear the SysTick. */
774     portNVIC_SYSTICK_CTRL_REG = 0UL;
775     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
776 
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 );
780 }
781 /*-----------------------------------------------------------*/
782 
783 /* This is a naked function. */
vPortEnableVFP(void)784 static void vPortEnableVFP( void )
785 {
786     __asm volatile
787     (
788         "   ldr.w r0, =0xE000ED88       \n" /* The FPU enable bits are in the CPACR. */
789         "   ldr r1, [r0]                \n"
790         "                               \n"
791         "   orr r1, r1, #( 0xf << 20 )  \n" /* Enable CP10 and CP11 coprocessors, then save back. */
792         "   str r1, [r0]                \n"
793         "   bx r14                      \n"
794         "   .ltorg                      \n"
795     );
796 }
797 /*-----------------------------------------------------------*/
798 
799 #if ( configASSERT_DEFINED == 1 )
800 
vPortValidateInterruptPriority(void)801     void vPortValidateInterruptPriority( void )
802     {
803         uint32_t ulCurrentInterrupt;
804         uint8_t ucCurrentPriority;
805 
806         /* Obtain the number of the currently executing interrupt. */
807         __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
808 
809         /* Is the interrupt number a user defined interrupt? */
810         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
811         {
812             /* Look up the interrupt's priority. */
813             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
814 
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.
821              *
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.
826              *
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.
831              *
832              * FreeRTOS maintains separate thread and ISR API functions to ensure
833              * interrupt entry is as fast and simple as possible.
834              *
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 );
839         }
840 
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).
847          *
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 );
855     }
856 
857 #endif /* configASSERT_DEFINED */
858