2 * FreeRTOS Kernel <DEVELOPMENT BRANCH>
3 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * SPDX-License-Identifier: MIT
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:
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
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.
24 * https://www.FreeRTOS.org
25 * https://github.com/FreeRTOS
29 /*-----------------------------------------------------------
30 * Implementation of functions defined in portable.h for the SH2A port.
31 *----------------------------------------------------------*/
33 /* Standard C includes. */
36 /* Scheduler includes. */
40 /* Library includes. */
43 /* Hardware specifics. */
46 /*-----------------------------------------------------------*/
48 /* Tasks should start with interrupts enabled and in Supervisor mode, therefore
49 PSW is set with U and I set, and PM and IPL clear. */
50 #define portINITIAL_PSW ( ( StackType_t ) 0x00030000 )
52 /* The peripheral clock is divided by this value before being supplying the
54 #if ( configUSE_TICKLESS_IDLE == 0 )
55 /* If tickless idle is not used then the divisor can be fixed. */
56 #define portCLOCK_DIVISOR 8UL
57 #elif ( configPERIPHERAL_CLOCK_HZ >= 12000000 )
58 #define portCLOCK_DIVISOR 512UL
59 #elif ( configPERIPHERAL_CLOCK_HZ >= 6000000 )
60 #define portCLOCK_DIVISOR 128UL
61 #elif ( configPERIPHERAL_CLOCK_HZ >= 1000000 )
62 #define portCLOCK_DIVISOR 32UL
64 #define portCLOCK_DIVISOR 8UL
68 /* Keys required to lock and unlock access to certain system registers
70 #define portUNLOCK_KEY 0xA50B
71 #define portLOCK_KEY 0xA500
73 /*-----------------------------------------------------------*/
76 * Function to start the first task executing - written in asm code as direct
77 * access to registers is required.
79 extern void prvStartFirstTask( void );
82 * The tick ISR handler. The peripheral used is configured by the application
83 * via a hook/callback function.
85 __interrupt static void prvTickISR( void );
88 * Sets up the periodic ISR used for the RTOS tick using the CMT.
89 * The application writer can define configSETUP_TICK_INTERRUPT() (in
90 * FreeRTOSConfig.h) such that their own tick interrupt configuration is used
91 * in place of prvSetupTimerInterrupt().
93 static void prvSetupTimerInterrupt( void );
94 #ifndef configSETUP_TICK_INTERRUPT
95 /* The user has not provided their own tick interrupt configuration so use
96 the definition in this file (which uses the interval timer). */
97 #define configSETUP_TICK_INTERRUPT() prvSetupTimerInterrupt()
98 #endif /* configSETUP_TICK_INTERRUPT */
101 * Called after the sleep mode registers have been configured, prvSleep()
102 * executes the pre and post sleep macros, and actually calls the wait
105 #if configUSE_TICKLESS_IDLE == 1
106 static void prvSleep( TickType_t xExpectedIdleTime );
107 #endif /* configUSE_TICKLESS_IDLE */
109 /*-----------------------------------------------------------*/
111 extern void *pxCurrentTCB;
113 /*-----------------------------------------------------------*/
115 /* Calculate how many clock increments make up a single tick period. */
116 static const uint32_t ulMatchValueForOneTick = ( ( configPERIPHERAL_CLOCK_HZ / portCLOCK_DIVISOR ) / configTICK_RATE_HZ );
118 #if configUSE_TICKLESS_IDLE == 1
120 /* Holds the maximum number of ticks that can be suppressed - which is
121 basically how far into the future an interrupt can be generated. Set
122 during initialisation. This is the maximum possible value that the
123 compare match register can hold divided by ulMatchValueForOneTick. */
124 static const TickType_t xMaximumPossibleSuppressedTicks = USHRT_MAX / ( ( configPERIPHERAL_CLOCK_HZ / portCLOCK_DIVISOR ) / configTICK_RATE_HZ );
126 /* Flag set from the tick interrupt to allow the sleep processing to know if
127 sleep mode was exited because of a tick interrupt, or an interrupt
128 generated by something else. */
129 static volatile uint32_t ulTickFlag = pdFALSE;
131 /* The CMT counter is stopped temporarily each time it is re-programmed.
132 The following constant offsets the CMT counter match value by the number of
133 CMT counts that would typically be missed while the counter was stopped to
134 compensate for the lost time. The large difference between the divided CMT
135 clock and the CPU clock means it is likely ulStoppedTimerCompensation will
136 equal zero - and be optimised away. */
137 static const uint32_t ulStoppedTimerCompensation = 100UL / ( configCPU_CLOCK_HZ / ( configPERIPHERAL_CLOCK_HZ / portCLOCK_DIVISOR ) );
141 /*-----------------------------------------------------------*/
144 * See header file for description.
146 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
148 /* Offset to end up on 8 byte boundary. */
151 /* R0 is not included as it is the stack pointer. */
152 *pxTopOfStack = 0x00;
154 *pxTopOfStack = 0x00;
156 *pxTopOfStack = portINITIAL_PSW;
158 *pxTopOfStack = ( StackType_t ) pxCode;
160 /* When debugging it can be useful if every register is set to a known
161 value. Otherwise code space can be saved by just setting the registers
162 that need to be set. */
163 #ifdef USE_FULL_REGISTER_INITIALISATION
166 *pxTopOfStack = 0x12345678; /* r15. */
168 *pxTopOfStack = 0xaaaabbbb;
170 *pxTopOfStack = 0xdddddddd;
172 *pxTopOfStack = 0xcccccccc;
174 *pxTopOfStack = 0xbbbbbbbb;
176 *pxTopOfStack = 0xaaaaaaaa;
178 *pxTopOfStack = 0x99999999;
180 *pxTopOfStack = 0x88888888;
182 *pxTopOfStack = 0x77777777;
184 *pxTopOfStack = 0x66666666;
186 *pxTopOfStack = 0x55555555;
188 *pxTopOfStack = 0x44444444;
190 *pxTopOfStack = 0x33333333;
192 *pxTopOfStack = 0x22222222;
197 /* Leave space for the registers that will get popped from the stack
198 when the task first starts executing. */
203 *pxTopOfStack = ( StackType_t ) pvParameters; /* R1 */
205 *pxTopOfStack = 0x12345678; /* Accumulator. */
207 *pxTopOfStack = 0x87654321; /* Accumulator. */
211 /*-----------------------------------------------------------*/
213 BaseType_t xPortStartScheduler( void )
215 /* Use pxCurrentTCB just so it does not get optimised away. */
216 if( pxCurrentTCB != NULL )
218 /* Call an application function to set up the timer that will generate
219 the tick interrupt. This way the application can decide which
220 peripheral to use. If tickless mode is used then the default
221 implementation defined in this file (which uses CMT0) should not be
223 configSETUP_TICK_INTERRUPT();
225 /* Enable the software interrupt. */
226 _IEN( _ICU_SWINT ) = 1;
228 /* Ensure the software interrupt is clear. */
229 _IR( _ICU_SWINT ) = 0;
231 /* Ensure the software interrupt is set to the kernel priority. */
232 _IPR( _ICU_SWINT ) = configKERNEL_INTERRUPT_PRIORITY;
234 /* Start the first task. */
238 /* Execution should not reach here as the tasks are now running!
239 prvSetupTimerInterrupt() is called here to prevent the compiler outputting
240 a warning about a statically declared function not being referenced in the
241 case that the application writer has provided their own tick interrupt
242 configuration routine (and defined configSETUP_TICK_INTERRUPT() such that
243 their own routine will be called in place of prvSetupTimerInterrupt()). */
244 prvSetupTimerInterrupt();
246 /* Should not get here. */
249 /*-----------------------------------------------------------*/
251 #pragma vector = configTICK_VECTOR
252 __interrupt static void prvTickISR( void )
254 /* Re-enable interrupts. */
255 __enable_interrupt();
257 /* Increment the tick, and perform any processing the new tick value
259 __set_interrupt_level( configMAX_SYSCALL_INTERRUPT_PRIORITY );
261 if( xTaskIncrementTick() != pdFALSE )
266 __set_interrupt_level( configKERNEL_INTERRUPT_PRIORITY );
268 #if configUSE_TICKLESS_IDLE == 1
270 /* The CPU woke because of a tick. */
273 /* If this is the first tick since exiting tickless mode then the CMT
274 compare match value needs resetting. */
275 CMT0.CMCOR = ( uint16_t ) ulMatchValueForOneTick;
279 /*-----------------------------------------------------------*/
281 void vPortEndScheduler( void )
283 /* Not implemented in ports where there is nothing to return to.
284 Artificially force an assert. */
285 configASSERT( pxCurrentTCB == NULL );
287 /*-----------------------------------------------------------*/
289 static void prvSetupTimerInterrupt( void )
292 SYSTEM.PRCR.WORD = portUNLOCK_KEY;
298 SYSTEM.PRCR.WORD = portLOCK_KEY;
300 /* Interrupt on compare match. */
301 CMT0.CMCR.BIT.CMIE = 1;
303 /* Set the compare match value. */
304 CMT0.CMCOR = ( uint16_t ) ulMatchValueForOneTick;
306 /* Divide the PCLK. */
307 #if portCLOCK_DIVISOR == 512
309 CMT0.CMCR.BIT.CKS = 3;
311 #elif portCLOCK_DIVISOR == 128
313 CMT0.CMCR.BIT.CKS = 2;
315 #elif portCLOCK_DIVISOR == 32
317 CMT0.CMCR.BIT.CKS = 1;
319 #elif portCLOCK_DIVISOR == 8
321 CMT0.CMCR.BIT.CKS = 0;
325 #error Invalid portCLOCK_DIVISOR setting
330 /* Enable the interrupt... */
331 _IEN( _CMT0_CMI0 ) = 1;
333 /* ...and set its priority to the application defined kernel priority. */
334 _IPR( _CMT0_CMI0 ) = configKERNEL_INTERRUPT_PRIORITY;
336 /* Start the timer. */
337 CMT.CMSTR0.BIT.STR0 = 1;
339 /*-----------------------------------------------------------*/
341 #if configUSE_TICKLESS_IDLE == 1
343 static void prvSleep( TickType_t xExpectedIdleTime )
345 /* Allow the application to define some pre-sleep processing. */
346 configPRE_SLEEP_PROCESSING( xExpectedIdleTime );
348 /* xExpectedIdleTime being set to 0 by configPRE_SLEEP_PROCESSING()
349 means the application defined code has already executed the WAIT
351 if( xExpectedIdleTime > 0 )
353 __wait_for_interrupt();
356 /* Allow the application to define some post sleep processing. */
357 configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
360 #endif /* configUSE_TICKLESS_IDLE */
361 /*-----------------------------------------------------------*/
363 #if configUSE_TICKLESS_IDLE == 1
365 void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
367 uint32_t ulMatchValue, ulCompleteTickPeriods, ulCurrentCount;
368 eSleepModeStatus eSleepAction;
370 /* THIS FUNCTION IS CALLED WITH THE SCHEDULER SUSPENDED. */
372 /* Make sure the CMT reload value does not overflow the counter. */
373 if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
375 xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
378 /* Calculate the reload value required to wait xExpectedIdleTime tick
380 ulMatchValue = ulMatchValueForOneTick * xExpectedIdleTime;
381 if( ulMatchValue > ulStoppedTimerCompensation )
383 /* Compensate for the fact that the CMT is going to be stopped
385 ulMatchValue -= ulStoppedTimerCompensation;
388 /* Stop the CMT momentarily. The time the CMT is stopped for is
389 accounted for as best it can be, but using the tickless mode will
390 inevitably result in some tiny drift of the time maintained by the
391 kernel with respect to calendar time. */
392 CMT.CMSTR0.BIT.STR0 = 0;
393 while( CMT.CMSTR0.BIT.STR0 == 1 )
395 /* Nothing to do here. */
398 /* Critical section using the global interrupt bit as the i bit is
399 automatically reset by the WAIT instruction. */
400 __disable_interrupt();
402 /* The tick flag is set to false before sleeping. If it is true when
403 sleep mode is exited then sleep mode was probably exited because the
404 tick was suppressed for the entire xExpectedIdleTime period. */
405 ulTickFlag = pdFALSE;
407 /* If a context switch is pending then abandon the low power entry as
408 the context switch might have been pended by an external interrupt that
409 requires processing. */
410 eSleepAction = eTaskConfirmSleepModeStatus();
411 if( eSleepAction == eAbortSleep )
414 CMT.CMSTR0.BIT.STR0 = 1;
415 __enable_interrupt();
417 else if( eSleepAction == eNoTasksWaitingTimeout )
419 /* Protection off. */
420 SYSTEM.PRCR.WORD = portUNLOCK_KEY;
422 /* Ready for software standby with all clocks stopped. */
423 SYSTEM.SBYCR.BIT.SSBY = 1;
426 SYSTEM.PRCR.WORD = portLOCK_KEY;
428 /* Sleep until something happens. Calling prvSleep() will
429 automatically reset the i bit in the PSW. */
430 prvSleep( xExpectedIdleTime );
432 /* Restart the CMT. */
433 CMT.CMSTR0.BIT.STR0 = 1;
437 /* Protection off. */
438 SYSTEM.PRCR.WORD = portUNLOCK_KEY;
440 /* Ready for deep sleep mode. */
441 SYSTEM.MSTPCRC.BIT.DSLPE = 1;
442 SYSTEM.MSTPCRA.BIT.MSTPA28 = 1;
443 SYSTEM.SBYCR.BIT.SSBY = 0;
446 SYSTEM.PRCR.WORD = portLOCK_KEY;
448 /* Adjust the match value to take into account that the current
449 time slice is already partially complete. */
450 ulMatchValue -= ( uint32_t ) CMT0.CMCNT;
451 CMT0.CMCOR = ( uint16_t ) ulMatchValue;
453 /* Restart the CMT to count up to the new match value. */
455 CMT.CMSTR0.BIT.STR0 = 1;
457 /* Sleep until something happens. Calling prvSleep() will
458 automatically reset the i bit in the PSW. */
459 prvSleep( xExpectedIdleTime );
461 /* Stop CMT. Again, the time the SysTick is stopped for is
462 accounted for as best it can be, but using the tickless mode will
463 inevitably result in some tiny drift of the time maintained by the
464 kernel with respect to calendar time. */
465 CMT.CMSTR0.BIT.STR0 = 0;
466 while( CMT.CMSTR0.BIT.STR0 == 1 )
468 /* Nothing to do here. */
471 ulCurrentCount = ( uint32_t ) CMT0.CMCNT;
473 if( ulTickFlag != pdFALSE )
475 /* The tick interrupt has already executed, although because
476 this function is called with the scheduler suspended the actual
477 tick processing will not occur until after this function has
478 exited. Reset the match value with whatever remains of this
480 ulMatchValue = ulMatchValueForOneTick - ulCurrentCount;
481 CMT0.CMCOR = ( uint16_t ) ulMatchValue;
483 /* The tick interrupt handler will already have pended the tick
484 processing in the kernel. As the pending tick will be
485 processed as soon as this function exits, the tick value
486 maintained by the tick is stepped forward by one less than the
487 time spent sleeping. The actual stepping of the tick appears
488 later in this function. */
489 ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
493 /* Something other than the tick interrupt ended the sleep.
494 How many complete tick periods passed while the processor was
496 ulCompleteTickPeriods = ulCurrentCount / ulMatchValueForOneTick;
498 /* The match value is set to whatever fraction of a single tick
500 ulMatchValue = ulCurrentCount - ( ulCompleteTickPeriods * ulMatchValueForOneTick );
501 CMT0.CMCOR = ( uint16_t ) ulMatchValue;
504 /* Restart the CMT so it runs up to the match value. The match value
505 will get set to the value required to generate exactly one tick period
506 the next time the CMT interrupt executes. */
508 CMT.CMSTR0.BIT.STR0 = 1;
510 /* Wind the tick forward by the number of tick periods that the CPU
511 remained in a low power state. */
512 vTaskStepTick( ulCompleteTickPeriods );
516 #endif /* configUSE_TICKLESS_IDLE */