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 /* Standard includes. */
30 #include <stdlib.h>
31 #include <string.h>
32
33 /* TriCore specific includes. */
34 #include <tc1782.h>
35 #include <machine/intrinsics.h>
36 #include <machine/cint.h>
37 #include <machine/wdtcon.h>
38
39 /* Kernel includes. */
40 #include "FreeRTOS.h"
41 #include "task.h"
42 #include "list.h"
43
44 #if configCHECK_FOR_STACK_OVERFLOW > 0
45 #error "Stack checking cannot be used with this port, as, unlike most ports, the pxTopOfStack member of the TCB is consumed CSA. CSA starvation, loosely equivalent to stack overflow, will result in a trap exception."
46 /* The stack pointer is accessible using portCSA_TO_ADDRESS( portCSA_TO_ADDRESS( pxCurrentTCB->pxTopOfStack )[ 0 ] )[ 2 ]; */
47 #endif /* configCHECK_FOR_STACK_OVERFLOW */
48
49
50 /*-----------------------------------------------------------*/
51
52 /* System register Definitions. */
53 #define portSYSTEM_PROGRAM_STATUS_WORD ( 0x000008FFUL ) /* Supervisor Mode, MPU Register Set 0 and Call Depth Counting disabled. */
54 #define portINITIAL_PRIVILEGED_PROGRAM_STATUS_WORD ( 0x000014FFUL ) /* IO Level 1, MPU Register Set 1 and Call Depth Counting disabled. */
55 #define portINITIAL_UNPRIVILEGED_PROGRAM_STATUS_WORD ( 0x000010FFUL ) /* IO Level 0, MPU Register Set 1 and Call Depth Counting disabled. */
56 #define portINITIAL_PCXI_UPPER_CONTEXT_WORD ( 0x00C00000UL ) /* The lower 20 bits identify the CSA address. */
57 #define portINITIAL_SYSCON ( 0x00000000UL ) /* MPU Disable. */
58
59 /* CSA manipulation macros. */
60 #define portCSA_FCX_MASK ( 0x000FFFFFUL )
61
62 /* OS Interrupt and Trap mechanisms. */
63 #define portRESTORE_PSW_MASK ( ~( 0x000000FFUL ) )
64 #define portSYSCALL_TRAP ( 6 )
65
66 /* Each CSA contains 16 words of data. */
67 #define portNUM_WORDS_IN_CSA ( 16 )
68
69 /* The interrupt enable bit in the PCP_SRC register. */
70 #define portENABLE_CPU_INTERRUPT ( 1U << 12U )
71 /*-----------------------------------------------------------*/
72
73 /*
74 * Perform any hardware configuration necessary to generate the tick interrupt.
75 */
76 static void prvSystemTickHandler( int ) __attribute__((longcall));
77 static void prvSetupTimerInterrupt( void );
78
79 /*
80 * Trap handler for yields.
81 */
82 static void prvTrapYield( int iTrapIdentification );
83
84 /*
85 * Priority 1 interrupt handler for yields pended from an interrupt.
86 */
87 static void prvInterruptYield( int iTrapIdentification );
88
89 /*-----------------------------------------------------------*/
90
91 /* This reference is required by the save/restore context macros. */
92 extern volatile uint32_t *pxCurrentTCB;
93
94 /* Precalculate the compare match value at compile time. */
95 static const uint32_t ulCompareMatchValue = ( configPERIPHERAL_CLOCK_HZ / configTICK_RATE_HZ );
96
97 /*-----------------------------------------------------------*/
98
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)99 StackType_t *pxPortInitialiseStack( StackType_t * pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
100 {
101 uint32_t *pulUpperCSA = NULL;
102 uint32_t *pulLowerCSA = NULL;
103
104 /* 16 Address Registers (4 Address registers are global), 16 Data
105 Registers, and 3 System Registers.
106
107 There are 3 registers that track the CSAs.
108 FCX points to the head of globally free set of CSAs.
109 PCX for the task needs to point to Lower->Upper->NULL arrangement.
110 LCX points to the last free CSA so that corrective action can be taken.
111
112 Need two CSAs to store the context of a task.
113 The upper context contains D8-D15, A10-A15, PSW and PCXI->NULL.
114 The lower context contains D0-D7, A2-A7, A11 and PCXI->UpperContext.
115 The pxCurrentTCB->pxTopOfStack points to the Lower Context RSLCX matching the initial BISR.
116 The Lower Context points to the Upper Context ready for the return from the interrupt handler.
117
118 The Real stack pointer for the task is stored in the A10 which is restored
119 with the upper context. */
120
121 /* Have to disable interrupts here because the CSAs are going to be
122 manipulated. */
123 portENTER_CRITICAL();
124 {
125 /* DSync to ensure that buffering is not a problem. */
126 _dsync();
127
128 /* Consume two free CSAs. */
129 pulLowerCSA = portCSA_TO_ADDRESS( __MFCR( $FCX ) );
130 if( NULL != pulLowerCSA )
131 {
132 /* The Lower Links to the Upper. */
133 pulUpperCSA = portCSA_TO_ADDRESS( pulLowerCSA[ 0 ] );
134 }
135
136 /* Check that we have successfully reserved two CSAs. */
137 if( ( NULL != pulLowerCSA ) && ( NULL != pulUpperCSA ) )
138 {
139 /* Remove the two consumed CSAs from the free CSA list. */
140 _disable();
141 _dsync();
142 _mtcr( $FCX, pulUpperCSA[ 0 ] );
143 _isync();
144 _enable();
145 }
146 else
147 {
148 /* Simply trigger a context list depletion trap. */
149 _svlcx();
150 }
151 }
152 portEXIT_CRITICAL();
153
154 /* Clear the upper CSA. */
155 memset( pulUpperCSA, 0, portNUM_WORDS_IN_CSA * sizeof( uint32_t ) );
156
157 /* Upper Context. */
158 pulUpperCSA[ 2 ] = ( uint32_t )pxTopOfStack; /* A10; Stack Return aka Stack Pointer */
159 pulUpperCSA[ 1 ] = portSYSTEM_PROGRAM_STATUS_WORD; /* PSW */
160
161 /* Clear the lower CSA. */
162 memset( pulLowerCSA, 0, portNUM_WORDS_IN_CSA * sizeof( uint32_t ) );
163
164 /* Lower Context. */
165 pulLowerCSA[ 8 ] = ( uint32_t ) pvParameters; /* A4; Address Type Parameter Register */
166 pulLowerCSA[ 1 ] = ( uint32_t ) pxCode; /* A11; Return Address aka RA */
167
168 /* PCXI pointing to the Upper context. */
169 pulLowerCSA[ 0 ] = ( portINITIAL_PCXI_UPPER_CONTEXT_WORD | ( uint32_t ) portADDRESS_TO_CSA( pulUpperCSA ) );
170
171 /* Save the link to the CSA in the top of stack. */
172 pxTopOfStack = (uint32_t * ) portADDRESS_TO_CSA( pulLowerCSA );
173
174 /* DSync to ensure that buffering is not a problem. */
175 _dsync();
176
177 return pxTopOfStack;
178 }
179 /*-----------------------------------------------------------*/
180
xPortStartScheduler(void)181 int32_t xPortStartScheduler( void )
182 {
183 extern void vTrapInstallHandlers( void );
184 uint32_t ulMFCR = 0UL;
185 uint32_t *pulUpperCSA = NULL;
186 uint32_t *pulLowerCSA = NULL;
187
188 /* Interrupts at or below configMAX_SYSCALL_INTERRUPT_PRIORITY are disable
189 when this function is called. */
190
191 /* Set-up the timer interrupt. */
192 prvSetupTimerInterrupt();
193
194 /* Install the Trap Handlers. */
195 vTrapInstallHandlers();
196
197 /* Install the Syscall Handler for yield calls. */
198 if( 0 == _install_trap_handler( portSYSCALL_TRAP, prvTrapYield ) )
199 {
200 /* Failed to install the yield handler, force an assert. */
201 configASSERT( ( ( volatile void * ) NULL ) );
202 }
203
204 /* Enable then install the priority 1 interrupt for pending context
205 switches from an ISR. See mod_SRC in the TriCore manual. */
206 CPU_SRC0.reg = ( portENABLE_CPU_INTERRUPT ) | ( configKERNEL_YIELD_PRIORITY );
207 if( 0 == _install_int_handler( configKERNEL_YIELD_PRIORITY, prvInterruptYield, 0 ) )
208 {
209 /* Failed to install the yield handler, force an assert. */
210 configASSERT( ( ( volatile void * ) NULL ) );
211 }
212
213 _disable();
214
215 /* Load the initial SYSCON. */
216 _mtcr( $SYSCON, portINITIAL_SYSCON );
217 _isync();
218
219 /* ENDINIT has already been applied in the 'cstart.c' code. */
220
221 /* Clear the PSW.CDC to enable the use of an RFE without it generating an
222 exception because this code is not genuinely in an exception. */
223 ulMFCR = __MFCR( $PSW );
224 ulMFCR &= portRESTORE_PSW_MASK;
225 _dsync();
226 _mtcr( $PSW, ulMFCR );
227 _isync();
228
229 /* Finally, perform the equivalent of a portRESTORE_CONTEXT() */
230 pulLowerCSA = portCSA_TO_ADDRESS( ( *pxCurrentTCB ) );
231 pulUpperCSA = portCSA_TO_ADDRESS( pulLowerCSA[0] );
232 _dsync();
233 _mtcr( $PCXI, *pxCurrentTCB );
234 _isync();
235 _nop();
236 _rslcx();
237 _nop();
238
239 /* Return to the first task selected to execute. */
240 __asm volatile( "rfe" );
241
242 /* Will not get here. */
243 return 0;
244 }
245 /*-----------------------------------------------------------*/
246
prvSetupTimerInterrupt(void)247 static void prvSetupTimerInterrupt( void )
248 {
249 /* Set-up the clock divider. */
250 unlock_wdtcon();
251 {
252 /* Wait until access to Endint protected register is enabled. */
253 while( 0 != ( WDT_CON0.reg & 0x1UL ) );
254
255 /* RMC == 1 so STM Clock == FPI */
256 STM_CLC.reg = ( 1UL << 8 );
257 }
258 lock_wdtcon();
259
260 /* Determine how many bits are used without changing other bits in the CMCON register. */
261 STM_CMCON.reg &= ~( 0x1fUL );
262 STM_CMCON.reg |= ( 0x1fUL - __CLZ( configPERIPHERAL_CLOCK_HZ / configTICK_RATE_HZ ) );
263
264 /* Take into account the current time so a tick doesn't happen immediately. */
265 STM_CMP0.reg = ulCompareMatchValue + STM_TIM0.reg;
266
267 if( 0 != _install_int_handler( configKERNEL_INTERRUPT_PRIORITY, prvSystemTickHandler, 0 ) )
268 {
269 /* Set-up the interrupt. */
270 STM_SRC0.reg = ( configKERNEL_INTERRUPT_PRIORITY | 0x00005000UL );
271
272 /* Enable the Interrupt. */
273 STM_ISRR.reg &= ~( 0x03UL );
274 STM_ISRR.reg |= 0x1UL;
275 STM_ISRR.reg &= ~( 0x07UL );
276 STM_ICR.reg |= 0x1UL;
277 }
278 else
279 {
280 /* Failed to install the Tick Interrupt. */
281 configASSERT( ( ( volatile void * ) NULL ) );
282 }
283 }
284 /*-----------------------------------------------------------*/
285
prvSystemTickHandler(int iArg)286 static void prvSystemTickHandler( int iArg )
287 {
288 uint32_t ulSavedInterruptMask;
289 uint32_t *pxUpperCSA = NULL;
290 uint32_t xUpperCSA = 0UL;
291 extern volatile uint32_t *pxCurrentTCB;
292 int32_t lYieldRequired;
293
294 /* Just to avoid compiler warnings about unused parameters. */
295 ( void ) iArg;
296
297 /* Clear the interrupt source. */
298 STM_ISRR.reg = 1UL;
299
300 /* Reload the Compare Match register for X ticks into the future.
301
302 If critical section or interrupt nesting budgets are exceeded, then
303 it is possible that the calculated next compare match value is in the
304 past. If this occurs (unlikely), it is possible that the resulting
305 time slippage will exceed a single tick period. Any adverse effect of
306 this is time bounded by the fact that only the first n bits of the 56 bit
307 STM timer are being used for a compare match, so another compare match
308 will occur after an overflow in just those n bits (not the entire 56 bits).
309 As an example, if the peripheral clock is 75MHz, and the tick rate is 1KHz,
310 a missed tick could result in the next tick interrupt occurring within a
311 time that is 1.7 times the desired period. The fact that this is greater
312 than a single tick period is an effect of using a timer that cannot be
313 automatically reset, in hardware, by the occurrence of a tick interrupt.
314 Changing the tick source to a timer that has an automatic reset on compare
315 match (such as a GPTA timer) will reduce the maximum possible additional
316 period to exactly 1 times the desired period. */
317 STM_CMP0.reg += ulCompareMatchValue;
318
319 /* Kernel API calls require Critical Sections. */
320 ulSavedInterruptMask = portSET_INTERRUPT_MASK_FROM_ISR();
321 {
322 /* Increment the Tick. */
323 lYieldRequired = xTaskIncrementTick();
324 }
325 portCLEAR_INTERRUPT_MASK_FROM_ISR( ulSavedInterruptMask );
326
327 if( lYieldRequired != pdFALSE )
328 {
329 /* Save the context of a task.
330 The upper context is automatically saved when entering a trap or interrupt.
331 Need to save the lower context as well and copy the PCXI CSA ID into
332 pxCurrentTCB->pxTopOfStack. Only Lower Context CSA IDs may be saved to the
333 TCB of a task.
334
335 Call vTaskSwitchContext to select the next task, note that this changes the
336 value of pxCurrentTCB so that it needs to be reloaded.
337
338 Call vPortSetMPURegisterSetOne to change the MPU mapping for the task
339 that has just been switched in.
340
341 Load the context of the task.
342 Need to restore the lower context by loading the CSA from
343 pxCurrentTCB->pxTopOfStack into PCXI (effectively changing the call stack).
344 In the Interrupt handler post-amble, RSLCX will restore the lower context
345 of the task. RFE will restore the upper context of the task, jump to the
346 return address and restore the previous state of interrupts being
347 enabled/disabled. */
348 _disable();
349 _dsync();
350 xUpperCSA = __MFCR( $PCXI );
351 pxUpperCSA = portCSA_TO_ADDRESS( xUpperCSA );
352 *pxCurrentTCB = pxUpperCSA[ 0 ];
353 vTaskSwitchContext();
354 pxUpperCSA[ 0 ] = *pxCurrentTCB;
355 CPU_SRC0.bits.SETR = 0;
356 _isync();
357 }
358 }
359 /*-----------------------------------------------------------*/
360
361 /*
362 * When a task is deleted, it is yielded permanently until the IDLE task
363 * has an opportunity to reclaim the memory that that task was using.
364 * Typically, the memory used by a task is the TCB and Stack but in the
365 * TriCore this includes the CSAs that were consumed as part of the Call
366 * Stack. These CSAs can only be returned to the Globally Free Pool when
367 * they are not part of the current Call Stack, hence, delaying the
368 * reclamation until the IDLE task is freeing the task's other resources.
369 * This function uses the head of the linked list of CSAs (from when the
370 * task yielded for the last time) and finds the tail (the very bottom of
371 * the call stack) and inserts this list at the head of the Free list,
372 * attaching the existing Free List to the tail of the reclaimed call stack.
373 *
374 * NOTE: the IDLE task needs processing time to complete this function
375 * and in heavily loaded systems, the Free CSAs may be consumed faster
376 * than they can be freed assuming that tasks are being spawned and
377 * deleted frequently.
378 */
vPortReclaimCSA(uint32_t * pxTCB)379 void vPortReclaimCSA( uint32_t *pxTCB )
380 {
381 uint32_t pxHeadCSA, pxTailCSA, pxFreeCSA;
382 uint32_t *pulNextCSA;
383
384 /* A pointer to the first CSA in the list of CSAs consumed by the task is
385 stored in the first element of the tasks TCB structure (where the stack
386 pointer would be on a traditional stack based architecture). */
387 pxHeadCSA = ( *pxTCB ) & portCSA_FCX_MASK;
388
389 /* Mask off everything in the CSA link field other than the address. If
390 the address is NULL, then the CSA is not linking anywhere and there is
391 nothing to do. */
392 pxTailCSA = pxHeadCSA;
393
394 /* Convert the link value to contain just a raw address and store this
395 in a local variable. */
396 pulNextCSA = portCSA_TO_ADDRESS( pxTailCSA );
397
398 /* Iterate over the CSAs that were consumed as part of the task. The
399 first field in the CSA is the pointer to then next CSA. Mask off
400 everything in the pointer to the next CSA, other than the link address.
401 If this is NULL, then the CSA currently being pointed to is the last in
402 the chain. */
403 while( 0UL != ( pulNextCSA[ 0 ] & portCSA_FCX_MASK ) )
404 {
405 /* Clear all bits of the pointer to the next in the chain, other
406 than the address bits themselves. */
407 pulNextCSA[ 0 ] = pulNextCSA[ 0 ] & portCSA_FCX_MASK;
408
409 /* Move the pointer to point to the next CSA in the list. */
410 pxTailCSA = pulNextCSA[ 0 ];
411
412 /* Update the local pointer to the CSA. */
413 pulNextCSA = portCSA_TO_ADDRESS( pxTailCSA );
414 }
415
416 _disable();
417 {
418 /* Look up the current free CSA head. */
419 _dsync();
420 pxFreeCSA = __MFCR( $FCX );
421
422 /* Join the current Free onto the Tail of what is being reclaimed. */
423 portCSA_TO_ADDRESS( pxTailCSA )[ 0 ] = pxFreeCSA;
424
425 /* Move the head of the reclaimed into the Free. */
426 _dsync();
427 _mtcr( $FCX, pxHeadCSA );
428 _isync();
429 }
430 _enable();
431 }
432 /*-----------------------------------------------------------*/
433
vPortEndScheduler(void)434 void vPortEndScheduler( void )
435 {
436 /* Nothing to do. Unlikely to want to end. */
437 }
438 /*-----------------------------------------------------------*/
439
prvTrapYield(int iTrapIdentification)440 static void prvTrapYield( int iTrapIdentification )
441 {
442 uint32_t *pxUpperCSA = NULL;
443 uint32_t xUpperCSA = 0UL;
444 extern volatile uint32_t *pxCurrentTCB;
445
446 switch( iTrapIdentification )
447 {
448 case portSYSCALL_TASK_YIELD:
449 /* Save the context of a task.
450 The upper context is automatically saved when entering a trap or interrupt.
451 Need to save the lower context as well and copy the PCXI CSA ID into
452 pxCurrentTCB->pxTopOfStack. Only Lower Context CSA IDs may be saved to the
453 TCB of a task.
454
455 Call vTaskSwitchContext to select the next task, note that this changes the
456 value of pxCurrentTCB so that it needs to be reloaded.
457
458 Call vPortSetMPURegisterSetOne to change the MPU mapping for the task
459 that has just been switched in.
460
461 Load the context of the task.
462 Need to restore the lower context by loading the CSA from
463 pxCurrentTCB->pxTopOfStack into PCXI (effectively changing the call stack).
464 In the Interrupt handler post-amble, RSLCX will restore the lower context
465 of the task. RFE will restore the upper context of the task, jump to the
466 return address and restore the previous state of interrupts being
467 enabled/disabled. */
468 _disable();
469 _dsync();
470 xUpperCSA = __MFCR( $PCXI );
471 pxUpperCSA = portCSA_TO_ADDRESS( xUpperCSA );
472 *pxCurrentTCB = pxUpperCSA[ 0 ];
473 vTaskSwitchContext();
474 pxUpperCSA[ 0 ] = *pxCurrentTCB;
475 CPU_SRC0.bits.SETR = 0;
476 _isync();
477 break;
478
479 default:
480 /* Unimplemented trap called. */
481 configASSERT( ( ( volatile void * ) NULL ) );
482 break;
483 }
484 }
485 /*-----------------------------------------------------------*/
486
prvInterruptYield(int iId)487 static void prvInterruptYield( int iId )
488 {
489 uint32_t *pxUpperCSA = NULL;
490 uint32_t xUpperCSA = 0UL;
491 extern volatile uint32_t *pxCurrentTCB;
492
493 /* Just to remove compiler warnings. */
494 ( void ) iId;
495
496 /* Save the context of a task.
497 The upper context is automatically saved when entering a trap or interrupt.
498 Need to save the lower context as well and copy the PCXI CSA ID into
499 pxCurrentTCB->pxTopOfStack. Only Lower Context CSA IDs may be saved to the
500 TCB of a task.
501
502 Call vTaskSwitchContext to select the next task, note that this changes the
503 value of pxCurrentTCB so that it needs to be reloaded.
504
505 Call vPortSetMPURegisterSetOne to change the MPU mapping for the task
506 that has just been switched in.
507
508 Load the context of the task.
509 Need to restore the lower context by loading the CSA from
510 pxCurrentTCB->pxTopOfStack into PCXI (effectively changing the call stack).
511 In the Interrupt handler post-amble, RSLCX will restore the lower context
512 of the task. RFE will restore the upper context of the task, jump to the
513 return address and restore the previous state of interrupts being
514 enabled/disabled. */
515 _disable();
516 _dsync();
517 xUpperCSA = __MFCR( $PCXI );
518 pxUpperCSA = portCSA_TO_ADDRESS( xUpperCSA );
519 *pxCurrentTCB = pxUpperCSA[ 0 ];
520 vTaskSwitchContext();
521 pxUpperCSA[ 0 ] = *pxCurrentTCB;
522 CPU_SRC0.bits.SETR = 0;
523 _isync();
524 }
525 /*-----------------------------------------------------------*/
526
uxPortSetInterruptMaskFromISR(void)527 uint32_t uxPortSetInterruptMaskFromISR( void )
528 {
529 uint32_t uxReturn = 0UL;
530
531 _disable();
532 uxReturn = __MFCR( $ICR );
533 _mtcr( $ICR, ( ( uxReturn & ~portCCPN_MASK ) | configMAX_SYSCALL_INTERRUPT_PRIORITY ) );
534 _isync();
535 _enable();
536
537 /* Return just the interrupt mask bits. */
538 return ( uxReturn & portCCPN_MASK );
539 }
540 /*-----------------------------------------------------------*/
541