⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sam7_emac.c

📁 FreeRTOS is a portable, open source, mini Real Time Kernel - a free to download and royalty free RTO
💻 C
📖 第 1 页 / 共 2 页
字号:
/*
	FreeRTOS.org V5.2.0 - Copyright (C) 2003-2009 Richard Barry.

	This file is part of the FreeRTOS.org distribution.

	FreeRTOS.org is free software; you can redistribute it and/or modify it 
	under the terms of the GNU General Public License (version 2) as published
	by the Free Software Foundation and modified by the FreeRTOS exception.

	FreeRTOS.org is distributed in the hope that it will be useful,	but WITHOUT
	ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
	FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for 
	more details.

	You should have received a copy of the GNU General Public License along 
	with FreeRTOS.org; if not, write to the Free Software Foundation, Inc., 59 
	Temple Place, Suite 330, Boston, MA  02111-1307  USA.

	A special exception to the GPL is included to allow you to distribute a 
	combined work that includes FreeRTOS.org without being obliged to provide
	the source code for any proprietary components.  See the licensing section
	of http://www.FreeRTOS.org for full details.


	***************************************************************************
	*                                                                         *
	* Get the FreeRTOS eBook!  See http://www.FreeRTOS.org/Documentation      *
	*                                                                         *
	* This is a concise, step by step, 'hands on' guide that describes both   *
	* general multitasking concepts and FreeRTOS specifics. It presents and   *
	* explains numerous examples that are written using the FreeRTOS API.     *
	* Full source code for all the examples is provided in an accompanying    *
	* .zip file.                                                              *
	*                                                                         *
	***************************************************************************

	1 tab == 4 spaces!

	Please ensure to read the configuration and relevant port sections of the
	online documentation.

	http://www.FreeRTOS.org - Documentation, latest information, license and
	contact details.

	http://www.SafeRTOS.com - A version that is certified for use in safety
	critical systems.

	http://www.OpenRTOS.com - Commercial support, development, porting,
	licensing and training services.
*/

/*
 * Interrupt driven driver for the EMAC peripheral.  This driver is not
 * reentrant, re-entrancy is handled by a semaphore at the network interface
 * level. 
 */


/*
Changes from V3.2.2

	+ Corrected the byte order when writing the MAC address to the MAC.
	+ Support added for MII interfaces.  Previously only RMII was supported.

Changes from V3.2.3

	+ The MII interface is now the default.
	+ Modified the initialisation sequence slightly to allow auto init more
	  time to complete.

Changes from V4.0.1

	+ Made the function vClearEMACTxBuffer() more robust by moving the index
	  manipulation into the if() statement.  This allows the tx interrupt to
	  execute even when there is no data to handle.

Changes from V4.0.4

	+ Corrected the Rx frame length mask when obtaining the length from the
	  rx descriptor.
*/


/* Standard includes. */
#include <string.h>

/* Scheduler includes. */
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"

/* Demo app includes. */
#include "SAM7_EMAC.h"

/* Hardware specific includes. */
#include "Emac.h"
#include "mii.h"
#include "AT91SAM7X256.h"


/* USE_RMII_INTERFACE must be defined as 1 to use an RMII interface, or 0
to use an MII interface. */
#define USE_RMII_INTERFACE 0


/* The buffer addresses written into the descriptors must be aligned so the
last few bits are zero.  These bits have special meaning for the EMAC
peripheral and cannot be used as part of the address. */
#define emacADDRESS_MASK			( ( unsigned portLONG ) 0xFFFFFFFC )

/* Bit used within the address stored in the descriptor to mark the last
descriptor in the array. */
#define emacRX_WRAP_BIT				( ( unsigned portLONG ) 0x02 )

/* Bit used within the Tx descriptor status to indicate whether the
descriptor is under the control of the EMAC or the software. */
#define emacTX_BUF_USED				( ( unsigned portLONG ) 0x80000000 )

/* A short delay is used to wait for a buffer to become available, should
one not be immediately available when trying to transmit a frame. */
#define emacBUFFER_WAIT_DELAY		( 2 )
#define emacMAX_WAIT_CYCLES			( ( portBASE_TYPE ) ( configTICK_RATE_HZ / 40 ) )

/* The time to block waiting for input. */
#define emacBLOCK_TIME_WAITING_FOR_INPUT	( ( portTickType ) 100 )

/* Peripheral setup for the EMAC. */
#define emacPERIPHERAL_A_SETUP 		( ( unsigned portLONG ) AT91C_PB2_ETX0			) | \
									( ( unsigned portLONG ) AT91C_PB12_ETXER		) | \
									( ( unsigned portLONG ) AT91C_PB16_ECOL			) | \
									( ( unsigned portLONG ) AT91C_PB11_ETX3			) | \
									( ( unsigned portLONG ) AT91C_PB6_ERX1			) | \
									( ( unsigned portLONG ) AT91C_PB15_ERXDV		) | \
									( ( unsigned portLONG ) AT91C_PB13_ERX2			) | \
									( ( unsigned portLONG ) AT91C_PB3_ETX1			) | \
									( ( unsigned portLONG ) AT91C_PB8_EMDC			) | \
									( ( unsigned portLONG ) AT91C_PB5_ERX0			) | \
									( ( unsigned portLONG ) AT91C_PB14_ERX3			) | \
									( ( unsigned portLONG ) AT91C_PB4_ECRS_ECRSDV	) | \
									( ( unsigned portLONG ) AT91C_PB1_ETXEN			) | \
									( ( unsigned portLONG ) AT91C_PB10_ETX2			) | \
									( ( unsigned portLONG ) AT91C_PB0_ETXCK_EREFCK	) | \
									( ( unsigned portLONG ) AT91C_PB9_EMDIO			) | \
									( ( unsigned portLONG ) AT91C_PB7_ERXER			) | \
									( ( unsigned portLONG ) AT91C_PB17_ERXCK		);

/* Misc defines. */
#define emacINTERRUPT_LEVEL			( 5 )
#define emacNO_DELAY				( 0 )
#define emacTOTAL_FRAME_HEADER_SIZE	( 54 )
#define emacPHY_INIT_DELAY			( 5000 / portTICK_RATE_MS )
#define emacRESET_KEY				( ( unsigned portLONG ) 0xA5000000 )
#define emacRESET_LENGTH			( ( unsigned portLONG ) ( 0x01 << 8 ) )

/* The Atmel header file only defines the TX frame length mask. */
#define emacRX_LENGTH_FRAME			( 0xfff )

/*-----------------------------------------------------------*/

/* Buffer written to by the EMAC DMA.  Must be aligned as described by the
comment above the emacADDRESS_MASK definition. */
static volatile portCHAR pcRxBuffer[ NB_RX_BUFFERS * ETH_RX_BUFFER_SIZE ] __attribute__ ((aligned (8)));

/* Buffer read by the EMAC DMA.  Must be aligned as described by the comment
above the emacADDRESS_MASK definition. */
static portCHAR pcTxBuffer[ NB_TX_BUFFERS * ETH_TX_BUFFER_SIZE ] __attribute__ ((aligned (8)));

/* Descriptors used to communicate between the program and the EMAC peripheral.
These descriptors hold the locations and state of the Rx and Tx buffers. */
static volatile AT91S_TxTdDescriptor xTxDescriptors[ NB_TX_BUFFERS ];
static volatile AT91S_RxTdDescriptor xRxDescriptors[ NB_RX_BUFFERS ];

/* The IP and Ethernet addresses are read from the header files. */
const portCHAR cMACAddress[ 6 ] = { emacETHADDR0, emacETHADDR1, emacETHADDR2, emacETHADDR3, emacETHADDR4, emacETHADDR5 };
const unsigned char ucIPAddress[ 4 ]  = { emacIPADDR0, emacIPADDR1, emacIPADDR2, emacIPADDR3 };

/*-----------------------------------------------------------*/

/* See the header file for descriptions of public functions. */

/*
 * Prototype for the EMAC interrupt function.
 */
void vEMACISR_Wrapper( void ) __attribute__ ((naked));

/*
 * Initialise both the Tx and Rx descriptors used by the EMAC.
 */
static void prvSetupDescriptors(void);

/*
 * Write our MAC address into the EMAC.  
 */
static void prvSetupMACAddress( void );

/*
 * Configure the EMAC and AIC for EMAC interrupts.
 */
static void prvSetupEMACInterrupt( void );

/*
 * Some initialisation functions taken from the Atmel EMAC sample code.
 */
static void vReadPHY( unsigned portCHAR ucPHYAddress, unsigned portCHAR ucAddress, unsigned portLONG *pulValue );
static portBASE_TYPE xGetLinkSpeed( void );
static portBASE_TYPE prvProbePHY( void );
#if USE_RMII_INTERFACE != 1
	static void vWritePHY( unsigned portCHAR ucPHYAddress, unsigned portCHAR ucAddress, unsigned portLONG ulValue);
#endif


/* The semaphore used by the EMAC ISR to wake the EMAC task. */
static xSemaphoreHandle xSemaphore = NULL;

/* Holds the index to the next buffer from which data will be read. */
static volatile unsigned portLONG ulNextRxBuffer = 0;

/*-----------------------------------------------------------*/

/* See the header file for descriptions of public functions. */
portLONG lEMACSend( portCHAR *pcFrom, unsigned portLONG ulLength, portLONG lEndOfFrame )
{
static unsigned portBASE_TYPE uxTxBufferIndex = 0;
portBASE_TYPE xWaitCycles = 0;
portLONG lReturn = pdPASS;
portCHAR *pcBuffer;
unsigned portLONG ulLastBuffer, ulDataBuffered = 0, ulDataRemainingToSend, ulLengthToSend;

	/* If the length of data to be transmitted is greater than each individual
	transmit buffer then the data will be split into more than one buffer.
	Loop until the entire length has been buffered. */
	while( ulDataBuffered < ulLength )
	{
		/* Is a buffer available? */
		while( !( xTxDescriptors[ uxTxBufferIndex ].U_Status.status & AT91C_TRANSMIT_OK ) )
		{
			/* There is no room to write the Tx data to the Tx buffer.  Wait a
			short while, then try again. */
			xWaitCycles++;
			if( xWaitCycles > emacMAX_WAIT_CYCLES )
			{
				/* Give up. */
				lReturn = pdFAIL;
				break;
			}
			else
			{
				vTaskDelay( emacBUFFER_WAIT_DELAY );
			}
		}
	
		/* lReturn will only be pdPASS if a buffer is available. */
		if( lReturn == pdPASS )
		{
			portENTER_CRITICAL();
			{
				/* Get the address of the buffer from the descriptor, then copy 
				the data into the buffer. */
				pcBuffer = ( portCHAR * ) xTxDescriptors[ uxTxBufferIndex ].addr;

				/* How much can we write to the buffer? */
				ulDataRemainingToSend = ulLength - ulDataBuffered;
				if( ulDataRemainingToSend <= ETH_TX_BUFFER_SIZE )
				{
					/* We can write all the remaining bytes. */
					ulLengthToSend = ulDataRemainingToSend;
				}
				else
				{
					/* We can not write more than ETH_TX_BUFFER_SIZE in one go. */
					ulLengthToSend = ETH_TX_BUFFER_SIZE;
				}

				/* Copy the data into the buffer. */
				memcpy( ( void * ) pcBuffer, ( void * ) &( pcFrom[ ulDataBuffered ] ), ulLengthToSend );
				ulDataBuffered += ulLengthToSend;

				/* Is this the last data for the frame? */
				if( lEndOfFrame && ( ulDataBuffered >= ulLength ) )
				{
					/* No more data remains for this frame so we can start the 
					transmission. */
					ulLastBuffer = AT91C_LAST_BUFFER;
				}
				else
				{
					/* More data to come for this frame. */
					ulLastBuffer = 0;
				}
	
				/* Fill out the necessary in the descriptor to get the data sent, 
				then move to the next descriptor, wrapping if necessary. */
				if( uxTxBufferIndex >= ( NB_TX_BUFFERS - 1 ) )
				{				
					xTxDescriptors[ uxTxBufferIndex ].U_Status.status = 	( ulLengthToSend & ( unsigned portLONG ) AT91C_LENGTH_FRAME )
																			| ulLastBuffer
																			| AT91C_TRANSMIT_WRAP;
					uxTxBufferIndex = 0;
				}
				else
				{
					xTxDescriptors[ uxTxBufferIndex ].U_Status.status = 	( ulLengthToSend & ( unsigned portLONG ) AT91C_LENGTH_FRAME )
																			| ulLastBuffer;
					uxTxBufferIndex++;
				}
	
				/* If this is the last buffer to be sent for this frame we can
				start the transmission. */
				if( ulLastBuffer )
				{
					AT91C_BASE_EMAC->EMAC_NCR |= AT91C_EMAC_TSTART;
				}
			}
			portEXIT_CRITICAL();
		}
		else
		{
			break;
		}
	}

	return lReturn;
}
/*-----------------------------------------------------------*/

/* See the header file for descriptions of public functions. */
unsigned portLONG ulEMACInputLength( void )
{
register unsigned portLONG ulIndex, ulLength = 0;

	/* Skip any fragments.  We are looking for the first buffer that contains
	data and has the SOF (start of frame) bit set. */
	while( ( xRxDescriptors[ ulNextRxBuffer ].addr & AT91C_OWNERSHIP_BIT ) && !( xRxDescriptors[ ulNextRxBuffer ].U_Status.status & AT91C_SOF ) )
	{
		/* Ignoring this buffer.  Mark it as free again. */
		xRxDescriptors[ ulNextRxBuffer ].addr &= ~( AT91C_OWNERSHIP_BIT );		
		ulNextRxBuffer++;
		if( ulNextRxBuffer >= NB_RX_BUFFERS )
		{
			ulNextRxBuffer = 0;
		}
	}

	/* We are going to walk through the descriptors that make up this frame, 
	but don't want to alter ulNextRxBuffer as this would prevent vEMACRead()
	from finding the data.  Therefore use a copy of ulNextRxBuffer instead. */
	ulIndex = ulNextRxBuffer;

	/* Walk through the descriptors until we find the last buffer for this 
	frame.  The last buffer will give us the length of the entire frame. */
	while( ( xRxDescriptors[ ulIndex ].addr & AT91C_OWNERSHIP_BIT ) && !ulLength )
	{
		ulLength = xRxDescriptors[ ulIndex ].U_Status.status & emacRX_LENGTH_FRAME;

		/* Increment to the next buffer, wrapping if necessary. */
		ulIndex++;
		if( ulIndex >= NB_RX_BUFFERS )
		{
			ulIndex = 0;
		}
	}

	return ulLength;
}
/*-----------------------------------------------------------*/

/* See the header file for descriptions of public functions. */
void vEMACRead( portCHAR *pcTo, unsigned portLONG ulSectionLength, unsigned portLONG ulTotalFrameLength )
{
static unsigned portLONG ulSectionBytesReadSoFar = 0, ulBufferPosition = 0, ulFameBytesReadSoFar = 0;
static portCHAR *pcSource;
register unsigned portLONG ulBytesRemainingInBuffer, ulRemainingSectionBytes;

	/* Read ulSectionLength bytes from the Rx buffers.  This is not necessarily any
	correspondence between the length of our Rx buffers, and the length of the
	data we are returning or the length of the data being requested.  Therefore, 
	between calls  we have to remember not only which buffer we are currently 
	processing, but our position within that buffer.  This would be greatly
	simplified if PBUF_POOL_BUFSIZE could be guaranteed to be greater than
	the size of each Rx buffer, and that memory fragmentation did not occur.
	
	This function should only be called after a call to ulEMACInputLength().
	This will ensure ulNextRxBuffer is set to the correct buffer. */



	/* vEMACRead is called with pcTo set to NULL to indicate that we are about
	to read a new frame.  Any fragments remaining in the frame we were 
	processing during the last call should be dropped. */
	if( pcTo == NULL )
	{
		/* How many bytes are indicated as being in this buffer?  If none then
		the buffer is completely full and the frame is contained within more
		than one buffer. */

		/* Reset our state variables ready for the next read from this buffer. */
        pcSource = ( portCHAR * )( xRxDescriptors[ ulNextRxBuffer ].addr & emacADDRESS_MASK );
        ulFameBytesReadSoFar = ( unsigned portLONG ) 0;
		ulBufferPosition = ( unsigned portLONG ) 0;
	}
	else
	{
		/* Loop until we have obtained the required amount of data. */
        ulSectionBytesReadSoFar = 0;
		while( ulSectionBytesReadSoFar < ulSectionLength )
		{
			/* We may have already read some data from this buffer.  How much
			data remains in the buffer? */
			ulBytesRemainingInBuffer = ( ETH_RX_BUFFER_SIZE - ulBufferPosition );

			/* How many more bytes do we need to read before we have the 
			required amount of data? */
            ulRemainingSectionBytes = ulSectionLength - ulSectionBytesReadSoFar;

			/* Do we want more data than remains in the buffer? */
			if( ulRemainingSectionBytes > ulBytesRemainingInBuffer )
			{
				/* We want more data than remains in the buffer so we can 
				write the remains of the buffer to the destination, then move
				onto the next buffer to get the rest. */
				memcpy( &( pcTo[ ulSectionBytesReadSoFar ] ), &( pcSource[ ulBufferPosition ] ), ulBytesRemainingInBuffer );
				ulSectionBytesReadSoFar += ulBytesRemainingInBuffer;
                ulFameBytesReadSoFar += ulBytesRemainingInBuffer;

				/* Mark the buffer as free again. */
				xRxDescriptors[ ulNextRxBuffer ].addr &= ~( AT91C_OWNERSHIP_BIT );

				/* Move onto the next buffer. */
				ulNextRxBuffer++;
				if( ulNextRxBuffer >= NB_RX_BUFFERS )
				{
					ulNextRxBuffer = ( unsigned portLONG ) 0;
				}

				/* Reset the variables for the new buffer. */
				pcSource = ( portCHAR * )( xRxDescriptors[ ulNextRxBuffer ].addr & emacADDRESS_MASK );
				ulBufferPosition = ( unsigned portLONG ) 0;
			}
			else
			{
				/* We have enough data in this buffer to send back.  Read out

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -