]> begriffs open source - cmsis-freertos/blob - Demo/lwIP_Demo_Rowley_ARM7/EMAC/SAM7_EMAC.c
This is a FreeRTOS header, not RTX.
[cmsis-freertos] / Demo / lwIP_Demo_Rowley_ARM7 / EMAC / SAM7_EMAC.c
1 /*
2  * FreeRTOS Kernel V10.0.1
3  * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9  * the Software, and to permit persons to whom the Software is furnished to do so,
10  * subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * http://www.FreeRTOS.org
23  * http://aws.amazon.com/freertos
24  *
25  * 1 tab == 4 spaces!
26  */
27
28 /*
29  * Interrupt driven driver for the EMAC peripheral.  This driver is not
30  * reentrant, re-entrancy is handled by a semaphore at the network interface
31  * level. 
32  */
33
34
35 /*
36 Changes from V3.2.2
37
38         + Corrected the byte order when writing the MAC address to the MAC.
39         + Support added for MII interfaces.  Previously only RMII was supported.
40
41 Changes from V3.2.3
42
43         + The MII interface is now the default.
44         + Modified the initialisation sequence slightly to allow auto init more
45           time to complete.
46
47 Changes from V4.0.1
48
49         + Made the function vClearEMACTxBuffer() more robust by moving the index
50           manipulation into the if() statement.  This allows the tx interrupt to
51           execute even when there is no data to handle.
52
53 Changes from V4.0.4
54
55         + Corrected the Rx frame length mask when obtaining the length from the
56           rx descriptor.
57 */
58
59
60 /* Standard includes. */
61 #include <string.h>
62
63 /* Scheduler includes. */
64 #include "FreeRTOS.h"
65 #include "semphr.h"
66 #include "task.h"
67
68 /* Demo app includes. */
69 #include "SAM7_EMAC.h"
70
71 /* Hardware specific includes. */
72 #include "Emac.h"
73 #include "mii.h"
74 #include "AT91SAM7X256.h"
75
76
77 /* USE_RMII_INTERFACE must be defined as 1 to use an RMII interface, or 0
78 to use an MII interface. */
79 #define USE_RMII_INTERFACE 0
80
81
82 /* The buffer addresses written into the descriptors must be aligned so the
83 last few bits are zero.  These bits have special meaning for the EMAC
84 peripheral and cannot be used as part of the address. */
85 #define emacADDRESS_MASK                        ( ( unsigned long ) 0xFFFFFFFC )
86
87 /* Bit used within the address stored in the descriptor to mark the last
88 descriptor in the array. */
89 #define emacRX_WRAP_BIT                         ( ( unsigned long ) 0x02 )
90
91 /* Bit used within the Tx descriptor status to indicate whether the
92 descriptor is under the control of the EMAC or the software. */
93 #define emacTX_BUF_USED                         ( ( unsigned long ) 0x80000000 )
94
95 /* A short delay is used to wait for a buffer to become available, should
96 one not be immediately available when trying to transmit a frame. */
97 #define emacBUFFER_WAIT_DELAY           ( 2 )
98 #define emacMAX_WAIT_CYCLES                     ( ( portBASE_TYPE ) ( configTICK_RATE_HZ / 40 ) )
99
100 /* The time to block waiting for input. */
101 #define emacBLOCK_TIME_WAITING_FOR_INPUT        ( ( TickType_t ) 100 )
102
103 /* Peripheral setup for the EMAC. */
104 #define emacPERIPHERAL_A_SETUP          ( ( unsigned long ) AT91C_PB2_ETX0                      ) | \
105                                                                         ( ( unsigned long ) AT91C_PB12_ETXER            ) | \
106                                                                         ( ( unsigned long ) AT91C_PB16_ECOL                     ) | \
107                                                                         ( ( unsigned long ) AT91C_PB11_ETX3                     ) | \
108                                                                         ( ( unsigned long ) AT91C_PB6_ERX1                      ) | \
109                                                                         ( ( unsigned long ) AT91C_PB15_ERXDV            ) | \
110                                                                         ( ( unsigned long ) AT91C_PB13_ERX2                     ) | \
111                                                                         ( ( unsigned long ) AT91C_PB3_ETX1                      ) | \
112                                                                         ( ( unsigned long ) AT91C_PB8_EMDC                      ) | \
113                                                                         ( ( unsigned long ) AT91C_PB5_ERX0                      ) | \
114                                                                         ( ( unsigned long ) AT91C_PB14_ERX3                     ) | \
115                                                                         ( ( unsigned long ) AT91C_PB4_ECRS_ECRSDV       ) | \
116                                                                         ( ( unsigned long ) AT91C_PB1_ETXEN                     ) | \
117                                                                         ( ( unsigned long ) AT91C_PB10_ETX2                     ) | \
118                                                                         ( ( unsigned long ) AT91C_PB0_ETXCK_EREFCK      ) | \
119                                                                         ( ( unsigned long ) AT91C_PB9_EMDIO                     ) | \
120                                                                         ( ( unsigned long ) AT91C_PB7_ERXER                     ) | \
121                                                                         ( ( unsigned long ) AT91C_PB17_ERXCK            );
122
123 /* Misc defines. */
124 #define emacINTERRUPT_LEVEL                     ( 5 )
125 #define emacNO_DELAY                            ( 0 )
126 #define emacTOTAL_FRAME_HEADER_SIZE     ( 54 )
127 #define emacPHY_INIT_DELAY                      ( 5000 / portTICK_PERIOD_MS )
128 #define emacRESET_KEY                           ( ( unsigned long ) 0xA5000000 )
129 #define emacRESET_LENGTH                        ( ( unsigned long ) ( 0x01 << 8 ) )
130
131 /* The Atmel header file only defines the TX frame length mask. */
132 #define emacRX_LENGTH_FRAME                     ( 0xfff )
133
134 /*-----------------------------------------------------------*/
135
136 /* Buffer written to by the EMAC DMA.  Must be aligned as described by the
137 comment above the emacADDRESS_MASK definition. */
138 static volatile char pcRxBuffer[ NB_RX_BUFFERS * ETH_RX_BUFFER_SIZE ] __attribute__ ((aligned (8)));
139
140 /* Buffer read by the EMAC DMA.  Must be aligned as described by the comment
141 above the emacADDRESS_MASK definition. */
142 static char pcTxBuffer[ NB_TX_BUFFERS * ETH_TX_BUFFER_SIZE ] __attribute__ ((aligned (8)));
143
144 /* Descriptors used to communicate between the program and the EMAC peripheral.
145 These descriptors hold the locations and state of the Rx and Tx buffers. */
146 static volatile AT91S_TxTdDescriptor xTxDescriptors[ NB_TX_BUFFERS ];
147 static volatile AT91S_RxTdDescriptor xRxDescriptors[ NB_RX_BUFFERS ];
148
149 /* The IP and Ethernet addresses are read from the header files. */
150 const char cMACAddress[ 6 ] = { emacETHADDR0, emacETHADDR1, emacETHADDR2, emacETHADDR3, emacETHADDR4, emacETHADDR5 };
151 const unsigned char ucIPAddress[ 4 ]  = { emacIPADDR0, emacIPADDR1, emacIPADDR2, emacIPADDR3 };
152
153 /*-----------------------------------------------------------*/
154
155 /* See the header file for descriptions of public functions. */
156
157 /*
158  * Prototype for the EMAC interrupt function.
159  */
160 void vEMACISR_Wrapper( void ) __attribute__ ((naked));
161
162 /*
163  * Initialise both the Tx and Rx descriptors used by the EMAC.
164  */
165 static void prvSetupDescriptors(void);
166
167 /*
168  * Write our MAC address into the EMAC.  
169  */
170 static void prvSetupMACAddress( void );
171
172 /*
173  * Configure the EMAC and AIC for EMAC interrupts.
174  */
175 static void prvSetupEMACInterrupt( void );
176
177 /*
178  * Some initialisation functions taken from the Atmel EMAC sample code.
179  */
180 static void vReadPHY( unsigned char ucPHYAddress, unsigned char ucAddress, unsigned long *pulValue );
181 static portBASE_TYPE xGetLinkSpeed( void );
182 static portBASE_TYPE prvProbePHY( void );
183 #if USE_RMII_INTERFACE != 1
184         static void vWritePHY( unsigned char ucPHYAddress, unsigned char ucAddress, unsigned long ulValue);
185 #endif
186
187
188 /* The semaphore used by the EMAC ISR to wake the EMAC task. */
189 static SemaphoreHandle_t xSemaphore = NULL;
190
191 /* Holds the index to the next buffer from which data will be read. */
192 static volatile unsigned long ulNextRxBuffer = 0;
193
194 /*-----------------------------------------------------------*/
195
196 /* See the header file for descriptions of public functions. */
197 long lEMACSend( char *pcFrom, unsigned long ulLength, long lEndOfFrame )
198 {
199 static unsigned portBASE_TYPE uxTxBufferIndex = 0;
200 portBASE_TYPE xWaitCycles = 0;
201 long lReturn = pdPASS;
202 char *pcBuffer;
203 unsigned long ulLastBuffer, ulDataBuffered = 0, ulDataRemainingToSend, ulLengthToSend;
204
205         /* If the length of data to be transmitted is greater than each individual
206         transmit buffer then the data will be split into more than one buffer.
207         Loop until the entire length has been buffered. */
208         while( ulDataBuffered < ulLength )
209         {
210                 /* Is a buffer available? */
211                 while( !( xTxDescriptors[ uxTxBufferIndex ].U_Status.status & AT91C_TRANSMIT_OK ) )
212                 {
213                         /* There is no room to write the Tx data to the Tx buffer.  Wait a
214                         short while, then try again. */
215                         xWaitCycles++;
216                         if( xWaitCycles > emacMAX_WAIT_CYCLES )
217                         {
218                                 /* Give up. */
219                                 lReturn = pdFAIL;
220                                 break;
221                         }
222                         else
223                         {
224                                 vTaskDelay( emacBUFFER_WAIT_DELAY );
225                         }
226                 }
227         
228                 /* lReturn will only be pdPASS if a buffer is available. */
229                 if( lReturn == pdPASS )
230                 {
231                         portENTER_CRITICAL();
232                         {
233                                 /* Get the address of the buffer from the descriptor, then copy 
234                                 the data into the buffer. */
235                                 pcBuffer = ( char * ) xTxDescriptors[ uxTxBufferIndex ].addr;
236
237                                 /* How much can we write to the buffer? */
238                                 ulDataRemainingToSend = ulLength - ulDataBuffered;
239                                 if( ulDataRemainingToSend <= ETH_TX_BUFFER_SIZE )
240                                 {
241                                         /* We can write all the remaining bytes. */
242                                         ulLengthToSend = ulDataRemainingToSend;
243                                 }
244                                 else
245                                 {
246                                         /* We can not write more than ETH_TX_BUFFER_SIZE in one go. */
247                                         ulLengthToSend = ETH_TX_BUFFER_SIZE;
248                                 }
249
250                                 /* Copy the data into the buffer. */
251                                 memcpy( ( void * ) pcBuffer, ( void * ) &( pcFrom[ ulDataBuffered ] ), ulLengthToSend );
252                                 ulDataBuffered += ulLengthToSend;
253
254                                 /* Is this the last data for the frame? */
255                                 if( lEndOfFrame && ( ulDataBuffered >= ulLength ) )
256                                 {
257                                         /* No more data remains for this frame so we can start the 
258                                         transmission. */
259                                         ulLastBuffer = AT91C_LAST_BUFFER;
260                                 }
261                                 else
262                                 {
263                                         /* More data to come for this frame. */
264                                         ulLastBuffer = 0;
265                                 }
266         
267                                 /* Fill out the necessary in the descriptor to get the data sent, 
268                                 then move to the next descriptor, wrapping if necessary. */
269                                 if( uxTxBufferIndex >= ( NB_TX_BUFFERS - 1 ) )
270                                 {                               
271                                         xTxDescriptors[ uxTxBufferIndex ].U_Status.status =     ( ulLengthToSend & ( unsigned long ) AT91C_LENGTH_FRAME )
272                                                                                                                                                         | ulLastBuffer
273                                                                                                                                                         | AT91C_TRANSMIT_WRAP;
274                                         uxTxBufferIndex = 0;
275                                 }
276                                 else
277                                 {
278                                         xTxDescriptors[ uxTxBufferIndex ].U_Status.status =     ( ulLengthToSend & ( unsigned long ) AT91C_LENGTH_FRAME )
279                                                                                                                                                         | ulLastBuffer;
280                                         uxTxBufferIndex++;
281                                 }
282         
283                                 /* If this is the last buffer to be sent for this frame we can
284                                 start the transmission. */
285                                 if( ulLastBuffer )
286                                 {
287                                         AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_TSTART;
288                                 }
289                         }
290                         portEXIT_CRITICAL();
291                 }
292                 else
293                 {
294                         break;
295                 }
296         }
297
298         return lReturn;
299 }
300 /*-----------------------------------------------------------*/
301
302 /* See the header file for descriptions of public functions. */
303 unsigned long ulEMACInputLength( void )
304 {
305 register unsigned long ulIndex, ulLength = 0;
306
307         /* Skip any fragments.  We are looking for the first buffer that contains
308         data and has the SOF (start of frame) bit set. */
309         while( ( xRxDescriptors[ ulNextRxBuffer ].addr & AT91C_OWNERSHIP_BIT ) && !( xRxDescriptors[ ulNextRxBuffer ].U_Status.status & AT91C_SOF ) )
310         {
311                 /* Ignoring this buffer.  Mark it as free again. */
312                 xRxDescriptors[ ulNextRxBuffer ].addr &= ~( AT91C_OWNERSHIP_BIT );              
313                 ulNextRxBuffer++;
314                 if( ulNextRxBuffer >= NB_RX_BUFFERS )
315                 {
316                         ulNextRxBuffer = 0;
317                 }
318         }
319
320         /* We are going to walk through the descriptors that make up this frame, 
321         but don't want to alter ulNextRxBuffer as this would prevent vEMACRead()
322         from finding the data.  Therefore use a copy of ulNextRxBuffer instead. */
323         ulIndex = ulNextRxBuffer;
324
325         /* Walk through the descriptors until we find the last buffer for this 
326         frame.  The last buffer will give us the length of the entire frame. */
327         while( ( xRxDescriptors[ ulIndex ].addr & AT91C_OWNERSHIP_BIT ) && !ulLength )
328         {
329                 ulLength = xRxDescriptors[ ulIndex ].U_Status.status & emacRX_LENGTH_FRAME;
330
331                 /* Increment to the next buffer, wrapping if necessary. */
332                 ulIndex++;
333                 if( ulIndex >= NB_RX_BUFFERS )
334                 {
335                         ulIndex = 0;
336                 }
337         }
338
339         return ulLength;
340 }
341 /*-----------------------------------------------------------*/
342
343 /* See the header file for descriptions of public functions. */
344 void vEMACRead( char *pcTo, unsigned long ulSectionLength, unsigned long ulTotalFrameLength )
345 {
346 static unsigned long ulSectionBytesReadSoFar = 0, ulBufferPosition = 0, ulFameBytesReadSoFar = 0;
347 static char *pcSource;
348 register unsigned long ulBytesRemainingInBuffer, ulRemainingSectionBytes;
349
350         /* Read ulSectionLength bytes from the Rx buffers.  This is not necessarily any
351         correspondence between the length of our Rx buffers, and the length of the
352         data we are returning or the length of the data being requested.  Therefore, 
353         between calls  we have to remember not only which buffer we are currently 
354         processing, but our position within that buffer.  This would be greatly
355         simplified if PBUF_POOL_BUFSIZE could be guaranteed to be greater than
356         the size of each Rx buffer, and that memory fragmentation did not occur.
357         
358         This function should only be called after a call to ulEMACInputLength().
359         This will ensure ulNextRxBuffer is set to the correct buffer. */
360
361
362
363         /* vEMACRead is called with pcTo set to NULL to indicate that we are about
364         to read a new frame.  Any fragments remaining in the frame we were 
365         processing during the last call should be dropped. */
366         if( pcTo == NULL )
367         {
368                 /* How many bytes are indicated as being in this buffer?  If none then
369                 the buffer is completely full and the frame is contained within more
370                 than one buffer. */
371
372                 /* Reset our state variables ready for the next read from this buffer. */
373         pcSource = ( char * )( xRxDescriptors[ ulNextRxBuffer ].addr & emacADDRESS_MASK );
374         ulFameBytesReadSoFar = ( unsigned long ) 0;
375                 ulBufferPosition = ( unsigned long ) 0;
376         }
377         else
378         {
379                 /* Loop until we have obtained the required amount of data. */
380         ulSectionBytesReadSoFar = 0;
381                 while( ulSectionBytesReadSoFar < ulSectionLength )
382                 {
383                         /* We may have already read some data from this buffer.  How much
384                         data remains in the buffer? */
385                         ulBytesRemainingInBuffer = ( ETH_RX_BUFFER_SIZE - ulBufferPosition );
386
387                         /* How many more bytes do we need to read before we have the 
388                         required amount of data? */
389             ulRemainingSectionBytes = ulSectionLength - ulSectionBytesReadSoFar;
390
391                         /* Do we want more data than remains in the buffer? */
392                         if( ulRemainingSectionBytes > ulBytesRemainingInBuffer )
393                         {
394                                 /* We want more data than remains in the buffer so we can 
395                                 write the remains of the buffer to the destination, then move
396                                 onto the next buffer to get the rest. */
397                                 memcpy( &( pcTo[ ulSectionBytesReadSoFar ] ), &( pcSource[ ulBufferPosition ] ), ulBytesRemainingInBuffer );
398                                 ulSectionBytesReadSoFar += ulBytesRemainingInBuffer;
399                 ulFameBytesReadSoFar += ulBytesRemainingInBuffer;
400
401                                 /* Mark the buffer as free again. */
402                                 xRxDescriptors[ ulNextRxBuffer ].addr &= ~( AT91C_OWNERSHIP_BIT );
403
404                                 /* Move onto the next buffer. */
405                                 ulNextRxBuffer++;
406                                 if( ulNextRxBuffer >= NB_RX_BUFFERS )
407                                 {
408                                         ulNextRxBuffer = ( unsigned long ) 0;
409                                 }
410
411                                 /* Reset the variables for the new buffer. */
412                                 pcSource = ( char * )( xRxDescriptors[ ulNextRxBuffer ].addr & emacADDRESS_MASK );
413                                 ulBufferPosition = ( unsigned long ) 0;
414                         }
415                         else
416                         {
417                                 /* We have enough data in this buffer to send back.  Read out
418                                 enough data and remember how far we read up to. */
419                                 memcpy( &( pcTo[ ulSectionBytesReadSoFar ] ), &( pcSource[ ulBufferPosition ] ), ulRemainingSectionBytes );
420
421                                 /* There may be more data in this buffer yet.  Increment our 
422                                 position in this buffer past the data we have just read. */
423                                 ulBufferPosition += ulRemainingSectionBytes;
424                                 ulSectionBytesReadSoFar += ulRemainingSectionBytes;
425                 ulFameBytesReadSoFar += ulRemainingSectionBytes;
426
427                                 /* Have we now finished with this buffer? */
428                                 if( ( ulBufferPosition >= ETH_RX_BUFFER_SIZE ) || ( ulFameBytesReadSoFar >= ulTotalFrameLength ) )
429                                 {
430                                         /* Mark the buffer as free again. */
431                                         xRxDescriptors[ ulNextRxBuffer ].addr &= ~( AT91C_OWNERSHIP_BIT );
432
433                                         /* Move onto the next buffer. */
434                                         ulNextRxBuffer++;
435                                         if( ulNextRxBuffer >= NB_RX_BUFFERS )
436                                         {
437                                                 ulNextRxBuffer = 0;
438                                         }
439         
440                                         pcSource = ( char * )( xRxDescriptors[ ulNextRxBuffer ].addr & emacADDRESS_MASK );
441                                         ulBufferPosition = 0;
442                                 }
443                         }
444                 }
445         }
446 }
447 /*-----------------------------------------------------------*/
448
449 /* See the header file for descriptions of public functions. */
450 SemaphoreHandle_t xEMACInit( void )
451 {
452         /* Code supplied by Atmel -------------------------------*/
453
454         /* Disable pull up on RXDV => PHY normal mode (not in test mode),
455         PHY has internal pull down. */
456         AT91C_BASE_PIOB->PIO_PPUDR = 1 << 15;
457
458         #if USE_RMII_INTERFACE != 1
459                 /* PHY has internal pull down : set MII mode. */
460                 AT91C_BASE_PIOB->PIO_PPUDR = 1 << 16;
461         #endif
462
463         /* Clear PB18 <=> PHY powerdown. */
464         AT91C_BASE_PIOB->PIO_PER = 1 << 18;
465         AT91C_BASE_PIOB->PIO_OER = 1 << 18;
466         AT91C_BASE_PIOB->PIO_CODR = 1 << 18;
467
468         /* After PHY power up, hardware reset. */
469         AT91C_BASE_RSTC->RSTC_RMR = emacRESET_KEY | emacRESET_LENGTH;
470         AT91C_BASE_RSTC->RSTC_RCR = emacRESET_KEY | AT91C_RSTC_EXTRST;
471
472         /* Wait for hardware reset end. */
473         while( !( AT91C_BASE_RSTC->RSTC_RSR & AT91C_RSTC_NRSTL ) )
474         {
475                 __asm volatile ( "NOP" );
476         }
477     __asm volatile ( "NOP" );
478
479         /* Setup the pins. */
480         AT91C_BASE_PIOB->PIO_ASR = emacPERIPHERAL_A_SETUP;
481         AT91C_BASE_PIOB->PIO_PDR = emacPERIPHERAL_A_SETUP;
482
483         /* Enable com between EMAC PHY.
484
485         Enable management port. */
486         AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_MPE;    
487
488         /* MDC = MCK/32. */
489         AT91C_BASE_EMAC->EMAC_NCFGR |= ( 2 ) << 10;     
490
491         /* Wait for PHY auto init end (rather crude delay!). */
492         vTaskDelay( emacPHY_INIT_DELAY );
493
494         /* PHY configuration. */
495         #if USE_RMII_INTERFACE != 1
496         {
497                 unsigned long ulControl;
498
499                 /* PHY has internal pull down : disable MII isolate. */
500                 vReadPHY( AT91C_PHY_ADDR, MII_BMCR, &ulControl );
501                 vReadPHY( AT91C_PHY_ADDR, MII_BMCR, &ulControl );
502                 ulControl &= ~BMCR_ISOLATE;
503                 vWritePHY( AT91C_PHY_ADDR, MII_BMCR, ulControl );
504         }
505         #endif
506
507         /* Disable management port again. */
508         AT91C_BASE_EMAC->EMAC_NCR &= ~AT91C_EMAC_MPE;
509
510         #if USE_RMII_INTERFACE != 1
511                 /* Enable EMAC in MII mode, enable clock ERXCK and ETXCK. */
512                 AT91C_BASE_EMAC->EMAC_USRIO = AT91C_EMAC_CLKEN ;
513         #else
514                 /* Enable EMAC in RMII mode, enable RMII clock (50MHz from oscillator
515                 on ERFCK). */
516                 AT91C_BASE_EMAC->EMAC_USRIO = AT91C_EMAC_RMII | AT91C_EMAC_CLKEN ;
517         #endif
518
519         /* End of code supplied by Atmel ------------------------*/
520
521         /* Setup the buffers and descriptors. */
522         prvSetupDescriptors();
523         
524         /* Load our MAC address into the EMAC. */
525         prvSetupMACAddress();
526
527         /* Are we connected? */
528         if( prvProbePHY() )
529         {
530                 /* Enable the interrupt! */
531                 portENTER_CRITICAL();
532                 {
533                         prvSetupEMACInterrupt();
534                         vPassEMACSemaphore( xSemaphore );
535                 }
536                 portEXIT_CRITICAL();
537         }
538
539         return xSemaphore;
540 }
541 /*-----------------------------------------------------------*/
542
543 /* See the header file for descriptions of public functions. */
544 void vClearEMACTxBuffer( void )
545 {
546 static unsigned portBASE_TYPE uxNextBufferToClear = 0;
547
548         /* Called on Tx interrupt events to reset the AT91C_TRANSMIT_OK bit in each 
549         Tx buffer within the frame just transmitted.  This marks all the buffers
550         as available again.
551
552         The first buffer in the frame should have the bit set automatically. */
553         if( xTxDescriptors[ uxNextBufferToClear ].U_Status.status & AT91C_TRANSMIT_OK )
554         {
555                 /* Loop through the other buffers in the frame. */
556                 while( !( xTxDescriptors[ uxNextBufferToClear ].U_Status.status & AT91C_LAST_BUFFER ) )
557                 {
558                         uxNextBufferToClear++;
559
560                         if( uxNextBufferToClear >= NB_TX_BUFFERS )
561                         {
562                                 uxNextBufferToClear = 0;
563                         }
564
565                         xTxDescriptors[ uxNextBufferToClear ].U_Status.status |= AT91C_TRANSMIT_OK;
566                 }
567
568                 /* Start with the next buffer the next time a Tx interrupt is called. */
569                 uxNextBufferToClear++;
570
571                 /* Do we need to wrap back to the first buffer? */
572                 if( uxNextBufferToClear >= NB_TX_BUFFERS )
573                 {
574                         uxNextBufferToClear = 0;
575                 }
576         }
577 }
578 /*-----------------------------------------------------------*/
579
580 static void prvSetupDescriptors(void)
581 {
582 unsigned portBASE_TYPE xIndex;
583 unsigned long ulAddress;
584
585         /* Initialise xRxDescriptors descriptor. */
586         for( xIndex = 0; xIndex < NB_RX_BUFFERS; ++xIndex )
587         {
588                 /* Calculate the address of the nth buffer within the array. */
589                 ulAddress = ( unsigned long )( pcRxBuffer + ( xIndex * ETH_RX_BUFFER_SIZE ) );
590
591                 /* Write the buffer address into the descriptor.  The DMA will place
592                 the data at this address when this descriptor is being used.  Mask off
593                 the bottom bits of the address as these have special meaning. */
594                 xRxDescriptors[ xIndex ].addr = ulAddress & emacADDRESS_MASK;
595         }       
596
597         /* The last buffer has the wrap bit set so the EMAC knows to wrap back
598         to the first buffer. */
599         xRxDescriptors[ NB_RX_BUFFERS - 1 ].addr |= emacRX_WRAP_BIT;
600
601         /* Initialise xTxDescriptors. */
602         for( xIndex = 0; xIndex < NB_TX_BUFFERS; ++xIndex )
603         {
604                 /* Calculate the address of the nth buffer within the array. */
605                 ulAddress = ( unsigned long )( pcTxBuffer + ( xIndex * ETH_TX_BUFFER_SIZE ) );
606
607                 /* Write the buffer address into the descriptor.  The DMA will read
608                 data from here when the descriptor is being used. */
609                 xTxDescriptors[ xIndex ].addr = ulAddress & emacADDRESS_MASK;
610                 xTxDescriptors[ xIndex ].U_Status.status = AT91C_TRANSMIT_OK;
611         }       
612
613         /* The last buffer has the wrap bit set so the EMAC knows to wrap back
614         to the first buffer. */
615         xTxDescriptors[ NB_TX_BUFFERS - 1 ].U_Status.status = AT91C_TRANSMIT_WRAP | AT91C_TRANSMIT_OK;
616
617         /* Tell the EMAC where to find the descriptors. */
618         AT91C_BASE_EMAC->EMAC_RBQP = ( unsigned long ) xRxDescriptors;
619         AT91C_BASE_EMAC->EMAC_TBQP = ( unsigned long ) xTxDescriptors;
620         
621         /* Clear all the bits in the receive status register. */
622         AT91C_BASE_EMAC->EMAC_RSR = ( AT91C_EMAC_OVR | AT91C_EMAC_REC | AT91C_EMAC_BNA );
623
624         /* Enable the copy of data into the buffers, ignore broadcasts, 
625         and don't copy FCS. */
626         AT91C_BASE_EMAC->EMAC_NCFGR |= ( AT91C_EMAC_CAF | AT91C_EMAC_NBC | AT91C_EMAC_DRFCS);
627
628         /* Enable Rx and Tx, plus the stats register. */
629         AT91C_BASE_EMAC->EMAC_NCR |= ( AT91C_EMAC_TE | AT91C_EMAC_RE | AT91C_EMAC_WESTAT );
630 }       
631 /*-----------------------------------------------------------*/
632
633 static void prvSetupMACAddress( void )
634 {
635         /* Must be written SA1L then SA1H. */
636         AT91C_BASE_EMAC->EMAC_SA1L =    ( ( unsigned long ) cMACAddress[ 3 ] << 24 ) |
637                                                                         ( ( unsigned long ) cMACAddress[ 2 ] << 16 ) |
638                                                                         ( ( unsigned long ) cMACAddress[ 1 ] << 8  ) |
639                                                                         cMACAddress[ 0 ];
640
641         AT91C_BASE_EMAC->EMAC_SA1H =    ( ( unsigned long ) cMACAddress[ 5 ] << 8 ) |
642                                                                         cMACAddress[ 4 ];
643 }
644 /*-----------------------------------------------------------*/
645
646 static void prvSetupEMACInterrupt( void )
647 {
648         /* Create the semaphore used to trigger the EMAC task. */
649         vSemaphoreCreateBinary( xSemaphore );
650         if( xSemaphore )
651         {
652                 /* We start by 'taking' the semaphore so the ISR can 'give' it when the
653                 first interrupt occurs. */
654                 xSemaphoreTake( xSemaphore, emacNO_DELAY );
655                 portENTER_CRITICAL();
656                 {
657                         /* We want to interrupt on Rx and Tx events. */
658                         AT91C_BASE_EMAC->EMAC_IER = AT91C_EMAC_RCOMP | AT91C_EMAC_TCOMP;
659
660                         /* Enable the interrupts in the AIC. */
661                         AT91F_AIC_ConfigureIt( AT91C_ID_EMAC, emacINTERRUPT_LEVEL, AT91C_AIC_SRCTYPE_INT_HIGH_LEVEL, ( void (*)( void ) ) vEMACISR_Wrapper );
662             AT91C_BASE_AIC->AIC_IECR = 0x1 << AT91C_ID_EMAC;
663                 }
664                 portEXIT_CRITICAL();
665         }
666 }
667
668
669
670
671
672 /*
673  * The following functions are initialisation functions taken from the Atmel
674  * EMAC sample code.
675  */
676
677
678 static portBASE_TYPE prvProbePHY( void )
679 {
680 unsigned long ulPHYId1, ulPHYId2, ulStatus;
681 portBASE_TYPE xReturn = pdPASS;
682         
683         /* Code supplied by Atmel (reformatted) -----------------*/
684
685         /* Enable management port */
686         AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_MPE;    
687         AT91C_BASE_EMAC->EMAC_NCFGR |= ( 2 ) << 10;
688
689         /* Read the PHY ID. */
690         vReadPHY( AT91C_PHY_ADDR, MII_PHYSID1, &ulPHYId1 );
691         vReadPHY(AT91C_PHY_ADDR, MII_PHYSID2, &ulPHYId2 );
692
693         /* AMD AM79C875:
694                         PHY_ID1 = 0x0022
695                         PHY_ID2 = 0x5541
696                         Bits 3:0 Revision Number Four bit manufacturer?s revision number.
697                                 0001 stands for Rev. A, etc.
698         */
699         if( ( ( ulPHYId1 << 16 ) | ( ulPHYId2 & 0xfff0 ) ) != MII_DM9161_ID )
700         {
701                 /* Did not expect this ID. */
702                 xReturn = pdFAIL;
703         }
704         else
705         {
706                 ulStatus = xGetLinkSpeed();
707
708                 if( ulStatus != pdPASS )
709                 {
710                         xReturn = pdFAIL;
711                 }
712         }
713
714         /* Disable management port */
715         AT91C_BASE_EMAC->EMAC_NCR &= ~AT91C_EMAC_MPE;   
716
717         /* End of code supplied by Atmel ------------------------*/
718
719         return xReturn;
720 }
721 /*-----------------------------------------------------------*/
722
723 static void vReadPHY( unsigned char ucPHYAddress, unsigned char ucAddress, unsigned long *pulValue )
724 {
725         /* Code supplied by Atmel (reformatted) ----------------------*/
726
727         AT91C_BASE_EMAC->EMAC_MAN =     (AT91C_EMAC_SOF & (0x01<<30))
728                                                                         | (2 << 16) | (2 << 28)
729                                                                         | ((ucPHYAddress & 0x1f) << 23)
730                                                                         | (ucAddress << 18);
731
732         /* Wait until IDLE bit in Network Status register is cleared. */
733         while( !( AT91C_BASE_EMAC->EMAC_NSR & AT91C_EMAC_IDLE ) )
734         {
735                 __asm( "NOP" );
736         }
737
738         *pulValue = ( AT91C_BASE_EMAC->EMAC_MAN & 0x0000ffff ); 
739
740         /* End of code supplied by Atmel ------------------------*/
741 }
742 /*-----------------------------------------------------------*/
743
744 #if USE_RMII_INTERFACE != 1
745 static void vWritePHY( unsigned char ucPHYAddress, unsigned char ucAddress, unsigned long ulValue )
746 {
747         /* Code supplied by Atmel (reformatted) ----------------------*/
748
749         AT91C_BASE_EMAC->EMAC_MAN = (( AT91C_EMAC_SOF & (0x01<<30))
750                                                                 | (2 << 16) | (1 << 28)
751                                                                 | ((ucPHYAddress & 0x1f) << 23)
752                                                                 | (ucAddress << 18))
753                                                                 | (ulValue & 0xffff);
754
755         /* Wait until IDLE bit in Network Status register is cleared */
756         while( !( AT91C_BASE_EMAC->EMAC_NSR & AT91C_EMAC_IDLE ) )
757         {
758                 __asm( "NOP" );
759         };
760
761         /* End of code supplied by Atmel ------------------------*/
762 }
763 #endif
764 /*-----------------------------------------------------------*/
765
766 static portBASE_TYPE xGetLinkSpeed( void )
767 {
768         unsigned long ulBMSR, ulBMCR, ulLPA, ulMACCfg, ulSpeed, ulDuplex;
769
770         /* Code supplied by Atmel (reformatted) -----------------*/
771
772         /* Link status is latched, so read twice to get current value */
773         vReadPHY(AT91C_PHY_ADDR, MII_BMSR, &ulBMSR);
774         vReadPHY(AT91C_PHY_ADDR, MII_BMSR, &ulBMSR);
775
776         if( !( ulBMSR & BMSR_LSTATUS ) )
777         {       
778                 /* No Link. */
779                 return pdFAIL;
780         }
781
782         vReadPHY(AT91C_PHY_ADDR, MII_BMCR, &ulBMCR);
783         if (ulBMCR & BMCR_ANENABLE)
784         {                               
785                 /* AutoNegotiation is enabled. */
786                 if (!(ulBMSR & BMSR_ANEGCOMPLETE))
787                 {
788                         /* Auto-negotitation in progress. */
789                         return pdFAIL;                          
790                 }               
791
792                 vReadPHY(AT91C_PHY_ADDR, MII_LPA, &ulLPA);
793                 if( ( ulLPA & LPA_100FULL ) || ( ulLPA & LPA_100HALF ) )
794                 {
795                         ulSpeed = SPEED_100;
796                 }
797                 else
798                 {
799                         ulSpeed = SPEED_10;
800                 }
801
802                 if( ( ulLPA & LPA_100FULL ) || ( ulLPA & LPA_10FULL ) )
803                 {
804                         ulDuplex = DUPLEX_FULL;
805                 }
806                 else
807                 {
808                         ulDuplex = DUPLEX_HALF;
809                 }
810         }
811         else
812         {
813                 ulSpeed = ( ulBMCR & BMCR_SPEED100 ) ? SPEED_100 : SPEED_10;
814                 ulDuplex = ( ulBMCR & BMCR_FULLDPLX ) ? DUPLEX_FULL : DUPLEX_HALF;
815         }
816
817         /* Update the MAC */
818         ulMACCfg = AT91C_BASE_EMAC->EMAC_NCFGR & ~( AT91C_EMAC_SPD | AT91C_EMAC_FD );
819         if( ulSpeed == SPEED_100 )
820         {
821                 if( ulDuplex == DUPLEX_FULL )
822                 {
823                         /* 100 Full Duplex */
824                         AT91C_BASE_EMAC->EMAC_NCFGR = ulMACCfg | AT91C_EMAC_SPD | AT91C_EMAC_FD;
825                 }
826                 else
827                 {                                       
828                         /* 100 Half Duplex */
829                         AT91C_BASE_EMAC->EMAC_NCFGR = ulMACCfg | AT91C_EMAC_SPD;
830                 }
831         }
832         else
833         {
834                 if (ulDuplex == DUPLEX_FULL)
835                 {
836                         /* 10 Full Duplex */
837                         AT91C_BASE_EMAC->EMAC_NCFGR = ulMACCfg | AT91C_EMAC_FD;
838                 }
839                 else
840                 {                       /* 10 Half Duplex */
841                         AT91C_BASE_EMAC->EMAC_NCFGR = ulMACCfg;
842                 }
843         }
844
845         /* End of code supplied by Atmel ------------------------*/
846
847         return pdPASS;
848 }
849 /*-----------------------------------------------------------*/
850
851 void vEMACWaitForInput( void )
852 {
853         /* Just wait until we are signled from an ISR that data is available, or
854         we simply time out. */
855         xSemaphoreTake( xSemaphore, emacBLOCK_TIME_WAITING_FOR_INPUT );
856 }