1 /*
2 * FreeRTOS Kernel V10.6.2
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 /* IAR includes. */
34 #include <intrinsics.h>
35
36 /* Scheduler includes. */
37 #include "FreeRTOS.h"
38 #include "task.h"
39
40 #if ( configMAX_SYSCALL_INTERRUPT_PRIORITY == 0 )
41 #error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. See http: /*www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
42 #endif
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_SHPR3_REG ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
49 /* ...then bits in the registers. */
50 #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
51 #define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
52 #define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
53 #define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
54 #define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
55 #define portNVIC_PEND_SYSTICK_SET_BIT ( 1UL << 26UL )
56 #define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
57
58 #define portMIN_INTERRUPT_PRIORITY ( 255UL )
59 #define portNVIC_PENDSV_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
60 #define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
61
62 /* Constants required to check the validity of an interrupt priority. */
63 #define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
64 #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
65 #define portAIRCR_REG ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
66 #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
67 #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
68 #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
69 #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
70 #define portPRIGROUP_SHIFT ( 8UL )
71
72 /* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
73 #define portVECTACTIVE_MASK ( 0xFFUL )
74
75 /* Constants required to set up the initial stack. */
76 #define portINITIAL_XPSR ( 0x01000000 )
77
78 /* The systick is a 24-bit counter. */
79 #define portMAX_24_BIT_NUMBER ( 0xffffffUL )
80
81 /* A fiddle factor to estimate the number of SysTick counts that would have
82 * occurred while the SysTick counter is stopped during tickless idle
83 * calculations. */
84 #define portMISSED_COUNTS_FACTOR ( 94UL )
85
86 /* For strict compliance with the Cortex-M spec the task start address should
87 * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
88 #define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
89
90 /* Let the user override the default SysTick clock rate. If defined by the
91 * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
92 * configuration register. */
93 #ifndef configSYSTICK_CLOCK_HZ
94 #define configSYSTICK_CLOCK_HZ ( configCPU_CLOCK_HZ )
95 /* Ensure the SysTick is clocked at the same frequency as the core. */
96 #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( portNVIC_SYSTICK_CLK_BIT )
97 #else
98 /* Select the option to clock SysTick not at the same frequency as the core. */
99 #define portNVIC_SYSTICK_CLK_BIT_CONFIG ( 0 )
100 #endif
101
102 /*
103 * Setup the timer to generate the tick interrupts. The implementation in this
104 * file is weak to allow application writers to change the timer used to
105 * generate the tick interrupt.
106 */
107 void vPortSetupTimerInterrupt( void );
108
109 /*
110 * Exception handlers.
111 */
112 void xPortSysTickHandler( void );
113
114 /*
115 * Start first task is a separate function so it can be tested in isolation.
116 */
117 extern void vPortStartFirstTask( void );
118
119 /*
120 * Used to catch tasks that attempt to return from their implementing function.
121 */
122 static void prvTaskExitError( void );
123
124 /*-----------------------------------------------------------*/
125
126 /* Each task maintains its own interrupt status in the critical nesting
127 * variable. */
128 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
129
130 /*
131 * The number of SysTick increments that make up one tick period.
132 */
133 #if ( configUSE_TICKLESS_IDLE == 1 )
134 static uint32_t ulTimerCountsForOneTick = 0;
135 #endif /* configUSE_TICKLESS_IDLE */
136
137 /*
138 * The maximum number of tick periods that can be suppressed is limited by the
139 * 24 bit resolution of the SysTick timer.
140 */
141 #if ( configUSE_TICKLESS_IDLE == 1 )
142 static uint32_t xMaximumPossibleSuppressedTicks = 0;
143 #endif /* configUSE_TICKLESS_IDLE */
144
145 /*
146 * Compensate for the CPU cycles that pass while the SysTick is stopped (low
147 * power functionality only.
148 */
149 #if ( configUSE_TICKLESS_IDLE == 1 )
150 static uint32_t ulStoppedTimerCompensation = 0;
151 #endif /* configUSE_TICKLESS_IDLE */
152
153 /*
154 * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
155 * FreeRTOS API functions are not called from interrupts that have been assigned
156 * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
157 */
158 #if ( configASSERT_DEFINED == 1 )
159 static uint8_t ucMaxSysCallPriority = 0;
160 static uint32_t ulMaxPRIGROUPValue = 0;
161 static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
162 #endif /* configASSERT_DEFINED */
163
164 /*-----------------------------------------------------------*/
165
166 /*
167 * See header file for description.
168 */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)169 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
170 TaskFunction_t pxCode,
171 void * pvParameters )
172 {
173 /* Simulate the stack frame as it would be created by a context switch
174 * interrupt. */
175 pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
176 *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
177 pxTopOfStack--;
178 *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
179 pxTopOfStack--;
180 *pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
181 pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
182 *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
183 pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
184
185 return pxTopOfStack;
186 }
187 /*-----------------------------------------------------------*/
188
prvTaskExitError(void)189 static void prvTaskExitError( void )
190 {
191 /* A function that implements a task must not exit or attempt to return to
192 * its caller as there is nothing to return to. If a task wants to exit it
193 * should instead call vTaskDelete( NULL ).
194 *
195 * Artificially force an assert() to be triggered if configASSERT() is
196 * defined, then stop here so application writers can catch the error. */
197 configASSERT( uxCriticalNesting == ~0UL );
198 portDISABLE_INTERRUPTS();
199
200 for( ; ; )
201 {
202 }
203 }
204 /*-----------------------------------------------------------*/
205
206 /*
207 * See header file for description.
208 */
xPortStartScheduler(void)209 BaseType_t xPortStartScheduler( void )
210 {
211 #if ( configASSERT_DEFINED == 1 )
212 {
213 volatile uint8_t ucOriginalPriority;
214 volatile uint32_t ulImplementedPrioBits = 0;
215 volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
216 volatile uint8_t ucMaxPriorityValue;
217
218 /* Determine the maximum priority from which ISR safe FreeRTOS API
219 * functions can be called. ISR safe functions are those that end in
220 * "FromISR". FreeRTOS maintains separate thread and ISR API functions to
221 * ensure interrupt entry is as fast and simple as possible.
222 *
223 * Save the interrupt priority value that is about to be clobbered. */
224 ucOriginalPriority = *pucFirstUserPriorityRegister;
225
226 /* Determine the number of priority bits available. First write to all
227 * possible bits. */
228 *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
229
230 /* Read the value back to see how many bits stuck. */
231 ucMaxPriorityValue = *pucFirstUserPriorityRegister;
232
233 /* Use the same mask on the maximum system call priority. */
234 ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
235
236 /* Check that the maximum system call priority is nonzero after
237 * accounting for the number of priority bits supported by the
238 * hardware. A priority of 0 is invalid because setting the BASEPRI
239 * register to 0 unmasks all interrupts, and interrupts with priority 0
240 * cannot be masked using BASEPRI.
241 * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
242 configASSERT( ucMaxSysCallPriority );
243
244 /* Check that the bits not implemented in hardware are zero in
245 * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
246 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
247
248 /* Calculate the maximum acceptable priority group value for the number
249 * of bits read back. */
250
251 while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
252 {
253 ulImplementedPrioBits++;
254 ucMaxPriorityValue <<= ( uint8_t ) 0x01;
255 }
256
257 if( ulImplementedPrioBits == 8 )
258 {
259 /* When the hardware implements 8 priority bits, there is no way for
260 * the software to configure PRIGROUP to not have sub-priorities. As
261 * a result, the least significant bit is always used for sub-priority
262 * and there are 128 preemption priorities and 2 sub-priorities.
263 *
264 * This may cause some confusion in some cases - for example, if
265 * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
266 * priority interrupts will be masked in Critical Sections as those
267 * are at the same preemption priority. This may appear confusing as
268 * 4 is higher (numerically lower) priority than
269 * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
270 * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
271 * to 4, this confusion does not happen and the behaviour remains the same.
272 *
273 * The following assert ensures that the sub-priority bit in the
274 * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
275 * confusion. */
276 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
277 ulMaxPRIGROUPValue = 0;
278 }
279 else
280 {
281 ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
282 }
283
284 /* Shift the priority group value back to its position within the AIRCR
285 * register. */
286 ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
287 ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
288
289 /* Restore the clobbered interrupt priority register to its original
290 * value. */
291 *pucFirstUserPriorityRegister = ucOriginalPriority;
292 }
293 #endif /* configASSERT_DEFINED */
294
295 /* Make PendSV and SysTick the lowest priority interrupts. */
296 portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
297 portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
298
299 /* Start the timer that generates the tick ISR. Interrupts are disabled
300 * here already. */
301 vPortSetupTimerInterrupt();
302
303 /* Initialise the critical nesting count ready for the first task. */
304 uxCriticalNesting = 0;
305
306 /* Start the first task. */
307 vPortStartFirstTask();
308
309 /* Should not get here! */
310 return 0;
311 }
312 /*-----------------------------------------------------------*/
313
vPortEndScheduler(void)314 void vPortEndScheduler( void )
315 {
316 /* Not implemented in ports where there is nothing to return to.
317 * Artificially force an assert. */
318 configASSERT( uxCriticalNesting == 1000UL );
319 }
320 /*-----------------------------------------------------------*/
321
vPortEnterCritical(void)322 void vPortEnterCritical( void )
323 {
324 portDISABLE_INTERRUPTS();
325 uxCriticalNesting++;
326
327 /* This is not the interrupt safe version of the enter critical function so
328 * assert() if it is being called from an interrupt context. Only API
329 * functions that end in "FromISR" can be used in an interrupt. Only assert if
330 * the critical nesting count is 1 to protect against recursive calls if the
331 * assert function also uses a critical section. */
332 if( uxCriticalNesting == 1 )
333 {
334 configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
335 }
336 }
337 /*-----------------------------------------------------------*/
338
vPortExitCritical(void)339 void vPortExitCritical( void )
340 {
341 configASSERT( uxCriticalNesting );
342 uxCriticalNesting--;
343
344 if( uxCriticalNesting == 0 )
345 {
346 portENABLE_INTERRUPTS();
347 }
348 }
349 /*-----------------------------------------------------------*/
350
xPortSysTickHandler(void)351 void xPortSysTickHandler( void )
352 {
353 /* The SysTick runs at the lowest interrupt priority, so when this interrupt
354 * executes all interrupts must be unmasked. There is therefore no need to
355 * save and then restore the interrupt mask value as its value is already
356 * known. */
357 portDISABLE_INTERRUPTS();
358 {
359 /* Increment the RTOS tick. */
360 if( xTaskIncrementTick() != pdFALSE )
361 {
362 /* A context switch is required. Context switching is performed in
363 * the PendSV interrupt. Pend the PendSV interrupt. */
364 portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
365 }
366 }
367 portENABLE_INTERRUPTS();
368 }
369 /*-----------------------------------------------------------*/
370
371 #if ( configUSE_TICKLESS_IDLE == 1 )
372
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)373 __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
374 {
375 uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
376 TickType_t xModifiableIdleTime;
377
378 /* Make sure the SysTick reload value does not overflow the counter. */
379 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
380 {
381 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
382 }
383
384 /* Enter a critical section but don't use the taskENTER_CRITICAL()
385 * method as that will mask interrupts that should exit sleep mode. */
386 __disable_interrupt();
387 __DSB();
388 __ISB();
389
390 /* If a context switch is pending or a task is waiting for the scheduler
391 * to be unsuspended then abandon the low power entry. */
392 if( eTaskConfirmSleepModeStatus() == eAbortSleep )
393 {
394 /* Re-enable interrupts - see comments above the __disable_interrupt()
395 * call above. */
396 __enable_interrupt();
397 }
398 else
399 {
400 /* Stop the SysTick momentarily. The time the SysTick is stopped for
401 * is accounted for as best it can be, but using the tickless mode will
402 * inevitably result in some tiny drift of the time maintained by the
403 * kernel with respect to calendar time. */
404 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
405
406 /* Use the SysTick current-value register to determine the number of
407 * SysTick decrements remaining until the next tick interrupt. If the
408 * current-value register is zero, then there are actually
409 * ulTimerCountsForOneTick decrements remaining, not zero, because the
410 * SysTick requests the interrupt when decrementing from 1 to 0. */
411 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
412
413 if( ulSysTickDecrementsLeft == 0 )
414 {
415 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
416 }
417
418 /* Calculate the reload value required to wait xExpectedIdleTime
419 * tick periods. -1 is used because this code normally executes part
420 * way through the first tick period. But if the SysTick IRQ is now
421 * pending, then clear the IRQ, suppressing the first tick, and correct
422 * the reload value to reflect that the second tick period is already
423 * underway. The expected idle time is always at least two ticks. */
424 ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
425
426 if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
427 {
428 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
429 ulReloadValue -= ulTimerCountsForOneTick;
430 }
431
432 if( ulReloadValue > ulStoppedTimerCompensation )
433 {
434 ulReloadValue -= ulStoppedTimerCompensation;
435 }
436
437 /* Set the new reload value. */
438 portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
439
440 /* Clear the SysTick count flag and set the count value back to
441 * zero. */
442 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
443
444 /* Restart SysTick. */
445 portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
446
447 /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
448 * set its parameter to 0 to indicate that its implementation contains
449 * its own wait for interrupt or wait for event instruction, and so wfi
450 * should not be executed again. However, the original expected idle
451 * time variable must remain unmodified, so a copy is taken. */
452 xModifiableIdleTime = xExpectedIdleTime;
453 configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
454
455 if( xModifiableIdleTime > 0 )
456 {
457 __DSB();
458 __WFI();
459 __ISB();
460 }
461
462 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
463
464 /* Re-enable interrupts to allow the interrupt that brought the MCU
465 * out of sleep mode to execute immediately. See comments above
466 * the __disable_interrupt() call above. */
467 __enable_interrupt();
468 __DSB();
469 __ISB();
470
471 /* Disable interrupts again because the clock is about to be stopped
472 * and interrupts that execute while the clock is stopped will increase
473 * any slippage between the time maintained by the RTOS and calendar
474 * time. */
475 __disable_interrupt();
476 __DSB();
477 __ISB();
478
479 /* Disable the SysTick clock without reading the
480 * portNVIC_SYSTICK_CTRL_REG register to ensure the
481 * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
482 * the time the SysTick is stopped for is accounted for as best it can
483 * be, but using the tickless mode will inevitably result in some tiny
484 * drift of the time maintained by the kernel with respect to calendar
485 * time*/
486 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
487
488 /* Determine whether the SysTick has already counted to zero. */
489 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
490 {
491 uint32_t ulCalculatedLoadValue;
492
493 /* The tick interrupt ended the sleep (or is now pending), and
494 * a new tick period has started. Reset portNVIC_SYSTICK_LOAD_REG
495 * with whatever remains of the new tick period. */
496 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
497
498 /* Don't allow a tiny value, or values that have somehow
499 * underflowed because the post sleep hook did something
500 * that took too long or because the SysTick current-value register
501 * is zero. */
502 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
503 {
504 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
505 }
506
507 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
508
509 /* As the pending tick will be processed as soon as this
510 * function exits, the tick value maintained by the tick is stepped
511 * forward by one less than the time spent waiting. */
512 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
513 }
514 else
515 {
516 /* Something other than the tick interrupt ended the sleep. */
517
518 /* Use the SysTick current-value register to determine the
519 * number of SysTick decrements remaining until the expected idle
520 * time would have ended. */
521 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
522 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
523 {
524 /* If the SysTick is not using the core clock, the current-
525 * value register might still be zero here. In that case, the
526 * SysTick didn't load from the reload register, and there are
527 * ulReloadValue decrements remaining in the expected idle
528 * time, not zero. */
529 if( ulSysTickDecrementsLeft == 0 )
530 {
531 ulSysTickDecrementsLeft = ulReloadValue;
532 }
533 }
534 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
535
536 /* Work out how long the sleep lasted rounded to complete tick
537 * periods (not the ulReload value which accounted for part
538 * ticks). */
539 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
540
541 /* How many complete tick periods passed while the processor
542 * was waiting? */
543 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
544
545 /* The reload value is set to whatever fraction of a single tick
546 * period remains. */
547 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
548 }
549
550 /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
551 * then set portNVIC_SYSTICK_LOAD_REG back to its standard value. If
552 * the SysTick is not using the core clock, temporarily configure it to
553 * use the core clock. This configuration forces the SysTick to load
554 * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
555 * cycle of the other clock. Then portNVIC_SYSTICK_LOAD_REG is ready
556 * to receive the standard value immediately. */
557 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
558 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
559 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
560 {
561 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
562 }
563 #else
564 {
565 /* The temporary usage of the core clock has served its purpose,
566 * as described above. Resume usage of the other clock. */
567 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
568
569 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
570 {
571 /* The partial tick period already ended. Be sure the SysTick
572 * counts it only once. */
573 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
574 }
575
576 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
577 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
578 }
579 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
580
581 /* Step the tick to account for any tick periods that elapsed. */
582 vTaskStepTick( ulCompleteTickPeriods );
583
584 /* Exit with interrupts enabled. */
585 __enable_interrupt();
586 }
587 }
588
589 #endif /* configUSE_TICKLESS_IDLE */
590 /*-----------------------------------------------------------*/
591
592 /*
593 * Setup the systick timer to generate the tick interrupts at the required
594 * frequency.
595 */
vPortSetupTimerInterrupt(void)596 __weak void vPortSetupTimerInterrupt( void )
597 {
598 /* Calculate the constants required to configure the tick interrupt. */
599 #if ( configUSE_TICKLESS_IDLE == 1 )
600 {
601 ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
602 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
603 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
604 }
605 #endif /* configUSE_TICKLESS_IDLE */
606
607 /* Stop and clear the SysTick. */
608 portNVIC_SYSTICK_CTRL_REG = 0UL;
609 portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
610
611 /* Configure SysTick to interrupt at the requested rate. */
612 portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
613 portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
614 }
615 /*-----------------------------------------------------------*/
616
617 #if ( configASSERT_DEFINED == 1 )
618
vPortValidateInterruptPriority(void)619 void vPortValidateInterruptPriority( void )
620 {
621 uint32_t ulCurrentInterrupt;
622 uint8_t ucCurrentPriority;
623
624 /* Obtain the number of the currently executing interrupt. */
625 __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
626
627 /* Is the interrupt number a user defined interrupt? */
628 if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
629 {
630 /* Look up the interrupt's priority. */
631 ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
632
633 /* The following assertion will fail if a service routine (ISR) for
634 * an interrupt that has been assigned a priority above
635 * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
636 * function. ISR safe FreeRTOS API functions must *only* be called
637 * from interrupts that have been assigned a priority at or below
638 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
639 *
640 * Numerically low interrupt priority numbers represent logically high
641 * interrupt priorities, therefore the priority of the interrupt must
642 * be set to a value equal to or numerically *higher* than
643 * configMAX_SYSCALL_INTERRUPT_PRIORITY.
644 *
645 * Interrupts that use the FreeRTOS API must not be left at their
646 * default priority of zero as that is the highest possible priority,
647 * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
648 * and therefore also guaranteed to be invalid.
649 *
650 * FreeRTOS maintains separate thread and ISR API functions to ensure
651 * interrupt entry is as fast and simple as possible.
652 *
653 * The following links provide detailed information:
654 * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
655 * https://www.FreeRTOS.org/FAQHelp.html */
656 configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
657 }
658
659 /* Priority grouping: The interrupt controller (NVIC) allows the bits
660 * that define each interrupt's priority to be split between bits that
661 * define the interrupt's pre-emption priority bits and bits that define
662 * the interrupt's sub-priority. For simplicity all bits must be defined
663 * to be pre-emption priority bits. The following assertion will fail if
664 * this is not the case (if some bits represent a sub-priority).
665 *
666 * If the application only uses CMSIS libraries for interrupt
667 * configuration then the correct setting can be achieved on all Cortex-M
668 * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
669 * scheduler. Note however that some vendor specific peripheral libraries
670 * assume a non-zero priority group setting, in which cases using a value
671 * of zero will result in unpredictable behaviour. */
672 configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
673 }
674
675 #endif /* configASSERT_DEFINED */
676