2 * FreeRTOS Kernel V10.2.1
\r
3 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
\r
5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
\r
6 * this software and associated documentation files (the "Software"), to deal in
\r
7 * the Software without restriction, including without limitation the rights to
\r
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
\r
9 * the Software, and to permit persons to whom the Software is furnished to do so,
\r
10 * subject to the following conditions:
\r
12 * The above copyright notice and this permission notice shall be included in all
\r
13 * copies or substantial portions of the Software.
\r
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
\r
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
\r
17 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
\r
18 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
\r
19 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
\r
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\r
22 * http://www.FreeRTOS.org
\r
23 * http://aws.amazon.com/freertos
\r
25 * 1 tab == 4 spaces!
\r
28 /*-----------------------------------------------------------
\r
29 * Implementation of functions defined in portable.h for the ARM CM0 port.
\r
30 *----------------------------------------------------------*/
\r
32 /* Scheduler includes. */
\r
33 #include "FreeRTOS.h"
\r
36 /* Constants required to manipulate the NVIC. */
\r
37 #define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) )
\r
38 #define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) )
\r
39 #define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) )
\r
40 #define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) )
\r
41 #define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) )
\r
42 #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
\r
43 #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
\r
44 #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
\r
45 #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
\r
46 #define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )
\r
47 #define portMIN_INTERRUPT_PRIORITY ( 255UL )
\r
48 #define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL )
\r
49 #define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL )
\r
51 /* Constants required to set up the initial stack. */
\r
52 #define portINITIAL_XPSR ( 0x01000000 )
\r
54 /* The systick is a 24-bit counter. */
\r
55 #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
\r
57 /* A fiddle factor to estimate the number of SysTick counts that would have
\r
58 occurred while the SysTick counter is stopped during tickless idle
\r
60 #ifndef portMISSED_COUNTS_FACTOR
\r
61 #define portMISSED_COUNTS_FACTOR ( 45UL )
\r
64 /* Let the user override the pre-loading of the initial LR with the address of
\r
65 prvTaskExitError() in case it messes up unwinding of the stack in the
\r
67 #ifdef configTASK_RETURN_ADDRESS
\r
68 #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
\r
70 #define portTASK_RETURN_ADDRESS prvTaskExitError
\r
74 * Setup the timer to generate the tick interrupts. The implementation in this
\r
75 * file is weak to allow application writers to change the timer used to
\r
76 * generate the tick interrupt.
\r
78 void vPortSetupTimerInterrupt( void );
\r
81 * Exception handlers.
\r
83 void xPortPendSVHandler( void ) __attribute__ (( naked ));
\r
84 void xPortSysTickHandler( void );
\r
85 void vPortSVCHandler( void );
\r
88 * Start first task is a separate function so it can be tested in isolation.
\r
90 static void vPortStartFirstTask( void ) __attribute__ (( naked ));
\r
93 * Used to catch tasks that attempt to return from their implementing function.
\r
95 static void prvTaskExitError( void );
\r
97 /*-----------------------------------------------------------*/
\r
99 /* Each task maintains its own interrupt status in the critical nesting
\r
101 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
\r
103 /*-----------------------------------------------------------*/
\r
106 * The number of SysTick increments that make up one tick period.
\r
108 #if( configUSE_TICKLESS_IDLE == 1 )
\r
109 static uint32_t ulTimerCountsForOneTick = 0;
\r
110 #endif /* configUSE_TICKLESS_IDLE */
\r
113 * The maximum number of tick periods that can be suppressed is limited by the
\r
114 * 24 bit resolution of the SysTick timer.
\r
116 #if( configUSE_TICKLESS_IDLE == 1 )
\r
117 static uint32_t xMaximumPossibleSuppressedTicks = 0;
\r
118 #endif /* configUSE_TICKLESS_IDLE */
\r
121 * Compensate for the CPU cycles that pass while the SysTick is stopped (low
\r
122 * power functionality only.
\r
124 #if( configUSE_TICKLESS_IDLE == 1 )
\r
125 static uint32_t ulStoppedTimerCompensation = 0;
\r
126 #endif /* configUSE_TICKLESS_IDLE */
\r
128 /*-----------------------------------------------------------*/
\r
131 * See header file for description.
\r
133 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
\r
135 /* Simulate the stack frame as it would be created by a context switch
\r
137 pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
\r
138 *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
\r
140 *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
\r
142 *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
\r
143 pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
\r
144 *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
\r
145 pxTopOfStack -= 8; /* R11..R4. */
\r
147 return pxTopOfStack;
\r
149 /*-----------------------------------------------------------*/
\r
151 static void prvTaskExitError( void )
\r
153 volatile uint32_t ulDummy = 0UL;
\r
155 /* A function that implements a task must not exit or attempt to return to
\r
156 its caller as there is nothing to return to. If a task wants to exit it
\r
157 should instead call vTaskDelete( NULL ).
\r
159 Artificially force an assert() to be triggered if configASSERT() is
\r
160 defined, then stop here so application writers can catch the error. */
\r
161 configASSERT( uxCriticalNesting == ~0UL );
\r
162 portDISABLE_INTERRUPTS();
\r
163 while( ulDummy == 0 )
\r
165 /* This file calls prvTaskExitError() after the scheduler has been
\r
166 started to remove a compiler warning about the function being defined
\r
167 but never called. ulDummy is used purely to quieten other warnings
\r
168 about code appearing after this function is called - making ulDummy
\r
169 volatile makes the compiler think the function could return and
\r
170 therefore not output an 'unreachable code' warning for code that appears
\r
174 /*-----------------------------------------------------------*/
\r
176 void vPortSVCHandler( void )
\r
178 /* This function is no longer used, but retained for backward
\r
181 /*-----------------------------------------------------------*/
\r
183 void vPortStartFirstTask( void )
\r
185 /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector
\r
186 table offset register that can be used to locate the initial stack value.
\r
187 Not all M0 parts have the application vector table at address 0. */
\r
189 " .syntax unified \n"
\r
190 " ldr r2, pxCurrentTCBConst2 \n" /* Obtain location of pxCurrentTCB. */
\r
192 " ldr r0, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
\r
193 " adds r0, #32 \n" /* Discard everything up to r0. */
\r
194 " msr psp, r0 \n" /* This is now the new top of stack to use in the task. */
\r
195 " movs r0, #2 \n" /* Switch to the psp stack. */
\r
196 " msr CONTROL, r0 \n"
\r
198 " pop {r0-r5} \n" /* Pop the registers that are saved automatically. */
\r
199 " mov lr, r5 \n" /* lr is now in r5. */
\r
200 " pop {r3} \n" /* Return address is now in r3. */
\r
201 " pop {r2} \n" /* Pop and discard XPSR. */
\r
202 " cpsie i \n" /* The first task has its context and interrupts can be enabled. */
\r
203 " bx r3 \n" /* Finally, jump to the user defined task code. */
\r
206 "pxCurrentTCBConst2: .word pxCurrentTCB "
\r
209 /*-----------------------------------------------------------*/
\r
212 * See header file for description.
\r
214 BaseType_t xPortStartScheduler( void )
\r
216 /* Make PendSV, CallSV and SysTick the same priority as the kernel. */
\r
217 portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
\r
218 portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
\r
220 /* Start the timer that generates the tick ISR. Interrupts are disabled
\r
222 vPortSetupTimerInterrupt();
\r
224 /* Initialise the critical nesting count ready for the first task. */
\r
225 uxCriticalNesting = 0;
\r
227 /* Start the first task. */
\r
228 vPortStartFirstTask();
\r
230 /* Should never get here as the tasks will now be executing! Call the task
\r
231 exit error function to prevent compiler warnings about a static function
\r
232 not being called in the case that the application writer overrides this
\r
233 functionality by defining configTASK_RETURN_ADDRESS. Call
\r
234 vTaskSwitchContext() so link time optimisation does not remove the
\r
236 vTaskSwitchContext();
\r
237 prvTaskExitError();
\r
239 /* Should not get here! */
\r
242 /*-----------------------------------------------------------*/
\r
244 void vPortEndScheduler( void )
\r
246 /* Not implemented in ports where there is nothing to return to.
\r
247 Artificially force an assert. */
\r
248 configASSERT( uxCriticalNesting == 1000UL );
\r
250 /*-----------------------------------------------------------*/
\r
252 void vPortYield( void )
\r
254 /* Set a PendSV to request a context switch. */
\r
255 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
\r
257 /* Barriers are normally not required but do ensure the code is completely
\r
258 within the specified behaviour for the architecture. */
\r
259 __asm volatile( "dsb" ::: "memory" );
\r
260 __asm volatile( "isb" );
\r
262 /*-----------------------------------------------------------*/
\r
264 void vPortEnterCritical( void )
\r
266 portDISABLE_INTERRUPTS();
\r
267 uxCriticalNesting++;
\r
268 __asm volatile( "dsb" ::: "memory" );
\r
269 __asm volatile( "isb" );
\r
271 /*-----------------------------------------------------------*/
\r
273 void vPortExitCritical( void )
\r
275 configASSERT( uxCriticalNesting );
\r
276 uxCriticalNesting--;
\r
277 if( uxCriticalNesting == 0 )
\r
279 portENABLE_INTERRUPTS();
\r
282 /*-----------------------------------------------------------*/
\r
284 uint32_t ulSetInterruptMaskFromISR( void )
\r
287 " mrs r0, PRIMASK \n"
\r
293 /*-----------------------------------------------------------*/
\r
295 void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask )
\r
298 " msr PRIMASK, r0 \n"
\r
303 /*-----------------------------------------------------------*/
\r
305 void xPortPendSVHandler( void )
\r
307 /* This is a naked function. */
\r
311 " .syntax unified \n"
\r
314 " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
\r
317 " subs r0, r0, #32 \n" /* Make space for the remaining low registers. */
\r
318 " str r0, [r2] \n" /* Save the new top of stack. */
\r
319 " stmia r0!, {r4-r7} \n" /* Store the low registers that are not saved automatically. */
\r
320 " mov r4, r8 \n" /* Store the high registers. */
\r
324 " stmia r0!, {r4-r7} \n"
\r
326 " push {r3, r14} \n"
\r
328 " bl vTaskSwitchContext \n"
\r
330 " pop {r2, r3} \n" /* lr goes in r3. r2 now holds tcb pointer. */
\r
333 " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
\r
334 " adds r0, r0, #16 \n" /* Move to the high registers. */
\r
335 " ldmia r0!, {r4-r7} \n" /* Pop the high registers. */
\r
341 " msr psp, r0 \n" /* Remember the new top of stack for the task. */
\r
343 " subs r0, r0, #32 \n" /* Go back for the low registers that are not automatically restored. */
\r
344 " ldmia r0!, {r4-r7} \n" /* Pop low registers. */
\r
349 "pxCurrentTCBConst: .word pxCurrentTCB "
\r
352 /*-----------------------------------------------------------*/
\r
354 void xPortSysTickHandler( void )
\r
356 uint32_t ulPreviousMask;
\r
358 ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
\r
360 /* Increment the RTOS tick. */
\r
361 if( xTaskIncrementTick() != pdFALSE )
\r
363 /* Pend a context switch. */
\r
364 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
\r
367 portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
\r
369 /*-----------------------------------------------------------*/
\r
372 * Setup the systick timer to generate the tick interrupts at the required
\r
375 __attribute__(( weak )) void vPortSetupTimerInterrupt( void )
\r
377 /* Calculate the constants required to configure the tick interrupt. */
\r
378 #if( configUSE_TICKLESS_IDLE == 1 )
\r
380 ulTimerCountsForOneTick = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ );
\r
381 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
\r
382 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;
\r
384 #endif /* configUSE_TICKLESS_IDLE */
\r
386 /* Stop and reset the SysTick. */
\r
387 portNVIC_SYSTICK_CTRL_REG = 0UL;
\r
388 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
\r
390 /* Configure SysTick to interrupt at the requested rate. */
\r
391 portNVIC_SYSTICK_LOAD_REG = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
\r
392 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
\r
394 /*-----------------------------------------------------------*/
\r
396 #if( configUSE_TICKLESS_IDLE == 1 )
\r
398 __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
\r
400 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
\r
401 TickType_t xModifiableIdleTime;
\r
403 /* Make sure the SysTick reload value does not overflow the counter. */
\r
404 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
\r
406 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
\r
409 /* Stop the SysTick momentarily. The time the SysTick is stopped for
\r
410 is accounted for as best it can be, but using the tickless mode will
\r
411 inevitably result in some tiny drift of the time maintained by the
\r
412 kernel with respect to calendar time. */
\r
413 portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
\r
415 /* Calculate the reload value required to wait xExpectedIdleTime
\r
416 tick periods. -1 is used because this code will execute part way
\r
417 through one of the tick periods. */
\r
418 ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
\r
419 if( ulReloadValue > ulStoppedTimerCompensation )
\r
421 ulReloadValue -= ulStoppedTimerCompensation;
\r
424 /* Enter a critical section but don't use the taskENTER_CRITICAL()
\r
425 method as that will mask interrupts that should exit sleep mode. */
\r
426 __asm volatile( "cpsid i" ::: "memory" );
\r
427 __asm volatile( "dsb" );
\r
428 __asm volatile( "isb" );
\r
430 /* If a context switch is pending or a task is waiting for the scheduler
\r
431 to be unsuspended then abandon the low power entry. */
\r
432 if( eTaskConfirmSleepModeStatus() == eAbortSleep )
\r
434 /* Restart from whatever is left in the count register to complete
\r
435 this tick period. */
\r
436 portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
\r
438 /* Restart SysTick. */
\r
439 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
\r
441 /* Reset the reload register to the value required for normal tick
\r
443 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
\r
445 /* Re-enable interrupts - see comments above the cpsid instruction()
\r
447 __asm volatile( "cpsie i" ::: "memory" );
\r
451 /* Set the new reload value. */
\r
452 portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
\r
454 /* Clear the SysTick count flag and set the count value back to
\r
456 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
\r
458 /* Restart SysTick. */
\r
459 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
\r
461 /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
\r
462 set its parameter to 0 to indicate that its implementation contains
\r
463 its own wait for interrupt or wait for event instruction, and so wfi
\r
464 should not be executed again. However, the original expected idle
\r
465 time variable must remain unmodified, so a copy is taken. */
\r
466 xModifiableIdleTime = xExpectedIdleTime;
\r
467 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
\r
468 if( xModifiableIdleTime > 0 )
\r
470 __asm volatile( "dsb" ::: "memory" );
\r
471 __asm volatile( "wfi" );
\r
472 __asm volatile( "isb" );
\r
474 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
\r
476 /* Re-enable interrupts to allow the interrupt that brought the MCU
\r
477 out of sleep mode to execute immediately. see comments above
\r
478 __disable_interrupt() call above. */
\r
479 __asm volatile( "cpsie i" ::: "memory" );
\r
480 __asm volatile( "dsb" );
\r
481 __asm volatile( "isb" );
\r
483 /* Disable interrupts again because the clock is about to be stopped
\r
484 and interrupts that execute while the clock is stopped will increase
\r
485 any slippage between the time maintained by the RTOS and calendar
\r
487 __asm volatile( "cpsid i" ::: "memory" );
\r
488 __asm volatile( "dsb" );
\r
489 __asm volatile( "isb" );
\r
491 /* Disable the SysTick clock without reading the
\r
492 portNVIC_SYSTICK_CTRL_REG register to ensure the
\r
493 portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
\r
494 the time the SysTick is stopped for is accounted for as best it can
\r
495 be, but using the tickless mode will inevitably result in some tiny
\r
496 drift of the time maintained by the kernel with respect to calendar
\r
498 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
\r
500 /* Determine if the SysTick clock has already counted to zero and
\r
501 been set back to the current reload value (the reload back being
\r
502 correct for the entire expected idle time) or if the SysTick is yet
\r
503 to count to zero (in which case an interrupt other than the SysTick
\r
504 must have brought the system out of sleep mode). */
\r
505 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
\r
507 uint32_t ulCalculatedLoadValue;
\r
509 /* The tick interrupt is already pending, and the SysTick count
\r
510 reloaded with ulReloadValue. Reset the
\r
511 portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
\r
513 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
\r
515 /* Don't allow a tiny value, or values that have somehow
\r
516 underflowed because the post sleep hook did something
\r
517 that took too long. */
\r
518 if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
\r
520 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
\r
523 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
\r
525 /* As the pending tick will be processed as soon as this
\r
526 function exits, the tick value maintained by the tick is stepped
\r
527 forward by one less than the time spent waiting. */
\r
528 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
\r
532 /* Something other than the tick interrupt ended the sleep.
\r
533 Work out how long the sleep lasted rounded to complete tick
\r
534 periods (not the ulReload value which accounted for part
\r
536 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
\r
538 /* How many complete tick periods passed while the processor
\r
540 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
\r
542 /* The reload value is set to whatever fraction of a single tick
\r
544 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
\r
547 /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
\r
548 again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
\r
550 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
\r
551 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
\r
552 vTaskStepTick( ulCompleteTickPeriods );
\r
553 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
\r
555 /* Exit with interrpts enabled. */
\r
556 __asm volatile( "cpsie i" ::: "memory" );
\r
560 #endif /* configUSE_TICKLESS_IDLE */
\r