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