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.
\r
76 static void prvSetupTimerInterrupt( void );
\r
79 * Exception handlers.
\r
81 void xPortPendSVHandler( void ) __attribute__ (( naked ));
\r
82 void xPortSysTickHandler( void );
\r
83 void vPortSVCHandler( void );
\r
86 * Start first task is a separate function so it can be tested in isolation.
\r
88 static void vPortStartFirstTask( void ) __attribute__ (( naked ));
\r
91 * Used to catch tasks that attempt to return from their implementing function.
\r
93 static void prvTaskExitError( void );
\r
95 /*-----------------------------------------------------------*/
\r
97 /* Each task maintains its own interrupt status in the critical nesting
\r
99 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
\r
101 /*-----------------------------------------------------------*/
\r
104 * The number of SysTick increments that make up one tick period.
\r
106 #if( configUSE_TICKLESS_IDLE == 1 )
\r
107 static uint32_t ulTimerCountsForOneTick = 0;
\r
108 #endif /* configUSE_TICKLESS_IDLE */
\r
111 * The maximum number of tick periods that can be suppressed is limited by the
\r
112 * 24 bit resolution of the SysTick timer.
\r
114 #if( configUSE_TICKLESS_IDLE == 1 )
\r
115 static uint32_t xMaximumPossibleSuppressedTicks = 0;
\r
116 #endif /* configUSE_TICKLESS_IDLE */
\r
119 * Compensate for the CPU cycles that pass while the SysTick is stopped (low
\r
120 * power functionality only.
\r
122 #if( configUSE_TICKLESS_IDLE == 1 )
\r
123 static uint32_t ulStoppedTimerCompensation = 0;
\r
124 #endif /* configUSE_TICKLESS_IDLE */
\r
126 /*-----------------------------------------------------------*/
\r
129 * See header file for description.
\r
131 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
\r
133 /* Simulate the stack frame as it would be created by a context switch
\r
135 pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
\r
136 *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
\r
138 *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
\r
140 *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
\r
141 pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
\r
142 *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
\r
143 pxTopOfStack -= 8; /* R11..R4. */
\r
145 return pxTopOfStack;
\r
147 /*-----------------------------------------------------------*/
\r
149 static void prvTaskExitError( void )
\r
151 volatile uint32_t ulDummy = 0UL;
\r
153 /* A function that implements a task must not exit or attempt to return to
\r
154 its caller as there is nothing to return to. If a task wants to exit it
\r
155 should instead call vTaskDelete( NULL ).
\r
157 Artificially force an assert() to be triggered if configASSERT() is
\r
158 defined, then stop here so application writers can catch the error. */
\r
159 configASSERT( uxCriticalNesting == ~0UL );
\r
160 portDISABLE_INTERRUPTS();
\r
161 while( ulDummy == 0 )
\r
163 /* This file calls prvTaskExitError() after the scheduler has been
\r
164 started to remove a compiler warning about the function being defined
\r
165 but never called. ulDummy is used purely to quieten other warnings
\r
166 about code appearing after this function is called - making ulDummy
\r
167 volatile makes the compiler think the function could return and
\r
168 therefore not output an 'unreachable code' warning for code that appears
\r
172 /*-----------------------------------------------------------*/
\r
174 void vPortSVCHandler( void )
\r
176 /* This function is no longer used, but retained for backward
\r
179 /*-----------------------------------------------------------*/
\r
181 void vPortStartFirstTask( void )
\r
183 /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector
\r
184 table offset register that can be used to locate the initial stack value.
\r
185 Not all M0 parts have the application vector table at address 0. */
\r
187 " .syntax unified \n"
\r
188 " ldr r2, pxCurrentTCBConst2 \n" /* Obtain location of pxCurrentTCB. */
\r
190 " ldr r0, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
\r
191 " adds r0, #32 \n" /* Discard everything up to r0. */
\r
192 " msr psp, r0 \n" /* This is now the new top of stack to use in the task. */
\r
193 " movs r0, #2 \n" /* Switch to the psp stack. */
\r
194 " msr CONTROL, r0 \n"
\r
196 " pop {r0-r5} \n" /* Pop the registers that are saved automatically. */
\r
197 " mov lr, r5 \n" /* lr is now in r5. */
\r
198 " pop {r3} \n" /* Return address is now in r3. */
\r
199 " pop {r2} \n" /* Pop and discard XPSR. */
\r
200 " cpsie i \n" /* The first task has its context and interrupts can be enabled. */
\r
201 " bx r3 \n" /* Finally, jump to the user defined task code. */
\r
204 "pxCurrentTCBConst2: .word pxCurrentTCB "
\r
207 /*-----------------------------------------------------------*/
\r
210 * See header file for description.
\r
212 BaseType_t xPortStartScheduler( void )
\r
214 /* Make PendSV, CallSV and SysTick the same priority as the kernel. */
\r
215 portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
\r
216 portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
\r
218 /* Start the timer that generates the tick ISR. Interrupts are disabled
\r
220 prvSetupTimerInterrupt();
\r
222 /* Initialise the critical nesting count ready for the first task. */
\r
223 uxCriticalNesting = 0;
\r
225 /* Start the first task. */
\r
226 vPortStartFirstTask();
\r
228 /* Should never get here as the tasks will now be executing! Call the task
\r
229 exit error function to prevent compiler warnings about a static function
\r
230 not being called in the case that the application writer overrides this
\r
231 functionality by defining configTASK_RETURN_ADDRESS. Call
\r
232 vTaskSwitchContext() so link time optimisation does not remove the
\r
234 vTaskSwitchContext();
\r
235 prvTaskExitError();
\r
237 /* Should not get here! */
\r
240 /*-----------------------------------------------------------*/
\r
242 void vPortEndScheduler( void )
\r
244 /* Not implemented in ports where there is nothing to return to.
\r
245 Artificially force an assert. */
\r
246 configASSERT( uxCriticalNesting == 1000UL );
\r
248 /*-----------------------------------------------------------*/
\r
250 void vPortYield( void )
\r
252 /* Set a PendSV to request a context switch. */
\r
253 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
\r
255 /* Barriers are normally not required but do ensure the code is completely
\r
256 within the specified behaviour for the architecture. */
\r
257 __asm volatile( "dsb" ::: "memory" );
\r
258 __asm volatile( "isb" );
\r
260 /*-----------------------------------------------------------*/
\r
262 void vPortEnterCritical( void )
\r
264 portDISABLE_INTERRUPTS();
\r
265 uxCriticalNesting++;
\r
266 __asm volatile( "dsb" ::: "memory" );
\r
267 __asm volatile( "isb" );
\r
269 /*-----------------------------------------------------------*/
\r
271 void vPortExitCritical( void )
\r
273 configASSERT( uxCriticalNesting );
\r
274 uxCriticalNesting--;
\r
275 if( uxCriticalNesting == 0 )
\r
277 portENABLE_INTERRUPTS();
\r
280 /*-----------------------------------------------------------*/
\r
282 uint32_t ulSetInterruptMaskFromISR( void )
\r
285 " mrs r0, PRIMASK \n"
\r
291 /*-----------------------------------------------------------*/
\r
293 void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask )
\r
296 " msr PRIMASK, r0 \n"
\r
301 /*-----------------------------------------------------------*/
\r
303 void xPortPendSVHandler( void )
\r
305 /* This is a naked function. */
\r
309 " .syntax unified \n"
\r
312 " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
\r
315 " subs r0, r0, #32 \n" /* Make space for the remaining low registers. */
\r
316 " str r0, [r2] \n" /* Save the new top of stack. */
\r
317 " stmia r0!, {r4-r7} \n" /* Store the low registers that are not saved automatically. */
\r
318 " mov r4, r8 \n" /* Store the high registers. */
\r
322 " stmia r0!, {r4-r7} \n"
\r
324 " push {r3, r14} \n"
\r
326 " bl vTaskSwitchContext \n"
\r
328 " pop {r2, r3} \n" /* lr goes in r3. r2 now holds tcb pointer. */
\r
331 " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
\r
332 " adds r0, r0, #16 \n" /* Move to the high registers. */
\r
333 " ldmia r0!, {r4-r7} \n" /* Pop the high registers. */
\r
339 " msr psp, r0 \n" /* Remember the new top of stack for the task. */
\r
341 " subs r0, r0, #32 \n" /* Go back for the low registers that are not automatically restored. */
\r
342 " ldmia r0!, {r4-r7} \n" /* Pop low registers. */
\r
347 "pxCurrentTCBConst: .word pxCurrentTCB "
\r
350 /*-----------------------------------------------------------*/
\r
352 void xPortSysTickHandler( void )
\r
354 uint32_t ulPreviousMask;
\r
356 ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
\r
358 /* Increment the RTOS tick. */
\r
359 if( xTaskIncrementTick() != pdFALSE )
\r
361 /* Pend a context switch. */
\r
362 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
\r
365 portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
\r
367 /*-----------------------------------------------------------*/
\r
370 * Setup the systick timer to generate the tick interrupts at the required
\r
373 void prvSetupTimerInterrupt( void )
\r
375 /* Calculate the constants required to configure the tick interrupt. */
\r
376 #if( configUSE_TICKLESS_IDLE == 1 )
\r
378 ulTimerCountsForOneTick = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ );
\r
379 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
\r
380 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;
\r
382 #endif /* configUSE_TICKLESS_IDLE */
\r
384 /* Stop and reset the SysTick. */
\r
385 portNVIC_SYSTICK_CTRL_REG = 0UL;
\r
386 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
\r
388 /* Configure SysTick to interrupt at the requested rate. */
\r
389 portNVIC_SYSTICK_LOAD_REG = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
\r
390 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
\r
392 /*-----------------------------------------------------------*/
\r
394 #if( configUSE_TICKLESS_IDLE == 1 )
\r
396 __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
\r
398 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
\r
399 TickType_t xModifiableIdleTime;
\r
401 /* Make sure the SysTick reload value does not overflow the counter. */
\r
402 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
\r
404 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
\r
407 /* Stop the SysTick momentarily. The time the SysTick is stopped for
\r
408 is accounted for as best it can be, but using the tickless mode will
\r
409 inevitably result in some tiny drift of the time maintained by the
\r
410 kernel with respect to calendar time. */
\r
411 portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
\r
413 /* Calculate the reload value required to wait xExpectedIdleTime
\r
414 tick periods. -1 is used because this code will execute part way
\r
415 through one of the tick periods. */
\r
416 ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
\r
417 if( ulReloadValue > ulStoppedTimerCompensation )
\r
419 ulReloadValue -= ulStoppedTimerCompensation;
\r
422 /* Enter a critical section but don't use the taskENTER_CRITICAL()
\r
423 method as that will mask interrupts that should exit sleep mode. */
\r
424 __asm volatile( "cpsid i" ::: "memory" );
\r
425 __asm volatile( "dsb" );
\r
426 __asm volatile( "isb" );
\r
428 /* If a context switch is pending or a task is waiting for the scheduler
\r
429 to be unsuspended then abandon the low power entry. */
\r
430 if( eTaskConfirmSleepModeStatus() == eAbortSleep )
\r
432 /* Restart from whatever is left in the count register to complete
\r
433 this tick period. */
\r
434 portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
\r
436 /* Restart SysTick. */
\r
437 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
\r
439 /* Reset the reload register to the value required for normal tick
\r
441 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
\r
443 /* Re-enable interrupts - see comments above the cpsid instruction()
\r
445 __asm volatile( "cpsie i" ::: "memory" );
\r
449 /* Set the new reload value. */
\r
450 portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
\r
452 /* Clear the SysTick count flag and set the count value back to
\r
454 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
\r
456 /* Restart SysTick. */
\r
457 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
\r
459 /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
\r
460 set its parameter to 0 to indicate that its implementation contains
\r
461 its own wait for interrupt or wait for event instruction, and so wfi
\r
462 should not be executed again. However, the original expected idle
\r
463 time variable must remain unmodified, so a copy is taken. */
\r
464 xModifiableIdleTime = xExpectedIdleTime;
\r
465 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
\r
466 if( xModifiableIdleTime > 0 )
\r
468 __asm volatile( "dsb" ::: "memory" );
\r
469 __asm volatile( "wfi" );
\r
470 __asm volatile( "isb" );
\r
472 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
\r
474 /* Re-enable interrupts to allow the interrupt that brought the MCU
\r
475 out of sleep mode to execute immediately. see comments above
\r
476 __disable_interrupt() call above. */
\r
477 __asm volatile( "cpsie i" ::: "memory" );
\r
478 __asm volatile( "dsb" );
\r
479 __asm volatile( "isb" );
\r
481 /* Disable interrupts again because the clock is about to be stopped
\r
482 and interrupts that execute while the clock is stopped will increase
\r
483 any slippage between the time maintained by the RTOS and calendar
\r
485 __asm volatile( "cpsid i" ::: "memory" );
\r
486 __asm volatile( "dsb" );
\r
487 __asm volatile( "isb" );
\r
489 /* Disable the SysTick clock without reading the
\r
490 portNVIC_SYSTICK_CTRL_REG register to ensure the
\r
491 portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
\r
492 the time the SysTick is stopped for is accounted for as best it can
\r
493 be, but using the tickless mode will inevitably result in some tiny
\r
494 drift of the time maintained by the kernel with respect to calendar
\r
496 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
\r
498 /* Determine if the SysTick clock has already counted to zero and
\r
499 been set back to the current reload value (the reload back being
\r
500 correct for the entire expected idle time) or if the SysTick is yet
\r
501 to count to zero (in which case an interrupt other than the SysTick
\r
502 must have brought the system out of sleep mode). */
\r
503 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
\r
505 uint32_t ulCalculatedLoadValue;
\r
507 /* The tick interrupt is already pending, and the SysTick count
\r
508 reloaded with ulReloadValue. Reset the
\r
509 portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
\r
511 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
\r
513 /* Don't allow a tiny value, or values that have somehow
\r
514 underflowed because the post sleep hook did something
\r
515 that took too long. */
\r
516 if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
\r
518 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
\r
521 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
\r
523 /* As the pending tick will be processed as soon as this
\r
524 function exits, the tick value maintained by the tick is stepped
\r
525 forward by one less than the time spent waiting. */
\r
526 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
\r
530 /* Something other than the tick interrupt ended the sleep.
\r
531 Work out how long the sleep lasted rounded to complete tick
\r
532 periods (not the ulReload value which accounted for part
\r
534 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
\r
536 /* How many complete tick periods passed while the processor
\r
538 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
\r
540 /* The reload value is set to whatever fraction of a single tick
\r
542 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
\r
545 /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
\r
546 again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
\r
548 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
\r
549 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
\r
550 vTaskStepTick( ulCompleteTickPeriods );
\r
551 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
\r
553 /* Exit with interrpts enabled. */
\r
554 __asm volatile( "cpsie i" ::: "memory" );
\r
558 #endif /* configUSE_TICKLESS_IDLE */
\r