1 /*
2 * FreeRTOS Kernel <DEVELOPMENT BRANCH>
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 __ARM_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, =pxCurrentTCB \n" /* Restore the context. */
264 " ldr r1, [r3] \n" /* 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 " .ltorg \n"
274 );
275 }
276 /*-----------------------------------------------------------*/
277
prvPortStartFirstTask(void)278 static void prvPortStartFirstTask( void )
279 {
280 /* Start the first task. This also clears the bit that indicates the FPU is
281 * in use in case the FPU was used before the scheduler was started - which
282 * would otherwise result in the unnecessary leaving of space in the SVC stack
283 * for lazy saving of FPU registers. */
284 __asm volatile (
285 " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
286 " ldr r0, [r0] \n"
287 " ldr r0, [r0] \n"
288 " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
289 " mov r0, #0 \n" /* Clear the bit that indicates the FPU is in use, see comment above. */
290 " msr control, r0 \n"
291 " cpsie i \n" /* Globally enable interrupts. */
292 " cpsie f \n"
293 " dsb \n"
294 " isb \n"
295 " svc 0 \n" /* System call to start first task. */
296 " nop \n"
297 " .ltorg \n"
298 );
299 }
300 /*-----------------------------------------------------------*/
301
302 /*
303 * See header file for description.
304 */
xPortStartScheduler(void)305 BaseType_t xPortStartScheduler( void )
306 {
307 /* This port can be used on all revisions of the Cortex-M7 core other than
308 * the r0p1 parts. r0p1 parts should use the port from the
309 * /source/portable/GCC/ARM_CM7/r0p1 directory. */
310 configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
311 configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
312
313 /* An application can install FreeRTOS interrupt handlers in one of the
314 * following ways:
315 * 1. Direct Routing - Install the functions vPortSVCHandler and
316 * xPortPendSVHandler for SVCall and PendSV interrupts respectively.
317 * 2. Indirect Routing - Install separate handlers for SVCall and PendSV
318 * interrupts and route program control from those handlers to
319 * vPortSVCHandler and xPortPendSVHandler functions.
320 *
321 * Applications that use Indirect Routing must set
322 * configCHECK_HANDLER_INSTALLATION to 0 in their FreeRTOSConfig.h. Direct
323 * routing, which is validated here when configCHECK_HANDLER_INSTALLATION
324 * is 1, should be preferred when possible. */
325 #if ( configCHECK_HANDLER_INSTALLATION == 1 )
326 {
327 const portISR_t * const pxVectorTable = portSCB_VTOR_REG;
328
329 /* Validate that the application has correctly installed the FreeRTOS
330 * handlers for SVCall and PendSV interrupts. We do not check the
331 * installation of the SysTick handler because the application may
332 * choose to drive the RTOS tick using a timer other than the SysTick
333 * timer by overriding the weak function vPortSetupTimerInterrupt().
334 *
335 * Assertion failures here indicate incorrect installation of the
336 * FreeRTOS handlers. For help installing the FreeRTOS handlers, see
337 * https://www.freertos.org/Why-FreeRTOS/FAQs.
338 *
339 * Systems with a configurable address for the interrupt vector table
340 * can also encounter assertion failures or even system faults here if
341 * VTOR is not set correctly to point to the application's vector table. */
342 configASSERT( pxVectorTable[ portVECTOR_INDEX_SVC ] == vPortSVCHandler );
343 configASSERT( pxVectorTable[ portVECTOR_INDEX_PENDSV ] == xPortPendSVHandler );
344 }
345 #endif /* configCHECK_HANDLER_INSTALLATION */
346
347 #if ( configASSERT_DEFINED == 1 )
348 {
349 volatile uint8_t ucOriginalPriority;
350 volatile uint32_t ulImplementedPrioBits = 0;
351 volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
352 volatile uint8_t ucMaxPriorityValue;
353
354 /* Determine the maximum priority from which ISR safe FreeRTOS API
355 * functions can be called. ISR safe functions are those that end in
356 * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
357 * ensure interrupt entry is as fast and simple as possible.
358 *
359 * Save the interrupt priority value that is about to be clobbered. */
360 ucOriginalPriority = *pucFirstUserPriorityRegister;
361
362 /* Determine the number of priority bits available. First write to all
363 * possible bits. */
364 *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
365
366 /* Read the value back to see how many bits stuck. */
367 ucMaxPriorityValue = *pucFirstUserPriorityRegister;
368
369 /* Use the same mask on the maximum system call priority. */
370 ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
371
372 /* Check that the maximum system call priority is nonzero after
373 * accounting for the number of priority bits supported by the
374 * hardware. A priority of 0 is invalid because setting the BASEPRI
375 * register to 0 unmasks all interrupts, and interrupts with priority 0
376 * cannot be masked using BASEPRI.
377 * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
378 configASSERT( ucMaxSysCallPriority );
379
380 /* Check that the bits not implemented in hardware are zero in
381 * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
382 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
383
384 /* Calculate the maximum acceptable priority group value for the number
385 * of bits read back. */
386
387 while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
388 {
389 ulImplementedPrioBits++;
390 ucMaxPriorityValue <<= ( uint8_t ) 0x01;
391 }
392
393 if( ulImplementedPrioBits == 8 )
394 {
395 /* When the hardware implements 8 priority bits, there is no way for
396 * the software to configure PRIGROUP to not have sub-priorities. As
397 * a result, the least significant bit is always used for sub-priority
398 * and there are 128 preemption priorities and 2 sub-priorities.
399 *
400 * This may cause some confusion in some cases - for example, if
401 * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
402 * priority interrupts will be masked in Critical Sections as those
403 * are at the same preemption priority. This may appear confusing as
404 * 4 is higher (numerically lower) priority than
405 * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
406 * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
407 * to 4, this confusion does not happen and the behaviour remains the same.
408 *
409 * The following assert ensures that the sub-priority bit in the
410 * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
411 * confusion. */
412 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
413 ulMaxPRIGROUPValue = 0;
414 }
415 else
416 {
417 ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
418 }
419
420 /* Shift the priority group value back to its position within the AIRCR
421 * register. */
422 ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
423 ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
424
425 /* Restore the clobbered interrupt priority register to its original
426 * value. */
427 *pucFirstUserPriorityRegister = ucOriginalPriority;
428 }
429 #endif /* configASSERT_DEFINED */
430
431 /* Make PendSV and SysTick the lowest priority interrupts, and make SVCall
432 * the highest priority. */
433 portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
434 portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
435 portNVIC_SHPR2_REG = 0;
436
437 /* Start the timer that generates the tick ISR. Interrupts are disabled
438 * here already. */
439 vPortSetupTimerInterrupt();
440
441 /* Initialise the critical nesting count ready for the first task. */
442 uxCriticalNesting = 0;
443
444 /* Ensure the VFP is enabled - it should be anyway. */
445 vPortEnableVFP();
446
447 /* Lazy save always. */
448 *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
449
450 /* Start the first task. */
451 prvPortStartFirstTask();
452
453 /* Should never get here as the tasks will now be executing! Call the task
454 * exit error function to prevent compiler warnings about a static function
455 * not being called in the case that the application writer overrides this
456 * functionality by defining configTASK_RETURN_ADDRESS. Call
457 * vTaskSwitchContext() so link time optimisation does not remove the
458 * symbol. */
459 vTaskSwitchContext();
460 prvTaskExitError();
461
462 /* Should not get here! */
463 return 0;
464 }
465 /*-----------------------------------------------------------*/
466
vPortEndScheduler(void)467 void vPortEndScheduler( void )
468 {
469 /* Not implemented in ports where there is nothing to return to.
470 * Artificially force an assert. */
471 configASSERT( uxCriticalNesting == 1000UL );
472 }
473 /*-----------------------------------------------------------*/
474
vPortEnterCritical(void)475 void vPortEnterCritical( void )
476 {
477 portDISABLE_INTERRUPTS();
478 uxCriticalNesting++;
479
480 /* This is not the interrupt safe version of the enter critical function so
481 * assert() if it is being called from an interrupt context. Only API
482 * functions that end in "FromISR" can be used in an interrupt. Only assert if
483 * the critical nesting count is 1 to protect against recursive calls if the
484 * assert function also uses a critical section. */
485 if( uxCriticalNesting == 1 )
486 {
487 configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
488 }
489 }
490 /*-----------------------------------------------------------*/
491
vPortExitCritical(void)492 void vPortExitCritical( void )
493 {
494 configASSERT( uxCriticalNesting );
495 uxCriticalNesting--;
496
497 if( uxCriticalNesting == 0 )
498 {
499 portENABLE_INTERRUPTS();
500 }
501 }
502 /*-----------------------------------------------------------*/
503
xPortPendSVHandler(void)504 void xPortPendSVHandler( void )
505 {
506 /* This is a naked function. */
507
508 __asm volatile
509 (
510 " mrs r0, psp \n"
511 " isb \n"
512 " \n"
513 " ldr r3, =pxCurrentTCB \n" /* Get the location of the current TCB. */
514 " ldr r2, [r3] \n"
515 " \n"
516 " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, push high vfp registers. */
517 " it eq \n"
518 " vstmdbeq r0!, {s16-s31} \n"
519 " \n"
520 " stmdb r0!, {r4-r11, r14} \n" /* Save the core registers. */
521 " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
522 " \n"
523 " stmdb sp!, {r0, r3} \n"
524 " mov r0, %0 \n"
525 " msr basepri, r0 \n"
526 " dsb \n"
527 " isb \n"
528 " bl vTaskSwitchContext \n"
529 " mov r0, #0 \n"
530 " msr basepri, r0 \n"
531 " ldmia sp!, {r0, r3} \n"
532 " \n"
533 " ldr r1, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
534 " ldr r0, [r1] \n"
535 " \n"
536 " ldmia r0!, {r4-r11, r14} \n" /* Pop the core registers. */
537 " \n"
538 " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, pop the high vfp registers too. */
539 " it eq \n"
540 " vldmiaeq r0!, {s16-s31} \n"
541 " \n"
542 " msr psp, r0 \n"
543 " isb \n"
544 " \n"
545 #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */
546 #if WORKAROUND_PMU_CM001 == 1
547 " push { r14 } \n"
548 " pop { pc } \n"
549 #endif
550 #endif
551 " \n"
552 " bx r14 \n"
553 " \n"
554 " .ltorg \n"
555 ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
556 );
557 }
558 /*-----------------------------------------------------------*/
559
xPortSysTickHandler(void)560 void xPortSysTickHandler( void )
561 {
562 /* The SysTick runs at the lowest interrupt priority, so when this interrupt
563 * executes all interrupts must be unmasked. There is therefore no need to
564 * save and then restore the interrupt mask value as its value is already
565 * known. */
566 portDISABLE_INTERRUPTS();
567 traceISR_ENTER();
568 {
569 /* Increment the RTOS tick. */
570 if( xTaskIncrementTick() != pdFALSE )
571 {
572 traceISR_EXIT_TO_SCHEDULER();
573
574 /* A context switch is required. Context switching is performed in
575 * the PendSV interrupt. Pend the PendSV interrupt. */
576 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
577 }
578 else
579 {
580 traceISR_EXIT();
581 }
582 }
583 portENABLE_INTERRUPTS();
584 }
585 /*-----------------------------------------------------------*/
586
587 #if ( configUSE_TICKLESS_IDLE == 1 )
588
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)589 __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
590 {
591 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
592 TickType_t xModifiableIdleTime;
593
594 /* Make sure the SysTick reload value does not overflow the counter. */
595 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
596 {
597 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
598 }
599
600 /* Enter a critical section but don't use the taskENTER_CRITICAL()
601 * method as that will mask interrupts that should exit sleep mode. */
602 __asm volatile ( "cpsid i" ::: "memory" );
603 __asm volatile ( "dsb" );
604 __asm volatile ( "isb" );
605
606 /* If a context switch is pending or a task is waiting for the scheduler
607 * to be unsuspended then abandon the low power entry. */
608 if( eTaskConfirmSleepModeStatus() == eAbortSleep )
609 {
610 /* Re-enable interrupts - see comments above the cpsid instruction
611 * above. */
612 __asm volatile ( "cpsie i" ::: "memory" );
613 }
614 else
615 {
616 /* Stop the SysTick momentarily. The time the SysTick is stopped for
617 * is accounted for as best it can be, but using the tickless mode will
618 * inevitably result in some tiny drift of the time maintained by the
619 * kernel with respect to calendar time. */
620 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
621
622 /* Use the SysTick current-value register to determine the number of
623 * SysTick decrements remaining until the next tick interrupt. If the
624 * current-value register is zero, then there are actually
625 * ulTimerCountsForOneTick decrements remaining, not zero, because the
626 * SysTick requests the interrupt when decrementing from 1 to 0. */
627 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
628
629 if( ulSysTickDecrementsLeft == 0 )
630 {
631 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
632 }
633
634 /* Calculate the reload value required to wait xExpectedIdleTime
635 * tick periods. -1 is used because this code normally executes part
636 * way through the first tick period. But if the SysTick IRQ is now
637 * pending, then clear the IRQ, suppressing the first tick, and correct
638 * the reload value to reflect that the second tick period is already
639 * underway. The expected idle time is always at least two ticks. */
640 ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
641
642 if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
643 {
644 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
645 ulReloadValue -= ulTimerCountsForOneTick;
646 }
647
648 if( ulReloadValue > ulStoppedTimerCompensation )
649 {
650 ulReloadValue -= ulStoppedTimerCompensation;
651 }
652
653 /* Set the new reload value. */
654 portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
655
656 /* Clear the SysTick count flag and set the count value back to
657 * zero. */
658 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
659
660 /* Restart SysTick. */
661 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
662
663 /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
664 * set its parameter to 0 to indicate that its implementation contains
665 * its own wait for interrupt or wait for event instruction, and so wfi
666 * should not be executed again. However, the original expected idle
667 * time variable must remain unmodified, so a copy is taken. */
668 xModifiableIdleTime = xExpectedIdleTime;
669 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
670
671 if( xModifiableIdleTime > 0 )
672 {
673 __asm volatile ( "dsb" ::: "memory" );
674 __asm volatile ( "wfi" );
675 __asm volatile ( "isb" );
676 }
677
678 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
679
680 /* Re-enable interrupts to allow the interrupt that brought the MCU
681 * out of sleep mode to execute immediately. See comments above
682 * the cpsid instruction above. */
683 __asm volatile ( "cpsie i" ::: "memory" );
684 __asm volatile ( "dsb" );
685 __asm volatile ( "isb" );
686
687 /* Disable interrupts again because the clock is about to be stopped
688 * and interrupts that execute while the clock is stopped will increase
689 * any slippage between the time maintained by the RTOS and calendar
690 * time. */
691 __asm volatile ( "cpsid i" ::: "memory" );
692 __asm volatile ( "dsb" );
693 __asm volatile ( "isb" );
694
695 /* Disable the SysTick clock without reading the
696 * portNVIC_SYSTICK_CTRL_REG register to ensure the
697 * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
698 * the time the SysTick is stopped for is accounted for as best it can
699 * be, but using the tickless mode will inevitably result in some tiny
700 * drift of the time maintained by the kernel with respect to calendar
701 * time*/
702 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
703
704 /* Determine whether the SysTick has already counted to zero. */
705 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
706 {
707 uint32_t ulCalculatedLoadValue;
708
709 /* The tick interrupt ended the sleep (or is now pending), and
710 * a new tick period has started. Reset portNVIC_SYSTICK_LOAD_REG
711 * with whatever remains of the new tick period. */
712 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
713
714 /* Don't allow a tiny value, or values that have somehow
715 * underflowed because the post sleep hook did something
716 * that took too long or because the SysTick current-value register
717 * is zero. */
718 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
719 {
720 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
721 }
722
723 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
724
725 /* As the pending tick will be processed as soon as this
726 * function exits, the tick value maintained by the tick is stepped
727 * forward by one less than the time spent waiting. */
728 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
729 }
730 else
731 {
732 /* Something other than the tick interrupt ended the sleep. */
733
734 /* Use the SysTick current-value register to determine the
735 * number of SysTick decrements remaining until the expected idle
736 * time would have ended. */
737 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
738 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
739 {
740 /* If the SysTick is not using the core clock, the current-
741 * value register might still be zero here. In that case, the
742 * SysTick didn't load from the reload register, and there are
743 * ulReloadValue decrements remaining in the expected idle
744 * time, not zero. */
745 if( ulSysTickDecrementsLeft == 0 )
746 {
747 ulSysTickDecrementsLeft = ulReloadValue;
748 }
749 }
750 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
751
752 /* Work out how long the sleep lasted rounded to complete tick
753 * periods (not the ulReload value which accounted for part
754 * ticks). */
755 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
756
757 /* How many complete tick periods passed while the processor
758 * was waiting? */
759 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
760
761 /* The reload value is set to whatever fraction of a single tick
762 * period remains. */
763 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
764 }
765
766 /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
767 * then set portNVIC_SYSTICK_LOAD_REG back to its standard value. If
768 * the SysTick is not using the core clock, temporarily configure it to
769 * use the core clock. This configuration forces the SysTick to load
770 * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
771 * cycle of the other clock. Then portNVIC_SYSTICK_LOAD_REG is ready
772 * to receive the standard value immediately. */
773 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
774 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
775 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
776 {
777 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
778 }
779 #else
780 {
781 /* The temporary usage of the core clock has served its purpose,
782 * as described above. Resume usage of the other clock. */
783 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
784
785 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
786 {
787 /* The partial tick period already ended. Be sure the SysTick
788 * counts it only once. */
789 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
790 }
791
792 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
793 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
794 }
795 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
796
797 /* Step the tick to account for any tick periods that elapsed. */
798 vTaskStepTick( ulCompleteTickPeriods );
799
800 /* Exit with interrupts enabled. */
801 __asm volatile ( "cpsie i" ::: "memory" );
802 }
803 }
804
805 #endif /* #if configUSE_TICKLESS_IDLE */
806 /*-----------------------------------------------------------*/
807
808 /*
809 * Setup the systick timer to generate the tick interrupts at the required
810 * frequency.
811 */
vPortSetupTimerInterrupt(void)812 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
813 {
814 /* Calculate the constants required to configure the tick interrupt. */
815 #if ( configUSE_TICKLESS_IDLE == 1 )
816 {
817 ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
818 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
819 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
820 }
821 #endif /* configUSE_TICKLESS_IDLE */
822
823 /* Stop and clear the SysTick. */
824 portNVIC_SYSTICK_CTRL_REG = 0UL;
825 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
826
827 /* Configure SysTick to interrupt at the requested rate. */
828 portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
829 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
830 }
831 /*-----------------------------------------------------------*/
832
833 /* This is a naked function. */
vPortEnableVFP(void)834 static void vPortEnableVFP( void )
835 {
836 __asm volatile
837 (
838 " ldr.w r0, =0xE000ED88 \n" /* The FPU enable bits are in the CPACR. */
839 " ldr r1, [r0] \n"
840 " \n"
841 " orr r1, r1, #( 0xf << 20 ) \n" /* Enable CP10 and CP11 coprocessors, then save back. */
842 " str r1, [r0] \n"
843 " bx r14 \n"
844 " .ltorg \n"
845 );
846 }
847 /*-----------------------------------------------------------*/
848
849 #if ( configASSERT_DEFINED == 1 )
850
vPortValidateInterruptPriority(void)851 void vPortValidateInterruptPriority( void )
852 {
853 uint32_t ulCurrentInterrupt;
854 uint8_t ucCurrentPriority;
855
856 /* Obtain the number of the currently executing interrupt. */
857 __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
858
859 /* Is the interrupt number a user defined interrupt? */
860 if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
861 {
862 /* Look up the interrupt's priority. */
863 ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
864
865 /* The following assertion will fail if a service routine (ISR) for
866 * an interrupt that has been assigned a priority above
867 * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
868 * function. ISR safe FreeRTOS API functions must *only* be called
869 * from interrupts that have been assigned a priority at or below
870 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
871 *
872 * Numerically low interrupt priority numbers represent logically high
873 * interrupt priorities, therefore the priority of the interrupt must
874 * be set to a value equal to or numerically *higher* than
875 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
876 *
877 * Interrupts that use the FreeRTOS API must not be left at their
878 * default priority of zero as that is the highest possible priority,
879 * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
880 * and therefore also guaranteed to be invalid.
881 *
882 * FreeRTOS maintains separate thread and ISR API functions to ensure
883 * interrupt entry is as fast and simple as possible.
884 *
885 * The following links provide detailed information:
886 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
887 * https://www.freertos.org/Why-FreeRTOS/FAQs */
888 configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
889 }
890
891 /* Priority grouping: The interrupt controller (NVIC) allows the bits
892 * that define each interrupt's priority to be split between bits that
893 * define the interrupt's pre-emption priority bits and bits that define
894 * the interrupt's sub-priority. For simplicity all bits must be defined
895 * to be pre-emption priority bits. The following assertion will fail if
896 * this is not the case (if some bits represent a sub-priority).
897 *
898 * If the application only uses CMSIS libraries for interrupt
899 * configuration then the correct setting can be achieved on all Cortex-M
900 * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
901 * scheduler. Note however that some vendor specific peripheral libraries
902 * assume a non-zero priority group setting, in which cases using a value
903 * of zero will result in unpredictable behaviour. */
904 configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
905 }
906
907 #endif /* configASSERT_DEFINED */
908