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