1 /*
2  * FreeRTOS Kernel V11.1.0
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 CM0 port.
31 *----------------------------------------------------------*/
32 
33 /* Scheduler includes. */
34 #include "FreeRTOS.h"
35 #include "task.h"
36 
37 /* Constants required to manipulate the NVIC. */
38 #define portNVIC_SYSTICK_CTRL_REG             ( *( ( volatile uint32_t * ) 0xe000e010 ) )
39 #define portNVIC_SYSTICK_LOAD_REG             ( *( ( volatile uint32_t * ) 0xe000e014 ) )
40 #define portNVIC_SYSTICK_CURRENT_VALUE_REG    ( *( ( volatile uint32_t * ) 0xe000e018 ) )
41 #define portNVIC_INT_CTRL_REG                 ( *( ( volatile uint32_t * ) 0xe000ed04 ) )
42 #define portNVIC_SHPR3_REG                    ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
43 #define portNVIC_SYSTICK_CLK_BIT              ( 1UL << 2UL )
44 #define portNVIC_SYSTICK_INT_BIT              ( 1UL << 1UL )
45 #define portNVIC_SYSTICK_ENABLE_BIT           ( 1UL << 0UL )
46 #define portNVIC_SYSTICK_COUNT_FLAG_BIT       ( 1UL << 16UL )
47 #define portNVIC_PENDSVSET_BIT                ( 1UL << 28UL )
48 #define portNVIC_PEND_SYSTICK_SET_BIT         ( 1UL << 26UL )
49 #define portNVIC_PEND_SYSTICK_CLEAR_BIT       ( 1UL << 25UL )
50 #define portMIN_INTERRUPT_PRIORITY            ( 255UL )
51 #define portNVIC_PENDSV_PRI                   ( portMIN_INTERRUPT_PRIORITY << 16UL )
52 #define portNVIC_SYSTICK_PRI                  ( portMIN_INTERRUPT_PRIORITY << 24UL )
53 
54 /* Constants required to set up the initial stack. */
55 #define portINITIAL_XPSR                      ( 0x01000000 )
56 
57 /* The systick is a 24-bit counter. */
58 #define portMAX_24_BIT_NUMBER                 ( 0xffffffUL )
59 
60 /* A fiddle factor to estimate the number of SysTick counts that would have
61  * occurred while the SysTick counter is stopped during tickless idle
62  * calculations. */
63 #ifndef portMISSED_COUNTS_FACTOR
64     #define portMISSED_COUNTS_FACTOR    ( 94UL )
65 #endif
66 
67 /* Constants used with memory barrier intrinsics. */
68 #define portSY_FULL_READ_WRITE    ( 15 )
69 
70 /* Let the user override the default SysTick clock rate.  If defined by the
71  * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
72  * configuration register. */
73 #ifndef configSYSTICK_CLOCK_HZ
74     #define configSYSTICK_CLOCK_HZ             ( configCPU_CLOCK_HZ )
75     /* Ensure the SysTick is clocked at the same frequency as the core. */
76     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( portNVIC_SYSTICK_CLK_BIT )
77 #else
78     /* Select the option to clock SysTick not at the same frequency as the core. */
79     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( 0 )
80 #endif
81 
82 /* Legacy macro for backward compatibility only.  This macro used to be used to
83  * replace the function that configures the clock used to generate the tick
84  * interrupt (prvSetupTimerInterrupt()), but now the function is declared weak so
85  * the application writer can override it by simply defining a function of the
86  * same name (vApplicationSetupTickInterrupt()). */
87 #ifndef configOVERRIDE_DEFAULT_TICK_CONFIGURATION
88     #define configOVERRIDE_DEFAULT_TICK_CONFIGURATION    0
89 #endif
90 
91 /* Each task maintains its own interrupt status in the critical nesting
92  * variable. */
93 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
94 
95 /* The number of SysTick increments that make up one tick period. */
96 #if ( configUSE_TICKLESS_IDLE == 1 )
97     static uint32_t ulTimerCountsForOneTick = 0;
98 #endif /* configUSE_TICKLESS_IDLE */
99 
100 /* The maximum number of tick periods that can be suppressed is limited by the
101  * 24 bit resolution of the SysTick timer. */
102 #if ( configUSE_TICKLESS_IDLE == 1 )
103     static uint32_t xMaximumPossibleSuppressedTicks = 0;
104 #endif /* configUSE_TICKLESS_IDLE */
105 
106 /* Compensate for the CPU cycles that pass while the SysTick is stopped (low
107  * power functionality only.
108  */
109 #if ( configUSE_TICKLESS_IDLE == 1 )
110     static uint32_t ulStoppedTimerCompensation = 0;
111 #endif /* configUSE_TICKLESS_IDLE */
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 );
124 void xPortSysTickHandler( void );
125 void vPortSVCHandler( void );
126 
127 /*
128  * Start first task is a separate function so it can be tested in isolation.
129  */
130 static void prvPortStartFirstTask( void );
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 /*
140  * See header file for description.
141  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)142 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
143                                      TaskFunction_t pxCode,
144                                      void * pvParameters )
145 {
146     /* Simulate the stack frame as it would be created by a context switch
147      * interrupt. */
148     pxTopOfStack--;                                   /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
149     *pxTopOfStack = portINITIAL_XPSR;                 /* xPSR */
150     pxTopOfStack--;
151     *pxTopOfStack = ( StackType_t ) pxCode;           /* PC */
152     pxTopOfStack--;
153     *pxTopOfStack = ( StackType_t ) prvTaskExitError; /* LR */
154     pxTopOfStack -= 5;                                /* R12, R3, R2 and R1. */
155     *pxTopOfStack = ( StackType_t ) pvParameters;     /* R0 */
156     pxTopOfStack -= 8;                                /* R11..R4. */
157 
158     return pxTopOfStack;
159 }
160 /*-----------------------------------------------------------*/
161 
prvTaskExitError(void)162 static void prvTaskExitError( void )
163 {
164     /* A function that implements a task must not exit or attempt to return to
165      * its caller as there is nothing to return to.  If a task wants to exit it
166      * should instead call vTaskDelete( NULL ).
167      *
168      * Artificially force an assert() to be triggered if configASSERT() is
169      * defined, then stop here so application writers can catch the error. */
170     configASSERT( uxCriticalNesting == ~0UL );
171     portDISABLE_INTERRUPTS();
172 
173     for( ; ; )
174     {
175     }
176 }
177 /*-----------------------------------------------------------*/
178 
vPortSVCHandler(void)179 void vPortSVCHandler( void )
180 {
181     /* This function is no longer used, but retained for backward
182      * compatibility. */
183 }
184 /*-----------------------------------------------------------*/
185 
prvPortStartFirstTask(void)186 __asm void prvPortStartFirstTask( void )
187 {
188     extern pxCurrentTCB;
189 
190     PRESERVE8
191 
192     /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector
193      * table offset register that can be used to locate the initial stack value.
194      * Not all M0 parts have the application vector table at address 0. */
195 /* *INDENT-OFF* */
196 
197     ldr r3, = pxCurrentTCB /* Obtain location of pxCurrentTCB. */
198     ldr r1, [ r3 ]
199     ldr r0, [ r1 ]         /* The first item in pxCurrentTCB is the task top of stack. */
200     adds r0, # 32          /* Discard everything up to r0. */
201     msr psp, r0            /* This is now the new top of stack to use in the task. */
202     movs r0, # 2           /* Switch to the psp stack. */
203     msr CONTROL, r0
204     isb
205     pop { r0 - r5 } /* Pop the registers that are saved automatically. */
206     mov lr, r5 /* lr is now in r5. */
207     pop { r3 } /* The return address is now in r3. */
208     pop { r2 } /* Pop and discard the XPSR. */
209     cpsie i /* The first task has its context and interrupts can be enabled. */
210     bx r3 /* Finally, jump to the user defined task code. */
211 
212     ALIGN
213 /* *INDENT-ON* */
214 }
215 /*-----------------------------------------------------------*/
216 
217 /*
218  * See header file for description.
219  */
xPortStartScheduler(void)220 BaseType_t xPortStartScheduler( void )
221 {
222     /* Make PendSV, CallSV and SysTick the same priority as the kernel. */
223     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
224 
225     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
226 
227     /* Start the timer that generates the tick ISR.  Interrupts are disabled
228      * here already. */
229     vPortSetupTimerInterrupt();
230 
231     /* Initialise the critical nesting count ready for the first task. */
232     uxCriticalNesting = 0;
233 
234     /* Start the first task. */
235     prvPortStartFirstTask();
236 
237     /* Should not get here! */
238     return 0;
239 }
240 /*-----------------------------------------------------------*/
241 
vPortEndScheduler(void)242 void vPortEndScheduler( void )
243 {
244     /* Not implemented in ports where there is nothing to return to.
245      * Artificially force an assert. */
246     configASSERT( uxCriticalNesting == 1000UL );
247 }
248 /*-----------------------------------------------------------*/
249 
vPortYield(void)250 void vPortYield( void )
251 {
252     /* Set a PendSV to request a context switch. */
253     portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
254 
255     /* Barriers are normally not required but do ensure the code is completely
256      * within the specified behaviour for the architecture. */
257     __dsb( portSY_FULL_READ_WRITE );
258     __isb( portSY_FULL_READ_WRITE );
259 }
260 /*-----------------------------------------------------------*/
261 
vPortEnterCritical(void)262 void vPortEnterCritical( void )
263 {
264     portDISABLE_INTERRUPTS();
265     uxCriticalNesting++;
266     __dsb( portSY_FULL_READ_WRITE );
267     __isb( portSY_FULL_READ_WRITE );
268 }
269 /*-----------------------------------------------------------*/
270 
vPortExitCritical(void)271 void vPortExitCritical( void )
272 {
273     configASSERT( uxCriticalNesting );
274     uxCriticalNesting--;
275 
276     if( uxCriticalNesting == 0 )
277     {
278         portENABLE_INTERRUPTS();
279     }
280 }
281 /*-----------------------------------------------------------*/
282 
ulSetInterruptMaskFromISR(void)283 __asm uint32_t ulSetInterruptMaskFromISR( void )
284 {
285 /* *INDENT-OFF* */
286     mrs r0, PRIMASK
287     cpsid i
288     bx lr
289 /* *INDENT-ON* */
290 }
291 /*-----------------------------------------------------------*/
292 
vClearInterruptMaskFromISR(uint32_t ulMask)293 __asm void vClearInterruptMaskFromISR( uint32_t ulMask )
294 {
295 /* *INDENT-OFF* */
296     msr PRIMASK, r0
297     bx lr
298 /* *INDENT-ON* */
299 }
300 /*-----------------------------------------------------------*/
301 
xPortPendSVHandler(void)302 __asm void xPortPendSVHandler( void )
303 {
304     extern vTaskSwitchContext
305     extern pxCurrentTCB
306 
307 /* *INDENT-OFF* */
308     PRESERVE8
309 
310     mrs r0, psp
311 
312     ldr r3, = pxCurrentTCB /* Get the location of the current TCB. */
313     ldr r2, [ r3 ]
314 
315     subs r0, # 32  /* Make space for the remaining low registers. */
316     str r0, [ r2 ] /* Save the new top of stack. */
317     stmia r0 !, { r4 - r7 } /* Store the low registers that are not saved automatically. */
318     mov r4, r8 /* Store the high registers. */
319     mov r5, r9
320     mov r6, r10
321     mov r7, r11
322     stmia r0 !, { r4 - r7 }
323 
324     push { r3, r14 }
325     cpsid i
326     bl vTaskSwitchContext
327     cpsie i
328     pop { r2, r3 } /* lr goes in r3. r2 now holds tcb pointer. */
329 
330     ldr r1, [ r2 ]
331     ldr r0, [ r1 ] /* The first item in pxCurrentTCB is the task top of stack. */
332     adds r0, # 16  /* Move to the high registers. */
333     ldmia r0 !, { r4 - r7 } /* Pop the high registers. */
334     mov r8, r4
335     mov r9, r5
336     mov r10, r6
337     mov r11, r7
338 
339     msr psp, r0   /* Remember the new top of stack for the task. */
340 
341     subs r0, # 32 /* Go back for the low registers that are not automatically restored. */
342     ldmia r0 !, { r4 - r7 } /* Pop low registers.  */
343 
344     bx r3
345     ALIGN
346 /* *INDENT-ON* */
347 }
348 /*-----------------------------------------------------------*/
349 
xPortSysTickHandler(void)350 void xPortSysTickHandler( void )
351 {
352     uint32_t ulPreviousMask;
353 
354     ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
355     traceISR_ENTER();
356     {
357         /* Increment the RTOS tick. */
358         if( xTaskIncrementTick() != pdFALSE )
359         {
360             traceISR_EXIT_TO_SCHEDULER();
361             /* Pend a context switch. */
362             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
363         }
364         else
365         {
366             traceISR_EXIT();
367         }
368     }
369     portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
370 }
371 /*-----------------------------------------------------------*/
372 
373 /*
374  * Setup the systick timer to generate the tick interrupts at the required
375  * frequency.
376  */
377 #if ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 )
378 
vPortSetupTimerInterrupt(void)379     __weak void vPortSetupTimerInterrupt( void )
380     {
381         /* Calculate the constants required to configure the tick interrupt. */
382         #if ( configUSE_TICKLESS_IDLE == 1 )
383         {
384             ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
385             xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
386             ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
387         }
388         #endif /* configUSE_TICKLESS_IDLE */
389 
390         /* Stop and clear the SysTick. */
391         portNVIC_SYSTICK_CTRL_REG = 0UL;
392         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
393 
394         /* Configure SysTick to interrupt at the requested rate. */
395         portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
396         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
397     }
398 
399 #endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
400 /*-----------------------------------------------------------*/
401 
402 #if ( configUSE_TICKLESS_IDLE == 1 )
403 
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)404     __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
405     {
406         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
407         TickType_t xModifiableIdleTime;
408 
409         /* Make sure the SysTick reload value does not overflow the counter. */
410         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
411         {
412             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
413         }
414 
415         /* Enter a critical section but don't use the taskENTER_CRITICAL()
416          * method as that will mask interrupts that should exit sleep mode. */
417         __disable_irq();
418         __dsb( portSY_FULL_READ_WRITE );
419         __isb( portSY_FULL_READ_WRITE );
420 
421         /* If a context switch is pending or a task is waiting for the scheduler
422          * to be unsuspended then abandon the low power entry. */
423         if( eTaskConfirmSleepModeStatus() == eAbortSleep )
424         {
425             /* Re-enable interrupts - see comments above the __disable_irq()
426              * call above. */
427             __enable_irq();
428         }
429         else
430         {
431             /* Stop the SysTick momentarily.  The time the SysTick is stopped for
432              * is accounted for as best it can be, but using the tickless mode will
433              * inevitably result in some tiny drift of the time maintained by the
434              * kernel with respect to calendar time. */
435             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
436 
437             /* Use the SysTick current-value register to determine the number of
438              * SysTick decrements remaining until the next tick interrupt.  If the
439              * current-value register is zero, then there are actually
440              * ulTimerCountsForOneTick decrements remaining, not zero, because the
441              * SysTick requests the interrupt when decrementing from 1 to 0. */
442             ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
443 
444             if( ulSysTickDecrementsLeft == 0 )
445             {
446                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
447             }
448 
449             /* Calculate the reload value required to wait xExpectedIdleTime
450              * tick periods.  -1 is used because this code normally executes part
451              * way through the first tick period.  But if the SysTick IRQ is now
452              * pending, then clear the IRQ, suppressing the first tick, and correct
453              * the reload value to reflect that the second tick period is already
454              * underway.  The expected idle time is always at least two ticks. */
455             ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
456 
457             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
458             {
459                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
460                 ulReloadValue -= ulTimerCountsForOneTick;
461             }
462 
463             if( ulReloadValue > ulStoppedTimerCompensation )
464             {
465                 ulReloadValue -= ulStoppedTimerCompensation;
466             }
467 
468             /* Set the new reload value. */
469             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
470 
471             /* Clear the SysTick count flag and set the count value back to
472              * zero. */
473             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
474 
475             /* Restart SysTick. */
476             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
477 
478             /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
479              * set its parameter to 0 to indicate that its implementation contains
480              * its own wait for interrupt or wait for event instruction, and so wfi
481              * should not be executed again.  However, the original expected idle
482              * time variable must remain unmodified, so a copy is taken. */
483             xModifiableIdleTime = xExpectedIdleTime;
484             configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
485 
486             if( xModifiableIdleTime > 0 )
487             {
488                 __dsb( portSY_FULL_READ_WRITE );
489                 __wfi();
490                 __isb( portSY_FULL_READ_WRITE );
491             }
492 
493             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
494 
495             /* Re-enable interrupts to allow the interrupt that brought the MCU
496              * out of sleep mode to execute immediately.  See comments above
497              * the __disable_irq() call above. */
498             __enable_irq();
499             __dsb( portSY_FULL_READ_WRITE );
500             __isb( portSY_FULL_READ_WRITE );
501 
502             /* Disable interrupts again because the clock is about to be stopped
503              * and interrupts that execute while the clock is stopped will increase
504              * any slippage between the time maintained by the RTOS and calendar
505              * time. */
506             __disable_irq();
507             __dsb( portSY_FULL_READ_WRITE );
508             __isb( portSY_FULL_READ_WRITE );
509 
510             /* Disable the SysTick clock without reading the
511              * portNVIC_SYSTICK_CTRL_REG register to ensure the
512              * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,
513              * the time the SysTick is stopped for is accounted for as best it can
514              * be, but using the tickless mode will inevitably result in some tiny
515              * drift of the time maintained by the kernel with respect to calendar
516              * time*/
517             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
518 
519             /* Determine whether the SysTick has already counted to zero. */
520             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
521             {
522                 uint32_t ulCalculatedLoadValue;
523 
524                 /* The tick interrupt ended the sleep (or is now pending), and
525                  * a new tick period has started.  Reset portNVIC_SYSTICK_LOAD_REG
526                  * with whatever remains of the new tick period. */
527                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
528 
529                 /* Don't allow a tiny value, or values that have somehow
530                  * underflowed because the post sleep hook did something
531                  * that took too long or because the SysTick current-value register
532                  * is zero. */
533                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
534                 {
535                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
536                 }
537 
538                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
539 
540                 /* As the pending tick will be processed as soon as this
541                  * function exits, the tick value maintained by the tick is stepped
542                  * forward by one less than the time spent waiting. */
543                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
544             }
545             else
546             {
547                 /* Something other than the tick interrupt ended the sleep. */
548 
549                 /* Use the SysTick current-value register to determine the
550                  * number of SysTick decrements remaining until the expected idle
551                  * time would have ended. */
552                 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
553                 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
554                 {
555                     /* If the SysTick is not using the core clock, the current-
556                      * value register might still be zero here.  In that case, the
557                      * SysTick didn't load from the reload register, and there are
558                      * ulReloadValue decrements remaining in the expected idle
559                      * time, not zero. */
560                     if( ulSysTickDecrementsLeft == 0 )
561                     {
562                         ulSysTickDecrementsLeft = ulReloadValue;
563                     }
564                 }
565                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
566 
567                 /* Work out how long the sleep lasted rounded to complete tick
568                  * periods (not the ulReload value which accounted for part
569                  * ticks). */
570                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
571 
572                 /* How many complete tick periods passed while the processor
573                  * was waiting? */
574                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
575 
576                 /* The reload value is set to whatever fraction of a single tick
577                  * period remains. */
578                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
579             }
580 
581             /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
582              * then set portNVIC_SYSTICK_LOAD_REG back to its standard value.  If
583              * the SysTick is not using the core clock, temporarily configure it to
584              * use the core clock.  This configuration forces the SysTick to load
585              * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
586              * cycle of the other clock.  Then portNVIC_SYSTICK_LOAD_REG is ready
587              * to receive the standard value immediately. */
588             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
589             portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
590             #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
591             {
592                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
593             }
594             #else
595             {
596                 /* The temporary usage of the core clock has served its purpose,
597                  * as described above.  Resume usage of the other clock. */
598                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
599 
600                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
601                 {
602                     /* The partial tick period already ended.  Be sure the SysTick
603                      * counts it only once. */
604                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
605                 }
606 
607                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
608                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
609             }
610             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
611 
612             /* Step the tick to account for any tick periods that elapsed. */
613             vTaskStepTick( ulCompleteTickPeriods );
614 
615             /* Exit with interrupts enabled. */
616             __enable_irq();
617         }
618     }
619 
620 #endif /* #if configUSE_TICKLESS_IDLE */
621 
622 /*-----------------------------------------------------------*/
623