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