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