]> begriffs open source - freertos/blob - portable/IAR/ARM_CM23/non_secure/port.c
Update system call entry mechanism (#896)
[freertos] / portable / IAR / ARM_CM23 / non_secure / port.c
1 /*
2  * FreeRTOS Kernel V10.6.1
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 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
30  * all the API functions to use the MPU wrappers. That should only be done when
31  * task.h is included from an application file. */
32 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
33
34 /* Scheduler includes. */
35 #include "FreeRTOS.h"
36 #include "task.h"
37
38 /* MPU includes. */
39 #include "mpu_wrappers.h"
40 #include "mpu_syscall_numbers.h"
41
42 /* Portasm includes. */
43 #include "portasm.h"
44
45 #if ( configENABLE_TRUSTZONE == 1 )
46     /* Secure components includes. */
47     #include "secure_context.h"
48     #include "secure_init.h"
49 #endif /* configENABLE_TRUSTZONE */
50
51 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
52
53 /**
54  * The FreeRTOS Cortex M33 port can be configured to run on the Secure Side only
55  * i.e. the processor boots as secure and never jumps to the non-secure side.
56  * The Trust Zone support in the port must be disabled in order to run FreeRTOS
57  * on the secure side. The following are the valid configuration seetings:
58  *
59  * 1. Run FreeRTOS on the Secure Side:
60  *    configRUN_FREERTOS_SECURE_ONLY = 1 and configENABLE_TRUSTZONE = 0
61  *
62  * 2. Run FreeRTOS on the Non-Secure Side with Secure Side function call support:
63  *    configRUN_FREERTOS_SECURE_ONLY = 0 and configENABLE_TRUSTZONE = 1
64  *
65  * 3. Run FreeRTOS on the Non-Secure Side only i.e. no Secure Side function call support:
66  *    configRUN_FREERTOS_SECURE_ONLY = 0 and configENABLE_TRUSTZONE = 0
67  */
68 #if ( ( configRUN_FREERTOS_SECURE_ONLY == 1 ) && ( configENABLE_TRUSTZONE == 1 ) )
69     #error TrustZone needs to be disabled in order to run FreeRTOS on the Secure Side.
70 #endif
71 /*-----------------------------------------------------------*/
72
73 /**
74  * @brief Constants required to manipulate the NVIC.
75  */
76 #define portNVIC_SYSTICK_CTRL_REG             ( *( ( volatile uint32_t * ) 0xe000e010 ) )
77 #define portNVIC_SYSTICK_LOAD_REG             ( *( ( volatile uint32_t * ) 0xe000e014 ) )
78 #define portNVIC_SYSTICK_CURRENT_VALUE_REG    ( *( ( volatile uint32_t * ) 0xe000e018 ) )
79 #define portNVIC_SHPR3_REG                    ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
80 #define portNVIC_SYSTICK_ENABLE_BIT           ( 1UL << 0UL )
81 #define portNVIC_SYSTICK_INT_BIT              ( 1UL << 1UL )
82 #define portNVIC_SYSTICK_CLK_BIT              ( 1UL << 2UL )
83 #define portNVIC_SYSTICK_COUNT_FLAG_BIT       ( 1UL << 16UL )
84 #define portNVIC_PEND_SYSTICK_CLEAR_BIT       ( 1UL << 25UL )
85 #define portNVIC_PEND_SYSTICK_SET_BIT         ( 1UL << 26UL )
86 #define portMIN_INTERRUPT_PRIORITY            ( 255UL )
87 #define portNVIC_PENDSV_PRI                   ( portMIN_INTERRUPT_PRIORITY << 16UL )
88 #define portNVIC_SYSTICK_PRI                  ( portMIN_INTERRUPT_PRIORITY << 24UL )
89 /*-----------------------------------------------------------*/
90
91 /**
92  * @brief Constants required to manipulate the SCB.
93  */
94 #define portSCB_SYS_HANDLER_CTRL_STATE_REG    ( *( volatile uint32_t * ) 0xe000ed24 )
95 #define portSCB_MEM_FAULT_ENABLE_BIT          ( 1UL << 16UL )
96 /*-----------------------------------------------------------*/
97
98 /**
99  * @brief Constants required to check the validity of an interrupt priority.
100  */
101 #define portNVIC_SHPR2_REG                 ( *( ( volatile uint32_t * ) 0xE000ED1C ) )
102 #define portFIRST_USER_INTERRUPT_NUMBER    ( 16 )
103 #define portNVIC_IP_REGISTERS_OFFSET_16    ( 0xE000E3F0 )
104 #define portAIRCR_REG                      ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
105 #define portTOP_BIT_OF_BYTE                ( ( uint8_t ) 0x80 )
106 #define portMAX_PRIGROUP_BITS              ( ( uint8_t ) 7 )
107 #define portPRIORITY_GROUP_MASK            ( 0x07UL << 8UL )
108 #define portPRIGROUP_SHIFT                 ( 8UL )
109 /*-----------------------------------------------------------*/
110
111 /**
112  * @brief Constants used during system call enter and exit.
113  */
114 #define portPSR_STACK_PADDING_MASK                ( 1UL << 9UL )
115 #define portEXC_RETURN_STACK_FRAME_TYPE_MASK      ( 1UL << 4UL )
116 /*-----------------------------------------------------------*/
117
118 /**
119  * @brief Constants required to manipulate the FPU.
120  */
121 #define portCPACR               ( ( volatile uint32_t * ) 0xe000ed88 )              /* Coprocessor Access Control Register. */
122 #define portCPACR_CP10_VALUE    ( 3UL )
123 #define portCPACR_CP11_VALUE    portCPACR_CP10_VALUE
124 #define portCPACR_CP10_POS      ( 20UL )
125 #define portCPACR_CP11_POS      ( 22UL )
126
127 #define portFPCCR               ( ( volatile uint32_t * ) 0xe000ef34 )              /* Floating Point Context Control Register. */
128 #define portFPCCR_ASPEN_POS     ( 31UL )
129 #define portFPCCR_ASPEN_MASK    ( 1UL << portFPCCR_ASPEN_POS )
130 #define portFPCCR_LSPEN_POS     ( 30UL )
131 #define portFPCCR_LSPEN_MASK    ( 1UL << portFPCCR_LSPEN_POS )
132 /*-----------------------------------------------------------*/
133
134 /**
135  * @brief Offsets in the stack to the parameters when inside the SVC handler.
136  */
137 #define portOFFSET_TO_LR                    ( 5 )
138 #define portOFFSET_TO_PC                    ( 6 )
139 #define portOFFSET_TO_PSR                   ( 7 )
140 /*-----------------------------------------------------------*/
141
142 /**
143  * @brief Constants required to manipulate the MPU.
144  */
145 #define portMPU_TYPE_REG                      ( *( ( volatile uint32_t * ) 0xe000ed90 ) )
146 #define portMPU_CTRL_REG                      ( *( ( volatile uint32_t * ) 0xe000ed94 ) )
147 #define portMPU_RNR_REG                       ( *( ( volatile uint32_t * ) 0xe000ed98 ) )
148
149 #define portMPU_RBAR_REG                      ( *( ( volatile uint32_t * ) 0xe000ed9c ) )
150 #define portMPU_RLAR_REG                      ( *( ( volatile uint32_t * ) 0xe000eda0 ) )
151
152 #define portMPU_RBAR_A1_REG                   ( *( ( volatile uint32_t * ) 0xe000eda4 ) )
153 #define portMPU_RLAR_A1_REG                   ( *( ( volatile uint32_t * ) 0xe000eda8 ) )
154
155 #define portMPU_RBAR_A2_REG                   ( *( ( volatile uint32_t * ) 0xe000edac ) )
156 #define portMPU_RLAR_A2_REG                   ( *( ( volatile uint32_t * ) 0xe000edb0 ) )
157
158 #define portMPU_RBAR_A3_REG                   ( *( ( volatile uint32_t * ) 0xe000edb4 ) )
159 #define portMPU_RLAR_A3_REG                   ( *( ( volatile uint32_t * ) 0xe000edb8 ) )
160
161 #define portMPU_MAIR0_REG                     ( *( ( volatile uint32_t * ) 0xe000edc0 ) )
162 #define portMPU_MAIR1_REG                     ( *( ( volatile uint32_t * ) 0xe000edc4 ) )
163
164 #define portMPU_RBAR_ADDRESS_MASK             ( 0xffffffe0 ) /* Must be 32-byte aligned. */
165 #define portMPU_RLAR_ADDRESS_MASK             ( 0xffffffe0 ) /* Must be 32-byte aligned. */
166
167 #define portMPU_RBAR_ACCESS_PERMISSIONS_MASK  ( 3UL << 1UL )
168
169 #define portMPU_MAIR_ATTR0_POS                ( 0UL )
170 #define portMPU_MAIR_ATTR0_MASK               ( 0x000000ff )
171
172 #define portMPU_MAIR_ATTR1_POS                ( 8UL )
173 #define portMPU_MAIR_ATTR1_MASK               ( 0x0000ff00 )
174
175 #define portMPU_MAIR_ATTR2_POS                ( 16UL )
176 #define portMPU_MAIR_ATTR2_MASK               ( 0x00ff0000 )
177
178 #define portMPU_MAIR_ATTR3_POS                ( 24UL )
179 #define portMPU_MAIR_ATTR3_MASK               ( 0xff000000 )
180
181 #define portMPU_MAIR_ATTR4_POS                ( 0UL )
182 #define portMPU_MAIR_ATTR4_MASK               ( 0x000000ff )
183
184 #define portMPU_MAIR_ATTR5_POS                ( 8UL )
185 #define portMPU_MAIR_ATTR5_MASK               ( 0x0000ff00 )
186
187 #define portMPU_MAIR_ATTR6_POS                ( 16UL )
188 #define portMPU_MAIR_ATTR6_MASK               ( 0x00ff0000 )
189
190 #define portMPU_MAIR_ATTR7_POS                ( 24UL )
191 #define portMPU_MAIR_ATTR7_MASK               ( 0xff000000 )
192
193 #define portMPU_RLAR_ATTR_INDEX0              ( 0UL << 1UL )
194 #define portMPU_RLAR_ATTR_INDEX1              ( 1UL << 1UL )
195 #define portMPU_RLAR_ATTR_INDEX2              ( 2UL << 1UL )
196 #define portMPU_RLAR_ATTR_INDEX3              ( 3UL << 1UL )
197 #define portMPU_RLAR_ATTR_INDEX4              ( 4UL << 1UL )
198 #define portMPU_RLAR_ATTR_INDEX5              ( 5UL << 1UL )
199 #define portMPU_RLAR_ATTR_INDEX6              ( 6UL << 1UL )
200 #define portMPU_RLAR_ATTR_INDEX7              ( 7UL << 1UL )
201
202 #define portMPU_RLAR_REGION_ENABLE            ( 1UL )
203
204 /* Enable privileged access to unmapped region. */
205 #define portMPU_PRIV_BACKGROUND_ENABLE_BIT    ( 1UL << 2UL )
206
207 /* Enable MPU. */
208 #define portMPU_ENABLE_BIT                    ( 1UL << 0UL )
209
210 /* Expected value of the portMPU_TYPE register. */
211 #define portEXPECTED_MPU_TYPE_VALUE           ( configTOTAL_MPU_REGIONS << 8UL )
212
213 /* Extract first address of the MPU region as encoded in the
214  * RBAR (Region Base Address Register) value. */
215 #define portEXTRACT_FIRST_ADDRESS_FROM_RBAR( rbar ) \
216     ( ( rbar ) & portMPU_RBAR_ADDRESS_MASK )
217
218 /* Extract last address of the MPU region as encoded in the
219  * RLAR (Region Limit Address Register) value. */
220 #define portEXTRACT_LAST_ADDRESS_FROM_RLAR( rlar ) \
221     ( ( ( rlar ) & portMPU_RLAR_ADDRESS_MASK ) | ~portMPU_RLAR_ADDRESS_MASK )
222
223 /* Does addr lies within [start, end] address range? */
224 #define portIS_ADDRESS_WITHIN_RANGE( addr, start, end ) \
225     ( ( ( addr ) >= ( start ) ) && ( ( addr ) <= ( end ) ) )
226
227 /* Is the access request satisfied by the available permissions? */
228 #define portIS_AUTHORIZED( accessRequest, permissions ) \
229     ( ( ( permissions ) & ( accessRequest ) ) == accessRequest )
230
231 /* Max value that fits in a uint32_t type. */
232 #define portUINT32_MAX    ( ~( ( uint32_t ) 0 ) )
233
234 /* Check if adding a and b will result in overflow. */
235 #define portADD_UINT32_WILL_OVERFLOW( a, b )    ( ( a ) > ( portUINT32_MAX - ( b ) ) )
236 /*-----------------------------------------------------------*/
237
238 /**
239  * @brief The maximum 24-bit number.
240  *
241  * It is needed because the systick is a 24-bit counter.
242  */
243 #define portMAX_24_BIT_NUMBER       ( 0xffffffUL )
244
245 /**
246  * @brief A fiddle factor to estimate the number of SysTick counts that would
247  * have occurred while the SysTick counter is stopped during tickless idle
248  * calculations.
249  */
250 #define portMISSED_COUNTS_FACTOR    ( 94UL )
251 /*-----------------------------------------------------------*/
252
253 /**
254  * @brief Constants required to set up the initial stack.
255  */
256 #define portINITIAL_XPSR    ( 0x01000000 )
257
258 #if ( configRUN_FREERTOS_SECURE_ONLY == 1 )
259
260 /**
261  * @brief Initial EXC_RETURN value.
262  *
263  *     FF         FF         FF         FD
264  * 1111 1111  1111 1111  1111 1111  1111 1101
265  *
266  * Bit[6] - 1 --> The exception was taken from the Secure state.
267  * Bit[5] - 1 --> Do not skip stacking of additional state context.
268  * Bit[4] - 1 --> The PE did not allocate space on the stack for FP context.
269  * Bit[3] - 1 --> Return to the Thread mode.
270  * Bit[2] - 1 --> Restore registers from the process stack.
271  * Bit[1] - 0 --> Reserved, 0.
272  * Bit[0] - 1 --> The exception was taken to the Secure state.
273  */
274     #define portINITIAL_EXC_RETURN    ( 0xfffffffd )
275 #else
276
277 /**
278  * @brief Initial EXC_RETURN value.
279  *
280  *     FF         FF         FF         BC
281  * 1111 1111  1111 1111  1111 1111  1011 1100
282  *
283  * Bit[6] - 0 --> The exception was taken from the Non-Secure state.
284  * Bit[5] - 1 --> Do not skip stacking of additional state context.
285  * Bit[4] - 1 --> The PE did not allocate space on the stack for FP context.
286  * Bit[3] - 1 --> Return to the Thread mode.
287  * Bit[2] - 1 --> Restore registers from the process stack.
288  * Bit[1] - 0 --> Reserved, 0.
289  * Bit[0] - 0 --> The exception was taken to the Non-Secure state.
290  */
291     #define portINITIAL_EXC_RETURN    ( 0xffffffbc )
292 #endif /* configRUN_FREERTOS_SECURE_ONLY */
293
294 /**
295  * @brief CONTROL register privileged bit mask.
296  *
297  * Bit[0] in CONTROL register tells the privilege:
298  *  Bit[0] = 0 ==> The task is privileged.
299  *  Bit[0] = 1 ==> The task is not privileged.
300  */
301 #define portCONTROL_PRIVILEGED_MASK         ( 1UL << 0UL )
302
303 /**
304  * @brief Initial CONTROL register values.
305  */
306 #define portINITIAL_CONTROL_UNPRIVILEGED    ( 0x3 )
307 #define portINITIAL_CONTROL_PRIVILEGED      ( 0x2 )
308
309 /**
310  * @brief Let the user override the default SysTick clock rate.  If defined by the
311  * user, this symbol must equal the SysTick clock rate when the CLK bit is 0 in the
312  * configuration register.
313  */
314 #ifndef configSYSTICK_CLOCK_HZ
315     #define configSYSTICK_CLOCK_HZ             ( configCPU_CLOCK_HZ )
316     /* Ensure the SysTick is clocked at the same frequency as the core. */
317     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( portNVIC_SYSTICK_CLK_BIT )
318 #else
319     /* Select the option to clock SysTick not at the same frequency as the core. */
320     #define portNVIC_SYSTICK_CLK_BIT_CONFIG    ( 0 )
321 #endif
322
323 /**
324  * @brief Let the user override the pre-loading of the initial LR with the
325  * address of prvTaskExitError() in case it messes up unwinding of the stack
326  * in the debugger.
327  */
328 #ifdef configTASK_RETURN_ADDRESS
329     #define portTASK_RETURN_ADDRESS    configTASK_RETURN_ADDRESS
330 #else
331     #define portTASK_RETURN_ADDRESS    prvTaskExitError
332 #endif
333
334 /**
335  * @brief If portPRELOAD_REGISTERS then registers will be given an initial value
336  * when a task is created. This helps in debugging at the cost of code size.
337  */
338 #define portPRELOAD_REGISTERS    1
339
340 /**
341  * @brief A task is created without a secure context, and must call
342  * portALLOCATE_SECURE_CONTEXT() to give itself a secure context before it makes
343  * any secure calls.
344  */
345 #define portNO_SECURE_CONTEXT    0
346 /*-----------------------------------------------------------*/
347
348 /**
349  * @brief Used to catch tasks that attempt to return from their implementing
350  * function.
351  */
352 static void prvTaskExitError( void );
353
354 #if ( configENABLE_MPU == 1 )
355
356 /**
357  * @brief Extract MPU region's access permissions from the Region Base Address
358  * Register (RBAR) value.
359  *
360  * @param ulRBARValue RBAR value for the MPU region.
361  *
362  * @return uint32_t Access permissions.
363  */
364     static uint32_t prvGetRegionAccessPermissions( uint32_t ulRBARValue ) PRIVILEGED_FUNCTION;
365 #endif /* configENABLE_MPU */
366
367 #if ( configENABLE_MPU == 1 )
368
369 /**
370  * @brief Setup the Memory Protection Unit (MPU).
371  */
372     static void prvSetupMPU( void ) PRIVILEGED_FUNCTION;
373 #endif /* configENABLE_MPU */
374
375 #if ( configENABLE_FPU == 1 )
376
377 /**
378  * @brief Setup the Floating Point Unit (FPU).
379  */
380     static void prvSetupFPU( void ) PRIVILEGED_FUNCTION;
381 #endif /* configENABLE_FPU */
382
383 /**
384  * @brief Setup the timer to generate the tick interrupts.
385  *
386  * The implementation in this file is weak to allow application writers to
387  * change the timer used to generate the tick interrupt.
388  */
389 void vPortSetupTimerInterrupt( void ) PRIVILEGED_FUNCTION;
390
391 /**
392  * @brief Checks whether the current execution context is interrupt.
393  *
394  * @return pdTRUE if the current execution context is interrupt, pdFALSE
395  * otherwise.
396  */
397 BaseType_t xPortIsInsideInterrupt( void );
398
399 /**
400  * @brief Yield the processor.
401  */
402 void vPortYield( void ) PRIVILEGED_FUNCTION;
403
404 /**
405  * @brief Enter critical section.
406  */
407 void vPortEnterCritical( void ) PRIVILEGED_FUNCTION;
408
409 /**
410  * @brief Exit from critical section.
411  */
412 void vPortExitCritical( void ) PRIVILEGED_FUNCTION;
413
414 /**
415  * @brief SysTick handler.
416  */
417 void SysTick_Handler( void ) PRIVILEGED_FUNCTION;
418
419 /**
420  * @brief C part of SVC handler.
421  */
422 portDONT_DISCARD void vPortSVCHandler_C( uint32_t * pulCallerStackAddress ) PRIVILEGED_FUNCTION;
423
424 #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) )
425
426 /**
427  * @brief Sets up the system call stack so that upon returning from
428  * SVC, the system call stack is used.
429  *
430  * @param pulTaskStack The current SP when the SVC was raised.
431  * @param ulLR The value of Link Register (EXC_RETURN) in the SVC handler.
432  * @param ucSystemCallNumber The system call number of the system call.
433  */
434     void vSystemCallEnter( uint32_t * pulTaskStack,
435                            uint32_t ulLR,
436                            uint8_t ucSystemCallNumber ) PRIVILEGED_FUNCTION;
437
438 #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
439
440 #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) )
441
442 /**
443  * @brief Raise SVC for exiting from a system call.
444  */
445     void vRequestSystemCallExit( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
446
447 #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
448
449 #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) )
450
451     /**
452      * @brief Sets up the task stack so that upon returning from
453      * SVC, the task stack is used again.
454      *
455      * @param pulSystemCallStack The current SP when the SVC was raised.
456      * @param ulLR The value of Link Register (EXC_RETURN) in the SVC handler.
457      */
458     void vSystemCallExit( uint32_t * pulSystemCallStack,
459                           uint32_t ulLR ) PRIVILEGED_FUNCTION;
460
461 #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
462
463 #if ( configENABLE_MPU == 1 )
464
465     /**
466      * @brief Checks whether or not the calling task is privileged.
467      *
468      * @return pdTRUE if the calling task is privileged, pdFALSE otherwise.
469      */
470     BaseType_t xPortIsTaskPrivileged( void ) PRIVILEGED_FUNCTION;
471
472 #endif /* configENABLE_MPU == 1 */
473 /*-----------------------------------------------------------*/
474
475 /**
476  * @brief Each task maintains its own interrupt status in the critical nesting
477  * variable.
478  */
479 PRIVILEGED_DATA static volatile uint32_t ulCriticalNesting = 0xaaaaaaaaUL;
480
481 #if ( configENABLE_TRUSTZONE == 1 )
482
483 /**
484  * @brief Saved as part of the task context to indicate which context the
485  * task is using on the secure side.
486  */
487     PRIVILEGED_DATA portDONT_DISCARD volatile SecureContextHandle_t xSecureContext = portNO_SECURE_CONTEXT;
488 #endif /* configENABLE_TRUSTZONE */
489
490 /**
491  * @brief Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
492  * FreeRTOS API functions are not called from interrupts that have been assigned
493  * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
494  */
495 #if ( ( configASSERT_DEFINED == 1 ) && ( portHAS_BASEPRI == 1 ) )
496
497     static uint8_t ucMaxSysCallPriority = 0;
498     static uint32_t ulMaxPRIGROUPValue = 0;
499     static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * ) portNVIC_IP_REGISTERS_OFFSET_16;
500
501 #endif /* #if ( ( configASSERT_DEFINED == 1 ) && ( portHAS_BASEPRI == 1 ) ) */
502
503 #if ( configUSE_TICKLESS_IDLE == 1 )
504
505 /**
506  * @brief The number of SysTick increments that make up one tick period.
507  */
508     PRIVILEGED_DATA static uint32_t ulTimerCountsForOneTick = 0;
509
510 /**
511  * @brief The maximum number of tick periods that can be suppressed is
512  * limited by the 24 bit resolution of the SysTick timer.
513  */
514     PRIVILEGED_DATA static uint32_t xMaximumPossibleSuppressedTicks = 0;
515
516 /**
517  * @brief Compensate for the CPU cycles that pass while the SysTick is
518  * stopped (low power functionality only).
519  */
520     PRIVILEGED_DATA static uint32_t ulStoppedTimerCompensation = 0;
521 #endif /* configUSE_TICKLESS_IDLE */
522 /*-----------------------------------------------------------*/
523
524 #if ( configUSE_TICKLESS_IDLE == 1 )
525     __attribute__( ( weak ) ) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
526     {
527         uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickDecrementsLeft;
528         TickType_t xModifiableIdleTime;
529
530         /* Make sure the SysTick reload value does not overflow the counter. */
531         if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
532         {
533             xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
534         }
535
536         /* Enter a critical section but don't use the taskENTER_CRITICAL()
537          * method as that will mask interrupts that should exit sleep mode. */
538         __asm volatile ( "cpsid i" ::: "memory" );
539         __asm volatile ( "dsb" );
540         __asm volatile ( "isb" );
541
542         /* If a context switch is pending or a task is waiting for the scheduler
543          * to be unsuspended then abandon the low power entry. */
544         if( eTaskConfirmSleepModeStatus() == eAbortSleep )
545         {
546             /* Re-enable interrupts - see comments above the cpsid instruction
547              * above. */
548             __asm volatile ( "cpsie i" ::: "memory" );
549         }
550         else
551         {
552             /* Stop the SysTick momentarily.  The time the SysTick is stopped for
553              * is accounted for as best it can be, but using the tickless mode will
554              * inevitably result in some tiny drift of the time maintained by the
555              * kernel with respect to calendar time. */
556             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
557
558             /* Use the SysTick current-value register to determine the number of
559              * SysTick decrements remaining until the next tick interrupt.  If the
560              * current-value register is zero, then there are actually
561              * ulTimerCountsForOneTick decrements remaining, not zero, because the
562              * SysTick requests the interrupt when decrementing from 1 to 0. */
563             ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
564
565             if( ulSysTickDecrementsLeft == 0 )
566             {
567                 ulSysTickDecrementsLeft = ulTimerCountsForOneTick;
568             }
569
570             /* Calculate the reload value required to wait xExpectedIdleTime
571              * tick periods.  -1 is used because this code normally executes part
572              * way through the first tick period.  But if the SysTick IRQ is now
573              * pending, then clear the IRQ, suppressing the first tick, and correct
574              * the reload value to reflect that the second tick period is already
575              * underway.  The expected idle time is always at least two ticks. */
576             ulReloadValue = ulSysTickDecrementsLeft + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
577
578             if( ( portNVIC_INT_CTRL_REG & portNVIC_PEND_SYSTICK_SET_BIT ) != 0 )
579             {
580                 portNVIC_INT_CTRL_REG = portNVIC_PEND_SYSTICK_CLEAR_BIT;
581                 ulReloadValue -= ulTimerCountsForOneTick;
582             }
583
584             if( ulReloadValue > ulStoppedTimerCompensation )
585             {
586                 ulReloadValue -= ulStoppedTimerCompensation;
587             }
588
589             /* Set the new reload value. */
590             portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
591
592             /* Clear the SysTick count flag and set the count value back to
593              * zero. */
594             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
595
596             /* Restart SysTick. */
597             portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
598
599             /* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
600              * set its parameter to 0 to indicate that its implementation contains
601              * its own wait for interrupt or wait for event instruction, and so wfi
602              * should not be executed again.  However, the original expected idle
603              * time variable must remain unmodified, so a copy is taken. */
604             xModifiableIdleTime = xExpectedIdleTime;
605             configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
606
607             if( xModifiableIdleTime > 0 )
608             {
609                 __asm volatile ( "dsb" ::: "memory" );
610                 __asm volatile ( "wfi" );
611                 __asm volatile ( "isb" );
612             }
613
614             configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
615
616             /* Re-enable interrupts to allow the interrupt that brought the MCU
617              * out of sleep mode to execute immediately.  See comments above
618              * the cpsid instruction above. */
619             __asm volatile ( "cpsie i" ::: "memory" );
620             __asm volatile ( "dsb" );
621             __asm volatile ( "isb" );
622
623             /* Disable interrupts again because the clock is about to be stopped
624              * and interrupts that execute while the clock is stopped will increase
625              * any slippage between the time maintained by the RTOS and calendar
626              * time. */
627             __asm volatile ( "cpsid i" ::: "memory" );
628             __asm volatile ( "dsb" );
629             __asm volatile ( "isb" );
630
631             /* Disable the SysTick clock without reading the
632              * portNVIC_SYSTICK_CTRL_REG register to ensure the
633              * portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set.  Again,
634              * the time the SysTick is stopped for is accounted for as best it can
635              * be, but using the tickless mode will inevitably result in some tiny
636              * drift of the time maintained by the kernel with respect to calendar
637              * time*/
638             portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT );
639
640             /* Determine whether the SysTick has already counted to zero. */
641             if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
642             {
643                 uint32_t ulCalculatedLoadValue;
644
645                 /* The tick interrupt ended the sleep (or is now pending), and
646                  * a new tick period has started.  Reset portNVIC_SYSTICK_LOAD_REG
647                  * with whatever remains of the new tick period. */
648                 ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
649
650                 /* Don't allow a tiny value, or values that have somehow
651                  * underflowed because the post sleep hook did something
652                  * that took too long or because the SysTick current-value register
653                  * is zero. */
654                 if( ( ulCalculatedLoadValue <= ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
655                 {
656                     ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
657                 }
658
659                 portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
660
661                 /* As the pending tick will be processed as soon as this
662                  * function exits, the tick value maintained by the tick is stepped
663                  * forward by one less than the time spent waiting. */
664                 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
665             }
666             else
667             {
668                 /* Something other than the tick interrupt ended the sleep. */
669
670                 /* Use the SysTick current-value register to determine the
671                  * number of SysTick decrements remaining until the expected idle
672                  * time would have ended. */
673                 ulSysTickDecrementsLeft = portNVIC_SYSTICK_CURRENT_VALUE_REG;
674                 #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG != portNVIC_SYSTICK_CLK_BIT )
675                 {
676                     /* If the SysTick is not using the core clock, the current-
677                      * value register might still be zero here.  In that case, the
678                      * SysTick didn't load from the reload register, and there are
679                      * ulReloadValue decrements remaining in the expected idle
680                      * time, not zero. */
681                     if( ulSysTickDecrementsLeft == 0 )
682                     {
683                         ulSysTickDecrementsLeft = ulReloadValue;
684                     }
685                 }
686                 #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
687
688                 /* Work out how long the sleep lasted rounded to complete tick
689                  * periods (not the ulReload value which accounted for part
690                  * ticks). */
691                 ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - ulSysTickDecrementsLeft;
692
693                 /* How many complete tick periods passed while the processor
694                  * was waiting? */
695                 ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
696
697                 /* The reload value is set to whatever fraction of a single tick
698                  * period remains. */
699                 portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
700             }
701
702             /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG again,
703              * then set portNVIC_SYSTICK_LOAD_REG back to its standard value.  If
704              * the SysTick is not using the core clock, temporarily configure it to
705              * use the core clock.  This configuration forces the SysTick to load
706              * from portNVIC_SYSTICK_LOAD_REG immediately instead of at the next
707              * cycle of the other clock.  Then portNVIC_SYSTICK_LOAD_REG is ready
708              * to receive the standard value immediately. */
709             portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
710             portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
711             #if ( portNVIC_SYSTICK_CLK_BIT_CONFIG == portNVIC_SYSTICK_CLK_BIT )
712             {
713                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
714             }
715             #else
716             {
717                 /* The temporary usage of the core clock has served its purpose,
718                  * as described above.  Resume usage of the other clock. */
719                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT;
720
721                 if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
722                 {
723                     /* The partial tick period already ended.  Be sure the SysTick
724                      * counts it only once. */
725                     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0;
726                 }
727
728                 portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
729                 portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
730             }
731             #endif /* portNVIC_SYSTICK_CLK_BIT_CONFIG */
732
733             /* Step the tick to account for any tick periods that elapsed. */
734             vTaskStepTick( ulCompleteTickPeriods );
735
736             /* Exit with interrupts enabled. */
737             __asm volatile ( "cpsie i" ::: "memory" );
738         }
739     }
740 #endif /* configUSE_TICKLESS_IDLE */
741 /*-----------------------------------------------------------*/
742
743 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void ) /* PRIVILEGED_FUNCTION */
744 {
745     /* Calculate the constants required to configure the tick interrupt. */
746     #if ( configUSE_TICKLESS_IDLE == 1 )
747     {
748         ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
749         xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
750         ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
751     }
752     #endif /* configUSE_TICKLESS_IDLE */
753
754     /* Stop and reset the SysTick. */
755     portNVIC_SYSTICK_CTRL_REG = 0UL;
756     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
757
758     /* Configure SysTick to interrupt at the requested rate. */
759     portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
760     portNVIC_SYSTICK_CTRL_REG = portNVIC_SYSTICK_CLK_BIT_CONFIG | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT;
761 }
762 /*-----------------------------------------------------------*/
763
764 static void prvTaskExitError( void )
765 {
766     volatile uint32_t ulDummy = 0UL;
767
768     /* A function that implements a task must not exit or attempt to return to
769      * its caller as there is nothing to return to. If a task wants to exit it
770      * should instead call vTaskDelete( NULL ). Artificially force an assert()
771      * to be triggered if configASSERT() is defined, then stop here so
772      * application writers can catch the error. */
773     configASSERT( ulCriticalNesting == ~0UL );
774     portDISABLE_INTERRUPTS();
775
776     while( ulDummy == 0 )
777     {
778         /* This file calls prvTaskExitError() after the scheduler has been
779          * started to remove a compiler warning about the function being
780          * defined but never called.  ulDummy is used purely to quieten other
781          * warnings about code appearing after this function is called - making
782          * ulDummy volatile makes the compiler think the function could return
783          * and therefore not output an 'unreachable code' warning for code that
784          * appears after it. */
785     }
786 }
787 /*-----------------------------------------------------------*/
788
789 #if ( configENABLE_MPU == 1 )
790     static uint32_t prvGetRegionAccessPermissions( uint32_t ulRBARValue ) /* PRIVILEGED_FUNCTION */
791     {
792         uint32_t ulAccessPermissions = 0;
793
794         if( ( ulRBARValue & portMPU_RBAR_ACCESS_PERMISSIONS_MASK ) == portMPU_REGION_READ_ONLY )
795         {
796             ulAccessPermissions = tskMPU_READ_PERMISSION;
797         }
798
799         if( ( ulRBARValue & portMPU_RBAR_ACCESS_PERMISSIONS_MASK ) == portMPU_REGION_READ_WRITE )
800         {
801             ulAccessPermissions = ( tskMPU_READ_PERMISSION | tskMPU_WRITE_PERMISSION );
802         }
803
804         return ulAccessPermissions;
805     }
806 #endif /* configENABLE_MPU */
807 /*-----------------------------------------------------------*/
808
809 #if ( configENABLE_MPU == 1 )
810     static void prvSetupMPU( void ) /* PRIVILEGED_FUNCTION */
811     {
812         #if defined( __ARMCC_VERSION )
813             /* Declaration when these variable are defined in code instead of being
814              * exported from linker scripts. */
815             extern uint32_t * __privileged_functions_start__;
816             extern uint32_t * __privileged_functions_end__;
817             extern uint32_t * __syscalls_flash_start__;
818             extern uint32_t * __syscalls_flash_end__;
819             extern uint32_t * __unprivileged_flash_start__;
820             extern uint32_t * __unprivileged_flash_end__;
821             extern uint32_t * __privileged_sram_start__;
822             extern uint32_t * __privileged_sram_end__;
823         #else /* if defined( __ARMCC_VERSION ) */
824             /* Declaration when these variable are exported from linker scripts. */
825             extern uint32_t __privileged_functions_start__[];
826             extern uint32_t __privileged_functions_end__[];
827             extern uint32_t __syscalls_flash_start__[];
828             extern uint32_t __syscalls_flash_end__[];
829             extern uint32_t __unprivileged_flash_start__[];
830             extern uint32_t __unprivileged_flash_end__[];
831             extern uint32_t __privileged_sram_start__[];
832             extern uint32_t __privileged_sram_end__[];
833         #endif /* defined( __ARMCC_VERSION ) */
834
835         /* The only permitted number of regions are 8 or 16. */
836         configASSERT( ( configTOTAL_MPU_REGIONS == 8 ) || ( configTOTAL_MPU_REGIONS == 16 ) );
837
838         /* Ensure that the configTOTAL_MPU_REGIONS is configured correctly. */
839         configASSERT( portMPU_TYPE_REG == portEXPECTED_MPU_TYPE_VALUE );
840
841         /* Check that the MPU is present. */
842         if( portMPU_TYPE_REG == portEXPECTED_MPU_TYPE_VALUE )
843         {
844             /* MAIR0 - Index 0. */
845             portMPU_MAIR0_REG |= ( ( portMPU_NORMAL_MEMORY_BUFFERABLE_CACHEABLE << portMPU_MAIR_ATTR0_POS ) & portMPU_MAIR_ATTR0_MASK );
846             /* MAIR0 - Index 1. */
847             portMPU_MAIR0_REG |= ( ( portMPU_DEVICE_MEMORY_nGnRE << portMPU_MAIR_ATTR1_POS ) & portMPU_MAIR_ATTR1_MASK );
848
849             /* Setup privileged flash as Read Only so that privileged tasks can
850              * read it but not modify. */
851             portMPU_RNR_REG = portPRIVILEGED_FLASH_REGION;
852             portMPU_RBAR_REG = ( ( ( uint32_t ) __privileged_functions_start__ ) & portMPU_RBAR_ADDRESS_MASK ) |
853                                ( portMPU_REGION_NON_SHAREABLE ) |
854                                ( portMPU_REGION_PRIVILEGED_READ_ONLY );
855             portMPU_RLAR_REG = ( ( ( uint32_t ) __privileged_functions_end__ ) & portMPU_RLAR_ADDRESS_MASK ) |
856                                ( portMPU_RLAR_ATTR_INDEX0 ) |
857                                ( portMPU_RLAR_REGION_ENABLE );
858
859             /* Setup unprivileged flash as Read Only by both privileged and
860              * unprivileged tasks. All tasks can read it but no-one can modify. */
861             portMPU_RNR_REG = portUNPRIVILEGED_FLASH_REGION;
862             portMPU_RBAR_REG = ( ( ( uint32_t ) __unprivileged_flash_start__ ) & portMPU_RBAR_ADDRESS_MASK ) |
863                                ( portMPU_REGION_NON_SHAREABLE ) |
864                                ( portMPU_REGION_READ_ONLY );
865             portMPU_RLAR_REG = ( ( ( uint32_t ) __unprivileged_flash_end__ ) & portMPU_RLAR_ADDRESS_MASK ) |
866                                ( portMPU_RLAR_ATTR_INDEX0 ) |
867                                ( portMPU_RLAR_REGION_ENABLE );
868
869             /* Setup unprivileged syscalls flash as Read Only by both privileged
870              * and unprivileged tasks. All tasks can read it but no-one can modify. */
871             portMPU_RNR_REG = portUNPRIVILEGED_SYSCALLS_REGION;
872             portMPU_RBAR_REG = ( ( ( uint32_t ) __syscalls_flash_start__ ) & portMPU_RBAR_ADDRESS_MASK ) |
873                                ( portMPU_REGION_NON_SHAREABLE ) |
874                                ( portMPU_REGION_READ_ONLY );
875             portMPU_RLAR_REG = ( ( ( uint32_t ) __syscalls_flash_end__ ) & portMPU_RLAR_ADDRESS_MASK ) |
876                                ( portMPU_RLAR_ATTR_INDEX0 ) |
877                                ( portMPU_RLAR_REGION_ENABLE );
878
879             /* Setup RAM containing kernel data for privileged access only. */
880             portMPU_RNR_REG = portPRIVILEGED_RAM_REGION;
881             portMPU_RBAR_REG = ( ( ( uint32_t ) __privileged_sram_start__ ) & portMPU_RBAR_ADDRESS_MASK ) |
882                                ( portMPU_REGION_NON_SHAREABLE ) |
883                                ( portMPU_REGION_PRIVILEGED_READ_WRITE ) |
884                                ( portMPU_REGION_EXECUTE_NEVER );
885             portMPU_RLAR_REG = ( ( ( uint32_t ) __privileged_sram_end__ ) & portMPU_RLAR_ADDRESS_MASK ) |
886                                ( portMPU_RLAR_ATTR_INDEX0 ) |
887                                ( portMPU_RLAR_REGION_ENABLE );
888
889             /* Enable mem fault. */
890             portSCB_SYS_HANDLER_CTRL_STATE_REG |= portSCB_MEM_FAULT_ENABLE_BIT;
891
892             /* Enable MPU with privileged background access i.e. unmapped
893              * regions have privileged access. */
894             portMPU_CTRL_REG |= ( portMPU_PRIV_BACKGROUND_ENABLE_BIT | portMPU_ENABLE_BIT );
895         }
896     }
897 #endif /* configENABLE_MPU */
898 /*-----------------------------------------------------------*/
899
900 #if ( configENABLE_FPU == 1 )
901     static void prvSetupFPU( void ) /* PRIVILEGED_FUNCTION */
902     {
903         #if ( configENABLE_TRUSTZONE == 1 )
904         {
905             /* Enable non-secure access to the FPU. */
906             SecureInit_EnableNSFPUAccess();
907         }
908         #endif /* configENABLE_TRUSTZONE */
909
910         /* CP10 = 11 ==> Full access to FPU i.e. both privileged and
911          * unprivileged code should be able to access FPU. CP11 should be
912          * programmed to the same value as CP10. */
913         *( portCPACR ) |= ( ( portCPACR_CP10_VALUE << portCPACR_CP10_POS ) |
914                             ( portCPACR_CP11_VALUE << portCPACR_CP11_POS )
915                             );
916
917         /* ASPEN = 1 ==> Hardware should automatically preserve floating point
918          * context on exception entry and restore on exception return.
919          * LSPEN = 1 ==> Enable lazy context save of FP state. */
920         *( portFPCCR ) |= ( portFPCCR_ASPEN_MASK | portFPCCR_LSPEN_MASK );
921     }
922 #endif /* configENABLE_FPU */
923 /*-----------------------------------------------------------*/
924
925 void vPortYield( void ) /* PRIVILEGED_FUNCTION */
926 {
927     /* Set a PendSV to request a context switch. */
928     portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
929
930     /* Barriers are normally not required but do ensure the code is
931      * completely within the specified behaviour for the architecture. */
932     __asm volatile ( "dsb" ::: "memory" );
933     __asm volatile ( "isb" );
934 }
935 /*-----------------------------------------------------------*/
936
937 void vPortEnterCritical( void ) /* PRIVILEGED_FUNCTION */
938 {
939     portDISABLE_INTERRUPTS();
940     ulCriticalNesting++;
941
942     /* Barriers are normally not required but do ensure the code is
943      * completely within the specified behaviour for the architecture. */
944     __asm volatile ( "dsb" ::: "memory" );
945     __asm volatile ( "isb" );
946 }
947 /*-----------------------------------------------------------*/
948
949 void vPortExitCritical( void ) /* PRIVILEGED_FUNCTION */
950 {
951     configASSERT( ulCriticalNesting );
952     ulCriticalNesting--;
953
954     if( ulCriticalNesting == 0 )
955     {
956         portENABLE_INTERRUPTS();
957     }
958 }
959 /*-----------------------------------------------------------*/
960
961 void SysTick_Handler( void ) /* PRIVILEGED_FUNCTION */
962 {
963     uint32_t ulPreviousMask;
964
965     ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
966     {
967         /* Increment the RTOS tick. */
968         if( xTaskIncrementTick() != pdFALSE )
969         {
970             /* Pend a context switch. */
971             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
972         }
973     }
974     portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
975 }
976 /*-----------------------------------------------------------*/
977
978 void vPortSVCHandler_C( uint32_t * pulCallerStackAddress ) /* PRIVILEGED_FUNCTION portDONT_DISCARD */
979 {
980     #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 1 ) )
981         #if defined( __ARMCC_VERSION )
982             /* Declaration when these variable are defined in code instead of being
983              * exported from linker scripts. */
984             extern uint32_t * __syscalls_flash_start__;
985             extern uint32_t * __syscalls_flash_end__;
986         #else
987             /* Declaration when these variable are exported from linker scripts. */
988             extern uint32_t __syscalls_flash_start__[];
989             extern uint32_t __syscalls_flash_end__[];
990         #endif /* defined( __ARMCC_VERSION ) */
991     #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 1 ) */
992
993     uint32_t ulPC;
994
995     #if ( configENABLE_TRUSTZONE == 1 )
996         uint32_t ulR0, ulR1;
997         extern TaskHandle_t pxCurrentTCB;
998         #if ( configENABLE_MPU == 1 )
999             uint32_t ulControl, ulIsTaskPrivileged;
1000         #endif /* configENABLE_MPU */
1001     #endif /* configENABLE_TRUSTZONE */
1002     uint8_t ucSVCNumber;
1003
1004     /* Register are stored on the stack in the following order - R0, R1, R2, R3,
1005      * R12, LR, PC, xPSR. */
1006     ulPC = pulCallerStackAddress[ portOFFSET_TO_PC ];
1007     ucSVCNumber = ( ( uint8_t * ) ulPC )[ -2 ];
1008
1009     switch( ucSVCNumber )
1010     {
1011         #if ( configENABLE_TRUSTZONE == 1 )
1012             case portSVC_ALLOCATE_SECURE_CONTEXT:
1013
1014                 /* R0 contains the stack size passed as parameter to the
1015                  * vPortAllocateSecureContext function. */
1016                 ulR0 = pulCallerStackAddress[ 0 ];
1017
1018                 #if ( configENABLE_MPU == 1 )
1019                 {
1020                     /* Read the CONTROL register value. */
1021                     __asm volatile ( "mrs %0, control"  : "=r" ( ulControl ) );
1022
1023                     /* The task that raised the SVC is privileged if Bit[0]
1024                      * in the CONTROL register is 0. */
1025                     ulIsTaskPrivileged = ( ( ulControl & portCONTROL_PRIVILEGED_MASK ) == 0 );
1026
1027                     /* Allocate and load a context for the secure task. */
1028                     xSecureContext = SecureContext_AllocateContext( ulR0, ulIsTaskPrivileged, pxCurrentTCB );
1029                 }
1030                 #else /* if ( configENABLE_MPU == 1 ) */
1031                 {
1032                     /* Allocate and load a context for the secure task. */
1033                     xSecureContext = SecureContext_AllocateContext( ulR0, pxCurrentTCB );
1034                 }
1035                 #endif /* configENABLE_MPU */
1036
1037                 configASSERT( xSecureContext != securecontextINVALID_CONTEXT_ID );
1038                 SecureContext_LoadContext( xSecureContext, pxCurrentTCB );
1039                 break;
1040
1041             case portSVC_FREE_SECURE_CONTEXT:
1042
1043                 /* R0 contains TCB being freed and R1 contains the secure
1044                  * context handle to be freed. */
1045                 ulR0 = pulCallerStackAddress[ 0 ];
1046                 ulR1 = pulCallerStackAddress[ 1 ];
1047
1048                 /* Free the secure context. */
1049                 SecureContext_FreeContext( ( SecureContextHandle_t ) ulR1, ( void * ) ulR0 );
1050                 break;
1051         #endif /* configENABLE_TRUSTZONE */
1052
1053         case portSVC_START_SCHEDULER:
1054             #if ( configENABLE_TRUSTZONE == 1 )
1055             {
1056                 /* De-prioritize the non-secure exceptions so that the
1057                  * non-secure pendSV runs at the lowest priority. */
1058                 SecureInit_DePrioritizeNSExceptions();
1059
1060                 /* Initialize the secure context management system. */
1061                 SecureContext_Init();
1062             }
1063             #endif /* configENABLE_TRUSTZONE */
1064
1065             #if ( configENABLE_FPU == 1 )
1066             {
1067                 /* Setup the Floating Point Unit (FPU). */
1068                 prvSetupFPU();
1069             }
1070             #endif /* configENABLE_FPU */
1071
1072             /* Setup the context of the first task so that the first task starts
1073              * executing. */
1074             vRestoreContextOfFirstTask();
1075             break;
1076
1077         #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 1 ) )
1078             case portSVC_RAISE_PRIVILEGE:
1079
1080                 /* Only raise the privilege, if the svc was raised from any of
1081                  * the system calls. */
1082                 if( ( ulPC >= ( uint32_t ) __syscalls_flash_start__ ) &&
1083                     ( ulPC <= ( uint32_t ) __syscalls_flash_end__ ) )
1084                 {
1085                     vRaisePrivilege();
1086                 }
1087                 break;
1088         #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 1 ) */
1089
1090         default:
1091             /* Incorrect SVC call. */
1092             configASSERT( pdFALSE );
1093     }
1094 }
1095 /*-----------------------------------------------------------*/
1096
1097 #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) )
1098
1099     void vSystemCallEnter( uint32_t * pulTaskStack,
1100                            uint32_t ulLR,
1101                            uint8_t ucSystemCallNumber ) /* PRIVILEGED_FUNCTION */
1102     {
1103         extern TaskHandle_t pxCurrentTCB;
1104         extern UBaseType_t uxSystemCallImplementations[ NUM_SYSTEM_CALLS ];
1105         xMPU_SETTINGS * pxMpuSettings;
1106         uint32_t * pulSystemCallStack;
1107         uint32_t ulStackFrameSize, ulSystemCallLocation, i;
1108
1109         #if defined( __ARMCC_VERSION )
1110             /* Declaration when these variable are defined in code instead of being
1111              * exported from linker scripts. */
1112             extern uint32_t * __syscalls_flash_start__;
1113             extern uint32_t * __syscalls_flash_end__;
1114         #else
1115             /* Declaration when these variable are exported from linker scripts. */
1116             extern uint32_t __syscalls_flash_start__[];
1117             extern uint32_t __syscalls_flash_end__[];
1118         #endif /* #if defined( __ARMCC_VERSION ) */
1119
1120         ulSystemCallLocation = pulTaskStack[ portOFFSET_TO_PC ];
1121         pxMpuSettings = xTaskGetMPUSettings( pxCurrentTCB );
1122
1123         /* Checks:
1124          * 1. SVC is raised from the system call section (i.e. application is
1125          *    not raising SVC directly).
1126          * 2. pxMpuSettings->xSystemCallStackInfo.pulTaskStack must be NULL as
1127          *    it is non-NULL only during the execution of a system call (i.e.
1128          *    between system call enter and exit).
1129          * 3. System call is not for a kernel API disabled by the configuration
1130          *    in FreeRTOSConfig.h.
1131          * 4. We do not need to check that ucSystemCallNumber is within range
1132          *    because the assembly SVC handler checks that before calling
1133          *    this function.
1134          */
1135         if( ( ulSystemCallLocation >= ( uint32_t ) __syscalls_flash_start__ ) &&
1136             ( ulSystemCallLocation <= ( uint32_t ) __syscalls_flash_end__ ) &&
1137             ( pxMpuSettings->xSystemCallStackInfo.pulTaskStack == NULL ) &&
1138             ( uxSystemCallImplementations[ ucSystemCallNumber ] != ( UBaseType_t ) 0 ) )
1139         {
1140             pulSystemCallStack = pxMpuSettings->xSystemCallStackInfo.pulSystemCallStack;
1141
1142             #if ( ( configENABLE_FPU == 1 ) || ( configENABLE_MVE == 1 ) )
1143             {
1144                 if( ( ulLR & portEXC_RETURN_STACK_FRAME_TYPE_MASK ) == 0UL )
1145                 {
1146                     /* Extended frame i.e. FPU in use. */
1147                     ulStackFrameSize = 26;
1148                     __asm volatile
1149                     (
1150                         " vpush {s0}         \n" /* Trigger lazy stacking. */
1151                         " vpop  {s0}         \n" /* Nullify the affect of the above instruction. */
1152                         ::: "memory"
1153                     );
1154                 }
1155                 else
1156                 {
1157                     /* Standard frame i.e. FPU not in use. */
1158                     ulStackFrameSize = 8;
1159                 }
1160             }
1161             #else /* if ( ( configENABLE_FPU == 1 ) || ( configENABLE_MVE == 1 ) ) */
1162             {
1163                 ulStackFrameSize = 8;
1164             }
1165             #endif /* if ( ( configENABLE_FPU == 1 ) || ( configENABLE_MVE == 1 ) ) */
1166
1167             /* Make space on the system call stack for the stack frame. */
1168             pulSystemCallStack = pulSystemCallStack - ulStackFrameSize;
1169
1170             /* Copy the stack frame. */
1171             for( i = 0; i < ulStackFrameSize; i++ )
1172             {
1173                 pulSystemCallStack[ i ] = pulTaskStack[ i ];
1174             }
1175
1176             /* Store the value of the Link Register before the SVC was raised.
1177              * It contains the address of the caller of the System Call entry
1178              * point (i.e. the caller of the MPU_<API>). We need to restore it
1179              * when we exit from the system call. */
1180             pxMpuSettings->xSystemCallStackInfo.ulLinkRegisterAtSystemCallEntry = pulTaskStack[ portOFFSET_TO_LR ];
1181
1182             /* Store the value of the PSPLIM register before the SVC was raised.
1183              * We need to restore it when we exit from the system call. */
1184             __asm volatile ( "mrs %0, psplim" : "=r" ( pxMpuSettings->xSystemCallStackInfo.ulStackLimitRegisterAtSystemCallEntry ) );
1185
1186             /* Use the pulSystemCallStack in thread mode. */
1187             __asm volatile ( "msr psp, %0" : : "r" ( pulSystemCallStack ) );
1188             __asm volatile ( "msr psplim, %0" : : "r" ( pxMpuSettings->xSystemCallStackInfo.pulSystemCallStackLimit ) );
1189
1190             /* Start executing the system call upon returning from this handler. */
1191             pulSystemCallStack[ portOFFSET_TO_PC ] = uxSystemCallImplementations[ ucSystemCallNumber ];
1192
1193             /* Raise a request to exit from the system call upon finishing the
1194              * system call. */
1195             pulSystemCallStack[ portOFFSET_TO_LR ] = ( uint32_t ) vRequestSystemCallExit;
1196
1197             /* Remember the location where we should copy the stack frame when we exit from
1198              * the system call. */
1199             pxMpuSettings->xSystemCallStackInfo.pulTaskStack = pulTaskStack + ulStackFrameSize;
1200
1201             /* Record if the hardware used padding to force the stack pointer
1202              * to be double word aligned. */
1203             if( ( pulTaskStack[ portOFFSET_TO_PSR ] & portPSR_STACK_PADDING_MASK ) == portPSR_STACK_PADDING_MASK )
1204             {
1205                 pxMpuSettings->ulTaskFlags |= portSTACK_FRAME_HAS_PADDING_FLAG;
1206             }
1207             else
1208             {
1209                 pxMpuSettings->ulTaskFlags &= ( ~portSTACK_FRAME_HAS_PADDING_FLAG );
1210             }
1211
1212             /* We ensure in pxPortInitialiseStack that the system call stack is
1213              * double word aligned and therefore, there is no need of padding.
1214              * Clear the bit[9] of stacked xPSR. */
1215             pulSystemCallStack[ portOFFSET_TO_PSR ] &= ( ~portPSR_STACK_PADDING_MASK );
1216
1217             /* Raise the privilege for the duration of the system call. */
1218             __asm volatile
1219             (
1220                 " mrs r0, control     \n" /* Obtain current control value. */
1221                 " movs r1, #1         \n" /* r1 = 1. */
1222                 " bics r0, r1         \n" /* Clear nPRIV bit. */
1223                 " msr control, r0     \n" /* Write back new control value. */
1224                 ::: "r0", "r1", "memory"
1225             );
1226         }
1227     }
1228
1229 #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
1230 /*-----------------------------------------------------------*/
1231
1232 #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) )
1233
1234     void vRequestSystemCallExit( void ) /* __attribute__( ( naked ) ) PRIVILEGED_FUNCTION */
1235     {
1236         __asm volatile ( "svc %0 \n" ::"i" ( portSVC_SYSTEM_CALL_EXIT ) : "memory" );
1237     }
1238
1239 #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
1240 /*-----------------------------------------------------------*/
1241
1242 #if ( ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) )
1243
1244     void vSystemCallExit( uint32_t * pulSystemCallStack,
1245                           uint32_t ulLR ) /* PRIVILEGED_FUNCTION */
1246     {
1247         extern TaskHandle_t pxCurrentTCB;
1248         xMPU_SETTINGS * pxMpuSettings;
1249         uint32_t * pulTaskStack;
1250         uint32_t ulStackFrameSize, ulSystemCallLocation, i;
1251
1252         #if defined( __ARMCC_VERSION )
1253             /* Declaration when these variable are defined in code instead of being
1254              * exported from linker scripts. */
1255             extern uint32_t * __privileged_functions_start__;
1256             extern uint32_t * __privileged_functions_end__;
1257         #else
1258             /* Declaration when these variable are exported from linker scripts. */
1259             extern uint32_t __privileged_functions_start__[];
1260             extern uint32_t __privileged_functions_end__[];
1261         #endif /* #if defined( __ARMCC_VERSION ) */
1262
1263         ulSystemCallLocation = pulSystemCallStack[ portOFFSET_TO_PC ];
1264         pxMpuSettings = xTaskGetMPUSettings( pxCurrentTCB );
1265
1266         /* Checks:
1267          * 1. SVC is raised from the privileged code (i.e. application is not
1268          *    raising SVC directly). This SVC is only raised from
1269          *    vRequestSystemCallExit which is in the privileged code section.
1270          * 2. pxMpuSettings->xSystemCallStackInfo.pulTaskStack must not be NULL -
1271          *    this means that we previously entered a system call and the
1272          *    application is not attempting to exit without entering a system
1273          *    call.
1274          */
1275         if( ( ulSystemCallLocation >= ( uint32_t ) __privileged_functions_start__ ) &&
1276             ( ulSystemCallLocation <= ( uint32_t ) __privileged_functions_end__ ) &&
1277             ( pxMpuSettings->xSystemCallStackInfo.pulTaskStack != NULL ) )
1278         {
1279             pulTaskStack = pxMpuSettings->xSystemCallStackInfo.pulTaskStack;
1280
1281             #if ( ( configENABLE_FPU == 1 ) || ( configENABLE_MVE == 1 ) )
1282             {
1283                 if( ( ulLR & portEXC_RETURN_STACK_FRAME_TYPE_MASK ) == 0UL )
1284                 {
1285                     /* Extended frame i.e. FPU in use. */
1286                     ulStackFrameSize = 26;
1287                     __asm volatile
1288                     (
1289                         " vpush {s0}         \n" /* Trigger lazy stacking. */
1290                         " vpop  {s0}         \n" /* Nullify the affect of the above instruction. */
1291                         ::: "memory"
1292                     );
1293                 }
1294                 else
1295                 {
1296                     /* Standard frame i.e. FPU not in use. */
1297                     ulStackFrameSize = 8;
1298                 }
1299             }
1300             #else /* if ( ( configENABLE_FPU == 1 ) || ( configENABLE_MVE == 1 ) ) */
1301             {
1302                 ulStackFrameSize = 8;
1303             }
1304             #endif /* if ( ( configENABLE_FPU == 1 ) || ( configENABLE_MVE == 1 ) ) */
1305
1306             /* Make space on the task stack for the stack frame. */
1307             pulTaskStack = pulTaskStack - ulStackFrameSize;
1308
1309             /* Copy the stack frame. */
1310             for( i = 0; i < ulStackFrameSize; i++ )
1311             {
1312                 pulTaskStack[ i ] = pulSystemCallStack[ i ];
1313             }
1314
1315             /* Use the pulTaskStack in thread mode. */
1316             __asm volatile ( "msr psp, %0" : : "r" ( pulTaskStack ) );
1317
1318             /* Return to the caller of the System Call entry point (i.e. the
1319              * caller of the MPU_<API>). */
1320             pulTaskStack[ portOFFSET_TO_PC ] = pxMpuSettings->xSystemCallStackInfo.ulLinkRegisterAtSystemCallEntry;
1321             /* Ensure that LR has a valid value.*/
1322             pulTaskStack[ portOFFSET_TO_LR ] = pxMpuSettings->xSystemCallStackInfo.ulLinkRegisterAtSystemCallEntry;
1323
1324             /* Restore the PSPLIM register to what it was at the time of
1325              * system call entry. */
1326             __asm volatile ( "msr psplim, %0" : : "r" ( pxMpuSettings->xSystemCallStackInfo.ulStackLimitRegisterAtSystemCallEntry ) );
1327
1328             /* If the hardware used padding to force the stack pointer
1329              * to be double word aligned, set the stacked xPSR bit[9],
1330              * otherwise clear it. */
1331             if( ( pxMpuSettings->ulTaskFlags & portSTACK_FRAME_HAS_PADDING_FLAG ) == portSTACK_FRAME_HAS_PADDING_FLAG )
1332             {
1333                 pulTaskStack[ portOFFSET_TO_PSR ] |= portPSR_STACK_PADDING_MASK;
1334             }
1335             else
1336             {
1337                 pulTaskStack[ portOFFSET_TO_PSR ] &= ( ~portPSR_STACK_PADDING_MASK );
1338             }
1339
1340             /* This is not NULL only for the duration of the system call. */
1341             pxMpuSettings->xSystemCallStackInfo.pulTaskStack = NULL;
1342
1343             /* Drop the privilege before returning to the thread mode. */
1344             __asm volatile
1345             (
1346                 " mrs r0, control     \n" /* Obtain current control value. */
1347                 " movs r1, #1         \n" /* r1 = 1. */
1348                 " orrs r0, r1         \n" /* Set nPRIV bit. */
1349                 " msr control, r0     \n" /* Write back new control value. */
1350                 ::: "r0", "r1", "memory"
1351             );
1352         }
1353     }
1354
1355 #endif /* ( configENABLE_MPU == 1 ) && ( configUSE_MPU_WRAPPERS_V1 == 0 ) */
1356 /*-----------------------------------------------------------*/
1357
1358 #if ( configENABLE_MPU == 1 )
1359
1360     BaseType_t xPortIsTaskPrivileged( void ) /* PRIVILEGED_FUNCTION */
1361     {
1362         BaseType_t xTaskIsPrivileged = pdFALSE;
1363         const xMPU_SETTINGS * xTaskMpuSettings = xTaskGetMPUSettings( NULL ); /* Calling task's MPU settings. */
1364
1365         if( ( xTaskMpuSettings->ulTaskFlags & portTASK_IS_PRIVILEGED_FLAG ) == portTASK_IS_PRIVILEGED_FLAG )
1366         {
1367             xTaskIsPrivileged = pdTRUE;
1368         }
1369
1370         return xTaskIsPrivileged;
1371     }
1372
1373 #endif /* configENABLE_MPU == 1 */
1374 /*-----------------------------------------------------------*/
1375
1376 #if ( configENABLE_MPU == 1 )
1377
1378     StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
1379                                          StackType_t * pxEndOfStack,
1380                                          TaskFunction_t pxCode,
1381                                          void * pvParameters,
1382                                          BaseType_t xRunPrivileged,
1383                                          xMPU_SETTINGS * xMPUSettings ) /* PRIVILEGED_FUNCTION */
1384     {
1385         uint32_t ulIndex = 0;
1386
1387         xMPUSettings->ulContext[ ulIndex ] = 0x04040404; /* r4. */
1388         ulIndex++;
1389         xMPUSettings->ulContext[ ulIndex ] = 0x05050505; /* r5. */
1390         ulIndex++;
1391         xMPUSettings->ulContext[ ulIndex ] = 0x06060606; /* r6. */
1392         ulIndex++;
1393         xMPUSettings->ulContext[ ulIndex ] = 0x07070707; /* r7. */
1394         ulIndex++;
1395         xMPUSettings->ulContext[ ulIndex ] = 0x08080808; /* r8. */
1396         ulIndex++;
1397         xMPUSettings->ulContext[ ulIndex ] = 0x09090909; /* r9. */
1398         ulIndex++;
1399         xMPUSettings->ulContext[ ulIndex ] = 0x10101010; /* r10. */
1400         ulIndex++;
1401         xMPUSettings->ulContext[ ulIndex ] = 0x11111111; /* r11. */
1402         ulIndex++;
1403
1404         xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) pvParameters; /* r0. */
1405         ulIndex++;
1406         xMPUSettings->ulContext[ ulIndex ] = 0x01010101; /* r1. */
1407         ulIndex++;
1408         xMPUSettings->ulContext[ ulIndex ] = 0x02020202; /* r2. */
1409         ulIndex++;
1410         xMPUSettings->ulContext[ ulIndex ] = 0x03030303; /* r3. */
1411         ulIndex++;
1412         xMPUSettings->ulContext[ ulIndex ] = 0x12121212; /* r12. */
1413         ulIndex++;
1414         xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) portTASK_RETURN_ADDRESS; /* LR. */
1415         ulIndex++;
1416         xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) pxCode; /* PC. */
1417         ulIndex++;
1418         xMPUSettings->ulContext[ ulIndex ] = portINITIAL_XPSR; /* xPSR. */
1419         ulIndex++;
1420
1421         #if ( configENABLE_TRUSTZONE == 1 )
1422         {
1423             xMPUSettings->ulContext[ ulIndex ] = portNO_SECURE_CONTEXT; /* xSecureContext. */
1424             ulIndex++;
1425         }
1426         #endif /* configENABLE_TRUSTZONE */
1427         xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) ( pxTopOfStack - 8 ); /* PSP with the hardware saved stack. */
1428         ulIndex++;
1429         xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) pxEndOfStack; /* PSPLIM. */
1430         ulIndex++;
1431         if( xRunPrivileged == pdTRUE )
1432         {
1433             xMPUSettings->ulTaskFlags |= portTASK_IS_PRIVILEGED_FLAG;
1434             xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) portINITIAL_CONTROL_PRIVILEGED; /* CONTROL. */
1435             ulIndex++;
1436         }
1437         else
1438         {
1439             xMPUSettings->ulTaskFlags &= ( ~portTASK_IS_PRIVILEGED_FLAG );
1440             xMPUSettings->ulContext[ ulIndex ] = ( uint32_t ) portINITIAL_CONTROL_UNPRIVILEGED; /* CONTROL. */
1441             ulIndex++;
1442         }
1443         xMPUSettings->ulContext[ ulIndex ] = portINITIAL_EXC_RETURN; /* LR (EXC_RETURN). */
1444         ulIndex++;
1445
1446         #if ( configUSE_MPU_WRAPPERS_V1 == 0 )
1447         {
1448             /* Ensure that the system call stack is double word aligned. */
1449             xMPUSettings->xSystemCallStackInfo.pulSystemCallStack = &( xMPUSettings->xSystemCallStackInfo.ulSystemCallStackBuffer[ configSYSTEM_CALL_STACK_SIZE - 1 ] );
1450             xMPUSettings->xSystemCallStackInfo.pulSystemCallStack = ( uint32_t * ) ( ( uint32_t ) ( xMPUSettings->xSystemCallStackInfo.pulSystemCallStack ) &
1451                                                                                      ( uint32_t ) ( ~( portBYTE_ALIGNMENT_MASK ) ) );
1452
1453             xMPUSettings->xSystemCallStackInfo.pulSystemCallStackLimit = &( xMPUSettings->xSystemCallStackInfo.ulSystemCallStackBuffer[ 0 ] );
1454             xMPUSettings->xSystemCallStackInfo.pulSystemCallStackLimit = ( uint32_t * ) ( ( ( uint32_t ) ( xMPUSettings->xSystemCallStackInfo.pulSystemCallStackLimit ) +
1455                                                                                             ( uint32_t ) ( portBYTE_ALIGNMENT - 1 ) ) &
1456                                                                                           ( uint32_t ) ( ~( portBYTE_ALIGNMENT_MASK ) ) );
1457
1458             /* This is not NULL only for the duration of a system call. */
1459             xMPUSettings->xSystemCallStackInfo.pulTaskStack = NULL;
1460         }
1461         #endif /* configUSE_MPU_WRAPPERS_V1 == 0 */
1462
1463         return &( xMPUSettings->ulContext[ ulIndex ] );
1464     }
1465
1466 #else /* configENABLE_MPU */
1467
1468     StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
1469                                          StackType_t * pxEndOfStack,
1470                                          TaskFunction_t pxCode,
1471                                          void * pvParameters ) /* PRIVILEGED_FUNCTION */
1472     {
1473         /* Simulate the stack frame as it would be created by a context switch
1474          * interrupt. */
1475         #if ( portPRELOAD_REGISTERS == 0 )
1476         {
1477             pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
1478             *pxTopOfStack = portINITIAL_XPSR;                        /* xPSR. */
1479             pxTopOfStack--;
1480             *pxTopOfStack = ( StackType_t ) pxCode;                  /* PC. */
1481             pxTopOfStack--;
1482             *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR. */
1483             pxTopOfStack -= 5;                                       /* R12, R3, R2 and R1. */
1484             *pxTopOfStack = ( StackType_t ) pvParameters;            /* R0. */
1485             pxTopOfStack -= 9;                                       /* R11..R4, EXC_RETURN. */
1486             *pxTopOfStack = portINITIAL_EXC_RETURN;
1487             pxTopOfStack--;
1488             *pxTopOfStack = ( StackType_t ) pxEndOfStack; /* Slot used to hold this task's PSPLIM value. */
1489
1490             #if ( configENABLE_TRUSTZONE == 1 )
1491             {
1492                 pxTopOfStack--;
1493                 *pxTopOfStack = portNO_SECURE_CONTEXT; /* Slot used to hold this task's xSecureContext value. */
1494             }
1495             #endif /* configENABLE_TRUSTZONE */
1496         }
1497         #else /* portPRELOAD_REGISTERS */
1498         {
1499             pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
1500             *pxTopOfStack = portINITIAL_XPSR;                        /* xPSR. */
1501             pxTopOfStack--;
1502             *pxTopOfStack = ( StackType_t ) pxCode;                  /* PC. */
1503             pxTopOfStack--;
1504             *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR. */
1505             pxTopOfStack--;
1506             *pxTopOfStack = ( StackType_t ) 0x12121212UL;            /* R12. */
1507             pxTopOfStack--;
1508             *pxTopOfStack = ( StackType_t ) 0x03030303UL;            /* R3. */
1509             pxTopOfStack--;
1510             *pxTopOfStack = ( StackType_t ) 0x02020202UL;            /* R2. */
1511             pxTopOfStack--;
1512             *pxTopOfStack = ( StackType_t ) 0x01010101UL;            /* R1. */
1513             pxTopOfStack--;
1514             *pxTopOfStack = ( StackType_t ) pvParameters;            /* R0. */
1515             pxTopOfStack--;
1516             *pxTopOfStack = ( StackType_t ) 0x11111111UL;            /* R11. */
1517             pxTopOfStack--;
1518             *pxTopOfStack = ( StackType_t ) 0x10101010UL;            /* R10. */
1519             pxTopOfStack--;
1520             *pxTopOfStack = ( StackType_t ) 0x09090909UL;            /* R09. */
1521             pxTopOfStack--;
1522             *pxTopOfStack = ( StackType_t ) 0x08080808UL;            /* R08. */
1523             pxTopOfStack--;
1524             *pxTopOfStack = ( StackType_t ) 0x07070707UL;            /* R07. */
1525             pxTopOfStack--;
1526             *pxTopOfStack = ( StackType_t ) 0x06060606UL;            /* R06. */
1527             pxTopOfStack--;
1528             *pxTopOfStack = ( StackType_t ) 0x05050505UL;            /* R05. */
1529             pxTopOfStack--;
1530             *pxTopOfStack = ( StackType_t ) 0x04040404UL;            /* R04. */
1531             pxTopOfStack--;
1532             *pxTopOfStack = portINITIAL_EXC_RETURN;                  /* EXC_RETURN. */
1533             pxTopOfStack--;
1534             *pxTopOfStack = ( StackType_t ) pxEndOfStack; /* Slot used to hold this task's PSPLIM value. */
1535
1536             #if ( configENABLE_TRUSTZONE == 1 )
1537             {
1538                 pxTopOfStack--;
1539                 *pxTopOfStack = portNO_SECURE_CONTEXT; /* Slot used to hold this task's xSecureContext value. */
1540             }
1541             #endif /* configENABLE_TRUSTZONE */
1542         }
1543         #endif /* portPRELOAD_REGISTERS */
1544
1545         return pxTopOfStack;
1546     }
1547
1548 #endif /* configENABLE_MPU */
1549 /*-----------------------------------------------------------*/
1550
1551 BaseType_t xPortStartScheduler( void ) /* PRIVILEGED_FUNCTION */
1552 {
1553     #if ( ( configASSERT_DEFINED == 1 ) && ( portHAS_BASEPRI == 1 ) )
1554     {
1555         volatile uint32_t ulOriginalPriority;
1556         volatile uint32_t ulImplementedPrioBits = 0;
1557         volatile uint8_t ucMaxPriorityValue;
1558
1559         /* Determine the maximum priority from which ISR safe FreeRTOS API
1560          * functions can be called.  ISR safe functions are those that end in
1561          * "FromISR".  FreeRTOS maintains separate thread and ISR API functions to
1562          * ensure interrupt entry is as fast and simple as possible.
1563          *
1564          * Save the interrupt priority value that is about to be clobbered. */
1565         ulOriginalPriority = portNVIC_SHPR2_REG;
1566
1567         /* Determine the number of priority bits available.  First write to all
1568          * possible bits. */
1569         portNVIC_SHPR2_REG = 0xFF000000;
1570
1571         /* Read the value back to see how many bits stuck. */
1572         ucMaxPriorityValue = ( uint8_t ) ( ( portNVIC_SHPR2_REG & 0xFF000000 ) >> 24 );
1573
1574         /* Use the same mask on the maximum system call priority. */
1575         ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
1576
1577         /* Check that the maximum system call priority is nonzero after
1578          * accounting for the number of priority bits supported by the
1579          * hardware. A priority of 0 is invalid because setting the BASEPRI
1580          * register to 0 unmasks all interrupts, and interrupts with priority 0
1581          * cannot be masked using BASEPRI.
1582          * See https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
1583         configASSERT( ucMaxSysCallPriority );
1584
1585         /* Check that the bits not implemented in hardware are zero in
1586          * configMAX_SYSCALL_INTERRUPT_PRIORITY. */
1587         configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & ( ~ucMaxPriorityValue ) ) == 0U );
1588
1589         /* Calculate the maximum acceptable priority group value for the number
1590          * of bits read back. */
1591
1592         while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
1593         {
1594             ulImplementedPrioBits++;
1595             ucMaxPriorityValue <<= ( uint8_t ) 0x01;
1596         }
1597
1598         if( ulImplementedPrioBits == 8 )
1599         {
1600             /* When the hardware implements 8 priority bits, there is no way for
1601              * the software to configure PRIGROUP to not have sub-priorities. As
1602              * a result, the least significant bit is always used for sub-priority
1603              * and there are 128 preemption priorities and 2 sub-priorities.
1604              *
1605              * This may cause some confusion in some cases - for example, if
1606              * configMAX_SYSCALL_INTERRUPT_PRIORITY is set to 5, both 5 and 4
1607              * priority interrupts will be masked in Critical Sections as those
1608              * are at the same preemption priority. This may appear confusing as
1609              * 4 is higher (numerically lower) priority than
1610              * configMAX_SYSCALL_INTERRUPT_PRIORITY and therefore, should not
1611              * have been masked. Instead, if we set configMAX_SYSCALL_INTERRUPT_PRIORITY
1612              * to 4, this confusion does not happen and the behaviour remains the same.
1613              *
1614              * The following assert ensures that the sub-priority bit in the
1615              * configMAX_SYSCALL_INTERRUPT_PRIORITY is clear to avoid the above mentioned
1616              * confusion. */
1617             configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY & 0x1U ) == 0U );
1618             ulMaxPRIGROUPValue = 0;
1619         }
1620         else
1621         {
1622             ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS - ulImplementedPrioBits;
1623         }
1624
1625         /* Shift the priority group value back to its position within the AIRCR
1626          * register. */
1627         ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
1628         ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
1629
1630         /* Restore the clobbered interrupt priority register to its original
1631          * value. */
1632         portNVIC_SHPR2_REG = ulOriginalPriority;
1633     }
1634     #endif /* #if ( ( configASSERT_DEFINED == 1 ) && ( portHAS_BASEPRI == 1 ) ) */
1635
1636     /* Make PendSV, CallSV and SysTick the same priority as the kernel. */
1637     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
1638     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
1639
1640     #if ( configENABLE_MPU == 1 )
1641     {
1642         /* Setup the Memory Protection Unit (MPU). */
1643         prvSetupMPU();
1644     }
1645     #endif /* configENABLE_MPU */
1646
1647     /* Start the timer that generates the tick ISR. Interrupts are disabled
1648      * here already. */
1649     vPortSetupTimerInterrupt();
1650
1651     /* Initialize the critical nesting count ready for the first task. */
1652     ulCriticalNesting = 0;
1653
1654     /* Start the first task. */
1655     vStartFirstTask();
1656
1657     /* Should never get here as the tasks will now be executing. Call the task
1658      * exit error function to prevent compiler warnings about a static function
1659      * not being called in the case that the application writer overrides this
1660      * functionality by defining configTASK_RETURN_ADDRESS. Call
1661      * vTaskSwitchContext() so link time optimization does not remove the
1662      * symbol. */
1663     vTaskSwitchContext();
1664     prvTaskExitError();
1665
1666     /* Should not get here. */
1667     return 0;
1668 }
1669 /*-----------------------------------------------------------*/
1670
1671 void vPortEndScheduler( void ) /* PRIVILEGED_FUNCTION */
1672 {
1673     /* Not implemented in ports where there is nothing to return to.
1674      * Artificially force an assert. */
1675     configASSERT( ulCriticalNesting == 1000UL );
1676 }
1677 /*-----------------------------------------------------------*/
1678
1679 #if ( configENABLE_MPU == 1 )
1680     void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings,
1681                                     const struct xMEMORY_REGION * const xRegions,
1682                                     StackType_t * pxBottomOfStack,
1683                                     uint32_t ulStackDepth )
1684     {
1685         uint32_t ulRegionStartAddress, ulRegionEndAddress, ulRegionNumber;
1686         int32_t lIndex = 0;
1687
1688         #if defined( __ARMCC_VERSION )
1689             /* Declaration when these variable are defined in code instead of being
1690              * exported from linker scripts. */
1691             extern uint32_t * __privileged_sram_start__;
1692             extern uint32_t * __privileged_sram_end__;
1693         #else
1694             /* Declaration when these variable are exported from linker scripts. */
1695             extern uint32_t __privileged_sram_start__[];
1696             extern uint32_t __privileged_sram_end__[];
1697         #endif /* defined( __ARMCC_VERSION ) */
1698
1699         /* Setup MAIR0. */
1700         xMPUSettings->ulMAIR0 = ( ( portMPU_NORMAL_MEMORY_BUFFERABLE_CACHEABLE << portMPU_MAIR_ATTR0_POS ) & portMPU_MAIR_ATTR0_MASK );
1701         xMPUSettings->ulMAIR0 |= ( ( portMPU_DEVICE_MEMORY_nGnRE << portMPU_MAIR_ATTR1_POS ) & portMPU_MAIR_ATTR1_MASK );
1702
1703         /* This function is called automatically when the task is created - in
1704          * which case the stack region parameters will be valid.  At all other
1705          * times the stack parameters will not be valid and it is assumed that
1706          * the stack region has already been configured. */
1707         if( ulStackDepth > 0 )
1708         {
1709             ulRegionStartAddress = ( uint32_t ) pxBottomOfStack;
1710             ulRegionEndAddress = ( uint32_t ) pxBottomOfStack + ( ulStackDepth * ( uint32_t ) sizeof( StackType_t ) ) - 1;
1711
1712             /* If the stack is within the privileged SRAM, do not protect it
1713              * using a separate MPU region. This is needed because privileged
1714              * SRAM is already protected using an MPU region and ARMv8-M does
1715              * not allow overlapping MPU regions. */
1716             if( ( ulRegionStartAddress >= ( uint32_t ) __privileged_sram_start__ ) &&
1717                 ( ulRegionEndAddress <= ( uint32_t ) __privileged_sram_end__ ) )
1718             {
1719                 xMPUSettings->xRegionsSettings[ 0 ].ulRBAR = 0;
1720                 xMPUSettings->xRegionsSettings[ 0 ].ulRLAR = 0;
1721             }
1722             else
1723             {
1724                 /* Define the region that allows access to the stack. */
1725                 ulRegionStartAddress &= portMPU_RBAR_ADDRESS_MASK;
1726                 ulRegionEndAddress &= portMPU_RLAR_ADDRESS_MASK;
1727
1728                 xMPUSettings->xRegionsSettings[ 0 ].ulRBAR = ( ulRegionStartAddress ) |
1729                                                              ( portMPU_REGION_NON_SHAREABLE ) |
1730                                                              ( portMPU_REGION_READ_WRITE ) |
1731                                                              ( portMPU_REGION_EXECUTE_NEVER );
1732
1733                 xMPUSettings->xRegionsSettings[ 0 ].ulRLAR = ( ulRegionEndAddress ) |
1734                                                              ( portMPU_RLAR_ATTR_INDEX0 ) |
1735                                                              ( portMPU_RLAR_REGION_ENABLE );
1736             }
1737         }
1738
1739         /* User supplied configurable regions. */
1740         for( ulRegionNumber = 1; ulRegionNumber <= portNUM_CONFIGURABLE_REGIONS; ulRegionNumber++ )
1741         {
1742             /* If xRegions is NULL i.e. the task has not specified any MPU
1743              * region, the else part ensures that all the configurable MPU
1744              * regions are invalidated. */
1745             if( ( xRegions != NULL ) && ( xRegions[ lIndex ].ulLengthInBytes > 0UL ) )
1746             {
1747                 /* Translate the generic region definition contained in xRegions
1748                  * into the ARMv8 specific MPU settings that are then stored in
1749                  * xMPUSettings. */
1750                 ulRegionStartAddress = ( ( uint32_t ) xRegions[ lIndex ].pvBaseAddress ) & portMPU_RBAR_ADDRESS_MASK;
1751                 ulRegionEndAddress = ( uint32_t ) xRegions[ lIndex ].pvBaseAddress + xRegions[ lIndex ].ulLengthInBytes - 1;
1752                 ulRegionEndAddress &= portMPU_RLAR_ADDRESS_MASK;
1753
1754                 /* Start address. */
1755                 xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRBAR = ( ulRegionStartAddress ) |
1756                                                                           ( portMPU_REGION_NON_SHAREABLE );
1757
1758                 /* RO/RW. */
1759                 if( ( xRegions[ lIndex ].ulParameters & tskMPU_REGION_READ_ONLY ) != 0 )
1760                 {
1761                     xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRBAR |= ( portMPU_REGION_READ_ONLY );
1762                 }
1763                 else
1764                 {
1765                     xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRBAR |= ( portMPU_REGION_READ_WRITE );
1766                 }
1767
1768                 /* XN. */
1769                 if( ( xRegions[ lIndex ].ulParameters & tskMPU_REGION_EXECUTE_NEVER ) != 0 )
1770                 {
1771                     xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRBAR |= ( portMPU_REGION_EXECUTE_NEVER );
1772                 }
1773
1774                 /* End Address. */
1775                 xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRLAR = ( ulRegionEndAddress ) |
1776                                                                           ( portMPU_RLAR_REGION_ENABLE );
1777
1778                 /* Normal memory/ Device memory. */
1779                 if( ( xRegions[ lIndex ].ulParameters & tskMPU_REGION_DEVICE_MEMORY ) != 0 )
1780                 {
1781                     /* Attr1 in MAIR0 is configured as device memory. */
1782                     xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRLAR |= portMPU_RLAR_ATTR_INDEX1;
1783                 }
1784                 else
1785                 {
1786                     /* Attr0 in MAIR0 is configured as normal memory. */
1787                     xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRLAR |= portMPU_RLAR_ATTR_INDEX0;
1788                 }
1789             }
1790             else
1791             {
1792                 /* Invalidate the region. */
1793                 xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRBAR = 0UL;
1794                 xMPUSettings->xRegionsSettings[ ulRegionNumber ].ulRLAR = 0UL;
1795             }
1796
1797             lIndex++;
1798         }
1799     }
1800 #endif /* configENABLE_MPU */
1801 /*-----------------------------------------------------------*/
1802
1803 #if ( configENABLE_MPU == 1 )
1804     BaseType_t xPortIsAuthorizedToAccessBuffer( const void * pvBuffer,
1805                                                 uint32_t ulBufferLength,
1806                                                 uint32_t ulAccessRequested ) /* PRIVILEGED_FUNCTION */
1807
1808     {
1809         uint32_t i, ulBufferStartAddress, ulBufferEndAddress;
1810         BaseType_t xAccessGranted = pdFALSE;
1811         const xMPU_SETTINGS * xTaskMpuSettings = xTaskGetMPUSettings( NULL ); /* Calling task's MPU settings. */
1812
1813         if( ( xTaskMpuSettings->ulTaskFlags & portTASK_IS_PRIVILEGED_FLAG ) == portTASK_IS_PRIVILEGED_FLAG )
1814         {
1815             xAccessGranted = pdTRUE;
1816         }
1817         else
1818         {
1819             if( portADD_UINT32_WILL_OVERFLOW( ( ( uint32_t ) pvBuffer ), ( ulBufferLength - 1UL ) ) == pdFALSE )
1820             {
1821                 ulBufferStartAddress = ( uint32_t ) pvBuffer;
1822                 ulBufferEndAddress = ( ( ( uint32_t ) pvBuffer ) + ulBufferLength - 1UL );
1823
1824                 for( i = 0; i < portTOTAL_NUM_REGIONS; i++ )
1825                 {
1826                     /* Is the MPU region enabled? */
1827                     if( ( xTaskMpuSettings->xRegionsSettings[ i ].ulRLAR & portMPU_RLAR_REGION_ENABLE ) == portMPU_RLAR_REGION_ENABLE )
1828                     {
1829                         if( portIS_ADDRESS_WITHIN_RANGE( ulBufferStartAddress,
1830                                                          portEXTRACT_FIRST_ADDRESS_FROM_RBAR( xTaskMpuSettings->xRegionsSettings[ i ].ulRBAR ),
1831                                                          portEXTRACT_LAST_ADDRESS_FROM_RLAR( xTaskMpuSettings->xRegionsSettings[ i ].ulRLAR ) ) &&
1832                             portIS_ADDRESS_WITHIN_RANGE( ulBufferEndAddress,
1833                                                          portEXTRACT_FIRST_ADDRESS_FROM_RBAR( xTaskMpuSettings->xRegionsSettings[ i ].ulRBAR ),
1834                                                          portEXTRACT_LAST_ADDRESS_FROM_RLAR( xTaskMpuSettings->xRegionsSettings[ i ].ulRLAR ) ) &&
1835                             portIS_AUTHORIZED( ulAccessRequested,
1836                                                prvGetRegionAccessPermissions( xTaskMpuSettings->xRegionsSettings[ i ].ulRBAR ) ) )
1837                         {
1838                             xAccessGranted = pdTRUE;
1839                             break;
1840                         }
1841                     }
1842                 }
1843             }
1844         }
1845
1846         return xAccessGranted;
1847     }
1848 #endif /* configENABLE_MPU */
1849 /*-----------------------------------------------------------*/
1850
1851 BaseType_t xPortIsInsideInterrupt( void )
1852 {
1853     uint32_t ulCurrentInterrupt;
1854     BaseType_t xReturn;
1855
1856     /* Obtain the number of the currently executing interrupt. Interrupt Program
1857      * Status Register (IPSR) holds the exception number of the currently-executing
1858      * exception or zero for Thread mode.*/
1859     __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
1860
1861     if( ulCurrentInterrupt == 0 )
1862     {
1863         xReturn = pdFALSE;
1864     }
1865     else
1866     {
1867         xReturn = pdTRUE;
1868     }
1869
1870     return xReturn;
1871 }
1872 /*-----------------------------------------------------------*/
1873
1874 #if ( ( configASSERT_DEFINED == 1 ) && ( portHAS_BASEPRI == 1 ) )
1875
1876     void vPortValidateInterruptPriority( void )
1877     {
1878         uint32_t ulCurrentInterrupt;
1879         uint8_t ucCurrentPriority;
1880
1881         /* Obtain the number of the currently executing interrupt. */
1882         __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
1883
1884         /* Is the interrupt number a user defined interrupt? */
1885         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
1886         {
1887             /* Look up the interrupt's priority. */
1888             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
1889
1890             /* The following assertion will fail if a service routine (ISR) for
1891              * an interrupt that has been assigned a priority above
1892              * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
1893              * function.  ISR safe FreeRTOS API functions must *only* be called
1894              * from interrupts that have been assigned a priority at or below
1895              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
1896              *
1897              * Numerically low interrupt priority numbers represent logically high
1898              * interrupt priorities, therefore the priority of the interrupt must
1899              * be set to a value equal to or numerically *higher* than
1900              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
1901              *
1902              * Interrupts that  use the FreeRTOS API must not be left at their
1903              * default priority of  zero as that is the highest possible priority,
1904              * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
1905              * and  therefore also guaranteed to be invalid.
1906              *
1907              * FreeRTOS maintains separate thread and ISR API functions to ensure
1908              * interrupt entry is as fast and simple as possible.
1909              *
1910              * The following links provide detailed information:
1911              * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
1912              * https://www.FreeRTOS.org/FAQHelp.html */
1913             configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
1914         }
1915
1916         /* Priority grouping:  The interrupt controller (NVIC) allows the bits
1917          * that define each interrupt's priority to be split between bits that
1918          * define the interrupt's pre-emption priority bits and bits that define
1919          * the interrupt's sub-priority.  For simplicity all bits must be defined
1920          * to be pre-emption priority bits.  The following assertion will fail if
1921          * this is not the case (if some bits represent a sub-priority).
1922          *
1923          * If the application only uses CMSIS libraries for interrupt
1924          * configuration then the correct setting can be achieved on all Cortex-M
1925          * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
1926          * scheduler.  Note however that some vendor specific peripheral libraries
1927          * assume a non-zero priority group setting, in which cases using a value
1928          * of zero will result in unpredictable behaviour. */
1929         configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
1930     }
1931
1932 #endif /* #if ( ( configASSERT_DEFINED == 1 ) && ( portHAS_BASEPRI == 1 ) ) */
1933 /*-----------------------------------------------------------*/