1 /*
2  * FreeRTOS Kernel <DEVELOPMENT BRANCH>
3  * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4  *
5  * SPDX-License-Identifier: MIT
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11  * the Software, and to permit persons to whom the Software is furnished to do so,
12  * subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in all
15  * copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * https://www.FreeRTOS.org
25  * https://github.com/FreeRTOS
26  *
27  */
28 
29 /*-----------------------------------------------------------
30  * Implementation of functions defined in portable.h for the 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 kernel 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     /* PR1 is 16-bit. Ensure that the configPERIPHERAL_CLOCK_HZ and
238      * configTICK_RATE_HZ are defined such that ulCompareMatch value would fit
239      * in 16-bits. */
240     configASSERT( ( ulCompareMatch & 0xFFFF0000 ) == 0 );
241 
242     T1CON = 0x0000;
243     T1CONbits.TCKPS = portPRESCALE_BITS;
244     PR1 = ulCompareMatch;
245     IPC1bits.T1IP = configKERNEL_INTERRUPT_PRIORITY;
246 
247     /* Clear the interrupt as a starting condition. */
248     IFS0bits.T1IF = 0;
249 
250     /* Enable the interrupt. */
251     IEC0bits.T1IE = 1;
252 
253     /* Start the timer. */
254     T1CONbits.TON = 1;
255 }
256 /*-----------------------------------------------------------*/
257 
vPortEndScheduler(void)258 void vPortEndScheduler(void)
259 {
260     /* Not implemented in ports where there is nothing to return to.
261     Artificially force an assert. */
262     configASSERT( uxInterruptNesting == 1000UL );
263 }
264 /*-----------------------------------------------------------*/
265 
xPortStartScheduler(void)266 BaseType_t xPortStartScheduler( void )
267 {
268 extern void vPortStartFirstTask( void );
269 extern void *pxCurrentTCB;
270 
271     #if ( configCHECK_FOR_STACK_OVERFLOW > 2 )
272     {
273         /* Fill the ISR stack to make it easy to asses how much is being used. */
274         memset( ( void * ) xISRStack, portISR_STACK_FILL_BYTE, sizeof( xISRStack ) );
275     }
276     #endif /* configCHECK_FOR_STACK_OVERFLOW > 2 */
277 
278     /* Clear the software interrupt flag. */
279     IFS0CLR = _IFS0_CS0IF_MASK;
280 
281     /* Set software timer priority. */
282     IPC0CLR = _IPC0_CS0IP_MASK;
283     IPC0SET = ( configKERNEL_INTERRUPT_PRIORITY << _IPC0_CS0IP_POSITION );
284 
285     /* Enable software interrupt. */
286     IEC0CLR = _IEC0_CS0IE_MASK;
287     IEC0SET = 1 << _IEC0_CS0IE_POSITION;
288 
289     /* Setup the timer to generate the tick.  Interrupts will have been
290     disabled by the time we get here. */
291     vApplicationSetupTickTimerInterrupt();
292 
293     /* Kick off the highest priority task that has been created so far.
294     Its stack location is loaded into uxSavedTaskStackPointer. */
295     uxSavedTaskStackPointer = *( UBaseType_t * ) pxCurrentTCB;
296     vPortStartFirstTask();
297 
298     /* Should never get here as the tasks will now be executing!  Call the task
299     exit error function to prevent compiler warnings about a static function
300     not being called in the case that the application writer overrides this
301     functionality by defining configTASK_RETURN_ADDRESS. */
302     prvTaskExitError();
303 
304     return pdFALSE;
305 }
306 /*-----------------------------------------------------------*/
307 
vPortIncrementTick(void)308 void vPortIncrementTick( void )
309 {
310 UBaseType_t uxSavedStatus;
311 
312     uxSavedStatus = uxPortSetInterruptMaskFromISR();
313     {
314         if( xTaskIncrementTick() != pdFALSE )
315         {
316             /* Pend a context switch. */
317             _CP0_BIS_CAUSE( portCORE_SW_0 );
318         }
319     }
320     vPortClearInterruptMaskFromISR( uxSavedStatus );
321 
322     /* Look for the ISR stack getting near or past its limit. */
323     portCHECK_ISR_STACK();
324 
325     /* Clear timer interrupt. */
326     configCLEAR_TICK_TIMER_INTERRUPT();
327 }
328 /*-----------------------------------------------------------*/
329 
uxPortSetInterruptMaskFromISR(void)330 UBaseType_t uxPortSetInterruptMaskFromISR( void )
331 {
332 UBaseType_t uxSavedStatusRegister;
333 
334     __builtin_disable_interrupts();
335     uxSavedStatusRegister = _CP0_GET_STATUS() | 0x01;
336     /* This clears the IPL bits, then sets them to
337     configMAX_SYSCALL_INTERRUPT_PRIORITY.  This function should not be called
338     from an interrupt that has a priority above
339     configMAX_SYSCALL_INTERRUPT_PRIORITY so, when used correctly, the action
340     can only result in the IPL being unchanged or raised, and therefore never
341     lowered. */
342     _CP0_SET_STATUS( ( ( uxSavedStatusRegister & ( ~portALL_IPL_BITS ) ) ) | ( configMAX_SYSCALL_INTERRUPT_PRIORITY << portIPL_SHIFT ) );
343 
344     return uxSavedStatusRegister;
345 }
346 /*-----------------------------------------------------------*/
347 
vPortClearInterruptMaskFromISR(UBaseType_t uxSavedStatusRegister)348 void vPortClearInterruptMaskFromISR( UBaseType_t uxSavedStatusRegister )
349 {
350     _CP0_SET_STATUS( uxSavedStatusRegister );
351 }
352 /*-----------------------------------------------------------*/
353 
354 #if ( __mips_hard_float == 1 ) && ( configUSE_TASK_FPU_SUPPORT == 1 )
355 
vPortTaskUsesFPU(void)356     void vPortTaskUsesFPU(void)
357     {
358     extern void vPortInitialiseFPSCR( uint32_t uxFPSCRInit );
359 
360         portENTER_CRITICAL();
361 
362         /* Initialise the floating point status register. */
363         vPortInitialiseFPSCR(portINITIAL_FPSCR);
364 
365         /* A task is registering the fact that it needs a FPU context. Set the
366         FPU flag (saved as part of the task context). */
367         ulTaskHasFPUContext = pdTRUE;
368 
369         portEXIT_CRITICAL();
370     }
371 
372 #endif /* __mips_hard_float == 1 */
373 
374 /*-----------------------------------------------------------*/
375