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