]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/GCC/ARM_CM4_MPU/port.c
Add more "memory" clobbers into the MPU ports to make them robust to more aggressive...
[freertos] / FreeRTOS / Source / portable / GCC / ARM_CM4_MPU / port.c
1 /*\r
2     FreeRTOS V9.0.1 - Copyright (C) 2017 Real Time Engineers Ltd.\r
3     All rights reserved\r
4 \r
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
6 \r
7     This file is part of the FreeRTOS distribution.\r
8 \r
9     FreeRTOS is free software; you can redistribute it and/or modify it under\r
10     the terms of the GNU General Public License (version 2) as published by the\r
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.\r
12 \r
13     ***************************************************************************\r
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<\r
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<\r
16     >>!   obliged to provide the source code for proprietary components     !<<\r
17     >>!   outside of the FreeRTOS kernel.                                   !<<\r
18     ***************************************************************************\r
19 \r
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following\r
23     link: http://www.freertos.org/a00114.html\r
24 \r
25     ***************************************************************************\r
26      *                                                                       *\r
27      *    FreeRTOS provides completely free yet professionally developed,    *\r
28      *    robust, strictly quality controlled, supported, and cross          *\r
29      *    platform software that is more than just the market leader, it     *\r
30      *    is the industry's de facto standard.                               *\r
31      *                                                                       *\r
32      *    Help yourself get started quickly while simultaneously helping     *\r
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *\r
34      *    tutorial book, reference manual, or both:                          *\r
35      *    http://www.FreeRTOS.org/Documentation                              *\r
36      *                                                                       *\r
37     ***************************************************************************\r
38 \r
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading\r
40     the FAQ page "My application does not run, what could be wrong?".  Have you\r
41     defined configASSERT()?\r
42 \r
43     http://www.FreeRTOS.org/support - In return for receiving this top quality\r
44     embedded software for free we request you assist our global community by\r
45     participating in the support forum.\r
46 \r
47     http://www.FreeRTOS.org/training - Investing in training allows your team to\r
48     be as productive as possible as early as possible.  Now you can receive\r
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers\r
50     Ltd, and the world's leading authority on the world's leading RTOS.\r
51 \r
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
55 \r
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.\r
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.\r
58 \r
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High\r
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
61     licenses offer ticketed support, indemnification and commercial middleware.\r
62 \r
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
64     engineered and independently SIL3 certified version for use in safety and\r
65     mission critical applications that require provable dependability.\r
66 \r
67     1 tab == 4 spaces!\r
68 */\r
69 \r
70 /*-----------------------------------------------------------\r
71  * Implementation of functions defined in portable.h for the ARM CM3 port.\r
72  *----------------------------------------------------------*/\r
73 \r
74 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining\r
75 all the API functions to use the MPU wrappers.  That should only be done when\r
76 task.h is included from an application file. */\r
77 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
78 \r
79 /* Scheduler includes. */\r
80 #include "FreeRTOS.h"\r
81 #include "queue.h"\r
82 #include "event_groups.h"\r
83 #include "mpu_prototypes.h"\r
84 \r
85 #ifndef __VFP_FP__\r
86         #error This port can only be used when the project options are configured to enable hardware floating point support.\r
87 #endif\r
88 \r
89 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
90 \r
91 #ifndef configSYSTICK_CLOCK_HZ\r
92         #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ\r
93         /* Ensure the SysTick is clocked at the same frequency as the core. */\r
94         #define portNVIC_SYSTICK_CLK    ( 1UL << 2UL )\r
95 #else\r
96         /* The way the SysTick is clocked is not modified in case it is not the same\r
97         as the core. */\r
98         #define portNVIC_SYSTICK_CLK    ( 0 )\r
99 #endif\r
100 \r
101 /* Constants required to access and manipulate the NVIC. */\r
102 #define portNVIC_SYSTICK_CTRL_REG                               ( * ( ( volatile uint32_t * ) 0xe000e010 ) )\r
103 #define portNVIC_SYSTICK_LOAD_REG                               ( * ( ( volatile uint32_t * ) 0xe000e014 ) )\r
104 #define portNVIC_SYSTICK_CURRENT_VALUE_REG              ( * ( ( volatile uint32_t * ) 0xe000e018 ) )\r
105 #define portNVIC_SYSPRI2_REG                                    ( *     ( ( volatile uint32_t * ) 0xe000ed20 ) )\r
106 #define portNVIC_SYSPRI1_REG                                    ( * ( ( volatile uint32_t * ) 0xe000ed1c ) )\r
107 #define portNVIC_SYS_CTRL_STATE_REG                             ( * ( ( volatile uint32_t * ) 0xe000ed24 ) )\r
108 #define portNVIC_MEM_FAULT_ENABLE                               ( 1UL << 16UL )\r
109 \r
110 /* Constants required to access and manipulate the MPU. */\r
111 #define portMPU_TYPE_REG                                                ( * ( ( volatile uint32_t * ) 0xe000ed90 ) )\r
112 #define portMPU_REGION_BASE_ADDRESS_REG                 ( * ( ( volatile uint32_t * ) 0xe000ed9C ) )\r
113 #define portMPU_REGION_ATTRIBUTE_REG                    ( * ( ( volatile uint32_t * ) 0xe000edA0 ) )\r
114 #define portMPU_CTRL_REG                                                ( * ( ( volatile uint32_t * ) 0xe000ed94 ) )\r
115 #define portEXPECTED_MPU_TYPE_VALUE                             ( 8UL << 8UL ) /* 8 regions, unified. */\r
116 #define portMPU_ENABLE                                                  ( 0x01UL )\r
117 #define portMPU_BACKGROUND_ENABLE                               ( 1UL << 2UL )\r
118 #define portPRIVILEGED_EXECUTION_START_ADDRESS  ( 0UL )\r
119 #define portMPU_REGION_VALID                                    ( 0x10UL )\r
120 #define portMPU_REGION_ENABLE                                   ( 0x01UL )\r
121 #define portPERIPHERALS_START_ADDRESS                   0x40000000UL\r
122 #define portPERIPHERALS_END_ADDRESS                             0x5FFFFFFFUL\r
123 \r
124 /* Constants required to access and manipulate the SysTick. */\r
125 #define portNVIC_SYSTICK_INT                                    ( 0x00000002UL )\r
126 #define portNVIC_SYSTICK_ENABLE                                 ( 0x00000001UL )\r
127 #define portNVIC_PENDSV_PRI                                             ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )\r
128 #define portNVIC_SYSTICK_PRI                                    ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )\r
129 #define portNVIC_SVC_PRI                                                ( ( ( uint32_t ) configMAX_SYSCALL_INTERRUPT_PRIORITY - 1UL ) << 24UL )\r
130 \r
131 /* Constants required to manipulate the VFP. */\r
132 #define portFPCCR                                                               ( ( volatile uint32_t * ) 0xe000ef34UL ) /* Floating point context control register. */\r
133 #define portASPEN_AND_LSPEN_BITS                                ( 0x3UL << 30UL )\r
134 \r
135 /* Constants required to set up the initial stack. */\r
136 #define portINITIAL_XPSR                                                ( 0x01000000UL )\r
137 #define portINITIAL_EXEC_RETURN                                 ( 0xfffffffdUL )\r
138 #define portINITIAL_CONTROL_IF_UNPRIVILEGED             ( 0x03 )\r
139 #define portINITIAL_CONTROL_IF_PRIVILEGED               ( 0x02 )\r
140 \r
141 /* Constants required to check the validity of an interrupt priority. */\r
142 #define portFIRST_USER_INTERRUPT_NUMBER         ( 16 )\r
143 #define portNVIC_IP_REGISTERS_OFFSET_16         ( 0xE000E3F0 )\r
144 #define portAIRCR_REG                                           ( * ( ( volatile uint32_t * ) 0xE000ED0C ) )\r
145 #define portMAX_8_BIT_VALUE                                     ( ( uint8_t ) 0xff )\r
146 #define portTOP_BIT_OF_BYTE                                     ( ( uint8_t ) 0x80 )\r
147 #define portMAX_PRIGROUP_BITS                           ( ( uint8_t ) 7 )\r
148 #define portPRIORITY_GROUP_MASK                         ( 0x07UL << 8UL )\r
149 #define portPRIGROUP_SHIFT                                      ( 8UL )\r
150 \r
151 /* Offsets in the stack to the parameters when inside the SVC handler. */\r
152 #define portOFFSET_TO_PC                                                ( 6 )\r
153 \r
154 /* For strict compliance with the Cortex-M spec the task start address should\r
155 have bit-0 clear, as it is loaded into the PC on exit from an ISR. */\r
156 #define portSTART_ADDRESS_MASK                          ( ( StackType_t ) 0xfffffffeUL )\r
157 \r
158 /*\r
159  * Configure a number of standard MPU regions that are used by all tasks.\r
160  */\r
161 static void prvSetupMPU( void ) PRIVILEGED_FUNCTION;\r
162 \r
163 /*\r
164  * Return the smallest MPU region size that a given number of bytes will fit\r
165  * into.  The region size is returned as the value that should be programmed\r
166  * into the region attribute register for that region.\r
167  */\r
168 static uint32_t prvGetMPURegionSizeSetting( uint32_t ulActualSizeInBytes ) PRIVILEGED_FUNCTION;\r
169 \r
170 /*\r
171  * Checks to see if being called from the context of an unprivileged task, and\r
172  * if so raises the privilege level and returns false - otherwise does nothing\r
173  * other than return true.\r
174  */\r
175 BaseType_t xPortRaisePrivilege( void ) __attribute__(( naked ));\r
176 \r
177 /*\r
178  * Setup the timer to generate the tick interrupts.  The implementation in this\r
179  * file is weak to allow application writers to change the timer used to\r
180  * generate the tick interrupt.\r
181  */\r
182 void vPortSetupTimerInterrupt( void );\r
183 \r
184 /*\r
185  * Standard FreeRTOS exception handlers.\r
186  */\r
187 void xPortPendSVHandler( void ) __attribute__ (( naked )) PRIVILEGED_FUNCTION;\r
188 void xPortSysTickHandler( void )  __attribute__ ((optimize("3"))) PRIVILEGED_FUNCTION;\r
189 void vPortSVCHandler( void ) __attribute__ (( naked )) PRIVILEGED_FUNCTION;\r
190 \r
191 /*\r
192  * Starts the scheduler by restoring the context of the first task to run.\r
193  */\r
194 static void prvRestoreContextOfFirstTask( void ) __attribute__(( naked )) PRIVILEGED_FUNCTION;\r
195 \r
196 /*\r
197  * C portion of the SVC handler.  The SVC handler is split between an asm entry\r
198  * and a C wrapper for simplicity of coding and maintenance.\r
199  */\r
200 static void prvSVCHandler( uint32_t *pulRegisters ) __attribute__(( noinline )) PRIVILEGED_FUNCTION;\r
201 \r
202 /*\r
203  * Function to enable the VFP.\r
204  */\r
205  static void vPortEnableVFP( void ) __attribute__ (( naked ));\r
206 \r
207 /*-----------------------------------------------------------*/\r
208 \r
209 /* Each task maintains its own interrupt status in the critical nesting\r
210 variable.  Note this is not saved as part of the task context as context\r
211 switches can only occur when uxCriticalNesting is zero. */\r
212 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;\r
213 \r
214 /*\r
215  * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure\r
216  * FreeRTOS API functions are not called from interrupts that have been assigned\r
217  * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.\r
218  */\r
219 #if ( configASSERT_DEFINED == 1 )\r
220          static uint8_t ucMaxSysCallPriority = 0;\r
221          static uint32_t ulMaxPRIGROUPValue = 0;\r
222          static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;\r
223 #endif /* configASSERT_DEFINED */\r
224 \r
225 /*-----------------------------------------------------------*/\r
226 \r
227 /*\r
228  * See header file for description.\r
229  */\r
230 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged )\r
231 {\r
232         /* Simulate the stack frame as it would be created by a context switch\r
233         interrupt. */\r
234         pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */\r
235         *pxTopOfStack = portINITIAL_XPSR;       /* xPSR */\r
236         pxTopOfStack--;\r
237         *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK;    /* PC */\r
238         pxTopOfStack--;\r
239         *pxTopOfStack = 0;      /* LR */\r
240         pxTopOfStack -= 5;      /* R12, R3, R2 and R1. */\r
241         *pxTopOfStack = ( StackType_t ) pvParameters;   /* R0 */\r
242 \r
243         /* A save method is being used that requires each task to maintain its\r
244         own exec return value. */\r
245         pxTopOfStack--;\r
246         *pxTopOfStack = portINITIAL_EXEC_RETURN;\r
247 \r
248         pxTopOfStack -= 9;      /* R11, R10, R9, R8, R7, R6, R5 and R4. */\r
249 \r
250         if( xRunPrivileged == pdTRUE )\r
251         {\r
252                 *pxTopOfStack = portINITIAL_CONTROL_IF_PRIVILEGED;\r
253         }\r
254         else\r
255         {\r
256                 *pxTopOfStack = portINITIAL_CONTROL_IF_UNPRIVILEGED;\r
257         }\r
258 \r
259         return pxTopOfStack;\r
260 }\r
261 /*-----------------------------------------------------------*/\r
262 \r
263 void vPortSVCHandler( void )\r
264 {\r
265         /* Assumes psp was in use. */\r
266         __asm volatile\r
267         (\r
268                 #ifndef USE_PROCESS_STACK       /* Code should not be required if a main() is using the process stack. */\r
269                         "       tst lr, #4                                              \n"\r
270                         "       ite eq                                                  \n"\r
271                         "       mrseq r0, msp                                   \n"\r
272                         "       mrsne r0, psp                                   \n"\r
273                 #else\r
274                         "       mrs r0, psp                                             \n"\r
275                 #endif\r
276                         "       b %0                                                    \n"\r
277                         ::"i"(prvSVCHandler):"r0", "memory"\r
278         );\r
279 }\r
280 /*-----------------------------------------------------------*/\r
281 \r
282 static void prvSVCHandler(      uint32_t *pulParam )\r
283 {\r
284 uint8_t ucSVCNumber;\r
285 \r
286         /* The stack contains: r0, r1, r2, r3, r12, r14, the return address and\r
287         xPSR.  The first argument (r0) is pulParam[ 0 ]. */\r
288         ucSVCNumber = ( ( uint8_t * ) pulParam[ portOFFSET_TO_PC ] )[ -2 ];\r
289         switch( ucSVCNumber )\r
290         {\r
291                 case portSVC_START_SCHEDULER    :       portNVIC_SYSPRI1_REG |= portNVIC_SVC_PRI;\r
292                                                                                         prvRestoreContextOfFirstTask();\r
293                                                                                         break;\r
294 \r
295                 case portSVC_YIELD                              :       portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
296                                                                                         /* Barriers are normally not required\r
297                                                                                         but do ensure the code is completely\r
298                                                                                         within the specified behaviour for the\r
299                                                                                         architecture. */\r
300                                                                                         __asm volatile( "dsb" ::: "memory" );\r
301                                                                                         __asm volatile( "isb" );\r
302 \r
303                                                                                         break;\r
304 \r
305                 case portSVC_RAISE_PRIVILEGE    :       __asm volatile\r
306                                                                                         (\r
307                                                                                                 "       mrs r1, control         \n" /* Obtain current control value. */\r
308                                                                                                 "       bic r1, #1                      \n" /* Set privilege bit. */\r
309                                                                                                 "       msr control, r1         \n" /* Write back new control value. */\r
310                                                                                                 ::: "r1", "memory"\r
311                                                                                         );\r
312                                                                                         break;\r
313 \r
314                 default                                                 :       /* Unknown SVC call. */\r
315                                                                                         break;\r
316         }\r
317 }\r
318 /*-----------------------------------------------------------*/\r
319 \r
320 static void prvRestoreContextOfFirstTask( void )\r
321 {\r
322         __asm volatile\r
323         (\r
324                 "       ldr r0, =0xE000ED08                             \n" /* Use the NVIC offset register to locate the stack. */\r
325                 "       ldr r0, [r0]                                    \n"\r
326                 "       ldr r0, [r0]                                    \n"\r
327                 "       msr msp, r0                                             \n" /* Set the msp back to the start of the stack. */\r
328                 "       ldr     r3, pxCurrentTCBConst2          \n" /* Restore the context. */\r
329                 "       ldr r1, [r3]                                    \n"\r
330                 "       ldr r0, [r1]                                    \n" /* The first item in the TCB is the task top of stack. */\r
331                 "       add r1, r1, #4                                  \n" /* Move onto the second item in the TCB... */\r
332                 "       ldr r2, =0xe000ed9c                             \n" /* Region Base Address register. */\r
333                 "       ldmia r1!, {r4-r11}                             \n" /* Read 4 sets of MPU registers. */\r
334                 "       stmia r2!, {r4-r11}                             \n" /* Write 4 sets of MPU registers. */\r
335                 "       ldmia r0!, {r3-r11, r14}                \n" /* Pop the registers that are not automatically saved on exception entry. */\r
336                 "       msr control, r3                                 \n"\r
337                 "       msr psp, r0                                             \n" /* Restore the task stack pointer. */\r
338                 "       mov r0, #0                                              \n"\r
339                 "       msr     basepri, r0                                     \n"\r
340                 "       bx r14                                                  \n"\r
341                 "                                                                       \n"\r
342                 "       .align 4                                                \n"\r
343                 "pxCurrentTCBConst2: .word pxCurrentTCB \n"\r
344         );\r
345 }\r
346 /*-----------------------------------------------------------*/\r
347 \r
348 /*\r
349  * See header file for description.\r
350  */\r
351 BaseType_t xPortStartScheduler( void )\r
352 {\r
353         /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.  See\r
354         http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */\r
355         configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) );\r
356 \r
357         #if( configASSERT_DEFINED == 1 )\r
358         {\r
359                 volatile uint32_t ulOriginalPriority;\r
360                 volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );\r
361                 volatile uint8_t ucMaxPriorityValue;\r
362 \r
363                 /* Determine the maximum priority from which ISR safe FreeRTOS API\r
364                 functions can be called.  ISR safe functions are those that end in\r
365                 "FromISR".  FreeRTOS maintains separate thread and ISR API functions to\r
366                 ensure interrupt entry is as fast and simple as possible.\r
367 \r
368                 Save the interrupt priority value that is about to be clobbered. */\r
369                 ulOriginalPriority = *pucFirstUserPriorityRegister;\r
370 \r
371                 /* Determine the number of priority bits available.  First write to all\r
372                 possible bits. */\r
373                 *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;\r
374 \r
375                 /* Read the value back to see how many bits stuck. */\r
376                 ucMaxPriorityValue = *pucFirstUserPriorityRegister;\r
377 \r
378                 /* Use the same mask on the maximum system call priority. */\r
379                 ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;\r
380 \r
381                 /* Calculate the maximum acceptable priority group value for the number\r
382                 of bits read back. */\r
383                 ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;\r
384                 while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )\r
385                 {\r
386                         ulMaxPRIGROUPValue--;\r
387                         ucMaxPriorityValue <<= ( uint8_t ) 0x01;\r
388                 }\r
389 \r
390                 #ifdef __NVIC_PRIO_BITS\r
391                 {\r
392                         /* Check the CMSIS configuration that defines the number of\r
393                         priority bits matches the number of priority bits actually queried\r
394                         from the hardware. */\r
395                         configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );\r
396                 }\r
397                 #endif\r
398 \r
399                 #ifdef configPRIO_BITS\r
400                 {\r
401                         /* Check the FreeRTOS configuration that defines the number of\r
402                         priority bits matches the number of priority bits actually queried\r
403                         from the hardware. */\r
404                         configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );\r
405                 }\r
406                 #endif\r
407 \r
408                 /* Shift the priority group value back to its position within the AIRCR\r
409                 register. */\r
410                 ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;\r
411                 ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;\r
412 \r
413                 /* Restore the clobbered interrupt priority register to its original\r
414                 value. */\r
415                 *pucFirstUserPriorityRegister = ulOriginalPriority;\r
416         }\r
417         #endif /* conifgASSERT_DEFINED */\r
418 \r
419         /* Make PendSV and SysTick the same priority as the kernel, and the SVC\r
420         handler higher priority so it can be used to exit a critical section (where\r
421         lower priorities are masked). */\r
422         portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;\r
423         portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;\r
424 \r
425         /* Configure the regions in the MPU that are common to all tasks. */\r
426         prvSetupMPU();\r
427 \r
428         /* Start the timer that generates the tick ISR.  Interrupts are disabled\r
429         here already. */\r
430         vPortSetupTimerInterrupt();\r
431 \r
432         /* Initialise the critical nesting count ready for the first task. */\r
433         uxCriticalNesting = 0;\r
434 \r
435         /* Ensure the VFP is enabled - it should be anyway. */\r
436         vPortEnableVFP();\r
437 \r
438         /* Lazy save always. */\r
439         *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;\r
440 \r
441         /* Start the first task.  This also clears the bit that indicates the FPU is\r
442         in use in case the FPU was used before the scheduler was started - which\r
443         would otherwise result in the unnecessary leaving of space in the SVC stack\r
444         for lazy saving of FPU registers. */\r
445         __asm volatile(\r
446                                         " ldr r0, =0xE000ED08   \n" /* Use the NVIC offset register to locate the stack. */\r
447                                         " ldr r0, [r0]                  \n"\r
448                                         " ldr r0, [r0]                  \n"\r
449                                         " msr msp, r0                   \n" /* Set the msp back to the start of the stack. */\r
450                                         " mov r0, #0                    \n" /* Clear the bit that indicates the FPU is in use, see comment above. */\r
451                                         " msr control, r0               \n"\r
452                                         " cpsie i                               \n" /* Globally enable interrupts. */\r
453                                         " cpsie f                               \n"\r
454                                         " dsb                                   \n"\r
455                                         " isb                                   \n"\r
456                                         " svc %0                                \n" /* System call to start first task. */\r
457                                         " nop                                   \n"\r
458                                         :: "i" (portSVC_START_SCHEDULER) : "memory" );\r
459 \r
460         /* Should not get here! */\r
461         return 0;\r
462 }\r
463 /*-----------------------------------------------------------*/\r
464 \r
465 void vPortEndScheduler( void )\r
466 {\r
467         /* Not implemented in ports where there is nothing to return to.\r
468         Artificially force an assert. */\r
469         configASSERT( uxCriticalNesting == 1000UL );\r
470 }\r
471 /*-----------------------------------------------------------*/\r
472 \r
473 void vPortEnterCritical( void )\r
474 {\r
475 BaseType_t xRunningPrivileged = xPortRaisePrivilege();\r
476 \r
477         portDISABLE_INTERRUPTS();\r
478         uxCriticalNesting++;\r
479 \r
480         vPortResetPrivilege( xRunningPrivileged );\r
481 }\r
482 /*-----------------------------------------------------------*/\r
483 \r
484 void vPortExitCritical( void )\r
485 {\r
486 BaseType_t xRunningPrivileged = xPortRaisePrivilege();\r
487 \r
488         configASSERT( uxCriticalNesting );\r
489         uxCriticalNesting--;\r
490         if( uxCriticalNesting == 0 )\r
491         {\r
492                 portENABLE_INTERRUPTS();\r
493         }\r
494         vPortResetPrivilege( xRunningPrivileged );\r
495 }\r
496 /*-----------------------------------------------------------*/\r
497 \r
498 void xPortPendSVHandler( void )\r
499 {\r
500         /* This is a naked function. */\r
501 \r
502         __asm volatile\r
503         (\r
504                 "       mrs r0, psp                                                     \n"\r
505                 "                                                                               \n"\r
506                 "       ldr     r3, pxCurrentTCBConst                   \n" /* Get the location of the current TCB. */\r
507                 "       ldr     r2, [r3]                                                \n"\r
508                 "                                                                               \n"\r
509                 "       tst r14, #0x10                                          \n" /* Is the task using the FPU context?  If so, push high vfp registers. */\r
510                 "       it eq                                                           \n"\r
511                 "       vstmdbeq r0!, {s16-s31}                         \n"\r
512                 "                                                                               \n"\r
513                 "       mrs r1, control                                         \n"\r
514                 "       stmdb r0!, {r1, r4-r11, r14}            \n" /* Save the remaining registers. */\r
515                 "       str r0, [r2]                                            \n" /* Save the new top of stack into the first member of the TCB. */\r
516                 "                                                                               \n"\r
517                 "       stmdb sp!, {r3}                                         \n"\r
518                 "       mov r0, %0                                                      \n"\r
519                 "       msr basepri, r0                                         \n"\r
520                 "       dsb                                                                     \n"\r
521                 "       isb                                                                     \n"\r
522                 "       bl vTaskSwitchContext                           \n"\r
523                 "       mov r0, #0                                                      \n"\r
524                 "       msr basepri, r0                                         \n"\r
525                 "       ldmia sp!, {r3}                                         \n"\r
526                 "                                                                               \n"     /* Restore the context. */\r
527                 "       ldr r1, [r3]                                            \n"\r
528                 "       ldr r0, [r1]                                            \n" /* The first item in the TCB is the task top of stack. */\r
529                 "       add r1, r1, #4                                          \n" /* Move onto the second item in the TCB... */\r
530                 "       ldr r2, =0xe000ed9c                                     \n" /* Region Base Address register. */\r
531                 "       ldmia r1!, {r4-r11}                                     \n" /* Read 4 sets of MPU registers. */\r
532                 "       stmia r2!, {r4-r11}                                     \n" /* Write 4 sets of MPU registers. */\r
533                 "       ldmia r0!, {r3-r11, r14}                        \n" /* Pop the registers that are not automatically saved on exception entry. */\r
534                 "       msr control, r3                                         \n"\r
535                 "                                                                               \n"\r
536                 "       tst r14, #0x10                                          \n" /* Is the task using the FPU context?  If so, pop the high vfp registers too. */\r
537                 "       it eq                                                           \n"\r
538                 "       vldmiaeq r0!, {s16-s31}                         \n"\r
539                 "                                                                               \n"\r
540                 "       msr psp, r0                                                     \n"\r
541                 "       bx r14                                                          \n"\r
542                 "                                                                               \n"\r
543                 "       .align 4                                                        \n"\r
544                 "pxCurrentTCBConst: .word pxCurrentTCB  \n"\r
545                 ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY)\r
546         );\r
547 }\r
548 /*-----------------------------------------------------------*/\r
549 \r
550 void xPortSysTickHandler( void )\r
551 {\r
552 uint32_t ulDummy;\r
553 \r
554         ulDummy = portSET_INTERRUPT_MASK_FROM_ISR();\r
555         {\r
556                 /* Increment the RTOS tick. */\r
557                 if( xTaskIncrementTick() != pdFALSE )\r
558                 {\r
559                         /* Pend a context switch. */\r
560                         portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;\r
561                 }\r
562         }\r
563         portCLEAR_INTERRUPT_MASK_FROM_ISR( ulDummy );\r
564 }\r
565 /*-----------------------------------------------------------*/\r
566 \r
567 /*\r
568  * Setup the systick timer to generate the tick interrupts at the required\r
569  * frequency.\r
570  */\r
571 __attribute__(( weak )) void vPortSetupTimerInterrupt( void )\r
572 {\r
573         /* Stop and clear the SysTick. */\r
574         portNVIC_SYSTICK_CTRL_REG = 0UL;\r
575         portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;\r
576 \r
577         /* Configure SysTick to interrupt at the requested rate. */\r
578         portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;\r
579         portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE );\r
580 }\r
581 /*-----------------------------------------------------------*/\r
582 \r
583 /* This is a naked function. */\r
584 static void vPortEnableVFP( void )\r
585 {\r
586         __asm volatile\r
587         (\r
588                 "       ldr.w r0, =0xE000ED88           \n" /* The FPU enable bits are in the CPACR. */\r
589                 "       ldr r1, [r0]                            \n"\r
590                 "                                                               \n"\r
591                 "       orr r1, r1, #( 0xf << 20 )      \n" /* Enable CP10 and CP11 coprocessors, then save back. */\r
592                 "       str r1, [r0]                            \n"\r
593                 "       bx r14                                          "\r
594         );\r
595 }\r
596 /*-----------------------------------------------------------*/\r
597 \r
598 static void prvSetupMPU( void )\r
599 {\r
600 extern uint32_t __privileged_functions_end__[];\r
601 extern uint32_t __FLASH_segment_start__[];\r
602 extern uint32_t __FLASH_segment_end__[];\r
603 extern uint32_t __privileged_data_start__[];\r
604 extern uint32_t __privileged_data_end__[];\r
605 \r
606         /* Check the expected MPU is present. */\r
607         if( portMPU_TYPE_REG == portEXPECTED_MPU_TYPE_VALUE )\r
608         {\r
609                 /* First setup the entire flash for unprivileged read only access. */\r
610                 portMPU_REGION_BASE_ADDRESS_REG =       ( ( uint32_t ) __FLASH_segment_start__ ) | /* Base address. */\r
611                                                                                         ( portMPU_REGION_VALID ) |\r
612                                                                                         ( portUNPRIVILEGED_FLASH_REGION );\r
613 \r
614                 portMPU_REGION_ATTRIBUTE_REG =  ( portMPU_REGION_READ_ONLY ) |\r
615                                                                                 ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |\r
616                                                                                 ( prvGetMPURegionSizeSetting( ( uint32_t ) __FLASH_segment_end__ - ( uint32_t ) __FLASH_segment_start__ ) ) |\r
617                                                                                 ( portMPU_REGION_ENABLE );\r
618 \r
619                 /* Setup the first 16K for privileged only access (even though less\r
620                 than 10K is actually being used).  This is where the kernel code is\r
621                 placed. */\r
622                 portMPU_REGION_BASE_ADDRESS_REG =       ( ( uint32_t ) __FLASH_segment_start__ ) | /* Base address. */\r
623                                                                                         ( portMPU_REGION_VALID ) |\r
624                                                                                         ( portPRIVILEGED_FLASH_REGION );\r
625 \r
626                 portMPU_REGION_ATTRIBUTE_REG =  ( portMPU_REGION_PRIVILEGED_READ_ONLY ) |\r
627                                                                                 ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |\r
628                                                                                 ( prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_functions_end__ - ( uint32_t ) __FLASH_segment_start__ ) ) |\r
629                                                                                 ( portMPU_REGION_ENABLE );\r
630 \r
631                 /* Setup the privileged data RAM region.  This is where the kernel data\r
632                 is placed. */\r
633                 portMPU_REGION_BASE_ADDRESS_REG =       ( ( uint32_t ) __privileged_data_start__ ) | /* Base address. */\r
634                                                                                         ( portMPU_REGION_VALID ) |\r
635                                                                                         ( portPRIVILEGED_RAM_REGION );\r
636 \r
637                 portMPU_REGION_ATTRIBUTE_REG =  ( portMPU_REGION_PRIVILEGED_READ_WRITE ) |\r
638                                                                                 ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |\r
639                                                                                 prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_data_end__ - ( uint32_t ) __privileged_data_start__ ) |\r
640                                                                                 ( portMPU_REGION_ENABLE );\r
641 \r
642                 /* By default allow everything to access the general peripherals.  The\r
643                 system peripherals and registers are protected. */\r
644                 portMPU_REGION_BASE_ADDRESS_REG =       ( portPERIPHERALS_START_ADDRESS ) |\r
645                                                                                         ( portMPU_REGION_VALID ) |\r
646                                                                                         ( portGENERAL_PERIPHERALS_REGION );\r
647 \r
648                 portMPU_REGION_ATTRIBUTE_REG =  ( portMPU_REGION_READ_WRITE | portMPU_REGION_EXECUTE_NEVER ) |\r
649                                                                                 ( prvGetMPURegionSizeSetting( portPERIPHERALS_END_ADDRESS - portPERIPHERALS_START_ADDRESS ) ) |\r
650                                                                                 ( portMPU_REGION_ENABLE );\r
651 \r
652                 /* Enable the memory fault exception. */\r
653                 portNVIC_SYS_CTRL_STATE_REG |= portNVIC_MEM_FAULT_ENABLE;\r
654 \r
655                 /* Enable the MPU with the background region configured. */\r
656                 portMPU_CTRL_REG |= ( portMPU_ENABLE | portMPU_BACKGROUND_ENABLE );\r
657         }\r
658 }\r
659 /*-----------------------------------------------------------*/\r
660 \r
661 static uint32_t prvGetMPURegionSizeSetting( uint32_t ulActualSizeInBytes )\r
662 {\r
663 uint32_t ulRegionSize, ulReturnValue = 4;\r
664 \r
665         /* 32 is the smallest region size, 31 is the largest valid value for\r
666         ulReturnValue. */\r
667         for( ulRegionSize = 32UL; ulReturnValue < 31UL; ( ulRegionSize <<= 1UL ) )\r
668         {\r
669                 if( ulActualSizeInBytes <= ulRegionSize )\r
670                 {\r
671                         break;\r
672                 }\r
673                 else\r
674                 {\r
675                         ulReturnValue++;\r
676                 }\r
677         }\r
678 \r
679         /* Shift the code by one before returning so it can be written directly\r
680         into the the correct bit position of the attribute register. */\r
681         return ( ulReturnValue << 1UL );\r
682 }\r
683 /*-----------------------------------------------------------*/\r
684 \r
685 BaseType_t xPortRaisePrivilege( void )\r
686 {\r
687         __asm volatile\r
688         (\r
689                 "       mrs r0, control                                         \n"\r
690                 "       tst r0, #1                                                      \n" /* Is the task running privileged? */\r
691                 "       itte ne                                                         \n"\r
692                 "       movne r0, #0                                            \n" /* CONTROL[0]!=0, return false. */\r
693                 "       svcne %0                                                        \n" /* Switch to privileged. */\r
694                 "       moveq r0, #1                                            \n" /* CONTROL[0]==0, return true. */\r
695                 "       bx lr                                                           \n"\r
696                 :: "i" (portSVC_RAISE_PRIVILEGE) : "r0", "memory"\r
697         );\r
698 \r
699         return 0;\r
700 }\r
701 /*-----------------------------------------------------------*/\r
702 \r
703 void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth )\r
704 {\r
705 extern uint32_t __SRAM_segment_start__[];\r
706 extern uint32_t __SRAM_segment_end__[];\r
707 extern uint32_t __privileged_data_start__[];\r
708 extern uint32_t __privileged_data_end__[];\r
709 int32_t lIndex;\r
710 uint32_t ul;\r
711 \r
712         if( xRegions == NULL )\r
713         {\r
714                 /* No MPU regions are specified so allow access to all RAM. */\r
715                 xMPUSettings->xRegion[ 0 ].ulRegionBaseAddress =\r
716                                 ( ( uint32_t ) __SRAM_segment_start__ ) | /* Base address. */\r
717                                 ( portMPU_REGION_VALID ) |\r
718                                 ( portSTACK_REGION );\r
719 \r
720                 xMPUSettings->xRegion[ 0 ].ulRegionAttribute =\r
721                                 ( portMPU_REGION_READ_WRITE ) |\r
722                                 ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |\r
723                                 ( prvGetMPURegionSizeSetting( ( uint32_t ) __SRAM_segment_end__ - ( uint32_t ) __SRAM_segment_start__ ) ) |\r
724                                 ( portMPU_REGION_ENABLE );\r
725 \r
726                 /* Re-instate the privileged only RAM region as xRegion[ 0 ] will have\r
727                 just removed the privileged only parameters. */\r
728                 xMPUSettings->xRegion[ 1 ].ulRegionBaseAddress =\r
729                                 ( ( uint32_t ) __privileged_data_start__ ) | /* Base address. */\r
730                                 ( portMPU_REGION_VALID ) |\r
731                                 ( portSTACK_REGION + 1 );\r
732 \r
733                 xMPUSettings->xRegion[ 1 ].ulRegionAttribute =\r
734                                 ( portMPU_REGION_PRIVILEGED_READ_WRITE ) |\r
735                                 ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |\r
736                                 prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_data_end__ - ( uint32_t ) __privileged_data_start__ ) |\r
737                                 ( portMPU_REGION_ENABLE );\r
738 \r
739                 /* Invalidate all other regions. */\r
740                 for( ul = 2; ul <= portNUM_CONFIGURABLE_REGIONS; ul++ )\r
741                 {\r
742                         xMPUSettings->xRegion[ ul ].ulRegionBaseAddress = ( portSTACK_REGION + ul ) | portMPU_REGION_VALID;\r
743                         xMPUSettings->xRegion[ ul ].ulRegionAttribute = 0UL;\r
744                 }\r
745         }\r
746         else\r
747         {\r
748                 /* This function is called automatically when the task is created - in\r
749                 which case the stack region parameters will be valid.  At all other\r
750                 times the stack parameters will not be valid and it is assumed that the\r
751                 stack region has already been configured. */\r
752                 if( ulStackDepth > 0 )\r
753                 {\r
754                         /* Define the region that allows access to the stack. */\r
755                         xMPUSettings->xRegion[ 0 ].ulRegionBaseAddress =\r
756                                         ( ( uint32_t ) pxBottomOfStack ) |\r
757                                         ( portMPU_REGION_VALID ) |\r
758                                         ( portSTACK_REGION ); /* Region number. */\r
759 \r
760                         xMPUSettings->xRegion[ 0 ].ulRegionAttribute =\r
761                                         ( portMPU_REGION_READ_WRITE ) | /* Read and write. */\r
762                                         ( prvGetMPURegionSizeSetting( ulStackDepth * ( uint32_t ) sizeof( StackType_t ) ) ) |\r
763                                         ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |\r
764                                         ( portMPU_REGION_ENABLE );\r
765                 }\r
766 \r
767                 lIndex = 0;\r
768 \r
769                 for( ul = 1; ul <= portNUM_CONFIGURABLE_REGIONS; ul++ )\r
770                 {\r
771                         if( ( xRegions[ lIndex ] ).ulLengthInBytes > 0UL )\r
772                         {\r
773                                 /* Translate the generic region definition contained in\r
774                                 xRegions into the CM3 specific MPU settings that are then\r
775                                 stored in xMPUSettings. */\r
776                                 xMPUSettings->xRegion[ ul ].ulRegionBaseAddress =\r
777                                                 ( ( uint32_t ) xRegions[ lIndex ].pvBaseAddress ) |\r
778                                                 ( portMPU_REGION_VALID ) |\r
779                                                 ( portSTACK_REGION + ul ); /* Region number. */\r
780 \r
781                                 xMPUSettings->xRegion[ ul ].ulRegionAttribute =\r
782                                                 ( prvGetMPURegionSizeSetting( xRegions[ lIndex ].ulLengthInBytes ) ) |\r
783                                                 ( xRegions[ lIndex ].ulParameters ) |\r
784                                                 ( portMPU_REGION_ENABLE );\r
785                         }\r
786                         else\r
787                         {\r
788                                 /* Invalidate the region. */\r
789                                 xMPUSettings->xRegion[ ul ].ulRegionBaseAddress = ( portSTACK_REGION + ul ) | portMPU_REGION_VALID;\r
790                                 xMPUSettings->xRegion[ ul ].ulRegionAttribute = 0UL;\r
791                         }\r
792 \r
793                         lIndex++;\r
794                 }\r
795         }\r
796 }\r
797 /*-----------------------------------------------------------*/\r
798 \r
799 #if( configASSERT_DEFINED == 1 )\r
800 \r
801         void vPortValidateInterruptPriority( void )\r
802         {\r
803         uint32_t ulCurrentInterrupt;\r
804         uint8_t ucCurrentPriority;\r
805 \r
806                 /* Obtain the number of the currently executing interrupt. */\r
807                 __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" );\r
808 \r
809                 /* Is the interrupt number a user defined interrupt? */\r
810                 if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )\r
811                 {\r
812                         /* Look up the interrupt's priority. */\r
813                         ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];\r
814 \r
815                         /* The following assertion will fail if a service routine (ISR) for\r
816                         an interrupt that has been assigned a priority above\r
817                         configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API\r
818                         function.  ISR safe FreeRTOS API functions must *only* be called\r
819                         from interrupts that have been assigned a priority at or below\r
820                         configMAX_SYSCALL_INTERRUPT_PRIORITY.\r
821 \r
822                         Numerically low interrupt priority numbers represent logically high\r
823                         interrupt priorities, therefore the priority of the interrupt must\r
824                         be set to a value equal to or numerically *higher* than\r
825                         configMAX_SYSCALL_INTERRUPT_PRIORITY.\r
826 \r
827                         Interrupts that use the FreeRTOS API must not be left at their\r
828                         default priority of     zero as that is the highest possible priority,\r
829                         which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,\r
830                         and     therefore also guaranteed to be invalid.\r
831 \r
832                         FreeRTOS maintains separate thread and ISR API functions to ensure\r
833                         interrupt entry is as fast and simple as possible.\r
834 \r
835                         The following links provide detailed information:\r
836                         http://www.freertos.org/RTOS-Cortex-M3-M4.html\r
837                         http://www.freertos.org/FAQHelp.html */\r
838                         configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );\r
839                 }\r
840 \r
841                 /* Priority grouping:  The interrupt controller (NVIC) allows the bits\r
842                 that define each interrupt's priority to be split between bits that\r
843                 define the interrupt's pre-emption priority bits and bits that define\r
844                 the interrupt's sub-priority.  For simplicity all bits must be defined\r
845                 to be pre-emption priority bits.  The following assertion will fail if\r
846                 this is not the case (if some bits represent a sub-priority).\r
847 \r
848                 If the application only uses CMSIS libraries for interrupt\r
849                 configuration then the correct setting can be achieved on all Cortex-M\r
850                 devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the\r
851                 scheduler.  Note however that some vendor specific peripheral libraries\r
852                 assume a non-zero priority group setting, in which cases using a value\r
853                 of zero will result in unpredicable behaviour. */\r
854                 configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );\r
855         }\r
856 \r
857 #endif /* configASSERT_DEFINED */\r
858 /*-----------------------------------------------------------*/\r
859 \r
860 \r