]> begriffs open source - freertos/blob - portable/GCC/ARM_CM4_MPU/port.c
Use the bigger priority whenever possible. (#760)
[freertos] / portable / GCC / ARM_CM4_MPU / port.c
1 /*
2  * FreeRTOS Kernel <DEVELOPMENT BRANCH>
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * https://www.FreeRTOS.org
25  * https://github.com/FreeRTOS
26  *
27  */
28
29 /*-----------------------------------------------------------
30 * Implementation of functions defined in portable.h for the ARM CM4 MPU port.
31 *----------------------------------------------------------*/
32
33 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
34  * all the API functions to use the MPU wrappers.  That should only be done when
35  * task.h is included from an application file. */
36 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
37
38 /* Scheduler includes. */
39 #include "FreeRTOS.h"
40 #include "task.h"
41
42 #ifndef __VFP_FP__
43     #error This port can only be used when the project options are configured to enable hardware floating point support.
44 #endif
45
46 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
47
48 #ifndef configSYSTICK_CLOCK_HZ
49     #define configSYSTICK_CLOCK_HZ    configCPU_CLOCK_HZ
50     /* Ensure the SysTick is clocked at the same frequency as the core. */
51     #define portNVIC_SYSTICK_CLK      ( 1UL << 2UL )
52 #else
53
54 /* The way the SysTick is clocked is not modified in case it is not the same
55  * as the core. */
56     #define portNVIC_SYSTICK_CLK    ( 0 )
57 #endif
58
59 #ifndef configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS
60     #warning "configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS is not defined. We recommend defining it to 0 in FreeRTOSConfig.h for better security."
61     #define configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS    1
62 #endif
63
64 /* Constants required to access and manipulate the NVIC. */
65 #define portNVIC_SYSTICK_CTRL_REG                 ( *( ( volatile uint32_t * ) 0xe000e010 ) )
66 #define portNVIC_SYSTICK_LOAD_REG                 ( *( ( volatile uint32_t * ) 0xe000e014 ) )
67 #define portNVIC_SYSTICK_CURRENT_VALUE_REG        ( *( ( volatile uint32_t * ) 0xe000e018 ) )
68 #define portNVIC_SHPR3_REG                        ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
69 #define portNVIC_SHPR2_REG                        ( *( ( volatile uint32_t * ) 0xe000ed1c ) )
70 #define portNVIC_SYS_CTRL_STATE_REG               ( *( ( volatile uint32_t * ) 0xe000ed24 ) )
71 #define portNVIC_MEM_FAULT_ENABLE                 ( 1UL << 16UL )
72
73 /* Constants used to detect Cortex-M7 r0p0 and r0p1 cores, and ensure
74  * that a work around is active for errata 837070. */
75 #define portCPUID                                 ( *( ( volatile uint32_t * ) 0xE000ed00 ) )
76 #define portCORTEX_M7_r0p1_ID                     ( 0x410FC271UL )
77 #define portCORTEX_M7_r0p0_ID                     ( 0x410FC270UL )
78
79 /* Constants required to access and manipulate the MPU. */
80 #define portMPU_TYPE_REG                          ( *( ( volatile uint32_t * ) 0xe000ed90 ) )
81 #define portMPU_REGION_BASE_ADDRESS_REG           ( *( ( volatile uint32_t * ) 0xe000ed9C ) )
82 #define portMPU_REGION_ATTRIBUTE_REG              ( *( ( volatile uint32_t * ) 0xe000edA0 ) )
83 #define portMPU_CTRL_REG                          ( *( ( volatile uint32_t * ) 0xe000ed94 ) )
84 #define portEXPECTED_MPU_TYPE_VALUE               ( configTOTAL_MPU_REGIONS << 8UL )
85 #define portMPU_ENABLE                            ( 0x01UL )
86 #define portMPU_BACKGROUND_ENABLE                 ( 1UL << 2UL )
87 #define portPRIVILEGED_EXECUTION_START_ADDRESS    ( 0UL )
88 #define portMPU_REGION_VALID                      ( 0x10UL )
89 #define portMPU_REGION_ENABLE                     ( 0x01UL )
90 #define portPERIPHERALS_START_ADDRESS             0x40000000UL
91 #define portPERIPHERALS_END_ADDRESS               0x5FFFFFFFUL
92
93 /* Constants required to access and manipulate the SysTick. */
94 #define portNVIC_SYSTICK_INT                      ( 0x00000002UL )
95 #define portNVIC_SYSTICK_ENABLE                   ( 0x00000001UL )
96 #define portMIN_INTERRUPT_PRIORITY                ( 255UL )
97 #define portNVIC_PENDSV_PRI                       ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 16UL )
98 #define portNVIC_SYSTICK_PRI                      ( ( ( uint32_t ) portMIN_INTERRUPT_PRIORITY ) << 24UL )
99 #define portNVIC_SVC_PRI                          ( ( ( uint32_t ) configMAX_SYSCALL_INTERRUPT_PRIORITY - 1UL ) << 24UL )
100
101 /* Constants required to manipulate the VFP. */
102 #define portFPCCR                                 ( ( volatile uint32_t * ) 0xe000ef34UL ) /* Floating point context control register. */
103 #define portASPEN_AND_LSPEN_BITS                  ( 0x3UL << 30UL )
104
105 /* Constants required to set up the initial stack. */
106 #define portINITIAL_XPSR                          ( 0x01000000UL )
107 #define portINITIAL_EXC_RETURN                    ( 0xfffffffdUL )
108 #define portINITIAL_CONTROL_IF_UNPRIVILEGED       ( 0x03 )
109 #define portINITIAL_CONTROL_IF_PRIVILEGED         ( 0x02 )
110
111 /* Constants required to check the validity of an interrupt priority. */
112 #define portFIRST_USER_INTERRUPT_NUMBER           ( 16 )
113 #define portNVIC_IP_REGISTERS_OFFSET_16           ( 0xE000E3F0 )
114 #define portAIRCR_REG                             ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
115 #define portMAX_8_BIT_VALUE                       ( ( uint8_t ) 0xff )
116 #define portTOP_BIT_OF_BYTE                       ( ( uint8_t ) 0x80 )
117 #define portMAX_PRIGROUP_BITS                     ( ( uint8_t ) 7 )
118 #define portPRIORITY_GROUP_MASK                   ( 0x07UL << 8UL )
119 #define portPRIGROUP_SHIFT                        ( 8UL )
120
121 /* Constants used during system call enter and exit. */
122 #define portPSR_STACK_PADDING_MASK                ( 1UL << 9UL )
123 #define portEXC_RETURN_STACK_FRAME_TYPE_MASK      ( 1UL << 4UL )
124
125 /* Offsets in the stack to the parameters when inside the SVC handler. */
126 #define portOFFSET_TO_LR                          ( 5 )
127 #define portOFFSET_TO_PC                          ( 6 )
128 #define portOFFSET_TO_PSR                         ( 7 )
129
130
131 /* For strict compliance with the Cortex-M spec the task start address should
132  * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
133 #define portSTART_ADDRESS_MASK                    ( ( StackType_t ) 0xfffffffeUL )
134
135 /* Does addr lie within [start, end] address range? */
136 #define portIS_ADDRESS_WITHIN_RANGE( addr, start, end ) \
137     ( ( ( addr ) >= ( start ) ) && ( ( addr ) <= ( end ) ) )
138
139 /* Is the access request satisfied by the available permissions? */
140 #define portIS_AUTHORIZED( accessRequest, permissions ) \
141     ( ( ( permissions ) & ( accessRequest ) ) == accessRequest )
142
143 /* Max value that fits in a uint32_t type. */
144 #define portUINT32_MAX    ( ~( ( uint32_t ) 0 ) )
145
146 /* Check if adding a and b will result in overflow. */
147 #define portADD_UINT32_WILL_OVERFLOW( a, b )    ( ( a ) > ( portUINT32_MAX - ( b ) ) )
148 /*-----------------------------------------------------------*/
149
150 /*
151  * Configure a number of standard MPU regions that are used by all tasks.
152  */
153 static void prvSetupMPU( void ) PRIVILEGED_FUNCTION;
154
155 /*
156  * Return the smallest MPU region size that a given number of bytes will fit
157  * into.  The region size is returned as the value that should be programmed
158  * into the region attribute register for that region.
159  */
160 static uint32_t prvGetMPURegionSizeSetting( uint32_t ulActualSizeInBytes ) PRIVILEGED_FUNCTION;
161
162 /*
163  * Setup the timer to generate the tick interrupts.  The implementation in this
164  * file is weak to allow application writers to change the timer used to
165  * generate the tick interrupt.
166  */
167 void vPortSetupTimerInterrupt( void );
168
169 /*
170  * Standard FreeRTOS exception handlers.
171  */
172 void xPortPendSVHandler( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
173 void xPortSysTickHandler( void ) PRIVILEGED_FUNCTION;
174 void vPortSVCHandler( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
175
176 /*
177  * Starts the scheduler by restoring the context of the first task to run.
178  */
179 static void prvRestoreContextOfFirstTask( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
180
181 /*
182  * C portion of the SVC handler.  The SVC handler is split between an asm entry
183  * and a C wrapper for simplicity of coding and maintenance.
184  */
185 void vSVCHandler_C( uint32_t * pulRegisters ) __attribute__( ( noinline ) ) PRIVILEGED_FUNCTION;
186
187 /*
188  * Function to enable the VFP.
189  */
190 static void vPortEnableVFP( void ) __attribute__( ( naked ) );
191
192 /**
193  * @brief Checks whether or not the processor is privileged.
194  *
195  * @return 1 if the processor is already privileged, 0 otherwise.
196  */
197 BaseType_t xIsPrivileged( void ) __attribute__( ( naked ) );
198
199 /**
200  * @brief Lowers the privilege level by setting the bit 0 of the CONTROL
201  * register.
202  *
203  * Bit 0 of the CONTROL register defines the privilege level of Thread Mode.
204  *  Bit[0] = 0 --> The processor is running privileged
205  *  Bit[0] = 1 --> The processor is running unprivileged.
206  */
207 void vResetPrivilege( void ) __attribute__( ( naked ) );
208
209 /**
210  * @brief Enter critical section.
211  */
212 #if( configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS == 1 )
213     void vPortEnterCritical( void ) FREERTOS_SYSTEM_CALL;
214 #else
215     void vPortEnterCritical( void ) PRIVILEGED_FUNCTION;
216 #endif
217
218 /**
219  * @brief Exit from critical section.
220  */
221 #if( configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS == 1 )
222     void vPortExitCritical( void ) FREERTOS_SYSTEM_CALL;
223 #else
224     void vPortExitCritical( void ) PRIVILEGED_FUNCTION;
225 #endif
226
227 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
228
229     /**
230      * @brief Sets up the system call stack so that upon returning from
231      * SVC, the system call stack is used.
232      *
233      * It is used for the system calls with up to 4 parameters.
234      *
235      * @param pulTaskStack The current SP when the SVC was raised.
236      * @param ulLR The value of Link Register (EXC_RETURN) in the SVC handler.
237      */
238     void vSystemCallEnter( uint32_t * pulTaskStack, uint32_t ulLR ) PRIVILEGED_FUNCTION;
239
240 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
241
242 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
243
244     /**
245      * @brief Sets up the system call stack so that upon returning from
246      * SVC, the system call stack is used.
247      *
248      * It is used for the system calls with 5 parameters.
249      *
250      * @param pulTaskStack The current SP when the SVC was raised.
251      * @param ulLR The value of Link Register (EXC_RETURN) in the SVC handler.
252      */
253     void vSystemCallEnter_1( uint32_t * pulTaskStack, uint32_t ulLR ) PRIVILEGED_FUNCTION;
254
255 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
256
257 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
258
259     /**
260      * @brief Sets up the task stack so that upon returning from
261      * SVC, the task stack is used again.
262      *
263      * @param pulSystemCallStack The current SP when the SVC was raised.
264      * @param ulLR The value of Link Register (EXC_RETURN) in the SVC handler.
265      */
266     void vSystemCallExit( uint32_t * pulSystemCallStack, uint32_t ulLR ) PRIVILEGED_FUNCTION;
267
268 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
269
270 /**
271  * @brief Checks whether or not the calling task is privileged.
272  *
273  * @return pdTRUE if the calling task is privileged, pdFALSE otherwise.
274  */
275 BaseType_t xPortIsTaskPrivileged( void ) PRIVILEGED_FUNCTION;
276 /*-----------------------------------------------------------*/
277
278 /* Each task maintains its own interrupt status in the critical nesting
279  * variable.  Note this is not saved as part of the task context as context
280  * switches can only occur when uxCriticalNesting is zero. */
281 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
282
283 /*
284  * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
285  * FreeRTOS API functions are not called from interrupts that have been assigned
286  * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
287  */
288 #if ( configASSERT_DEFINED == 1 )
289     static uint8_t ucMaxSysCallPriority = 0;
290     static uint32_t ulMaxPRIGROUPValue = 0;
291     static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
292 #endif /* configASSERT_DEFINED */
293
294 /*-----------------------------------------------------------*/
295
296 /*
297  * See header file for description.
298  */
299 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
300                                      TaskFunction_t pxCode,
301                                      void * pvParameters,
302                                      BaseType_t xRunPrivileged,
303                                      xMPU_SETTINGS * xMPUSettings )
304 {
305     if( xRunPrivileged == pdTRUE )
306     {
307         xMPUSettings->ulTaskFlags |= portTASK_IS_PRIVILEGED_FLAG;
308         xMPUSettings->ulContext[ 0 ] = portINITIAL_CONTROL_IF_PRIVILEGED;
309     }
310     else
311     {
312         xMPUSettings->ulTaskFlags &= ( ~portTASK_IS_PRIVILEGED_FLAG );
313         xMPUSettings->ulContext[ 0 ] = portINITIAL_CONTROL_IF_UNPRIVILEGED;
314     }
315     xMPUSettings->ulContext[ 1 ] = 0x04040404; /* r4. */
316     xMPUSettings->ulContext[ 2 ] = 0x05050505; /* r5. */
317     xMPUSettings->ulContext[ 3 ] = 0x06060606; /* r6. */
318     xMPUSettings->ulContext[ 4 ] = 0x07070707; /* r7. */
319     xMPUSettings->ulContext[ 5 ] = 0x08080808; /* r8. */
320     xMPUSettings->ulContext[ 6 ] = 0x09090909; /* r9. */
321     xMPUSettings->ulContext[ 7 ] = 0x10101010; /* r10. */
322     xMPUSettings->ulContext[ 8 ] = 0x11111111; /* r11. */
323     xMPUSettings->ulContext[ 9 ] = portINITIAL_EXC_RETURN; /* EXC_RETURN. */
324
325     xMPUSettings->ulContext[ 10 ] = ( uint32_t ) ( pxTopOfStack - 8 ); /* PSP with the hardware saved stack. */
326     xMPUSettings->ulContext[ 11 ] = ( uint32_t ) pvParameters; /* r0. */
327     xMPUSettings->ulContext[ 12 ] = 0x01010101; /* r1. */
328     xMPUSettings->ulContext[ 13 ] = 0x02020202; /* r2. */
329     xMPUSettings->ulContext[ 14 ] = 0x03030303; /* r3. */
330     xMPUSettings->ulContext[ 15 ] = 0x12121212; /* r12. */
331     xMPUSettings->ulContext[ 16 ] = 0; /* LR. */
332     xMPUSettings->ulContext[ 17 ] = ( ( uint32_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC. */
333     xMPUSettings->ulContext[ 18 ] = portINITIAL_XPSR; /* xPSR. */
334
335     #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
336     {
337         /* Ensure that the system call stack is double word aligned. */
338         xMPUSettings->xSystemCallStackInfo.pulSystemCallStack = &( xMPUSettings->xSystemCallStackInfo.ulSystemCallStackBuffer[ configSYSTEM_CALL_STACK_SIZE - 1 ] );
339         xMPUSettings->xSystemCallStackInfo.pulSystemCallStack = ( uint32_t * ) ( ( uint32_t ) ( xMPUSettings->xSystemCallStackInfo.pulSystemCallStack ) &
340                                                                                  ( uint32_t ) ( ~( portBYTE_ALIGNMENT_MASK ) ) );
341
342         /* This is not NULL only for the duration of a system call. */
343         xMPUSettings->xSystemCallStackInfo.pulTaskStack = NULL;
344     }
345     #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
346
347     return &( xMPUSettings->ulContext[ 19 ] );
348 }
349 /*-----------------------------------------------------------*/
350
351 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
352
353 void vPortSVCHandler( void ) /* __attribute__( ( naked ) ) PRIVILEGED_FUNCTION */
354 {
355     __asm volatile
356     (
357         ".syntax unified                \n"
358         ".extern vSVCHandler_C          \n"
359         ".extern vSystemCallEnter       \n"
360         ".extern vSystemCallEnter_1     \n"
361         ".extern vSystemCallExit        \n"
362         "                               \n"
363         "tst lr, #4                     \n"
364         "ite eq                         \n"
365         "mrseq r0, msp                  \n"
366         "mrsne r0, psp                  \n"
367         "                               \n"
368         "ldr r1, [r0, #24]              \n"
369         "ldrb r2, [r1, #-2]             \n"
370         "cmp r2, %0                     \n"
371         "beq syscall_enter              \n"
372         "cmp r2, %1                     \n"
373         "beq syscall_enter_1            \n"
374         "cmp r2, %2                     \n"
375         "beq syscall_exit               \n"
376         "b vSVCHandler_C                \n"
377         "                               \n"
378         "syscall_enter:                 \n"
379         "    mov r1, lr                 \n"
380         "    b vSystemCallEnter         \n"
381         "                               \n"
382         "syscall_enter_1:               \n"
383         "    mov r1, lr                 \n"
384         "    b vSystemCallEnter_1       \n"
385         "                               \n"
386         "syscall_exit:                  \n"
387         "    mov r1, lr                 \n"
388         "    b vSystemCallExit          \n"
389         "                               \n"
390         : /* No outputs. */
391         :"i" ( portSVC_SYSTEM_CALL_ENTER ), "i" ( portSVC_SYSTEM_CALL_ENTER_1 ), "i" ( portSVC_SYSTEM_CALL_EXIT )
392         : "r0", "r1", "r2", "memory"
393     );
394 }
395
396 #else /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
397
398 void vPortSVCHandler( void )
399 {
400     /* Assumes psp was in use. */
401     __asm volatile
402     (
403         #ifndef USE_PROCESS_STACK   /* Code should not be required if a main() is using the process stack. */
404             "   tst lr, #4                      \n"
405             "   ite eq                          \n"
406             "   mrseq r0, msp                   \n"
407             "   mrsne r0, psp                   \n"
408         #else
409             "   mrs r0, psp                     \n"
410         #endif
411         "   b %0                            \n"
412         ::"i" ( vSVCHandler_C ) : "r0", "memory"
413     );
414 }
415
416 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
417 /*-----------------------------------------------------------*/
418
419 void vSVCHandler_C( uint32_t * pulParam ) /* PRIVILEGED_FUNCTION */
420 {
421     uint8_t ucSVCNumber;
422     uint32_t ulPC;
423
424     #if ( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 )
425         #if defined( __ARMCC_VERSION )
426
427             /* Declaration when these variable are defined in code instead of being
428             * exported from linker scripts. */
429             extern uint32_t * __syscalls_flash_start__;
430             extern uint32_t * __syscalls_flash_end__;
431         #else
432             /* Declaration when these variable are exported from linker scripts. */
433             extern uint32_t __syscalls_flash_start__[];
434             extern uint32_t __syscalls_flash_end__[];
435         #endif /* #if defined( __ARMCC_VERSION ) */
436     #endif /* #if( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 ) */
437
438     /* The stack contains: r0, r1, r2, r3, r12, LR, PC and xPSR.  The first
439      * argument (r0) is pulParam[ 0 ]. */
440     ulPC = pulParam[ portOFFSET_TO_PC ];
441     ucSVCNumber = ( ( uint8_t * ) ulPC )[ -2 ];
442
443     switch( ucSVCNumber )
444     {
445         case portSVC_START_SCHEDULER:
446             portNVIC_SHPR2_REG |= portNVIC_SVC_PRI;
447             prvRestoreContextOfFirstTask();
448             break;
449
450         case portSVC_YIELD:
451             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
452
453             /* Barriers are normally not required
454              * but do ensure the code is completely
455              * within the specified behaviour for the
456              * architecture. */
457             __asm volatile ( "dsb" ::: "memory" );
458             __asm volatile ( "isb" );
459
460             break;
461
462             #if ( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 )
463                 case portSVC_RAISE_PRIVILEGE: /* Only raise the privilege, if the
464                                                * svc was raised from any of the
465                                                * system calls. */
466
467                     if( ( ulPC >= ( uint32_t ) __syscalls_flash_start__ ) &&
468                         ( ulPC <= ( uint32_t ) __syscalls_flash_end__ ) )
469                     {
470                         __asm volatile
471                         (
472                             "   mrs r1, control     \n"/* Obtain current control value. */
473                             "   bic r1, #1          \n"/* Set privilege bit. */
474                             "   msr control, r1     \n"/* Write back new control value. */
475                             ::: "r1", "memory"
476                         );
477                     }
478
479                     break;
480             #else /* if ( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 ) */
481                 case portSVC_RAISE_PRIVILEGE:
482                     __asm volatile
483                     (
484                         "   mrs r1, control     \n"/* Obtain current control value. */
485                         "   bic r1, #1          \n"/* Set privilege bit. */
486                         "   msr control, r1     \n"/* Write back new control value. */
487                         ::: "r1", "memory"
488                     );
489                     break;
490             #endif /* #if( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 ) */
491
492                 default: /* Unknown SVC call. */
493                     break;
494     }
495 }
496 /*-----------------------------------------------------------*/
497
498 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
499
500 void vSystemCallEnter( uint32_t * pulTaskStack, uint32_t ulLR ) /* PRIVILEGED_FUNCTION */
501 {
502     extern TaskHandle_t pxCurrentTCB;
503     xMPU_SETTINGS * pxMpuSettings;
504     uint32_t * pulSystemCallStack;
505     uint32_t ulStackFrameSize, ulSystemCallLocation, i;
506     #if defined( __ARMCC_VERSION )
507         /* Declaration when these variable are defined in code instead of being
508          * exported from linker scripts. */
509         extern uint32_t * __syscalls_flash_start__;
510         extern uint32_t * __syscalls_flash_end__;
511     #else
512         /* Declaration when these variable are exported from linker scripts. */
513         extern uint32_t __syscalls_flash_start__[];
514         extern uint32_t __syscalls_flash_end__[];
515     #endif /* #if defined( __ARMCC_VERSION ) */
516
517     ulSystemCallLocation = pulTaskStack[ portOFFSET_TO_PC ];
518
519     /* If the request did not come from the system call section, do nothing. */
520     if( ( ulSystemCallLocation >= ( uint32_t ) __syscalls_flash_start__ ) &&
521         ( ulSystemCallLocation <= ( uint32_t ) __syscalls_flash_end__ ) )
522     {
523         pxMpuSettings = xTaskGetMPUSettings( pxCurrentTCB );
524         pulSystemCallStack = pxMpuSettings->xSystemCallStackInfo.pulSystemCallStack;
525
526         /* This is not NULL only for the duration of the system call. */
527         configASSERT( pxMpuSettings->xSystemCallStackInfo.pulTaskStack == NULL );
528
529         if( ( ulLR & portEXC_RETURN_STACK_FRAME_TYPE_MASK ) == 0UL )
530         {
531             /* Extended frame i.e. FPU in use. */
532             ulStackFrameSize = 26;
533             __asm volatile (
534                                 " vpush {s0}         \n" /* Trigger lazy stacking. */
535                                 " vpop  {s0}         \n" /* Nullify the affect of the above instruction. */
536                                 ::: "memory"
537                            );
538         }
539         else
540         {
541             /* Standard frame i.e. FPU not in use. */
542             ulStackFrameSize = 8;
543         }
544
545         /* Make space on the system call stack for the stack frame. */
546         pulSystemCallStack = pulSystemCallStack - ulStackFrameSize;
547
548         /* Copy the stack frame. */
549         for( i = 0; i < ulStackFrameSize; i++ )
550         {
551             pulSystemCallStack[ i ] = pulTaskStack[ i ];
552         }
553
554         /* Use the pulSystemCallStack in thread mode. */
555         __asm volatile ( "msr psp, %0" : : "r" ( pulSystemCallStack ) );
556
557         /* Raise the privilege for the duration of the system call. */
558         __asm volatile (
559                             " mrs r1, control     \n" /* Obtain current control value. */
560                             " bic r1, #1          \n" /* Clear nPRIV bit. */
561                             " msr control, r1     \n" /* Write back new control value. */
562                             ::: "r1", "memory"
563                         );
564
565         /* Remember the location where we should copy the stack frame when we exit from
566          * the system call. */
567         pxMpuSettings->xSystemCallStackInfo.pulTaskStack = pulTaskStack + ulStackFrameSize;
568
569         /* Store the value of the Link Register before the SVC was raised. We need to
570          * restore it when we exit from the system call. */
571         pxMpuSettings->xSystemCallStackInfo.ulLinkRegisterAtSystemCallEntry = pulTaskStack[ portOFFSET_TO_LR ];
572
573         /* Record if the hardware used padding to force the stack pointer
574          * to be double word aligned. */
575         if( ( pulTaskStack[ portOFFSET_TO_PSR ] & portPSR_STACK_PADDING_MASK ) == portPSR_STACK_PADDING_MASK )
576         {
577             pxMpuSettings->ulTaskFlags |= portSTACK_FRAME_HAS_PADDING_FLAG;
578         }
579         else
580         {
581             pxMpuSettings->ulTaskFlags &= ( ~portSTACK_FRAME_HAS_PADDING_FLAG );
582         }
583
584         /* We ensure in pxPortInitialiseStack that the system call stack is
585          * double word aligned and therefore, there is no need of padding.
586          * Clear the bit[9] of stacked xPSR. */
587         pulSystemCallStack[ portOFFSET_TO_PSR ] &= ( ~portPSR_STACK_PADDING_MASK );
588     }
589 }
590
591 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
592 /*-----------------------------------------------------------*/
593
594 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
595
596 void vSystemCallEnter_1( uint32_t * pulTaskStack, uint32_t ulLR ) /* PRIVILEGED_FUNCTION */
597 {
598     extern TaskHandle_t pxCurrentTCB;
599     xMPU_SETTINGS * pxMpuSettings;
600     uint32_t * pulSystemCallStack;
601     uint32_t ulStackFrameSize, ulSystemCallLocation, i;
602     #if defined( __ARMCC_VERSION )
603         /* Declaration when these variable are defined in code instead of being
604          * exported from linker scripts. */
605         extern uint32_t * __syscalls_flash_start__;
606         extern uint32_t * __syscalls_flash_end__;
607     #else
608         /* Declaration when these variable are exported from linker scripts. */
609         extern uint32_t __syscalls_flash_start__[];
610         extern uint32_t __syscalls_flash_end__[];
611     #endif /* #if defined( __ARMCC_VERSION ) */
612
613     ulSystemCallLocation = pulTaskStack[ portOFFSET_TO_PC ];
614
615     /* If the request did not come from the system call section, do nothing. */
616     if( ( ulSystemCallLocation >= ( uint32_t ) __syscalls_flash_start__ ) &&
617         ( ulSystemCallLocation <= ( uint32_t ) __syscalls_flash_end__ ) )
618     {
619         pxMpuSettings = xTaskGetMPUSettings( pxCurrentTCB );
620         pulSystemCallStack = pxMpuSettings->xSystemCallStackInfo.pulSystemCallStack;
621
622         /* This is not NULL only for the duration of the system call. */
623         configASSERT( pxMpuSettings->xSystemCallStackInfo.pulTaskStack == NULL );
624
625         if( ( ulLR & portEXC_RETURN_STACK_FRAME_TYPE_MASK ) == 0UL )
626         {
627             /* Extended frame i.e. FPU in use. */
628             ulStackFrameSize = 26;
629             __asm volatile (
630                                 " vpush {s0}         \n" /* Trigger lazy stacking. */
631                                 " vpop  {s0}         \n" /* Nullify the affect of the above instruction. */
632                                 ::: "memory"
633                            );
634         }
635         else
636         {
637             /* Standard frame i.e. FPU not in use. */
638             ulStackFrameSize = 8;
639         }
640
641         /* Make space on the system call stack for the stack frame and
642          * the parameter passed on the stack. We only need to copy one
643          * parameter but we still reserve 2 spaces to keep the stack
644          * double word aligned. */
645         pulSystemCallStack = pulSystemCallStack - ulStackFrameSize - 2UL;
646
647         /* Copy the stack frame. */
648         for( i = 0; i < ulStackFrameSize; i++ )
649         {
650             pulSystemCallStack[ i ] = pulTaskStack[ i ];
651         }
652
653         /* Copy the parameter which is passed the stack. */
654         if( ( pulTaskStack[ portOFFSET_TO_PSR ] & portPSR_STACK_PADDING_MASK ) == portPSR_STACK_PADDING_MASK )
655         {
656             pulSystemCallStack[ ulStackFrameSize ] = pulTaskStack[ ulStackFrameSize + 1 ];
657             /* Record if the hardware used padding to force the stack pointer
658              * to be double word aligned. */
659             pxMpuSettings->ulTaskFlags |= portSTACK_FRAME_HAS_PADDING_FLAG;
660         }
661         else
662         {
663             pulSystemCallStack[ ulStackFrameSize ] = pulTaskStack[ ulStackFrameSize ];
664             /* Record if the hardware used padding to force the stack pointer
665              * to be double word aligned. */
666             pxMpuSettings->ulTaskFlags &= ( ~portSTACK_FRAME_HAS_PADDING_FLAG );
667         }
668
669         /* Use the pulSystemCallStack in thread mode. */
670         __asm volatile ( "msr psp, %0" : : "r" ( pulSystemCallStack ) );
671
672         /* Raise the privilege for the duration of the system call. */
673         __asm volatile (
674                             " mrs r1, control     \n" /* Obtain current control value. */
675                             " bic r1, #1          \n" /* Clear nPRIV bit. */
676                             " msr control, r1     \n" /* Write back new control value. */
677                             ::: "r1", "memory"
678                         );
679
680         /* Remember the location where we should copy the stack frame when we exit from
681          * the system call. */
682         pxMpuSettings->xSystemCallStackInfo.pulTaskStack = pulTaskStack + ulStackFrameSize;
683
684         /* Store the value of the Link Register before the SVC was raised. We need to
685          * restore it when we exit from the system call. */
686         pxMpuSettings->xSystemCallStackInfo.ulLinkRegisterAtSystemCallEntry = pulTaskStack[ portOFFSET_TO_LR ];
687
688         /* We ensure in pxPortInitialiseStack that the system call stack is
689          * double word aligned and therefore, there is no need of padding.
690          * Clear the bit[9] of stacked xPSR. */
691         pulSystemCallStack[ portOFFSET_TO_PSR ] &= ( ~portPSR_STACK_PADDING_MASK );
692     }
693 }
694
695 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
696 /*-----------------------------------------------------------*/
697
698 #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
699
700 void vSystemCallExit( uint32_t * pulSystemCallStack, uint32_t ulLR ) /* PRIVILEGED_FUNCTION */
701 {
702     extern TaskHandle_t pxCurrentTCB;
703     xMPU_SETTINGS * pxMpuSettings;
704     uint32_t * pulTaskStack;
705     uint32_t ulStackFrameSize, ulSystemCallLocation, i;
706     #if defined( __ARMCC_VERSION )
707         /* Declaration when these variable are defined in code instead of being
708          * exported from linker scripts. */
709         extern uint32_t * __syscalls_flash_start__;
710         extern uint32_t * __syscalls_flash_end__;
711     #else
712         /* Declaration when these variable are exported from linker scripts. */
713         extern uint32_t __syscalls_flash_start__[];
714         extern uint32_t __syscalls_flash_end__[];
715     #endif /* #if defined( __ARMCC_VERSION ) */
716
717     ulSystemCallLocation = pulSystemCallStack[ portOFFSET_TO_PC ];
718
719     /* If the request did not come from the system call section, do nothing. */
720     if( ( ulSystemCallLocation >= ( uint32_t ) __syscalls_flash_start__ ) &&
721         ( ulSystemCallLocation <= ( uint32_t ) __syscalls_flash_end__ ) )
722     {
723         pxMpuSettings = xTaskGetMPUSettings( pxCurrentTCB );
724         pulTaskStack = pxMpuSettings->xSystemCallStackInfo.pulTaskStack;
725
726         if( ( ulLR & portEXC_RETURN_STACK_FRAME_TYPE_MASK ) == 0UL )
727         {
728             /* Extended frame i.e. FPU in use. */
729             ulStackFrameSize = 26;
730             __asm volatile (
731                                 " vpush {s0}         \n" /* Trigger lazy stacking. */
732                                 " vpop  {s0}         \n" /* Nullify the affect of the above instruction. */
733                                 ::: "memory"
734                         );
735         }
736         else
737         {
738             /* Standard frame i.e. FPU not in use. */
739             ulStackFrameSize = 8;
740         }
741
742         /* Make space on the task stack for the stack frame. */
743         pulTaskStack = pulTaskStack - ulStackFrameSize;
744
745         /* Copy the stack frame. */
746         for( i = 0; i < ulStackFrameSize; i++ )
747         {
748             pulTaskStack[ i ] = pulSystemCallStack[ i ];
749         }
750
751         /* Use the pulTaskStack in thread mode. */
752         __asm volatile ( "msr psp, %0" : : "r" ( pulTaskStack ) );
753
754         /* Drop the privilege before returning to the thread mode. */
755         __asm volatile (
756                             " mrs r1, control     \n" /* Obtain current control value. */
757                             " orr r1, #1          \n" /* Set nPRIV bit. */
758                             " msr control, r1     \n" /* Write back new control value. */
759                             ::: "r1", "memory"
760                         );
761
762         /* Restore the stacked link register to what it was at the time of
763          * system call entry. */
764         pulTaskStack[ portOFFSET_TO_LR ] = pxMpuSettings->xSystemCallStackInfo.ulLinkRegisterAtSystemCallEntry;
765
766         /* If the hardware used padding to force the stack pointer
767          * to be double word aligned, set the stacked xPSR bit[9],
768          * otherwise clear it. */
769         if( ( pxMpuSettings->ulTaskFlags & portSTACK_FRAME_HAS_PADDING_FLAG ) == portSTACK_FRAME_HAS_PADDING_FLAG )
770         {
771             pulTaskStack[ portOFFSET_TO_PSR ] |= portPSR_STACK_PADDING_MASK;
772         }
773         else
774         {
775             pulTaskStack[ portOFFSET_TO_PSR ] &= ( ~portPSR_STACK_PADDING_MASK );
776         }
777
778         /* This is not NULL only for the duration of the system call. */
779         pxMpuSettings->xSystemCallStackInfo.pulTaskStack = NULL;
780     }
781 }
782
783 #endif /* #if ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
784 /*-----------------------------------------------------------*/
785
786 BaseType_t xPortIsTaskPrivileged( void ) /* PRIVILEGED_FUNCTION */
787 {
788     BaseType_t xTaskIsPrivileged = pdFALSE;
789     const xMPU_SETTINGS * xTaskMpuSettings = xTaskGetMPUSettings( NULL ); /* Calling task's MPU settings. */
790
791     if( ( xTaskMpuSettings->ulTaskFlags & portTASK_IS_PRIVILEGED_FLAG ) == portTASK_IS_PRIVILEGED_FLAG )
792     {
793         xTaskIsPrivileged = pdTRUE;
794     }
795
796     return xTaskIsPrivileged;
797 }
798 /*-----------------------------------------------------------*/
799
800 static void prvRestoreContextOfFirstTask( void )
801 {
802     __asm volatile
803     (
804         " ldr r0, =0xE000ED08                   \n" /* Use the NVIC offset register to locate the stack. */
805         " ldr r0, [r0]                          \n"
806         " ldr r0, [r0]                          \n"
807         " msr msp, r0                           \n" /* Set the msp back to the start of the stack. */
808         "                                       \n"
809         /*------------ Program MPU. ------------ */
810         " ldr r3, pxCurrentTCBConst2            \n" /* r3 = pxCurrentTCBConst2. */
811         " ldr r2, [r3]                          \n" /* r2 = pxCurrentTCB. */
812         " add r2, r2, #4                        \n" /* r2 = Second item in the TCB which is xMPUSettings. */
813         "                                       \n"
814         " dmb                                   \n" /* Complete outstanding transfers before disabling MPU. */
815         " ldr r0, =0xe000ed94                   \n" /* MPU_CTRL register. */
816         " ldr r3, [r0]                          \n" /* Read the value of MPU_CTRL. */
817         " bic r3, #1                            \n" /* r3 = r3 & ~1 i.e. Clear the bit 0 in r3. */
818         " str r3, [r0]                          \n" /* Disable MPU. */
819         "                                       \n"
820         " ldr r0, =0xe000ed9c                   \n" /* Region Base Address register. */
821         " ldmia r2!, {r4-r11}                   \n" /* Read 4 sets of MPU registers [MPU Region # 0 - 3]. */
822         " stmia r0, {r4-r11}                    \n" /* Write 4 sets of MPU registers [MPU Region # 0 - 3]. */
823         "                                       \n"
824     #if ( configTOTAL_MPU_REGIONS == 16 )
825         " ldmia r2!, {r4-r11}                   \n" /* Read 4 sets of MPU registers [MPU Region # 4 - 8]. */
826         " stmia r0, {r4-r11}                    \n" /* Write 4 sets of MPU registers. [MPU Region # 4 - 8]. */
827         " ldmia r2!, {r4-r11}                   \n" /* Read 4 sets of MPU registers [MPU Region # 9 - 12]. */
828         " stmia r0, {r4-r11}                    \n" /* Write 4 sets of MPU registers. [MPU Region # 9 - 12]. */
829     #endif /* configTOTAL_MPU_REGIONS == 16. */
830         "                                       \n"
831         " ldr r0, =0xe000ed94                   \n" /* MPU_CTRL register. */
832         " ldr r3, [r0]                          \n" /* Read the value of MPU_CTRL. */
833         " orr r3, #1                            \n" /* r3 = r3 | 1 i.e. Set the bit 0 in r3. */
834         " str r3, [r0]                          \n" /* Enable MPU. */
835         " dsb                                   \n" /* Force memory writes before continuing. */
836         "                                       \n"
837         /*---------- Restore Context. ---------- */
838         " ldr r3, pxCurrentTCBConst2            \n" /* r3 = pxCurrentTCBConst2. */
839         " ldr r2, [r3]                          \n" /* r2 = pxCurrentTCB. */
840         " ldr r1, [r2]                          \n" /* r1 = Location of saved context in TCB. */
841         "                                       \n"
842         " ldmdb r1!, {r0, r4-r11}               \n" /* r0 contains PSP after the hardware had saved context. r4-r11 contain hardware saved context. */
843         " msr psp, r0                           \n"
844         " stmia r0, {r4-r11}                    \n" /* Copy the hardware saved context on the task stack. */
845         " ldmdb r1!, {r3-r11, lr}               \n" /* r3 contains CONTROL register. r4-r11 and LR restored. */
846         " msr control, r3                       \n"
847         " str r1, [r2]                          \n" /* Save the location where the context should be saved next as the first member of TCB. */
848         "                                       \n"
849         " mov r0, #0                            \n"
850         " msr basepri, r0                       \n"
851         " bx lr                                 \n"
852         "                                       \n"
853         " .ltorg                                \n" /* Assemble current literal pool to avoid offset-out-of-bound errors with lto. */
854         " .align 4                              \n"
855         " pxCurrentTCBConst2: .word pxCurrentTCB\n"
856     );
857 }
858 /*-----------------------------------------------------------*/
859
860 /*
861  * See header file for description.
862  */
863 BaseType_t xPortStartScheduler( void )
864 {
865     /* Errata 837070 workaround must only be enabled on Cortex-M7 r0p0
866      * and r0p1 cores. */
867     #if ( configENABLE_ERRATA_837070_WORKAROUND == 1 )
868         configASSERT( ( portCPUID == portCORTEX_M7_r0p1_ID ) || ( portCPUID == portCORTEX_M7_r0p0_ID ) );
869     #else
870         /* When using this port on a Cortex-M7 r0p0 or r0p1 core, define
871          * configENABLE_ERRATA_837070_WORKAROUND to 1 in your
872          * FreeRTOSConfig.h. */
873         configASSERT( portCPUID != portCORTEX_M7_r0p1_ID );
874         configASSERT( portCPUID != portCORTEX_M7_r0p0_ID );
875     #endif
876
877     #if ( configASSERT_DEFINED == 1 )
878         {
879             volatile uint8_t ucOriginalPriority;
880             volatile uint32_t ulImplementedPrioBits = 0;
881             volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
882             volatile uint8_t ucMaxPriorityValue;
883
884             /* Determine the maximum priority from which ISR safe FreeRTOS API
885              * functions can be called.  ISR safe functions are those that end in
886              * "FromISR".  FreeRTOS maintains separate thread and ISR API functions to
887              * ensure interrupt entry is as fast and simple as possible.
888              *
889              * Save the interrupt priority value that is about to be clobbered. */
890             ucOriginalPriority = *pucFirstUserPriorityRegister;
891
892             /* Determine the number of priority bits available.  First write to all
893              * possible bits. */
894             *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
895
896             /* Read the value back to see how many bits stuck. */
897             ucMaxPriorityValue = *pucFirstUserPriorityRegister;
898
899             /* Use the same mask on the maximum system call priority. */
900             ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
901
902             /* Check that the maximum system call priority is nonzero after
903              * accounting for the number of priority bits supported by the
904              * hardware. A priority of 0 is invalid because setting the BASEPRI
905              * register to 0 unmasks all interrupts, and interrupts with priority 0
906              * cannot be masked using BASEPRI.
907              * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
908             configASSERT( ucMaxSysCallPriority );
909
910             /* Check that the bits not implemented in hardware are zero in
911              * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
912             configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
913
914             /* Calculate the maximum acceptable priority group value for the number
915              * of bits read back. */
916
917             while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
918             {
919                 ulImplementedPrioBits++;
920                 ucMaxPriorityValue <<= ( uint8_t ) 0x01;
921             }
922
923             if( ulImplementedPrioBits == 8 )
924             {
925                 /* When the hardware implements 8 priority bits, there is no way for
926                 * the software to configure PRIGROUP to not have sub-priorities. As
927                 * a result, the least significant bit is always used for sub-priority
928                 * and there are 128 preemption priorities and 2 sub-priorities.
929                 *
930                 * This may cause some confusion in some cases - for example, if
931                 * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
932                 * priority interrupts will be masked in Critical Sections as those
933                 * are at the same preemption priority. This may appear confusing as
934                 * 4 is higher (numerically lower) priority than
935                 * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
936                 * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
937                 * to 4, this confusion does not happen and the behaviour remains the same.
938                 *
939                 * The following assert ensures that the sub-priority bit in the
940                 * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
941                 * confusion. */
942                 configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
943                 ulMaxPRIGROUPValue = 0;
944             }
945             else
946             {
947                 ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
948             }
949
950             /* Shift the priority group value back to its position within the AIRCR
951              * register. */
952             ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
953             ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
954
955             /* Restore the clobbered interrupt priority register to its original
956              * value. */
957             *pucFirstUserPriorityRegister = ucOriginalPriority;
958         }
959     #endif /* configASSERT_DEFINED */
960
961     /* Make PendSV and SysTick the same priority as the kernel, and the SVC
962      * handler higher priority so it can be used to exit a critical section (where
963      * lower priorities are masked). */
964     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
965     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
966
967     /* Configure the regions in the MPU that are common to all tasks. */
968     prvSetupMPU();
969
970     /* Start the timer that generates the tick ISR.  Interrupts are disabled
971      * here already. */
972     vPortSetupTimerInterrupt();
973
974     /* Initialise the critical nesting count ready for the first task. */
975     uxCriticalNesting = 0;
976
977     /* Ensure the VFP is enabled - it should be anyway. */
978     vPortEnableVFP();
979
980     /* Lazy save always. */
981     *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS;
982
983     /* Start the first task.  This also clears the bit that indicates the FPU is
984      * in use in case the FPU was used before the scheduler was started - which
985      * would otherwise result in the unnecessary leaving of space in the SVC stack
986      * for lazy saving of FPU registers. */
987     __asm volatile (
988         " ldr r0, =0xE000ED08   \n"/* Use the NVIC offset register to locate the stack. */
989         " ldr r0, [r0]          \n"
990         " ldr r0, [r0]          \n"
991         " msr msp, r0           \n"/* Set the msp back to the start of the stack. */
992         " mov r0, #0            \n"/* Clear the bit that indicates the FPU is in use, see comment above. */
993         " msr control, r0       \n"
994         " cpsie i               \n"/* Globally enable interrupts. */
995         " cpsie f               \n"
996         " dsb                   \n"
997         " isb                   \n"
998         " svc %0                \n"/* System call to start first task. */
999         " nop                   \n"
1000         " .ltorg                \n"
1001         ::"i" ( portSVC_START_SCHEDULER ) : "memory" );
1002
1003     /* Should not get here! */
1004     return 0;
1005 }
1006 /*-----------------------------------------------------------*/
1007
1008 void vPortEndScheduler( void )
1009 {
1010     /* Not implemented in ports where there is nothing to return to.
1011      * Artificially force an assert. */
1012     configASSERT( uxCriticalNesting == 1000UL );
1013 }
1014 /*-----------------------------------------------------------*/
1015
1016 void vPortEnterCritical( void )
1017 {
1018 #if( configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS == 1 )
1019     if( portIS_PRIVILEGED() == pdFALSE )
1020     {
1021         portRAISE_PRIVILEGE();
1022         portMEMORY_BARRIER();
1023
1024         portDISABLE_INTERRUPTS();
1025         uxCriticalNesting++;
1026         portMEMORY_BARRIER();
1027
1028         portRESET_PRIVILEGE();
1029         portMEMORY_BARRIER();
1030     }
1031     else
1032     {
1033         portDISABLE_INTERRUPTS();
1034         uxCriticalNesting++;
1035     }
1036 #else
1037     portDISABLE_INTERRUPTS();
1038     uxCriticalNesting++;
1039 #endif
1040 }
1041 /*-----------------------------------------------------------*/
1042
1043 void vPortExitCritical( void )
1044 {
1045 #if( configALLOW_UNPRIVILEGED_CRITICAL_SECTIONS == 1 )
1046     if( portIS_PRIVILEGED() == pdFALSE )
1047     {
1048         portRAISE_PRIVILEGE();
1049         portMEMORY_BARRIER();
1050
1051         configASSERT( uxCriticalNesting );
1052         uxCriticalNesting--;
1053
1054         if( uxCriticalNesting == 0 )
1055         {
1056             portENABLE_INTERRUPTS();
1057         }
1058         portMEMORY_BARRIER();
1059
1060         portRESET_PRIVILEGE();
1061         portMEMORY_BARRIER();
1062     }
1063     else
1064     {
1065         configASSERT( uxCriticalNesting );
1066         uxCriticalNesting--;
1067
1068         if( uxCriticalNesting == 0 )
1069         {
1070             portENABLE_INTERRUPTS();
1071         }
1072     }
1073 #else
1074     configASSERT( uxCriticalNesting );
1075     uxCriticalNesting--;
1076
1077     if( uxCriticalNesting == 0 )
1078     {
1079         portENABLE_INTERRUPTS();
1080     }
1081 #endif
1082 }
1083 /*-----------------------------------------------------------*/
1084
1085 void xPortPendSVHandler( void )
1086 {
1087     /* This is a naked function. */
1088
1089     __asm volatile
1090     (
1091         " ldr r3, pxCurrentTCBConst             \n" /* r3 = pxCurrentTCBConst. */
1092         " ldr r2, [r3]                          \n" /* r2 = pxCurrentTCB. */
1093         " ldr r1, [r2]                          \n" /* r1 = Location where the context should be saved. */
1094         "                                       \n"
1095         /*------------ Save Context. ----------- */
1096         " mrs r3, control                       \n"
1097         " mrs r0, psp                           \n"
1098         " isb                                   \n"
1099         "                                       \n"
1100         " add r0, r0, #0x20                     \n" /* Move r0 to location where s0 is saved. */
1101         " tst lr, #0x10                         \n"
1102         " ittt eq                               \n"
1103         " vstmiaeq r1!, {s16-s31}               \n" /* Store s16-s31. */
1104         " vldmiaeq r0, {s0-s16}                 \n" /* Copy hardware saved FP context into s0-s16. */
1105         " vstmiaeq r1!, {s0-s16}                \n" /* Store hardware saved FP context. */
1106         " sub r0, r0, #0x20                     \n" /* Set r0 back to the location of hardware saved context. */
1107         "                                       \n"
1108         " stmia r1!, {r3-r11, lr}               \n" /* Store CONTROL register, r4-r11 and LR. */
1109         " ldmia r0, {r4-r11}                    \n" /* Copy hardware saved context into r4-r11. */
1110         " stmia r1!, {r0, r4-r11}               \n" /* Store original PSP (after hardware has saved context) and the hardware saved context. */
1111         " str r1, [r2]                          \n" /* Save the location from where the context should be restored as the first member of TCB. */
1112         "                                       \n"
1113         /*---------- Select next task. --------- */
1114         " mov r0, %0                            \n"
1115     #if ( configENABLE_ERRATA_837070_WORKAROUND == 1 )
1116         " cpsid i                               \n" /* ARM Cortex-M7 r0p1 Errata 837070 workaround. */
1117     #endif
1118         " msr basepri, r0                       \n"
1119         " dsb                                   \n"
1120         " isb                                   \n"
1121     #if ( configENABLE_ERRATA_837070_WORKAROUND == 1 )
1122         " cpsie i                               \n" /* ARM Cortex-M7 r0p1 Errata 837070 workaround. */
1123     #endif
1124         " bl vTaskSwitchContext                 \n"
1125         " mov r0, #0                            \n"
1126         " msr basepri, r0                       \n"
1127         "                                       \n"
1128         /*------------ Program MPU. ------------ */
1129         " ldr r3, pxCurrentTCBConst             \n" /* r3 = pxCurrentTCBConst. */
1130         " ldr r2, [r3]                          \n" /* r2 = pxCurrentTCB. */
1131         " add r2, r2, #4                        \n" /* r2 = Second item in the TCB which is xMPUSettings. */
1132         "                                       \n"
1133         " dmb                                   \n" /* Complete outstanding transfers before disabling MPU. */
1134         " ldr r0, =0xe000ed94                   \n" /* MPU_CTRL register. */
1135         " ldr r3, [r0]                          \n" /* Read the value of MPU_CTRL. */
1136         " bic r3, #1                            \n" /* r3 = r3 & ~1 i.e. Clear the bit 0 in r3. */
1137         " str r3, [r0]                          \n" /* Disable MPU. */
1138         "                                       \n"
1139         " ldr r0, =0xe000ed9c                   \n" /* Region Base Address register. */
1140         " ldmia r2!, {r4-r11}                   \n" /* Read 4 sets of MPU registers [MPU Region # 0 - 3]. */
1141         " stmia r0, {r4-r11}                    \n" /* Write 4 sets of MPU registers [MPU Region # 0 - 3]. */
1142         "                                       \n"
1143     #if ( configTOTAL_MPU_REGIONS == 16 )
1144         " ldmia r2!, {r4-r11}                   \n" /* Read 4 sets of MPU registers [MPU Region # 4 - 7]. */
1145         " stmia r0, {r4-r11}                    \n" /* Write 4 sets of MPU registers. [MPU Region # 4 - 7]. */
1146         " ldmia r2!, {r4-r11}                   \n" /* Read 4 sets of MPU registers [MPU Region # 8 - 11]. */
1147         " stmia r0, {r4-r11}                    \n" /* Write 4 sets of MPU registers. [MPU Region # 8 - 11]. */
1148     #endif /* configTOTAL_MPU_REGIONS == 16. */
1149         "                                       \n"
1150         " ldr r0, =0xe000ed94                   \n" /* MPU_CTRL register. */
1151         " ldr r3, [r0]                          \n" /* Read the value of MPU_CTRL. */
1152         " orr r3, #1                            \n" /* r3 = r3 | 1 i.e. Set the bit 0 in r3. */
1153         " str r3, [r0]                          \n" /* Enable MPU. */
1154         " dsb                                   \n" /* Force memory writes before continuing. */
1155         "                                       \n"
1156         /*---------- Restore Context. ---------- */
1157         " ldr r3, pxCurrentTCBConst             \n" /* r3 = pxCurrentTCBConst. */
1158         " ldr r2, [r3]                          \n" /* r2 = pxCurrentTCB. */
1159         " ldr r1, [r2]                          \n" /* r1 = Location of saved context in TCB. */
1160         "                                       \n"
1161         " ldmdb r1!, {r0, r4-r11}               \n" /* r0 contains PSP after the hardware had saved context. r4-r11 contain hardware saved context. */
1162         " msr psp, r0                           \n"
1163         " stmia r0!, {r4-r11}                   \n" /* Copy the hardware saved context on the task stack. */
1164         " ldmdb r1!, {r3-r11, lr}               \n" /* r3 contains CONTROL register. r4-r11 and LR restored. */
1165         " msr control, r3                       \n"
1166
1167         " tst lr, #0x10                         \n"
1168         " ittt eq                               \n"
1169         " vldmdbeq r1!, {s0-s16}                \n" /* s0-s16 contain hardware saved FP context. */
1170         " vstmiaeq r0!, {s0-s16}                \n" /* Copy hardware saved FP context on the task stack. */
1171         " vldmdbeq r1!, {s16-s31}               \n" /* Restore s16-s31. */
1172
1173         " str r1, [r2]                          \n" /* Save the location where the context should be saved next as the first member of TCB. */
1174         " bx lr                                 \n"
1175         "                                       \n"
1176         " .ltorg                                \n" /* Assemble the current literal pool to avoid offset-out-of-bound errors with lto. */
1177         " .align 4                              \n"
1178         " pxCurrentTCBConst: .word pxCurrentTCB \n"
1179         ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
1180     );
1181 }
1182 /*-----------------------------------------------------------*/
1183
1184 void xPortSysTickHandler( void )
1185 {
1186     uint32_t ulDummy;
1187
1188     ulDummy = portSET_INTERRUPT_MASK_FROM_ISR();
1189     {
1190         /* Increment the RTOS tick. */
1191         if( xTaskIncrementTick() != pdFALSE )
1192         {
1193             /* Pend a context switch. */
1194             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
1195         }
1196     }
1197     portCLEAR_INTERRUPT_MASK_FROM_ISR( ulDummy );
1198 }
1199 /*-----------------------------------------------------------*/
1200
1201 /*
1202  * Setup the systick timer to generate the tick interrupts at the required
1203  * frequency.
1204  */
1205 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
1206 {
1207     /* Stop and clear the SysTick. */
1208     portNVIC_SYSTICK_CTRL_REG = 0UL;
1209     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
1210
1211     /* Configure SysTick to interrupt at the requested rate. */
1212     portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
1213     portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE );
1214 }
1215 /*-----------------------------------------------------------*/
1216
1217 /* This is a naked function. */
1218 static void vPortEnableVFP( void )
1219 {
1220     __asm volatile
1221     (
1222         "   ldr.w r0, =0xE000ED88       \n"/* The FPU enable bits are in the CPACR. */
1223         "   ldr r1, [r0]                \n"
1224         "                               \n"
1225         "   orr r1, r1, #( 0xf << 20 )  \n"/* Enable CP10 and CP11 coprocessors, then save back. */
1226         "   str r1, [r0]                \n"
1227         "   bx r14                      \n"
1228         "   .ltorg                      \n"
1229     );
1230 }
1231 /*-----------------------------------------------------------*/
1232
1233 static void prvSetupMPU( void )
1234 {
1235     #if defined( __ARMCC_VERSION )
1236
1237         /* Declaration when these variable are defined in code instead of being
1238          * exported from linker scripts. */
1239         extern uint32_t * __privileged_functions_start__;
1240         extern uint32_t * __privileged_functions_end__;
1241         extern uint32_t * __FLASH_segment_start__;
1242         extern uint32_t * __FLASH_segment_end__;
1243         extern uint32_t * __privileged_data_start__;
1244         extern uint32_t * __privileged_data_end__;
1245     #else
1246         /* Declaration when these variable are exported from linker scripts. */
1247         extern uint32_t __privileged_functions_start__[];
1248         extern uint32_t __privileged_functions_end__[];
1249         extern uint32_t __FLASH_segment_start__[];
1250         extern uint32_t __FLASH_segment_end__[];
1251         extern uint32_t __privileged_data_start__[];
1252         extern uint32_t __privileged_data_end__[];
1253     #endif /* if defined( __ARMCC_VERSION ) */
1254
1255     /* The only permitted number of regions are 8 or 16. */
1256     configASSERT( ( configTOTAL_MPU_REGIONS == 8 ) || ( configTOTAL_MPU_REGIONS == 16 ) );
1257
1258     /* Ensure that the configTOTAL_MPU_REGIONS is configured correctly. */
1259     configASSERT( portMPU_TYPE_REG == portEXPECTED_MPU_TYPE_VALUE );
1260
1261     /* Check the expected MPU is present. */
1262     if( portMPU_TYPE_REG == portEXPECTED_MPU_TYPE_VALUE )
1263     {
1264         /* First setup the unprivileged flash for unprivileged read only access. */
1265         portMPU_REGION_BASE_ADDRESS_REG = ( ( uint32_t ) __FLASH_segment_start__ ) | /* Base address. */
1266                                           ( portMPU_REGION_VALID ) |
1267                                           ( portUNPRIVILEGED_FLASH_REGION );
1268
1269         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_READ_ONLY ) |
1270                                        ( ( configTEX_S_C_B_FLASH & portMPU_RASR_TEX_S_C_B_MASK ) << portMPU_RASR_TEX_S_C_B_LOCATION ) |
1271                                        ( prvGetMPURegionSizeSetting( ( uint32_t ) __FLASH_segment_end__ - ( uint32_t ) __FLASH_segment_start__ ) ) |
1272                                        ( portMPU_REGION_ENABLE );
1273
1274         /* Setup the privileged flash for privileged only access.  This is where
1275          * the kernel code is placed. */
1276         portMPU_REGION_BASE_ADDRESS_REG = ( ( uint32_t ) __privileged_functions_start__ ) | /* Base address. */
1277                                           ( portMPU_REGION_VALID ) |
1278                                           ( portPRIVILEGED_FLASH_REGION );
1279
1280         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_PRIVILEGED_READ_ONLY ) |
1281                                        ( ( configTEX_S_C_B_FLASH & portMPU_RASR_TEX_S_C_B_MASK ) << portMPU_RASR_TEX_S_C_B_LOCATION ) |
1282                                        ( prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_functions_end__ - ( uint32_t ) __privileged_functions_start__ ) ) |
1283                                        ( portMPU_REGION_ENABLE );
1284
1285         /* Setup the privileged data RAM region.  This is where the kernel data
1286          * is placed. */
1287         portMPU_REGION_BASE_ADDRESS_REG = ( ( uint32_t ) __privileged_data_start__ ) | /* Base address. */
1288                                           ( portMPU_REGION_VALID ) |
1289                                           ( portPRIVILEGED_RAM_REGION );
1290
1291         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_PRIVILEGED_READ_WRITE ) |
1292                                        ( portMPU_REGION_EXECUTE_NEVER ) |
1293                                        ( ( configTEX_S_C_B_SRAM & portMPU_RASR_TEX_S_C_B_MASK ) << portMPU_RASR_TEX_S_C_B_LOCATION ) |
1294                                        prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_data_end__ - ( uint32_t ) __privileged_data_start__ ) |
1295                                        ( portMPU_REGION_ENABLE );
1296
1297         /* By default allow everything to access the general peripherals.  The
1298          * system peripherals and registers are protected. */
1299         portMPU_REGION_BASE_ADDRESS_REG = ( portPERIPHERALS_START_ADDRESS ) |
1300                                           ( portMPU_REGION_VALID ) |
1301                                           ( portGENERAL_PERIPHERALS_REGION );
1302
1303         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_READ_WRITE | portMPU_REGION_EXECUTE_NEVER ) |
1304                                        ( prvGetMPURegionSizeSetting( portPERIPHERALS_END_ADDRESS - portPERIPHERALS_START_ADDRESS ) ) |
1305                                        ( portMPU_REGION_ENABLE );
1306
1307         /* Enable the memory fault exception. */
1308         portNVIC_SYS_CTRL_STATE_REG |= portNVIC_MEM_FAULT_ENABLE;
1309
1310         /* Enable the MPU with the background region configured. */
1311         portMPU_CTRL_REG |= ( portMPU_ENABLE | portMPU_BACKGROUND_ENABLE );
1312     }
1313 }
1314 /*-----------------------------------------------------------*/
1315
1316 static uint32_t prvGetMPURegionSizeSetting( uint32_t ulActualSizeInBytes )
1317 {
1318     uint32_t ulRegionSize, ulReturnValue = 4;
1319
1320     /* 32 is the smallest region size, 31 is the largest valid value for
1321      * ulReturnValue. */
1322     for( ulRegionSize = 32UL; ulReturnValue < 31UL; ( ulRegionSize <<= 1UL ) )
1323     {
1324         if( ulActualSizeInBytes <= ulRegionSize )
1325         {
1326             break;
1327         }
1328         else
1329         {
1330             ulReturnValue++;
1331         }
1332     }
1333
1334     /* Shift the code by one before returning so it can be written directly
1335      * into the the correct bit position of the attribute register. */
1336     return( ulReturnValue << 1UL );
1337 }
1338 /*-----------------------------------------------------------*/
1339
1340 BaseType_t xIsPrivileged( void ) /* __attribute__ (( naked )) */
1341 {
1342     __asm volatile
1343     (
1344         "   mrs r0, control                         \n"/* r0 = CONTROL. */
1345         "   tst r0, #1                              \n"/* Perform r0 & 1 (bitwise AND) and update the conditions flag. */
1346         "   ite ne                                  \n"
1347         "   movne r0, #0                            \n"/* CONTROL[0]!=0. Return false to indicate that the processor is not privileged. */
1348         "   moveq r0, #1                            \n"/* CONTROL[0]==0. Return true to indicate that the processor is privileged. */
1349         "   bx lr                                   \n"/* Return. */
1350         "                                           \n"
1351         "   .align 4                                \n"
1352         ::: "r0", "memory"
1353     );
1354 }
1355 /*-----------------------------------------------------------*/
1356
1357 void vResetPrivilege( void ) /* __attribute__ (( naked )) */
1358 {
1359     __asm volatile
1360     (
1361         "   mrs r0, control                         \n"/* r0 = CONTROL. */
1362         "   orr r0, #1                              \n"/* r0 = r0 | 1. */
1363         "   msr control, r0                         \n"/* CONTROL = r0. */
1364         "   bx lr                                   \n"/* Return to the caller. */
1365         ::: "r0", "memory"
1366     );
1367 }
1368 /*-----------------------------------------------------------*/
1369
1370 void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings,
1371                                 const struct xMEMORY_REGION * const xRegions,
1372                                 StackType_t * pxBottomOfStack,
1373                                 uint32_t ulStackDepth )
1374 {
1375     #if defined( __ARMCC_VERSION )
1376
1377         /* Declaration when these variable are defined in code instead of being
1378          * exported from linker scripts. */
1379         extern uint32_t * __SRAM_segment_start__;
1380         extern uint32_t * __SRAM_segment_end__;
1381         extern uint32_t * __privileged_data_start__;
1382         extern uint32_t * __privileged_data_end__;
1383     #else
1384         /* Declaration when these variable are exported from linker scripts. */
1385         extern uint32_t __SRAM_segment_start__[];
1386         extern uint32_t __SRAM_segment_end__[];
1387         extern uint32_t __privileged_data_start__[];
1388         extern uint32_t __privileged_data_end__[];
1389     #endif /* if defined( __ARMCC_VERSION ) */
1390
1391     int32_t lIndex;
1392     uint32_t ul;
1393
1394     if( xRegions == NULL )
1395     {
1396         /* No MPU regions are specified so allow access to all RAM. */
1397         xMPUSettings->xRegion[ 0 ].ulRegionBaseAddress =
1398             ( ( uint32_t ) __SRAM_segment_start__ ) | /* Base address. */
1399             ( portMPU_REGION_VALID ) |
1400             ( portSTACK_REGION ); /* Region number. */
1401
1402         xMPUSettings->xRegion[ 0 ].ulRegionAttribute =
1403             ( portMPU_REGION_READ_WRITE ) |
1404             ( portMPU_REGION_EXECUTE_NEVER ) |
1405             ( ( configTEX_S_C_B_SRAM & portMPU_RASR_TEX_S_C_B_MASK ) << portMPU_RASR_TEX_S_C_B_LOCATION ) |
1406             ( prvGetMPURegionSizeSetting( ( uint32_t ) __SRAM_segment_end__ - ( uint32_t ) __SRAM_segment_start__ ) ) |
1407             ( portMPU_REGION_ENABLE );
1408
1409         xMPUSettings->xRegionSettings[ 0 ].ulRegionStartAddress = ( uint32_t ) __SRAM_segment_start__;
1410         xMPUSettings->xRegionSettings[ 0 ].ulRegionEndAddress = ( uint32_t ) __SRAM_segment_end__;
1411         xMPUSettings->xRegionSettings[ 0 ].ulRegionPermissions = ( tskMPU_READ_PERMISSION |
1412                                                                    tskMPU_WRITE_PERMISSION );
1413
1414         /* Invalidate user configurable regions. */
1415         for( ul = 1UL; ul <= portNUM_CONFIGURABLE_REGIONS; ul++ )
1416         {
1417             xMPUSettings->xRegion[ ul ].ulRegionBaseAddress = ( ( ul - 1UL ) | portMPU_REGION_VALID );
1418             xMPUSettings->xRegion[ ul ].ulRegionAttribute = 0UL;
1419             xMPUSettings->xRegionSettings[ ul ].ulRegionStartAddress = 0UL;
1420             xMPUSettings->xRegionSettings[ ul ].ulRegionEndAddress = 0UL;
1421             xMPUSettings->xRegionSettings[ ul ].ulRegionPermissions = 0UL;
1422         }
1423     }
1424     else
1425     {
1426         /* This function is called automatically when the task is created - in
1427          * which case the stack region parameters will be valid.  At all other
1428          * times the stack parameters will not be valid and it is assumed that the
1429          * stack region has already been configured. */
1430         if( ulStackDepth > 0 )
1431         {
1432             /* Define the region that allows access to the stack. */
1433             xMPUSettings->xRegion[ 0 ].ulRegionBaseAddress =
1434                 ( ( uint32_t ) pxBottomOfStack ) |
1435                 ( portMPU_REGION_VALID ) |
1436                 ( portSTACK_REGION ); /* Region number. */
1437
1438             xMPUSettings->xRegion[ 0 ].ulRegionAttribute =
1439                 ( portMPU_REGION_READ_WRITE ) |
1440                 ( portMPU_REGION_EXECUTE_NEVER ) |
1441                 ( prvGetMPURegionSizeSetting( ulStackDepth * ( uint32_t ) sizeof( StackType_t ) ) ) |
1442                 ( ( configTEX_S_C_B_SRAM & portMPU_RASR_TEX_S_C_B_MASK ) << portMPU_RASR_TEX_S_C_B_LOCATION ) |
1443                 ( portMPU_REGION_ENABLE );
1444
1445             xMPUSettings->xRegionSettings[ 0 ].ulRegionStartAddress = ( uint32_t ) pxBottomOfStack;
1446             xMPUSettings->xRegionSettings[ 0 ].ulRegionEndAddress = ( uint32_t ) ( ( uint32_t ) ( pxBottomOfStack ) +
1447                                                                                    ( ulStackDepth * ( uint32_t ) sizeof( StackType_t ) ) - 1UL );
1448             xMPUSettings->xRegionSettings[ 0 ].ulRegionPermissions = ( tskMPU_READ_PERMISSION |
1449                                                                        tskMPU_WRITE_PERMISSION );
1450         }
1451
1452         lIndex = 0;
1453
1454         for( ul = 1UL; ul <= portNUM_CONFIGURABLE_REGIONS; ul++ )
1455         {
1456             if( ( xRegions[ lIndex ] ).ulLengthInBytes > 0UL )
1457             {
1458                 /* Translate the generic region definition contained in
1459                  * xRegions into the CM4 specific MPU settings that are then
1460                  * stored in xMPUSettings. */
1461                 xMPUSettings->xRegion[ ul ].ulRegionBaseAddress =
1462                     ( ( uint32_t ) xRegions[ lIndex ].pvBaseAddress ) |
1463                     ( portMPU_REGION_VALID ) |
1464                     ( ul - 1UL ); /* Region number. */
1465
1466                 xMPUSettings->xRegion[ ul ].ulRegionAttribute =
1467                     ( prvGetMPURegionSizeSetting( xRegions[ lIndex ].ulLengthInBytes ) ) |
1468                     ( xRegions[ lIndex ].ulParameters ) |
1469                     ( portMPU_REGION_ENABLE );
1470
1471                 xMPUSettings->xRegionSettings[ ul ].ulRegionStartAddress = ( uint32_t ) xRegions[ lIndex ].pvBaseAddress;
1472                 xMPUSettings->xRegionSettings[ ul ].ulRegionEndAddress = ( uint32_t ) ( ( uint32_t ) xRegions[ lIndex ].pvBaseAddress + xRegions[ lIndex ].ulLengthInBytes - 1UL );
1473                 xMPUSettings->xRegionSettings[ ul ].ulRegionPermissions = 0UL;
1474                 if( ( ( xRegions[ lIndex ].ulParameters & portMPU_REGION_READ_ONLY ) == portMPU_REGION_READ_ONLY ) ||
1475                     ( ( xRegions[ lIndex ].ulParameters & portMPU_REGION_PRIVILEGED_READ_WRITE_UNPRIV_READ_ONLY ) == portMPU_REGION_PRIVILEGED_READ_WRITE_UNPRIV_READ_ONLY ) )
1476                 {
1477                     xMPUSettings->xRegionSettings[ ul ].ulRegionPermissions = tskMPU_READ_PERMISSION;
1478                 }
1479                 if( ( xRegions[ lIndex ].ulParameters & portMPU_REGION_READ_WRITE ) == portMPU_REGION_READ_WRITE )
1480                 {
1481                     xMPUSettings->xRegionSettings[ ul ].ulRegionPermissions = ( tskMPU_READ_PERMISSION | tskMPU_WRITE_PERMISSION );
1482                 }
1483             }
1484             else
1485             {
1486                 /* Invalidate the region. */
1487                 xMPUSettings->xRegion[ ul ].ulRegionBaseAddress = ( ( ul - 1UL ) | portMPU_REGION_VALID );
1488                 xMPUSettings->xRegion[ ul ].ulRegionAttribute = 0UL;
1489                 xMPUSettings->xRegionSettings[ ul ].ulRegionStartAddress = 0UL;
1490                 xMPUSettings->xRegionSettings[ ul ].ulRegionEndAddress = 0UL;
1491                 xMPUSettings->xRegionSettings[ ul ].ulRegionPermissions = 0UL;
1492             }
1493
1494             lIndex++;
1495         }
1496     }
1497 }
1498 /*-----------------------------------------------------------*/
1499
1500 BaseType_t xPortIsAuthorizedToAccessBuffer( const void * pvBuffer,
1501                                             uint32_t ulBufferLength,
1502                                             uint32_t ulAccessRequested ) /* PRIVILEGED_FUNCTION */
1503
1504 {
1505     uint32_t i, ulBufferStartAddress, ulBufferEndAddress;
1506     BaseType_t xAccessGranted = pdFALSE;
1507     const xMPU_SETTINGS * xTaskMpuSettings = xTaskGetMPUSettings( NULL ); /* Calling task's MPU settings. */
1508
1509     if( ( xTaskMpuSettings->ulTaskFlags & portTASK_IS_PRIVILEGED_FLAG ) == portTASK_IS_PRIVILEGED_FLAG )
1510     {
1511         xAccessGranted = pdTRUE;
1512     }
1513     else
1514     {
1515         if( portADD_UINT32_WILL_OVERFLOW( ( ( uint32_t ) pvBuffer ), ( ulBufferLength - 1UL ) ) == pdFALSE )
1516         {
1517             ulBufferStartAddress = ( uint32_t ) pvBuffer;
1518             ulBufferEndAddress = ( ( ( uint32_t ) pvBuffer ) + ulBufferLength - 1UL );
1519
1520             for( i = 0; i < portTOTAL_NUM_REGIONS_IN_TCB; i++ )
1521             {
1522                 if( portIS_ADDRESS_WITHIN_RANGE( ulBufferStartAddress,
1523                                                  xTaskMpuSettings->xRegionSettings[ i ].ulRegionStartAddress,
1524                                                  xTaskMpuSettings->xRegionSettings[ i ].ulRegionEndAddress ) &&
1525                     portIS_ADDRESS_WITHIN_RANGE( ulBufferEndAddress,
1526                                                  xTaskMpuSettings->xRegionSettings[ i ].ulRegionStartAddress,
1527                                                  xTaskMpuSettings->xRegionSettings[ i ].ulRegionEndAddress ) &&
1528                     portIS_AUTHORIZED( ulAccessRequested, xTaskMpuSettings->xRegionSettings[ i ].ulRegionPermissions ) )
1529                 {
1530                     xAccessGranted = pdTRUE;
1531                     break;
1532                 }
1533             }
1534         }
1535     }
1536
1537     return xAccessGranted;
1538 }
1539 /*-----------------------------------------------------------*/
1540
1541 #if ( configASSERT_DEFINED == 1 )
1542
1543     void vPortValidateInterruptPriority( void )
1544     {
1545         uint32_t ulCurrentInterrupt;
1546         uint8_t ucCurrentPriority;
1547
1548         /* Obtain the number of the currently executing interrupt. */
1549         __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
1550
1551         /* Is the interrupt number a user defined interrupt? */
1552         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
1553         {
1554             /* Look up the interrupt's priority. */
1555             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
1556
1557             /* The following assertion will fail if a service routine (ISR) for
1558              * an interrupt that has been assigned a priority above
1559              * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
1560              * function.  ISR safe FreeRTOS API functions must *only* be called
1561              * from interrupts that have been assigned a priority at or below
1562              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
1563              *
1564              * Numerically low interrupt priority numbers represent logically high
1565              * interrupt priorities, therefore the priority of the interrupt must
1566              * be set to a value equal to or numerically *higher* than
1567              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
1568              *
1569              * Interrupts that use the FreeRTOS API must not be left at their
1570              * default priority of zero as that is the highest possible priority,
1571              * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
1572              * and therefore also guaranteed to be invalid.
1573              *
1574              * FreeRTOS maintains separate thread and ISR API functions to ensure
1575              * interrupt entry is as fast and simple as possible.
1576              *
1577              * The following links provide detailed information:
1578              * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
1579              * https://www.FreeRTOS.org/FAQHelp.html */
1580             configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
1581         }
1582
1583         /* Priority grouping:  The interrupt controller (NVIC) allows the bits
1584          * that define each interrupt's priority to be split between bits that
1585          * define the interrupt's pre-emption priority bits and bits that define
1586          * the interrupt's sub-priority.  For simplicity all bits must be defined
1587          * to be pre-emption priority bits.  The following assertion will fail if
1588          * this is not the case (if some bits represent a sub-priority).
1589          *
1590          * If the application only uses CMSIS libraries for interrupt
1591          * configuration then the correct setting can be achieved on all Cortex-M
1592          * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
1593          * scheduler.  Note however that some vendor specific peripheral libraries
1594          * assume a non-zero priority group setting, in which cases using a value
1595          * of zero will result in unpredicable behaviour. */
1596         configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
1597     }
1598
1599 #endif /* configASSERT_DEFINED */
1600 /*-----------------------------------------------------------*/