xref: /Kernel-v10.6.2/portable/GCC/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:           GNU GCC for AVR32
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 /* Standard includes. */
73 #include <sys/cpu.h>
74 #include <sys/usart.h>
75 #include <malloc.h>
76 
77 /* Scheduler includes. */
78 #include "FreeRTOS.h"
79 #include "task.h"
80 
81 /* AVR32 UC3 includes. */
82 #include <avr32/io.h>
83 #include "gpio.h"
84 #if( configTICK_USE_TC==1 )
85     #include "tc.h"
86 #endif
87 
88 
89 /* Constants required to setup the task context. */
90 #define portINITIAL_SR            ( ( StackType_t ) 0x00400000 ) /* AVR32 : [M2:M0]=001 I1M=0 I0M=0, GM=0 */
91 #define portINSTRUCTION_SIZE      ( ( StackType_t ) 0 )
92 
93 /* Each task maintains its own critical nesting variable. */
94 #define portNO_CRITICAL_NESTING   ( ( uint32_t ) 0 )
95 volatile uint32_t ulCriticalNesting = 9999UL;
96 
97 #if( configTICK_USE_TC==0 )
98     static void prvScheduleNextTick( void );
99 #else
100     static void prvClearTcInt( void );
101 #endif
102 
103 /* Setup the timer to generate the tick interrupts. */
104 static void prvSetupTimerInterrupt( void );
105 
106 /*-----------------------------------------------------------*/
107 
108 /*
109  * Low-level initialization routine called during startup, before the main
110  * function.
111  * This version comes in replacement to the default one provided by Newlib.
112  * Newlib's _init_startup only calls init_exceptions, but Newlib's exception
113  * vectors are not compatible with the SCALL management in the current FreeRTOS
114  * port. More low-level initializations are besides added here.
115  */
_init_startup(void)116 void _init_startup(void)
117 {
118     /* Import the Exception Vector Base Address. */
119     extern void _evba;
120 
121     #if configHEAP_INIT
122         extern void __heap_start__;
123         extern void __heap_end__;
124         BaseType_t *pxMem;
125     #endif
126 
127     /* Load the Exception Vector Base Address in the corresponding system register. */
128     Set_system_register( AVR32_EVBA, ( int ) &_evba );
129 
130     /* Enable exceptions. */
131     ENABLE_ALL_EXCEPTIONS();
132 
133     /* Initialize interrupt handling. */
134     INTC_init_interrupts();
135 
136     #if configHEAP_INIT
137 
138         /* Initialize the heap used by malloc. */
139         for( pxMem = &__heap_start__; pxMem < ( BaseType_t * )&__heap_end__; )
140         {
141             *pxMem++ = 0xA5A5A5A5;
142         }
143 
144     #endif
145 
146     /* Give the used CPU clock frequency to Newlib, so it can work properly. */
147     set_cpu_hz( configCPU_CLOCK_HZ );
148 
149     /* Code section present if and only if the debug trace is activated. */
150     #if configDBG
151     {
152         static const gpio_map_t DBG_USART_GPIO_MAP =
153         {
154             { configDBG_USART_RX_PIN, configDBG_USART_RX_FUNCTION },
155             { configDBG_USART_TX_PIN, configDBG_USART_TX_FUNCTION }
156         };
157 
158         /* Initialize the USART used for the debug trace with the configured parameters. */
159         set_usart_base( ( void * ) configDBG_USART );
160         gpio_enable_module( DBG_USART_GPIO_MAP,
161                             sizeof( DBG_USART_GPIO_MAP ) / sizeof( DBG_USART_GPIO_MAP[0] ) );
162         usart_init( configDBG_USART_BAUDRATE );
163     }
164     #endif
165 }
166 /*-----------------------------------------------------------*/
167 
168 /*
169  * malloc, realloc and free are meant to be called through respectively
170  * pvPortMalloc, pvPortRealloc and vPortFree.
171  * The latter functions call the former ones from within sections where tasks
172  * are suspended, so the latter functions are task-safe. __malloc_lock and
173  * __malloc_unlock use the same mechanism to also keep the former functions
174  * task-safe as they may be called directly from Newlib's functions.
175  * However, all these functions are interrupt-unsafe and SHALL THEREFORE NOT BE
176  * CALLED FROM WITHIN AN INTERRUPT, because __malloc_lock and __malloc_unlock do
177  * not call portENTER_CRITICAL and portEXIT_CRITICAL in order not to disable
178  * interrupts during memory allocation management as this may be a very time-
179  * consuming process.
180  */
181 
182 /*
183  * Lock routine called by Newlib on malloc / realloc / free entry to guarantee a
184  * safe section as memory allocation management uses global data.
185  * See the aforementioned details.
186  */
__malloc_lock(struct _reent * ptr)187 void __malloc_lock(struct _reent *ptr)
188 {
189     vTaskSuspendAll();
190 }
191 
192 /*
193  * Unlock routine called by Newlib on malloc / realloc / free exit to guarantee
194  * a safe section as memory allocation management uses global data.
195  * See the aforementioned details.
196  */
__malloc_unlock(struct _reent * ptr)197 void __malloc_unlock(struct _reent *ptr)
198 {
199     xTaskResumeAll();
200 }
201 /*-----------------------------------------------------------*/
202 
203 /* Added as there is no such function in FreeRTOS. */
pvPortRealloc(void * pv,size_t xWantedSize)204 void *pvPortRealloc( void *pv, size_t xWantedSize )
205 {
206 void *pvReturn;
207 
208     vTaskSuspendAll();
209     {
210         pvReturn = realloc( pv, xWantedSize );
211     }
212     xTaskResumeAll();
213 
214     return pvReturn;
215 }
216 /*-----------------------------------------------------------*/
217 
218 /* The cooperative scheduler requires a normal IRQ service routine to
219 simply increment the system tick. */
220 /* The preemptive scheduler is defined as "naked" as the full context is saved
221 on entry as part of the context switch. */
vTick(void)222 __attribute__((__naked__)) static void vTick( void )
223 {
224     /* Save the context of the interrupted task. */
225     portSAVE_CONTEXT_OS_INT();
226 
227     #if( configTICK_USE_TC==1 )
228         /* Clear the interrupt flag. */
229         prvClearTcInt();
230     #else
231         /* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
232         clock cycles from now. */
233         prvScheduleNextTick();
234     #endif
235 
236     /* Because FreeRTOS is not supposed to run with nested interrupts, put all OS
237     calls in a critical section . */
238     portENTER_CRITICAL();
239         xTaskIncrementTick();
240     portEXIT_CRITICAL();
241 
242     /* Restore the context of the "elected task". */
243     portRESTORE_CONTEXT_OS_INT();
244 }
245 /*-----------------------------------------------------------*/
246 
SCALLYield(void)247 __attribute__((__naked__)) void SCALLYield( void )
248 {
249     /* Save the context of the interrupted task. */
250     portSAVE_CONTEXT_SCALL();
251     vTaskSwitchContext();
252     portRESTORE_CONTEXT_SCALL();
253 }
254 /*-----------------------------------------------------------*/
255 
256 /* The code generated by the GCC compiler uses the stack in different ways at
257 different optimisation levels.  The interrupt flags can therefore not always
258 be saved to the stack.  Instead the critical section nesting level is stored
259 in a variable, which is then saved as part of the stack context. */
vPortEnterCritical(void)260 __attribute__((__noinline__)) void vPortEnterCritical( void )
261 {
262     /* Disable interrupts */
263     portDISABLE_INTERRUPTS();
264 
265     /* Now interrupts are disabled ulCriticalNesting can be accessed
266      directly.  Increment ulCriticalNesting to keep a count of how many times
267      portENTER_CRITICAL() has been called. */
268     ulCriticalNesting++;
269 }
270 /*-----------------------------------------------------------*/
271 
vPortExitCritical(void)272 __attribute__((__noinline__)) void vPortExitCritical( void )
273 {
274     if(ulCriticalNesting > portNO_CRITICAL_NESTING)
275     {
276         ulCriticalNesting--;
277         if( ulCriticalNesting == portNO_CRITICAL_NESTING )
278         {
279             /* Enable all interrupt/exception. */
280             portENABLE_INTERRUPTS();
281         }
282     }
283 }
284 /*-----------------------------------------------------------*/
285 
286 /*
287  * Initialise the stack of a task to look exactly as if a call to
288  * portSAVE_CONTEXT had been called.
289  *
290  * See header file for description.
291  */
pxPortInitialiseStack(StackType_t * pxTopOfStack,TaskFunction_t pxCode,void * pvParameters)292 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
293 {
294     /* Setup the initial stack of the task.  The stack is set exactly as
295     expected by the portRESTORE_CONTEXT() macro. */
296 
297     /* When the task starts, it will expect to find the function parameter in R12. */
298     pxTopOfStack--;
299     *pxTopOfStack-- = ( StackType_t ) 0x08080808;                   /* R8 */
300     *pxTopOfStack-- = ( StackType_t ) 0x09090909;                   /* R9 */
301     *pxTopOfStack-- = ( StackType_t ) 0x0A0A0A0A;                   /* R10 */
302     *pxTopOfStack-- = ( StackType_t ) 0x0B0B0B0B;                   /* R11 */
303     *pxTopOfStack-- = ( StackType_t ) pvParameters;                 /* R12 */
304     *pxTopOfStack-- = ( StackType_t ) 0xDEADBEEF;                   /* R14/LR */
305     *pxTopOfStack-- = ( StackType_t ) pxCode + portINSTRUCTION_SIZE; /* R15/PC */
306     *pxTopOfStack-- = ( StackType_t ) portINITIAL_SR;               /* SR */
307     *pxTopOfStack-- = ( StackType_t ) 0xFF0000FF;                   /* R0 */
308     *pxTopOfStack-- = ( StackType_t ) 0x01010101;                   /* R1 */
309     *pxTopOfStack-- = ( StackType_t ) 0x02020202;                   /* R2 */
310     *pxTopOfStack-- = ( StackType_t ) 0x03030303;                   /* R3 */
311     *pxTopOfStack-- = ( StackType_t ) 0x04040404;                   /* R4 */
312     *pxTopOfStack-- = ( StackType_t ) 0x05050505;                   /* R5 */
313     *pxTopOfStack-- = ( StackType_t ) 0x06060606;                   /* R6 */
314     *pxTopOfStack-- = ( StackType_t ) 0x07070707;                   /* R7 */
315     *pxTopOfStack = ( StackType_t ) portNO_CRITICAL_NESTING;            /* ulCriticalNesting */
316 
317     return pxTopOfStack;
318 }
319 /*-----------------------------------------------------------*/
320 
xPortStartScheduler(void)321 BaseType_t xPortStartScheduler( void )
322 {
323     /* Start the timer that generates the tick ISR.  Interrupts are disabled
324     here already. */
325     prvSetupTimerInterrupt();
326 
327     /* Start the first task. */
328     portRESTORE_CONTEXT();
329 
330     /* Should not get here! */
331     return 0;
332 }
333 /*-----------------------------------------------------------*/
334 
vPortEndScheduler(void)335 void vPortEndScheduler( void )
336 {
337     /* It is unlikely that the AVR32 port will require this function as there
338     is nothing to return to.  */
339 }
340 /*-----------------------------------------------------------*/
341 
342 /* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
343 clock cycles from now. */
344 #if( configTICK_USE_TC==0 )
prvScheduleFirstTick(void)345     static void prvScheduleFirstTick(void)
346     {
347         uint32_t lCycles;
348 
349         lCycles = Get_system_register(AVR32_COUNT);
350         lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
351         // If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
352         // generation feature does not get disabled.
353         if(0 == lCycles)
354         {
355             lCycles++;
356         }
357         Set_system_register(AVR32_COMPARE, lCycles);
358     }
359 
prvScheduleNextTick(void)360     __attribute__((__noinline__)) static void prvScheduleNextTick(void)
361     {
362         uint32_t lCycles, lCount;
363 
364         lCycles = Get_system_register(AVR32_COMPARE);
365         lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
366         // If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
367         // generation feature does not get disabled.
368         if(0 == lCycles)
369         {
370             lCycles++;
371         }
372         lCount = Get_system_register(AVR32_COUNT);
373         if( lCycles < lCount )
374         {       // We missed a tick, recover for the next.
375             lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
376         }
377         Set_system_register(AVR32_COMPARE, lCycles);
378     }
379 #else
prvClearTcInt(void)380     __attribute__((__noinline__)) static void prvClearTcInt(void)
381     {
382         AVR32_TC.channel[configTICK_TC_CHANNEL].sr;
383     }
384 #endif
385 /*-----------------------------------------------------------*/
386 
387 /* Setup the timer to generate the tick interrupts. */
prvSetupTimerInterrupt(void)388 static void prvSetupTimerInterrupt(void)
389 {
390 #if( configTICK_USE_TC==1 )
391 
392     volatile avr32_tc_t *tc = &AVR32_TC;
393 
394     // Options for waveform genration.
395     tc_waveform_opt_t waveform_opt =
396     {
397     .channel  = configTICK_TC_CHANNEL,             /* Channel selection. */
398 
399     .bswtrg   = TC_EVT_EFFECT_NOOP,                /* Software trigger effect on TIOB. */
400     .beevt    = TC_EVT_EFFECT_NOOP,                /* External event effect on TIOB. */
401     .bcpc     = TC_EVT_EFFECT_NOOP,                /* RC compare effect on TIOB. */
402     .bcpb     = TC_EVT_EFFECT_NOOP,                /* RB compare effect on TIOB. */
403 
404     .aswtrg   = TC_EVT_EFFECT_NOOP,                /* Software trigger effect on TIOA. */
405     .aeevt    = TC_EVT_EFFECT_NOOP,                /* External event effect on TIOA. */
406     .acpc     = TC_EVT_EFFECT_NOOP,                /* RC compare effect on TIOA: toggle. */
407     .acpa     = TC_EVT_EFFECT_NOOP,                /* RA compare effect on TIOA: toggle (other possibilities are none, set and clear). */
408 
409     .wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,/* Waveform selection: Up mode without automatic trigger on RC compare. */
410     .enetrg   = FALSE,                             /* External event trigger enable. */
411     .eevt     = 0,                                 /* External event selection. */
412     .eevtedg  = TC_SEL_NO_EDGE,                    /* External event edge selection. */
413     .cpcdis   = FALSE,                             /* Counter disable when RC compare. */
414     .cpcstop  = FALSE,                             /* Counter clock stopped with RC compare. */
415 
416     .burst    = FALSE,                             /* Burst signal selection. */
417     .clki     = FALSE,                             /* Clock inversion. */
418     .tcclks   = TC_CLOCK_SOURCE_TC2                /* Internal source clock 2. */
419     };
420 
421     tc_interrupt_t tc_interrupt =
422     {
423         .etrgs=0,
424         .ldrbs=0,
425         .ldras=0,
426         .cpcs =1,
427         .cpbs =0,
428         .cpas =0,
429         .lovrs=0,
430         .covfs=0,
431     };
432 
433 #endif
434 
435     /* Disable all interrupt/exception. */
436     portDISABLE_INTERRUPTS();
437 
438     /* Register the compare interrupt handler to the interrupt controller and
439     enable the compare interrupt. */
440 
441     #if( configTICK_USE_TC==1 )
442     {
443         INTC_register_interrupt(&vTick, configTICK_TC_IRQ, INT0);
444 
445         /* Initialize the timer/counter. */
446         tc_init_waveform(tc, &waveform_opt);
447 
448         /* Set the compare triggers.
449         Remember TC counter is 16-bits, so counting second is not possible!
450         That's why we configure it to count ms. */
451         tc_write_rc( tc, configTICK_TC_CHANNEL, ( configPBA_CLOCK_HZ / 4) / configTICK_RATE_HZ );
452 
453         tc_configure_interrupts( tc, configTICK_TC_CHANNEL, &tc_interrupt );
454 
455         /* Start the timer/counter. */
456         tc_start(tc, configTICK_TC_CHANNEL);
457     }
458     #else
459     {
460         INTC_register_interrupt(&vTick, AVR32_CORE_COMPARE_IRQ, INT0);
461         prvScheduleFirstTick();
462     }
463     #endif
464 }
465