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