]> begriffs open source - freertos/blob - portable/GCC/ARM_CM3_MPU/port.c
RP2040: Fix compiler warning and comment (#509)
[freertos] / portable / GCC / ARM_CM3_MPU / port.c
1 /*
2  * FreeRTOS SMP Kernel V202110.00
3  * Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9  * the Software, and to permit persons to whom the Software is furnished to do so,
10  * subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * https://www.FreeRTOS.org
23  * https://github.com/FreeRTOS
24  *
25  */
26
27 /*-----------------------------------------------------------
28 * Implementation of functions defined in portable.h for the ARM CM3 MPU port.
29 *----------------------------------------------------------*/
30
31 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
32  * all the API functions to use the MPU wrappers.  That should only be done when
33  * task.h is included from an application file. */
34 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
35
36 /* Scheduler includes. */
37 #include "FreeRTOS.h"
38 #include "task.h"
39
40 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
41
42 #ifndef configSYSTICK_CLOCK_HZ
43     #define configSYSTICK_CLOCK_HZ    configCPU_CLOCK_HZ
44     /* Ensure the SysTick is clocked at the same frequency as the core. */
45     #define portNVIC_SYSTICK_CLK      ( 1UL << 2UL )
46 #else
47
48 /* The way the SysTick is clocked is not modified in case it is not the same
49  * as the core. */
50     #define portNVIC_SYSTICK_CLK    ( 0 )
51 #endif
52
53 /* Constants required to access and manipulate the NVIC. */
54 #define portNVIC_SYSTICK_CTRL_REG                 ( *( ( volatile uint32_t * ) 0xe000e010 ) )
55 #define portNVIC_SYSTICK_LOAD_REG                 ( *( ( volatile uint32_t * ) 0xe000e014 ) )
56 #define portNVIC_SYSTICK_CURRENT_VALUE_REG        ( *( ( volatile uint32_t * ) 0xe000e018 ) )
57 #define portNVIC_SHPR3_REG                        ( *( ( volatile uint32_t * ) 0xe000ed20 ) )
58 #define portNVIC_SHPR2_REG                        ( *( ( volatile uint32_t * ) 0xe000ed1c ) )
59 #define portNVIC_SYS_CTRL_STATE_REG               ( *( ( volatile uint32_t * ) 0xe000ed24 ) )
60 #define portNVIC_MEM_FAULT_ENABLE                 ( 1UL << 16UL )
61
62 /* Constants required to access and manipulate the MPU. */
63 #define portMPU_TYPE_REG                          ( *( ( volatile uint32_t * ) 0xe000ed90 ) )
64 #define portMPU_REGION_BASE_ADDRESS_REG           ( *( ( volatile uint32_t * ) 0xe000ed9C ) )
65 #define portMPU_REGION_ATTRIBUTE_REG              ( *( ( volatile uint32_t * ) 0xe000edA0 ) )
66 #define portMPU_CTRL_REG                          ( *( ( volatile uint32_t * ) 0xe000ed94 ) )
67 #define portEXPECTED_MPU_TYPE_VALUE               ( 8UL << 8UL ) /* 8 regions, unified. */
68 #define portMPU_ENABLE                            ( 0x01UL )
69 #define portMPU_BACKGROUND_ENABLE                 ( 1UL << 2UL )
70 #define portPRIVILEGED_EXECUTION_START_ADDRESS    ( 0UL )
71 #define portMPU_REGION_VALID                      ( 0x10UL )
72 #define portMPU_REGION_ENABLE                     ( 0x01UL )
73 #define portPERIPHERALS_START_ADDRESS             0x40000000UL
74 #define portPERIPHERALS_END_ADDRESS               0x5FFFFFFFUL
75
76 /* Constants required to access and manipulate the SysTick. */
77 #define portNVIC_SYSTICK_INT                      ( 0x00000002UL )
78 #define portNVIC_SYSTICK_ENABLE                   ( 0x00000001UL )
79 #define portNVIC_PENDSV_PRI                       ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
80 #define portNVIC_SYSTICK_PRI                      ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
81 #define portNVIC_SVC_PRI                          ( ( ( uint32_t ) configMAX_SYSCALL_INTERRUPT_PRIORITY - 1UL ) << 24UL )
82
83 /* Constants required to set up the initial stack. */
84 #define portINITIAL_XPSR                          ( 0x01000000 )
85 #define portINITIAL_CONTROL_IF_UNPRIVILEGED       ( 0x03 )
86 #define portINITIAL_CONTROL_IF_PRIVILEGED         ( 0x02 )
87
88 /* Constants required to check the validity of an interrupt priority. */
89 #define portFIRST_USER_INTERRUPT_NUMBER           ( 16 )
90 #define portNVIC_IP_REGISTERS_OFFSET_16           ( 0xE000E3F0 )
91 #define portAIRCR_REG                             ( *( ( volatile uint32_t * ) 0xE000ED0C ) )
92 #define portMAX_8_BIT_VALUE                       ( ( uint8_t ) 0xff )
93 #define portTOP_BIT_OF_BYTE                       ( ( uint8_t ) 0x80 )
94 #define portMAX_PRIGROUP_BITS                     ( ( uint8_t ) 7 )
95 #define portPRIORITY_GROUP_MASK                   ( 0x07UL << 8UL )
96 #define portPRIGROUP_SHIFT                        ( 8UL )
97
98 /* Offsets in the stack to the parameters when inside the SVC handler. */
99 #define portOFFSET_TO_PC                          ( 6 )
100
101 /* For strict compliance with the Cortex-M spec the task start address should
102  * have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
103 #define portSTART_ADDRESS_MASK                    ( ( StackType_t ) 0xfffffffeUL )
104 /*-----------------------------------------------------------*/
105
106 /*
107  * Configure a number of standard MPU regions that are used by all tasks.
108  */
109 static void prvSetupMPU( void ) PRIVILEGED_FUNCTION;
110
111 /*
112  * Return the smallest MPU region size that a given number of bytes will fit
113  * into.  The region size is returned as the value that should be programmed
114  * into the region attribute register for that region.
115  */
116 static uint32_t prvGetMPURegionSizeSetting( uint32_t ulActualSizeInBytes ) PRIVILEGED_FUNCTION;
117
118 /*
119  * Setup the timer to generate the tick interrupts.  The implementation in this
120  * file is weak to allow application writers to change the timer used to
121  * generate the tick interrupt.
122  */
123 void vPortSetupTimerInterrupt( void );
124
125 /*
126  * Standard FreeRTOS exception handlers.
127  */
128 void xPortPendSVHandler( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
129 void xPortSysTickHandler( void )  __attribute__( ( optimize( "3" ) ) ) PRIVILEGED_FUNCTION;
130 void vPortSVCHandler( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
131
132 /*
133  * Starts the scheduler by restoring the context of the first task to run.
134  */
135 static void prvRestoreContextOfFirstTask( void ) __attribute__( ( naked ) ) PRIVILEGED_FUNCTION;
136
137 /*
138  * C portion of the SVC handler.  The SVC handler is split between an asm entry
139  * and a C wrapper for simplicity of coding and maintenance.
140  */
141 static void prvSVCHandler( uint32_t * pulRegisters ) __attribute__( ( noinline ) ) PRIVILEGED_FUNCTION;
142
143 /**
144  * @brief Checks whether or not the processor is privileged.
145  *
146  * @return 1 if the processor is already privileged, 0 otherwise.
147  */
148 BaseType_t xIsPrivileged( void ) __attribute__( ( naked ) );
149
150 /**
151  * @brief Lowers the privilege level by setting the bit 0 of the CONTROL
152  * register.
153  *
154  * Bit 0 of the CONTROL register defines the privilege level of Thread Mode.
155  *  Bit[0] = 0 --> The processor is running privileged
156  *  Bit[0] = 1 --> The processor is running unprivileged.
157  */
158 void vResetPrivilege( void ) __attribute__( ( naked ) );
159
160 /**
161  * @brief Calls the port specific code to raise the privilege.
162  *
163  * @return pdFALSE if privilege was raised, pdTRUE otherwise.
164  */
165 extern BaseType_t xPortRaisePrivilege( void );
166
167 /**
168  * @brief If xRunningPrivileged is not pdTRUE, calls the port specific
169  * code to reset the privilege, otherwise does nothing.
170  */
171 extern void vPortResetPrivilege( BaseType_t xRunningPrivileged );
172 /*-----------------------------------------------------------*/
173
174 /* Each task maintains its own interrupt status in the critical nesting
175  * variable.  Note this is not saved as part of the task context as context
176  * switches can only occur when uxCriticalNesting is zero. */
177 static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
178
179 /*
180  * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
181  * FreeRTOS API functions are not called from interrupts that have been assigned
182  * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
183  */
184 #if ( configASSERT_DEFINED == 1 )
185     static uint8_t ucMaxSysCallPriority = 0;
186     static uint32_t ulMaxPRIGROUPValue = 0;
187     static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16;
188 #endif /* configASSERT_DEFINED */
189 /*-----------------------------------------------------------*/
190
191 /*
192  * See header file for description.
193  */
194 StackType_t * pxPortInitialiseStack( StackType_t * pxTopOfStack,
195                                      TaskFunction_t pxCode,
196                                      void * pvParameters,
197                                      BaseType_t xRunPrivileged )
198 {
199     /* Simulate the stack frame as it would be created by a context switch
200      * interrupt. */
201     pxTopOfStack--;                                                      /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
202     *pxTopOfStack = portINITIAL_XPSR;                                    /* xPSR */
203     pxTopOfStack--;
204     *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */
205     pxTopOfStack--;
206     *pxTopOfStack = 0;                                                   /* LR */
207     pxTopOfStack -= 5;                                                   /* R12, R3, R2 and R1. */
208     *pxTopOfStack = ( StackType_t ) pvParameters;                        /* R0 */
209     pxTopOfStack -= 9;                                                   /* R11, R10, R9, R8, R7, R6, R5 and R4. */
210
211     if( xRunPrivileged == pdTRUE )
212     {
213         *pxTopOfStack = portINITIAL_CONTROL_IF_PRIVILEGED;
214     }
215     else
216     {
217         *pxTopOfStack = portINITIAL_CONTROL_IF_UNPRIVILEGED;
218     }
219
220     return pxTopOfStack;
221 }
222 /*-----------------------------------------------------------*/
223
224 void vPortSVCHandler( void )
225 {
226     /* Assumes psp was in use. */
227     __asm volatile
228     (
229         #ifndef USE_PROCESS_STACK   /* Code should not be required if a main() is using the process stack. */
230             "   tst lr, #4                                              \n"
231             "   ite eq                                                  \n"
232             "   mrseq r0, msp                                   \n"
233             "   mrsne r0, psp                                   \n"
234         #else
235             "   mrs r0, psp                                             \n"
236         #endif
237         "       b %0                                                    \n"
238         ::"i" ( prvSVCHandler ) : "r0", "memory"
239     );
240 }
241 /*-----------------------------------------------------------*/
242
243 static void prvSVCHandler( uint32_t * pulParam )
244 {
245     uint8_t ucSVCNumber;
246     uint32_t ulPC;
247
248     #if ( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 )
249         #if defined( __ARMCC_VERSION )
250
251             /* Declaration when these variable are defined in code instead of being
252              * exported from linker scripts. */
253             extern uint32_t * __syscalls_flash_start__;
254             extern uint32_t * __syscalls_flash_end__;
255         #else
256             /* Declaration when these variable are exported from linker scripts. */
257             extern uint32_t __syscalls_flash_start__[];
258             extern uint32_t __syscalls_flash_end__[];
259         #endif /* #if defined( __ARMCC_VERSION ) */
260     #endif /* #if( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 ) */
261
262     /* The stack contains: r0, r1, r2, r3, r12, LR, PC and xPSR.  The first
263      * argument (r0) is pulParam[ 0 ]. */
264     ulPC = pulParam[ portOFFSET_TO_PC ];
265     ucSVCNumber = ( ( uint8_t * ) ulPC )[ -2 ];
266
267     switch( ucSVCNumber )
268     {
269         case portSVC_START_SCHEDULER:
270             portNVIC_SHPR2_REG |= portNVIC_SVC_PRI;
271             prvRestoreContextOfFirstTask();
272             break;
273
274         case portSVC_YIELD:
275             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
276
277             /* Barriers are normally not required
278              * but do ensure the code is completely
279              * within the specified behaviour for the
280              * architecture. */
281             __asm volatile ( "dsb" ::: "memory" );
282             __asm volatile ( "isb" );
283
284             break;
285
286
287             #if ( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 )
288                 case portSVC_RAISE_PRIVILEGE: /* Only raise the privilege, if the
289                                                * svc was raised from any of the
290                                                * system calls. */
291
292                     if( ( ulPC >= ( uint32_t ) __syscalls_flash_start__ ) &&
293                         ( ulPC <= ( uint32_t ) __syscalls_flash_end__ ) )
294                     {
295                         __asm volatile
296                         (
297                             "   mrs r1, control         \n"/* Obtain current control value. */
298                             "   bic r1, #1                      \n"/* Set privilege bit. */
299                             "   msr control, r1         \n"/* Write back new control value. */
300                             ::: "r1", "memory"
301                         );
302                     }
303
304                     break;
305             #else /* if ( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 ) */
306                 case portSVC_RAISE_PRIVILEGE:
307                     __asm volatile
308                     (
309                         "       mrs r1, control         \n"/* Obtain current control value. */
310                         "       bic r1, #1                      \n"/* Set privilege bit. */
311                         "       msr control, r1         \n"/* Write back new control value. */
312                         ::: "r1", "memory"
313                     );
314                     break;
315                     #endif /* #if( configENFORCE_SYSTEM_CALLS_FROM_KERNEL_ONLY == 1 ) */
316
317                 default: /* Unknown SVC call. */
318                     break;
319     }
320 }
321 /*-----------------------------------------------------------*/
322
323 static void prvRestoreContextOfFirstTask( void )
324 {
325     __asm volatile
326     (
327         "       ldr r0, =0xE000ED08                             \n"/* Use the NVIC offset register to locate the stack. */
328         "       ldr r0, [r0]                                    \n"
329         "       ldr r0, [r0]                                    \n"
330         "       msr msp, r0                                             \n"/* Set the msp back to the start of the stack. */
331         "       ldr     r3, pxCurrentTCBConst2          \n"/* Restore the context. */
332         "       ldr r1, [r3]                                    \n"
333         "       ldr r0, [r1]                                    \n"/* The first item in the TCB is the task top of stack. */
334         "       add r1, r1, #4                                  \n"/* Move onto the second item in the TCB... */
335         "                                                                       \n"
336         "       dmb                                                             \n"/* Complete outstanding transfers before disabling MPU. */
337         "       ldr r2, =0xe000ed94                             \n"/* MPU_CTRL register. */
338         "       ldr r3, [r2]                                    \n"/* Read the value of MPU_CTRL. */
339         "       bic r3, #1                                              \n"/* r3 = r3 & ~1 i.e. Clear the bit 0 in r3. */
340         "       str r3, [r2]                                    \n"/* Disable MPU. */
341         "                                                                       \n"
342         "       ldr r2, =0xe000ed9c                             \n"/* Region Base Address register. */
343         "       ldmia r1!, {r4-r11}                             \n"/* Read 4 sets of MPU registers. */
344         "       stmia r2!, {r4-r11}                             \n"/* Write 4 sets of MPU registers. */
345         "                                                                       \n"
346         "       ldr r2, =0xe000ed94                             \n"/* MPU_CTRL register. */
347         "       ldr r3, [r2]                                    \n"/* Read the value of MPU_CTRL. */
348         "       orr r3, #1                                              \n"/* r3 = r3 | 1 i.e. Set the bit 0 in r3. */
349         "       str r3, [r2]                                    \n"/* Enable MPU. */
350         "       dsb                                                             \n"/* Force memory writes before continuing. */
351         "                                                                       \n"
352         "       ldmia r0!, {r3, r4-r11}                 \n"/* Pop the registers that are not automatically saved on exception entry. */
353         "       msr control, r3                                 \n"
354         "       msr psp, r0                                             \n"/* Restore the task stack pointer. */
355         "       mov r0, #0                                              \n"
356         "       msr     basepri, r0                                     \n"
357         "       ldr r14, =0xfffffffd                    \n"/* Load exec return code. */
358         "       bx r14                                                  \n"
359         "                                                                       \n"
360         "       .align 4                                                \n"
361         "pxCurrentTCBConst2: .word pxCurrentTCB \n"
362     );
363 }
364 /*-----------------------------------------------------------*/
365
366 /*
367  * See header file for description.
368  */
369 BaseType_t xPortStartScheduler( void )
370 {
371     /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.  See
372      * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
373     configASSERT( ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) );
374
375     #if ( configASSERT_DEFINED == 1 )
376         {
377             volatile uint32_t ulOriginalPriority;
378             volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
379             volatile uint8_t ucMaxPriorityValue;
380
381             /* Determine the maximum priority from which ISR safe FreeRTOS API
382              * functions can be called.  ISR safe functions are those that end in
383              * "FromISR".  FreeRTOS maintains separate thread and ISR API functions
384              * to ensure interrupt entry is as fast and simple as possible.
385              *
386              * Save the interrupt priority value that is about to be clobbered. */
387             ulOriginalPriority = *pucFirstUserPriorityRegister;
388
389             /* Determine the number of priority bits available.  First write to all
390              * possible bits. */
391             *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
392
393             /* Read the value back to see how many bits stuck. */
394             ucMaxPriorityValue = *pucFirstUserPriorityRegister;
395
396             /* Use the same mask on the maximum system call priority. */
397             ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
398
399             /* Calculate the maximum acceptable priority group value for the number
400              * of bits read back. */
401             ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
402
403             while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
404             {
405                 ulMaxPRIGROUPValue--;
406                 ucMaxPriorityValue <<= ( uint8_t ) 0x01;
407             }
408
409             #ifdef __NVIC_PRIO_BITS
410                 {
411                     /* Check the CMSIS configuration that defines the number of
412                      * priority bits matches the number of priority bits actually queried
413                      * from the hardware. */
414                     configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );
415                 }
416             #endif
417
418             #ifdef configPRIO_BITS
419                 {
420                     /* Check the FreeRTOS configuration that defines the number of
421                      * priority bits matches the number of priority bits actually queried
422                      * from the hardware. */
423                     configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );
424                 }
425             #endif
426
427             /* Shift the priority group value back to its position within the AIRCR
428              * register. */
429             ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
430             ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
431
432             /* Restore the clobbered interrupt priority register to its original
433              * value. */
434             *pucFirstUserPriorityRegister = ulOriginalPriority;
435         }
436     #endif /* conifgASSERT_DEFINED */
437
438     /* Make PendSV and SysTick the same priority as the kernel, and the SVC
439      * handler higher priority so it can be used to exit a critical section (where
440      * lower priorities are masked). */
441     portNVIC_SHPR3_REG |= portNVIC_PENDSV_PRI;
442     portNVIC_SHPR3_REG |= portNVIC_SYSTICK_PRI;
443
444     /* Configure the regions in the MPU that are common to all tasks. */
445     prvSetupMPU();
446
447     /* Start the timer that generates the tick ISR.  Interrupts are disabled
448      * here already. */
449     vPortSetupTimerInterrupt();
450
451     /* Initialise the critical nesting count ready for the first task. */
452     uxCriticalNesting = 0;
453
454     /* Start the first task. */
455     __asm volatile (
456         " ldr r0, =0xE000ED08   \n"/* Use the NVIC offset register to locate the stack. */
457         " ldr r0, [r0]                  \n"
458         " ldr r0, [r0]                  \n"
459         " msr msp, r0                   \n"/* Set the msp back to the start of the stack. */
460         " cpsie i                               \n"/* Globally enable interrupts. */
461         " cpsie f                               \n"
462         " dsb                                   \n"
463         " isb                                   \n"
464         " svc %0                                \n"/* System call to start first task. */
465         " nop                                   \n"
466         " .ltorg                                \n"
467         ::"i" ( portSVC_START_SCHEDULER ) : "memory" );
468
469     /* Should not get here! */
470     return 0;
471 }
472 /*-----------------------------------------------------------*/
473
474 void vPortEndScheduler( void )
475 {
476     /* Not implemented in ports where there is nothing to return to.
477      * Artificially force an assert. */
478     configASSERT( uxCriticalNesting == 1000UL );
479 }
480 /*-----------------------------------------------------------*/
481
482 void vPortEnterCritical( void )
483 {
484     BaseType_t xRunningPrivileged = xPortRaisePrivilege();
485
486     portDISABLE_INTERRUPTS();
487     uxCriticalNesting++;
488
489     vPortResetPrivilege( xRunningPrivileged );
490 }
491 /*-----------------------------------------------------------*/
492
493 void vPortExitCritical( void )
494 {
495     BaseType_t xRunningPrivileged = xPortRaisePrivilege();
496
497     configASSERT( uxCriticalNesting );
498     uxCriticalNesting--;
499
500     if( uxCriticalNesting == 0 )
501     {
502         portENABLE_INTERRUPTS();
503     }
504
505     vPortResetPrivilege( xRunningPrivileged );
506 }
507 /*-----------------------------------------------------------*/
508
509 void xPortPendSVHandler( void )
510 {
511     /* This is a naked function. */
512
513     __asm volatile
514     (
515         "       mrs r0, psp                                                     \n"
516         "                                                                               \n"
517         "       ldr     r3, pxCurrentTCBConst                   \n"/* Get the location of the current TCB. */
518         "       ldr     r2, [r3]                                                \n"
519         "                                                                               \n"
520         "       mrs r1, control                                         \n"
521         "       stmdb r0!, {r1, r4-r11}                         \n"/* Save the remaining registers. */
522         "       str r0, [r2]                                            \n"/* Save the new top of stack into the first member of the TCB. */
523         "                                                                               \n"
524         "       stmdb sp!, {r3, r14}                            \n"
525         "       mov r0, %0                                                      \n"
526         "       msr basepri, r0                                         \n"
527         "       dsb                                                                     \n"
528         "       isb                                                                     \n"
529         "       bl vTaskSwitchContext                           \n"
530         "       mov r0, #0                                                      \n"
531         "       msr basepri, r0                                         \n"
532         "       ldmia sp!, {r3, r14}                            \n"
533         "                                                                               \n"/* Restore the context. */
534         "       ldr r1, [r3]                                            \n"
535         "       ldr r0, [r1]                                            \n"/* The first item in the TCB is the task top of stack. */
536         "       add r1, r1, #4                                          \n"/* Move onto the second item in the TCB... */
537         "                                                                               \n"
538         "       dmb                                                                     \n"/* Complete outstanding transfers before disabling MPU. */
539         "       ldr r2, =0xe000ed94                                     \n"/* MPU_CTRL register. */
540         "       ldr r3, [r2]                                            \n"/* Read the value of MPU_CTRL. */
541         "       bic r3, #1                                                      \n"/* r3 = r3 & ~1 i.e. Clear the bit 0 in r3. */
542         "       str r3, [r2]                                            \n"/* Disable MPU. */
543         "                                                                               \n"
544         "       ldr r2, =0xe000ed9c                                     \n"/* Region Base Address register. */
545         "       ldmia r1!, {r4-r11}                                     \n"/* Read 4 sets of MPU registers. */
546         "       stmia r2!, {r4-r11}                                     \n"/* Write 4 sets of MPU registers. */
547         "                                                                               \n"
548         "       ldr r2, =0xe000ed94                                     \n"/* MPU_CTRL register. */
549         "       ldr r3, [r2]                                            \n"/* Read the value of MPU_CTRL. */
550         "       orr r3, #1                                                      \n"/* r3 = r3 | 1 i.e. Set the bit 0 in r3. */
551         "       str r3, [r2]                                            \n"/* Enable MPU. */
552         "       dsb                                                                     \n"/* Force memory writes before continuing. */
553         "                                                                               \n"
554         "       ldmia r0!, {r3, r4-r11}                         \n"/* Pop the registers that are not automatically saved on exception entry. */
555         "       msr control, r3                                         \n"
556         "                                                                               \n"
557         "       msr psp, r0                                                     \n"
558         "       bx r14                                                          \n"
559         "                                                                               \n"
560         "       .align 4                                                        \n"
561         "pxCurrentTCBConst: .word pxCurrentTCB  \n"
562         ::"i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY )
563     );
564 }
565 /*-----------------------------------------------------------*/
566
567 void xPortSysTickHandler( void )
568 {
569     uint32_t ulDummy;
570
571     ulDummy = portSET_INTERRUPT_MASK_FROM_ISR();
572     {
573         /* Increment the RTOS tick. */
574         if( xTaskIncrementTick() != pdFALSE )
575         {
576             /* Pend a context switch. */
577             portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
578         }
579     }
580     portCLEAR_INTERRUPT_MASK_FROM_ISR( ulDummy );
581 }
582 /*-----------------------------------------------------------*/
583
584 /*
585  * Setup the systick timer to generate the tick interrupts at the required
586  * frequency.
587  */
588 __attribute__( ( weak ) ) void vPortSetupTimerInterrupt( void )
589 {
590     /* Stop and clear the SysTick. */
591     portNVIC_SYSTICK_CTRL_REG = 0UL;
592     portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
593
594     /* Configure SysTick to interrupt at the requested rate. */
595     portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
596     portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE );
597 }
598 /*-----------------------------------------------------------*/
599
600 static void prvSetupMPU( void )
601 {
602     extern uint32_t __privileged_functions_start__[];
603     extern uint32_t __privileged_functions_end__[];
604     extern uint32_t __FLASH_segment_start__[];
605     extern uint32_t __FLASH_segment_end__[];
606     extern uint32_t __privileged_data_start__[];
607     extern uint32_t __privileged_data_end__[];
608
609     /* Check the expected MPU is present. */
610     if( portMPU_TYPE_REG == portEXPECTED_MPU_TYPE_VALUE )
611     {
612         /* First setup the unprivileged flash for unprivileged read only access. */
613         portMPU_REGION_BASE_ADDRESS_REG = ( ( uint32_t ) __FLASH_segment_start__ ) | /* Base address. */
614                                           ( portMPU_REGION_VALID ) |
615                                           ( portUNPRIVILEGED_FLASH_REGION );
616
617         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_READ_ONLY ) |
618                                        ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |
619                                        ( prvGetMPURegionSizeSetting( ( uint32_t ) __FLASH_segment_end__ - ( uint32_t ) __FLASH_segment_start__ ) ) |
620                                        ( portMPU_REGION_ENABLE );
621
622         /* Setup the privileged flash for privileged only access.  This is where
623          * the kernel code is * placed. */
624         portMPU_REGION_BASE_ADDRESS_REG = ( ( uint32_t ) __privileged_functions_start__ ) | /* Base address. */
625                                           ( portMPU_REGION_VALID ) |
626                                           ( portPRIVILEGED_FLASH_REGION );
627
628         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_PRIVILEGED_READ_ONLY ) |
629                                        ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |
630                                        ( prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_functions_end__ - ( uint32_t ) __privileged_functions_start__ ) ) |
631                                        ( portMPU_REGION_ENABLE );
632
633         /* Setup the privileged data RAM region.  This is where the kernel data
634          * is placed. */
635         portMPU_REGION_BASE_ADDRESS_REG = ( ( uint32_t ) __privileged_data_start__ ) | /* Base address. */
636                                           ( portMPU_REGION_VALID ) |
637                                           ( portPRIVILEGED_RAM_REGION );
638
639         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_PRIVILEGED_READ_WRITE ) |
640                                        ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |
641                                        prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_data_end__ - ( uint32_t ) __privileged_data_start__ ) |
642                                        ( portMPU_REGION_ENABLE );
643
644         /* By default allow everything to access the general peripherals.  The
645          * system peripherals and registers are protected. */
646         portMPU_REGION_BASE_ADDRESS_REG = ( portPERIPHERALS_START_ADDRESS ) |
647                                           ( portMPU_REGION_VALID ) |
648                                           ( portGENERAL_PERIPHERALS_REGION );
649
650         portMPU_REGION_ATTRIBUTE_REG = ( portMPU_REGION_READ_WRITE | portMPU_REGION_EXECUTE_NEVER ) |
651                                        ( prvGetMPURegionSizeSetting( portPERIPHERALS_END_ADDRESS - portPERIPHERALS_START_ADDRESS ) ) |
652                                        ( portMPU_REGION_ENABLE );
653
654         /* Enable the memory fault exception. */
655         portNVIC_SYS_CTRL_STATE_REG |= portNVIC_MEM_FAULT_ENABLE;
656
657         /* Enable the MPU with the background region configured. */
658         portMPU_CTRL_REG |= ( portMPU_ENABLE | portMPU_BACKGROUND_ENABLE );
659     }
660 }
661 /*-----------------------------------------------------------*/
662
663 static uint32_t prvGetMPURegionSizeSetting( uint32_t ulActualSizeInBytes )
664 {
665     uint32_t ulRegionSize, ulReturnValue = 4;
666
667     /* 32 is the smallest region size, 31 is the largest valid value for
668      * ulReturnValue. */
669     for( ulRegionSize = 32UL; ulReturnValue < 31UL; ( ulRegionSize <<= 1UL ) )
670     {
671         if( ulActualSizeInBytes <= ulRegionSize )
672         {
673             break;
674         }
675         else
676         {
677             ulReturnValue++;
678         }
679     }
680
681     /* Shift the code by one before returning so it can be written directly
682      * into the the correct bit position of the attribute register. */
683     return( ulReturnValue << 1UL );
684 }
685 /*-----------------------------------------------------------*/
686
687 BaseType_t xIsPrivileged( void ) /* __attribute__ (( naked )) */
688 {
689     __asm volatile
690     (
691         "       mrs r0, control                                                 \n"/* r0 = CONTROL. */
692         "       tst r0, #1                                                              \n"/* Perform r0 & 1 (bitwise AND) and update the conditions flag. */
693         "       ite ne                                                                  \n"
694         "       movne r0, #0                                                    \n"/* CONTROL[0]!=0. Return false to indicate that the processor is not privileged. */
695         "       moveq r0, #1                                                    \n"/* CONTROL[0]==0. Return true to indicate that the processor is privileged. */
696         "       bx lr                                                                   \n"/* Return. */
697         "                                                                                       \n"
698         "       .align 4                                                                \n"
699         ::: "r0", "memory"
700     );
701 }
702 /*-----------------------------------------------------------*/
703
704 void vResetPrivilege( void ) /* __attribute__ (( naked )) */
705 {
706     __asm volatile
707     (
708         "       mrs r0, control                                                 \n"/* r0 = CONTROL. */
709         "       orr r0, #1                                                              \n"/* r0 = r0 | 1. */
710         "       msr control, r0                                                 \n"/* CONTROL = r0. */
711         "       bx lr                                                                   \n"/* Return to the caller. */
712         ::: "r0", "memory"
713     );
714 }
715 /*-----------------------------------------------------------*/
716
717 void vPortStoreTaskMPUSettings( xMPU_SETTINGS * xMPUSettings,
718                                 const struct xMEMORY_REGION * const xRegions,
719                                 StackType_t * pxBottomOfStack,
720                                 uint32_t ulStackDepth )
721 {
722     extern uint32_t __SRAM_segment_start__[];
723     extern uint32_t __SRAM_segment_end__[];
724     extern uint32_t __privileged_data_start__[];
725     extern uint32_t __privileged_data_end__[];
726     int32_t lIndex;
727     uint32_t ul;
728
729     if( xRegions == NULL )
730     {
731         /* No MPU regions are specified so allow access to all RAM. */
732         xMPUSettings->xRegion[ 0 ].ulRegionBaseAddress =
733             ( ( uint32_t ) __SRAM_segment_start__ ) | /* Base address. */
734             ( portMPU_REGION_VALID ) |
735             ( portSTACK_REGION );
736
737         xMPUSettings->xRegion[ 0 ].ulRegionAttribute =
738             ( portMPU_REGION_READ_WRITE ) |
739             ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |
740             ( prvGetMPURegionSizeSetting( ( uint32_t ) __SRAM_segment_end__ - ( uint32_t ) __SRAM_segment_start__ ) ) |
741             ( portMPU_REGION_ENABLE );
742
743         /* Re-instate the privileged only RAM region as xRegion[ 0 ] will have
744          * just removed the privileged only parameters. */
745         xMPUSettings->xRegion[ 1 ].ulRegionBaseAddress =
746             ( ( uint32_t ) __privileged_data_start__ ) | /* Base address. */
747             ( portMPU_REGION_VALID ) |
748             ( portSTACK_REGION + 1 );
749
750         xMPUSettings->xRegion[ 1 ].ulRegionAttribute =
751             ( portMPU_REGION_PRIVILEGED_READ_WRITE ) |
752             ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |
753             prvGetMPURegionSizeSetting( ( uint32_t ) __privileged_data_end__ - ( uint32_t ) __privileged_data_start__ ) |
754             ( portMPU_REGION_ENABLE );
755
756         /* Invalidate all other regions. */
757         for( ul = 2; ul <= portNUM_CONFIGURABLE_REGIONS; ul++ )
758         {
759             xMPUSettings->xRegion[ ul ].ulRegionBaseAddress = ( portSTACK_REGION + ul ) | portMPU_REGION_VALID;
760             xMPUSettings->xRegion[ ul ].ulRegionAttribute = 0UL;
761         }
762     }
763     else
764     {
765         /* This function is called automatically when the task is created - in
766          * which case the stack region parameters will be valid.  At all other
767          * times the stack parameters will not be valid and it is assumed that the
768          * stack region has already been configured. */
769         if( ulStackDepth > 0 )
770         {
771             /* Define the region that allows access to the stack. */
772             xMPUSettings->xRegion[ 0 ].ulRegionBaseAddress =
773                 ( ( uint32_t ) pxBottomOfStack ) |
774                 ( portMPU_REGION_VALID ) |
775                 ( portSTACK_REGION ); /* Region number. */
776
777             xMPUSettings->xRegion[ 0 ].ulRegionAttribute =
778                 ( portMPU_REGION_READ_WRITE ) | /* Read and write. */
779                 ( prvGetMPURegionSizeSetting( ulStackDepth * ( uint32_t ) sizeof( StackType_t ) ) ) |
780                 ( portMPU_REGION_CACHEABLE_BUFFERABLE ) |
781                 ( portMPU_REGION_ENABLE );
782         }
783
784         lIndex = 0;
785
786         for( ul = 1; ul <= portNUM_CONFIGURABLE_REGIONS; ul++ )
787         {
788             if( ( xRegions[ lIndex ] ).ulLengthInBytes > 0UL )
789             {
790                 /* Translate the generic region definition contained in
791                  * xRegions into the CM3 specific MPU settings that are then
792                  * stored in xMPUSettings. */
793                 xMPUSettings->xRegion[ ul ].ulRegionBaseAddress =
794                     ( ( uint32_t ) xRegions[ lIndex ].pvBaseAddress ) |
795                     ( portMPU_REGION_VALID ) |
796                     ( portSTACK_REGION + ul ); /* Region number. */
797
798                 xMPUSettings->xRegion[ ul ].ulRegionAttribute =
799                     ( prvGetMPURegionSizeSetting( xRegions[ lIndex ].ulLengthInBytes ) ) |
800                     ( xRegions[ lIndex ].ulParameters ) |
801                     ( portMPU_REGION_ENABLE );
802             }
803             else
804             {
805                 /* Invalidate the region. */
806                 xMPUSettings->xRegion[ ul ].ulRegionBaseAddress = ( portSTACK_REGION + ul ) | portMPU_REGION_VALID;
807                 xMPUSettings->xRegion[ ul ].ulRegionAttribute = 0UL;
808             }
809
810             lIndex++;
811         }
812     }
813 }
814 /*-----------------------------------------------------------*/
815
816 #if ( configASSERT_DEFINED == 1 )
817
818     void vPortValidateInterruptPriority( void )
819     {
820         uint32_t ulCurrentInterrupt;
821         uint8_t ucCurrentPriority;
822
823         /* Obtain the number of the currently executing interrupt. */
824         __asm volatile ( "mrs %0, ipsr" : "=r" ( ulCurrentInterrupt )::"memory" );
825
826         /* Is the interrupt number a user defined interrupt? */
827         if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
828         {
829             /* Look up the interrupt's priority. */
830             ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
831
832             /* The following assertion will fail if a service routine (ISR) for
833              * an interrupt that has been assigned a priority above
834              * configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
835              * function.  ISR safe FreeRTOS API functions must *only* be called
836              * from interrupts that have been assigned a priority at or below
837              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
838              *
839              * Numerically low interrupt priority numbers represent logically high
840              * interrupt priorities, therefore the priority of the interrupt must
841              * be set to a value equal to or numerically *higher* than
842              * configMAX_SYSCALL_INTERRUPT_PRIORITY.
843              *
844              * Interrupts that  use the FreeRTOS API must not be left at their
845              * default priority of      zero as that is the highest possible priority,
846              * which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
847              * and      therefore also guaranteed to be invalid.
848              *
849              * FreeRTOS maintains separate thread and ISR API functions to ensure
850              * interrupt entry is as fast and simple as possible.
851              *
852              * The following links provide detailed information:
853              * https://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
854              * https://www.FreeRTOS.org/FAQHelp.html */
855             configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
856         }
857
858         /* Priority grouping:  The interrupt controller (NVIC) allows the bits
859          * that define each interrupt's priority to be split between bits that
860          * define the interrupt's pre-emption priority bits and bits that define
861          * the interrupt's sub-priority.  For simplicity all bits must be defined
862          * to be pre-emption priority bits.  The following assertion will fail if
863          * this is not the case (if some bits represent a sub-priority).
864          *
865          * If the application only uses CMSIS libraries for interrupt
866          * configuration then the correct setting can be achieved on all Cortex-M
867          * devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
868          * scheduler.  Note however that some vendor specific peripheral libraries
869          * assume a non-zero priority group setting, in which cases using a value
870          * of zero will result in unpredicable behaviour. */
871         configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
872     }
873
874 #endif /* configASSERT_DEFINED */
875 /*-----------------------------------------------------------*/