]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/GCC/ARM_CM0/port.c
Cortex M0 GCC/IAR/Keil ports -- tickless support.
[freertos] / FreeRTOS / Source / portable / GCC / ARM_CM0 / port.c
1 /*\r
2  * FreeRTOS Kernel V10.2.1\r
3  * Copyright (C) 2019 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\r
4  *\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
11  *\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
14  *\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
21  *\r
22  * http://www.FreeRTOS.org\r
23  * http://aws.amazon.com/freertos\r
24  *\r
25  * 1 tab == 4 spaces!\r
26  */\r
27 \r
28 /*-----------------------------------------------------------\r
29  * Implementation of functions defined in portable.h for the ARM CM0 port.\r
30  *----------------------------------------------------------*/\r
31 \r
32 /* Scheduler includes. */\r
33 #include "FreeRTOS.h"\r
34 #include "task.h"\r
35 \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
50 \r
51 /* Constants required to set up the initial stack. */\r
52 #define portINITIAL_XPSR                        ( 0x01000000 )\r
53 \r
54 /* The systick is a 24-bit counter. */\r
55 #define portMAX_24_BIT_NUMBER                           ( 0xffffffUL )\r
56 \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
59 calculations. */\r
60 #ifndef portMISSED_COUNTS_FACTOR\r
61         #define portMISSED_COUNTS_FACTOR                        ( 45UL )\r
62 #endif\r
63 \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
66 debugger. */\r
67 #ifdef configTASK_RETURN_ADDRESS\r
68         #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS\r
69 #else\r
70         #define portTASK_RETURN_ADDRESS prvTaskExitError\r
71 #endif\r
72 \r
73 /*\r
74  * Setup the timer to generate the tick interrupts.\r
75  */\r
76 static void prvSetupTimerInterrupt( void );\r
77 \r
78 /*\r
79  * Exception handlers.\r
80  */\r
81 void xPortPendSVHandler( void ) __attribute__ (( naked ));\r
82 void xPortSysTickHandler( void );\r
83 void vPortSVCHandler( void );\r
84 \r
85 /*\r
86  * Start first task is a separate function so it can be tested in isolation.\r
87  */\r
88 static void vPortStartFirstTask( void ) __attribute__ (( naked ));\r
89 \r
90 /*\r
91  * Used to catch tasks that attempt to return from their implementing function.\r
92  */\r
93 static void prvTaskExitError( void );\r
94 \r
95 /*-----------------------------------------------------------*/\r
96 \r
97 /* Each task maintains its own interrupt status in the critical nesting\r
98 variable. */\r
99 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;\r
100 \r
101 /*-----------------------------------------------------------*/\r
102 \r
103 /*\r
104 * The number of SysTick increments that make up one tick period.\r
105 */\r
106 #if( configUSE_TICKLESS_IDLE == 1 )\r
107         static uint32_t ulTimerCountsForOneTick = 0;\r
108 #endif /* configUSE_TICKLESS_IDLE */\r
109 \r
110 /*\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
113  */\r
114 #if( configUSE_TICKLESS_IDLE == 1 )\r
115         static uint32_t xMaximumPossibleSuppressedTicks = 0;\r
116 #endif /* configUSE_TICKLESS_IDLE */\r
117 \r
118 /*\r
119  * Compensate for the CPU cycles that pass while the SysTick is stopped (low\r
120  * power functionality only.\r
121  */\r
122 #if( configUSE_TICKLESS_IDLE == 1 )\r
123         static uint32_t ulStoppedTimerCompensation = 0;\r
124 #endif /* configUSE_TICKLESS_IDLE */\r
125 \r
126 /*-----------------------------------------------------------*/\r
127 \r
128 /*\r
129  * See header file for description.\r
130  */\r
131 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )\r
132 {\r
133         /* Simulate the stack frame as it would be created by a context switch\r
134         interrupt. */\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
137         pxTopOfStack--;\r
138         *pxTopOfStack = ( StackType_t ) pxCode; /* PC */\r
139         pxTopOfStack--;\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
144 \r
145         return pxTopOfStack;\r
146 }\r
147 /*-----------------------------------------------------------*/\r
148 \r
149 static void prvTaskExitError( void )\r
150 {\r
151 volatile uint32_t ulDummy = 0UL;\r
152 \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
156 \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
162         {\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
169                 after it. */\r
170         }\r
171 }\r
172 /*-----------------------------------------------------------*/\r
173 \r
174 void vPortSVCHandler( void )\r
175 {\r
176         /* This function is no longer used, but retained for backward\r
177         compatibility. */\r
178 }\r
179 /*-----------------------------------------------------------*/\r
180 \r
181 void vPortStartFirstTask( void )\r
182 {\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
186         __asm volatile(\r
187         "       .syntax unified                         \n"\r
188         "       ldr  r2, pxCurrentTCBConst2     \n" /* Obtain location of pxCurrentTCB. */\r
189         "       ldr  r3, [r2]                           \n"\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
195         "       isb                                                     \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
202         "                                                               \n"\r
203         "       .align 4                                        \n"\r
204         "pxCurrentTCBConst2: .word pxCurrentTCB   "\r
205                                   );\r
206 }\r
207 /*-----------------------------------------------------------*/\r
208 \r
209 /*\r
210  * See header file for description.\r
211  */\r
212 BaseType_t xPortStartScheduler( void )\r
213 {\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
217 \r
218         /* Start the timer that generates the tick ISR.  Interrupts are disabled\r
219         here already. */\r
220         prvSetupTimerInterrupt();\r
221 \r
222         /* Initialise the critical nesting count ready for the first task. */\r
223         uxCriticalNesting = 0;\r
224 \r
225         /* Start the first task. */\r
226         vPortStartFirstTask();\r
227 \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
233         symbol. */\r
234         vTaskSwitchContext();\r
235         prvTaskExitError();\r
236 \r
237         /* Should not get here! */\r
238         return 0;\r
239 }\r
240 /*-----------------------------------------------------------*/\r
241 \r
242 void vPortEndScheduler( void )\r
243 {\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
247 }\r
248 /*-----------------------------------------------------------*/\r
249 \r
250 void vPortYield( void )\r
251 {\r
252         /* Set a PendSV to request a context switch. */\r
253         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
254 \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
259 }\r
260 /*-----------------------------------------------------------*/\r
261 \r
262 void vPortEnterCritical( void )\r
263 {\r
264         portDISABLE_INTERRUPTS();\r
265         uxCriticalNesting++;\r
266         __asm volatile( "dsb" ::: "memory" );\r
267         __asm volatile( "isb" );\r
268 }\r
269 /*-----------------------------------------------------------*/\r
270 \r
271 void vPortExitCritical( void )\r
272 {\r
273         configASSERT( uxCriticalNesting );\r
274         uxCriticalNesting--;\r
275         if( uxCriticalNesting == 0 )\r
276         {\r
277                 portENABLE_INTERRUPTS();\r
278         }\r
279 }\r
280 /*-----------------------------------------------------------*/\r
281 \r
282 uint32_t ulSetInterruptMaskFromISR( void )\r
283 {\r
284         __asm volatile(\r
285                                         " mrs r0, PRIMASK       \n"\r
286                                         " cpsid i                       \n"\r
287                                         " bx lr                           "\r
288                                         ::: "memory"\r
289                                   );\r
290 }\r
291 /*-----------------------------------------------------------*/\r
292 \r
293 void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask )\r
294 {\r
295         __asm volatile(\r
296                                         " msr PRIMASK, r0       \n"\r
297                                         " bx lr                           "\r
298                                         ::: "memory"\r
299                                   );\r
300 }\r
301 /*-----------------------------------------------------------*/\r
302 \r
303 void xPortPendSVHandler( void )\r
304 {\r
305         /* This is a naked function. */\r
306 \r
307         __asm volatile\r
308         (\r
309         "       .syntax unified                                         \n"\r
310         "       mrs r0, psp                                                     \n"\r
311         "                                                                               \n"\r
312         "       ldr     r3, pxCurrentTCBConst                   \n" /* Get the location of the current TCB. */\r
313         "       ldr     r2, [r3]                                                \n"\r
314         "                                                                               \n"\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
319         "       mov r5, r9                                                      \n"\r
320         "       mov r6, r10                                                     \n"\r
321         "       mov r7, r11                                                     \n"\r
322         "       stmia r0!, {r4-r7}                                      \n"\r
323         "                                                                               \n"\r
324         "       push {r3, r14}                                          \n"\r
325         "       cpsid i                                                         \n"\r
326         "       bl vTaskSwitchContext                           \n"\r
327         "       cpsie i                                                         \n"\r
328         "       pop {r2, r3}                                            \n" /* lr goes in r3. r2 now holds tcb pointer. */\r
329         "                                                                               \n"\r
330         "       ldr r1, [r2]                                            \n"\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
334         "       mov r8, r4                                                      \n"\r
335         "       mov r9, r5                                                      \n"\r
336         "       mov r10, r6                                                     \n"\r
337         "       mov r11, r7                                                     \n"\r
338         "                                                                               \n"\r
339         "       msr psp, r0                                                     \n" /* Remember the new top of stack for the task. */\r
340         "                                                                               \n"\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
343         "                                                                               \n"\r
344         "       bx r3                                                           \n"\r
345         "                                                                               \n"\r
346         "       .align 4                                                        \n"\r
347         "pxCurrentTCBConst: .word pxCurrentTCB    "\r
348         );\r
349 }\r
350 /*-----------------------------------------------------------*/\r
351 \r
352 void xPortSysTickHandler( void )\r
353 {\r
354 uint32_t ulPreviousMask;\r
355 \r
356         ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();\r
357         {\r
358                 /* Increment the RTOS tick. */\r
359                 if( xTaskIncrementTick() != pdFALSE )\r
360                 {\r
361                         /* Pend a context switch. */\r
362                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
363                 }\r
364         }\r
365         portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );\r
366 }\r
367 /*-----------------------------------------------------------*/\r
368 \r
369 /*\r
370  * Setup the systick timer to generate the tick interrupts at the required\r
371  * frequency.\r
372  */\r
373 void prvSetupTimerInterrupt( void )\r
374 {\r
375         /* Calculate the constants required to configure the tick interrupt. */\r
376         #if( configUSE_TICKLESS_IDLE == 1 )\r
377         {\r
378                 ulTimerCountsForOneTick = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ );\r
379                 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;\r
380                 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;\r
381         }\r
382         #endif /* configUSE_TICKLESS_IDLE */\r
383 \r
384         /* Stop and reset the SysTick. */\r
385         portNVIC_SYSTICK_CTRL_REG = 0UL;\r
386         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;\r
387 \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
391 }\r
392 /*-----------------------------------------------------------*/\r
393 \r
394 #if( configUSE_TICKLESS_IDLE == 1 )\r
395 \r
396         __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
397         {\r
398         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;\r
399         TickType_t xModifiableIdleTime;\r
400 \r
401                 /* Make sure the SysTick reload value does not overflow the counter. */\r
402                 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
403                 {\r
404                         xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
405                 }\r
406 \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
412 \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
418                 {\r
419                         ulReloadValue -= ulStoppedTimerCompensation;\r
420                 }\r
421 \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
427 \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
431                 {\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
435 \r
436                         /* Restart SysTick. */\r
437                         portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;\r
438 \r
439                         /* Reset the reload register to the value required for normal tick\r
440                         periods. */\r
441                         portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;\r
442 \r
443                         /* Re-enable interrupts - see comments above the cpsid instruction()\r
444                         above. */\r
445                         __asm volatile( "cpsie i" ::: "memory" );\r
446                 }\r
447                 else\r
448                 {\r
449                         /* Set the new reload value. */\r
450                         portNVIC_SYSTICK_LOAD_REG = ulReloadValue;\r
451 \r
452                         /* Clear the SysTick count flag and set the count value back to\r
453                         zero. */\r
454                         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;\r
455 \r
456                         /* Restart SysTick. */\r
457                         portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;\r
458 \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
467                         {\r
468                                 __asm volatile( "dsb" ::: "memory" );\r
469                                 __asm volatile( "wfi" );\r
470                                 __asm volatile( "isb" );\r
471                         }\r
472                         configPOST_SLEEP_PROCESSING( xExpectedIdleTime );\r
473 \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
480 \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
484                         time. */\r
485                         __asm volatile( "cpsid i" ::: "memory" );\r
486                         __asm volatile( "dsb" );\r
487                         __asm volatile( "isb" );\r
488 \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
495                         time*/\r
496                         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );\r
497 \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
504                         {\r
505                                 uint32_t ulCalculatedLoadValue;\r
506 \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
510                                 period. */\r
511                                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );\r
512 \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
517                                 {\r
518                                         ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );\r
519                                 }\r
520 \r
521                                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;\r
522 \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
527                         }\r
528                         else\r
529                         {\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
533                                 ticks). */\r
534                                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;\r
535 \r
536                                 /* How many complete tick periods passed while the processor\r
537                                 was waiting? */\r
538                                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;\r
539 \r
540                                 /* The reload value is set to whatever fraction of a single tick\r
541                                 period remains. */\r
542                                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;\r
543                         }\r
544 \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
547                         value. */\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
552 \r
553                         /* Exit with interrpts enabled. */\r
554                         __asm volatile( "cpsie i" ::: "memory" );\r
555                 }\r
556         }\r
557 \r
558 #endif /* configUSE_TICKLESS_IDLE */\r