xref: /Kernel-v10.6.2/portable/MPLAB/PIC32MZ/port.c (revision ef7b253b56c9788077f5ecd6c9deb4021923d646)
1 /*
2  * FreeRTOS Kernel V10.6.2
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * https://www.FreeRTOS.org
25  * https://github.com/FreeRTOS
26  *
27  */
28 
29 /*-----------------------------------------------------------
30  * Implementation of functions defined in portable.h for the PIC32MZ port.
31   *----------------------------------------------------------*/
32 
33 /* Microchip specific headers. */
34 #include <xc.h>
35 
36 /* Standard headers. */
37 #include <string.h>
38 
39 /* Scheduler include files. */
40 #include "FreeRTOS.h"
41 #include "task.h"
42 
43 #if !defined(__PIC32MZ__)
44     #error This port is designed to work with XC32 on PIC32MZ MCUs.  Please update your C compiler version or settings.
45 #endif
46 
47 #if( ( configMAX_SYSCALL_INTERRUPT_PRIORITY >= 0x7 ) || ( configMAX_SYSCALL_INTERRUPT_PRIORITY == 0 ) )
48     #error configMAX_SYSCALL_INTERRUPT_PRIORITY must be less than 7 and greater than 0
49 #endif
50 
51 /* Hardware specifics. */
52 #define portTIMER_PRESCALE  8
53 #define portPRESCALE_BITS   1
54 
55 /* Bits within various registers. */
56 #define portIE_BIT                  ( 0x00000001 )
57 #define portEXL_BIT                 ( 0x00000002 )
58 #define portMX_BIT                  ( 0x01000000 ) /* Allow access to DSP instructions. */
59 #define portCU1_BIT                 ( 0x20000000 ) /* enable CP1 for parts with hardware. */
60 #define portFR_BIT                  ( 0x04000000 ) /* Enable 64 bit floating point registers. */
61 
62 /* Bits within the CAUSE register. */
63 #define portCORE_SW_0               ( 0x00000100 )
64 #define portCORE_SW_1               ( 0x00000200 )
65 
66 /* The EXL bit is set to ensure interrupts do not occur while the context of
67 the first task is being restored. */
68 #if ( __mips_hard_float == 1 )
69     #define portINITIAL_SR          ( portIE_BIT | portEXL_BIT | portMX_BIT | portFR_BIT | portCU1_BIT )
70 #else
71     #define portINITIAL_SR          ( portIE_BIT | portEXL_BIT | portMX_BIT )
72 #endif
73 
74 /* The initial value to store into the FPU status and control register. This is
75  only used on parts that support a hardware FPU. */
76 #define portINITIAL_FPSCR           (0x1000000) /* High perf on denormal ops */
77 
78 
79 /*
80 By default port.c generates its tick interrupt from TIMER1.  The user can
81 override this behaviour by:
82     1: Providing their own implementation of vApplicationSetupTickTimerInterrupt(),
83        which is the function that configures the timer.  The function is defined
84        as a weak symbol in this file so if the same function name is used in the
85        application code then the version in the application code will be linked
86        into the application in preference to the version defined in this file.
87     2: Define configTICK_INTERRUPT_VECTOR to the vector number of the timer used
88        to generate the tick interrupt.  For example, when timer 1 is used then
89        configTICK_INTERRUPT_VECTOR is set to _TIMER_1_VECTOR.
90        configTICK_INTERRUPT_VECTOR should be defined in FreeRTOSConfig.h.
91     3: Define configCLEAR_TICK_TIMER_INTERRUPT() to clear the interrupt in the
92        timer used to generate the tick interrupt.  For example, when timer 1 is
93        used configCLEAR_TICK_TIMER_INTERRUPT() is defined to
94        IFS0CLR = _IFS0_T1IF_MASK.
95 */
96 #ifndef configTICK_INTERRUPT_VECTOR
97     #define configTICK_INTERRUPT_VECTOR _TIMER_1_VECTOR
98     #define configCLEAR_TICK_TIMER_INTERRUPT() IFS0CLR = _IFS0_T1IF_MASK
99 #else
100     #ifndef configCLEAR_TICK_TIMER_INTERRUPT
101         #error If configTICK_INTERRUPT_VECTOR is defined in application code then configCLEAR_TICK_TIMER_INTERRUPT must also be defined in application code.
102     #endif
103 #endif
104 
105 /* Let the user override the pre-loading of the initial RA with the address of
106 prvTaskExitError() in case it messes up unwinding of the stack in the
107 debugger - in which case configTASK_RETURN_ADDRESS can be defined as 0 (NULL). */
108 #ifdef configTASK_RETURN_ADDRESS
109     #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
110 #else
111     #define portTASK_RETURN_ADDRESS prvTaskExitError
112 #endif
113 
114 /* Set configCHECK_FOR_STACK_OVERFLOW to 3 to add ISR stack checking to task
115 stack checking.  A problem in the ISR stack will trigger an assert, not call the
116 stack overflow hook function (because the stack overflow hook is specific to a
117 task stack, not the ISR stack). */
118 #if( configCHECK_FOR_STACK_OVERFLOW > 2 )
119 
120     /* Don't use 0xa5 as the stack fill bytes as that is used by the kernerl for
121     the task stacks, and so will legitimately appear in many positions within
122     the ISR stack. */
123     #define portISR_STACK_FILL_BYTE 0xee
124 
125     static const uint8_t ucExpectedStackBytes[] = {
126                                     portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,     \
127                                     portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,     \
128                                     portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,     \
129                                     portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE,     \
130                                     portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE, portISR_STACK_FILL_BYTE };   \
131 
132     #define portCHECK_ISR_STACK() configASSERT( ( memcmp( ( void * ) xISRStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) == 0 ) )
133 #else
134     /* Define the function away. */
135     #define portCHECK_ISR_STACK()
136 #endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */
137 
138 /*-----------------------------------------------------------*/
139 
140 /*
141  * Used to catch tasks that attempt to return from their implementing function.
142  */
143 static void prvTaskExitError( void );
144 
145 /*-----------------------------------------------------------*/
146 
147 /* Records the interrupt nesting depth.  This is initialised to one as it is
148 decremented to 0 when the first task starts. */
149 volatile UBaseType_t uxInterruptNesting = 0x01;
150 
151 /* Stores the task stack pointer when a switch is made to use the system stack. */
152 UBaseType_t uxSavedTaskStackPointer = 0;
153 
154 /* The stack used by interrupt service routines that cause a context switch. */
155 __attribute__ ((aligned(8))) StackType_t xISRStack[ configISR_STACK_SIZE ] = { 0 };
156 
157 /* The top of stack value ensures there is enough space to store 6 registers on
158 the callers stack, as some functions seem to want to do this.  8 byte alignment
159 is required to allow double word floating point stack pushes generated by the
160 compiler. */
161 const StackType_t * const xISRStackTop = &( xISRStack[ ( configISR_STACK_SIZE & ~portBYTE_ALIGNMENT_MASK ) - 8 ] );
162 
163 /* Saved as part of the task context. Set to pdFALSE if the task does not
164  require an FPU context. */
165 #if ( __mips_hard_float == 1 ) && ( configUSE_TASK_FPU_SUPPORT == 1 )
166     uint32_t ulTaskHasFPUContext = 0;
167 #endif
168 
169 /*-----------------------------------------------------------*/
170 
171 /*
172  * See header file for description.
173  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)174 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
175 {
176     /* Ensure 8 byte alignment is maintained when leaving this function. */
177     pxTopOfStack--;
178     pxTopOfStack--;
179 
180     *pxTopOfStack = (StackType_t) 0xDEADBEEF;
181     pxTopOfStack--;
182 
183     *pxTopOfStack = (StackType_t) 0x12345678;   /* Word to which the stack pointer will be left pointing after context restore. */
184     pxTopOfStack--;
185 
186     *pxTopOfStack = (StackType_t) _CP0_GET_CAUSE();
187     pxTopOfStack--;
188 
189     *pxTopOfStack = (StackType_t) portINITIAL_SR;/* CP0_STATUS */
190     pxTopOfStack--;
191 
192     *pxTopOfStack = (StackType_t) pxCode;       /* CP0_EPC */
193     pxTopOfStack--;
194 
195     *pxTopOfStack = (StackType_t) 0x00000000;   /* DSPControl */
196     pxTopOfStack -= 7;                          /* Includes space for AC1 - AC3. */
197 
198     *pxTopOfStack = (StackType_t) portTASK_RETURN_ADDRESS;  /* ra */
199     pxTopOfStack -= 15;
200 
201     *pxTopOfStack = (StackType_t) pvParameters; /* Parameters to pass in. */
202     pxTopOfStack -= 15;
203 
204     *pxTopOfStack = (StackType_t) pdFALSE; /*by default disable FPU context save on parts with FPU */
205 
206     return pxTopOfStack;
207 }
208 /*-----------------------------------------------------------*/
209 
prvTaskExitError(void)210 static void prvTaskExitError( void )
211 {
212     /* A function that implements a task must not exit or attempt to return to
213     its caller as there is nothing to return to.  If a task wants to exit it
214     should instead call vTaskDelete( NULL ).
215 
216     Artificially force an assert() to be triggered if configASSERT() is
217     defined, then stop here so application writers can catch the error. */
218     configASSERT( uxSavedTaskStackPointer == 0UL );
219     portDISABLE_INTERRUPTS();
220     for( ;; );
221 }
222 /*-----------------------------------------------------------*/
223 
224 /*
225  * Setup a timer for a regular tick.  This function uses peripheral timer 1.
226  * The function is declared weak so an application writer can use a different
227  * timer by redefining this implementation.  If a different timer is used then
228  * configTICK_INTERRUPT_VECTOR must also be defined in FreeRTOSConfig.h to
229  * ensure the RTOS provided tick interrupt handler is installed on the correct
230  * vector number.  When Timer 1 is used the vector number is defined as
231  * _TIMER_1_VECTOR.
232  */
vApplicationSetupTickTimerInterrupt(void)233 __attribute__(( weak )) void vApplicationSetupTickTimerInterrupt( void )
234 {
235 const uint32_t ulCompareMatch = ( (configPERIPHERAL_CLOCK_HZ / portTIMER_PRESCALE) / configTICK_RATE_HZ ) - 1UL;
236 
237     T1CON = 0x0000;
238     T1CONbits.TCKPS = portPRESCALE_BITS;
239     PR1 = ulCompareMatch;
240     IPC1bits.T1IP = configKERNEL_INTERRUPT_PRIORITY;
241 
242     /* Clear the interrupt as a starting condition. */
243     IFS0bits.T1IF = 0;
244 
245     /* Enable the interrupt. */
246     IEC0bits.T1IE = 1;
247 
248     /* Start the timer. */
249     T1CONbits.TON = 1;
250 }
251 /*-----------------------------------------------------------*/
252 
vPortEndScheduler(void)253 void vPortEndScheduler(void)
254 {
255     /* Not implemented in ports where there is nothing to return to.
256     Artificially force an assert. */
257     configASSERT( uxInterruptNesting == 1000UL );
258 }
259 /*-----------------------------------------------------------*/
260 
xPortStartScheduler(void)261 BaseType_t xPortStartScheduler( void )
262 {
263 extern void vPortStartFirstTask( void );
264 extern void *pxCurrentTCB;
265 
266     #if ( configCHECK_FOR_STACK_OVERFLOW > 2 )
267     {
268         /* Fill the ISR stack to make it easy to asses how much is being used. */
269         memset( ( void * ) xISRStack, portISR_STACK_FILL_BYTE, sizeof( xISRStack ) );
270     }
271     #endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */
272 
273     /* Clear the software interrupt flag. */
274     IFS0CLR = _IFS0_CS0IF_MASK;
275 
276     /* Set software timer priority. */
277     IPC0CLR = _IPC0_CS0IP_MASK;
278     IPC0SET = ( configKERNEL_INTERRUPT_PRIORITY << _IPC0_CS0IP_POSITION );
279 
280     /* Enable software interrupt. */
281     IEC0CLR = _IEC0_CS0IE_MASK;
282     IEC0SET = 1 << _IEC0_CS0IE_POSITION;
283 
284     /* Setup the timer to generate the tick.  Interrupts will have been
285     disabled by the time we get here. */
286     vApplicationSetupTickTimerInterrupt();
287 
288     /* Kick off the highest priority task that has been created so far.
289     Its stack location is loaded into uxSavedTaskStackPointer. */
290     uxSavedTaskStackPointer = *( UBaseType_t * ) pxCurrentTCB;
291     vPortStartFirstTask();
292 
293     /* Should never get here as the tasks will now be executing!  Call the task
294     exit error function to prevent compiler warnings about a static function
295     not being called in the case that the application writer overrides this
296     functionality by defining configTASK_RETURN_ADDRESS. */
297     prvTaskExitError();
298 
299     return pdFALSE;
300 }
301 /*-----------------------------------------------------------*/
302 
vPortIncrementTick(void)303 void vPortIncrementTick( void )
304 {
305 UBaseType_t uxSavedStatus;
306 
307     uxSavedStatus = uxPortSetInterruptMaskFromISR();
308     {
309         if( xTaskIncrementTick() != pdFALSE )
310         {
311             /* Pend a context switch. */
312             _CP0_BIS_CAUSE( portCORE_SW_0 );
313         }
314     }
315     vPortClearInterruptMaskFromISR( uxSavedStatus );
316 
317     /* Look for the ISR stack getting near or past its limit. */
318     portCHECK_ISR_STACK();
319 
320     /* Clear timer interrupt. */
321     configCLEAR_TICK_TIMER_INTERRUPT();
322 }
323 /*-----------------------------------------------------------*/
324 
uxPortSetInterruptMaskFromISR(void)325 UBaseType_t uxPortSetInterruptMaskFromISR( void )
326 {
327 UBaseType_t uxSavedStatusRegister;
328 
329     __builtin_disable_interrupts();
330     uxSavedStatusRegister = _CP0_GET_STATUS() | 0x01;
331     /* This clears the IPL bits, then sets them to
332     configMAX_SYSCALL_INTERRUPT_PRIORITY.  This function should not be called
333     from an interrupt that has a priority above
334     configMAX_SYSCALL_INTERRUPT_PRIORITY so, when used correctly, the action
335     can only result in the IPL being unchanged or raised, and therefore never
336     lowered. */
337     _CP0_SET_STATUS( ( ( uxSavedStatusRegister & ( ~portALL_IPL_BITS ) ) ) | ( configMAX_SYSCALL_INTERRUPT_PRIORITY << portIPL_SHIFT ) );
338 
339     return uxSavedStatusRegister;
340 }
341 /*-----------------------------------------------------------*/
342 
vPortClearInterruptMaskFromISR(UBaseType_t uxSavedStatusRegister)343 void vPortClearInterruptMaskFromISR( UBaseType_t uxSavedStatusRegister )
344 {
345     _CP0_SET_STATUS( uxSavedStatusRegister );
346 }
347 /*-----------------------------------------------------------*/
348 
349 #if ( __mips_hard_float == 1 ) && ( configUSE_TASK_FPU_SUPPORT == 1 )
350 
vPortTaskUsesFPU(void)351     void vPortTaskUsesFPU(void)
352     {
353     extern void vPortInitialiseFPSCR( uint32_t uxFPSCRInit );
354 
355         portENTER_CRITICAL();
356 
357         /* Initialise the floating point status register. */
358         vPortInitialiseFPSCR(portINITIAL_FPSCR);
359 
360         /* A task is registering the fact that it needs a FPU context. Set the
361         FPU flag (saved as part of the task context). */
362         ulTaskHasFPUContext = pdTRUE;
363 
364         portEXIT_CRITICAL();
365     }
366 
367 #endif /* __mips_hard_float == 1 */
368 
369 /*-----------------------------------------------------------*/
370