]> begriffs open source - freertos/blob - portable/GCC/AVR32_UC3/port.c
Add SMP in the License Header (#402)
[freertos] / portable / GCC / AVR32_UC3 / port.c
1 /*This file has been prepared for Doxygen automatic documentation generation.*/
2 /*! \file *********************************************************************
3  *
4  * \brief FreeRTOS port source for AVR32 UC3.
5  *
6  * - Compiler:           GNU GCC for AVR32
7  * - Supported devices:  All AVR32 devices can be used.
8  * - AppNote:
9  *
10  * \author               Atmel Corporation (Now Microchip):
11  *                                        https://www.microchip.com \n
12  *                       Support and FAQ: https://www.microchip.com/support/
13  *
14  *****************************************************************************/
15
16 /*
17  * FreeRTOS SMP Kernel V202110.00
18  * Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining a copy of
21  * this software and associated documentation files (the "Software"), to deal in
22  * the Software without restriction, including without limitation the rights to
23  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
24  * the Software, and to permit persons to whom the Software is furnished to do so,
25  * subject to the following conditions:
26  *
27  * The above copyright notice and this permission notice shall be included in all
28  * copies or substantial portions of the Software.
29  *
30  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
32  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
33  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
34  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
35  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36  *
37  * https://www.FreeRTOS.org
38  * https://github.com/FreeRTOS
39  *
40  * 1 tab == 4 spaces!
41  */
42
43
44 /* Standard includes. */
45 #include <sys/cpu.h>
46 #include <sys/usart.h>
47 #include <malloc.h>
48
49 /* Scheduler includes. */
50 #include "FreeRTOS.h"
51 #include "task.h"
52
53 /* AVR32 UC3 includes. */
54 #include <avr32/io.h>
55 #include "gpio.h"
56 #if( configTICK_USE_TC==1 )
57         #include "tc.h"
58 #endif
59
60
61 /* Constants required to setup the task context. */
62 #define portINITIAL_SR            ( ( StackType_t ) 0x00400000 ) /* AVR32 : [M2:M0]=001 I1M=0 I0M=0, GM=0 */
63 #define portINSTRUCTION_SIZE      ( ( StackType_t ) 0 )
64
65 /* Each task maintains its own critical nesting variable. */
66 #define portNO_CRITICAL_NESTING   ( ( uint32_t ) 0 )
67 volatile uint32_t ulCriticalNesting = 9999UL;
68
69 #if( configTICK_USE_TC==0 )
70         static void prvScheduleNextTick( void );
71 #else
72         static void prvClearTcInt( void );
73 #endif
74
75 /* Setup the timer to generate the tick interrupts. */
76 static void prvSetupTimerInterrupt( void );
77
78 /*-----------------------------------------------------------*/
79
80 /*
81  * Low-level initialization routine called during startup, before the main
82  * function.
83  * This version comes in replacement to the default one provided by Newlib.
84  * Newlib's _init_startup only calls init_exceptions, but Newlib's exception
85  * vectors are not compatible with the SCALL management in the current FreeRTOS
86  * port. More low-level initializations are besides added here.
87  */
88 void _init_startup(void)
89 {
90         /* Import the Exception Vector Base Address. */
91         extern void _evba;
92
93         #if configHEAP_INIT
94                 extern void __heap_start__;
95                 extern void __heap_end__;
96                 BaseType_t *pxMem;
97         #endif
98
99         /* Load the Exception Vector Base Address in the corresponding system register. */
100         Set_system_register( AVR32_EVBA, ( int ) &_evba );
101
102         /* Enable exceptions. */
103         ENABLE_ALL_EXCEPTIONS();
104
105         /* Initialize interrupt handling. */
106         INTC_init_interrupts();
107
108         #if configHEAP_INIT
109
110                 /* Initialize the heap used by malloc. */
111                 for( pxMem = &__heap_start__; pxMem < ( BaseType_t * )&__heap_end__; )
112                 {
113                         *pxMem++ = 0xA5A5A5A5;
114                 }
115
116         #endif
117
118         /* Give the used CPU clock frequency to Newlib, so it can work properly. */
119         set_cpu_hz( configCPU_CLOCK_HZ );
120
121         /* Code section present if and only if the debug trace is activated. */
122         #if configDBG
123         {
124                 static const gpio_map_t DBG_USART_GPIO_MAP =
125                 {
126                         { configDBG_USART_RX_PIN, configDBG_USART_RX_FUNCTION },
127                         { configDBG_USART_TX_PIN, configDBG_USART_TX_FUNCTION }
128                 };
129
130                 /* Initialize the USART used for the debug trace with the configured parameters. */
131                 set_usart_base( ( void * ) configDBG_USART );
132                 gpio_enable_module( DBG_USART_GPIO_MAP,
133                                     sizeof( DBG_USART_GPIO_MAP ) / sizeof( DBG_USART_GPIO_MAP[0] ) );
134                 usart_init( configDBG_USART_BAUDRATE );
135         }
136         #endif
137 }
138 /*-----------------------------------------------------------*/
139
140 /*
141  * malloc, realloc and free are meant to be called through respectively
142  * pvPortMalloc, pvPortRealloc and vPortFree.
143  * The latter functions call the former ones from within sections where tasks
144  * are suspended, so the latter functions are task-safe. __malloc_lock and
145  * __malloc_unlock use the same mechanism to also keep the former functions
146  * task-safe as they may be called directly from Newlib's functions.
147  * However, all these functions are interrupt-unsafe and SHALL THEREFORE NOT BE
148  * CALLED FROM WITHIN AN INTERRUPT, because __malloc_lock and __malloc_unlock do
149  * not call portENTER_CRITICAL and portEXIT_CRITICAL in order not to disable
150  * interrupts during memory allocation management as this may be a very time-
151  * consuming process.
152  */
153
154 /*
155  * Lock routine called by Newlib on malloc / realloc / free entry to guarantee a
156  * safe section as memory allocation management uses global data.
157  * See the aforementioned details.
158  */
159 void __malloc_lock(struct _reent *ptr)
160 {
161         vTaskSuspendAll();
162 }
163
164 /*
165  * Unlock routine called by Newlib on malloc / realloc / free exit to guarantee
166  * a safe section as memory allocation management uses global data.
167  * See the aforementioned details.
168  */
169 void __malloc_unlock(struct _reent *ptr)
170 {
171         xTaskResumeAll();
172 }
173 /*-----------------------------------------------------------*/
174
175 /* Added as there is no such function in FreeRTOS. */
176 void *pvPortRealloc( void *pv, size_t xWantedSize )
177 {
178 void *pvReturn;
179
180         vTaskSuspendAll();
181         {
182                 pvReturn = realloc( pv, xWantedSize );
183         }
184         xTaskResumeAll();
185
186         return pvReturn;
187 }
188 /*-----------------------------------------------------------*/
189
190 /* The cooperative scheduler requires a normal IRQ service routine to
191 simply increment the system tick. */
192 /* The preemptive scheduler is defined as "naked" as the full context is saved
193 on entry as part of the context switch. */
194 __attribute__((__naked__)) static void vTick( void )
195 {
196         /* Save the context of the interrupted task. */
197         portSAVE_CONTEXT_OS_INT();
198
199         #if( configTICK_USE_TC==1 )
200                 /* Clear the interrupt flag. */
201                 prvClearTcInt();
202         #else
203                 /* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
204                 clock cycles from now. */
205                 prvScheduleNextTick();
206         #endif
207
208         /* Because FreeRTOS is not supposed to run with nested interrupts, put all OS
209         calls in a critical section . */
210         portENTER_CRITICAL();
211                 xTaskIncrementTick();
212         portEXIT_CRITICAL();
213
214         /* Restore the context of the "elected task". */
215         portRESTORE_CONTEXT_OS_INT();
216 }
217 /*-----------------------------------------------------------*/
218
219 __attribute__((__naked__)) void SCALLYield( void )
220 {
221         /* Save the context of the interrupted task. */
222         portSAVE_CONTEXT_SCALL();
223         vTaskSwitchContext();
224         portRESTORE_CONTEXT_SCALL();
225 }
226 /*-----------------------------------------------------------*/
227
228 /* The code generated by the GCC compiler uses the stack in different ways at
229 different optimisation levels.  The interrupt flags can therefore not always
230 be saved to the stack.  Instead the critical section nesting level is stored
231 in a variable, which is then saved as part of the stack context. */
232 __attribute__((__noinline__)) void vPortEnterCritical( void )
233 {
234         /* Disable interrupts */
235         portDISABLE_INTERRUPTS();
236
237         /* Now interrupts are disabled ulCriticalNesting can be accessed
238          directly.  Increment ulCriticalNesting to keep a count of how many times
239          portENTER_CRITICAL() has been called. */
240         ulCriticalNesting++;
241 }
242 /*-----------------------------------------------------------*/
243
244 __attribute__((__noinline__)) void vPortExitCritical( void )
245 {
246         if(ulCriticalNesting > portNO_CRITICAL_NESTING)
247         {
248                 ulCriticalNesting--;
249                 if( ulCriticalNesting == portNO_CRITICAL_NESTING )
250                 {
251                         /* Enable all interrupt/exception. */
252                         portENABLE_INTERRUPTS();
253                 }
254         }
255 }
256 /*-----------------------------------------------------------*/
257
258 /*
259  * Initialise the stack of a task to look exactly as if a call to
260  * portSAVE_CONTEXT had been called.
261  *
262  * See header file for description.
263  */
264 StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
265 {
266         /* Setup the initial stack of the task.  The stack is set exactly as
267         expected by the portRESTORE_CONTEXT() macro. */
268
269         /* When the task starts, it will expect to find the function parameter in R12. */
270         pxTopOfStack--;
271         *pxTopOfStack-- = ( StackType_t ) 0x08080808;                                   /* R8 */
272         *pxTopOfStack-- = ( StackType_t ) 0x09090909;                                   /* R9 */
273         *pxTopOfStack-- = ( StackType_t ) 0x0A0A0A0A;                                   /* R10 */
274         *pxTopOfStack-- = ( StackType_t ) 0x0B0B0B0B;                                   /* R11 */
275         *pxTopOfStack-- = ( StackType_t ) pvParameters;                                 /* R12 */
276         *pxTopOfStack-- = ( StackType_t ) 0xDEADBEEF;                                   /* R14/LR */
277         *pxTopOfStack-- = ( StackType_t ) pxCode + portINSTRUCTION_SIZE; /* R15/PC */
278         *pxTopOfStack-- = ( StackType_t ) portINITIAL_SR;                               /* SR */
279         *pxTopOfStack-- = ( StackType_t ) 0xFF0000FF;                                   /* R0 */
280         *pxTopOfStack-- = ( StackType_t ) 0x01010101;                                   /* R1 */
281         *pxTopOfStack-- = ( StackType_t ) 0x02020202;                                   /* R2 */
282         *pxTopOfStack-- = ( StackType_t ) 0x03030303;                                   /* R3 */
283         *pxTopOfStack-- = ( StackType_t ) 0x04040404;                                   /* R4 */
284         *pxTopOfStack-- = ( StackType_t ) 0x05050505;                                   /* R5 */
285         *pxTopOfStack-- = ( StackType_t ) 0x06060606;                                   /* R6 */
286         *pxTopOfStack-- = ( StackType_t ) 0x07070707;                                   /* R7 */
287         *pxTopOfStack = ( StackType_t ) portNO_CRITICAL_NESTING;                        /* ulCriticalNesting */
288
289         return pxTopOfStack;
290 }
291 /*-----------------------------------------------------------*/
292
293 BaseType_t xPortStartScheduler( void )
294 {
295         /* Start the timer that generates the tick ISR.  Interrupts are disabled
296         here already. */
297         prvSetupTimerInterrupt();
298
299         /* Start the first task. */
300         portRESTORE_CONTEXT();
301
302         /* Should not get here! */
303         return 0;
304 }
305 /*-----------------------------------------------------------*/
306
307 void vPortEndScheduler( void )
308 {
309         /* It is unlikely that the AVR32 port will require this function as there
310         is nothing to return to.  */
311 }
312 /*-----------------------------------------------------------*/
313
314 /* Schedule the COUNT&COMPARE match interrupt in (configCPU_CLOCK_HZ/configTICK_RATE_HZ)
315 clock cycles from now. */
316 #if( configTICK_USE_TC==0 )
317         static void prvScheduleFirstTick(void)
318         {
319                 uint32_t lCycles;
320
321                 lCycles = Get_system_register(AVR32_COUNT);
322                 lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
323                 // If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
324                 // generation feature does not get disabled.
325                 if(0 == lCycles)
326                 {
327                         lCycles++;
328                 }
329                 Set_system_register(AVR32_COMPARE, lCycles);
330         }
331         
332         __attribute__((__noinline__)) static void prvScheduleNextTick(void)
333         {
334                 uint32_t lCycles, lCount;
335
336                 lCycles = Get_system_register(AVR32_COMPARE);
337                 lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
338                 // If lCycles ends up to be 0, make it 1 so that the COMPARE and exception
339                 // generation feature does not get disabled.
340                 if(0 == lCycles)
341                 {
342                         lCycles++;
343                 }
344                 lCount = Get_system_register(AVR32_COUNT);
345                 if( lCycles < lCount )
346                 {               // We missed a tick, recover for the next.
347                         lCycles += (configCPU_CLOCK_HZ/configTICK_RATE_HZ);
348                 }
349                 Set_system_register(AVR32_COMPARE, lCycles);
350         }
351 #else
352         __attribute__((__noinline__)) static void prvClearTcInt(void)
353         {
354                 AVR32_TC.channel[configTICK_TC_CHANNEL].sr;
355         }
356 #endif
357 /*-----------------------------------------------------------*/
358
359 /* Setup the timer to generate the tick interrupts. */
360 static void prvSetupTimerInterrupt(void)
361 {
362 #if( configTICK_USE_TC==1 )
363
364         volatile avr32_tc_t *tc = &AVR32_TC;
365
366         // Options for waveform genration.
367         tc_waveform_opt_t waveform_opt =
368         {
369         .channel  = configTICK_TC_CHANNEL,             /* Channel selection. */
370
371         .bswtrg   = TC_EVT_EFFECT_NOOP,                /* Software trigger effect on TIOB. */
372         .beevt    = TC_EVT_EFFECT_NOOP,                /* External event effect on TIOB. */
373         .bcpc     = TC_EVT_EFFECT_NOOP,                /* RC compare effect on TIOB. */
374         .bcpb     = TC_EVT_EFFECT_NOOP,                /* RB compare effect on TIOB. */
375
376         .aswtrg   = TC_EVT_EFFECT_NOOP,                /* Software trigger effect on TIOA. */
377         .aeevt    = TC_EVT_EFFECT_NOOP,                /* External event effect on TIOA. */
378         .acpc     = TC_EVT_EFFECT_NOOP,                /* RC compare effect on TIOA: toggle. */
379         .acpa     = TC_EVT_EFFECT_NOOP,                /* RA compare effect on TIOA: toggle (other possibilities are none, set and clear). */
380
381         .wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,/* Waveform selection: Up mode without automatic trigger on RC compare. */
382         .enetrg   = FALSE,                             /* External event trigger enable. */
383         .eevt     = 0,                                 /* External event selection. */
384         .eevtedg  = TC_SEL_NO_EDGE,                    /* External event edge selection. */
385         .cpcdis   = FALSE,                             /* Counter disable when RC compare. */
386         .cpcstop  = FALSE,                             /* Counter clock stopped with RC compare. */
387
388         .burst    = FALSE,                             /* Burst signal selection. */
389         .clki     = FALSE,                             /* Clock inversion. */
390         .tcclks   = TC_CLOCK_SOURCE_TC2                /* Internal source clock 2. */
391         };
392
393         tc_interrupt_t tc_interrupt =
394         {
395                 .etrgs=0,
396                 .ldrbs=0,
397                 .ldras=0,
398                 .cpcs =1,
399                 .cpbs =0,
400                 .cpas =0,
401                 .lovrs=0,
402                 .covfs=0,
403         };
404
405 #endif
406
407         /* Disable all interrupt/exception. */
408         portDISABLE_INTERRUPTS();
409
410         /* Register the compare interrupt handler to the interrupt controller and
411         enable the compare interrupt. */
412
413         #if( configTICK_USE_TC==1 )
414         {
415                 INTC_register_interrupt(&vTick, configTICK_TC_IRQ, INT0);
416
417                 /* Initialize the timer/counter. */
418                 tc_init_waveform(tc, &waveform_opt);
419
420                 /* Set the compare triggers.
421                 Remember TC counter is 16-bits, so counting second is not possible!
422                 That's why we configure it to count ms. */
423                 tc_write_rc( tc, configTICK_TC_CHANNEL, ( configPBA_CLOCK_HZ / 4) / configTICK_RATE_HZ );
424
425                 tc_configure_interrupts( tc, configTICK_TC_CHANNEL, &tc_interrupt );
426
427                 /* Start the timer/counter. */
428                 tc_start(tc, configTICK_TC_CHANNEL);
429         }
430         #else
431         {
432                 INTC_register_interrupt(&vTick, AVR32_CORE_COMPARE_IRQ, INT0);
433                 prvScheduleFirstTick();
434         }
435         #endif
436 }