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