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 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     {
356         /* Increment the RTOS tick. */
357         if( xTaskIncrementTick() != pdFALSE )
358         {
359             /* Pend a context switch. */
360             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
361         }
362     }
363     portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
364 }
365 /*-----------------------------------------------------------*/
366 
367 /*
368  * Setup the systick timer to generate the tick interrupts at the required
369  * frequency.
370  */
371 #if ( configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0 )
372 
vPortSetupTimerInterrupt(void)373     __weak void vPortSetupTimerInterrupt( void )
374     {
375         /* Calculate the constants required to configure the tick interrupt. */
376         #if ( configUSE_TICKLESS_IDLE == 1 )
377         {
378             ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
379             xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
380             ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
381         }
382         #endif /* configUSE_TICKLESS_IDLE */
383 
384         /* Stop and clear the SysTick. */
385         portNVIC_SYSTICK_CTRL_REG = 0UL;
386         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
387 
388         /* Configure SysTick to interrupt at the requested rate. */
389         portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
390         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
391     }
392 
393 #endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
394 /*-----------------------------------------------------------*/
395 
396 #if ( configUSE_TICKLESS_IDLE == 1 )
397 
vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime)398     __weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
399     {
400         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
401         TickType_t xModifiableIdleTime;
402 
403         /* Make sure the SysTick reload value does not overflow the counter. */
404         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
405         {
406             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
407         }
408 
409         /* Enter a critical section but don't use the taskENTER_CRITICAL()
410          * method as that will mask interrupts that should exit sleep mode. */
411         __disable_irq();
412         __dsb( portSY_FULL_READ_WRITE );
413         __isb( portSY_FULL_READ_WRITE );
414 
415         /* If a context switch is pending or a task is waiting for the scheduler
416          * to be unsuspended then abandon the low power entry. */
417         if( eTaskConfirmSleepModeStatus() == eAbortSleep )
418         {
419             /* Re-enable interrupts - see comments above the __disable_irq()
420              * call above. */
421             __enable_irq();
422         }
423         else
424         {
425             /* Stop the SysTick momentarily.  The time the SysTick is stopped for
426              * is accounted for as best it can be, but using the tickless mode will
427              * inevitably result in some tiny drift of the time maintained by the
428              * kernel with respect to calendar time. */
429             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
430 
431             /* Use the SysTick current-value register to determine the number of
432              * SysTick decrements remaining until the next tick interrupt.  If the
433              * current-value register is zero, then there are actually
434              * ulTimerCountsForOneTick decrements remaining, not zero, because the
435              * SysTick requests the interrupt when decrementing from 1 to 0. */
436             ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
437 
438             if( ulSysTickDecrementsLeft == 0 )
439             {
440                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
441             }
442 
443             /* Calculate the reload value required to wait xExpectedIdleTime
444              * tick periods.  -1 is used because this code normally executes part
445              * way through the first tick period.  But if the SysTick IRQ is now
446              * pending, then clear the IRQ, suppressing the first tick, and correct
447              * the reload value to reflect that the second tick period is already
448              * underway.  The expected idle time is always at least two ticks. */
449             ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
450 
451             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
452             {
453                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
454                 ulReloadValue -= ulTimerCountsForOneTick;
455             }
456 
457             if( ulReloadValue > ulStoppedTimerCompensation )
458             {
459                 ulReloadValue -= ulStoppedTimerCompensation;
460             }
461 
462             /* Set the new reload value. */
463             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
464 
465             /* Clear the SysTick count flag and set the count value back to
466              * zero. */
467             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
468 
469             /* Restart SysTick. */
470             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
471 
472             /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
473              * set its parameter to 0 to indicate that its implementation contains
474              * its own wait for interrupt or wait for event instruction, and so wfi
475              * should not be executed again.  However, the original expected idle
476              * time variable must remain unmodified, so a copy is taken. */
477             xModifiableIdleTime = xExpectedIdleTime;
478             configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
479 
480             if( xModifiableIdleTime > 0 )
481             {
482                 __dsb( portSY_FULL_READ_WRITE );
483                 __wfi();
484                 __isb( portSY_FULL_READ_WRITE );
485             }
486 
487             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
488 
489             /* Re-enable interrupts to allow the interrupt that brought the MCU
490              * out of sleep mode to execute immediately.  See comments above
491              * the __disable_irq() call above. */
492             __enable_irq();
493             __dsb( portSY_FULL_READ_WRITE );
494             __isb( portSY_FULL_READ_WRITE );
495 
496             /* Disable interrupts again because the clock is about to be stopped
497              * and interrupts that execute while the clock is stopped will increase
498              * any slippage between the time maintained by the RTOS and calendar
499              * time. */
500             __disable_irq();
501             __dsb( portSY_FULL_READ_WRITE );
502             __isb( portSY_FULL_READ_WRITE );
503 
504             /* Disable the SysTick clock without reading the
505              * portNVIC_SYSTICK_CTRL_REG register to ensure the
506              * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,
507              * the time the SysTick is stopped for is accounted for as best it can
508              * be, but using the tickless mode will inevitably result in some tiny
509              * drift of the time maintained by the kernel with respect to calendar
510              * time*/
511             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
512 
513             /* Determine whether the SysTick has already counted to zero. */
514             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
515             {
516                 uint32_t ulCalculatedLoadValue;
517 
518                 /* The tick interrupt ended the sleep (or is now pending), and
519                  * a new tick period has started.  Reset portNVIC_SYSTICK_LOAD_REG
520                  * with whatever remains of the new tick period. */
521                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
522 
523                 /* Don't allow a tiny value, or values that have somehow
524                  * underflowed because the post sleep hook did something
525                  * that took too long or because the SysTick current-value register
526                  * is zero. */
527                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
528                 {
529                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
530                 }
531 
532                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
533 
534                 /* As the pending tick will be processed as soon as this
535                  * function exits, the tick value maintained by the tick is stepped
536                  * forward by one less than the time spent waiting. */
537                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
538             }
539             else
540             {
541                 /* Something other than the tick interrupt ended the sleep. */
542 
543                 /* Use the SysTick current-value register to determine the
544                  * number of SysTick decrements remaining until the expected idle
545                  * time would have ended. */
546                 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
547                 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
548                 {
549                     /* If the SysTick is not using the core clock, the current-
550                      * value register might still be zero here.  In that case, the
551                      * SysTick didn't load from the reload register, and there are
552                      * ulReloadValue decrements remaining in the expected idle
553                      * time, not zero. */
554                     if( ulSysTickDecrementsLeft == 0 )
555                     {
556                         ulSysTickDecrementsLeft = ulReloadValue;
557                     }
558                 }
559                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
560 
561                 /* Work out how long the sleep lasted rounded to complete tick
562                  * periods (not the ulReload value which accounted for part
563                  * ticks). */
564                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
565 
566                 /* How many complete tick periods passed while the processor
567                  * was waiting? */
568                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
569 
570                 /* The reload value is set to whatever fraction of a single tick
571                  * period remains. */
572                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
573             }
574 
575             /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
576              * then set portNVIC_SYSTICK_LOAD_REG back to its standard value.  If
577              * the SysTick is not using the core clock, temporarily configure it to
578              * use the core clock.  This configuration forces the SysTick to load
579              * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
580              * cycle of the other clock.  Then portNVIC_SYSTICK_LOAD_REG is ready
581              * to receive the standard value immediately. */
582             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
583             portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
584             #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
585             {
586                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
587             }
588             #else
589             {
590                 /* The temporary usage of the core clock has served its purpose,
591                  * as described above.  Resume usage of the other clock. */
592                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
593 
594                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
595                 {
596                     /* The partial tick period already ended.  Be sure the SysTick
597                      * counts it only once. */
598                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
599                 }
600 
601                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
602                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
603             }
604             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
605 
606             /* Step the tick to account for any tick periods that elapsed. */
607             vTaskStepTick( ulCompleteTickPeriods );
608 
609             /* Exit with interrupts enabled. */
610             __enable_irq();
611         }
612     }
613 
614 #endif /* #if configUSE_TICKLESS_IDLE */
615 
616 /*-----------------------------------------------------------*/
617