xref: /Kernel-v10.6.2/portable/IAR/AVR32_UC3/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 AND BSD-3-Clause
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 /*This file has been prepared for Doxygen automatic documentation generation.*/
30 /*! \file *********************************************************************
31  *
32  * \brief FreeRTOS port source for AVR32 UC3.
33  *
34  * - Compiler:           IAR EWAVR32
35  * - Supported devices:  All AVR32 devices can be used.
36  * - AppNote:
37  *
38  * \author               Atmel Corporation (Now Microchip):
39  *                                        https://www.microchip.com \n
40  *                       Support and FAQ: https://www.microchip.com/support/
41  *
42  *****************************************************************************/
43 
44 /*
45  * Copyright (c) 2007, Atmel Corporation All rights reserved.
46  *
47  * Redistribution and use in source and binary forms, with or without
48  * modification, are permitted provided that the following conditions are met:
49  *
50  * 1. Redistributions of source code must retain the above copyright notice,
51  * this list of conditions and the following disclaimer.
52  *
53  * 2. Redistributions in binary form must reproduce the above copyright notice,
54  * this list of conditions and the following disclaimer in the documentation
55  * and/or other materials provided with the distribution.
56  *
57  * 3. The name of ATMEL may not be used to endorse or promote products derived
58  * from this software without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY ATMEL ``AS IS'' AND ANY EXPRESS OR IMPLIED
61  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
62  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY AND
63  * SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT,
64  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
65  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
66  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
67  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
68  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
69  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
70  */
71 
72 /* Scheduler includes. */
73 #include "FreeRTOS.h"
74 #include "task.h"
75 
76 /* AVR32 UC3 includes. */
77 #include <avr32/io.h>
78 #include <intrinsics.h>
79 #include "gpio.h"
80 
81 #if configDBG
82     #include "usart.h"
83 #endif
84 
85 #if( configTICK_USE_TC==1 )
86     #include "tc.h"
87 #endif
88 
89 
90 /* Constants required to setup the task context. */
91 #define portINITIAL_SR            ( ( StackType_t ) 0x00400000 ) /* AVR32 : [M2:M0]=001 I1M=0 I0M=0, GM=0 */
92 #define portINSTRUCTION_SIZE      ( ( StackType_t ) 0 )
93 
94 /* Each task maintains its own critical nesting variable. */
95 #define portNO_CRITICAL_NESTING   ( ( uint32_t ) 0 )
96 volatile uint32_t ulCriticalNesting = 9999UL;
97 
98 #if( configTICK_USE_TC==0 )
99     static void prvScheduleNextTick( void );
100 #else
101     static void prvClearTcInt( void );
102 #endif
103 
104 /* Setup the timer to generate the tick interrupts. */
105 static void prvSetupTimerInterrupt( void );
106 
107 /*-----------------------------------------------------------*/
108 
109 /*
110  * Low-level initialization routine called during startup, before the main
111  * function.
112  */
__low_level_init(void)113 int __low_level_init(void)
114 {
115     #if configHEAP_INIT
116         #pragma segment = "HEAP"
117         BaseType_t *pxMem;
118     #endif
119 
120     /* Enable exceptions. */
121     ENABLE_ALL_EXCEPTIONS();
122 
123     /* Initialize interrupt handling. */
124     INTC_init_interrupts();
125 
126     #if configHEAP_INIT
127     {
128         /* Initialize the heap used by malloc. */
129         for( pxMem = __segment_begin( "HEAP" ); pxMem < ( BaseType_t * ) __segment_end( "HEAP" ); )
130         {
131             *pxMem++ = 0xA5A5A5A5;
132         }
133     }
134     #endif
135 
136     /* Code section present if and only if the debug trace is activated. */
137     #if configDBG
138     {
139         static const gpio_map_t DBG_USART_GPIO_MAP =
140         {
141             { configDBG_USART_RX_PIN, configDBG_USART_RX_FUNCTION },
142             { configDBG_USART_TX_PIN, configDBG_USART_TX_FUNCTION }
143         };
144 
145         static const usart_options_t DBG_USART_OPTIONS =
146         {
147             .baudrate = configDBG_USART_BAUDRATE,
148             .charlength = 8,
149             .paritytype = USART_NO_PARITY,
150             .stopbits = USART_1_STOPBIT,
151             .channelmode = USART_NORMAL_CHMODE
152         };
153 
154         /* Initialize the USART used for the debug trace with the configured parameters. */
155         extern volatile avr32_usart_t *volatile stdio_usart_base;
156         stdio_usart_base = configDBG_USART;
157         gpio_enable_module( DBG_USART_GPIO_MAP,
158                             sizeof( DBG_USART_GPIO_MAP ) / sizeof( DBG_USART_GPIO_MAP[0] ) );
159         usart_init_rs232(configDBG_USART, &DBG_USART_OPTIONS, configCPU_CLOCK_HZ);
160     }
161     #endif
162 
163     /* Request initialization of data segments. */
164     return 1;
165 }
166 /*-----------------------------------------------------------*/
167 
168 /* Added as there is no such function in FreeRTOS. */
pvPortRealloc(void * pv,size_t xWantedSize)169 void *pvPortRealloc( void *pv, size_t xWantedSize )
170 {
171 void *pvReturn;
172 
173     vTaskSuspendAll();
174     {
175         pvReturn = realloc( pv, xWantedSize );
176     }
177     xTaskResumeAll();
178 
179     return pvReturn;
180 }
181 /*-----------------------------------------------------------*/
182 
183 /* The cooperative scheduler requires a normal IRQ service routine to
184 simply increment the system tick. */
185 /* The preemptive scheduler is defined as "naked" as the full context is saved
186 on entry as part of the context switch. */
187 #pragma shadow_registers = full   // Naked.
vTick(void)188 static void vTick( void )
189 {
190     /* Save the context of the interrupted task. */
191     portSAVE_CONTEXT_OS_INT();
192 
193     #if( configTICK_USE_TC==1 )
194         /* Clear the interrupt flag. */
195         prvClearTcInt();
196     #else
197         /* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
198         clock cycles from now. */
199         prvScheduleNextTick();
200     #endif
201 
202     /* Because FreeRTOS is not supposed to run with nested interrupts, put all OS
203     calls in a critical section . */
204     portENTER_CRITICAL();
205         xTaskIncrementTick();
206     portEXIT_CRITICAL();
207 
208     /* Restore the context of the "elected task". */
209     portRESTORE_CONTEXT_OS_INT();
210 }
211 /*-----------------------------------------------------------*/
212 
213 #pragma shadow_registers = full   // Naked.
SCALLYield(void)214 void SCALLYield( void )
215 {
216     /* Save the context of the interrupted task. */
217     portSAVE_CONTEXT_SCALL();
218     vTaskSwitchContext();
219     portRESTORE_CONTEXT_SCALL();
220 }
221 /*-----------------------------------------------------------*/
222 
223 /* The code generated by the GCC compiler uses the stack in different ways at
224 different optimisation levels.  The interrupt flags can therefore not always
225 be saved to the stack.  Instead the critical section nesting level is stored
226 in a variable, which is then saved as part of the stack context. */
227 #pragma optimize = no_inline
vPortEnterCritical(void)228 void vPortEnterCritical( void )
229 {
230     /* Disable interrupts */
231     portDISABLE_INTERRUPTS();
232 
233     /* Now interrupts are disabled ulCriticalNesting can be accessed
234      directly.  Increment ulCriticalNesting to keep a count of how many times
235      portENTER_CRITICAL() has been called. */
236     ulCriticalNesting++;
237 }
238 /*-----------------------------------------------------------*/
239 
240 #pragma optimize = no_inline
vPortExitCritical(void)241 void vPortExitCritical( void )
242 {
243     if(ulCriticalNesting > portNO_CRITICAL_NESTING)
244     {
245         ulCriticalNesting--;
246         if( ulCriticalNesting == portNO_CRITICAL_NESTING )
247         {
248             /* Enable all interrupt/exception. */
249             portENABLE_INTERRUPTS();
250         }
251     }
252 }
253 /*-----------------------------------------------------------*/
254 
255 /*
256  * Initialise the stack of a task to look exactly as if a call to
257  * portSAVE_CONTEXT had been called.
258  *
259  * See header file for description.
260  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)261 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
262 {
263     /* Setup the initial stack of the task.  The stack is set exactly as
264     expected by the portRESTORE_CONTEXT() macro. */
265 
266     /* When the task starts, it will expect to find the function parameter in R12. */
267     pxTopOfStack--;
268     *pxTopOfStack-- = ( StackType_t ) 0x08080808;                   /* R8 */
269     *pxTopOfStack-- = ( StackType_t ) 0x09090909;                   /* R9 */
270     *pxTopOfStack-- = ( StackType_t ) 0x0A0A0A0A;                   /* R10 */
271     *pxTopOfStack-- = ( StackType_t ) 0x0B0B0B0B;                   /* R11 */
272     *pxTopOfStack-- = ( StackType_t ) pvParameters;                 /* R12 */
273     *pxTopOfStack-- = ( StackType_t ) 0xDEADBEEF;                   /* R14/LR */
274     *pxTopOfStack-- = ( StackType_t ) pxCode + portINSTRUCTION_SIZE; /* R15/PC */
275     *pxTopOfStack-- = ( StackType_t ) portINITIAL_SR;               /* SR */
276     *pxTopOfStack-- = ( StackType_t ) 0xFF0000FF;                   /* R0 */
277     *pxTopOfStack-- = ( StackType_t ) 0x01010101;                   /* R1 */
278     *pxTopOfStack-- = ( StackType_t ) 0x02020202;                   /* R2 */
279     *pxTopOfStack-- = ( StackType_t ) 0x03030303;                   /* R3 */
280     *pxTopOfStack-- = ( StackType_t ) 0x04040404;                   /* R4 */
281     *pxTopOfStack-- = ( StackType_t ) 0x05050505;                   /* R5 */
282     *pxTopOfStack-- = ( StackType_t ) 0x06060606;                   /* R6 */
283     *pxTopOfStack-- = ( StackType_t ) 0x07070707;                   /* R7 */
284     *pxTopOfStack = ( StackType_t ) portNO_CRITICAL_NESTING;            /* ulCriticalNesting */
285 
286     return pxTopOfStack;
287 }
288 /*-----------------------------------------------------------*/
289 
xPortStartScheduler(void)290 BaseType_t xPortStartScheduler( void )
291 {
292     /* Start the timer that generates the tick ISR.  Interrupts are disabled
293     here already. */
294     prvSetupTimerInterrupt();
295 
296     /* Start the first task. */
297     portRESTORE_CONTEXT();
298 
299     /* Should not get here! */
300     return 0;
301 }
302 /*-----------------------------------------------------------*/
303 
vPortEndScheduler(void)304 void vPortEndScheduler( void )
305 {
306     /* It is unlikely that the AVR32 port will require this function as there
307     is nothing to return to.  */
308 }
309 /*-----------------------------------------------------------*/
310 
311 /* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
312 clock cycles from now. */
313 #if( configTICK_USE_TC==0 )
prvScheduleFirstTick(void)314     static void prvScheduleFirstTick(void)
315     {
316         uint32_t lCycles;
317 
318         lCycles = Get_system_register(AVR32_COUNT);
319         lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
320         // If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
321         // generation feature does not get disabled.
322         if(0 == lCycles)
323         {
324             lCycles++;
325         }
326         Set_system_register(AVR32_COMPARE, lCycles);
327     }
328 
329     #pragma optimize = no_inline
prvScheduleNextTick(void)330     static void prvScheduleNextTick(void)
331     {
332         uint32_t lCycles, lCount;
333 
334         lCycles = Get_system_register(AVR32_COMPARE);
335         lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
336         // If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
337         // generation feature does not get disabled.
338         if(0 == lCycles)
339         {
340             lCycles++;
341         }
342         lCount = Get_system_register(AVR32_COUNT);
343         if( lCycles < lCount )
344         {       // We missed a tick, recover for the next.
345             lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
346         }
347         Set_system_register(AVR32_COMPARE, lCycles);
348     }
349 #else
350     #pragma optimize = no_inline
prvClearTcInt(void)351     static void prvClearTcInt(void)
352     {
353         AVR32_TC.channel[configTICK_TC_CHANNEL].sr;
354     }
355 #endif
356 /*-----------------------------------------------------------*/
357 
358 /* Setup the timer to generate the tick interrupts. */
prvSetupTimerInterrupt(void)359 static void prvSetupTimerInterrupt(void)
360 {
361     #if( configTICK_USE_TC==1 )
362 
363         volatile avr32_tc_t *tc = &AVR32_TC;
364 
365         // Options for waveform genration.
366         tc_waveform_opt_t waveform_opt =
367         {
368         .channel  = configTICK_TC_CHANNEL,             /* Channel selection. */
369 
370         .bswtrg   = TC_EVT_EFFECT_NOOP,                /* Software trigger effect on TIOB. */
371         .beevt    = TC_EVT_EFFECT_NOOP,                /* External event effect on TIOB. */
372         .bcpc     = TC_EVT_EFFECT_NOOP,                /* RC compare effect on TIOB. */
373         .bcpb     = TC_EVT_EFFECT_NOOP,                /* RB compare effect on TIOB. */
374 
375         .aswtrg   = TC_EVT_EFFECT_NOOP,                /* Software trigger effect on TIOA. */
376         .aeevt    = TC_EVT_EFFECT_NOOP,                /* External event effect on TIOA. */
377         .acpc     = TC_EVT_EFFECT_NOOP,                /* RC compare effect on TIOA: toggle. */
378         .acpa     = TC_EVT_EFFECT_NOOP,                /* RA compare effect on TIOA: toggle (other possibilities are none, set and clear). */
379 
380         .wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,/* Waveform selection: Up mode without automatic trigger on RC compare. */
381         .enetrg   = FALSE,                             /* External event trigger enable. */
382         .eevt     = 0,                                 /* External event selection. */
383         .eevtedg  = TC_SEL_NO_EDGE,                    /* External event edge selection. */
384         .cpcdis   = FALSE,                             /* Counter disable when RC compare. */
385         .cpcstop  = FALSE,                             /* Counter clock stopped with RC compare. */
386 
387         .burst    = FALSE,                             /* Burst signal selection. */
388         .clki     = FALSE,                             /* Clock inversion. */
389         .tcclks   = TC_CLOCK_SOURCE_TC2                /* Internal source clock 2. */
390         };
391 
392         tc_interrupt_t tc_interrupt =
393         {
394             .etrgs=0,
395             .ldrbs=0,
396             .ldras=0,
397             .cpcs =1,
398             .cpbs =0,
399             .cpas =0,
400             .lovrs=0,
401             .covfs=0,
402         };
403 
404     #endif
405 
406     /* Disable all interrupt/exception. */
407     portDISABLE_INTERRUPTS();
408 
409     /* Register the compare interrupt handler to the interrupt controller and
410     enable the compare interrupt. */
411 
412     #if( configTICK_USE_TC==1 )
413     {
414         INTC_register_interrupt((__int_handler)&vTick, configTICK_TC_IRQ, INT0);
415 
416         /* Initialize the timer/counter. */
417         tc_init_waveform(tc, &waveform_opt);
418 
419         /* Set the compare triggers.
420         Remember TC counter is 16-bits, so counting second is not possible!
421         That's why we configure it to count ms. */
422         tc_write_rc( tc, configTICK_TC_CHANNEL, ( configPBA_CLOCK_HZ / 4) / configTICK_RATE_HZ );
423 
424         tc_configure_interrupts( tc, configTICK_TC_CHANNEL, &tc_interrupt );
425 
426         /* Start the timer/counter. */
427         tc_start(tc, configTICK_TC_CHANNEL);
428     }
429     #else
430     {
431         INTC_register_interrupt((__int_handler)&vTick, AVR32_CORE_COMPARE_IRQ, INT0);
432         prvScheduleFirstTick();
433     }
434     #endif
435 }
436