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 CM3 port.
31 *----------------------------------------------------------*/
32 
33 /* Scheduler includes. */
34 #include "FreeRTOS.h"
35 #include "task.h"
36 
37 /* Prototype of all Interrupt Service Routines (ISRs). */
38 typedef void ( * portISR_t )( void );
39 
40 /* Constants required to manipulate the core.  Registers first... */
41 #define portNVIC_SYSTICK_CTRL_REG             ( *( ( volatile uint32_t * ) 0xe000e010 ) )
42 #define portNVIC_SYSTICK_LOAD_REG             ( *( ( volatile uint32_t * ) 0xe000e014 ) )
43 #define portNVIC_SYSTICK_CURRENT_VALUE_REG    ( *( ( volatile uint32_t * ) 0xe000e018 ) )
44 #define portNVIC_SHPR2_REG                    ( *( ( volatile uint32_t * ) 0xe000ed1c ) )
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 #define portMIN_INTERRUPT_PRIORITY            ( 255UL )
56 #define portNVIC_PENDSV_PRI                   ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
57 #define portNVIC_SYSTICK_PRI                  ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
58 
59 /* Constants used to check the installation of the FreeRTOS interrupt handlers. */
60 #define portSCB_VTOR_REG                      ( *( ( portISR_t ** ) 0xE000ED08 ) )
61 #define portVECTOR_INDEX_SVC                  ( 11 )
62 #define portVECTOR_INDEX_PENDSV               ( 14 )
63 
64 /* Constants required to check the validity of an interrupt priority. */
65 #define portFIRST_USER_INTERRUPT_NUMBER       ( 16 )
66 #define portNVIC_IP_REGISTERS_OFFSET_16       ( 0xE000E3F0 )
67 #define portAIRCR_REG                         ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
68 #define portMAX_8_BIT_VALUE                   ( ( uint8_t ) 0xff )
69 #define portTOP_BIT_OF_BYTE                   ( ( uint8_t ) 0x80 )
70 #define portMAX_PRIGROUP_BITS                 ( ( uint8_t ) 7 )
71 #define portPRIORITY_GROUP_MASK               ( 0x07UL << 8UL )
72 #define portPRIGROUP_SHIFT                    ( 8UL )
73 
74 /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
75 #define portVECTACTIVE_MASK                   ( 0xFFUL )
76 
77 /* Constants required to set up the initial stack. */
78 #define portINITIAL_XPSR                      ( 0x01000000UL )
79 
80 /* The systick is a 24-bit counter. */
81 #define portMAX_24_BIT_NUMBER                 ( 0xffffffUL )
82 
83 /* A fiddle factor to estimate the number of SysTick counts that would have
84  * occurred while the SysTick counter is stopped during tickless idle
85  * calculations. */
86 #define portMISSED_COUNTS_FACTOR              ( 94UL )
87 
88 /* For strict compliance with the Cortex-M spec the task start address should
89  * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
90 #define portSTART_ADDRESS_MASK                ( ( StackType_t ) 0xfffffffeUL )
91 
92 /* Let the user override the default SysTick clock rate.  If defined by the
93  * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
94  * configuration register. */
95 #ifndef configSYSTICK_CLOCK_HZ
96     #define configSYSTICK_CLOCK_HZ             ( configCPU_CLOCK_HZ )
97     /* Ensure the SysTick is clocked at the same frequency as the core. */
98     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( portNVIC_SYSTICK_CLK_BIT )
99 #else
100     /* Select the option to clock SysTick not at the same frequency as the core. */
101     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( 0 )
102 #endif
103 
104 /* Let the user override the pre-loading of the initial LR with the address of
105  * prvTaskExitError() in case it messes up unwinding of the stack in the
106  * debugger. */
107 #ifdef configTASK_RETURN_ADDRESS
108     #define portTASK_RETURN_ADDRESS    configTASK_RETURN_ADDRESS
109 #else
110     #define portTASK_RETURN_ADDRESS    prvTaskExitError
111 #endif
112 
113 /*
114  * Setup the timer to generate the tick interrupts.  The implementation in this
115  * file is weak to allow application writers to change the timer used to
116  * generate the tick interrupt.
117  */
118 void vPortSetupTimerInterrupt( void );
119 
120 /*
121  * Exception handlers.
122  */
123 void xPortPendSVHandler( void ) __attribute__( ( naked ) );
124 void xPortSysTickHandler( void );
125 void vPortSVCHandler( void ) __attribute__( ( naked ) );
126 
127 /*
128  * Start first task is a separate function so it can be tested in isolation.
129  */
130 static void prvPortStartFirstTask( void ) __attribute__( ( naked ) );
131 
132 /*
133  * Used to catch tasks that attempt to return from their implementing function.
134  */
135 static void prvTaskExitError( void );
136 
137 /*-----------------------------------------------------------*/
138 
139 /* Each task maintains its own interrupt status in the critical nesting
140  * variable. */
141 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
142 
143 /*
144  * The number of SysTick increments that make up one tick period.
145  */
146 #if ( configUSE_TICKLESS_IDLE == 1 )
147     static uint32_t ulTimerCountsForOneTick = 0;
148 #endif /* configUSE_TICKLESS_IDLE */
149 
150 /*
151  * The maximum number of tick periods that can be suppressed is limited by the
152  * 24 bit resolution of the SysTick timer.
153  */
154 #if ( configUSE_TICKLESS_IDLE == 1 )
155     static uint32_t xMaximumPossibleSuppressedTicks = 0;
156 #endif /* configUSE_TICKLESS_IDLE */
157 
158 /*
159  * Compensate for the CPU cycles that pass while the SysTick is stopped (low
160  * power functionality only.
161  */
162 #if ( configUSE_TICKLESS_IDLE == 1 )
163     static uint32_t ulStoppedTimerCompensation = 0;
164 #endif /* configUSE_TICKLESS_IDLE */
165 
166 /*
167  * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
168  * FreeRTOS API functions are not called from interrupts that have been assigned
169  * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
170  */
171 #if ( configASSERT_DEFINED == 1 )
172     static uint8_t ucMaxSysCallPriority = 0;
173     static uint32_t ulMaxPRIGROUPValue = 0;
174     static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
175 #endif /* configASSERT_DEFINED */
176 
177 /*-----------------------------------------------------------*/
178 
179 /*
180  * See header file for description.
181  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)182 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
183                                      TaskFunction_t pxCode,
184                                      void * pvParameters )
185 {
186     /* Simulate the stack frame as it would be created by a context switch
187      * interrupt. */
188     pxTopOfStack--;                                                      /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
189     *pxTopOfStack = portINITIAL_XPSR;                                    /* xPSR */
190     pxTopOfStack--;
191     *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
192     pxTopOfStack--;
193     *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS;             /* LR */
194     pxTopOfStack -= 5;                                                   /* R12, R3, R2 and R1. */
195     *pxTopOfStack = ( StackType_t ) pvParameters;                        /* R0 */
196     pxTopOfStack -= 8;                                                   /* R11, R10, R9, R8, R7, R6, R5 and R4. */
197 
198     return pxTopOfStack;
199 }
200 /*-----------------------------------------------------------*/
201 
prvTaskExitError(void)202 static void prvTaskExitError( void )
203 {
204     volatile uint32_t ulDummy = 0UL;
205 
206     /* A function that implements a task must not exit or attempt to return to
207      * its caller as there is nothing to return to.  If a task wants to exit it
208      * should instead call vTaskDelete( NULL ).
209      *
210      * Artificially force an assert() to be triggered if configASSERT() is
211      * defined, then stop here so application writers can catch the error. */
212     configASSERT( uxCriticalNesting == ~0UL );
213     portDISABLE_INTERRUPTS();
214 
215     while( ulDummy == 0 )
216     {
217         /* This file calls prvTaskExitError() after the scheduler has been
218          * started to remove a compiler warning about the function being defined
219          * but never called.  ulDummy is used purely to quieten other warnings
220          * about code appearing after this function is called - making ulDummy
221          * volatile makes the compiler think the function could return and
222          * therefore not output an 'unreachable code' warning for code that appears
223          * after it. */
224     }
225 }
226 /*-----------------------------------------------------------*/
227 
vPortSVCHandler(void)228 void vPortSVCHandler( void )
229 {
230     __asm volatile (
231         "   ldr r3, pxCurrentTCBConst2      \n" /* Restore the context. */
232         "   ldr r1, [r3]                    \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
233         "   ldr r0, [r1]                    \n" /* The first item in pxCurrentTCB is the task top of stack. */
234         "   ldmia r0!, {r4-r11}             \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
235         "   msr psp, r0                     \n" /* Restore the task stack pointer. */
236         "   isb                             \n"
237         "   mov r0, #0                      \n"
238         "   msr basepri, r0                 \n"
239         "   orr r14, #0xd                   \n"
240         "   bx r14                          \n"
241         "                                   \n"
242         "   .align 4                        \n"
243         "pxCurrentTCBConst2: .word pxCurrentTCB             \n"
244         );
245 }
246 /*-----------------------------------------------------------*/
247 
prvPortStartFirstTask(void)248 static void prvPortStartFirstTask( void )
249 {
250     __asm volatile (
251         " ldr r0, =0xE000ED08   \n" /* Use the NVIC offset register to locate the stack. */
252         " ldr r0, [r0]          \n"
253         " ldr r0, [r0]          \n"
254         " msr msp, r0           \n" /* Set the msp back to the start of the stack. */
255         " cpsie i               \n" /* Globally enable interrupts. */
256         " cpsie f               \n"
257         " dsb                   \n"
258         " isb                   \n"
259         " svc 0                 \n" /* System call to start first task. */
260         " nop                   \n"
261         " .ltorg                \n"
262         );
263 }
264 /*-----------------------------------------------------------*/
265 
266 /*
267  * See header file for description.
268  */
xPortStartScheduler(void)269 BaseType_t xPortStartScheduler( void )
270 {
271     /* An application can install FreeRTOS interrupt handlers in one of the
272      * following ways:
273      * 1. Direct Routing - Install the functions vPortSVCHandler and
274      *    xPortPendSVHandler for SVCall and PendSV interrupts respectively.
275      * 2. Indirect Routing - Install separate handlers for SVCall and PendSV
276      *    interrupts and route program control from those handlers to
277      *    vPortSVCHandler and xPortPendSVHandler functions.
278      *
279      * Applications that use Indirect Routing must set
280      * configCHECK_HANDLER_INSTALLATION to 0 in their FreeRTOSConfig.h. Direct
281      * routing, which is validated here when configCHECK_HANDLER_INSTALLATION
282      * is 1, should be preferred when possible. */
283     #if ( configCHECK_HANDLER_INSTALLATION == 1 )
284     {
285         const portISR_t * const pxVectorTable = portSCB_VTOR_REG;
286 
287         /* Validate that the application has correctly installed the FreeRTOS
288          * handlers for SVCall and PendSV interrupts. We do not check the
289          * installation of the SysTick handler because the application may
290          * choose to drive the RTOS tick using a timer other than the SysTick
291          * timer by overriding the weak function vPortSetupTimerInterrupt().
292          *
293          * Assertion failures here indicate incorrect installation of the
294          * FreeRTOS handlers. For help installing the FreeRTOS handlers, see
295          * https://www.FreeRTOS.org/FAQHelp.html.
296          *
297          * Systems with a configurable address for the interrupt vector table
298          * can also encounter assertion failures or even system faults here if
299          * VTOR is not set correctly to point to the application's vector table. */
300         configASSERT( pxVectorTable[ portVECTOR_INDEX_SVC ] == vPortSVCHandler );
301         configASSERT( pxVectorTable[ portVECTOR_INDEX_PENDSV ] == xPortPendSVHandler );
302     }
303     #endif /* configCHECK_HANDLER_INSTALLATION */
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, and make SVCall
390      * the highest priority. */
391     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
392     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
393     portNVIC_SHPR2_REG = 0;
394 
395     /* Start the timer that generates the tick ISR.  Interrupts are disabled
396      * here already. */
397     vPortSetupTimerInterrupt();
398 
399     /* Initialise the critical nesting count ready for the first task. */
400     uxCriticalNesting = 0;
401 
402     /* Start the first task. */
403     prvPortStartFirstTask();
404 
405     /* Should never get here as the tasks will now be executing!  Call the task
406      * exit error function to prevent compiler warnings about a static function
407      * not being called in the case that the application writer overrides this
408      * functionality by defining configTASK_RETURN_ADDRESS.  Call
409      * vTaskSwitchContext() so link time optimisation does not remove the
410      * symbol. */
411     vTaskSwitchContext();
412     prvTaskExitError();
413 
414     /* Should not get here! */
415     return 0;
416 }
417 /*-----------------------------------------------------------*/
418 
vPortEndScheduler(void)419 void vPortEndScheduler( void )
420 {
421     /* Not implemented in ports where there is nothing to return to.
422      * Artificially force an assert. */
423     configASSERT( uxCriticalNesting == 1000UL );
424 }
425 /*-----------------------------------------------------------*/
426 
vPortEnterCritical(void)427 void vPortEnterCritical( void )
428 {
429     portDISABLE_INTERRUPTS();
430     uxCriticalNesting++;
431 
432     /* This is not the interrupt safe version of the enter critical function so
433      * assert() if it is being called from an interrupt context.  Only API
434      * functions that end in "FromISR" can be used in an interrupt.  Only assert if
435      * the critical nesting count is 1 to protect against recursive calls if the
436      * assert function also uses a critical section. */
437     if( uxCriticalNesting == 1 )
438     {
439         configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
440     }
441 }
442 /*-----------------------------------------------------------*/
443 
vPortExitCritical(void)444 void vPortExitCritical( void )
445 {
446     configASSERT( uxCriticalNesting );
447     uxCriticalNesting--;
448 
449     if( uxCriticalNesting == 0 )
450     {
451         portENABLE_INTERRUPTS();
452     }
453 }
454 /*-----------------------------------------------------------*/
455 
xPortPendSVHandler(void)456 void xPortPendSVHandler( void )
457 {
458     /* This is a naked function. */
459 
460     __asm volatile
461     (
462         "   mrs r0, psp                         \n"
463         "   isb                                 \n"
464         "                                       \n"
465         "   ldr r3, pxCurrentTCBConst           \n" /* Get the location of the current TCB. */
466         "   ldr r2, [r3]                        \n"
467         "                                       \n"
468         "   stmdb r0!, {r4-r11}                 \n" /* Save the remaining registers. */
469         "   str r0, [r2]                        \n" /* Save the new top of stack into the first member of the TCB. */
470         "                                       \n"
471         "   stmdb sp!, {r3, r14}                \n"
472         "   mov r0, %0                          \n"
473         "   msr basepri, r0                     \n"
474         "   bl vTaskSwitchContext               \n"
475         "   mov r0, #0                          \n"
476         "   msr basepri, r0                     \n"
477         "   ldmia sp!, {r3, r14}                \n"
478         "                                       \n" /* Restore the context, including the critical nesting count. */
479         "   ldr r1, [r3]                        \n"
480         "   ldr r0, [r1]                        \n" /* The first item in pxCurrentTCB is the task top of stack. */
481         "   ldmia r0!, {r4-r11}                 \n" /* Pop the registers. */
482         "   msr psp, r0                         \n"
483         "   isb                                 \n"
484         "   bx r14                              \n"
485         "                                       \n"
486         "   .align 4                            \n"
487         "pxCurrentTCBConst: .word pxCurrentTCB  \n"
488         ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
489     );
490 }
491 /*-----------------------------------------------------------*/
492 
xPortSysTickHandler(void)493 void xPortSysTickHandler( void )
494 {
495     /* The SysTick runs at the lowest interrupt priority, so when this interrupt
496      * executes all interrupts must be unmasked.  There is therefore no need to
497      * save and then restore the interrupt mask value as its value is already
498      * known. */
499     portDISABLE_INTERRUPTS();
500     traceISR_ENTER();
501     {
502         /* Increment the RTOS tick. */
503         if( xTaskIncrementTick() != pdFALSE )
504         {
505             traceISR_EXIT_TO_SCHEDULER();
506 
507             /* A context switch is required.  Context switching is performed in
508              * the PendSV interrupt.  Pend the PendSV interrupt. */
509             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
510         }
511         else
512         {
513             traceISR_EXIT();
514         }
515     }
516     portENABLE_INTERRUPTS();
517 }
518 /*-----------------------------------------------------------*/
519 
520 #if ( configUSE_TICKLESS_IDLE == 1 )
521 
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)522     __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
523     {
524         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
525         TickType_t xModifiableIdleTime;
526 
527         /* Make sure the SysTick reload value does not overflow the counter. */
528         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
529         {
530             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
531         }
532 
533         /* Enter a critical section but don't use the taskENTER_CRITICAL()
534          * method as that will mask interrupts that should exit sleep mode. */
535         __asm volatile ( "cpsid i" ::: "memory" );
536         __asm volatile ( "dsb" );
537         __asm volatile ( "isb" );
538 
539         /* If a context switch is pending or a task is waiting for the scheduler
540          * to be unsuspended then abandon the low power entry. */
541         if( eTaskConfirmSleepModeStatus() == eAbortSleep )
542         {
543             /* Re-enable interrupts - see comments above the cpsid instruction
544              * above. */
545             __asm volatile ( "cpsie i" ::: "memory" );
546         }
547         else
548         {
549             /* Stop the SysTick momentarily.  The time the SysTick is stopped for
550              * is accounted for as best it can be, but using the tickless mode will
551              * inevitably result in some tiny drift of the time maintained by the
552              * kernel with respect to calendar time. */
553             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
554 
555             /* Use the SysTick current-value register to determine the number of
556              * SysTick decrements remaining until the next tick interrupt.  If the
557              * current-value register is zero, then there are actually
558              * ulTimerCountsForOneTick decrements remaining, not zero, because the
559              * SysTick requests the interrupt when decrementing from 1 to 0. */
560             ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
561 
562             if( ulSysTickDecrementsLeft == 0 )
563             {
564                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
565             }
566 
567             /* Calculate the reload value required to wait xExpectedIdleTime
568              * tick periods.  -1 is used because this code normally executes part
569              * way through the first tick period.  But if the SysTick IRQ is now
570              * pending, then clear the IRQ, suppressing the first tick, and correct
571              * the reload value to reflect that the second tick period is already
572              * underway.  The expected idle time is always at least two ticks. */
573             ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
574 
575             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
576             {
577                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
578                 ulReloadValue -= ulTimerCountsForOneTick;
579             }
580 
581             if( ulReloadValue > ulStoppedTimerCompensation )
582             {
583                 ulReloadValue -= ulStoppedTimerCompensation;
584             }
585 
586             /* Set the new reload value. */
587             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
588 
589             /* Clear the SysTick count flag and set the count value back to
590              * zero. */
591             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
592 
593             /* Restart SysTick. */
594             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
595 
596             /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
597              * set its parameter to 0 to indicate that its implementation contains
598              * its own wait for interrupt or wait for event instruction, and so wfi
599              * should not be executed again.  However, the original expected idle
600              * time variable must remain unmodified, so a copy is taken. */
601             xModifiableIdleTime = xExpectedIdleTime;
602             configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
603 
604             if( xModifiableIdleTime > 0 )
605             {
606                 __asm volatile ( "dsb" ::: "memory" );
607                 __asm volatile ( "wfi" );
608                 __asm volatile ( "isb" );
609             }
610 
611             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
612 
613             /* Re-enable interrupts to allow the interrupt that brought the MCU
614              * out of sleep mode to execute immediately.  See comments above
615              * the cpsid instruction above. */
616             __asm volatile ( "cpsie i" ::: "memory" );
617             __asm volatile ( "dsb" );
618             __asm volatile ( "isb" );
619 
620             /* Disable interrupts again because the clock is about to be stopped
621              * and interrupts that execute while the clock is stopped will increase
622              * any slippage between the time maintained by the RTOS and calendar
623              * time. */
624             __asm volatile ( "cpsid i" ::: "memory" );
625             __asm volatile ( "dsb" );
626             __asm volatile ( "isb" );
627 
628             /* Disable the SysTick clock without reading the
629              * portNVIC_SYSTICK_CTRL_REG register to ensure the
630              * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,
631              * the time the SysTick is stopped for is accounted for as best it can
632              * be, but using the tickless mode will inevitably result in some tiny
633              * drift of the time maintained by the kernel with respect to calendar
634              * time*/
635             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
636 
637             /* Determine whether the SysTick has already counted to zero. */
638             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
639             {
640                 uint32_t ulCalculatedLoadValue;
641 
642                 /* The tick interrupt ended the sleep (or is now pending), and
643                  * a new tick period has started.  Reset portNVIC_SYSTICK_LOAD_REG
644                  * with whatever remains of the new tick period. */
645                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
646 
647                 /* Don't allow a tiny value, or values that have somehow
648                  * underflowed because the post sleep hook did something
649                  * that took too long or because the SysTick current-value register
650                  * is zero. */
651                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
652                 {
653                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
654                 }
655 
656                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
657 
658                 /* As the pending tick will be processed as soon as this
659                  * function exits, the tick value maintained by the tick is stepped
660                  * forward by one less than the time spent waiting. */
661                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
662             }
663             else
664             {
665                 /* Something other than the tick interrupt ended the sleep. */
666 
667                 /* Use the SysTick current-value register to determine the
668                  * number of SysTick decrements remaining until the expected idle
669                  * time would have ended. */
670                 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
671                 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
672                 {
673                     /* If the SysTick is not using the core clock, the current-
674                      * value register might still be zero here.  In that case, the
675                      * SysTick didn't load from the reload register, and there are
676                      * ulReloadValue decrements remaining in the expected idle
677                      * time, not zero. */
678                     if( ulSysTickDecrementsLeft == 0 )
679                     {
680                         ulSysTickDecrementsLeft = ulReloadValue;
681                     }
682                 }
683                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
684 
685                 /* Work out how long the sleep lasted rounded to complete tick
686                  * periods (not the ulReload value which accounted for part
687                  * ticks). */
688                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
689 
690                 /* How many complete tick periods passed while the processor
691                  * was waiting? */
692                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
693 
694                 /* The reload value is set to whatever fraction of a single tick
695                  * period remains. */
696                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
697             }
698 
699             /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
700              * then set portNVIC_SYSTICK_LOAD_REG back to its standard value.  If
701              * the SysTick is not using the core clock, temporarily configure it to
702              * use the core clock.  This configuration forces the SysTick to load
703              * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
704              * cycle of the other clock.  Then portNVIC_SYSTICK_LOAD_REG is ready
705              * to receive the standard value immediately. */
706             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
707             portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
708             #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
709             {
710                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
711             }
712             #else
713             {
714                 /* The temporary usage of the core clock has served its purpose,
715                  * as described above.  Resume usage of the other clock. */
716                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
717 
718                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
719                 {
720                     /* The partial tick period already ended.  Be sure the SysTick
721                      * counts it only once. */
722                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
723                 }
724 
725                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
726                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
727             }
728             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
729 
730             /* Step the tick to account for any tick periods that elapsed. */
731             vTaskStepTick( ulCompleteTickPeriods );
732 
733             /* Exit with interrupts enabled. */
734             __asm volatile ( "cpsie i" ::: "memory" );
735         }
736     }
737 
738 #endif /* configUSE_TICKLESS_IDLE */
739 /*-----------------------------------------------------------*/
740 
741 /*
742  * Setup the systick timer to generate the tick interrupts at the required
743  * frequency.
744  */
vPortSetupTimerInterrupt(void)745 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
746 {
747     /* Calculate the constants required to configure the tick interrupt. */
748     #if ( configUSE_TICKLESS_IDLE == 1 )
749     {
750         ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
751         xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
752         ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
753     }
754     #endif /* configUSE_TICKLESS_IDLE */
755 
756     /* Stop and clear the SysTick. */
757     portNVIC_SYSTICK_CTRL_REG = 0UL;
758     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
759 
760     /* Configure SysTick to interrupt at the requested rate. */
761     portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
762     portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
763 }
764 /*-----------------------------------------------------------*/
765 
766 #if ( configASSERT_DEFINED == 1 )
767 
vPortValidateInterruptPriority(void)768     void vPortValidateInterruptPriority( void )
769     {
770         uint32_t ulCurrentInterrupt;
771         uint8_t ucCurrentPriority;
772 
773         /* Obtain the number of the currently executing interrupt. */
774         __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
775 
776         /* Is the interrupt number a user defined interrupt? */
777         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
778         {
779             /* Look up the interrupt's priority. */
780             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
781 
782             /* The following assertion will fail if a service routine (ISR) for
783              * an interrupt that has been assigned a priority above
784              * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
785              * function.  ISR safe FreeRTOS API functions must *only* be called
786              * from interrupts that have been assigned a priority at or below
787              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
788              *
789              * Numerically low interrupt priority numbers represent logically high
790              * interrupt priorities, therefore the priority of the interrupt must
791              * be set to a value equal to or numerically *higher* than
792              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
793              *
794              * Interrupts that  use the FreeRTOS API must not be left at their
795              * default priority of  zero as that is the highest possible priority,
796              * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
797              * and  therefore also guaranteed to be invalid.
798              *
799              * FreeRTOS maintains separate thread and ISR API functions to ensure
800              * interrupt entry is as fast and simple as possible.
801              *
802              * The following links provide detailed information:
803              * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
804              * https://www.FreeRTOS.org/FAQHelp.html */
805             configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
806         }
807 
808         /* Priority grouping:  The interrupt controller (NVIC) allows the bits
809          * that define each interrupt's priority to be split between bits that
810          * define the interrupt's pre-emption priority bits and bits that define
811          * the interrupt's sub-priority.  For simplicity all bits must be defined
812          * to be pre-emption priority bits.  The following assertion will fail if
813          * this is not the case (if some bits represent a sub-priority).
814          *
815          * If the application only uses CMSIS libraries for interrupt
816          * configuration then the correct setting can be achieved on all Cortex-M
817          * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
818          * scheduler.  Note however that some vendor specific peripheral libraries
819          * assume a non-zero priority group setting, in which cases using a value
820          * of zero will result in unpredictable behaviour. */
821         configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
822     }
823 
824 #endif /* configASSERT_DEFINED */
825