]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/GCC/ARM_CM0/port.c
f5aed42ecf4ed7daeaa9db2a7cfde8c053924689
[freertos] / FreeRTOS / Source / portable / GCC / ARM_CM0 / port.c
1 /*\r
2  * FreeRTOS Kernel V10.3.0\r
3  * Copyright (C) 2020 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.  The implementation in this\r
75  * file is weak to allow application writers to change the timer used to\r
76  * generate the tick interrupt.\r
77  */\r
78 void vPortSetupTimerInterrupt( void );\r
79 \r
80 /*\r
81  * Exception handlers.\r
82  */\r
83 void xPortPendSVHandler( void ) __attribute__ (( naked ));\r
84 void xPortSysTickHandler( void );\r
85 void vPortSVCHandler( void );\r
86 \r
87 /*\r
88  * Start first task is a separate function so it can be tested in isolation.\r
89  */\r
90 static void vPortStartFirstTask( void ) __attribute__ (( naked ));\r
91 \r
92 /*\r
93  * Used to catch tasks that attempt to return from their implementing function.\r
94  */\r
95 static void prvTaskExitError( void );\r
96 \r
97 /*-----------------------------------------------------------*/\r
98 \r
99 /* Each task maintains its own interrupt status in the critical nesting\r
100 variable. */\r
101 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;\r
102 \r
103 /*-----------------------------------------------------------*/\r
104 \r
105 /*\r
106 * The number of SysTick increments that make up one tick period.\r
107 */\r
108 #if( configUSE_TICKLESS_IDLE == 1 )\r
109         static uint32_t ulTimerCountsForOneTick = 0;\r
110 #endif /* configUSE_TICKLESS_IDLE */\r
111 \r
112 /*\r
113  * The maximum number of tick periods that can be suppressed is limited by the\r
114  * 24 bit resolution of the SysTick timer.\r
115  */\r
116 #if( configUSE_TICKLESS_IDLE == 1 )\r
117         static uint32_t xMaximumPossibleSuppressedTicks = 0;\r
118 #endif /* configUSE_TICKLESS_IDLE */\r
119 \r
120 /*\r
121  * Compensate for the CPU cycles that pass while the SysTick is stopped (low\r
122  * power functionality only.\r
123  */\r
124 #if( configUSE_TICKLESS_IDLE == 1 )\r
125         static uint32_t ulStoppedTimerCompensation = 0;\r
126 #endif /* configUSE_TICKLESS_IDLE */\r
127 \r
128 /*-----------------------------------------------------------*/\r
129 \r
130 /*\r
131  * See header file for description.\r
132  */\r
133 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )\r
134 {\r
135         /* Simulate the stack frame as it would be created by a context switch\r
136         interrupt. */\r
137         pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */\r
138         *pxTopOfStack = portINITIAL_XPSR;       /* xPSR */\r
139         pxTopOfStack--;\r
140         *pxTopOfStack = ( StackType_t ) pxCode; /* PC */\r
141         pxTopOfStack--;\r
142         *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS;        /* LR */\r
143         pxTopOfStack -= 5;      /* R12, R3, R2 and R1. */\r
144         *pxTopOfStack = ( StackType_t ) pvParameters;   /* R0 */\r
145         pxTopOfStack -= 8; /* R11..R4. */\r
146 \r
147         return pxTopOfStack;\r
148 }\r
149 /*-----------------------------------------------------------*/\r
150 \r
151 static void prvTaskExitError( void )\r
152 {\r
153 volatile uint32_t ulDummy = 0UL;\r
154 \r
155         /* A function that implements a task must not exit or attempt to return to\r
156         its caller as there is nothing to return to.  If a task wants to exit it\r
157         should instead call vTaskDelete( NULL ).\r
158 \r
159         Artificially force an assert() to be triggered if configASSERT() is\r
160         defined, then stop here so application writers can catch the error. */\r
161         configASSERT( uxCriticalNesting == ~0UL );\r
162         portDISABLE_INTERRUPTS();\r
163         while( ulDummy == 0 )\r
164         {\r
165                 /* This file calls prvTaskExitError() after the scheduler has been\r
166                 started to remove a compiler warning about the function being defined\r
167                 but never called.  ulDummy is used purely to quieten other warnings\r
168                 about code appearing after this function is called - making ulDummy\r
169                 volatile makes the compiler think the function could return and\r
170                 therefore not output an 'unreachable code' warning for code that appears\r
171                 after it. */\r
172         }\r
173 }\r
174 /*-----------------------------------------------------------*/\r
175 \r
176 void vPortSVCHandler( void )\r
177 {\r
178         /* This function is no longer used, but retained for backward\r
179         compatibility. */\r
180 }\r
181 /*-----------------------------------------------------------*/\r
182 \r
183 void vPortStartFirstTask( void )\r
184 {\r
185         /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector\r
186         table offset register that can be used to locate the initial stack value.\r
187         Not all M0 parts have the application vector table at address 0. */\r
188         __asm volatile(\r
189         "       .syntax unified                         \n"\r
190         "       ldr  r2, pxCurrentTCBConst2     \n" /* Obtain location of pxCurrentTCB. */\r
191         "       ldr  r3, [r2]                           \n"\r
192         "       ldr  r0, [r3]                           \n" /* The first item in pxCurrentTCB is the task top of stack. */\r
193         "       adds r0, #32                                    \n" /* Discard everything up to r0. */\r
194         "       msr  psp, r0                                    \n" /* This is now the new top of stack to use in the task. */\r
195         "       movs r0, #2                                     \n" /* Switch to the psp stack. */\r
196         "       msr  CONTROL, r0                                \n"\r
197         "       isb                                                     \n"\r
198         "       pop  {r0-r5}                                    \n" /* Pop the registers that are saved automatically. */\r
199         "       mov  lr, r5                                     \n" /* lr is now in r5. */\r
200         "       pop  {r3}                                       \n" /* Return address is now in r3. */\r
201         "       pop  {r2}                                       \n" /* Pop and discard XPSR. */\r
202         "       cpsie i                                         \n" /* The first task has its context and interrupts can be enabled. */\r
203         "       bx   r3                                         \n" /* Finally, jump to the user defined task code. */\r
204         "                                                               \n"\r
205         "       .align 4                                        \n"\r
206         "pxCurrentTCBConst2: .word pxCurrentTCB   "\r
207                                   );\r
208 }\r
209 /*-----------------------------------------------------------*/\r
210 \r
211 /*\r
212  * See header file for description.\r
213  */\r
214 BaseType_t xPortStartScheduler( void )\r
215 {\r
216         /* Make PendSV, CallSV and SysTick the same priority as the kernel. */\r
217         portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;\r
218         portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;\r
219 \r
220         /* Start the timer that generates the tick ISR.  Interrupts are disabled\r
221         here already. */\r
222         vPortSetupTimerInterrupt();\r
223 \r
224         /* Initialise the critical nesting count ready for the first task. */\r
225         uxCriticalNesting = 0;\r
226 \r
227         /* Start the first task. */\r
228         vPortStartFirstTask();\r
229 \r
230         /* Should never get here as the tasks will now be executing!  Call the task\r
231         exit error function to prevent compiler warnings about a static function\r
232         not being called in the case that the application writer overrides this\r
233         functionality by defining configTASK_RETURN_ADDRESS.  Call\r
234         vTaskSwitchContext() so link time optimisation does not remove the\r
235         symbol. */\r
236         vTaskSwitchContext();\r
237         prvTaskExitError();\r
238 \r
239         /* Should not get here! */\r
240         return 0;\r
241 }\r
242 /*-----------------------------------------------------------*/\r
243 \r
244 void vPortEndScheduler( void )\r
245 {\r
246         /* Not implemented in ports where there is nothing to return to.\r
247         Artificially force an assert. */\r
248         configASSERT( uxCriticalNesting == 1000UL );\r
249 }\r
250 /*-----------------------------------------------------------*/\r
251 \r
252 void vPortYield( void )\r
253 {\r
254         /* Set a PendSV to request a context switch. */\r
255         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
256 \r
257         /* Barriers are normally not required but do ensure the code is completely\r
258         within the specified behaviour for the architecture. */\r
259         __asm volatile( "dsb" ::: "memory" );\r
260         __asm volatile( "isb" );\r
261 }\r
262 /*-----------------------------------------------------------*/\r
263 \r
264 void vPortEnterCritical( void )\r
265 {\r
266         portDISABLE_INTERRUPTS();\r
267         uxCriticalNesting++;\r
268         __asm volatile( "dsb" ::: "memory" );\r
269         __asm volatile( "isb" );\r
270 }\r
271 /*-----------------------------------------------------------*/\r
272 \r
273 void vPortExitCritical( void )\r
274 {\r
275         configASSERT( uxCriticalNesting );\r
276         uxCriticalNesting--;\r
277         if( uxCriticalNesting == 0 )\r
278         {\r
279                 portENABLE_INTERRUPTS();\r
280         }\r
281 }\r
282 /*-----------------------------------------------------------*/\r
283 \r
284 uint32_t ulSetInterruptMaskFromISR( void )\r
285 {\r
286         __asm volatile(\r
287                                         " mrs r0, PRIMASK       \n"\r
288                                         " cpsid i                       \n"\r
289                                         " bx lr                           "\r
290                                         ::: "memory"\r
291                                   );\r
292 }\r
293 /*-----------------------------------------------------------*/\r
294 \r
295 void vClearInterruptMaskFromISR( __attribute__( ( unused ) ) uint32_t ulMask )\r
296 {\r
297         __asm volatile(\r
298                                         " msr PRIMASK, r0       \n"\r
299                                         " bx lr                           "\r
300                                         ::: "memory"\r
301                                   );\r
302 }\r
303 /*-----------------------------------------------------------*/\r
304 \r
305 void xPortPendSVHandler( void )\r
306 {\r
307         /* This is a naked function. */\r
308 \r
309         __asm volatile\r
310         (\r
311         "       .syntax unified                                         \n"\r
312         "       mrs r0, psp                                                     \n"\r
313         "                                                                               \n"\r
314         "       ldr     r3, pxCurrentTCBConst                   \n" /* Get the location of the current TCB. */\r
315         "       ldr     r2, [r3]                                                \n"\r
316         "                                                                               \n"\r
317         "       subs r0, r0, #32                                        \n" /* Make space for the remaining low registers. */\r
318         "       str r0, [r2]                                            \n" /* Save the new top of stack. */\r
319         "       stmia r0!, {r4-r7}                                      \n" /* Store the low registers that are not saved automatically. */\r
320         "       mov r4, r8                                                      \n" /* Store the high registers. */\r
321         "       mov r5, r9                                                      \n"\r
322         "       mov r6, r10                                                     \n"\r
323         "       mov r7, r11                                                     \n"\r
324         "       stmia r0!, {r4-r7}                                      \n"\r
325         "                                                                               \n"\r
326         "       push {r3, r14}                                          \n"\r
327         "       cpsid i                                                         \n"\r
328         "       bl vTaskSwitchContext                           \n"\r
329         "       cpsie i                                                         \n"\r
330         "       pop {r2, r3}                                            \n" /* lr goes in r3. r2 now holds tcb pointer. */\r
331         "                                                                               \n"\r
332         "       ldr r1, [r2]                                            \n"\r
333         "       ldr r0, [r1]                                            \n" /* The first item in pxCurrentTCB is the task top of stack. */\r
334         "       adds r0, r0, #16                                        \n" /* Move to the high registers. */\r
335         "       ldmia r0!, {r4-r7}                                      \n" /* Pop the high registers. */\r
336         "       mov r8, r4                                                      \n"\r
337         "       mov r9, r5                                                      \n"\r
338         "       mov r10, r6                                                     \n"\r
339         "       mov r11, r7                                                     \n"\r
340         "                                                                               \n"\r
341         "       msr psp, r0                                                     \n" /* Remember the new top of stack for the task. */\r
342         "                                                                               \n"\r
343         "       subs r0, r0, #32                                        \n" /* Go back for the low registers that are not automatically restored. */\r
344         "       ldmia r0!, {r4-r7}                                      \n" /* Pop low registers.  */\r
345         "                                                                               \n"\r
346         "       bx r3                                                           \n"\r
347         "                                                                               \n"\r
348         "       .align 4                                                        \n"\r
349         "pxCurrentTCBConst: .word pxCurrentTCB    "\r
350         );\r
351 }\r
352 /*-----------------------------------------------------------*/\r
353 \r
354 void xPortSysTickHandler( void )\r
355 {\r
356 uint32_t ulPreviousMask;\r
357 \r
358         ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();\r
359         {\r
360                 /* Increment the RTOS tick. */\r
361                 if( xTaskIncrementTick() != pdFALSE )\r
362                 {\r
363                         /* Pend a context switch. */\r
364                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
365                 }\r
366         }\r
367         portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );\r
368 }\r
369 /*-----------------------------------------------------------*/\r
370 \r
371 /*\r
372  * Setup the systick timer to generate the tick interrupts at the required\r
373  * frequency.\r
374  */\r
375 __attribute__(( weak )) void vPortSetupTimerInterrupt( void )\r
376 {\r
377         /* Calculate the constants required to configure the tick interrupt. */\r
378         #if( configUSE_TICKLESS_IDLE == 1 )\r
379         {\r
380                 ulTimerCountsForOneTick = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ );\r
381                 xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;\r
382                 ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR;\r
383         }\r
384         #endif /* configUSE_TICKLESS_IDLE */\r
385 \r
386         /* Stop and reset the SysTick. */\r
387         portNVIC_SYSTICK_CTRL_REG = 0UL;\r
388         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;\r
389 \r
390         /* Configure SysTick to interrupt at the requested rate. */\r
391         portNVIC_SYSTICK_LOAD_REG = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;\r
392         portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;\r
393 }\r
394 /*-----------------------------------------------------------*/\r
395 \r
396 #if( configUSE_TICKLESS_IDLE == 1 )\r
397 \r
398         __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )\r
399         {\r
400         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;\r
401         TickType_t xModifiableIdleTime;\r
402 \r
403                 /* Make sure the SysTick reload value does not overflow the counter. */\r
404                 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )\r
405                 {\r
406                         xExpectedIdleTime = xMaximumPossibleSuppressedTicks;\r
407                 }\r
408 \r
409                 /* Stop the SysTick momentarily.  The time the SysTick is stopped for\r
410                 is accounted for as best it can be, but using the tickless mode will\r
411                 inevitably result in some tiny drift of the time maintained by the\r
412                 kernel with respect to calendar time. */\r
413                 portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;\r
414 \r
415                 /* Calculate the reload value required to wait xExpectedIdleTime\r
416                 tick periods.  -1 is used because this code will execute part way\r
417                 through one of the tick periods. */\r
418                 ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );\r
419                 if( ulReloadValue > ulStoppedTimerCompensation )\r
420                 {\r
421                         ulReloadValue -= ulStoppedTimerCompensation;\r
422                 }\r
423 \r
424                 /* Enter a critical section but don't use the taskENTER_CRITICAL()\r
425                 method as that will mask interrupts that should exit sleep mode. */\r
426                 __asm volatile( "cpsid i" ::: "memory" );\r
427                 __asm volatile( "dsb" );\r
428                 __asm volatile( "isb" );\r
429 \r
430                 /* If a context switch is pending or a task is waiting for the scheduler\r
431                 to be unsuspended then abandon the low power entry. */\r
432                 if( eTaskConfirmSleepModeStatus() == eAbortSleep )\r
433                 {\r
434                         /* Restart from whatever is left in the count register to complete\r
435                         this tick period. */\r
436                         portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;\r
437 \r
438                         /* Restart SysTick. */\r
439                         portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;\r
440 \r
441                         /* Reset the reload register to the value required for normal tick\r
442                         periods. */\r
443                         portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;\r
444 \r
445                         /* Re-enable interrupts - see comments above the cpsid instruction()\r
446                         above. */\r
447                         __asm volatile( "cpsie i" ::: "memory" );\r
448                 }\r
449                 else\r
450                 {\r
451                         /* Set the new reload value. */\r
452                         portNVIC_SYSTICK_LOAD_REG = ulReloadValue;\r
453 \r
454                         /* Clear the SysTick count flag and set the count value back to\r
455                         zero. */\r
456                         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;\r
457 \r
458                         /* Restart SysTick. */\r
459                         portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;\r
460 \r
461                         /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can\r
462                         set its parameter to 0 to indicate that its implementation contains\r
463                         its own wait for interrupt or wait for event instruction, and so wfi\r
464                         should not be executed again.  However, the original expected idle\r
465                         time variable must remain unmodified, so a copy is taken. */\r
466                         xModifiableIdleTime = xExpectedIdleTime;\r
467                         configPRE_SLEEP_PROCESSING( xModifiableIdleTime );\r
468                         if( xModifiableIdleTime > 0 )\r
469                         {\r
470                                 __asm volatile( "dsb" ::: "memory" );\r
471                                 __asm volatile( "wfi" );\r
472                                 __asm volatile( "isb" );\r
473                         }\r
474                         configPOST_SLEEP_PROCESSING( xExpectedIdleTime );\r
475 \r
476                         /* Re-enable interrupts to allow the interrupt that brought the MCU\r
477                         out of sleep mode to execute immediately.  see comments above\r
478                         __disable_interrupt() call above. */\r
479                         __asm volatile( "cpsie i" ::: "memory" );\r
480                         __asm volatile( "dsb" );\r
481                         __asm volatile( "isb" );\r
482 \r
483                         /* Disable interrupts again because the clock is about to be stopped\r
484                         and interrupts that execute while the clock is stopped will increase\r
485                         any slippage between the time maintained by the RTOS and calendar\r
486                         time. */\r
487                         __asm volatile( "cpsid i" ::: "memory" );\r
488                         __asm volatile( "dsb" );\r
489                         __asm volatile( "isb" );\r
490 \r
491                         /* Disable the SysTick clock without reading the\r
492                         portNVIC_SYSTICK_CTRL_REG register to ensure the\r
493                         portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,\r
494                         the time the SysTick is stopped for is accounted for as best it can\r
495                         be, but using the tickless mode will inevitably result in some tiny\r
496                         drift of the time maintained by the kernel with respect to calendar\r
497                         time*/\r
498                         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );\r
499 \r
500                         /* Determine if the SysTick clock has already counted to zero and\r
501                         been set back to the current reload value (the reload back being\r
502                         correct for the entire expected idle time) or if the SysTick is yet\r
503                         to count to zero (in which case an interrupt other than the SysTick\r
504                         must have brought the system out of sleep mode). */\r
505                         if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )\r
506                         {\r
507                                 uint32_t ulCalculatedLoadValue;\r
508 \r
509                                 /* The tick interrupt is already pending, and the SysTick count\r
510                                 reloaded with ulReloadValue.  Reset the\r
511                                 portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick\r
512                                 period. */\r
513                                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );\r
514 \r
515                                 /* Don't allow a tiny value, or values that have somehow\r
516                                 underflowed because the post sleep hook did something\r
517                                 that took too long. */\r
518                                 if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )\r
519                                 {\r
520                                         ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );\r
521                                 }\r
522 \r
523                                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;\r
524 \r
525                                 /* As the pending tick will be processed as soon as this\r
526                                 function exits, the tick value maintained by the tick is stepped\r
527                                 forward by one less than the time spent waiting. */\r
528                                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;\r
529                         }\r
530                         else\r
531                         {\r
532                                 /* Something other than the tick interrupt ended the sleep.\r
533                                 Work out how long the sleep lasted rounded to complete tick\r
534                                 periods (not the ulReload value which accounted for part\r
535                                 ticks). */\r
536                                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;\r
537 \r
538                                 /* How many complete tick periods passed while the processor\r
539                                 was waiting? */\r
540                                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;\r
541 \r
542                                 /* The reload value is set to whatever fraction of a single tick\r
543                                 period remains. */\r
544                                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;\r
545                         }\r
546 \r
547                         /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG\r
548                         again, then set portNVIC_SYSTICK_LOAD_REG back to its standard\r
549                         value. */\r
550                         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;\r
551                         portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;\r
552                         vTaskStepTick( ulCompleteTickPeriods );\r
553                         portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;\r
554 \r
555                         /* Exit with interrpts enabled. */\r
556                         __asm volatile( "cpsie i" ::: "memory" );\r
557                 }\r
558         }\r
559 \r
560 #endif /* configUSE_TICKLESS_IDLE */\r