]> begriffs open source - cmsis-freertos/blob - Demo/RX600_RX62N-RSK_IAR/webserver/EMAC.c
Initial commit
[cmsis-freertos] / Demo / RX600_RX62N-RSK_IAR / webserver / EMAC.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
9     FreeRTOS is free software; you can redistribute it and/or modify it under
10     the terms of the GNU General Public License (version 2) as published by the
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
12
13     ***************************************************************************
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<
16     >>!   obliged to provide the source code for proprietary components     !<<
17     >>!   outside of the FreeRTOS kernel.                                   !<<
18     ***************************************************************************
19
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following
23     link: http://www.freertos.org/a00114.html
24
25     ***************************************************************************
26      *                                                                       *
27      *    FreeRTOS provides completely free yet professionally developed,    *
28      *    robust, strictly quality controlled, supported, and cross          *
29      *    platform software that is more than just the market leader, it     *
30      *    is the industry's de facto standard.                               *
31      *                                                                       *
32      *    Help yourself get started quickly while simultaneously helping     *
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *
34      *    tutorial book, reference manual, or both:                          *
35      *    http://www.FreeRTOS.org/Documentation                              *
36      *                                                                       *
37     ***************************************************************************
38
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
40     the FAQ page "My application does not run, what could be wrong?".  Have you
41     defined configASSERT()?
42
43     http://www.FreeRTOS.org/support - In return for receiving this top quality
44     embedded software for free we request you assist our global community by
45     participating in the support forum.
46
47     http://www.FreeRTOS.org/training - Investing in training allows your team to
48     be as productive as possible as early as possible.  Now you can receive
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50     Ltd, and the world's leading authority on the world's leading RTOS.
51
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.
55
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
58
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
61     licenses offer ticketed support, indemnification and commercial middleware.
62
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64     engineered and independently SIL3 certified version for use in safety and
65     mission critical applications that require provable dependability.
66
67     1 tab == 4 spaces!
68 */
69
70 /* Hardware specific includes. */
71 #include <iorx62n.h>
72 #include "typedefine.h"
73 #include "r_ether.h"
74 #include "phy.h"
75
76 /* FreeRTOS includes. */
77 #include "FreeRTOS.h"
78 #include "task.h"
79 #include "semphr.h"
80
81 /* uIP includes. */
82 #include "net/uip.h"
83
84 /* The time to wait between attempts to obtain a free buffer. */
85 #define emacBUFFER_WAIT_DELAY_ms                ( 3 / portTICK_PERIOD_MS )
86
87 /* The number of times emacBUFFER_WAIT_DELAY_ms should be waited before giving
88 up on attempting to obtain a free buffer all together. */
89 #define emacBUFFER_WAIT_ATTEMPTS        ( 30 )
90
91 /* The number of Rx descriptors. */
92 #define emacNUM_RX_DESCRIPTORS  8
93
94 /* The number of Tx descriptors.  When using uIP there is not point in having
95 more than two. */
96 #define emacNUM_TX_BUFFERS      2
97
98 /* The total number of EMAC buffers to allocate. */
99 #define emacNUM_BUFFERS         ( emacNUM_RX_DESCRIPTORS + emacNUM_TX_BUFFERS )
100
101 /* The time to wait for the Tx descriptor to become free. */
102 #define emacTX_WAIT_DELAY_ms ( 10 / portTICK_PERIOD_MS )
103
104 /* The total number of times to wait emacTX_WAIT_DELAY_ms for the Tx descriptor to
105 become free. */
106 #define emacTX_WAIT_ATTEMPTS ( 50 )
107
108 /* Only Rx end and Tx end interrupts are used by this driver. */
109 #define emacTX_END_INTERRUPT    ( 1UL << 21UL )
110 #define emacRX_END_INTERRUPT    ( 1UL << 18UL )
111
112 /*-----------------------------------------------------------*/
113
114 /* The buffers and descriptors themselves.  */
115 #pragma data_alignment=32
116 volatile ethfifo xRxDescriptors[ emacNUM_RX_DESCRIPTORS ];
117
118 #pragma data_alignment=32
119 volatile ethfifo xTxDescriptors[ emacNUM_TX_BUFFERS ];
120
121 #pragma data_alignment=32
122 char xEthernetBuffers[ emacNUM_BUFFERS ][ UIP_BUFSIZE ];
123
124
125 /* Used to indicate which buffers are free and which are in use.  If an index
126 contains 0 then the corresponding buffer in xEthernetBuffers is free, otherwise
127 the buffer is in use or about to be used. */
128 static unsigned char ucBufferInUse[ emacNUM_BUFFERS ];
129
130 /*-----------------------------------------------------------*/
131
132 /*
133  * Initialise both the Rx and Tx descriptors.
134  */
135 static void prvInitialiseDescriptors( void );
136
137 /*
138  * Return a pointer to a free buffer within xEthernetBuffers.
139  */
140 static unsigned char *prvGetNextBuffer( void );
141
142 /*
143  * Return a buffer to the list of free buffers.
144  */
145 static void prvReturnBuffer( unsigned char *pucBuffer );
146
147 /*
148  * Examine the status of the next Rx FIFO to see if it contains new data.
149  */
150 static unsigned long prvCheckRxFifoStatus( void );
151
152 /*
153  * Setup the microcontroller for communication with the PHY.
154  */
155 static void prvResetMAC( void );
156
157 /*
158  * Configure the Ethernet interface peripherals.
159  */
160 static void prvConfigureEtherCAndEDMAC( void );
161
162 /*
163  * Something has gone wrong with the descriptor usage.  Reset all the buffers
164  * and descriptors.
165  */
166 static void prvResetEverything( void );
167
168 /*-----------------------------------------------------------*/
169
170 /* Points to the Rx descriptor currently in use. */
171 static volatile ethfifo *pxCurrentRxDesc = NULL;
172
173 /* The buffer used by the uIP stack to both receive and send.  This points to
174 one of the Ethernet buffers when its actually in use. */
175 unsigned char *uip_buf = NULL;
176
177 /*-----------------------------------------------------------*/
178
179 void vInitEmac( void )
180 {
181         /* Software reset. */
182         prvResetMAC();
183         
184         /* Set the Rx and Tx descriptors into their initial state. */
185         prvInitialiseDescriptors();
186
187         /* Set the MAC address into the ETHERC */
188         ETHERC.MAHR =   ( ( unsigned long ) configMAC_ADDR0 << 24UL ) |
189                                         ( ( unsigned long ) configMAC_ADDR1 << 16UL ) |
190                                         ( ( unsigned long ) configMAC_ADDR2 << 8UL ) |
191                                         ( unsigned long ) configMAC_ADDR3;
192                                         
193         ETHERC.MALR.BIT.MA = ( ( unsigned long ) configMAC_ADDR4 << 8UL ) |
194                                                  ( unsigned long ) configMAC_ADDR5;
195
196         /* Perform rest of interface hardware configuration. */
197         prvConfigureEtherCAndEDMAC();
198         
199         /* Nothing received yet, so uip_buf points nowhere. */
200         uip_buf = NULL;
201
202         /* Initialize the PHY */
203         phy_init();
204 }
205 /*-----------------------------------------------------------*/
206
207 void vEMACWrite( void )
208 {
209 long x;
210
211         /* Wait until the second transmission of the last packet has completed. */
212         for( x = 0; x < emacTX_WAIT_ATTEMPTS; x++ )
213         {
214                 if( ( xTxDescriptors[ 1 ].status & ACT ) != 0 )
215                 {
216                         /* Descriptor is still active. */
217                         vTaskDelay( emacTX_WAIT_DELAY_ms );
218                 }
219                 else
220                 {
221                         break;
222                 }
223         }
224         
225         /* Is the descriptor free after waiting for it? */
226         if( ( xTxDescriptors[ 1 ].status & ACT ) != 0 )
227         {
228                 /* Something has gone wrong. */
229                 prvResetEverything();
230         }
231         
232         /* Setup both descriptors to transmit the frame. */
233         xTxDescriptors[ 0 ].buf_p = ( char * ) uip_buf;
234         xTxDescriptors[ 0 ].bufsize = uip_len;  
235         xTxDescriptors[ 1 ].buf_p = ( char * ) uip_buf;
236         xTxDescriptors[ 1 ].bufsize = uip_len;
237
238         /* uip_buf is being sent by the Tx descriptor.  Allocate a new buffer
239         for use by the stack. */
240         uip_buf = prvGetNextBuffer();
241
242         /* Clear previous settings and go. */
243         xTxDescriptors[0].status &= ~( FP1 | FP0 );
244         xTxDescriptors[0].status |= ( FP1 | FP0 | ACT );
245         xTxDescriptors[1].status &= ~( FP1 | FP0 );
246         xTxDescriptors[1].status |= ( FP1 | FP0 | ACT );
247
248         EDMAC.EDTRR.LONG = 0x00000001;
249 }
250 /*-----------------------------------------------------------*/
251
252 unsigned long ulEMACRead( void )
253 {
254 unsigned long ulBytesReceived;
255
256         ulBytesReceived = prvCheckRxFifoStatus();
257
258         if( ulBytesReceived > 0 )
259         {
260                 /* Mark the pxDescriptor buffer as free as uip_buf is going to be set to
261                 the buffer that contains the received data. */
262                 prvReturnBuffer( uip_buf );
263
264                 /* Point uip_buf to the data about ot be processed. */
265                 uip_buf = ( void * ) pxCurrentRxDesc->buf_p;
266                 
267                 /* Allocate a new buffer to the descriptor, as uip_buf is now using it's
268                 old descriptor. */
269                 pxCurrentRxDesc->buf_p = ( char * ) prvGetNextBuffer();
270
271                 /* Prepare the descriptor to go again. */
272                 pxCurrentRxDesc->status &= ~( FP1 | FP0 );
273                 pxCurrentRxDesc->status |= ACT;
274
275                 /* Move onto the next buffer in the ring. */
276                 pxCurrentRxDesc = pxCurrentRxDesc->next;
277                 
278                 if( EDMAC.EDRRR.LONG == 0x00000000L )
279                 {
280                         /* Restart Ethernet if it has stopped */
281                         EDMAC.EDRRR.LONG = 0x00000001L;
282                 }
283         }
284
285         return ulBytesReceived;
286 }
287 /*-----------------------------------------------------------*/
288
289 long lEMACWaitForLink( void )
290 {
291 long lReturn;
292
293         /* Set the link status. */
294         switch( phy_set_autonegotiate() )
295         {
296                 /* Half duplex link */
297                 case PHY_LINK_100H:
298                                                                 ETHERC.ECMR.BIT.DM = 0;
299                                                                 ETHERC.ECMR.BIT.RTM = 1;
300                                                                 lReturn = pdPASS;
301                                                                 break;
302
303                 case PHY_LINK_10H:
304                                                                 ETHERC.ECMR.BIT.DM = 0;
305                                                                 ETHERC.ECMR.BIT.RTM = 0;
306                                                                 lReturn = pdPASS;
307                                                                 break;
308
309
310                 /* Full duplex link */
311                 case PHY_LINK_100F:
312                                                                 ETHERC.ECMR.BIT.DM = 1;
313                                                                 ETHERC.ECMR.BIT.RTM = 1;
314                                                                 lReturn = pdPASS;
315                                                                 break;
316                 
317                 case PHY_LINK_10F:
318                                                                 ETHERC.ECMR.BIT.DM = 1;
319                                                                 ETHERC.ECMR.BIT.RTM = 0;
320                                                                 lReturn = pdPASS;
321                                                                 break;
322
323                 default:
324                                                                 lReturn = pdFAIL;
325                                                                 break;
326         }
327
328         if( lReturn == pdPASS )
329         {
330                 /* Enable receive and transmit. */
331                 ETHERC.ECMR.BIT.RE = 1;
332                 ETHERC.ECMR.BIT.TE = 1;
333
334                 /* Enable EDMAC receive */
335                 EDMAC.EDRRR.LONG = 0x1;
336         }
337         
338         return lReturn;
339 }
340 /*-----------------------------------------------------------*/
341
342 static void prvInitialiseDescriptors( void )
343 {
344 volatile ethfifo *pxDescriptor;
345 long x;
346
347         for( x = 0; x < emacNUM_BUFFERS; x++ )
348         {
349                 /* Ensure none of the buffers are shown as in use at the start. */
350                 ucBufferInUse[ x ] = pdFALSE;
351         }
352
353         /* Initialise the Rx descriptors. */
354         for( x = 0; x < emacNUM_RX_DESCRIPTORS; x++ )
355         {
356                 pxDescriptor = &( xRxDescriptors[ x ] );
357                 pxDescriptor->buf_p = &( xEthernetBuffers[ x ][ 0 ] );
358
359                 pxDescriptor->bufsize = UIP_BUFSIZE;
360                 pxDescriptor->size = 0;
361                 pxDescriptor->status = ACT;
362                 pxDescriptor->next = ( ethfifo * ) &xRxDescriptors[ x + 1 ];    
363                 
364                 /* Mark this buffer as in use. */
365                 ucBufferInUse[ x ] = pdTRUE;
366         }
367
368         /* The last descriptor points back to the start. */
369         pxDescriptor->status |= DL;
370         pxDescriptor->next = ( ethfifo * ) &xRxDescriptors[ 0 ];
371         
372         /* Initialise the Tx descriptors. */
373         for( x = 0; x < emacNUM_TX_BUFFERS; x++ )
374         {
375                 pxDescriptor = &( xTxDescriptors[ x ] );
376                 
377                 /* A buffer is not allocated to the Tx descriptor until a send is
378                 actually required. */
379                 pxDescriptor->buf_p = NULL;
380
381                 pxDescriptor->bufsize = UIP_BUFSIZE;
382                 pxDescriptor->size = 0;
383                 pxDescriptor->status = 0;
384                 pxDescriptor->next = ( ethfifo * ) &xTxDescriptors[ x + 1 ];    
385         }
386
387         /* The last descriptor points back to the start. */
388         pxDescriptor->status |= DL;
389         pxDescriptor->next = ( ethfifo * ) &( xTxDescriptors[ 0 ] );
390         
391         /* Use the first Rx descriptor to start with. */
392         pxCurrentRxDesc = &( xRxDescriptors[ 0 ] );
393 }
394 /*-----------------------------------------------------------*/
395
396 static unsigned char *prvGetNextBuffer( void )
397 {
398 long x;
399 unsigned char *pucReturn = NULL;
400 unsigned long ulAttempts = 0;
401
402         while( pucReturn == NULL )
403         {
404                 /* Look through the buffers to find one that is not in use by
405                 anything else. */
406                 for( x = 0; x < emacNUM_BUFFERS; x++ )
407                 {
408                         if( ucBufferInUse[ x ] == pdFALSE )
409                         {
410                                 ucBufferInUse[ x ] = pdTRUE;
411                                 pucReturn = ( unsigned char * ) &( xEthernetBuffers[ x ][ 0 ] );
412                                 break;
413                         }
414                 }
415
416                 /* Was a buffer found? */
417                 if( pucReturn == NULL )
418                 {
419                         ulAttempts++;
420
421                         if( ulAttempts >= emacBUFFER_WAIT_ATTEMPTS )
422                         {
423                                 break;
424                         }
425
426                         /* Wait then look again. */
427                         vTaskDelay( emacBUFFER_WAIT_DELAY_ms );
428                 }
429         }
430
431         return pucReturn;
432 }
433 /*-----------------------------------------------------------*/
434
435 static void prvReturnBuffer( unsigned char *pucBuffer )
436 {
437 unsigned long ul;
438
439         /* Return a buffer to the pool of free buffers. */
440         for( ul = 0; ul < emacNUM_BUFFERS; ul++ )
441         {
442                 if( &( xEthernetBuffers[ ul ][ 0 ] ) == ( void * ) pucBuffer )
443                 {
444                         ucBufferInUse[ ul ] = pdFALSE;
445                         break;
446                 }
447         }
448 }
449 /*-----------------------------------------------------------*/
450
451 static void prvResetEverything( void )
452 {
453         /* Temporary code just to see if this gets called.  This function has not
454         been implemented. */
455         portDISABLE_INTERRUPTS();
456         for( ;; );
457 }
458 /*-----------------------------------------------------------*/
459
460 static unsigned long prvCheckRxFifoStatus( void )
461 {
462 unsigned long ulReturn = 0;
463
464         if( ( pxCurrentRxDesc->status & ACT ) != 0 )
465         {
466                 /* Current descriptor is still active. */
467         }
468         else if( ( pxCurrentRxDesc->status & FE ) != 0 )
469         {
470                 /* Frame error.  Clear the error. */
471                 pxCurrentRxDesc->status &= ~( FP1 | FP0 | FE );
472                 pxCurrentRxDesc->status &= ~( RMAF | RRF | RTLF | RTSF | PRE | CERF );
473                 pxCurrentRxDesc->status |= ACT;
474                 pxCurrentRxDesc = pxCurrentRxDesc->next;
475
476                 if( EDMAC.EDRRR.LONG == 0x00000000UL )
477                 {
478                         /* Restart Ethernet if it has stopped. */
479                         EDMAC.EDRRR.LONG = 0x00000001UL;
480                 }       
481         }
482         else
483         {
484                 /* The descriptor contains a frame.  Because of the size of the buffers
485                 the frame should always be complete. */
486                 if( ( pxCurrentRxDesc->status & FP0 ) == FP0 )
487                 {
488                         ulReturn = pxCurrentRxDesc->size;
489                 }
490                 else
491                 {
492                         /* Do not expect to get here. */
493                         prvResetEverything();
494                 }
495         }
496         
497         return ulReturn;
498 }
499 /*-----------------------------------------------------------*/
500
501 static void prvResetMAC( void )
502 {
503         /* Ensure the EtherC and EDMAC are enabled. */
504         SYSTEM.MSTPCRB.BIT.MSTPB15 = 0;
505         vTaskDelay( 100 / portTICK_PERIOD_MS );
506         
507         EDMAC.EDMR.BIT.SWR = 1; 
508         
509         /* Crude wait for reset to complete. */
510         vTaskDelay( 500 / portTICK_PERIOD_MS ); 
511 }
512 /*-----------------------------------------------------------*/
513
514 static void prvConfigureEtherCAndEDMAC( void )
515 {
516         /* Initialisation code taken from Renesas example project. */
517         
518         /* TODO:    Check   bit 5   */
519         ETHERC.ECSR.LONG = 0x00000037;                          /* Clear all ETHERC statuS BFR, PSRTO, LCHNG, MPD, ICD */
520
521         /* Set the EDMAC interrupt priority. */
522         _IPR( _ETHER_EINT ) = configKERNEL_INTERRUPT_PRIORITY;
523
524         /* TODO:    Check   bit 5   */
525         /* Enable interrupts of interest only. */
526         EDMAC.EESIPR.LONG = emacTX_END_INTERRUPT | emacRX_END_INTERRUPT;
527         ETHERC.RFLR.LONG = 1518;                                        /* Ether payload is 1500+ CRC */
528         ETHERC.IPGR.LONG = 0x00000014;                          /* Intergap is 96-bit time */
529
530         /* EDMAC */
531         EDMAC.EESR.LONG = 0x47FF0F9F;                           /* Clear all ETHERC and EDMAC status bits */
532         #if __LITTLE_ENDIAN__ == 1
533                 EDMAC.EDMR.BIT.DE = 1;
534         #endif
535         EDMAC.RDLAR = ( void * ) pxCurrentRxDesc;       /* Initialaize Rx Descriptor List Address */
536         EDMAC.TDLAR = ( void * ) &( xTxDescriptors[ 0 ] );/* Initialaize Tx Descriptor List Address */
537         EDMAC.TRSCER.LONG = 0x00000000;                         /* Copy-back status is RFE & TFE only   */
538         EDMAC.TFTR.LONG = 0x00000000;                           /* Threshold of Tx_FIFO */
539         EDMAC.FDR.LONG = 0x00000000;                            /* Transmit fifo & receive fifo is 256 bytes */
540         EDMAC.RMCR.LONG = 0x00000003;                           /* Receive function is normal mode(continued) */
541         ETHERC.ECMR.BIT.PRM = 0;                                        /* Ensure promiscuous mode is off. */
542         
543         /* Enable the interrupt... */
544         _IEN( _ETHER_EINT ) = 1;        
545 }
546 /*-----------------------------------------------------------*/
547
548 #pragma vector = VECT_ETHER_EINT
549 __interrupt void vEMAC_ISR_Handler( void )
550 {
551 unsigned long ul = EDMAC.EESR.LONG;
552 long lHigherPriorityTaskWoken = pdFALSE;
553 extern QueueHandle_t xEMACEventQueue;
554 const unsigned long ulRxEvent = uipETHERNET_RX_EVENT;
555
556         __enable_interrupt();
557
558         /* Has a Tx end occurred? */
559         if( ul & emacTX_END_INTERRUPT )
560         {
561                 /* Only return the buffer to the pool once both Txes have completed. */
562                 prvReturnBuffer( ( void * ) xTxDescriptors[ 0 ].buf_p );
563                 EDMAC.EESR.LONG = emacTX_END_INTERRUPT;
564         }
565
566         /* Has an Rx end occurred? */
567         if( ul & emacRX_END_INTERRUPT )
568         {
569                 /* Make sure the Ethernet task is not blocked waiting for a packet. */
570                 xQueueSendFromISR( xEMACEventQueue, &ulRxEvent, &lHigherPriorityTaskWoken );
571                 portYIELD_FROM_ISR( lHigherPriorityTaskWoken );
572                 EDMAC.EESR.LONG = emacRX_END_INTERRUPT;
573         }
574 }
575