/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
}\r
}\r
#endif\r
+ if( xIsCallingFromIPTask() != 0 )\r
+ {\r
+ /* Only the IP-task is allowed to call this function directly. */\r
+ xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE );\r
+ }\r
+ else\r
+ {\r
+ IPStackEvent_t xSendEvent;\r
\r
- xNetworkInterfaceOutput( pxNetworkBuffer, pdTRUE );\r
+ /* Send a message to the IP-task to send this ARP packet. */\r
+ xSendEvent.eEventType = eNetworkTxEvent;\r
+ xSendEvent.pvData = ( void * ) pxNetworkBuffer;\r
+ if( xSendEventStructToIPTask( &xSendEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL )\r
+ {\r
+ /* Failed to send the message, so release the network buffer. */\r
+ vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );\r
+ }\r
+ }\r
}\r
}\r
\r
{\r
ARPPacket_t *pxARPPacket;\r
\r
+ /* Buffer allocation ensures that buffers always have space\r
+ for an ARP packet. See buffer allocation implementations 1\r
+ and 2 under portable/BufferManagement. */\r
+ configASSERT( pxNetworkBuffer );\r
+ configASSERT( pxNetworkBuffer->xDataLength >= sizeof(ARPPacket_t) );\r
+\r
pxARPPacket = ( ARPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;\r
\r
/* memcpy the const part of the header information into the correct\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
\r
/* Offsets into the transmitted DHCP options fields at which various parameters\r
are located. */\r
-#define dhcpCLIENT_IDENTIFIER_OFFSET ( 5 )\r
-#define dhcpREQUESTED_IP_ADDRESS_OFFSET ( 13 )\r
-#define dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ( 19 )\r
+#define dhcpCLIENT_IDENTIFIER_OFFSET ( 6 )\r
+#define dhcpREQUESTED_IP_ADDRESS_OFFSET ( 14 )\r
+#define dhcpDHCP_SERVER_IP_ADDRESS_OFFSET ( 20 )\r
\r
/* Values used in the DHCP packets. */\r
#define dhcpREQUEST_OPCODE ( 1 )\r
\r
if( xDHCPData.xDHCPTxPeriod <= ipconfigMAXIMUM_DISCOVER_TX_PERIOD )\r
{\r
- xDHCPData.ulTransactionId = ipconfigRAND32( );\r
-\r
- if( 0 != xDHCPData.ulTransactionId )\r
+ if( xApplicationGetRandomNumber( &( xDHCPData.ulTransactionId ) ) != pdFALSE )\r
{\r
xDHCPData.xDHCPTxTime = xTaskGetTickCount( );\r
xDHCPData.xUseBroadcast = !xDHCPData.xUseBroadcast;\r
/* Initialise the parameters that will be set by the DHCP process. Per\r
https://www.ietf.org/rfc/rfc2131.txt, Transaction ID should be a random\r
value chosen by the client. */\r
- xDHCPData.ulTransactionId = ipconfigRAND32();\r
\r
/* Check for random number generator API failure. */\r
- if( 0 != xDHCPData.ulTransactionId )\r
+ if( xApplicationGetRandomNumber( &( xDHCPData.ulTransactionId ) ) != pdFALSE )\r
{\r
xDHCPData.xUseBroadcast = 0;\r
xDHCPData.ulOfferedIPAddress = 0UL;\r
FreeRTOS_debug_printf( ( "prvInitialiseDHCP: start after %lu ticks\n", dhcpINITIAL_TIMER_PERIOD ) );\r
vIPReloadDHCPTimer( dhcpINITIAL_TIMER_PERIOD );\r
}\r
+ else\r
+ {\r
+ /* There was a problem with the randomiser. */\r
+ }\r
}\r
/*-----------------------------------------------------------*/\r
\r
/* Walk through the options until the dhcpOPTION_END_BYTE byte\r
is found, taking care not to walk off the end of the options. */\r
pucByte = &( pxDHCPMessage->ucFirstOptionByte );\r
- /* Maintain a pointer to the last valid byte (i.e. not the first\r
- invalid byte). */\r
+ /* Maintain a pointer to the last valid byte (i.e. not the first\r
+ invalid byte). */\r
pucLastByte = pucUDPPayload + lBytes - 1;\r
\r
while( pucByte <= pucLastByte )\r
/* Stop if the response is malformed. */\r
if( pucByte < pucLastByte )\r
{\r
- /* There are at least two bytes left. */\r
+ /* There are at least two bytes left. */\r
ucLength = pucByte[ 1 ];\r
pucByte += 2;\r
\r
dhcpCLIENT_IDENTIFIER_OFFSET, dhcpREQUESTED_IP_ADDRESS_OFFSET and\r
dhcpDHCP_SERVER_IP_ADDRESS_OFFSET. */\r
dhcpMESSAGE_TYPE_OPTION_CODE, 1, dhcpMESSAGE_TYPE_REQUEST, /* Message type option. */\r
- dhcpCLIENT_IDENTIFIER_OPTION_CODE, 6, 0, 0, 0, 0, 0, 0, /* Client identifier. */\r
+ dhcpCLIENT_IDENTIFIER_OPTION_CODE, 7, 1, 0, 0, 0, 0, 0, 0, /* Client identifier. */\r
dhcpREQUEST_IP_ADDRESS_OPTION_CODE, 4, 0, 0, 0, 0, /* The IP address being requested. */\r
dhcpSERVER_IP_ADDRESS_OPTION_CODE, 4, 0, 0, 0, 0, /* The IP address of the DHCP server. */\r
dhcpOPTION_END_BYTE\r
{\r
/* Do not change the ordering without also changing dhcpCLIENT_IDENTIFIER_OFFSET. */\r
dhcpMESSAGE_TYPE_OPTION_CODE, 1, dhcpMESSAGE_TYPE_DISCOVER, /* Message type option. */\r
- dhcpCLIENT_IDENTIFIER_OPTION_CODE, 6, 0, 0, 0, 0, 0, 0, /* Client identifier. */\r
+ dhcpCLIENT_IDENTIFIER_OPTION_CODE, 7, 1, 0, 0, 0, 0, 0, 0, /* Client identifier. */\r
dhcpPARAMETER_REQUEST_OPTION_CODE, 3, dhcpSUBNET_MASK_OPTION_CODE, dhcpGATEWAY_OPTION_CODE, dhcpDNS_SERVER_OPTIONS_CODE, /* Parameter request option. */\r
dhcpOPTION_END_BYTE\r
};\r
static void prvPrepareLinkLayerIPLookUp( void )\r
{\r
uint8_t ucLinkLayerIPAddress[ 2 ];\r
+ uint32_t ulNumbers[ 2 ];\r
\r
/* After DHCP has failed to answer, prepare everything to start\r
trying-out LinkLayer IP-addresses, using the random method. */\r
xDHCPData.xDHCPTxTime = xTaskGetTickCount();\r
\r
- ucLinkLayerIPAddress[ 0 ] = ( uint8_t )1 + ( uint8_t )( ipconfigRAND32() % 0xFDu ); /* get value 1..254 for IP-address 3rd byte of IP address to try. */\r
- ucLinkLayerIPAddress[ 1 ] = ( uint8_t )1 + ( uint8_t )( ipconfigRAND32() % 0xFDu ); /* get value 1..254 for IP-address 4th byte of IP address to try. */\r
+ xApplicationGetRandomNumber( &( ulNumbers[ 0 ] ) );\r
+ xApplicationGetRandomNumber( &( ulNumbers[ 1 ] ) );\r
+ ucLinkLayerIPAddress[ 0 ] = ( uint8_t )1 + ( uint8_t )( ulNumbers[ 0 ] % 0xFDu ); /* get value 1..254 for IP-address 3rd byte of IP address to try. */\r
+ ucLinkLayerIPAddress[ 1 ] = ( uint8_t )1 + ( uint8_t )( ulNumbers[ 1 ] % 0xFDu ); /* get value 1..254 for IP-address 4th byte of IP address to try. */\r
\r
xNetworkAddressing.ulGatewayAddress = FreeRTOS_htonl( 0xA9FE0203 );\r
\r
xNetworkAddressing.ulBroadcastAddress = ( xDHCPData.ulOfferedIPAddress & xNetworkAddressing.ulNetMask ) | ~xNetworkAddressing.ulNetMask;\r
\r
/* Close socket to ensure packets don't queue on it. not needed anymore as DHCP failed. but still need timer for ARP testing. */\r
- vSocketClose( xDHCPData.xDHCPSocket );\r
- xDHCPData.xDHCPSocket = NULL;\r
- xDHCPData.xDHCPTxPeriod = pdMS_TO_TICKS( 3000ul + ( ipconfigRAND32() & 0x3fful ) ); /* do ARP test every (3 + 0-1024mS) seconds. */\r
+ if( xDHCPData.xDHCPSocket != NULL )\r
+ {\r
+ /* Close socket to ensure packets don't queue on it. */\r
+ vSocketClose( xDHCPData.xDHCPSocket );\r
+ xDHCPData.xDHCPSocket = NULL;\r
+ }\r
+\r
+ xApplicationGetRandomNumber( &( ulNumbers[ 0 ] ) );\r
+ xDHCPData.xDHCPTxPeriod = pdMS_TO_TICKS( 3000ul + ( ulNumbers[ 0 ] & 0x3ffuL ) ); /* do ARP test every (3 + 0-1024mS) seconds. */\r
\r
xARPHadIPClash = pdFALSE; /* reset flag that shows if have ARP clash. */\r
vARPSendGratuitous();\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
#if( ipconfigUSE_DNS != 0 )\r
\r
#if( ipconfigBYTE_ORDER == pdFREERTOS_LITTLE_ENDIAN )\r
- #define dnsDNS_PORT 0x3500\r
- #define dnsONE_QUESTION 0x0100\r
- #define dnsOUTGOING_FLAGS 0x0001 /* Standard query. */\r
- #define dnsRX_FLAGS_MASK 0x0f80 /* The bits of interest in the flags field of incoming DNS messages. */\r
- #define dnsEXPECTED_RX_FLAGS 0x0080 /* Should be a response, without any errors. */\r
+ #define dnsDNS_PORT 0x3500u\r
+ #define dnsONE_QUESTION 0x0100u\r
+ #define dnsOUTGOING_FLAGS 0x0001u /* Standard query. */\r
+ #define dnsRX_FLAGS_MASK 0x0f80u /* The bits of interest in the flags field of incoming DNS messages. */\r
+ #define dnsEXPECTED_RX_FLAGS 0x0080u /* Should be a response, without any errors. */\r
#else\r
- #define dnsDNS_PORT 0x0035\r
- #define dnsONE_QUESTION 0x0001\r
- #define dnsOUTGOING_FLAGS 0x0100 /* Standard query. */\r
- #define dnsRX_FLAGS_MASK 0x800f /* The bits of interest in the flags field of incoming DNS messages. */\r
- #define dnsEXPECTED_RX_FLAGS 0x8000 /* Should be a response, without any errors. */\r
+ #define dnsDNS_PORT 0x0035u\r
+ #define dnsONE_QUESTION 0x0001u\r
+ #define dnsOUTGOING_FLAGS 0x0100u /* Standard query. */\r
+ #define dnsRX_FLAGS_MASK 0x800fu /* The bits of interest in the flags field of incoming DNS messages. */\r
+ #define dnsEXPECTED_RX_FLAGS 0x8000u /* Should be a response, without any errors. */\r
\r
#endif /* ipconfigBYTE_ORDER */\r
\r
/* The maximum number of times a DNS request should be sent out if a response\r
is not received, before giving up. */\r
#ifndef ipconfigDNS_REQUEST_ATTEMPTS\r
- #define ipconfigDNS_REQUEST_ATTEMPTS 5\r
+ #define ipconfigDNS_REQUEST_ATTEMPTS 5\r
#endif\r
\r
/* If the top two bits in the first character of a name field are set then the\r
name field is an offset to the string, rather than the string itself. */\r
-#define dnsNAME_IS_OFFSET ( ( uint8_t ) 0xc0 )\r
+#define dnsNAME_IS_OFFSET ( ( uint8_t ) 0xc0 )\r
\r
/* NBNS flags. */\r
-#define dnsNBNS_FLAGS_RESPONSE 0x8000\r
-#define dnsNBNS_FLAGS_OPCODE_MASK 0x7800\r
-#define dnsNBNS_FLAGS_OPCODE_QUERY 0x0000\r
-#define dnsNBNS_FLAGS_OPCODE_REGISTRATION 0x2800\r
+#define dnsNBNS_FLAGS_RESPONSE 0x8000u\r
+#define dnsNBNS_FLAGS_OPCODE_MASK 0x7800u\r
+#define dnsNBNS_FLAGS_OPCODE_QUERY 0x0000u\r
+#define dnsNBNS_FLAGS_OPCODE_REGISTRATION 0x2800u\r
\r
/* Host types. */\r
-#define dnsTYPE_A_HOST 0x01\r
-#define dnsCLASS_IN 0x01\r
+#define dnsTYPE_A_HOST 0x01u\r
+#define dnsCLASS_IN 0x01u\r
\r
/* LLMNR constants. */\r
-#define dnsLLMNR_TTL_VALUE 300000\r
-#define dnsLLMNR_FLAGS_IS_REPONSE 0x8000\r
+#define dnsLLMNR_TTL_VALUE 300000uL\r
+#define dnsLLMNR_FLAGS_IS_REPONSE 0x8000u\r
\r
/* NBNS constants. */\r
-#define dnsNBNS_TTL_VALUE 3600 /* 1 hour valid */\r
-#define dnsNBNS_TYPE_NET_BIOS 0x0020\r
-#define dnsNBNS_CLASS_IN 0x01\r
-#define dnsNBNS_NAME_FLAGS 0x6000\r
-#define dnsNBNS_ENCODED_NAME_LENGTH 32\r
+#define dnsNBNS_TTL_VALUE 3600uL /* 1 hour valid */\r
+#define dnsNBNS_TYPE_NET_BIOS 0x0020u\r
+#define dnsNBNS_CLASS_IN 0x01u\r
+#define dnsNBNS_NAME_FLAGS 0x6000u\r
+#define dnsNBNS_ENCODED_NAME_LENGTH 32\r
\r
/* If the queried NBNS name matches with the device's name,\r
the query will be responded to with these flags: */\r
-#define dnsNBNS_QUERY_RESPONSE_FLAGS ( 0x8500 )\r
+#define dnsNBNS_QUERY_RESPONSE_FLAGS ( 0x8500u )\r
\r
/* Flag DNS parsing errors in situations where an IPv4 address is the return\r
type. */\r
-#define dnsPARSE_ERROR 0UL\r
+#define dnsPARSE_ERROR 0uL\r
\r
/*\r
* Create a socket and bind it to the standard DNS port number. Return the\r
/*\r
* Create the DNS message in the zero copy buffer passed in the first parameter.\r
*/\r
-static size_t prvCreateDNSMessage( uint8_t *pucUDPPayloadBuffer, const char *pcHostName, TickType_t xIdentifier );\r
+static size_t prvCreateDNSMessage( uint8_t *pucUDPPayloadBuffer,\r
+ const char *pcHostName,\r
+ TickType_t uxIdentifier );\r
\r
/*\r
* Simple routine that jumps over the NAME field of a resource record.\r
*/\r
-static uint8_t *prvSkipNameField( uint8_t *pucByte, size_t xSourceLen );\r
+static uint8_t * prvSkipNameField( uint8_t *pucByte,\r
+ size_t uxSourceLen );\r
\r
/*\r
* Process a response packet from a DNS server.\r
+ * The parameter 'xExpected' indicates whether the identifier in the reply\r
+ * was expected, and thus if the DNS cache may be updated with the reply.\r
*/\r
-static uint32_t prvParseDNSReply( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, TickType_t xIdentifier );\r
+static uint32_t prvParseDNSReply( uint8_t *pucUDPPayloadBuffer,\r
+ size_t uxBufferLength,\r
+ BaseType_t xExpected );\r
\r
/*\r
- * Prepare and send a message to a DNS server. 'xReadTimeOut_ms' will be passed as\r
+ * Prepare and send a message to a DNS server. 'uxReadTimeOut_ticks' will be passed as\r
* zero, in case the user has supplied a call-back function.\r
*/\r
-static uint32_t prvGetHostByName( const char *pcHostName, TickType_t xIdentifier, TickType_t xReadTimeOut_ms );\r
+static uint32_t prvGetHostByName( const char *pcHostName,\r
+ TickType_t uxIdentifier,\r
+ TickType_t uxReadTimeOut_ticks );\r
\r
/*\r
* The NBNS and the LLMNR protocol share this reply function.\r
*/\r
#if( ( ipconfigUSE_NBNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) )\r
- static void prvReplyDNSMessage( NetworkBufferDescriptor_t *pxNetworkBuffer, BaseType_t lNetLength );\r
+ static void prvReplyDNSMessage( NetworkBufferDescriptor_t *pxNetworkBuffer,\r
+ BaseType_t lNetLength );\r
#endif\r
\r
#if( ipconfigUSE_NBNS == 1 )\r
- static portINLINE void prvTreatNBNS( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, uint32_t ulIPAddress );\r
+ static portINLINE void prvTreatNBNS( uint8_t *pucUDPPayloadBuffer,\r
+ size_t uxBufferLength,\r
+ uint32_t ulIPAddress );\r
#endif /* ipconfigUSE_NBNS */\r
\r
+\r
+#if( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 )\r
+ static uint8_t * prvReadNameField( uint8_t *pucByte,\r
+ size_t uxSourceLen,\r
+ char *pcName,\r
+ size_t uxLen );\r
+#endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */\r
+\r
#if( ipconfigUSE_DNS_CACHE == 1 )\r
- static uint8_t *prvReadNameField( uint8_t *pucByte, size_t xSourceLen, char *pcName, size_t xLen );\r
- static void prvProcessDNSCache( const char *pcName, uint32_t *pulIP, uint32_t ulTTL, BaseType_t xLookUp );\r
+ static void prvProcessDNSCache( const char *pcName,\r
+ uint32_t *pulIP,\r
+ uint32_t ulTTL,\r
+ BaseType_t xLookUp );\r
\r
typedef struct xDNS_CACHE_TABLE_ROW\r
{\r
- uint32_t ulIPAddress; /* The IP address of an ARP cache entry. */\r
- char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ]; /* The name of the host */\r
- uint32_t ulTTL; /* Time-to-Live (in seconds) from the DNS server. */\r
+ uint32_t ulIPAddress; /* The IP address of an ARP cache entry. */\r
+ char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ]; /* The name of the host */\r
+ uint32_t ulTTL; /* Time-to-Live (in seconds) from the DNS server. */\r
uint32_t ulTimeWhenAddedInSeconds;\r
} DNSCacheRow_t;\r
\r
\r
#if( ipconfigUSE_LLMNR == 1 )\r
const MACAddress_t xLLMNR_MacAdress = { { 0x01, 0x00, 0x5e, 0x00, 0x00, 0xfc } };\r
-#endif /* ipconfigUSE_LLMNR == 1 */\r
+#endif /* ipconfigUSE_LLMNR == 1 */\r
\r
/*-----------------------------------------------------------*/\r
\r
struct xLLMNRAnswer\r
{\r
uint8_t ucNameCode;\r
- uint8_t ucNameOffset; /* The name is not repeated in the answer, only the offset is given with "0xc0 <offs>" */\r
+ uint8_t ucNameOffset; /* The name is not repeated in the answer, only the offset is given with "0xc0 <offs>" */\r
uint16_t usType;\r
uint16_t usClass;\r
uint32_t ulTTL;\r
uint16_t usClass;\r
uint32_t ulTTL;\r
uint16_t usDataLength;\r
- uint16_t usNbFlags; /* NetBIOS flags 0x6000 : IP-address, big-endian */\r
+ uint16_t usNbFlags; /* NetBIOS flags 0x6000 : IP-address, big-endian */\r
uint32_t ulIPAddress;\r
}\r
#include "pack_struct_end.h"\r
typedef struct xNBNSAnswer NBNSAnswer_t;\r
\r
-#endif /* ipconfigUSE_NBNS == 1 */\r
+ #endif /* ipconfigUSE_NBNS == 1 */\r
\r
/*-----------------------------------------------------------*/\r
\r
#if( ipconfigUSE_DNS_CACHE == 1 )\r
uint32_t FreeRTOS_dnslookup( const char *pcHostName )\r
{\r
- uint32_t ulIPAddress = 0UL;\r
+ uint32_t ulIPAddress = 0uL;\r
+\r
prvProcessDNSCache( pcHostName, &ulIPAddress, 0, pdTRUE );\r
return ulIPAddress;\r
}\r
#endif /* ipconfigUSE_DNS_CACHE == 1 */\r
/*-----------------------------------------------------------*/\r
\r
-#if( ipconfigDNS_USE_CALLBACKS != 0 )\r
+#if( ipconfigDNS_USE_CALLBACKS == 1 )\r
\r
- typedef struct xDNS_Callback {\r
- TickType_t xRemaningTime; /* Timeout in ms */\r
+ typedef struct xDNS_Callback\r
+ {\r
+ TickType_t uxRemaningTime; /* Timeout in ms */\r
FOnDNSEvent pCallbackFunction; /* Function to be called when the address has been found or when a timeout has beeen reached */\r
- TimeOut_t xTimeoutState;\r
+ TimeOut_t uxTimeoutState;\r
void *pvSearchID;\r
struct xLIST_ITEM xListItem;\r
char pcName[ 1 ];\r
/* Define FreeRTOS_gethostbyname() as a normal blocking call. */\r
uint32_t FreeRTOS_gethostbyname( const char *pcHostName )\r
{\r
- return FreeRTOS_gethostbyname_a( pcHostName, ( FOnDNSEvent ) NULL, ( void* )NULL, 0 );\r
+ return FreeRTOS_gethostbyname_a( pcHostName, ( FOnDNSEvent ) NULL, ( void * ) NULL, 0 );\r
}\r
/*-----------------------------------------------------------*/\r
\r
void vDNSCheckCallBack( void *pvSearchID )\r
{\r
const ListItem_t *pxIterator;\r
- const MiniListItem_t* xEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xCallbackList );\r
+ const MiniListItem_t * xEnd = ( const MiniListItem_t * ) listGET_END_MARKER( &xCallbackList );\r
\r
vTaskSuspendAll();\r
{\r
for( pxIterator = ( const ListItem_t * ) listGET_NEXT( xEnd );\r
pxIterator != ( const ListItem_t * ) xEnd;\r
- )\r
+ )\r
{\r
- DNSCallback_t *pxCallback = ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator );\r
+ DNSCallback_t *pxCallback = ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator );\r
+\r
/* Move to the next item because we might remove this item */\r
- pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator );\r
+ pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator );\r
+\r
if( ( pvSearchID != NULL ) && ( pvSearchID == pxCallback->pvSearchID ) )\r
{\r
uxListRemove( &pxCallback->xListItem );\r
vPortFree( pxCallback );\r
}\r
- else if( xTaskCheckForTimeOut( &pxCallback->xTimeoutState, &pxCallback->xRemaningTime ) != pdFALSE )\r
+ else if( xTaskCheckForTimeOut( &pxCallback->uxTimeoutState, &pxCallback->uxRemaningTime ) != pdFALSE )\r
{\r
pxCallback->pCallbackFunction( pxCallback->pcName, pxCallback->pvSearchID, 0 );\r
uxListRemove( &pxCallback->xListItem );\r
\r
/* FreeRTOS_gethostbyname_a() was called along with callback parameters.\r
Store them in a list for later reference. */\r
- static void vDNSSetCallBack( const char *pcHostName, void *pvSearchID, FOnDNSEvent pCallbackFunction, TickType_t xTimeout, TickType_t xIdentifier );\r
- static void vDNSSetCallBack( const char *pcHostName, void *pvSearchID, FOnDNSEvent pCallbackFunction, TickType_t xTimeout, TickType_t xIdentifier )\r
+ static void vDNSSetCallBack( const char *pcHostName,\r
+ void *pvSearchID,\r
+ FOnDNSEvent pCallbackFunction,\r
+ TickType_t uxTimeout,\r
+ TickType_t uxIdentifier );\r
+ static void vDNSSetCallBack( const char *pcHostName,\r
+ void *pvSearchID,\r
+ FOnDNSEvent pCallbackFunction,\r
+ TickType_t uxTimeout,\r
+ TickType_t uxIdentifier )\r
{\r
- size_t lLength = strlen( pcHostName );\r
- DNSCallback_t *pxCallback = ( DNSCallback_t * )pvPortMalloc( sizeof( *pxCallback ) + lLength );\r
+ size_t lLength = strlen( pcHostName );\r
+ DNSCallback_t *pxCallback = ( DNSCallback_t * ) pvPortMalloc( sizeof( *pxCallback ) + lLength );\r
\r
/* Translate from ms to number of clock ticks. */\r
- xTimeout /= portTICK_PERIOD_MS;\r
+ uxTimeout /= portTICK_PERIOD_MS;\r
+\r
if( pxCallback != NULL )\r
{\r
if( listLIST_IS_EMPTY( &xCallbackList ) )\r
{\r
/* This is the first one, start the DNS timer to check for timeouts */\r
- vIPReloadDNSTimer( FreeRTOS_min_uint32( 1000U, xTimeout ) );\r
+ vIPReloadDNSTimer( FreeRTOS_min_uint32( 1000U, uxTimeout ) );\r
}\r
+\r
strcpy( pxCallback->pcName, pcHostName );\r
pxCallback->pCallbackFunction = pCallbackFunction;\r
pxCallback->pvSearchID = pvSearchID;\r
- pxCallback->xRemaningTime = xTimeout;\r
- vTaskSetTimeOutState( &pxCallback->xTimeoutState );\r
- listSET_LIST_ITEM_OWNER( &( pxCallback->xListItem ), ( void* ) pxCallback );\r
- listSET_LIST_ITEM_VALUE( &( pxCallback->xListItem ), xIdentifier );\r
+ pxCallback->uxRemaningTime = uxTimeout;\r
+ vTaskSetTimeOutState( &pxCallback->uxTimeoutState );\r
+ listSET_LIST_ITEM_OWNER( &( pxCallback->xListItem ), ( void * ) pxCallback );\r
+ listSET_LIST_ITEM_VALUE( &( pxCallback->xListItem ), uxIdentifier );\r
vTaskSuspendAll();\r
{\r
vListInsertEnd( &xCallbackList, &pxCallback->xListItem );\r
/*-----------------------------------------------------------*/\r
\r
/* A DNS reply was received, see if there is any matching entry and\r
- call the handler. */\r
- static void vDNSDoCallback( TickType_t xIdentifier, const char *pcName, uint32_t ulIPAddress );\r
- static void vDNSDoCallback( TickType_t xIdentifier, const char *pcName, uint32_t ulIPAddress )\r
+ call the handler. Returns pdTRUE if uxIdentifier was recognised. */\r
+ static BaseType_t xDNSDoCallback( TickType_t uxIdentifier,\r
+ const char *pcName,\r
+ uint32_t ulIPAddress );\r
+ static BaseType_t xDNSDoCallback( TickType_t uxIdentifier,\r
+ const char *pcName,\r
+ uint32_t ulIPAddress )\r
{\r
- const ListItem_t *pxIterator;\r
- const MiniListItem_t* xEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xCallbackList );\r
+ BaseType_t xResult = pdFALSE;\r
+ const ListItem_t *pxIterator;\r
+ const MiniListItem_t * xEnd = ( const MiniListItem_t * ) listGET_END_MARKER( &xCallbackList );\r
\r
vTaskSuspendAll();\r
{\r
pxIterator != ( const ListItem_t * ) xEnd;\r
pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) )\r
{\r
- if( listGET_LIST_ITEM_VALUE( pxIterator ) == xIdentifier )\r
+ /* The cast will take away the 'configLIST_VOLATILE' */\r
+ if( uxIdentifier == ( TickType_t ) listGET_LIST_ITEM_VALUE( pxIterator ) )\r
{\r
- DNSCallback_t *pxCallback = ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator );\r
+ DNSCallback_t *pxCallback = ( DNSCallback_t * ) listGET_LIST_ITEM_OWNER( pxIterator );\r
+\r
pxCallback->pCallbackFunction( pcName, pxCallback->pvSearchID, ulIPAddress );\r
uxListRemove( &pxCallback->xListItem );\r
vPortFree( pxCallback );\r
+\r
if( listLIST_IS_EMPTY( &xCallbackList ) )\r
{\r
+ /* The list of outstanding requests is empty. No need for periodic polling. */\r
vIPSetDnsTimerEnableState( pdFALSE );\r
}\r
+\r
+ xResult = pdTRUE;\r
break;\r
}\r
}\r
}\r
xTaskResumeAll();\r
+ return xResult;\r
}\r
\r
-#endif /* ipconfigDNS_USE_CALLBACKS != 0 */\r
+#endif /* ipconfigDNS_USE_CALLBACKS == 1 */\r
/*-----------------------------------------------------------*/\r
\r
#if( ipconfigDNS_USE_CALLBACKS == 0 )\r
-uint32_t FreeRTOS_gethostbyname( const char *pcHostName )\r
+ uint32_t FreeRTOS_gethostbyname( const char *pcHostName )\r
#else\r
-uint32_t FreeRTOS_gethostbyname_a( const char *pcHostName, FOnDNSEvent pCallback, void *pvSearchID, TickType_t xTimeout )\r
+ uint32_t FreeRTOS_gethostbyname_a( const char *pcHostName,\r
+ FOnDNSEvent pCallback,\r
+ void *pvSearchID,\r
+ TickType_t uxTimeout )\r
#endif\r
{\r
-uint32_t ulIPAddress = 0UL;\r
-TickType_t xReadTimeOut_ms = ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME;\r
-TickType_t xIdentifier = 0;\r
+uint32_t ulIPAddress = 0uL;\r
+TickType_t uxReadTimeOut_ticks = ipconfigDNS_RECEIVE_BLOCK_TIME_TICKS;\r
+TickType_t uxIdentifier = 0u;\r
+BaseType_t xHasRandom = pdFALSE;\r
\r
- /* If the supplied hostname is IP address, convert it to uint32_t\r
- and return. */\r
- #if( ipconfigINCLUDE_FULL_INET_ADDR == 1 )\r
+ if( pcHostName != NULL )\r
{\r
- ulIPAddress = FreeRTOS_inet_addr( pcHostName );\r
- }\r
- #endif /* ipconfigINCLUDE_FULL_INET_ADDR == 1 */\r
+ /* If the supplied hostname is IP address, convert it to uint32_t\r
+ and return. */\r
+ #if( ipconfigINCLUDE_FULL_INET_ADDR == 1 )\r
+ {\r
+ ulIPAddress = FreeRTOS_inet_addr( pcHostName );\r
+ }\r
+ #endif /* ipconfigINCLUDE_FULL_INET_ADDR == 1 */\r
\r
- /* If a DNS cache is used then check the cache before issuing another DNS\r
- request. */\r
- #if( ipconfigUSE_DNS_CACHE == 1 )\r
- {\r
- if( ulIPAddress == 0UL )\r
+ /* If a DNS cache is used then check the cache before issuing another DNS\r
+ request. */\r
+ #if( ipconfigUSE_DNS_CACHE == 1 )\r
{\r
- ulIPAddress = FreeRTOS_dnslookup( pcHostName );\r
- if( ulIPAddress != 0 )\r
+ if( ulIPAddress == 0uL )\r
{\r
- FreeRTOS_debug_printf( ( "FreeRTOS_gethostbyname: found '%s' in cache: %lxip\n", pcHostName, ulIPAddress ) );\r
- }\r
- else\r
- {\r
- /* prvGetHostByName will be called to start a DNS lookup */\r
+ ulIPAddress = FreeRTOS_dnslookup( pcHostName );\r
+\r
+ if( ulIPAddress != 0 )\r
+ {\r
+ FreeRTOS_debug_printf( ( "FreeRTOS_gethostbyname: found '%s' in cache: %lxip\n", pcHostName, ulIPAddress ) );\r
+ }\r
+ else\r
+ {\r
+ /* prvGetHostByName will be called to start a DNS lookup. */\r
+ }\r
}\r
}\r
- }\r
- #endif /* ipconfigUSE_DNS_CACHE == 1 */\r
+ #endif /* ipconfigUSE_DNS_CACHE == 1 */\r
\r
- /* Generate a unique identifier. */\r
- if( 0 == ulIPAddress )\r
- {\r
- xIdentifier = ( TickType_t )ipconfigRAND32( );\r
- }\r
+ /* Generate a unique identifier. */\r
+ if( ulIPAddress == 0uL )\r
+ {\r
+ uint32_t ulNumber;\r
\r
- #if( ipconfigDNS_USE_CALLBACKS != 0 )\r
- {\r
- if( pCallback != NULL )\r
+ xHasRandom = xApplicationGetRandomNumber( &( ulNumber ) );\r
+ /* DNS identifiers are 16-bit. */\r
+ uxIdentifier = ( TickType_t ) ( ulNumber & 0xffffu );\r
+ /* ipconfigRAND32() may not return a non-zero value. */\r
+ }\r
+\r
+ #if( ipconfigDNS_USE_CALLBACKS == 1 )\r
{\r
- if( ulIPAddress == 0UL )\r
+ if( pCallback != NULL )\r
{\r
- /* The user has provided a callback function, so do not block on recvfrom() */\r
- if( 0 != xIdentifier )\r
+ if( ulIPAddress == 0uL )\r
{\r
- xReadTimeOut_ms = 0;\r
- vDNSSetCallBack( pcHostName, pvSearchID, pCallback, xTimeout, ( TickType_t )xIdentifier );\r
+ /* The user has provided a callback function, so do not block on recvfrom() */\r
+ if( xHasRandom != pdFALSE )\r
+ {\r
+ uxReadTimeOut_ticks = 0u;\r
+ vDNSSetCallBack( pcHostName, pvSearchID, pCallback, uxTimeout, uxIdentifier );\r
+ }\r
+ }\r
+ else\r
+ {\r
+ /* The IP address is known, do the call-back now. */\r
+ pCallback( pcHostName, pvSearchID, ulIPAddress );\r
}\r
- }\r
- else\r
- {\r
- /* The IP address is known, do the call-back now. */\r
- pCallback( pcHostName, pvSearchID, ulIPAddress );\r
}\r
}\r
- }\r
- #endif\r
+ #endif /* if ( ipconfigDNS_USE_CALLBACKS == 1 ) */\r
\r
- if( ( ulIPAddress == 0UL ) && ( 0 != xIdentifier ) )\r
- {\r
- ulIPAddress = prvGetHostByName( pcHostName, xIdentifier, xReadTimeOut_ms );\r
+ if( ( ulIPAddress == 0uL ) && ( xHasRandom != pdFALSE ) )\r
+ {\r
+ ulIPAddress = prvGetHostByName( pcHostName, uxIdentifier, uxReadTimeOut_ticks );\r
+ }\r
}\r
-\r
return ulIPAddress;\r
}\r
/*-----------------------------------------------------------*/\r
\r
-static uint32_t prvGetHostByName( const char *pcHostName, TickType_t xIdentifier, TickType_t xReadTimeOut_ms )\r
+static uint32_t prvGetHostByName( const char *pcHostName,\r
+ TickType_t uxIdentifier,\r
+ TickType_t uxReadTimeOut_ticks )\r
{\r
struct freertos_sockaddr xAddress;\r
Socket_t xDNSSocket;\r
-uint32_t ulIPAddress = 0UL;\r
+uint32_t ulIPAddress = 0uL;\r
uint8_t *pucUDPPayloadBuffer;\r
uint32_t ulAddressLength = sizeof( struct freertos_sockaddr );\r
BaseType_t xAttempt;\r
int32_t lBytes;\r
-size_t xPayloadLength, xExpectedPayloadLength;\r
-TickType_t xWriteTimeOut_ms = ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME;\r
+size_t uxPayloadLength, uxExpectedPayloadLength;\r
+TickType_t uxWriteTimeOut_ticks = ipconfigDNS_SEND_BLOCK_TIME_TICKS;\r
\r
#if( ipconfigUSE_LLMNR == 1 )\r
BaseType_t bHasDot = pdFALSE;\r
if not then LLMNR can be used as the lookup method. */\r
#if( ipconfigUSE_LLMNR == 1 )\r
{\r
- const char *pucPtr;\r
+ const char *pucPtr;\r
+\r
for( pucPtr = pcHostName; *pucPtr; pucPtr++ )\r
{\r
if( *pucPtr == '.' )\r
\r
/* Two is added at the end for the count of characters in the first\r
subdomain part and the string end byte. */\r
- xExpectedPayloadLength = sizeof( DNSMessage_t ) + strlen( pcHostName ) + sizeof( uint16_t ) + sizeof( uint16_t ) + 2u;\r
+ uxExpectedPayloadLength = sizeof( DNSMessage_t ) + strlen( pcHostName ) + sizeof( uint16_t ) + sizeof( uint16_t ) + 2u;\r
\r
xDNSSocket = prvCreateDNSSocket();\r
\r
if( xDNSSocket != NULL )\r
{\r
- FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xWriteTimeOut_ms, sizeof( TickType_t ) );\r
- FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xReadTimeOut_ms, sizeof( TickType_t ) );\r
+ FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &uxWriteTimeOut_ticks, sizeof( TickType_t ) );\r
+ FreeRTOS_setsockopt( xDNSSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &uxReadTimeOut_ticks, sizeof( TickType_t ) );\r
\r
for( xAttempt = 0; xAttempt < ipconfigDNS_REQUEST_ATTEMPTS; xAttempt++ )\r
{\r
/* Get a buffer. This uses a maximum delay, but the delay will be\r
capped to ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS so the return value\r
still needs to be tested. */\r
- pucUDPPayloadBuffer = ( uint8_t * ) FreeRTOS_GetUDPPayloadBuffer( xExpectedPayloadLength, portMAX_DELAY );\r
+ pucUDPPayloadBuffer = ( uint8_t * ) FreeRTOS_GetUDPPayloadBuffer( uxExpectedPayloadLength, portMAX_DELAY );\r
\r
if( pucUDPPayloadBuffer != NULL )\r
{\r
/* Create the message in the obtained buffer. */\r
- xPayloadLength = prvCreateDNSMessage( pucUDPPayloadBuffer, pcHostName, xIdentifier );\r
+ uxPayloadLength = prvCreateDNSMessage( pucUDPPayloadBuffer, pcHostName, uxIdentifier );\r
\r
iptraceSENDING_DNS_REQUEST();\r
\r
if( bHasDot == pdFALSE )\r
{\r
/* Use LLMNR addressing. */\r
- ( ( DNSMessage_t * ) pucUDPPayloadBuffer) -> usFlags = 0;\r
- xAddress.sin_addr = ipLLMNR_IP_ADDR; /* Is in network byte order. */\r
+ ( ( DNSMessage_t * ) pucUDPPayloadBuffer )->usFlags = 0;\r
+ xAddress.sin_addr = ipLLMNR_IP_ADDR; /* Is in network byte order. */\r
xAddress.sin_port = FreeRTOS_ntohs( ipLLMNR_PORT );\r
}\r
else\r
xAddress.sin_port = dnsDNS_PORT;\r
}\r
\r
- ulIPAddress = 0UL;\r
+ ulIPAddress = 0uL;\r
\r
- if( FreeRTOS_sendto( xDNSSocket, pucUDPPayloadBuffer, xPayloadLength, FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) != 0 )\r
+ if( FreeRTOS_sendto( xDNSSocket, pucUDPPayloadBuffer, uxPayloadLength, FREERTOS_ZERO_COPY, &xAddress, sizeof( xAddress ) ) != 0 )\r
{\r
/* Wait for the reply. */\r
lBytes = FreeRTOS_recvfrom( xDNSSocket, &pucUDPPayloadBuffer, 0, FREERTOS_ZERO_COPY, &xAddress, &ulAddressLength );\r
\r
if( lBytes > 0 )\r
{\r
+ BaseType_t xExpected;\r
+ DNSMessage_t *pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;\r
+\r
+ /* See if the identifiers match. */\r
+ if( uxIdentifier == ( TickType_t ) pxDNSMessageHeader->usIdentifier )\r
+ {\r
+ xExpected = pdTRUE;\r
+ }\r
+ else\r
+ {\r
+ /* The reply was not expected. */\r
+ xExpected = pdFALSE;\r
+ }\r
+\r
/* The reply was received. Process it. */\r
- ulIPAddress = prvParseDNSReply( pucUDPPayloadBuffer, lBytes, xIdentifier );\r
+ #if( ipconfigDNS_USE_CALLBACKS == 0 )\r
+ /* It is useless to analyse the unexpected reply\r
+ unless asynchronous look-ups are enabled. */\r
+ if( xExpected != pdFALSE )\r
+ #endif /* ipconfigDNS_USE_CALLBACKS == 0 */\r
+ {\r
+ ulIPAddress = prvParseDNSReply( pucUDPPayloadBuffer, ( size_t ) lBytes, xExpected );\r
+ }\r
\r
/* Finished with the buffer. The zero copy interface\r
is being used, so the buffer must be freed by the\r
task. */\r
FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayloadBuffer );\r
\r
- if( ulIPAddress != 0UL )\r
+ if( ulIPAddress != 0uL )\r
{\r
/* All done. */\r
break;\r
FreeRTOS_ReleaseUDPPayloadBuffer( ( void * ) pucUDPPayloadBuffer );\r
}\r
}\r
+\r
+ if( uxReadTimeOut_ticks == 0u )\r
+ {\r
+ /* This DNS lookup is asynchronous, using a call-back:\r
+ send the request only once. */\r
+ break;\r
+ }\r
}\r
\r
/* Finished with the socket. */\r
}\r
/*-----------------------------------------------------------*/\r
\r
-static size_t prvCreateDNSMessage( uint8_t *pucUDPPayloadBuffer, const char *pcHostName, TickType_t xIdentifier )\r
+static size_t prvCreateDNSMessage( uint8_t *pucUDPPayloadBuffer,\r
+ const char *pcHostName,\r
+ TickType_t uxIdentifier )\r
{\r
DNSMessage_t *pxDNSMessageHeader;\r
uint8_t *pucStart, *pucByte;\r
DNSTail_t *pxTail;\r
static const DNSMessage_t xDefaultPartDNSHeader =\r
{\r
- 0, /* The identifier will be overwritten. */\r
- dnsOUTGOING_FLAGS, /* Flags set for standard query. */\r
- dnsONE_QUESTION, /* One question is being asked. */\r
- 0, /* No replies are included. */\r
- 0, /* No authorities. */\r
- 0 /* No additional authorities. */\r
+ 0, /* The identifier will be overwritten. */\r
+ dnsOUTGOING_FLAGS, /* Flags set for standard query. */\r
+ dnsONE_QUESTION, /* One question is being asked. */\r
+ 0, /* No replies are included. */\r
+ 0, /* No authorities. */\r
+ 0 /* No additional authorities. */\r
};\r
\r
/* Copy in the const part of the header. */\r
\r
/* Write in a unique identifier. */\r
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;\r
- pxDNSMessageHeader->usIdentifier = ( uint16_t ) xIdentifier;\r
+ pxDNSMessageHeader->usIdentifier = ( uint16_t ) uxIdentifier;\r
\r
/* Create the resource record at the end of the header. First\r
find the end of the header. */\r
( *pucStart )--;\r
\r
pucStart = pucByte;\r
-\r
} while( *pucByte != 0x00 );\r
\r
/* Finish off the record. */\r
\r
- pxTail = (DNSTail_t *)( pucByte + 1 );\r
+ pxTail = ( DNSTail_t * ) ( pucByte + 1 );\r
\r
- vSetField16( pxTail, DNSTail_t, usType, dnsTYPE_A_HOST ); /* Type A: host */\r
- vSetField16( pxTail, DNSTail_t, usClass, dnsCLASS_IN ); /* 1: Class IN */\r
+ vSetField16( pxTail, DNSTail_t, usType, dnsTYPE_A_HOST ); /* Type A: host */\r
+ vSetField16( pxTail, DNSTail_t, usClass, dnsCLASS_IN ); /* 1: Class IN */\r
\r
/* Return the total size of the generated message, which is the space from\r
the last written byte to the beginning of the buffer. */\r
}\r
/*-----------------------------------------------------------*/\r
\r
-#if( ipconfigUSE_DNS_CACHE == 1 )\r
+#if( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 )\r
\r
- static uint8_t *prvReadNameField( uint8_t *pucByte, size_t xSourceLen, char *pcName, size_t xDestLen )\r
+ static uint8_t * prvReadNameField( uint8_t *pucByte,\r
+ size_t uxSourceLen,\r
+ char *pcName,\r
+ size_t uxDestLen )\r
{\r
- size_t xNameLen = 0;\r
+ size_t uxNameLen = 0;\r
BaseType_t xCount;\r
\r
- if( 0 == xSourceLen )\r
+ if( 0 == uxSourceLen )\r
{\r
return NULL;\r
}\r
if( ( *pucByte & dnsNAME_IS_OFFSET ) == dnsNAME_IS_OFFSET )\r
{\r
/* Jump over the two byte offset. */\r
- if( xSourceLen > sizeof( uint16_t ) )\r
+ if( uxSourceLen > sizeof( uint16_t ) )\r
{\r
pucByte += sizeof( uint16_t );\r
}\r
else\r
{\r
/* pucByte points to the full name. Walk over the string. */\r
- while( ( NULL != pucByte ) && ( *pucByte != 0x00 ) && ( xSourceLen > 1 ) )\r
+ while( ( NULL != pucByte ) && ( *pucByte != 0x00u ) && ( uxSourceLen > 1u ) )\r
{\r
/* If this is not the first time through the loop, then add a\r
separator in the output. */\r
- if( ( xNameLen > 0 ) && ( xNameLen < ( xDestLen - 1 ) ) )\r
+ if( ( uxNameLen > 0 ) && ( uxNameLen < ( uxDestLen - 1u ) ) )\r
{\r
- pcName[ xNameLen++ ] = '.';\r
+ pcName[ uxNameLen++ ] = '.';\r
}\r
\r
/* Process the first/next sub-string. */\r
- for( xCount = *(pucByte++), xSourceLen--;\r
- xCount-- && xSourceLen > 1;\r
- pucByte++, xSourceLen-- )\r
+ for( xCount = *( pucByte++ ), uxSourceLen--;\r
+ xCount-- && uxSourceLen > 1u;\r
+ pucByte++, uxSourceLen-- )\r
{\r
- if( xNameLen < xDestLen - 1 )\r
+ if( uxNameLen < uxDestLen - 1u )\r
{\r
- pcName[ xNameLen++ ] = *( ( char * )pucByte );\r
+ pcName[ uxNameLen++ ] = *( ( char * ) pucByte );\r
}\r
else\r
{\r
if( 0x00 == *pucByte )\r
{\r
pucByte++;\r
- xSourceLen--;\r
- pcName[ xNameLen++ ] = '\0';\r
+ uxSourceLen--;\r
+ pcName[ uxNameLen++ ] = '\0';\r
}\r
else\r
{\r
\r
return pucByte;\r
}\r
-#endif /* ipconfigUSE_DNS_CACHE == 1 */\r
+#endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */\r
/*-----------------------------------------------------------*/\r
\r
-static uint8_t *prvSkipNameField( uint8_t *pucByte, size_t xSourceLen )\r
+static uint8_t * prvSkipNameField( uint8_t *pucByte,\r
+ size_t uxSourceLen )\r
{\r
- size_t xChunkLength;\r
+size_t uxChunkLength;\r
\r
- if( 0 == xSourceLen )\r
+ if( 0u == uxSourceLen )\r
{\r
return NULL;\r
}\r
if( ( *pucByte & dnsNAME_IS_OFFSET ) == dnsNAME_IS_OFFSET )\r
{\r
/* Jump over the two byte offset. */\r
- if( xSourceLen > sizeof( uint16_t ) )\r
+ if( uxSourceLen > sizeof( uint16_t ) )\r
{\r
pucByte += sizeof( uint16_t );\r
}\r
else\r
{\r
/* pucByte points to the full name. Walk over the string. */\r
- while( ( *pucByte != 0x00 ) && ( xSourceLen > 1 ) )\r
+ while( ( *pucByte != 0x00u ) && ( uxSourceLen > 1u ) )\r
{\r
- xChunkLength = *pucByte + 1;\r
+ uxChunkLength = *pucByte + 1u;\r
\r
- if( xSourceLen > xChunkLength )\r
+ if( uxSourceLen > uxChunkLength )\r
{\r
- xSourceLen -= xChunkLength;\r
- pucByte += xChunkLength;\r
+ uxSourceLen -= uxChunkLength;\r
+ pucByte += uxChunkLength;\r
}\r
else\r
{\r
/* Confirm that a fully formed name was found. */\r
if( NULL != pucByte )\r
{\r
- if( 0x00 == *pucByte )\r
+ if( 0x00u == *pucByte )\r
{\r
pucByte++;\r
}\r
}\r
/*-----------------------------------------------------------*/\r
\r
+/* The function below will only be called :\r
+when ipconfigDNS_USE_CALLBACKS == 1\r
+when ipconfigUSE_LLMNR == 1\r
+for testing purposes, by the module iot_test_freertos_tcp.c\r
+*/\r
uint32_t ulDNSHandlePacket( NetworkBufferDescriptor_t *pxNetworkBuffer )\r
{\r
DNSMessage_t *pxDNSMessageHeader;\r
-\r
- if( pxNetworkBuffer->xDataLength >= sizeof( DNSMessage_t ) )\r
- {\r
- pxDNSMessageHeader = \r
- ( DNSMessage_t * )( pxNetworkBuffer->pucEthernetBuffer + sizeof( UDPPacket_t ) );\r
-\r
- prvParseDNSReply( ( uint8_t * )pxDNSMessageHeader,\r
- pxNetworkBuffer->xDataLength,\r
- ( uint32_t )pxDNSMessageHeader->usIdentifier );\r
- }\r
+size_t uxPayloadSize;\r
+\r
+ /* Only proceed if the payload length indicated in the header\r
+ appears to be valid. */\r
+ if( pxNetworkBuffer->xDataLength >= sizeof( UDPPacket_t ) )\r
+ {\r
+ uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );\r
+\r
+ if( uxPayloadSize >= sizeof( DNSMessage_t ) )\r
+ {\r
+ pxDNSMessageHeader =\r
+ ( DNSMessage_t * ) ( pxNetworkBuffer->pucEthernetBuffer + sizeof( UDPPacket_t ) );\r
+\r
+ /* The parameter pdFALSE indicates that the reply was not expected. */\r
+ prvParseDNSReply( ( uint8_t * ) pxDNSMessageHeader,\r
+ uxPayloadSize,\r
+ pdFALSE );\r
+ }\r
+ }\r
\r
/* The packet was not consumed. */\r
return pdFAIL;\r
\r
#if( ipconfigUSE_NBNS == 1 )\r
\r
- uint32_t ulNBNSHandlePacket (NetworkBufferDescriptor_t *pxNetworkBuffer )\r
+ uint32_t ulNBNSHandlePacket( NetworkBufferDescriptor_t * pxNetworkBuffer )\r
{\r
UDPPacket_t *pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;\r
uint8_t *pucUDPPayloadBuffer = pxNetworkBuffer->pucEthernetBuffer + sizeof( UDPPacket_t );\r
+ size_t uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );\r
\r
- /* The network buffer data length has already been set to the \r
+ /* The network buffer data length has already been set to the\r
length of the UDP payload. */\r
prvTreatNBNS( pucUDPPayloadBuffer,\r
- pxNetworkBuffer->xDataLength,\r
+ uxPayloadSize,\r
pxUDPPacket->xIPHeader.ulSourceIPAddress );\r
\r
/* The packet was not consumed. */\r
#endif /* ipconfigUSE_NBNS */\r
/*-----------------------------------------------------------*/\r
\r
-static uint32_t prvParseDNSReply( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, TickType_t xIdentifier )\r
+static uint32_t prvParseDNSReply( uint8_t *pucUDPPayloadBuffer,\r
+ size_t uxBufferLength,\r
+ BaseType_t xExpected )\r
{\r
DNSMessage_t *pxDNSMessageHeader;\r
DNSAnswerRecord_t *pxDNSAnswerRecord;\r
-uint32_t ulIPAddress = 0UL;\r
+uint32_t ulIPAddress = 0uL;\r
#if( ipconfigUSE_LLMNR == 1 )\r
char *pcRequestedName = NULL;\r
#endif\r
uint8_t *pucByte;\r
-size_t xSourceBytesRemaining;\r
+size_t uxSourceBytesRemaining;\r
uint16_t x, usDataLength, usQuestions;\r
+BaseType_t xDoStore = xExpected;\r
#if( ipconfigUSE_LLMNR == 1 )\r
uint16_t usType = 0, usClass = 0;\r
#endif\r
-#if( ipconfigUSE_DNS_CACHE == 1 )\r
+#if( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 )\r
char pcName[ ipconfigDNS_CACHE_NAME_LENGTH ] = "";\r
#endif\r
\r
/* Ensure that the buffer is of at least minimal DNS message length. */\r
- if( xBufferLength < sizeof( DNSMessage_t ) )\r
+ if( uxBufferLength < sizeof( DNSMessage_t ) )\r
{\r
return dnsPARSE_ERROR;\r
}\r
- else\r
- {\r
- xSourceBytesRemaining = xBufferLength;\r
- }\r
+\r
+ uxSourceBytesRemaining = uxBufferLength;\r
\r
/* Parse the DNS message header. */\r
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;\r
\r
- if( pxDNSMessageHeader->usIdentifier == ( uint16_t ) xIdentifier )\r
+ /* Introduce a do {} while (0) to allow the use of breaks. */\r
+ do\r
{\r
/* Start at the first byte after the header. */\r
pucByte = pucUDPPayloadBuffer + sizeof( DNSMessage_t );\r
- xSourceBytesRemaining -= sizeof( DNSMessage_t );\r
+ uxSourceBytesRemaining -= sizeof( DNSMessage_t );\r
\r
/* Skip any question records. */\r
usQuestions = FreeRTOS_ntohs( pxDNSMessageHeader->usQuestions );\r
+\r
for( x = 0; x < usQuestions; x++ )\r
{\r
#if( ipconfigUSE_LLMNR == 1 )\r
}\r
#endif\r
\r
-#if( ipconfigUSE_DNS_CACHE == 1 )\r
+#if( ipconfigUSE_DNS_CACHE == 1 ) || ( ipconfigDNS_USE_CALLBACKS == 1 )\r
if( x == 0 )\r
{\r
pucByte = prvReadNameField( pucByte,\r
- xSourceBytesRemaining,\r
+ uxSourceBytesRemaining,\r
pcName,\r
sizeof( pcName ) );\r
\r
{\r
return dnsPARSE_ERROR;\r
}\r
- else\r
- {\r
- xSourceBytesRemaining = ( pucUDPPayloadBuffer + xBufferLength ) - pucByte;\r
- }\r
+\r
+ uxSourceBytesRemaining = ( pucUDPPayloadBuffer + uxBufferLength ) - pucByte;\r
}\r
else\r
-#endif /* ipconfigUSE_DNS_CACHE */\r
+#endif /* ipconfigUSE_DNS_CACHE || ipconfigDNS_USE_CALLBACKS */\r
{\r
/* Skip the variable length pcName field. */\r
pucByte = prvSkipNameField( pucByte,\r
- xSourceBytesRemaining );\r
+ uxSourceBytesRemaining );\r
\r
/* Check for a malformed response. */\r
if( NULL == pucByte )\r
{\r
return dnsPARSE_ERROR;\r
}\r
- else\r
- {\r
- xSourceBytesRemaining = pucUDPPayloadBuffer + xBufferLength - pucByte;\r
- }\r
+\r
+ uxSourceBytesRemaining = ( size_t )\r
+ ( pucUDPPayloadBuffer + uxBufferLength - pucByte );\r
}\r
\r
/* Check the remaining buffer size. */\r
- if( xSourceBytesRemaining >= sizeof( uint32_t ) )\r
+ if( uxSourceBytesRemaining >= sizeof( uint32_t ) )\r
{\r
#if( ipconfigUSE_LLMNR == 1 )\r
{\r
- /* usChar2u16 returns value in host endianness */\r
+ /* usChar2u16 returns value in host endianness. */\r
usType = usChar2u16( pucByte );\r
usClass = usChar2u16( pucByte + 2 );\r
}\r
\r
/* Skip the type and class fields. */\r
pucByte += sizeof( uint32_t );\r
- xSourceBytesRemaining -= sizeof( uint32_t );\r
+ uxSourceBytesRemaining -= sizeof( uint32_t );\r
}\r
else\r
{\r
for( x = 0; x < pxDNSMessageHeader->usAnswers; x++ )\r
{\r
pucByte = prvSkipNameField( pucByte,\r
- xSourceBytesRemaining );\r
+ uxSourceBytesRemaining );\r
\r
/* Check for a malformed response. */\r
if( NULL == pucByte )\r
{\r
return dnsPARSE_ERROR;\r
}\r
- else\r
- {\r
- xSourceBytesRemaining = pucUDPPayloadBuffer + xBufferLength - pucByte;\r
- }\r
+\r
+ uxSourceBytesRemaining = ( size_t )\r
+ ( pucUDPPayloadBuffer + uxBufferLength - pucByte );\r
\r
/* Is there enough data for an IPv4 A record answer and, if so,\r
is this an A record? */\r
- if( xSourceBytesRemaining >= sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t ) &&\r
- usChar2u16( pucByte ) == dnsTYPE_A_HOST )\r
+ if( ( uxSourceBytesRemaining >= ( sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t ) ) ) &&\r
+ ( usChar2u16( pucByte ) == dnsTYPE_A_HOST ) )\r
{\r
/* This is the required record type and is of sufficient size. */\r
- pxDNSAnswerRecord = ( DNSAnswerRecord_t * )pucByte;\r
+ pxDNSAnswerRecord = ( DNSAnswerRecord_t * ) pucByte;\r
\r
/* Sanity check the data length of an IPv4 answer. */\r
if( FreeRTOS_ntohs( pxDNSAnswerRecord->usDataLength ) == sizeof( uint32_t ) )\r
pucByte + sizeof( DNSAnswerRecord_t ),\r
sizeof( uint32_t ) );\r
\r
- #if( ipconfigUSE_DNS_CACHE == 1 )\r
+ #if( ipconfigDNS_USE_CALLBACKS == 1 )\r
{\r
- prvProcessDNSCache( pcName, &ulIPAddress, pxDNSAnswerRecord->ulTTL, pdFALSE );\r
+ /* See if any asynchronous call was made to FreeRTOS_gethostbyname_a() */\r
+ if( xDNSDoCallback( ( TickType_t ) pxDNSMessageHeader->usIdentifier, pcName, ulIPAddress ) != pdFALSE )\r
+ {\r
+ /* This device has requested this DNS look-up.\r
+ The result may be stored in the DNS cache. */\r
+ xDoStore = pdTRUE;\r
+ }\r
}\r
- #endif /* ipconfigUSE_DNS_CACHE */\r
- #if( ipconfigDNS_USE_CALLBACKS != 0 )\r
+ #endif /* ipconfigDNS_USE_CALLBACKS == 1 */\r
+ #if( ipconfigUSE_DNS_CACHE == 1 )\r
{\r
- /* See if any asynchronous call was made to FreeRTOS_gethostbyname_a() */\r
- vDNSDoCallback( ( TickType_t ) pxDNSMessageHeader->usIdentifier, pcName, ulIPAddress );\r
+ /* The reply will only be stored in the DNS cache when the\r
+ request was issued by this device. */\r
+ if( xDoStore != pdFALSE )\r
+ {\r
+ prvProcessDNSCache( pcName, &ulIPAddress, pxDNSAnswerRecord->ulTTL, pdFALSE );\r
+ }\r
+\r
+ /* Show what has happened. */\r
+ FreeRTOS_printf( ( "DNS[0x%04X]: The answer to '%s' (%xip) will%s be stored\n",\r
+ ( unsigned ) pxDNSMessageHeader->usIdentifier,\r
+ pcName,\r
+ ( unsigned ) FreeRTOS_ntohl( ulIPAddress ),\r
+ ( xDoStore != 0 ) ? "" : " NOT" ) );\r
}\r
- #endif /* ipconfigDNS_USE_CALLBACKS != 0 */\r
+ #endif /* ipconfigUSE_DNS_CACHE */\r
}\r
\r
pucByte += sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t );\r
- xSourceBytesRemaining -= ( sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t ) );\r
+ uxSourceBytesRemaining -= ( sizeof( DNSAnswerRecord_t ) + sizeof( uint32_t ) );\r
break;\r
}\r
- else if( xSourceBytesRemaining >= sizeof( DNSAnswerRecord_t ) )\r
+ else if( uxSourceBytesRemaining >= sizeof( DNSAnswerRecord_t ) )\r
{\r
/* It's not an A record, so skip it. Get the header location\r
and then jump over the header. */\r
- pxDNSAnswerRecord = ( DNSAnswerRecord_t * )pucByte;\r
+ pxDNSAnswerRecord = ( DNSAnswerRecord_t * ) pucByte;\r
pucByte += sizeof( DNSAnswerRecord_t );\r
- xSourceBytesRemaining -= sizeof( DNSAnswerRecord_t );\r
+ uxSourceBytesRemaining -= sizeof( DNSAnswerRecord_t );\r
\r
/* Determine the length of the answer data from the header. */\r
usDataLength = FreeRTOS_ntohs( pxDNSAnswerRecord->usDataLength );\r
\r
/* Jump over the answer. */\r
- if( xSourceBytesRemaining >= usDataLength )\r
+ if( uxSourceBytesRemaining >= usDataLength )\r
{\r
pucByte += usDataLength;\r
- xSourceBytesRemaining -= usDataLength;\r
+ uxSourceBytesRemaining -= usDataLength;\r
}\r
else\r
{\r
}\r
}\r
}\r
+\r
#if( ipconfigUSE_LLMNR == 1 )\r
else if( usQuestions && ( usType == dnsTYPE_A_HOST ) && ( usClass == dnsCLASS_IN ) )\r
{\r
/* If this is not a reply to our DNS request, it might an LLMNR\r
request. */\r
- if( xApplicationDNSQueryHook ( ( pcRequestedName + 1 ) ) )\r
+ if( xApplicationDNSQueryHook( ( pcRequestedName + 1 ) ) )\r
{\r
int16_t usLength;\r
NetworkBufferDescriptor_t *pxNewBuffer = NULL;\r
\r
if( ( xBufferAllocFixedSize == pdFALSE ) && ( pxNetworkBuffer != NULL ) )\r
{\r
- BaseType_t xDataLength = xBufferLength + sizeof( UDPHeader_t ) + sizeof( EthernetHeader_t ) + sizeof( IPHeader_t );\r
+ BaseType_t xDataLength = uxBufferLength + sizeof( UDPHeader_t ) + sizeof( EthernetHeader_t ) + sizeof( IPHeader_t );\r
\r
- /* The field xDataLength was set to the length of the UDP payload.\r
- The answer (reply) will be longer than the request, so the packet\r
- must be duplicaed into a bigger buffer */\r
+ /* Set the size of the outgoing packet. */\r
pxNetworkBuffer->xDataLength = xDataLength;\r
- pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, xDataLength + 16 );\r
+ pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, xDataLength + sizeof( LLMNRAnswer_t ) );\r
+\r
if( pxNewBuffer != NULL )\r
{\r
BaseType_t xOffset1, xOffset2;\r
pucByte = pucUDPPayloadBuffer + xOffset1;\r
pcRequestedName = ( char * ) ( pucUDPPayloadBuffer + xOffset2 );\r
pxDNSMessageHeader = ( DNSMessage_t * ) pucUDPPayloadBuffer;\r
-\r
}\r
else\r
{\r
pxNetworkBuffer = NULL;\r
}\r
}\r
+\r
if( pxNetworkBuffer != NULL )\r
{\r
- pxAnswer = (LLMNRAnswer_t *)pucByte;\r
+ pxAnswer = ( LLMNRAnswer_t * ) pucByte;\r
\r
/* We leave 'usIdentifier' and 'usQuestions' untouched */\r
- vSetField16( pxDNSMessageHeader, DNSMessage_t, usFlags, dnsLLMNR_FLAGS_IS_REPONSE ); /* Set the response flag */\r
- vSetField16( pxDNSMessageHeader, DNSMessage_t, usAnswers, 1 ); /* Provide a single answer */\r
- vSetField16( pxDNSMessageHeader, DNSMessage_t, usAuthorityRRs, 0 ); /* No authority */\r
- vSetField16( pxDNSMessageHeader, DNSMessage_t, usAdditionalRRs, 0 ); /* No additional info */\r
+ vSetField16( pxDNSMessageHeader, DNSMessage_t, usFlags, dnsLLMNR_FLAGS_IS_REPONSE ); /* Set the response flag */\r
+ vSetField16( pxDNSMessageHeader, DNSMessage_t, usAnswers, 1 ); /* Provide a single answer */\r
+ vSetField16( pxDNSMessageHeader, DNSMessage_t, usAuthorityRRs, 0 ); /* No authority */\r
+ vSetField16( pxDNSMessageHeader, DNSMessage_t, usAdditionalRRs, 0 ); /* No additional info */\r
\r
pxAnswer->ucNameCode = dnsNAME_IS_OFFSET;\r
- pxAnswer->ucNameOffset = ( uint8_t )( pcRequestedName - ( char * ) pucUDPPayloadBuffer );\r
+ pxAnswer->ucNameOffset = ( uint8_t ) ( pcRequestedName - ( char * ) pucUDPPayloadBuffer );\r
\r
- vSetField16( pxAnswer, LLMNRAnswer_t, usType, dnsTYPE_A_HOST ); /* Type A: host */\r
- vSetField16( pxAnswer, LLMNRAnswer_t, usClass, dnsCLASS_IN ); /* 1: Class IN */\r
+ vSetField16( pxAnswer, LLMNRAnswer_t, usType, dnsTYPE_A_HOST ); /* Type A: host */\r
+ vSetField16( pxAnswer, LLMNRAnswer_t, usClass, dnsCLASS_IN ); /* 1: Class IN */\r
vSetField32( pxAnswer, LLMNRAnswer_t, ulTTL, dnsLLMNR_TTL_VALUE );\r
vSetField16( pxAnswer, LLMNRAnswer_t, usDataLength, 4 );\r
vSetField32( pxAnswer, LLMNRAnswer_t, ulIPAddress, FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) );\r
}\r
}\r
#endif /* ipconfigUSE_LLMNR == 1 */\r
+ } while( 0 );\r
+\r
+ if( xExpected == pdFALSE )\r
+ {\r
+ /* Do not return a valid IP-address in case the reply was not expected. */\r
+ ulIPAddress = 0uL;\r
}\r
\r
return ulIPAddress;\r
\r
#if( ipconfigUSE_NBNS == 1 )\r
\r
- static void prvTreatNBNS( uint8_t *pucUDPPayloadBuffer, size_t xBufferLength, uint32_t ulIPAddress )\r
+ static void prvTreatNBNS( uint8_t *pucUDPPayloadBuffer,\r
+ size_t uxBufferLength,\r
+ uint32_t ulIPAddress )\r
{\r
- uint16_t usFlags, usType, usClass;\r
- uint8_t *pucSource, *pucTarget;\r
- uint8_t ucByte;\r
- uint8_t ucNBNSName[ 17 ];\r
+ uint16_t usFlags, usType, usClass;\r
+ uint8_t *pucSource, *pucTarget;\r
+ uint8_t ucByte;\r
+ uint8_t ucNBNSName[ 17 ];\r
\r
/* Check for minimum buffer size. */\r
- if( xBufferLength < sizeof( NBNSRequest_t ) )\r
+ if( uxBufferLength < sizeof( NBNSRequest_t ) )\r
{\r
return;\r
}\r
usClass = usChar2u16( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usClass ) );\r
\r
/* Not used for now */\r
- ( void )usClass;\r
+ ( void ) usClass;\r
+\r
/* For NBNS a name is 16 bytes long, written with capitals only.\r
Make sure that the copy is terminated with a zero. */\r
- pucTarget = ucNBNSName + sizeof(ucNBNSName ) - 2;\r
+ pucTarget = ucNBNSName + sizeof( ucNBNSName ) - 2;\r
pucTarget[ 1 ] = '\0';\r
\r
/* Start with decoding the last 2 bytes. */\r
if( ( xBufferAllocFixedSize == pdFALSE ) && ( pxNetworkBuffer != NULL ) )\r
{\r
NetworkBufferDescriptor_t *pxNewBuffer;\r
- BaseType_t xDataLength = pxNetworkBuffer->xDataLength + sizeof( UDPHeader_t ) +\r
- sizeof( EthernetHeader_t ) + sizeof( IPHeader_t );\r
\r
- /* The field xDataLength was set to the length of the UDP payload.\r
- The answer (reply) will be longer than the request, so the packet\r
- must be duplicated into a bigger buffer */\r
- pxNetworkBuffer->xDataLength = xDataLength;\r
- pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, xDataLength + 16 );\r
+ /* The field xDataLength was set to the total length of the UDP packet,\r
+ i.e. the payload size plus sizeof( UDPPacket_t ). */\r
+ pxNewBuffer = pxDuplicateNetworkBufferWithDescriptor( pxNetworkBuffer, pxNetworkBuffer->xDataLength + sizeof( NBNSAnswer_t ) );\r
+\r
if( pxNewBuffer != NULL )\r
{\r
pucUDPPayloadBuffer = pxNewBuffer->pucEthernetBuffer + sizeof( UDPPacket_t );\r
/* Should not occur: pucUDPPayloadBuffer is part of a xNetworkBufferDescriptor */\r
if( pxNetworkBuffer != NULL )\r
{\r
- pxMessage = (DNSMessage_t *)pucUDPPayloadBuffer;\r
+ pxMessage = ( DNSMessage_t * ) pucUDPPayloadBuffer;\r
\r
/* As the fields in the structures are not word-aligned, we have to\r
copy the values byte-by-byte using macro's vSetField16() and vSetField32() */\r
vSetField16( pxMessage, DNSMessage_t, usAuthorityRRs, 0 );\r
vSetField16( pxMessage, DNSMessage_t, usAdditionalRRs, 0 );\r
\r
- pxAnswer = (NBNSAnswer_t *)( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usType ) );\r
+ pxAnswer = ( NBNSAnswer_t * ) ( pucUDPPayloadBuffer + offsetof( NBNSRequest_t, usType ) );\r
\r
- vSetField16( pxAnswer, NBNSAnswer_t, usType, usType ); /* Type */\r
- vSetField16( pxAnswer, NBNSAnswer_t, usClass, dnsNBNS_CLASS_IN ); /* Class */\r
+ vSetField16( pxAnswer, NBNSAnswer_t, usType, usType ); /* Type */\r
+ vSetField16( pxAnswer, NBNSAnswer_t, usClass, dnsNBNS_CLASS_IN ); /* Class */\r
vSetField32( pxAnswer, NBNSAnswer_t, ulTTL, dnsNBNS_TTL_VALUE );\r
- vSetField16( pxAnswer, NBNSAnswer_t, usDataLength, 6 ); /* 6 bytes including the length field */\r
+ vSetField16( pxAnswer, NBNSAnswer_t, usDataLength, 6 ); /* 6 bytes including the length field */\r
vSetField16( pxAnswer, NBNSAnswer_t, usNbFlags, dnsNBNS_NAME_FLAGS );\r
vSetField32( pxAnswer, NBNSAnswer_t, ulIPAddress, FreeRTOS_ntohl( *ipLOCAL_IP_ADDRESS_POINTER ) );\r
\r
}\r
}\r
\r
-#endif /* ipconfigUSE_NBNS */\r
+#endif /* ipconfigUSE_NBNS */\r
/*-----------------------------------------------------------*/\r
\r
static Socket_t prvCreateDNSSocket( void )\r
Socket_t xSocket = NULL;\r
struct freertos_sockaddr xAddress;\r
BaseType_t xReturn;\r
-TickType_t xTimeoutTime = pdMS_TO_TICKS( 200 );\r
\r
/* This must be the first time this function has been called. Create\r
the socket. */\r
}\r
else\r
{\r
- /* Set the send and receive timeouts. */\r
- FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );\r
- FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDTIMEO, ( void * ) &xTimeoutTime, sizeof( TickType_t ) );\r
+ /* The send and receive timeouts will be set later on. */\r
}\r
\r
return xSocket;\r
\r
#if( ( ipconfigUSE_NBNS == 1 ) || ( ipconfigUSE_LLMNR == 1 ) )\r
\r
- static void prvReplyDNSMessage( NetworkBufferDescriptor_t *pxNetworkBuffer, BaseType_t lNetLength )\r
+ static void prvReplyDNSMessage( NetworkBufferDescriptor_t *pxNetworkBuffer,\r
+ BaseType_t lNetLength )\r
{\r
UDPPacket_t *pxUDPPacket;\r
IPHeader_t *pxIPHeader;\r
UDPHeader_t *pxUDPHeader;\r
\r
- pxUDPPacket = (UDPPacket_t *) pxNetworkBuffer->pucEthernetBuffer;\r
+ pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;\r
pxIPHeader = &pxUDPPacket->xIPHeader;\r
pxUDPHeader = &pxUDPPacket->xUDPHeader;\r
/* HT: started using defines like 'ipSIZE_OF_xxx' */\r
#if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 )\r
{\r
/* calculate the IP header checksum */\r
- pxIPHeader->usHeaderChecksum = 0x00;\r
- pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0UL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );\r
- pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );\r
+ pxIPHeader->usHeaderChecksum = 0x00;\r
+ pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0uL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );\r
+ pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );\r
\r
/* calculate the UDP checksum for outgoing package */\r
usGenerateProtocolChecksum( ( uint8_t* ) pxUDPPacket, pxNetworkBuffer->xDataLength, pdTRUE );\r
\r
#if( ipconfigUSE_DNS_CACHE == 1 )\r
\r
- static void prvProcessDNSCache( const char *pcName, uint32_t *pulIP, uint32_t ulTTL, BaseType_t xLookUp )\r
+ static void prvProcessDNSCache( const char *pcName,\r
+ uint32_t *pulIP,\r
+ uint32_t ulTTL,\r
+ BaseType_t xLookUp )\r
{\r
BaseType_t x;\r
BaseType_t xFound = pdFALSE;\r
uint32_t ulCurrentTimeSeconds = ( xTaskGetTickCount() / portTICK_PERIOD_MS ) / 1000;\r
static BaseType_t xFreeEntry = 0;\r
- configASSERT(pcName);\r
-\r
+ configASSERT(pcName);\r
\r
/* For each entry in the DNS cache table. */\r
for( x = 0; x < ipconfigDNS_CACHE_ENTRIES; x++ )\r
xDNSCache[ xFreeEntry ].ulTimeWhenAddedInSeconds = ulCurrentTimeSeconds;\r
\r
xFreeEntry++;\r
+\r
if( xFreeEntry == ipconfigDNS_CACHE_ENTRIES )\r
{\r
xFreeEntry = 0;\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
\r
\r
/* Time delay between repeated attempts to initialise the network hardware. */\r
-#define ipINITIALISATION_RETRY_DELAY ( pdMS_TO_TICKS( 3000 ) )\r
+#ifndef ipINITIALISATION_RETRY_DELAY\r
+ #define ipINITIALISATION_RETRY_DELAY ( pdMS_TO_TICKS( 3000 ) )\r
+#endif\r
\r
/* Defines how often the ARP timer callback function is executed. The time is\r
shorted in the Windows simulator as simulated time is not real time. */\r
prvHandleEthernetPacket( ( NetworkBufferDescriptor_t * ) ( xReceivedEvent.pvData ) );\r
break;\r
\r
+ case eNetworkTxEvent:\r
+ /* Send a network packet. The ownership will be transferred to\r
+ the driver, which will release it after delivery. */\r
+ xNetworkInterfaceOutput( ( NetworkBufferDescriptor_t * ) ( xReceivedEvent.pvData ), pdTRUE );\r
+ break;\r
+\r
case eARPTimerEvent :\r
/* The ARP timer has expired, process the ARP cache. */\r
vARPAgeCache();\r
/*-----------------------------------------------------------*/\r
\r
NetworkBufferDescriptor_t *pxDuplicateNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer,\r
- BaseType_t xNewLength )\r
+ size_t uxNewLength )\r
{\r
NetworkBufferDescriptor_t * pxNewBuffer;\r
\r
/* This function is only used when 'ipconfigZERO_COPY_TX_DRIVER' is set to 1.\r
The transmit routine wants to have ownership of the network buffer\r
descriptor, because it will pass the buffer straight to DMA. */\r
- pxNewBuffer = pxGetNetworkBufferWithDescriptor( ( size_t ) xNewLength, ( TickType_t ) 0 );\r
+ pxNewBuffer = pxGetNetworkBufferWithDescriptor( uxNewLength, ( TickType_t ) 0 );\r
\r
if( pxNewBuffer != NULL )\r
{\r
/* Set the actual packet size in case a bigger buffer than requested\r
was returned. */\r
- pxNewBuffer->xDataLength = xNewLength;\r
+ pxNewBuffer->xDataLength = uxNewLength;\r
\r
/* Copy the original packet information. */\r
pxNewBuffer->ulIPAddress = pxNetworkBuffer->ulIPAddress;\r
\r
/* Added to prevent ARP flood to gateway. Ensure the\r
gateway is on the same subnet as the IP address. */\r
- configASSERT( ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) == ( xNetworkAddressing.ulGatewayAddress & xNetworkAddressing.ulNetMask ) );\r
+ if( xNetworkAddressing.ulGatewayAddress != 0ul )\r
+ {\r
+ configASSERT( ( ( *ipLOCAL_IP_ADDRESS_POINTER ) & xNetworkAddressing.ulNetMask ) == ( xNetworkAddressing.ulGatewayAddress & xNetworkAddressing.ulNetMask ) );\r
+ }\r
}\r
#endif /* ipconfigUSE_DHCP == 1 */\r
\r
pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ] = FREERTOS_SO_UDPCKSUM_OUT;\r
pxNetworkBuffer->ulIPAddress = ulIPAddress;\r
pxNetworkBuffer->usPort = ipPACKET_CONTAINS_ICMP_DATA;\r
- pxNetworkBuffer->xDataLength = xNumberOfBytesToSend + sizeof( ICMPHeader_t );\r
+ /* xDataLength is the size of the total packet, including the Ethernet header. */\r
+ pxNetworkBuffer->xDataLength = xNumberOfBytesToSend + sizeof( ICMPPacket_t );\r
\r
/* Send to the stack. */\r
xStackTxEvent.pvData = pxNetworkBuffer;\r
\r
/* Only proceed if the payload length indicated in the header\r
appears to be valid. */\r
- if ( pxNetworkBuffer->xDataLength >= sizeof( UDPPacket_t ) )\r
+ if ( ( pxNetworkBuffer->xDataLength >= sizeof( UDPPacket_t ) ) && ( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ) >= sizeof( UDPHeader_t ) ) )\r
{\r
- /* Ensure that downstream UDP packet handling has the lesser\r
- * of: the actual network buffer Ethernet frame length, or\r
- * the sender's UDP packet header payload length, minus the\r
- * size of the UDP header.\r
- *\r
- * The size of the UDP packet structure in this implementation\r
- * includes the size of the Ethernet header, the size of\r
- * the IP header, and the size of the UDP header.\r
+ size_t uxPayloadSize_1, uxPayloadSize_2;\r
+ /* The UDP payload size can be calculated by subtracting the\r
+ * header size from `xDataLength`.\r
+ * However, the `xDataLength` may be longer that expected,\r
+ * e.g. when a small packet is padded with zero's.\r
+ * The UDP header contains a field `usLength` reflecting\r
+ * the payload size plus the UDP header ( 8 bytes ).\r
+ * Set `xDataLength` to the size of the headers,\r
+ * plus the lower of the two calculated payload sizes.\r
*/\r
\r
- pxNetworkBuffer->xDataLength -= sizeof( UDPPacket_t );\r
- if( ( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ) - sizeof( UDPHeader_t ) ) <\r
- pxNetworkBuffer->xDataLength )\r
+ uxPayloadSize_1 = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );\r
+ uxPayloadSize_2 = FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ) - sizeof( UDPHeader_t );\r
+ if( uxPayloadSize_1 > uxPayloadSize_2 )\r
{\r
- pxNetworkBuffer->xDataLength = FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usLength ) - sizeof( UDPHeader_t );\r
+ pxNetworkBuffer->xDataLength = uxPayloadSize_2 + sizeof( UDPPacket_t );\r
}\r
\r
/* Fields in pxNetworkBuffer (usPort, ulIPAddress) are network order. */\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
}\r
}\r
\r
- return ( SocketSet_t * ) pxSocketSet;\r
+ return ( SocketSet_t ) pxSocketSet;\r
}\r
\r
#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */\r
}\r
taskEXIT_CRITICAL();\r
\r
- /* The returned value is the data length, which may have been capped to\r
- the receive buffer size. */\r
- lReturn = ( int32_t ) pxNetworkBuffer->xDataLength;\r
+ /* The returned value is the length of the payload data, which is\r
+ calculated at the total packet size minus the headers.\r
+ The validity of `xDataLength` prvProcessIPPacket has been confirmed\r
+ in 'prvProcessIPPacket()'. */\r
+ lReturn = ( int32_t ) ( pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ) );\r
\r
if( pxSourceAddress != NULL )\r
{\r
\r
if( pxNetworkBuffer != NULL )\r
{\r
- pxNetworkBuffer->xDataLength = xTotalDataLength;\r
+ /* xDataLength is the size of the total packet, including the Ethernet header. */\r
+ pxNetworkBuffer->xDataLength = xTotalDataLength + sizeof( UDPPacket_t );\r
pxNetworkBuffer->usPort = pxDestinationAddress->sin_port;\r
pxNetworkBuffer->usBoundPort = ( uint16_t ) socketGET_SOCKET_PORT( pxSocket );\r
pxNetworkBuffer->ulIPAddress = pxDestinationAddress->sin_addr;\r
{\r
if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleSent ) )\r
{\r
- pxSocket->u.xUDP.pxHandleSent( (Socket_t *)pxSocket, xTotalDataLength );\r
+ pxSocket->u.xUDP.pxHandleSent( ( Socket_t )pxSocket, xTotalDataLength );\r
}\r
}\r
#endif /* ipconfigUSE_CALLBACKS */\r
uint16_t usIterations = usEphemeralPortCount;\r
uint32_t ulRandomSeed = 0;\r
uint16_t usResult = 0;\r
-BaseType_t xGotZeroOnce = pdFALSE;\r
const List_t *pxList;\r
\r
#if ipconfigUSE_TCP == 1\r
point. */\r
do\r
{\r
- /* Generate a random seed. */\r
- ulRandomSeed = ipconfigRAND32( );\r
-\r
/* Only proceed if the random number generator succeeded. */\r
- if( 0 == ulRandomSeed )\r
+ if( xApplicationGetRandomNumber( &( ulRandomSeed ) ) == pdFALSE )\r
{\r
- if( pdFALSE == xGotZeroOnce )\r
- {\r
- xGotZeroOnce = pdTRUE;\r
- continue;\r
- }\r
- else\r
- {\r
- break;\r
- }\r
+ break;\r
}\r
\r
/* Map the random to a candidate port. */\r
xResult = -pdFREERTOS_ERRNO_ENOMEM;\r
}\r
else if( pxSocket->u.xTCP.ucTCPState == eCLOSED ||\r
- pxSocket->u.xTCP.ucTCPState == eCLOSE_WAIT ||\r
- pxSocket->u.xTCP.ucTCPState == eCLOSING )\r
+ pxSocket->u.xTCP.ucTCPState == eCLOSE_WAIT ||\r
+ pxSocket->u.xTCP.ucTCPState == eCLOSING )\r
{\r
xResult = -pdFREERTOS_ERRNO_ENOTCONN;\r
}\r
'*pxLength' will contain the number of bytes that may be written. */\r
uint8_t *FreeRTOS_get_tx_head( Socket_t xSocket, BaseType_t *pxLength )\r
{\r
- uint8_t *pucReturn = NULL;\r
+ uint8_t *pucReturn = NULL;\r
FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;\r
StreamBuffer_t *pxBuffer = NULL;\r
\r
- *pxLength = 0;\r
+ *pxLength = 0;\r
\r
- /* Confirm that this is a TCP socket before dereferencing structure\r
- member pointers. */\r
- if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE )\r
- {\r
- pxBuffer = pxSocket->u.xTCP.txStream;\r
- if( pxBuffer != NULL )\r
- {\r
- BaseType_t xSpace = ( BaseType_t )uxStreamBufferGetSpace( pxBuffer );\r
- BaseType_t xRemain = ( BaseType_t )( pxBuffer->LENGTH - pxBuffer->uxHead );\r
+ /* Confirm that this is a TCP socket before dereferencing structure\r
+ member pointers. */\r
+ if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE )\r
+ {\r
+ pxBuffer = pxSocket->u.xTCP.txStream;\r
+ if( pxBuffer != NULL )\r
+ {\r
+ BaseType_t xSpace = ( BaseType_t )uxStreamBufferGetSpace( pxBuffer );\r
+ BaseType_t xRemain = ( BaseType_t )( pxBuffer->LENGTH - pxBuffer->uxHead );\r
\r
- *pxLength = FreeRTOS_min_BaseType( xSpace, xRemain );\r
- pucReturn = pxBuffer->ucArray + pxBuffer->uxHead;\r
- }\r
+ *pxLength = FreeRTOS_min_BaseType( xSpace, xRemain );\r
+ pucReturn = pxBuffer->ucArray + pxBuffer->uxHead;\r
+ }\r
}\r
\r
return pucReturn;\r
\r
#if( ipconfigUSE_TCP == 1 )\r
\r
- const struct xSTREAM_BUFFER *FreeRTOS_get_rx_buf( Socket_t xSocket )\r
- {\r
- FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * )xSocket;\r
- struct xSTREAM_BUFFER *pxReturn = NULL;\r
+ const struct xSTREAM_BUFFER *FreeRTOS_get_rx_buf( Socket_t xSocket )\r
+ {\r
+ FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * )xSocket;\r
+ struct xSTREAM_BUFFER *pxReturn = NULL;\r
\r
- /* Confirm that this is a TCP socket before dereferencing structure\r
- member pointers. */\r
- if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE )\r
- {\r
- pxReturn = pxSocket->u.xTCP.rxStream;\r
- }\r
+ /* Confirm that this is a TCP socket before dereferencing structure\r
+ member pointers. */\r
+ if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE )\r
+ {\r
+ pxReturn = pxSocket->u.xTCP.rxStream;\r
+ }\r
\r
- return pxReturn;\r
- }\r
+ return pxReturn;\r
+ }\r
\r
#endif /* ipconfigUSE_TCP */\r
/*-----------------------------------------------------------*/\r
break;\r
}\r
\r
- pxSocket->u.xTCP.pxHandleReceive( (Socket_t *)pxSocket, ( void* )ucReadPtr, ( size_t ) ulCount );\r
+ pxSocket->u.xTCP.pxHandleReceive( ( Socket_t )pxSocket, ( void* )ucReadPtr, ( size_t ) ulCount );\r
uxStreamBufferGet( pxStream, 0ul, NULL, ( size_t ) ulCount, pdFALSE );\r
}\r
} else\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
*/\r
static void prvCheckOptions( FreeRTOS_Socket_t *pxSocket, NetworkBufferDescriptor_t *pxNetworkBuffer );\r
\r
+/*\r
+ * Identify and deal with a single TCP header option, advancing the pointer to\r
+ * the header. This function returns pdTRUE or pdFALSE depending on whether the\r
+ * caller should continue to parse more header options or break the loop.\r
+ */\r
+static BaseType_t prvSingleStepTCPHeaderOptions( const unsigned char ** const ppucPtr, const unsigned char ** const ppucLast, FreeRTOS_Socket_t ** const ppxSocket, TCPWindow_t ** const ppxTCPWindow);\r
+\r
+/*\r
+ * Skip past TCP header options when doing Selective ACK, until there are no\r
+ * more options left.\r
+ */\r
+static void prvSkipPastRemainingOptions( const unsigned char ** const ppucPtr, FreeRTOS_Socket_t ** const ppxSocket, unsigned char * const ppucLen );\r
+\r
/*\r
* Set the initial properties in the options fields, like the preferred\r
* value of MSS and whether SACK allowed. Will be transmitted in the state\r
* payload, just flags).\r
*/\r
static BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t *pxNetworkBuffer,\r
- uint8_t ucTCPFlags );\r
+ uint8_t ucTCPFlags );\r
\r
/*\r
* A "challenge ACK" is as per https://tools.ietf.org/html/rfc5961#section-3.2,\r
const unsigned char *pucPtr;\r
const unsigned char *pucLast;\r
TCPWindow_t *pxTCPWindow;\r
-UBaseType_t uxNewMSS;\r
+BaseType_t xShouldContinueLoop;\r
\r
pxTCPPacket = ( TCPPacket_t * ) ( pxNetworkBuffer->pucEthernetBuffer );\r
pxTCPHeader = &pxTCPPacket->xTCPHeader;\r
\r
/* The comparison with pucLast is only necessary in case the option data are\r
corrupted, we don't like to run into invalid memory and crash. */\r
- while( pucPtr < pucLast )\r
+ xShouldContinueLoop = pdTRUE;\r
+ while( ( pucPtr < pucLast ) && ( xShouldContinueLoop == pdTRUE ) )\r
{\r
- UBaseType_t xRemainingOptionsBytes = pucLast - pucPtr;\r
+ xShouldContinueLoop = prvSingleStepTCPHeaderOptions( &pucPtr, &pucLast, &pxSocket, &pxTCPWindow );\r
+ }\r
+}\r
\r
- if( pucPtr[ 0 ] == TCP_OPT_END )\r
- {\r
- /* End of options. */\r
- break;\r
- }\r
- if( pucPtr[ 0 ] == TCP_OPT_NOOP)\r
+/*-----------------------------------------------------------*/\r
+\r
+static BaseType_t prvSingleStepTCPHeaderOptions( const unsigned char ** const ppucPtr, const unsigned char ** const ppucLast, FreeRTOS_Socket_t ** const ppxSocket, TCPWindow_t ** const ppxTCPWindow)\r
+{\r
+ UBaseType_t uxNewMSS;\r
+ UBaseType_t xRemainingOptionsBytes = ( *ppucLast ) - ( *ppucPtr );\r
+ unsigned char ucLen;\r
+\r
+ if( ( *ppucPtr )[ 0 ] == TCP_OPT_END )\r
+ {\r
+ /* End of options. */\r
+ return pdFALSE;\r
+ }\r
+ if( ( *ppucPtr )[ 0 ] == TCP_OPT_NOOP)\r
+ {\r
+ /* NOP option, inserted to make the length a multiple of 4. */\r
+ ( *ppucPtr )++;\r
+ return pdTRUE;\r
+ }\r
+\r
+ /* Any other well-formed option must be at least two bytes: the option\r
+ type byte followed by a length byte. */\r
+ if( xRemainingOptionsBytes < 2 )\r
+ {\r
+ return pdFALSE;\r
+ }\r
+#if( ipconfigUSE_TCP_WIN != 0 )\r
+ else if( ( *ppucPtr )[ 0 ] == TCP_OPT_WSOPT )\r
+ {\r
+ /* Confirm that the option fits in the remaining buffer space. */\r
+ if( ( xRemainingOptionsBytes < TCP_OPT_WSOPT_LEN ) || ( ( *ppucPtr )[ 1 ] != TCP_OPT_WSOPT_LEN ) )\r
{\r
- /* NOP option, inserted to make the length a multiple of 4. */\r
- pucPtr++;\r
- continue;\r
+ return pdFALSE;\r
}\r
\r
- /* Any other well-formed option must be at least two bytes: the option\r
- type byte followed by a length byte. */\r
- if( xRemainingOptionsBytes < 2 )\r
+ ( *ppxSocket )->u.xTCP.ucPeerWinScaleFactor = ( *ppucPtr )[ 2 ];\r
+ ( *ppxSocket )->u.xTCP.bits.bWinScaling = pdTRUE_UNSIGNED;\r
+ ( *ppucPtr ) += TCP_OPT_WSOPT_LEN;\r
+ }\r
+#endif /* ipconfigUSE_TCP_WIN */\r
+ else if( ( *ppucPtr )[ 0 ] == TCP_OPT_MSS )\r
+ {\r
+ /* Confirm that the option fits in the remaining buffer space. */\r
+ if( ( xRemainingOptionsBytes < TCP_OPT_MSS_LEN )|| ( ( *ppucPtr )[ 1 ] != TCP_OPT_MSS_LEN ) )\r
{\r
- break;\r
+ return pdFALSE;\r
}\r
-#if( ipconfigUSE_TCP_WIN != 0 )\r
- else if( pucPtr[ 0 ] == TCP_OPT_WSOPT )\r
+\r
+ /* An MSS option with the correct option length. FreeRTOS_htons()\r
+ is not needed here because usChar2u16() already returns a host\r
+ endian number. */\r
+ uxNewMSS = usChar2u16( ( *ppucPtr ) + 2 );\r
+\r
+ if( ( *ppxSocket )->u.xTCP.usInitMSS != uxNewMSS )\r
{\r
- /* Confirm that the option fits in the remaining buffer space. */\r
- if( ( xRemainingOptionsBytes < TCP_OPT_WSOPT_LEN ) || ( pucPtr[ 1 ] != TCP_OPT_WSOPT_LEN ) )\r
+ /* Perform a basic check on the the new MSS. */\r
+ if( uxNewMSS == 0 )\r
{\r
- break;\r
+ return pdFALSE;\r
}\r
\r
- pxSocket->u.xTCP.ucPeerWinScaleFactor = pucPtr[ 2 ];\r
- pxSocket->u.xTCP.bits.bWinScaling = pdTRUE_UNSIGNED;\r
- pucPtr += TCP_OPT_WSOPT_LEN;\r
+ FreeRTOS_debug_printf( ( "MSS change %u -> %lu\n", ( *ppxSocket )->u.xTCP.usInitMSS, uxNewMSS ) );\r
}\r
-#endif /* ipconfigUSE_TCP_WIN */\r
- else if( pucPtr[ 0 ] == TCP_OPT_MSS )\r
+\r
+ if( ( *ppxSocket )->u.xTCP.usInitMSS > uxNewMSS )\r
{\r
- /* Confirm that the option fits in the remaining buffer space. */\r
- if( ( xRemainingOptionsBytes < TCP_OPT_MSS_LEN )|| ( pucPtr[ 1 ] != TCP_OPT_MSS_LEN ) )\r
+ /* our MSS was bigger than the MSS of the other party: adapt it. */\r
+ ( *ppxSocket )->u.xTCP.bits.bMssChange = pdTRUE_UNSIGNED;\r
+ if( ( ( *ppxTCPWindow ) != NULL ) && ( ( *ppxSocket )->u.xTCP.usCurMSS > uxNewMSS ) )\r
{\r
- break;\r
+ /* The peer advertises a smaller MSS than this socket was\r
+ using. Use that as well. */\r
+ FreeRTOS_debug_printf( ( "Change mss %d => %lu\n", ( *ppxSocket )->u.xTCP.usCurMSS, uxNewMSS ) );\r
+ ( *ppxSocket )->u.xTCP.usCurMSS = ( uint16_t ) uxNewMSS;\r
}\r
+ ( *ppxTCPWindow )->xSize.ulRxWindowLength = ( ( uint32_t ) uxNewMSS ) * ( ( *ppxTCPWindow )->xSize.ulRxWindowLength / ( ( uint32_t ) uxNewMSS ) );\r
+ ( *ppxTCPWindow )->usMSSInit = ( uint16_t ) uxNewMSS;\r
+ ( *ppxTCPWindow )->usMSS = ( uint16_t ) uxNewMSS;\r
+ ( *ppxSocket )->u.xTCP.usInitMSS = ( uint16_t ) uxNewMSS;\r
+ ( *ppxSocket )->u.xTCP.usCurMSS = ( uint16_t ) uxNewMSS;\r
+ }\r
\r
- /* An MSS option with the correct option length. FreeRTOS_htons()\r
- is not needed here because usChar2u16() already returns a host\r
- endian number. */\r
- uxNewMSS = usChar2u16( pucPtr + 2 );\r
+ #if( ipconfigUSE_TCP_WIN != 1 )\r
+ /* Without scaled windows, MSS is the only interesting option. */\r
+ return pdFALSE;\r
+ #else\r
+ /* Or else we continue to check another option: selective ACK. */\r
+ ( *ppucPtr ) += TCP_OPT_MSS_LEN;\r
+ #endif /* ipconfigUSE_TCP_WIN != 1 */\r
+ }\r
+ else\r
+ {\r
+ /* All other options have a length field, so that we easily\r
+ can skip past them. */\r
+ ucLen = ( *ppucPtr )[ 1 ];\r
+ if( ( ucLen < 2 ) || ( ucLen > xRemainingOptionsBytes ) )\r
+ {\r
+ /* If the length field is too small or too big, the options are\r
+ * malformed, don't process them further.\r
+ */\r
+ return pdFALSE;\r
+ }\r
\r
- if( pxSocket->u.xTCP.usInitMSS != uxNewMSS )\r
+ #if( ipconfigUSE_TCP_WIN == 1 )\r
+ {\r
+ /* Selective ACK: the peer has received a packet but it is missing\r
+ * earlier packets. At least this packet does not need retransmission\r
+ * anymore. ulTCPWindowTxSack( ) takes care of this administration.\r
+ */\r
+ if( ( *ppucPtr )[0] == TCP_OPT_SACK_A )\r
{\r
- /* Perform a basic check on the the new MSS. */\r
- if( uxNewMSS == 0 )\r
- {\r
- break;\r
- }\r
-\r
- FreeRTOS_debug_printf( ( "MSS change %u -> %lu\n", pxSocket->u.xTCP.usInitMSS, uxNewMSS ) );\r
- }\r
+ ucLen -= 2;\r
+ ( *ppucPtr ) += 2;\r
\r
- if( pxSocket->u.xTCP.usInitMSS > uxNewMSS )\r
- {\r
- /* our MSS was bigger than the MSS of the other party: adapt it. */\r
- pxSocket->u.xTCP.bits.bMssChange = pdTRUE_UNSIGNED;\r
- if( ( pxTCPWindow != NULL ) && ( pxSocket->u.xTCP.usCurMSS > uxNewMSS ) )\r
+ while( ucLen >= 8 )\r
{\r
- /* The peer advertises a smaller MSS than this socket was\r
- using. Use that as well. */\r
- FreeRTOS_debug_printf( ( "Change mss %d => %lu\n", pxSocket->u.xTCP.usCurMSS, uxNewMSS ) );\r
- pxSocket->u.xTCP.usCurMSS = ( uint16_t ) uxNewMSS;\r
+ prvSkipPastRemainingOptions( ppucPtr, ppxSocket, &ucLen );\r
}\r
- pxTCPWindow->xSize.ulRxWindowLength = ( ( uint32_t ) uxNewMSS ) * ( pxTCPWindow->xSize.ulRxWindowLength / ( ( uint32_t ) uxNewMSS ) );\r
- pxTCPWindow->usMSSInit = ( uint16_t ) uxNewMSS;\r
- pxTCPWindow->usMSS = ( uint16_t ) uxNewMSS;\r
- pxSocket->u.xTCP.usInitMSS = ( uint16_t ) uxNewMSS;\r
- pxSocket->u.xTCP.usCurMSS = ( uint16_t ) uxNewMSS;\r
+ /* ucLen should be 0 by now. */\r
}\r
-\r
- #if( ipconfigUSE_TCP_WIN != 1 )\r
- /* Without scaled windows, MSS is the only interesting option. */\r
- break;\r
- #else\r
- /* Or else we continue to check another option: selective ACK. */\r
- pucPtr += TCP_OPT_MSS_LEN;\r
- #endif /* ipconfigUSE_TCP_WIN != 1 */\r
}\r
- else\r
+ #endif /* ipconfigUSE_TCP_WIN == 1 */\r
+\r
+ ( *ppucPtr ) += ucLen;\r
+ }\r
+ return pdTRUE;\r
+}\r
+\r
+/*-----------------------------------------------------------*/\r
+\r
+static void prvSkipPastRemainingOptions( const unsigned char ** const ppucPtr, FreeRTOS_Socket_t ** const ppxSocket, unsigned char * const pucLen )\r
+{\r
+uint32_t ulFirst = ulChar2u32( ( *ppucPtr ) );\r
+uint32_t ulLast = ulChar2u32( ( *ppucPtr ) + 4 );\r
+uint32_t ulCount = ulTCPWindowTxSack( &( *ppxSocket )->u.xTCP.xTCPWindow, ulFirst, ulLast );\r
+ /* ulTCPWindowTxSack( ) returns the number of bytes which have been acked\r
+ * starting from the head position. Advance the tail pointer in txStream.\r
+ */\r
+ if( ( ( *ppxSocket )->u.xTCP.txStream != NULL ) && ( ulCount > 0 ) )\r
+ {\r
+ /* Just advancing the tail index, 'ulCount' bytes have been confirmed. */\r
+ uxStreamBufferGet( ( *ppxSocket )->u.xTCP.txStream, 0, NULL, ( size_t ) ulCount, pdFALSE );\r
+ ( *ppxSocket )->xEventBits |= eSOCKET_SEND;\r
+\r
+ #if ipconfigSUPPORT_SELECT_FUNCTION == 1\r
{\r
- /* All other options have a length field, so that we easily\r
- can skip past them. */\r
- unsigned char len = pucPtr[ 1 ];\r
- if( ( len < 2 ) || ( len > xRemainingOptionsBytes ) )\r
+ if( ( *ppxSocket )->xSelectBits & eSELECT_WRITE )\r
{\r
- /* If the length field is too small or too big, the options are malformed.\r
- Don't process them further. */\r
- break;\r
+ /* The field 'xEventBits' is used to store regular socket events\r
+ * (at most 8), as well as 'select events', which will be left-shifted.\r
+ */\r
+ ( *ppxSocket )->xEventBits |= ( eSELECT_WRITE << SOCKET_EVENT_BIT_COUNT );\r
}\r
+ }\r
+ #endif\r
\r
- #if( ipconfigUSE_TCP_WIN == 1 )\r
+ /* In case the socket owner has installed an OnSent handler, call it now.\r
+ */\r
+ #if( ipconfigUSE_CALLBACKS == 1 )\r
+ {\r
+ if( ipconfigIS_VALID_PROG_ADDRESS( ( *ppxSocket )->u.xTCP.pxHandleSent ) )\r
{\r
- /* Selective ACK: the peer has received a packet but it is missing earlier\r
- packets. At least this packet does not need retransmission anymore\r
- ulTCPWindowTxSack( ) takes care of this administration. */\r
- if( pucPtr[0] == TCP_OPT_SACK_A )\r
- {\r
- len -= 2;\r
- pucPtr += 2;\r
-\r
- while( len >= 8 )\r
- {\r
- uint32_t ulFirst = ulChar2u32( pucPtr );\r
- uint32_t ulLast = ulChar2u32( pucPtr + 4 );\r
- uint32_t ulCount = ulTCPWindowTxSack( &pxSocket->u.xTCP.xTCPWindow, ulFirst, ulLast );\r
- /* ulTCPWindowTxSack( ) returns the number of bytes which have been acked\r
- starting from the head position.\r
- Advance the tail pointer in txStream. */\r
- if( ( pxSocket->u.xTCP.txStream != NULL ) && ( ulCount > 0 ) )\r
- {\r
- /* Just advancing the tail index, 'ulCount' bytes have been confirmed. */\r
- uxStreamBufferGet( pxSocket->u.xTCP.txStream, 0, NULL, ( size_t ) ulCount, pdFALSE );\r
- pxSocket->xEventBits |= eSOCKET_SEND;\r
-\r
- #if ipconfigSUPPORT_SELECT_FUNCTION == 1\r
- {\r
- if( pxSocket->xSelectBits & eSELECT_WRITE )\r
- {\r
- /* The field 'xEventBits' is used to store regular socket events (at most 8),\r
- as well as 'select events', which will be left-shifted */\r
- pxSocket->xEventBits |= ( eSELECT_WRITE << SOCKET_EVENT_BIT_COUNT );\r
- }\r
- }\r
- #endif\r
-\r
- /* In case the socket owner has installed an OnSent handler,\r
- call it now. */\r
- #if( ipconfigUSE_CALLBACKS == 1 )\r
- {\r
- if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleSent ) )\r
- {\r
- pxSocket->u.xTCP.pxHandleSent( (Socket_t *)pxSocket, ulCount );\r
- }\r
- }\r
- #endif /* ipconfigUSE_CALLBACKS == 1 */\r
- }\r
- pucPtr += 8;\r
- len -= 8;\r
- }\r
- /* len should be 0 by now. */\r
- }\r
+ ( *ppxSocket )->u.xTCP.pxHandleSent( (Socket_t )( *ppxSocket ), ulCount );\r
}\r
- #endif /* ipconfigUSE_TCP_WIN == 1 */\r
-\r
- pucPtr += len;\r
}\r
+ #endif /* ipconfigUSE_CALLBACKS == 1 */\r
}\r
+ ( *ppucPtr ) += 8;\r
+ ( *pucLen ) -= 8;\r
}\r
+\r
/*-----------------------------------------------------------*/\r
\r
#if( ipconfigUSE_TCP_WIN != 0 )\r
if( xConnected != NULL )\r
{\r
/* The 'connected' state has changed, call the OnConnect handler of the parent. */\r
- xConnected->u.xTCP.pxHandleConnected( ( Socket_t * ) xConnected, bAfter );\r
+ xConnected->u.xTCP.pxHandleConnected( ( Socket_t ) xConnected, bAfter );\r
}\r
}\r
#endif\r
{\r
if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleSent ) )\r
{\r
- pxSocket->u.xTCP.pxHandleSent( (Socket_t *)pxSocket, ulCount );\r
+ pxSocket->u.xTCP.pxHandleSent( ( Socket_t )pxSocket, ulCount );\r
}\r
}\r
#endif /* ipconfigUSE_CALLBACKS == 1 */\r
}\r
/*-----------------------------------------------------------*/\r
\r
-static BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t *pxNetworkBuffer, \r
- uint8_t ucTCPFlags )\r
+static BaseType_t prvTCPSendSpecialPacketHelper( NetworkBufferDescriptor_t *pxNetworkBuffer,\r
+ uint8_t ucTCPFlags )\r
{\r
#if( ipconfigIGNORE_UNKNOWN_PACKETS == 0 )\r
- {\r
- TCPPacket_t *pxTCPPacket = ( TCPPacket_t * )( pxNetworkBuffer->pucEthernetBuffer );\r
- const BaseType_t xSendLength = ( BaseType_t )\r
- ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER + 0u ); /* Plus 0 options. */\r
+ {\r
+ TCPPacket_t *pxTCPPacket = ( TCPPacket_t * )( pxNetworkBuffer->pucEthernetBuffer );\r
+ const BaseType_t xSendLength = ( BaseType_t )\r
+ ( ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER + 0u ); /* Plus 0 options. */\r
\r
- pxTCPPacket->xTCPHeader.ucTCPFlags = ucTCPFlags;\r
- pxTCPPacket->xTCPHeader.ucTCPOffset = ( ipSIZE_OF_TCP_HEADER + 0u ) << 2;\r
+ pxTCPPacket->xTCPHeader.ucTCPFlags = ucTCPFlags;\r
+ pxTCPPacket->xTCPHeader.ucTCPOffset = ( ipSIZE_OF_TCP_HEADER + 0u ) << 2;\r
\r
- prvTCPReturnPacket( NULL, pxNetworkBuffer, ( uint32_t )xSendLength, pdFALSE );\r
- }\r
+ prvTCPReturnPacket( NULL, pxNetworkBuffer, ( uint32_t )xSendLength, pdFALSE );\r
+ }\r
#endif /* !ipconfigIGNORE_UNKNOWN_PACKETS */\r
\r
- /* Remove compiler warnings if ipconfigIGNORE_UNKNOWN_PACKETS == 1. */\r
- ( void )pxNetworkBuffer;\r
- ( void )ucTCPFlags;\r
+ /* Remove compiler warnings if ipconfigIGNORE_UNKNOWN_PACKETS == 1. */\r
+ ( void )pxNetworkBuffer;\r
+ ( void )ucTCPFlags;\r
\r
- /* The packet was not consumed. */\r
- return pdFAIL;\r
+ /* The packet was not consumed. */\r
+ return pdFAIL;\r
}\r
/*-----------------------------------------------------------*/\r
\r
static BaseType_t prvTCPSendChallengeAck( NetworkBufferDescriptor_t *pxNetworkBuffer )\r
{\r
- return prvTCPSendSpecialPacketHelper( pxNetworkBuffer, ipTCP_FLAG_ACK );\r
+ return prvTCPSendSpecialPacketHelper( pxNetworkBuffer, ipTCP_FLAG_ACK );\r
}\r
/*-----------------------------------------------------------*/\r
\r
static BaseType_t prvTCPSendReset( NetworkBufferDescriptor_t *pxNetworkBuffer )\r
{\r
- return prvTCPSendSpecialPacketHelper( pxNetworkBuffer, \r
- ipTCP_FLAG_ACK | ipTCP_FLAG_RST );\r
+ return prvTCPSendSpecialPacketHelper( pxNetworkBuffer,\r
+ ipTCP_FLAG_ACK | ipTCP_FLAG_RST );\r
}\r
/*-----------------------------------------------------------*/\r
\r
uint32_t ulSequenceNumber;\r
uint32_t ulAckNumber;\r
BaseType_t xResult = pdPASS;\r
-\r
- configASSERT( pxNetworkBuffer );\r
- configASSERT( pxNetworkBuffer->pucEthernetBuffer );\r
+configASSERT(pxNetworkBuffer);\r
+configASSERT(pxNetworkBuffer->pucEthernetBuffer);\r
\r
/* Check for a minimum packet size. */\r
if( pxNetworkBuffer->xDataLength >= ( ipSIZE_OF_ETH_HEADER + ipSIZE_OF_IPv4_HEADER + ipSIZE_OF_TCP_HEADER ) )\r
xLocalPort = FreeRTOS_htons( pxTCPPacket->xTCPHeader.usDestinationPort );\r
ulRemoteIP = FreeRTOS_htonl( pxTCPPacket->xIPHeader.ulSourceIPAddress );\r
xRemotePort = FreeRTOS_htons( pxTCPPacket->xTCPHeader.usSourcePort );\r
- ulSequenceNumber = FreeRTOS_ntohl( pxTCPPacket->xTCPHeader.ulSequenceNumber );\r
- ulAckNumber = FreeRTOS_ntohl( pxTCPPacket->xTCPHeader.ulAckNr );\r
+ ulSequenceNumber = FreeRTOS_ntohl( pxTCPPacket->xTCPHeader.ulSequenceNumber );\r
+ ulAckNumber = FreeRTOS_ntohl( pxTCPPacket->xTCPHeader.ulAckNr );\r
\r
/* Find the destination socket, and if not found: return a socket listing to\r
the destination PORT. */\r
flag. */\r
if( ( ucTCPFlags & ipTCP_FLAG_RST ) != 0u )\r
{\r
- FreeRTOS_debug_printf( ( "TCP: RST received from %lxip:%u for %u\n", ulRemoteIP, xRemotePort, xLocalPort ) );\r
-\r
- /* Implement https://tools.ietf.org/html/rfc5961#section-3.2. */\r
- if( pxSocket->u.xTCP.ucTCPState == eCONNECT_SYN )\r
- {\r
- /* Per the above RFC, "In the SYN-SENT state ... the RST is \r
- acceptable if the ACK field acknowledges the SYN." */\r
- if( ulAckNumber == pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber + 1 )\r
- {\r
- vTCPStateChange( pxSocket, eCLOSED );\r
- }\r
- }\r
- else\r
- {\r
- /* Check whether the packet matches the next expected sequence number. */\r
- if( ulSequenceNumber == pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber )\r
- {\r
- vTCPStateChange( pxSocket, eCLOSED );\r
- }\r
- /* Otherwise, check whether the packet is within the receive window. */\r
- else if( ulSequenceNumber > pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber &&\r
- ulSequenceNumber < ( pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber +\r
- pxSocket->u.xTCP.xTCPWindow.xSize.ulRxWindowLength ) )\r
- {\r
- /* Send a challenge ACK. */\r
- prvTCPSendChallengeAck( pxNetworkBuffer );\r
- }\r
- }\r
-\r
- /* Otherwise, do nothing. In any case, the packet cannot be handled. */\r
+ FreeRTOS_debug_printf( ( "TCP: RST received from %lxip:%u for %u\n", ulRemoteIP, xRemotePort, xLocalPort ) );\r
+\r
+ /* Implement https://tools.ietf.org/html/rfc5961#section-3.2. */\r
+ if( pxSocket->u.xTCP.ucTCPState == eCONNECT_SYN )\r
+ {\r
+ /* Per the above RFC, "In the SYN-SENT state ... the RST is\r
+ acceptable if the ACK field acknowledges the SYN." */\r
+ if( ulAckNumber == pxSocket->u.xTCP.xTCPWindow.ulOurSequenceNumber + 1 )\r
+ {\r
+ vTCPStateChange( pxSocket, eCLOSED );\r
+ }\r
+ }\r
+ else\r
+ {\r
+ /* Check whether the packet matches the next expected sequence number. */\r
+ if( ulSequenceNumber == pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber )\r
+ {\r
+ vTCPStateChange( pxSocket, eCLOSED );\r
+ }\r
+ /* Otherwise, check whether the packet is within the receive window. */\r
+ else if( ulSequenceNumber > pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber &&\r
+ ulSequenceNumber < ( pxSocket->u.xTCP.xTCPWindow.rx.ulCurrentSequenceNumber +\r
+ pxSocket->u.xTCP.xTCPWindow.xSize.ulRxWindowLength ) )\r
+ {\r
+ /* Send a challenge ACK. */\r
+ prvTCPSendChallengeAck( pxNetworkBuffer );\r
+ }\r
+ }\r
+\r
+ /* Otherwise, do nothing. In any case, the packet cannot be handled. */\r
xResult = pdFAIL;\r
}\r
else if( ( ( ucTCPFlags & ipTCP_FLAG_CTRL ) == ipTCP_FLAG_SYN ) && ( pxSocket->u.xTCP.ucTCPState >= eESTABLISHED ) )\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
\r
#if( ipconfigUSE_TCP_WIN == 1 )\r
\r
- void vTCPSegmentCleanup( void )\r
- {\r
- /* Free and clear the TCP segments pointer. This function should only be called\r
- * once FreeRTOS+TCP will no longer be used. No thread-safety is provided for this\r
- * function. */\r
- if( xTCPSegments != NULL )\r
- {\r
- vPortFreeLarge( xTCPSegments );\r
- xTCPSegments = NULL;\r
- }\r
- }\r
+ void vTCPSegmentCleanup( void )\r
+ {\r
+ /* Free and clear the TCP segments pointer. This function should only be called\r
+ * once FreeRTOS+TCP will no longer be used. No thread-safety is provided for this\r
+ * function. */\r
+ if( xTCPSegments != NULL )\r
+ {\r
+ vPortFreeLarge( xTCPSegments );\r
+ xTCPSegments = NULL;\r
+ }\r
+ }\r
\r
#endif /* ipconfgiUSE_TCP_WIN == 1 */\r
/*-----------------------------------------------------------*/\r
{\r
ulSavedSequenceNumber = ulCurrentSequenceNumber;\r
\r
- /* Clean up all sequence received between ulSequenceNumber and ulSequenceNumber + ulLength since they are duplicated.\r
- If the server is forced to retransmit packets several time in a row it might send a batch of concatenated packet for speed.\r
- So we cannot rely on the packets between ulSequenceNumber and ulSequenceNumber + ulLength to be sequential and it is better to just\r
- clean them out. */\r
- do\r
- {\r
- pxFound = xTCPWindowRxConfirm( pxWindow, ulSequenceNumber, ulLength );\r
-\r
- if ( pxFound != NULL )\r
- {\r
- /* Remove it because it will be passed to user directly. */\r
- vTCPWindowFree( pxFound );\r
- }\r
- } while ( pxFound );\r
+ /* Clean up all sequence received between ulSequenceNumber and ulSequenceNumber + ulLength since they are duplicated.\r
+ If the server is forced to retransmit packets several time in a row it might send a batch of concatenated packet for speed.\r
+ So we cannot rely on the packets between ulSequenceNumber and ulSequenceNumber + ulLength to be sequential and it is better to just\r
+ clean them out. */\r
+ do\r
+ {\r
+ pxFound = xTCPWindowRxConfirm( pxWindow, ulSequenceNumber, ulLength );\r
+\r
+ if ( pxFound != NULL )\r
+ {\r
+ /* Remove it because it will be passed to user directly. */\r
+ vTCPWindowFree( pxFound );\r
+ }\r
+ } while ( pxFound );\r
\r
/* Check for following segments that are already in the\r
queue and increment ulCurrentSequenceNumber. */\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
IPHeader_t *pxIPHeader;\r
eARPLookupResult_t eReturned;\r
uint32_t ulIPAddress = pxNetworkBuffer->ulIPAddress;\r
+size_t uxPayloadSize;\r
\r
/* Map the UDP packet onto the start of the frame. */\r
pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;\r
\r
+#if ipconfigSUPPORT_OUTGOING_PINGS == 1\r
+ if( pxNetworkBuffer->usPort == ipPACKET_CONTAINS_ICMP_DATA )\r
+ {\r
+ uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( ICMPPacket_t );\r
+ }\r
+ else\r
+#endif\r
+ {\r
+ uxPayloadSize = pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t );\r
+ }\r
+\r
/* Determine the ARP cache status for the requested IP address. */\r
eReturned = eARPGetCacheEntry( &( ulIPAddress ), &( pxUDPPacket->xEthernetHeader.xDestinationAddress ) );\r
\r
\r
pxUDPHeader->usDestinationPort = pxNetworkBuffer->usPort;\r
pxUDPHeader->usSourcePort = pxNetworkBuffer->usBoundPort;\r
- pxUDPHeader->usLength = ( uint16_t ) ( pxNetworkBuffer->xDataLength + sizeof( UDPHeader_t ) );\r
+ pxUDPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( UDPHeader_t ) );\r
pxUDPHeader->usLength = FreeRTOS_htons( pxUDPHeader->usLength );\r
pxUDPHeader->usChecksum = 0u;\r
}\r
if( pxNetworkBuffer->usPort == ipPACKET_CONTAINS_ICMP_DATA )\r
{\r
pxIPHeader->ucProtocol = ipPROTOCOL_ICMP;\r
- pxIPHeader->usLength = ( uint16_t ) ( pxNetworkBuffer->xDataLength + sizeof( IPHeader_t ) );\r
+ pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( ICMPHeader_t ) );\r
}\r
else\r
#endif /* ipconfigSUPPORT_OUTGOING_PINGS */\r
{\r
- pxIPHeader->usLength = ( uint16_t ) ( pxNetworkBuffer->xDataLength + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) );\r
+ pxIPHeader->usLength = ( uint16_t ) ( uxPayloadSize + sizeof( IPHeader_t ) + sizeof( UDPHeader_t ) );\r
}\r
\r
- /* The total transmit size adds on the Ethernet header. */\r
- pxNetworkBuffer->xDataLength = pxIPHeader->usLength + sizeof( EthernetHeader_t );\r
pxIPHeader->usLength = FreeRTOS_htons( pxIPHeader->usLength );\r
/* HT:endian: changed back to network endian */\r
pxIPHeader->ulDestinationIPAddress = pxNetworkBuffer->ulIPAddress;\r
{\r
BaseType_t xReturn = pdPASS;\r
FreeRTOS_Socket_t *pxSocket;\r
-UDPPacket_t *pxUDPPacket;\r
+configASSERT(pxNetworkBuffer);\r
+configASSERT(pxNetworkBuffer->pucEthernetBuffer);\r
\r
- configASSERT( pxNetworkBuffer );\r
- configASSERT( pxNetworkBuffer->pucEthernetBuffer );\r
\r
- pxUDPPacket = ( UDPPacket_t * ) pxNetworkBuffer->pucEthernetBuffer;\r
- \r
+UDPPacket_t *pxUDPPacket = (UDPPacket_t *) pxNetworkBuffer->pucEthernetBuffer;\r
+\r
/* Caller must check for minimum packet size. */\r
pxSocket = pxUDPSocketLookup( usPort );\r
\r
destinationAddress.sin_port = usPort;\r
destinationAddress.sin_addr = pxUDPPacket->xIPHeader.ulDestinationIPAddress;\r
\r
- if( xHandler( ( Socket_t * ) pxSocket, ( void* ) pcData, ( size_t ) pxNetworkBuffer->xDataLength,\r
+ /* The value of 'xDataLength' was proven to be at least the size of a UDP packet in prvProcessIPPacket(). */\r
+ if( xHandler( ( Socket_t ) pxSocket, ( void* ) pcData, ( size_t ) ( pxNetworkBuffer->xDataLength - ipUDP_PAYLOAD_OFFSET_IPv4 ),\r
&xSourceAddress, &destinationAddress ) )\r
{\r
xReturn = pdFAIL; /* FAIL means that we did not consume or release the buffer */\r
/* There is no socket listening to the target port, but still it might\r
be for this node. */\r
\r
+ #if( ipconfigUSE_DNS == 1 ) && ( ipconfigDNS_USE_CALLBACKS == 1 )\r
+ /* A DNS reply, check for the source port. Although the DNS client\r
+ does open a UDP socket to send a messages, this socket will be\r
+ closed after a short timeout. Messages that come late (after the\r
+ socket is closed) will be treated here. */\r
+ if( FreeRTOS_ntohs( pxUDPPacket->xUDPHeader.usSourcePort ) == ipDNS_PORT )\r
+ {\r
+ vARPRefreshCacheEntry( &( pxUDPPacket->xEthernetHeader.xSourceAddress ), pxUDPPacket->xIPHeader.ulSourceIPAddress );\r
+ xReturn = ( BaseType_t )ulDNSHandlePacket( pxNetworkBuffer );\r
+ }\r
+ else\r
+ #endif\r
+\r
#if( ipconfigUSE_LLMNR == 1 )\r
/* a LLMNR request, check for the destination port. */\r
if( ( usPort == FreeRTOS_ntohs( ipLLMNR_PORT ) ) ||\r
-Changes in V2.0.11\r
-\r
- + Updates some drivers in the portable layer.\r
-\r
Changes between 160919 and 180821 releases:\r
\r
+ Multiple security improvements and fixes in packet parsing routines, DNS\r
+ Disable NBNS and LLMNR by default.\r
+ Add TCP hang protection by default.\r
\r
- We thank Ori Karliner of Zimperium zLabs Team for reporting these issues.\r
-\r
- + Update FreeRTOS_gethostbyname() to allow an IP address to be passed in -\r
- in which case it is just returned as a uint32_t.\r
- + Introduce ipconfigSOCKET_HAS_USER_WAKE_CALLBACK to FreeRTOS_Sockets.c to\r
- allow a user supposed callback function to be executed when socket events\r
- occur in the same way that the socket semaphore is currently used.\r
- + Update xNetworkBuffersInitialise() to ensure the semaphore created by the\r
- function is not accessed until after the NULL check.\r
- + Improve print messages output by the Win32 port layer version of\r
- prvPrintAvailableNetworkInterfaces().\r
+We thank Ori Karliner of Zimperium zLabs Team for reporting these issues.\r
\r
Changes between 160908 and 160919 releases:\r
\r
+ Fix: Previously if a listening socket was reused, and a connection\r
failed, the TCP/IP stack closed the socket, now the socket is correctly\r
left unclosed as it is owned by the application.\r
- + Various other formatting and minor fix alterations.
\ No newline at end of file
+ + Various other formatting and minor fix alterations.\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
#define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME portMAX_DELAY\r
#endif\r
\r
+\r
+#ifndef ipconfigDNS_RECEIVE_BLOCK_TIME_TICKS\r
+ #define ipconfigDNS_RECEIVE_BLOCK_TIME_TICKS pdMS_TO_TICKS( 500u )\r
+#endif\r
+\r
+#ifndef ipconfigDNS_SEND_BLOCK_TIME_TICKS\r
+ #define ipconfigDNS_SEND_BLOCK_TIME_TICKS pdMS_TO_TICKS( 500u )\r
+#endif\r
/*\r
* FreeRTOS debug logging routine (proposal)\r
* The macro will be called in the printf() style. Users can define\r
#endif /* _WINDOWS_ */\r
#endif /* ipconfigMAXIMUM_DISCOVER_TX_PERIOD */\r
\r
+#if( ipconfigUSE_DNS == 0 )\r
+ /* The DNS module will not be included. */\r
+ #if( ( ipconfigUSE_LLMNR != 0 ) || ( ipconfigUSE_NBNS != 0 ) )\r
+ /* LLMNR and NBNS depend on DNS because those protocols share a lot of code. */\r
+ #error When either LLMNR or NBNS is used, ipconfigUSE_DNS must be defined\r
+ #endif\r
+#endif\r
+\r
#ifndef ipconfigUSE_DNS\r
#define ipconfigUSE_DNS 1\r
#endif\r
#define ipconfigUSE_LLMNR ( 0 )\r
#endif\r
\r
-#if( !defined( ipconfigUSE_DNS ) )\r
- #if( ( ipconfigUSE_LLMNR != 0 ) || ( ipconfigUSE_NBNS != 0 ) )\r
- /* LLMNR and NBNS depend on DNS because those protocols share a lot of code. */\r
- #error When either LLMNR or NBNS is used, ipconfigUSE_DNS must be defined\r
- #endif\r
-#endif\r
-\r
#ifndef ipconfigREPLY_TO_INCOMING_PINGS\r
#define ipconfigREPLY_TO_INCOMING_PINGS 1\r
#endif\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
typedef struct xARP_CACHE_TABLE_ROW\r
{\r
uint32_t ulIPAddress; /* The IP address of an ARP cache entry. */\r
- MACAddress_t xMACAddress; /* The MAC address of an ARP cache entry. */\r
+ MACAddress_t xMACAddress; /* The MAC address of an ARP cache entry. */\r
uint8_t ucAge; /* A value that is periodically decremented but can also be refreshed by active communication. The ARP cache entry is removed if the value reaches zero. */\r
- uint8_t ucValid; /* pdTRUE: xMACAddress is valid, pdFALSE: waiting for ARP reply */\r
+ uint8_t ucValid; /* pdTRUE: xMACAddress is valid, pdFALSE: waiting for ARP reply */\r
} ARPCacheRow_t;\r
\r
typedef enum\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
\r
#if( ipconfigUSE_DNS_CACHE != 0 )\r
\r
- /* Look for the indicated host name in the DNS cache. Returns the IPv4 \r
- address if present, or 0x0 otherwise. */\r
+ /* Look for the indicated host name in the DNS cache. Returns the IPv4 \r
+ address if present, or 0x0 otherwise. */\r
uint32_t FreeRTOS_dnslookup( const char *pcHostName );\r
\r
- /* Remove all entries from the DNS cache. */\r
- void FreeRTOS_dnsclear();\r
+ /* Remove all entries from the DNS cache. */\r
+ void FreeRTOS_dnsclear();\r
#endif /* ipconfigUSE_DNS_CACHE != 0 */\r
\r
#if( ipconfigDNS_USE_CALLBACKS != 0 )\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
#endif /* ipconfigDHCP_REGISTER_HOSTNAME */\r
\r
\r
+/* This xApplicationGetRandomNumber() will set *pulNumber to a random number,\r
+and return pdTRUE. When the random number generator is broken, it shall return\r
+pdFALSE.\r
+The function is defined in 'iot_secure_sockets.c'.\r
+If that module is not included in the project, the application must provide an\r
+implementation of it.\r
+The macro's ipconfigRAND32() and configRAND32() are not in use anymore. */\r
+BaseType_t xApplicationGetRandomNumber( uint32_t *pulNumber );\r
+\r
/* For backward compatibility define old structure names to the newer equivalent\r
structure name. */\r
#ifndef ipconfigENABLE_BACKWARD_COMPATIBILITY\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
#include "FreeRTOS_TCP_IP.h"\r
#endif\r
\r
-#if( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )\r
- #include "semphr.h"\r
-#endif\r
-\r
#include "event_groups.h"\r
\r
typedef struct xNetworkAddressingParameters\r
eNoEvent = -1,\r
eNetworkDownEvent, /* 0: The network interface has been lost and/or needs [re]connecting. */\r
eNetworkRxEvent, /* 1: The network interface has queued a received Ethernet frame. */\r
- eARPTimerEvent, /* 2: The ARP timer expired. */\r
- eStackTxEvent, /* 3: The software stack has queued a packet to transmit. */\r
- eDHCPEvent, /* 4: Process the DHCP state machine. */\r
- eTCPTimerEvent, /* 5: See if any TCP socket needs attention. */\r
- eTCPAcceptEvent, /* 6: Client API FreeRTOS_accept() waiting for client connections. */\r
- eTCPNetStat, /* 7: IP-task is asked to produce a netstat listing. */\r
- eSocketBindEvent, /* 8: Send a message to the IP-task to bind a socket to a port. */\r
- eSocketCloseEvent, /* 9: Send a message to the IP-task to close a socket. */\r
- eSocketSelectEvent, /*10: Send a message to the IP-task for select(). */\r
- eSocketSignalEvent, /*11: A socket must be signalled. */\r
+ eNetworkTxEvent, /* 2: Let the IP-task send a network packet. */\r
+ eARPTimerEvent, /* 3: The ARP timer expired. */\r
+ eStackTxEvent, /* 4: The software stack has queued a packet to transmit. */\r
+ eDHCPEvent, /* 5: Process the DHCP state machine. */\r
+ eTCPTimerEvent, /* 6: See if any TCP socket needs attention. */\r
+ eTCPAcceptEvent, /* 7: Client API FreeRTOS_accept() waiting for client connections. */\r
+ eTCPNetStat, /* 8: IP-task is asked to produce a netstat listing. */\r
+ eSocketBindEvent, /* 9: Send a message to the IP-task to bind a socket to a port. */\r
+ eSocketCloseEvent, /*10: Send a message to the IP-task to close a socket. */\r
+ eSocketSelectEvent, /*11: Send a message to the IP-task for select(). */\r
+ eSocketSignalEvent, /*12: A socket must be signalled. */\r
} eIPEvent_t;\r
\r
typedef struct IP_TASK_COMMANDS\r
BaseType_t xIPIsNetworkTaskReady( void );\r
\r
#if( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 )\r
- struct XSOCKET;\r
- typedef void (*SocketWakeupCallback_t)( struct XSOCKET * pxSocket );\r
+ struct xSOCKET;\r
+ typedef void (*SocketWakeupCallback_t)( struct xSOCKET * pxSocket );\r
#endif\r
\r
#if( ipconfigUSE_TCP == 1 )\r
* This counter is separate from the xmitCount in the\r
* TCP win segments */\r
uint8_t ucTCPState; /* TCP state: see eTCP_STATE */\r
- struct XSOCKET *pxPeerSocket; /* for server socket: child, for child socket: parent */\r
+ struct xSOCKET *pxPeerSocket; /* for server socket: child, for child socket: parent */\r
#if( ipconfigTCP_KEEP_ALIVE == 1 )\r
uint8_t ucKeepRepCount;\r
TickType_t xLastAliveTime;\r
eSOCKET_ALL = 0x007F,\r
} eSocketEvent_t;\r
\r
-typedef struct XSOCKET\r
+typedef struct xSOCKET\r
{\r
EventBits_t xEventBits;\r
EventGroupHandle_t xEventGroup;\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
\r
/* Assigned to an Socket_t variable when the socket is not valid, probably\r
because it could not be created. */\r
-#define FREERTOS_INVALID_SOCKET ( ( void * ) ~0U )\r
+#define FREERTOS_INVALID_SOCKET ( ( Socket_t ) ~0U )\r
\r
/* API function error values. As errno is supported, the FreeRTOS sockets\r
functions return error codes rather than just a pass or fail indication. */\r
#endif /* ipconfigBYTE_ORDER */\r
\r
/* The socket type itself. */\r
-typedef void *Socket_t;\r
+struct xSOCKET;\r
+typedef struct xSOCKET *Socket_t;\r
\r
/* The SocketSet_t type is the equivalent to the fd_set type used by the\r
Berkeley API. */\r
-typedef void *SocketSet_t;\r
+struct xSOCKET_SET;\r
+typedef struct xSOCKET_SET *SocketSet_t;\r
\r
/**\r
* FULL, UP-TO-DATE AND MAINTAINED REFERENCE DOCUMENTATION FOR ALL THESE\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
}\r
}\r
/*-----------------------------------------------------------*/\r
-static portINLINE BaseType_t xStreamBufferIsEmpty( const StreamBuffer_t *pxBuffer );\r
-static portINLINE BaseType_t xStreamBufferIsEmpty( const StreamBuffer_t *pxBuffer )\r
-{\r
-BaseType_t xReturn;\r
-\r
- /* True if no item is available */\r
- if( pxBuffer->uxHead == pxBuffer->uxTail )\r
- {\r
- xReturn = pdTRUE;\r
- }\r
- else\r
- {\r
- xReturn = pdFALSE;\r
- }\r
- return xReturn;\r
-}\r
-/*-----------------------------------------------------------*/\r
-\r
-static portINLINE BaseType_t xStreamBufferIsFull( const StreamBuffer_t *pxBuffer );\r
-static portINLINE BaseType_t xStreamBufferIsFull( const StreamBuffer_t *pxBuffer )\r
-{\r
- /* True if the available space equals zero. */\r
- return ( BaseType_t ) ( uxStreamBufferGetSpace( pxBuffer ) == 0u );\r
-}\r
-/*-----------------------------------------------------------*/\r
\r
static portINLINE BaseType_t xStreamBufferLessThenEqual( const StreamBuffer_t *pxBuffer, const size_t uxLeft, const size_t uxRight );\r
static portINLINE BaseType_t xStreamBufferLessThenEqual( const StreamBuffer_t *pxBuffer, const size_t uxLeft, const size_t uxRight )\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
\r
/* Copy a network buffer into a bigger buffer. */\r
NetworkBufferDescriptor_t *pxDuplicateNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer,\r
- BaseType_t xNewLength);\r
+ size_t uxNewLength);\r
\r
/* Increase the size of a Network Buffer.\r
In case BufferAllocation_2.c is used, the new space must be allocated. */\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
+ * FreeRTOS+TCP V2.2.0\r
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
*\r
* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
pxReturn->pxNextBuffer = NULL;\r
}\r
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
-\r
- if( xTCPWindowLoggingLevel > 3 )\r
- {\r
- FreeRTOS_debug_printf( ( "BUF_GET[%ld]: %p (%p)\n",\r
- bIsValidNetworkDescriptor( pxReturn ),\r
- pxReturn, pxReturn->pucEthernetBuffer ) );\r
- }\r
}\r
iptraceNETWORK_BUFFER_OBTAINED( pxReturn );\r
}\r
{\r
xSemaphoreGive( xNetworkBufferSemaphore );\r
prvShowWarnings();\r
- if( xTCPWindowLoggingLevel > 3 )\r
- FreeRTOS_debug_printf( ( "BUF_PUT[%ld]: %p (%p) (now %lu)\n",\r
- bIsValidNetworkDescriptor( pxNetworkBuffer ),\r
- pxNetworkBuffer, pxNetworkBuffer->pucEthernetBuffer,\r
- uxGetNumberOfFreeNetworkBuffers( ) ) );\r
}\r
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );\r
}\r
--- /dev/null
+/*\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
+\r
+/*****************************************************************************\r
+ *\r
+ * See the following URL for an explanation of this file:\r
+ * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html\r
+ *\r
+ *****************************************************************************/\r
+;\r
+#pragma pack(pop)\r
--- /dev/null
+/*\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
+\r
+/*****************************************************************************\r
+ *\r
+ * See the following URL for an explanation of this file:\r
+ * http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html\r
+ *\r
+ *****************************************************************************/\r
+\r
+#pragma pack(push,1)\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
- * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
- * this software and associated documentation files (the "Software"), to deal in\r
- * the Software without restriction, including without limitation the rights to\r
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
- * the Software, and to permit persons to whom the Software is furnished to do so,\r
- * subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in all\r
- * copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
- *\r
- * http://aws.amazon.com/freertos\r
- * http://www.FreeRTOS.org\r
- */\r
-\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
\r
/* Standard includes. */\r
#include <stdint.h>\r
#error Please define GMAC_USES_TX_CALLBACK as 1\r
#endif\r
\r
-#if( ipconfigZERO_COPY_RX_DRIVER != 0 )\r
- #warning The EMAC of SAM4E has fixed-size RX buffers so ZERO_COPY_RX is not possible\r
-#endif\r
-\r
/* Default the size of the stack used by the EMAC deferred handler task to 4x\r
the size of the stack used by the idle task - but allow this to be overridden in\r
FreeRTOSConfig.h as configMINIMAL_STACK_SIZE is a user definable constant. */\r
configASSERT( xTXDescriptorSemaphore );\r
}\r
/* When returning non-zero, the stack will become active and\r
- start DHCP (in configured) */\r
+ start DHCP (in configured) */\r
return ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != 0;\r
}\r
/*-----------------------------------------------------------*/\r
\r
if ( xProtPacket->xTCPPacket.xEthernetHeader.usFrameType == ipIPv4_FRAME_TYPE )\r
{\r
- IPHeader_t *pxIPHeader = &( xProtPacket->xTCPPacket.xIPHeader );\r
+ IPHeader_t *pxIPHeader = &(xProtPacket->xTCPPacket.xIPHeader);\r
\r
/* Calculate the IP header checksum. */\r
pxIPHeader->usHeaderChecksum = 0x00;\r
- pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0u, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );\r
+ pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );\r
pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );\r
\r
/* Calculate the TCP checksum for an outgoing packet. */\r
}\r
/*-----------------------------------------------------------*/\r
\r
-void vCheckBuffersAndQueue( void )\r
-{\r
-static UBaseType_t uxLastMinBufferCount = 0;\r
-#if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
- static UBaseType_t uxLastMinQueueSpace;\r
-#endif\r
-static UBaseType_t uxCurrentCount;\r
-\r
- #if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
- {\r
- uxCurrentCount = uxGetMinimumIPQueueSpace();\r
- if( uxLastMinQueueSpace != uxCurrentCount )\r
- {\r
- /* The logging produced below may be helpful\r
- while tuning +TCP: see how many buffers are in use. */\r
- uxLastMinQueueSpace = uxCurrentCount;\r
- FreeRTOS_printf( ( "Queue space: lowest %lu\n", uxCurrentCount ) );\r
- }\r
- }\r
- #endif /* ipconfigCHECK_IP_QUEUE_SPACE */\r
- uxCurrentCount = uxGetMinimumFreeNetworkBuffers();\r
- if( uxLastMinBufferCount != uxCurrentCount )\r
- {\r
- /* The logging produced below may be helpful\r
- while tuning +TCP: see how many buffers are in use. */\r
- uxLastMinBufferCount = uxCurrentCount;\r
- FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",\r
- uxGetNumberOfFreeNetworkBuffers(), uxCurrentCount ) );\r
- }\r
-\r
-}\r
-\r
static void prvEMACHandlerTask( void *pvParameters )\r
{\r
TimeOut_t xPhyTime;\r
TickType_t xPhyRemTime;\r
-UBaseType_t uxCount;\r
+UBaseType_t uxLastMinBufferCount = 0, uxCount;\r
+UBaseType_t uxCurrentCount;\r
+#if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
+ UBaseType_t uxLastMinQueueSpace;\r
+#endif\r
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )\r
NetworkBufferDescriptor_t *pxBuffer;\r
#endif\r
\r
for( ;; )\r
{\r
- vCheckBuffersAndQueue();\r
+ uxCurrentCount = uxGetMinimumFreeNetworkBuffers();\r
+ if( uxLastMinBufferCount != uxCurrentCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinBufferCount = uxCurrentCount;\r
+ FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",\r
+ uxGetNumberOfFreeNetworkBuffers(), uxCurrentCount ) );\r
+ }\r
+\r
+ #if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
+ {\r
+ uxCurrentCount = uxGetMinimumIPQueueSpace();\r
+ if( uxLastMinQueueSpace != uxCurrentCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinQueueSpace = uxCurrentCount;\r
+ FreeRTOS_printf( ( "Queue space: lowest %lu\n", uxCurrentCount ) );\r
+ }\r
+ }\r
+ #endif /* ipconfigCHECK_IP_QUEUE_SPACE */\r
\r
if( ( ulISREvents & EMAC_IF_ALL_EVENT ) == 0 )\r
{\r
* GMAC_DCFGR_TXCOEN: (GMAC_DCFGR) Transmitter Checksum Generation Offload Enable.\r
* Note: tha SAM4E does have RX checksum offloading\r
* but TX checksum offloading has NOT been implemented.\r
- * http://community.atmel.com/forum/sam4e-gmac-transmit-checksum-offload-enablesolved\r
*/\r
\r
gmac_set_dma(p_gmac,\r
}\r
#else\r
{\r
- /* Or memcopy... */\r
+ /* Or Memcopy... */\r
memcpy((void *)p_tx_td->addr, p_buffer, ul_size);\r
}\r
#endif /* ipconfigZERO_COPY_TX_DRIVER */\r
-/*\r
- * FreeRTOS+TCP V2.0.11\r
- * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
- * this software and associated documentation files (the "Software"), to deal in\r
- * the Software without restriction, including without limitation the rights to\r
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
- * the Software, and to permit persons to whom the Software is furnished to do so,\r
- * subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in all\r
- * copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
- *\r
- * http://aws.amazon.com/freertos\r
- * http://www.FreeRTOS.org\r
- */\r
-\r
/*\r
* Handling of Ethernet PHY's\r
* PHY's communicate with an EMAC either through\r
#endif\r
\r
#ifndef ipconfigPHY_LS_HIGH_CHECK_TIME_MS\r
- /* Check if the LinkSStatus in the PHY is still high after 15 seconds of not\r
+ /* Check if the LinkStatus in the PHY is still high after 15 seconds of not\r
receiving packets. */\r
- #define ipconfigPHY_LS_HIGH_CHECK_TIME_MS 15000\r
+ #define ipconfigPHY_LS_HIGH_CHECK_TIME_MS 15000uL\r
#endif\r
\r
#ifndef ipconfigPHY_LS_LOW_CHECK_TIME_MS\r
- /* Check if the LinkSStatus in the PHY is still low every second. */\r
- #define ipconfigPHY_LS_LOW_CHECK_TIME_MS 1000\r
+ /* Check if the LinkStatus in the PHY is still low every second. */\r
+ #define ipconfigPHY_LS_LOW_CHECK_TIME_MS 1000uL\r
+#endif\r
+\r
+/* As the following 3 macro's are OK in most situations, and so they're not\r
+included in 'FreeRTOSIPConfigDefaults.h'.\r
+Users can change their values in the project's 'FreeRTOSIPConfig.h'. */\r
+#ifndef phyPHY_MAX_RESET_TIME_MS\r
+ #define phyPHY_MAX_RESET_TIME_MS 1000uL\r
+#endif\r
+\r
+#ifndef phyPHY_MAX_NEGOTIATE_TIME_MS\r
+ #define phyPHY_MAX_NEGOTIATE_TIME_MS 3000uL\r
+#endif\r
+\r
+#ifndef phySHORT_DELAY_MS\r
+ #define phySHORT_DELAY_MS 50uL\r
#endif\r
\r
/* Naming and numbering of basic PHY registers. */\r
* Description of all capabilities that can be advertised to\r
* the peer (usually a switch or router).\r
*/\r
-#define phyADVERTISE_CSMA 0x0001u /* Only selector supported. */\r
+\r
+#define phyADVERTISE_CSMA 0x0001u /* Supports IEEE 802.3u: Fast Ethernet at 100 Mbit/s */\r
#define phyADVERTISE_10HALF 0x0020u /* Try for 10mbps half-duplex. */\r
#define phyADVERTISE_10FULL 0x0040u /* Try for 10mbps full-duplex. */\r
#define phyADVERTISE_100HALF 0x0080u /* Try for 100mbps half-duplex. */\r
#define phyADVERTISE_100FULL 0x0100u /* Try for 100mbps full-duplex. */\r
\r
#define phyADVERTISE_ALL ( phyADVERTISE_10HALF | phyADVERTISE_10FULL | \\r
- phyADVERTISE_100HALF | phyADVERTISE_100FULL )\r
+ phyADVERTISE_100HALF | phyADVERTISE_100FULL | \\r
+ phyADVERTISE_CSMA )\r
\r
-/* Send a reset commando to a set of PHY-ports. */\r
+/* Send a reset command to a set of PHY-ports. */\r
static uint32_t xPhyReset( EthernetPhy_t *pxPhyObject, uint32_t ulPhyMask );\r
\r
static BaseType_t xHas_1F_PHYSPCS( uint32_t ulPhyID )\r
}\r
/*-----------------------------------------------------------*/\r
\r
-/* Send a reset commando to a set of PHY-ports. */\r
+/* Send a reset command to a set of PHY-ports. */\r
static uint32_t xPhyReset( EthernetPhy_t *pxPhyObject, uint32_t ulPhyMask )\r
{\r
uint32_t ulDoneMask, ulConfig;\r
TimeOut_t xTimer;\r
BaseType_t xPhyIndex;\r
\r
- /* A bit-mask ofPHY ports that are ready. */\r
+ /* A bit-mask of PHY ports that are ready. */\r
ulDoneMask = 0ul;\r
\r
/* Set the RESET bits high. */\r
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig | phyBMCR_RESET );\r
}\r
\r
- xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( 1000UL );\r
+ xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( phyPHY_MAX_RESET_TIME_MS );\r
vTaskSetTimeOutState( &xTimer );\r
\r
/* The reset should last less than a second. */\r
break;\r
}\r
/* Block for a while */\r
- vTaskDelay( pdMS_TO_TICKS( 50ul ) );\r
+ vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );\r
}\r
\r
/* Clear the reset bits. */\r
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )\r
{\r
- BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];\r
+ if( ( ulDoneMask & ( 1ul << xPhyIndex ) ) == 0uL )\r
+ {\r
+ BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];\r
\r
- pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );\r
- pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig & ~phyBMCR_RESET );\r
+ /* The reset operation timed out, clear the bit manually. */\r
+ pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );\r
+ pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig & ~phyBMCR_RESET );\r
+ }\r
}\r
\r
- vTaskDelay( pdMS_TO_TICKS( 50ul ) );\r
+ vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );\r
\r
return ulDoneMask;\r
}\r
\r
if( pxPhyObject->xPortCount < 1 )\r
{\r
- FreeRTOS_printf( ( "xPhyResetAll: No PHY's detected.\n" ) );\r
+ FreeRTOS_printf( ( "xPhyConfigure: No PHY's detected.\n" ) );\r
return -1;\r
}\r
\r
/* Set advertise register. */\r
if( ( pxPhyProperties->ucSpeed == ( uint8_t )PHY_SPEED_AUTO ) && ( pxPhyProperties->ucDuplex == ( uint8_t )PHY_DUPLEX_AUTO ) )\r
{\r
- ulAdvertise = phyADVERTISE_CSMA | phyADVERTISE_ALL;\r
+ ulAdvertise = phyADVERTISE_ALL;\r
/* Reset auto-negotiation capability. */\r
}\r
else\r
{\r
+ /* Always select protocol 802.3u. */\r
ulAdvertise = phyADVERTISE_CSMA;\r
\r
if( pxPhyProperties->ucSpeed == ( uint8_t )PHY_SPEED_AUTO )\r
}\r
}\r
\r
- /* Send a reset commando to a set of PHY-ports. */\r
+ /* Send a reset command to a set of PHY-ports. */\r
xPhyReset( pxPhyObject, xPhyGetMask( pxPhyObject ) );\r
\r
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )\r
}\r
/*-----------------------------------------------------------*/\r
\r
+/* xPhyFixedValue(): this function is called in case auto-negotiation is disabled.\r
+The caller has set the values in 'xPhyPreferences' (ucDuplex and ucSpeed).\r
+The PHY register phyREG_00_BMCR will be set for every connected PHY that matches\r
+with ulPhyMask. */\r
BaseType_t xPhyFixedValue( EthernetPhy_t *pxPhyObject, uint32_t ulPhyMask )\r
{\r
BaseType_t xPhyIndex;\r
}\r
/*-----------------------------------------------------------*/\r
\r
+/* xPhyStartAutoNegotiation() is the alternative xPhyFixedValue():\r
+It sets the BMCR_AN_RESTART bit and waits for the auto-negotiation completion\r
+( phyBMSR_AN_COMPLETE ). */\r
BaseType_t xPhyStartAutoNegotiation( EthernetPhy_t *pxPhyObject, uint32_t ulPhyMask )\r
{\r
uint32_t xPhyIndex, ulDoneMask, ulBitMask;\r
{\r
return 0;\r
}\r
- for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )\r
+ for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++ )\r
{\r
if( ( ulPhyMask & ( 1lu << xPhyIndex ) ) != 0lu )\r
{\r
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, pxPhyObject->ulBCRValue | phyBMCR_AN_RESTART );\r
}\r
}\r
- xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( 3000UL );\r
+ xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( phyPHY_MAX_NEGOTIATE_TIME_MS );\r
vTaskSetTimeOutState( &xTimer );\r
ulDoneMask = 0;\r
/* Wait until the auto-negotiation will be completed */\r
for( ;; )\r
{\r
ulBitMask = ( uint32_t )1u;\r
- for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )\r
+ for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )\r
{\r
if( ( ulPhyMask & ulBitMask ) != 0lu )\r
{\r
}\r
if( xTaskCheckForTimeOut( &xTimer, &xRemainingTime ) != pdFALSE )\r
{\r
- FreeRTOS_printf( ( "xPhyReset: phyBMCR_RESET timed out ( done 0x%02lX )\n", ulDoneMask ) );\r
+ FreeRTOS_printf( ( "xPhyStartAutoNegotiation: phyBMCR_RESET timed out ( done 0x%02lX )\n", ulDoneMask ) );\r
break;\r
}\r
- vTaskDelay( pdMS_TO_TICKS( 50 ) );\r
+ vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );\r
}\r
\r
if( ulDoneMask != ( uint32_t)0u )\r
{\r
ulBitMask = ( uint32_t )1u;\r
pxPhyObject->ulLinkStatusMask &= ~( ulDoneMask );\r
- for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )\r
+ for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )\r
{\r
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];\r
uint32_t ulPhyID = pxPhyObject->ulPhyIDs[ xPhyIndex ];\r
pxPhyObject->fnPhyRead( xPhyAddress, PHYREG_10_PHYSTS, &ulRegValue);\r
}\r
\r
- FreeRTOS_printf( ( ">> Autonego ready: %08lx: %s duplex %u mbit %s status\n",\r
+ FreeRTOS_printf( ( "Autonego ready: %08lx: %s duplex %u mbit %s status\n",\r
ulRegValue,\r
( ulRegValue & phyPHYSTS_DUPLEX_STATUS ) ? "full" : "half",\r
( ulRegValue & phyPHYSTS_SPEED_STATUS ) ? 10 : 100,\r
}\r
else if( xTaskCheckForTimeOut( &( pxPhyObject->xLinkStatusTimer ), &( pxPhyObject->xLinkStatusRemaining ) ) != pdFALSE )\r
{\r
+ /* Frequent checking the PHY Link Status can affect for the performance of Ethernet controller.\r
+ As long as packets are received, no polling is needed.\r
+ Otherwise, polling will be done when the 'xLinkStatusTimer' expires. */\r
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )\r
{\r
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];\r
vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );\r
if( ( pxPhyObject->ulLinkStatusMask & phyBMSR_LINK_STATUS ) != 0 )\r
{\r
+ /* The link status is high, so don't poll the PHY too often. */\r
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );\r
}\r
else\r
{\r
+ /* The link status is low, polling may be done more frequently. */\r
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_LOW_CHECK_TIME_MS );\r
}\r
}\r
--- /dev/null
+/*\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
+\r
+/* FreeRTOS includes. */\r
+#include "FreeRTOS.h"\r
+#include "list.h"\r
+#include "queue.h"\r
+#include "semphr.h"\r
+#include "task.h"\r
+\r
+/* FreeRTOS+TCP includes. */\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_Sockets.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+#include "NetworkBufferManagement.h"\r
+#include "NetworkInterface.h"\r
+\r
+\r
+#include "m480_eth.h"\r
+\r
+/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet\r
+driver will filter incoming packets and only pass the stack those packets it\r
+considers need processing. */\r
+#if( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )\r
+#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer\r
+#else\r
+#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )\r
+#endif\r
+\r
+/* Default the size of the stack used by the EMAC deferred handler task to twice\r
+the size of the stack used by the idle task - but allow this to be overridden in\r
+FreeRTOSConfig.h as configMINIMAL_STACK_SIZE is a user definable constant. */\r
+#ifndef configEMAC_TASK_STACK_SIZE\r
+ #define configEMAC_TASK_STACK_SIZE ( 2 * configMINIMAL_STACK_SIZE )\r
+#endif\r
+\r
+\r
+static SemaphoreHandle_t xTXMutex = NULL;\r
+\r
+/* The handle of the task that processes Rx packets. The handle is required so\r
+the task can be notified when new packets arrive. */\r
+static TaskHandle_t xRxHanderTask = NULL;\r
+static TimerHandle_t xPhyHandlerTask = NULL;\r
+/*\r
+ * A task that processes received frames.\r
+ */\r
+static void prvEMACHandlerTask( void *pvParameters );\r
+static void prvPhyTmrCallback( TimerHandle_t xTimer );\r
+\r
+/* The size of each buffer when BufferAllocation_1 is used:\r
+http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Ethernet_Buffer_Management.html */\r
+\r
+#define niBUFFER_1_PACKET_SIZE 1536\r
+#ifdef __ICCARM__\r
+#pragma data_alignment=4\r
+static uint8_t ucNetworkPackets[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS * niBUFFER_1_PACKET_SIZE ]\r
+#else\r
+static uint8_t ucNetworkPackets[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS * niBUFFER_1_PACKET_SIZE ] __attribute__ ((aligned(4)));\r
+#endif\r
+\r
+BaseType_t xNetworkInterfaceInitialise( void )\r
+{\r
+ uint8_t hwaddr[6];\r
+ BaseType_t xReturn = pdPASS;\r
+\r
+ /* Init ETH */\r
+ numaker_mac_address(hwaddr);\r
+ FreeRTOS_UpdateMACAddress(hwaddr);\r
+ FreeRTOS_printf( ("mac address %02x-%02x-%02x-%02x-%02x-%02x \r\n", hwaddr[0], hwaddr[1],hwaddr[2],hwaddr[3],hwaddr[4],hwaddr[5]) );\r
+ /* Enable clock & set EMAC configuration */\r
+ /* Enable MAC and DMA transmission and reception */\r
+ if( numaker_eth_init(hwaddr) < 0)\r
+ {\r
+ xReturn = pdFAIL;\r
+ } else {\r
+ xReturn = pdPASS;\r
+ /* Guard against the task being created more than once and the\r
+ descriptors being initialized more than once. */\r
+ /* Timer task to monitor PHY Link status */\r
+ if( xPhyHandlerTask == NULL )\r
+ {\r
+ xPhyHandlerTask = xTimerCreate( "TimerPhy", pdMS_TO_TICKS( 1000 ), pdTRUE, 0, prvPhyTmrCallback );\r
+ configASSERT(xPhyHandlerTask);\r
+ xReturn = xTimerStart( xPhyHandlerTask, 0 ) ;\r
+ configASSERT( xReturn );\r
+ }\r
+ /* Rx task */\r
+ if( xRxHanderTask == NULL )\r
+ {\r
+ xReturn = xTaskCreate( prvEMACHandlerTask, "EMAC", configEMAC_TASK_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, &xRxHanderTask );\r
+ configASSERT( xReturn );\r
+ }\r
+ \r
+ if( xTXMutex == NULL )\r
+ {\r
+ xTXMutex = xSemaphoreCreateMutex();\r
+ configASSERT( xTXMutex );\r
+ } \r
+ }\r
+\r
+ NVIC_SetPriority( EMAC_RX_IRQn, configMAC_INTERRUPT_PRIORITY );\r
+ NVIC_SetPriority( EMAC_TX_IRQn, configMAC_INTERRUPT_PRIORITY );\r
+\r
+ numaker_eth_enable_interrupts();\r
+\r
+ FreeRTOS_printf( ("ETH-RX priority:%d\n",NVIC_GetPriority( EMAC_RX_IRQn)) );\r
+\r
+ return xReturn;\r
+}\r
+\r
+BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxDescriptor, BaseType_t xReleaseAfterSend )\r
+{\r
+ uint8_t *buffer=NULL;\r
+// FreeRTOS_printf(("<-- dataLength=%d\n",pxDescriptor->xDataLength));\r
+ if( pxDescriptor->xDataLength >= PACKET_BUFFER_SIZE )\r
+ {\r
+ FreeRTOS_printf(("TX buffer length %d over %d\n", pxDescriptor->xDataLength, PACKET_BUFFER_SIZE));\r
+ return pdFALSE;\r
+ }\r
+ \r
+ buffer = numaker_eth_get_tx_buf();\r
+ if( buffer == NULL )\r
+ {\r
+ NU_DEBUGF(("Eth TX slots are busy\n"));\r
+ return pdFALSE;\r
+ } \r
+ \r
+ /* Get exclusive access */\r
+ xSemaphoreTake(xTXMutex, portMAX_DELAY);\r
+ NU_DEBUGF(("%s ... buffer=0x%x\r\n",__FUNCTION__, buffer)); \r
+ //SendData: pt = pxDescriptor->pucBuffer, length = pxDescriptor->xDataLength\r
+ memcpy(buffer, pxDescriptor->pucEthernetBuffer, pxDescriptor->xDataLength);\r
+ numaker_eth_trigger_tx(pxDescriptor->xDataLength, NULL);\r
+ /* Call the standard trace macro to log the send event. */\r
+ iptraceNETWORK_INTERFACE_TRANSMIT();\r
+\r
+ if( xReleaseAfterSend != pdFALSE )\r
+ {\r
+ /* It is assumed SendData() copies the data out of the FreeRTOS+TCP Ethernet\r
+ buffer. The Ethernet buffer is therefore no longer needed, and must be\r
+ freed for re-use. */\r
+ vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
+ }\r
+\r
+ xSemaphoreGive(xTXMutex);\r
+ \r
+ return pdTRUE;\r
+}\r
+\r
+\r
+void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )\r
+{\r
+\r
+ uint8_t *ucRAMBuffer = ucNetworkPackets;\r
+ uint32_t ul;\r
+\r
+ for( ul = 0; ul < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; ul++ )\r
+ {\r
+ pxNetworkBuffers[ ul ].pucEthernetBuffer = ucRAMBuffer + ipBUFFER_PADDING;\r
+ *( ( unsigned * ) ucRAMBuffer ) = ( unsigned ) ( &( pxNetworkBuffers[ ul ] ) );\r
+ ucRAMBuffer += niBUFFER_1_PACKET_SIZE;\r
+ }\r
+}\r
+\r
+\r
+BaseType_t xGetPhyLinkStatus( void )\r
+{\r
+ BaseType_t xReturn;\r
+\r
+ if( numaker_eth_link_ok() )\r
+ {\r
+ xReturn = pdPASS;\r
+ }\r
+ else\r
+ {\r
+ xReturn = pdFAIL;\r
+ }\r
+\r
+ return xReturn;\r
+}\r
+\r
+static void prvPhyTmrCallback( TimerHandle_t xTimer )\r
+{\r
+ IPStackEvent_t xRxEvent;\r
+ static BaseType_t lastLink = pdFAIL;\r
+ BaseType_t currLink = xGetPhyLinkStatus();\r
+ if( currLink != lastLink )\r
+ {\r
+ FreeRTOS_printf(("PHY Link %s\n", (currLink) ? "Up" : "Down"));\r
+ if( !currLink )\r
+ {\r
+ xRxEvent.eEventType = eNetworkDownEvent;\r
+ xSendEventStructToIPTask( &xRxEvent, 0 );\r
+ }\r
+ lastLink = currLink;\r
+ }\r
+\r
+} \r
+\r
+ \r
+static void prvEMACHandlerTask( void *pvParameters )\r
+{\r
+ TimeOut_t xPhyTime;\r
+ TickType_t xPhyRemTime;\r
+ UBaseType_t uxLastMinBufferCount = 0;\r
+ UBaseType_t uxCurrentCount;\r
+ BaseType_t xResult = 0;\r
+ uint32_t ulStatus;\r
+ uint16_t dataLength = 0;\r
+ uint8_t *buffer = NULL;\r
+ NetworkBufferDescriptor_t *pxBufferDescriptor = NULL;\r
+ IPStackEvent_t xRxEvent;\r
+ const TickType_t xBlockTime = pdMS_TO_TICKS( 5000ul );\r
+ \r
+ /* Remove compiler warnings about unused parameters. */\r
+ ( void ) pvParameters;\r
+ /* A possibility to set some additional task properties. */\r
+ \r
+ for( ;; )\r
+ {\r
+ uxCurrentCount = uxGetMinimumFreeNetworkBuffers();\r
+ if( uxLastMinBufferCount != uxCurrentCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinBufferCount = uxCurrentCount;\r
+ FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",\r
+ uxGetNumberOfFreeNetworkBuffers(), uxCurrentCount ) );\r
+ }\r
+ \r
+ /* No events to process now, wait for the next. */\r
+ ulTaskNotifyTake( pdFALSE, portMAX_DELAY ); \r
+ while(1)\r
+ { \r
+ /* get received frame */\r
+ if ( numaker_eth_get_rx_buf(&dataLength, &buffer) != 0) {\r
+ /* The event was lost because a network buffer was not available.\r
+ Call the standard trace macro to log the occurrence. */\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ break;\r
+ } \r
+\r
+ /* Allocate a network buffer descriptor that points to a buffer\r
+ large enough to hold the received frame. As this is the simple\r
+ rather than efficient example the received data will just be copied\r
+ into this buffer. */\r
+\r
+ pxBufferDescriptor = pxGetNetworkBufferWithDescriptor( PACKET_BUFFER_SIZE, 0 );\r
+\r
+ if( pxBufferDescriptor != NULL )\r
+ { \r
+ memcpy( pxBufferDescriptor->pucEthernetBuffer, buffer, dataLength );\r
+// FreeRTOS_printf(("--> dataLength=%d\n",dataLength));\r
+ pxBufferDescriptor->xDataLength = dataLength; \r
+ } else {\r
+ numaker_eth_rx_next();\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ break;\r
+ }\r
+ /* The event about to be sent to the TCP/IP is an Rx event. */\r
+ xRxEvent.eEventType = eNetworkRxEvent;\r
+\r
+ /* pvData is used to point to the network buffer descriptor that\r
+ now references the received data. */\r
+ xRxEvent.pvData = ( void * ) pxBufferDescriptor;\r
+\r
+ /* Send the data to the TCP/IP stack. */\r
+ if( xSendEventStructToIPTask( &xRxEvent, 0 ) == pdFALSE )\r
+ {\r
+ /* The buffer could not be sent to the IP task so the buffer\r
+ must be released. */\r
+ vReleaseNetworkBufferAndDescriptor( pxBufferDescriptor );\r
+\r
+ /* Make a call to the standard trace macro to log the\r
+ occurrence. */\r
+\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ } else\r
+ {\r
+ /* The message was successfully sent to the TCP/IP stack.\r
+ Call the standard trace macro to log the occurrence. */\r
+ iptraceNETWORK_INTERFACE_RECEIVE();\r
+ } \r
+ numaker_eth_rx_next();\r
+ } \r
+ numaker_eth_trigger_rx();\r
+ }\r
+}\r
+\r
+void xNetworkCallback(char event)\r
+{\r
+ BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
+ switch (event)\r
+ {\r
+ case 'R': //For RX event\r
+ /* Wakeup the prvEMACHandlerTask. */\r
+ if( xRxHanderTask != NULL )\r
+ {\r
+ vTaskNotifyGiveFromISR( xRxHanderTask, &xHigherPriorityTaskWoken );\r
+ portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
+ }\r
+ break;\r
+ case 'T': //For TX event\r
+ // ack of tx done, no-op in this stage\r
+ break;\r
+ default:\r
+ break;\r
+ }\r
+}\r
--- /dev/null
+/**************************************************************************//**\r
+ * @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved.\r
+ * \r
+ * Redistribution and use in source and binary forms, with or without modification,\r
+ * are permitted provided that the following conditions are met:\r
+ * 1. Redistributions of source code must retain the above copyright notice,\r
+ * this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright notice,\r
+ * this list of conditions and the following disclaimer in the documentation\r
+ * and/or other materials provided with the distribution.\r
+ * 3. Neither the name of Nuvoton Technology Corp. nor the names of its contributors\r
+ * may be used to endorse or promote products derived from this software\r
+ * without specific prior written permission.\r
+ * \r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+*****************************************************************************/\r
+#include "FreeRTOS.h"\r
+#include "list.h"\r
+#include "FreeRTOS_IP.h"\r
+\r
+#include "m480_eth.h"\r
+\r
+#define ETH_TRIGGER_RX() do{EMAC->RXST = 0;}while(0)\r
+#define ETH_TRIGGER_TX() do{EMAC->TXST = 0;}while(0)\r
+#define ETH_ENABLE_TX() do{EMAC->CTL |= EMAC_CTL_TXON;}while(0)\r
+#define ETH_ENABLE_RX() do{EMAC->CTL |= EMAC_CTL_RXON;}while(0)\r
+#define ETH_DISABLE_TX() do{EMAC->CTL &= ~EMAC_CTL_TXON;}while(0)\r
+#define ETH_DISABLE_RX() do{EMAC->CTL &= ~EMAC_CTL_RXON;}while(0)\r
+ \r
+\r
+struct eth_descriptor rx_desc[RX_DESCRIPTOR_NUM] __attribute__ ((aligned(4)));\r
+struct eth_descriptor tx_desc[TX_DESCRIPTOR_NUM] __attribute__ ((aligned(4)));\r
+#ifdef __ICCARM__\r
+#pragma data_alignment=4\r
+struct eth_descriptor rx_desc[RX_DESCRIPTOR_NUM];\r
+struct eth_descriptor tx_desc[TX_DESCRIPTOR_NUM];\r
+uint8_t rx_buf[RX_DESCRIPTOR_NUM][PACKET_BUFFER_SIZE];\r
+uint8_t tx_buf[TX_DESCRIPTOR_NUM][PACKET_BUFFER_SIZE];\r
+#else\r
+struct eth_descriptor rx_desc[RX_DESCRIPTOR_NUM] __attribute__ ((aligned(4)));\r
+struct eth_descriptor tx_desc[TX_DESCRIPTOR_NUM] __attribute__ ((aligned(4)));\r
+uint8_t rx_buf[RX_DESCRIPTOR_NUM][PACKET_BUFFER_SIZE] __attribute__ ((aligned(4)));\r
+uint8_t tx_buf[TX_DESCRIPTOR_NUM][PACKET_BUFFER_SIZE] __attribute__ ((aligned(4)));\r
+#endif\r
+struct eth_descriptor volatile *cur_tx_desc_ptr, *cur_rx_desc_ptr, *fin_tx_desc_ptr;\r
+\r
+\r
+// PTP source clock is 84MHz (Real chip using PLL). Each tick is 11.90ns\r
+// Assume we want to set each tick to 100ns.\r
+// Increase register = (100 * 2^31) / (10^9) = 214.71 =~ 215 = 0xD7\r
+// Addend register = 2^32 * tick_freq / (84MHz), where tick_freq = (2^31 / 215) MHz\r
+// From above equation, addend register = 2^63 / (84M * 215) ~= 510707200 = 0x1E70C600\r
+\r
+\r
+\r
+static void mdio_write(uint8_t addr, uint8_t reg, uint16_t val)\r
+{\r
+\r
+ EMAC->MIIMDAT = val;\r
+ EMAC->MIIMCTL = (addr << EMAC_MIIMCTL_PHYADDR_Pos) | reg | EMAC_MIIMCTL_BUSY_Msk | EMAC_MIIMCTL_WRITE_Msk | EMAC_MIIMCTL_MDCON_Msk;\r
+\r
+ while (EMAC->MIIMCTL & EMAC_MIIMCTL_BUSY_Msk);\r
+\r
+}\r
+\r
+\r
+static uint16_t mdio_read(uint8_t addr, uint8_t reg)\r
+{\r
+ EMAC->MIIMCTL = (addr << EMAC_MIIMCTL_PHYADDR_Pos) | reg | EMAC_MIIMCTL_BUSY_Msk | EMAC_MIIMCTL_MDCON_Msk;\r
+ while (EMAC->MIIMCTL & EMAC_MIIMCTL_BUSY_Msk);\r
+\r
+ return(EMAC->MIIMDAT);\r
+}\r
+\r
+static int reset_phy(void)\r
+{\r
+\r
+ uint16_t reg;\r
+ uint32_t delayCnt;\r
+\r
+\r
+ mdio_write(CONFIG_PHY_ADDR, MII_BMCR, BMCR_RESET);\r
+\r
+ delayCnt = 2000;\r
+ while(delayCnt-- > 0) {\r
+ if((mdio_read(CONFIG_PHY_ADDR, MII_BMCR) & BMCR_RESET) == 0)\r
+ break;\r
+\r
+ }\r
+\r
+ if(delayCnt == 0) {\r
+ NU_DEBUGF(("Reset phy failed\n"));\r
+ return(-1);\r
+ }\r
+\r
+ mdio_write(CONFIG_PHY_ADDR, MII_ADVERTISE, ADVERTISE_CSMA |\r
+ ADVERTISE_10HALF |\r
+ ADVERTISE_10FULL |\r
+ ADVERTISE_100HALF |\r
+ ADVERTISE_100FULL);\r
+\r
+ reg = mdio_read(CONFIG_PHY_ADDR, MII_BMCR);\r
+ mdio_write(CONFIG_PHY_ADDR, MII_BMCR, reg | BMCR_ANRESTART);\r
+\r
+ delayCnt = 200000;\r
+ while(delayCnt-- > 0) {\r
+ if((mdio_read(CONFIG_PHY_ADDR, MII_BMSR) & (BMSR_ANEGCOMPLETE | BMSR_LSTATUS))\r
+ == (BMSR_ANEGCOMPLETE | BMSR_LSTATUS))\r
+ break;\r
+ }\r
+\r
+ if(delayCnt == 0) {\r
+ NU_DEBUGF(("AN failed. Set to 100 FULL\n"));\r
+ EMAC->CTL |= (EMAC_CTL_OPMODE_Msk | EMAC_CTL_FUDUP_Msk);\r
+ return(-1);\r
+ } else {\r
+ reg = mdio_read(CONFIG_PHY_ADDR, MII_LPA);\r
+\r
+ if(reg & ADVERTISE_100FULL) {\r
+ NU_DEBUGF(("100 full\n"));\r
+ EMAC->CTL |= (EMAC_CTL_OPMODE_Msk | EMAC_CTL_FUDUP_Msk);\r
+ } else if(reg & ADVERTISE_100HALF) {\r
+ NU_DEBUGF(("100 half\n"));\r
+ EMAC->CTL = (EMAC->CTL & ~EMAC_CTL_FUDUP_Msk) | EMAC_CTL_OPMODE_Msk;\r
+ } else if(reg & ADVERTISE_10FULL) {\r
+ NU_DEBUGF(("10 full\n"));\r
+ EMAC->CTL = (EMAC->CTL & ~EMAC_CTL_OPMODE_Msk) | EMAC_CTL_FUDUP_Msk;\r
+ } else {\r
+ NU_DEBUGF(("10 half\n"));\r
+ EMAC->CTL &= ~(EMAC_CTL_OPMODE_Msk | EMAC_CTL_FUDUP_Msk);\r
+ }\r
+ }\r
+ FreeRTOS_printf(("PHY ID 1:0x%x\r\n", mdio_read(CONFIG_PHY_ADDR, MII_PHYSID1)));\r
+ FreeRTOS_printf(("PHY ID 2:0x%x\r\n", mdio_read(CONFIG_PHY_ADDR, MII_PHYSID2)));\r
+\r
+ return(0);\r
+}\r
+\r
+\r
+static void init_tx_desc(void)\r
+{\r
+ uint32_t i;\r
+\r
+\r
+ cur_tx_desc_ptr = fin_tx_desc_ptr = &tx_desc[0];\r
+\r
+ for(i = 0; i < TX_DESCRIPTOR_NUM; i++) {\r
+ tx_desc[i].status1 = TXFD_PADEN | TXFD_CRCAPP | TXFD_INTEN;\r
+ tx_desc[i].buf = &tx_buf[i][0];\r
+ tx_desc[i].status2 = 0;\r
+ tx_desc[i].next = &tx_desc[(i + 1) % TX_DESCRIPTOR_NUM];\r
+\r
+ }\r
+ EMAC->TXDSA = (unsigned int)&tx_desc[0];\r
+ return;\r
+}\r
+\r
+static void init_rx_desc(void)\r
+{\r
+ uint32_t i;\r
+\r
+\r
+ cur_rx_desc_ptr = &rx_desc[0];\r
+\r
+ for(i = 0; i < RX_DESCRIPTOR_NUM; i++) {\r
+ rx_desc[i].status1 = OWNERSHIP_EMAC;\r
+ rx_desc[i].buf = &rx_buf[i][0];\r
+ rx_desc[i].status2 = 0;\r
+ rx_desc[i].next = &rx_desc[(i + 1) % TX_DESCRIPTOR_NUM];\r
+ }\r
+ EMAC->RXDSA = (unsigned int)&rx_desc[0];\r
+ return;\r
+}\r
+\r
+void numaker_set_mac_addr(uint8_t *addr)\r
+{\r
+\r
+ EMAC->CAM0M = (addr[0] << 24) |\r
+ (addr[1] << 16) |\r
+ (addr[2] << 8) |\r
+ addr[3];\r
+\r
+ EMAC->CAM0L = (addr[4] << 24) |\r
+ (addr[5] << 16);\r
+\r
+\r
+}\r
+\r
+static void __eth_clk_pin_init()\r
+{\r
+ /* Unlock protected registers */\r
+ SYS_UnlockReg();\r
+\r
+ /* Enable IP clock */\r
+ CLK_EnableModuleClock(EMAC_MODULE);\r
+ \r
+ // Configure MDC clock rate to HCLK / (127 + 1) = 1.25 MHz if system is running at 160 MH\r
+ CLK_SetModuleClock(EMAC_MODULE, 0, CLK_CLKDIV3_EMAC(127));\r
+ \r
+ /* Update System Core Clock */\r
+ SystemCoreClockUpdate();\r
+ \r
+ /*---------------------------------------------------------------------------------------------------------*/\r
+ /* Init I/O Multi-function */\r
+ /*---------------------------------------------------------------------------------------------------------*/\r
+ // Configure RMII pins\r
+ SYS->GPA_MFPL &= ~(SYS_GPA_MFPL_PA6MFP_Msk | SYS_GPA_MFPL_PA7MFP_Msk);\r
+ SYS->GPA_MFPL |= SYS_GPA_MFPL_PA6MFP_EMAC_RMII_RXERR | SYS_GPA_MFPL_PA7MFP_EMAC_RMII_CRSDV;\r
+ SYS->GPC_MFPL &= ~(SYS_GPC_MFPL_PC6MFP_Msk | SYS_GPC_MFPL_PC7MFP_Msk);\r
+ SYS->GPC_MFPL |= SYS_GPC_MFPL_PC6MFP_EMAC_RMII_RXD1 | SYS_GPC_MFPL_PC7MFP_EMAC_RMII_RXD0;\r
+ SYS->GPC_MFPH &= ~SYS_GPC_MFPH_PC8MFP_Msk;\r
+ SYS->GPC_MFPH |= SYS_GPC_MFPH_PC8MFP_EMAC_RMII_REFCLK;\r
+ SYS->GPE_MFPH &= ~(SYS_GPE_MFPH_PE8MFP_Msk | SYS_GPE_MFPH_PE9MFP_Msk | SYS_GPE_MFPH_PE10MFP_Msk |\r
+ SYS_GPE_MFPH_PE11MFP_Msk | SYS_GPE_MFPH_PE12MFP_Msk);\r
+ SYS->GPE_MFPH |= SYS_GPE_MFPH_PE8MFP_EMAC_RMII_MDC |\r
+ SYS_GPE_MFPH_PE9MFP_EMAC_RMII_MDIO |\r
+ SYS_GPE_MFPH_PE10MFP_EMAC_RMII_TXD0 |\r
+ SYS_GPE_MFPH_PE11MFP_EMAC_RMII_TXD1 |\r
+ SYS_GPE_MFPH_PE12MFP_EMAC_RMII_TXEN;\r
+\r
+ // Enable high slew rate on all RMII TX output pins\r
+ PE->SLEWCTL = (GPIO_SLEWCTL_HIGH << GPIO_SLEWCTL_HSREN10_Pos) |\r
+ (GPIO_SLEWCTL_HIGH << GPIO_SLEWCTL_HSREN11_Pos) |\r
+ (GPIO_SLEWCTL_HIGH << GPIO_SLEWCTL_HSREN12_Pos);\r
+\r
+\r
+ /* Lock protected registers */\r
+ SYS_LockReg();\r
+\r
+\r
+}\r
+\r
+int numaker_eth_init(uint8_t *mac_addr)\r
+{\r
+ int ret = 0;\r
+ // init CLK & pins\r
+ __eth_clk_pin_init();\r
+ \r
+ // Reset MAC\r
+ EMAC->CTL = EMAC_CTL_RST_Msk;\r
+ while(EMAC->CTL & EMAC_CTL_RST_Msk) {}\r
+\r
+ init_tx_desc();\r
+ init_rx_desc();\r
+\r
+ numaker_set_mac_addr(mac_addr); // need to reconfigure hardware address 'cos we just RESET emc...\r
+\r
+\r
+ /* Configure the MAC interrupt enable register. */\r
+ EMAC->INTEN = EMAC_INTEN_RXIEN_Msk |\r
+ EMAC_INTEN_TXIEN_Msk |\r
+ EMAC_INTEN_RXGDIEN_Msk |\r
+ EMAC_INTEN_TXCPIEN_Msk |\r
+ EMAC_INTEN_RXBEIEN_Msk |\r
+ EMAC_INTEN_TXBEIEN_Msk |\r
+ EMAC_INTEN_RDUIEN_Msk |\r
+ EMAC_INTEN_TSALMIEN_Msk |\r
+ EMAC_INTEN_WOLIEN_Msk;\r
+\r
+ /* Configure the MAC control register. */\r
+ EMAC->CTL = EMAC_CTL_STRIPCRC_Msk | EMAC_CTL_RMIIEN_Msk;\r
+\r
+ /* Accept packets for us and all broadcast and multicast packets */\r
+ EMAC->CAMCTL = EMAC_CAMCTL_CMPEN_Msk |\r
+ EMAC_CAMCTL_AMP_Msk |\r
+ EMAC_CAMCTL_ABP_Msk;\r
+ EMAC->CAMEN = 1; // Enable CAM entry 0 \r
+\r
+ ret= reset_phy(); \r
+ \r
+ EMAC_ENABLE_RX();\r
+ EMAC_ENABLE_TX();\r
+ return ret;\r
+}\r
+\r
+\r
+\r
+void ETH_halt(void)\r
+{\r
+\r
+ EMAC->CTL &= ~(EMAC_CTL_RXON_Msk | EMAC_CTL_TXON_Msk);\r
+}\r
+\r
+unsigned int m_status;\r
+\r
+void EMAC_RX_IRQHandler(void)\r
+{\r
+// NU_DEBUGF(("%s ... \r\n", __FUNCTION__));\r
+ m_status = EMAC->INTSTS & 0xFFFF;\r
+ EMAC->INTSTS = m_status;\r
+ if (m_status & EMAC_INTSTS_RXBEIF_Msk) {\r
+ // Shouldn't goes here, unless descriptor corrupted\r
+ NU_DEBUGF(("RX descriptor corrupted \r\n"));\r
+ //return;\r
+ }\r
+ // FIX ME: for rx-event, to ack rx_isr into event queue\r
+ xNetworkCallback('R');\r
+}\r
+\r
+\r
+void numaker_eth_trigger_rx(void)\r
+{\r
+ ETH_TRIGGER_RX();\r
+}\r
+\r
+int numaker_eth_get_rx_buf(uint16_t *len, uint8_t **buf)\r
+{\r
+ unsigned int cur_entry, status;\r
+\r
+ cur_entry = EMAC->CRXDSA;\r
+ if ((cur_entry == (uint32_t)cur_rx_desc_ptr) && (!(m_status & EMAC_INTSTS_RDUIF_Msk))) // cur_entry may equal to cur_rx_desc_ptr if RDU occures\r
+ return -1;\r
+ status = cur_rx_desc_ptr->status1;\r
+\r
+ if(status & OWNERSHIP_EMAC)\r
+ return -1;\r
+\r
+ if (status & RXFD_RXGD) {\r
+ *buf = cur_rx_desc_ptr->buf;\r
+ *len = status & 0xFFFF;\r
+ }\r
+ return 0;\r
+} \r
+\r
+void numaker_eth_rx_next(void)\r
+{\r
+ cur_rx_desc_ptr->status1 = OWNERSHIP_EMAC;\r
+ cur_rx_desc_ptr = cur_rx_desc_ptr->next; \r
+} \r
+\r
+void EMAC_TX_IRQHandler(void)\r
+{\r
+ unsigned int cur_entry, status;\r
+\r
+ status = EMAC->INTSTS & 0xFFFF0000;\r
+ EMAC->INTSTS = status;\r
+ if(status & EMAC_INTSTS_TXBEIF_Msk) {\r
+ // Shouldn't goes here, unless descriptor corrupted\r
+ return;\r
+ }\r
+\r
+ cur_entry = EMAC->CTXDSA;\r
+\r
+ while (cur_entry != (uint32_t)fin_tx_desc_ptr) {\r
+\r
+ fin_tx_desc_ptr = fin_tx_desc_ptr->next;\r
+ }\r
+ // FIX ME: for tx-event, no-op at this stage\r
+ xNetworkCallback('T');\r
+}\r
+\r
+uint8_t *numaker_eth_get_tx_buf(void)\r
+{\r
+ if(cur_tx_desc_ptr->status1 & OWNERSHIP_EMAC)\r
+ return(NULL);\r
+ else\r
+ return(cur_tx_desc_ptr->buf);\r
+}\r
+\r
+void numaker_eth_trigger_tx(uint16_t length, void *p)\r
+{\r
+ struct eth_descriptor volatile *desc;\r
+ cur_tx_desc_ptr->status2 = (unsigned int)length;\r
+ desc = cur_tx_desc_ptr->next; // in case TX is transmitting and overwrite next pointer before we can update cur_tx_desc_ptr\r
+ cur_tx_desc_ptr->status1 |= OWNERSHIP_EMAC;\r
+ cur_tx_desc_ptr = desc;\r
+\r
+ ETH_TRIGGER_TX();\r
+\r
+}\r
+\r
+int numaker_eth_link_ok(void)\r
+{\r
+ /* first, a dummy read to latch */\r
+ mdio_read(CONFIG_PHY_ADDR, MII_BMSR);\r
+ if(mdio_read(CONFIG_PHY_ADDR, MII_BMSR) & BMSR_LSTATUS)\r
+ return 1;\r
+ return 0; \r
+}\r
+\r
+//void numaker_eth_set_cb(eth_callback_t eth_cb, void *userData)\r
+//{\r
+// nu_eth_txrx_cb = eth_cb;\r
+// nu_userData = userData;\r
+//}\r
+\r
+// Provide ethernet devices with a semi-unique MAC address\r
+void numaker_mac_address(uint8_t *mac)\r
+{\r
+ uint32_t uID1;\r
+ // Fetch word 0\r
+ uint32_t word0 = *(uint32_t *)0x7F804; // 2KB Data Flash at 0x7F800\r
+ // Fetch word 1\r
+ // we only want bottom 16 bits of word1 (MAC bits 32-47)\r
+ // and bit 9 forced to 1, bit 8 forced to 0\r
+ // Locally administered MAC, reduced conflicts\r
+ // http://en.wikipedia.org/wiki/MAC_address\r
+ uint32_t word1 = *(uint32_t *)0x7F800; // 2KB Data Flash at 0x7F800\r
+\r
+ if( word0 == 0xFFFFFFFF ) // Not burn any mac address at 1st 2 words of Data Flash\r
+ {\r
+ // with a semi-unique MAC address from the UUID\r
+ /* Enable FMC ISP function */\r
+ SYS_UnlockReg();\r
+ FMC_Open();\r
+ // = FMC_ReadUID(0);\r
+ uID1 = FMC_ReadUID(1);\r
+ word1 = (uID1 & 0x003FFFFF) | ((uID1 & 0x030000) << 6) >> 8;\r
+ word0 = ((FMC_ReadUID(0) >> 4) << 20) | ((uID1 & 0xFF)<<12) | (FMC_ReadUID(2) & 0xFFF);\r
+ /* Disable FMC ISP function */\r
+ FMC_Close();\r
+ /* Lock protected registers */\r
+ SYS_LockReg();\r
+ }\r
+\r
+ word1 |= 0x00000200;\r
+ word1 &= 0x0000FEFF;\r
+\r
+ mac[0] = (word1 & 0x0000ff00) >> 8; \r
+ mac[1] = (word1 & 0x000000ff);\r
+ mac[2] = (word0 & 0xff000000) >> 24;\r
+ mac[3] = (word0 & 0x00ff0000) >> 16;\r
+ mac[4] = (word0 & 0x0000ff00) >> 8;\r
+ mac[5] = (word0 & 0x000000ff);\r
+ \r
+ NU_DEBUGF(("mac address %02x-%02x-%02x-%02x-%02x-%02x \r\n", mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]));\r
+}\r
+\r
+void numaker_eth_enable_interrupts(void) {\r
+ EMAC->INTEN |= EMAC_INTEN_RXIEN_Msk |\r
+ EMAC_INTEN_TXIEN_Msk ;\r
+ NVIC_EnableIRQ(EMAC_RX_IRQn);\r
+ NVIC_EnableIRQ(EMAC_TX_IRQn);\r
+}\r
+\r
+void numaker_eth_disable_interrupts(void) {\r
+ NVIC_DisableIRQ(EMAC_RX_IRQn);\r
+ NVIC_DisableIRQ(EMAC_TX_IRQn);\r
+}\r
--- /dev/null
+/**************************************************************************//**\r
+ * @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved.\r
+ * \r
+ * Redistribution and use in source and binary forms, with or without modification,\r
+ * are permitted provided that the following conditions are met:\r
+ * 1. Redistributions of source code must retain the above copyright notice,\r
+ * this list of conditions and the following disclaimer.\r
+ * 2. Redistributions in binary form must reproduce the above copyright notice,\r
+ * this list of conditions and the following disclaimer in the documentation\r
+ * and/or other materials provided with the distribution.\r
+ * 3. Neither the name of Nuvoton Technology Corp. nor the names of its contributors\r
+ * may be used to endorse or promote products derived from this software\r
+ * without specific prior written permission.\r
+ * \r
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\r
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+*****************************************************************************/\r
+#include "M480.h"\r
+#ifndef _M480_ETH_\r
+#define _M480_ETH_\r
+\r
+/* Generic MII registers. */\r
+\r
+#define MII_BMCR 0x00 /* Basic mode control register */\r
+#define MII_BMSR 0x01 /* Basic mode status register */\r
+#define MII_PHYSID1 0x02 /* PHYS ID 1 */\r
+#define MII_PHYSID2 0x03 /* PHYS ID 2 */\r
+#define MII_ADVERTISE 0x04 /* Advertisement control reg */\r
+#define MII_LPA 0x05 /* Link partner ability reg */\r
+#define MII_EXPANSION 0x06 /* Expansion register */\r
+#define MII_DCOUNTER 0x12 /* Disconnect counter */\r
+#define MII_FCSCOUNTER 0x13 /* False carrier counter */\r
+#define MII_NWAYTEST 0x14 /* N-way auto-neg test reg */\r
+#define MII_RERRCOUNTER 0x15 /* Receive error counter */\r
+#define MII_SREVISION 0x16 /* Silicon revision */\r
+#define MII_RESV1 0x17 /* Reserved... */\r
+#define MII_LBRERROR 0x18 /* Lpback, rx, bypass error */\r
+#define MII_PHYADDR 0x19 /* PHY address */\r
+#define MII_RESV2 0x1a /* Reserved... */\r
+#define MII_TPISTATUS 0x1b /* TPI status for 10mbps */\r
+#define MII_NCONFIG 0x1c /* Network interface config */\r
+\r
+/* Basic mode control register. */\r
+#define BMCR_RESV 0x007f /* Unused... */\r
+#define BMCR_CTST 0x0080 /* Collision test */\r
+#define BMCR_FULLDPLX 0x0100 /* Full duplex */\r
+#define BMCR_ANRESTART 0x0200 /* Auto negotiation restart */\r
+#define BMCR_ISOLATE 0x0400 /* Disconnect DP83840 from MII */\r
+#define BMCR_PDOWN 0x0800 /* Powerdown the DP83840 */\r
+#define BMCR_ANENABLE 0x1000 /* Enable auto negotiation */\r
+#define BMCR_SPEED100 0x2000 /* Select 100Mbps */\r
+#define BMCR_LOOPBACK 0x4000 /* TXD loopback bits */\r
+#define BMCR_RESET 0x8000 /* Reset the DP83840 */\r
+\r
+/* Basic mode status register. */\r
+#define BMSR_ERCAP 0x0001 /* Ext-reg capability */\r
+#define BMSR_JCD 0x0002 /* Jabber detected */\r
+#define BMSR_LSTATUS 0x0004 /* Link status */\r
+#define BMSR_ANEGCAPABLE 0x0008 /* Able to do auto-negotiation */\r
+#define BMSR_RFAULT 0x0010 /* Remote fault detected */\r
+#define BMSR_ANEGCOMPLETE 0x0020 /* Auto-negotiation complete */\r
+#define BMSR_RESV 0x07c0 /* Unused... */\r
+#define BMSR_10HALF 0x0800 /* Can do 10mbps, half-duplex */\r
+#define BMSR_10FULL 0x1000 /* Can do 10mbps, full-duplex */\r
+#define BMSR_100HALF 0x2000 /* Can do 100mbps, half-duplex */\r
+#define BMSR_100FULL 0x4000 /* Can do 100mbps, full-duplex */\r
+#define BMSR_100BASE4 0x8000 /* Can do 100mbps, 4k packets */\r
+\r
+/* Advertisement control register. */\r
+#define ADVERTISE_SLCT 0x001f /* Selector bits */\r
+#define ADVERTISE_CSMA 0x0001 /* Only selector supported */\r
+#define ADVERTISE_10HALF 0x0020 /* Try for 10mbps half-duplex */\r
+#define ADVERTISE_10FULL 0x0040 /* Try for 10mbps full-duplex */\r
+#define ADVERTISE_100HALF 0x0080 /* Try for 100mbps half-duplex */\r
+#define ADVERTISE_100FULL 0x0100 /* Try for 100mbps full-duplex */\r
+#define ADVERTISE_100BASE4 0x0200 /* Try for 100mbps 4k packets */\r
+#define ADVERTISE_RESV 0x1c00 /* Unused... */\r
+#define ADVERTISE_RFAULT 0x2000 /* Say we can detect faults */\r
+#define ADVERTISE_LPACK 0x4000 /* Ack link partners response */\r
+#define ADVERTISE_NPAGE 0x8000 /* Next page bit */\r
+\r
+#define RX_DESCRIPTOR_NUM 4 //8 // Max Number of Rx Frame Descriptors\r
+#define TX_DESCRIPTOR_NUM 2 //4 // Max number of Tx Frame Descriptors\r
+\r
+#define PACKET_BUFFER_SIZE 1520\r
+\r
+#define CONFIG_PHY_ADDR 1\r
+\r
+\r
+// Frame Descriptor's Owner bit\r
+#define OWNERSHIP_EMAC 0x80000000 // 1 = EMAC\r
+//#define OWNERSHIP_CPU 0x7fffffff // 0 = CPU\r
+\r
+\r
+\r
+// Rx Frame Descriptor Status\r
+#define RXFD_RXGD 0x00100000 // Receiving Good Packet Received\r
+#define RXFD_RTSAS 0x00800000 // RX Time Stamp Available \r
+\r
+\r
+// Tx Frame Descriptor's Control bits\r
+#define TXFD_TTSEN 0x08 // Tx Time Stamp Enable\r
+#define TXFD_INTEN 0x04 // Interrupt Enable\r
+#define TXFD_CRCAPP 0x02 // Append CRC\r
+#define TXFD_PADEN 0x01 // Padding Enable\r
+\r
+// Tx Frame Descriptor Status\r
+#define TXFD_TXCP 0x00080000 // Transmission Completion\r
+#define TXFD_TTSAS 0x08000000 // TX Time Stamp Available\r
+\r
+// Tx/Rx buffer descriptor structure\r
+struct eth_descriptor;\r
+struct eth_descriptor {\r
+ uint32_t status1;\r
+ uint8_t *buf;\r
+ uint32_t status2;\r
+ struct eth_descriptor *next;\r
+#ifdef TIME_STAMPING\r
+ uint32_t backup1;\r
+ uint32_t backup2;\r
+ uint32_t reserved1;\r
+ uint32_t reserved2;\r
+#endif\r
+};\r
+\r
+#ifdef TIME_STAMPING\r
+\r
+#define ETH_TS_ENABLE() do{EMAC->TSCTL = EMAC_TSCTL_TSEN_Msk;}while(0)\r
+#define ETH_TS_START() do{EMAC->TSCTL |= (EMAC_TSCTL_TSMODE_Msk | EMAC_TSCTL_TSIEN_Msk);}while(0)\r
+s32_t ETH_settime(u32_t sec, u32_t nsec);\r
+s32_t ETH_gettime(u32_t *sec, u32_t *nsec);\r
+s32_t ETH_updatetime(u32_t neg, u32_t sec, u32_t nsec);\r
+s32_t ETH_adjtimex(int ppm);\r
+void ETH_setinc(void);\r
+\r
+#endif\r
+\r
+#ifdef NU_TRACE\r
+#define NU_DEBUGF(x) { printf x; }\r
+#else\r
+#define NU_DEBUGF(x)\r
+#endif\r
+\r
+void numaker_set_mac_addr(uint8_t *addr);\r
+int numaker_eth_init(uint8_t *mac_addr);\r
+uint8_t *numaker_eth_get_tx_buf(void);\r
+void numaker_eth_trigger_tx(uint16_t length, void *p);\r
+int numaker_eth_get_rx_buf(uint16_t *len, uint8_t **buf);\r
+void numaker_eth_rx_next(void);\r
+void numaker_eth_trigger_rx(void);\r
+int numaker_eth_link_ok(void);\r
+void numaker_mac_address(uint8_t *mac);\r
+void numaker_eth_enable_interrupts(void);\r
+void numaker_eth_disable_interrupts(void);\r
+\r
+#endif /* _M480_ETH_ */\r
--- /dev/null
+/***********************************************************************************************************************\r
+* DISCLAIMER\r
+* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\r
+* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\r
+* applicable laws, including copyright laws.\r
+* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING\r
+* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\r
+* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\r
+* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\r
+* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\r
+* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\r
+* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\r
+* this software. By using this software, you agree to the additional terms and conditions found by accessing the\r
+* following link:\r
+* http://www.renesas.com/disclaimer\r
+*\r
+* Copyright (C) 2018 Renesas Electronics Corporation. All rights reserved.\r
+***********************************************************************************************************************/\r
+\r
+/***********************************************************************************************************************\r
+* File Name : NetworkInterface.c\r
+* Device(s) : RX\r
+* Description : Interfaces FreeRTOS TCP/IP stack to RX Ethernet driver.\r
+***********************************************************************************************************************/\r
+\r
+/***********************************************************************************************************************\r
+* History : DD.MM.YYYY Version Description\r
+* : 07.03.2018 0.1 Development\r
+***********************************************************************************************************************/\r
+\r
+/***********************************************************************************************************************\r
+* Includes <System Includes> , "Project Includes"\r
+***********************************************************************************************************************/\r
+#include <stdint.h>\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+\r
+/* FreeRTOS includes. */\r
+#include "FreeRTOS.h"\r
+#include "task.h"\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+/*#include "FreeRTOS_DNS.h" */\r
+#include "NetworkBufferManagement.h"\r
+#include "NetworkInterface.h"\r
+\r
+#include "r_ether_rx_if.h"\r
+#include "r_pinset.h"\r
+\r
+/***********************************************************************************************************************\r
+ * Macro definitions\r
+ **********************************************************************************************************************/\r
+#define ETHER_BUFSIZE_MIN 60\r
+\r
+#if defined( BSP_MCU_RX65N ) || defined( BSP_MCU_RX64M ) || defined( BSP_MCU_RX71M )\r
+ #if ETHER_CFG_MODE_SEL == 0\r
+ #define R_ETHER_PinSet_CHANNEL_0() R_ETHER_PinSet_ETHERC0_MII()\r
+ #elif ETHER_CFG_MODE_SEL == 1\r
+ #define R_ETHER_PinSet_CHANNEL_0() R_ETHER_PinSet_ETHERC0_RMII()\r
+ #endif\r
+#elif defined( BSP_MCU_RX63N )\r
+ #if ETHER_CFG_MODE_SEL == 0\r
+ #define R_ETHER_PinSet_CHANNEL_0() R_ETHER_PinSet_ETHERC_MII()\r
+ #elif ETHER_CFG_MODE_SEL == 1\r
+ #define R_ETHER_PinSet_CHANNEL_0() R_ETHER_PinSet_ETHERC_RMII()\r
+ #endif\r
+#endif /* if defined( BSP_MCU_RX65N ) || defined( BSP_MCU_RX64M ) || defined( BSP_MCU_RX71M ) */\r
+\r
+#ifndef PHY_LS_HIGH_CHECK_TIME_MS\r
+\r
+/* Check if the LinkSStatus in the PHY is still high after 2 seconds of not\r
+ * receiving packets. */\r
+ #define PHY_LS_HIGH_CHECK_TIME_MS 2000\r
+#endif\r
+\r
+#ifndef PHY_LS_LOW_CHECK_TIME_MS\r
+ /* Check if the LinkSStatus in the PHY is still low every second. */\r
+ #define PHY_LS_LOW_CHECK_TIME_MS 1000\r
+#endif\r
+\r
+/***********************************************************************************************************************\r
+ * Private global variables and functions\r
+ **********************************************************************************************************************/\r
+typedef enum\r
+{\r
+ eMACInit, /* Must initialise MAC. */\r
+ eMACPass, /* Initialisation was successful. */\r
+ eMACFailed, /* Initialisation failed. */\r
+} eMAC_INIT_STATUS_TYPE;\r
+\r
+static TaskHandle_t ether_receive_check_task_handle = 0;\r
+static TaskHandle_t ether_link_check_task_handle = 0;\r
+static TaskHandle_t xTaskToNotify = NULL;\r
+static BaseType_t xPHYLinkStatus;\r
+static BaseType_t xReportedStatus;\r
+static eMAC_INIT_STATUS_TYPE xMacInitStatus = eMACInit;\r
+\r
+static int16_t SendData( uint8_t * pucBuffer,\r
+ size_t length );\r
+static int InitializeNetwork( void );\r
+static void prvEMACDeferredInterruptHandlerTask( void * pvParameters );\r
+static void clear_all_ether_rx_discriptors( uint32_t event );\r
+\r
+int32_t callback_ether_regist( void );\r
+void EINT_Trig_isr( void * );\r
+void get_random_number( uint8_t * data,\r
+ uint32_t len );\r
+\r
+void prvLinkStatusChange( BaseType_t xStatus );\r
+#if ( ipconfigHAS_PRINTF != 0 )\r
+ static void prvMonitorResources( void );\r
+#endif\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: xNetworkInterfaceInitialise ()\r
+ * Description : Initialization of Ethernet driver.\r
+ * Arguments : none\r
+ * Return Value : pdPASS, pdFAIL\r
+ **********************************************************************************************************************/\r
+BaseType_t xNetworkInterfaceInitialise( void )\r
+{\r
+ BaseType_t xReturn;\r
+\r
+ if( xMacInitStatus == eMACInit )\r
+ {\r
+ /*\r
+ * Perform the hardware specific network initialization here using the Ethernet driver library to initialize the\r
+ * Ethernet hardware, initialize DMA descriptors, and perform a PHY auto-negotiation to obtain a network link.\r
+ *\r
+ * InitialiseNetwork() uses Ethernet peripheral driver library function, and returns 0 if the initialization fails.\r
+ */\r
+ if( InitializeNetwork() == pdFALSE )\r
+ {\r
+ xMacInitStatus = eMACFailed;\r
+ }\r
+ else\r
+ {\r
+ /* Indicate that the MAC initialisation succeeded. */\r
+ xMacInitStatus = eMACPass;\r
+ }\r
+\r
+ FreeRTOS_printf( ( "InitializeNetwork returns %s\n", ( xMacInitStatus == eMACPass ) ? "OK" : " Fail" ) );\r
+ }\r
+\r
+ if( xMacInitStatus == eMACPass )\r
+ {\r
+ xReturn = xPHYLinkStatus;\r
+ }\r
+ else\r
+ {\r
+ xReturn = pdFAIL;\r
+ }\r
+\r
+ FreeRTOS_printf( ( "xNetworkInterfaceInitialise returns %d\n", xReturn ) );\r
+\r
+ return xReturn;\r
+} /* End of function xNetworkInterfaceInitialise() */\r
+\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: xNetworkInterfaceOutput ()\r
+ * Description : Simple network output interface.\r
+ * Arguments : pxDescriptor, xReleaseAfterSend\r
+ * Return Value : pdTRUE, pdFALSE\r
+ **********************************************************************************************************************/\r
+BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxDescriptor,\r
+ BaseType_t xReleaseAfterSend )\r
+{\r
+ BaseType_t xReturn = pdFALSE;\r
+\r
+ /* Simple network interfaces (as opposed to more efficient zero copy network\r
+ * interfaces) just use Ethernet peripheral driver library functions to copy\r
+ * data from the FreeRTOS+TCP buffer into the peripheral driver's own buffer.\r
+ * This example assumes SendData() is a peripheral driver library function that\r
+ * takes a pointer to the start of the data to be sent and the length of the\r
+ * data to be sent as two separate parameters. The start of the data is located\r
+ * by pxDescriptor->pucEthernetBuffer. The length of the data is located\r
+ * by pxDescriptor->xDataLength. */\r
+ if( xPHYLinkStatus != 0 )\r
+ {\r
+ if( SendData( pxDescriptor->pucEthernetBuffer, pxDescriptor->xDataLength ) >= 0 )\r
+ {\r
+ xReturn = pdTRUE;\r
+ /* Call the standard trace macro to log the send event. */\r
+ iptraceNETWORK_INTERFACE_TRANSMIT();\r
+ }\r
+ }\r
+ else\r
+ {\r
+ /* As the PHY Link Status is low, it makes no sense trying to deliver a packet. */\r
+ }\r
+\r
+ if( xReleaseAfterSend != pdFALSE )\r
+ {\r
+ /* It is assumed SendData() copies the data out of the FreeRTOS+TCP Ethernet\r
+ * buffer. The Ethernet buffer is therefore no longer needed, and must be\r
+ * freed for re-use. */\r
+ vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
+ }\r
+\r
+ return xReturn;\r
+} /* End of function xNetworkInterfaceOutput() */\r
+\r
+\r
+#if ( ipconfigHAS_PRINTF != 0 )\r
+ static void prvMonitorResources()\r
+ {\r
+ static UBaseType_t uxLastMinBufferCount = 0u;\r
+ static UBaseType_t uxCurrentBufferCount = 0u;\r
+ static size_t uxMinLastSize = 0uL;\r
+ static size_t uxCurLastSize = 0uL;\r
+ size_t uxMinSize;\r
+ size_t uxCurSize;\r
+\r
+ uxCurrentBufferCount = uxGetMinimumFreeNetworkBuffers();\r
+\r
+ if( uxLastMinBufferCount != uxCurrentBufferCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ * while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinBufferCount = uxCurrentBufferCount;\r
+ FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",\r
+ uxGetNumberOfFreeNetworkBuffers(), uxCurrentBufferCount ) );\r
+ }\r
+\r
+ uxMinSize = xPortGetMinimumEverFreeHeapSize();\r
+ uxCurSize = xPortGetFreeHeapSize();\r
+\r
+ if( uxMinLastSize != uxMinSize )\r
+ {\r
+ uxCurLastSize = uxCurSize;\r
+ uxMinLastSize = uxMinSize;\r
+ FreeRTOS_printf( ( "Heap: current %lu lowest %lu\n", uxCurSize, uxMinSize ) );\r
+ }\r
+\r
+ #if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
+ {\r
+ static UBaseType_t uxLastMinQueueSpace = 0;\r
+ UBaseType_t uxCurrentCount = 0u;\r
+\r
+ uxCurrentCount = uxGetMinimumIPQueueSpace();\r
+\r
+ if( uxLastMinQueueSpace != uxCurrentCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ * while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinQueueSpace = uxCurrentCount;\r
+ FreeRTOS_printf( ( "Queue space: lowest %lu\n", uxCurrentCount ) );\r
+ }\r
+ }\r
+ #endif /* ipconfigCHECK_IP_QUEUE_SPACE */\r
+ }\r
+#endif /* ( ipconfigHAS_PRINTF != 0 ) */\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: prvEMACDeferredInterruptHandlerTask ()\r
+ * Description : The deferred interrupt handler is a standard RTOS task.\r
+ * Arguments : pvParameters\r
+ * Return Value : none\r
+ **********************************************************************************************************************/\r
+static void prvEMACDeferredInterruptHandlerTask( void * pvParameters )\r
+{\r
+ NetworkBufferDescriptor_t * pxBufferDescriptor;\r
+ int32_t xBytesReceived = 0;\r
+\r
+ /* Avoid compiler warning about unreferenced parameter. */\r
+ ( void ) pvParameters;\r
+\r
+ /* Used to indicate that xSendEventStructToIPTask() is being called because\r
+ * of an Ethernet receive event. */\r
+ IPStackEvent_t xRxEvent;\r
+\r
+ uint8_t * buffer_pointer;\r
+\r
+ /* Some variables related to monitoring the PHY. */\r
+ TimeOut_t xPhyTime;\r
+ TickType_t xPhyRemTime;\r
+ const TickType_t ulMaxBlockTime = pdMS_TO_TICKS( 100UL );\r
+\r
+ vTaskSetTimeOutState( &xPhyTime );\r
+ xPhyRemTime = pdMS_TO_TICKS( PHY_LS_LOW_CHECK_TIME_MS );\r
+\r
+ FreeRTOS_printf( ( "Deferred Interrupt Handler Task started\n" ) );\r
+ xTaskToNotify = ether_receive_check_task_handle;\r
+\r
+ for( ; ; )\r
+ {\r
+ #if ( ipconfigHAS_PRINTF != 0 )\r
+ {\r
+ prvMonitorResources();\r
+ }\r
+ #endif /* ipconfigHAS_PRINTF != 0 ) */\r
+\r
+ /* Wait for the Ethernet MAC interrupt to indicate that another packet\r
+ * has been received. */\r
+ if( xBytesReceived <= 0 )\r
+ {\r
+ ulTaskNotifyTake( pdFALSE, ulMaxBlockTime );\r
+ }\r
+\r
+ /* See how much data was received. */\r
+ xBytesReceived = R_ETHER_Read_ZC2( ETHER_CHANNEL_0, ( void ** ) &buffer_pointer );\r
+\r
+ if( xBytesReceived < 0 )\r
+ {\r
+ /* This is an error. Logged. */\r
+ if( xBytesReceived == ETHER_ERR_LINK )\r
+ {\r
+ /* Auto-negotiation is not completed, and transmission/\r
+ reception is not enabled. Will be logged elsewhere. */\r
+ }\r
+ else\r
+ {\r
+ FreeRTOS_printf( ( "R_ETHER_Read_ZC2: rc = %d not %d\n", xBytesReceived, ETHER_ERR_LINK ) );\r
+ }\r
+ }\r
+ else if( xBytesReceived > 0 )\r
+ {\r
+ /* Allocate a network buffer descriptor that points to a buffer\r
+ * large enough to hold the received frame. As this is the simple\r
+ * rather than efficient example the received data will just be copied\r
+ * into this buffer. */\r
+ pxBufferDescriptor = pxGetNetworkBufferWithDescriptor( ( size_t ) xBytesReceived, 0 );\r
+\r
+ if( pxBufferDescriptor != NULL )\r
+ {\r
+ /* pxBufferDescriptor->pucEthernetBuffer now points to an Ethernet\r
+ * buffer large enough to hold the received data. Copy the\r
+ * received data into pcNetworkBuffer->pucEthernetBuffer. Here it\r
+ * is assumed ReceiveData() is a peripheral driver function that\r
+ * copies the received data into a buffer passed in as the function's\r
+ * parameter. Remember! While is is a simple robust technique -\r
+ * it is not efficient. An example that uses a zero copy technique\r
+ * is provided further down this page. */\r
+ memcpy( pxBufferDescriptor->pucEthernetBuffer, buffer_pointer, ( size_t ) xBytesReceived );\r
+ /*ReceiveData( pxBufferDescriptor->pucEthernetBuffer ); */\r
+\r
+ /* Set the actual packet length, in case a larger buffer was returned. */\r
+ pxBufferDescriptor->xDataLength = ( size_t ) xBytesReceived;\r
+\r
+ R_ETHER_Read_ZC2_BufRelease( ETHER_CHANNEL_0 );\r
+\r
+ /* See if the data contained in the received Ethernet frame needs\r
+ * to be processed. NOTE! It is preferable to do this in\r
+ * the interrupt service routine itself, which would remove the need\r
+ * to unblock this task for packets that don't need processing. */\r
+ if( eConsiderFrameForProcessing( pxBufferDescriptor->pucEthernetBuffer ) == eProcessBuffer )\r
+ {\r
+ /* The event about to be sent to the TCP/IP is an Rx event. */\r
+ xRxEvent.eEventType = eNetworkRxEvent;\r
+\r
+ /* pvData is used to point to the network buffer descriptor that\r
+ * now references the received data. */\r
+ xRxEvent.pvData = ( void * ) pxBufferDescriptor;\r
+\r
+ /* Send the data to the TCP/IP stack. */\r
+ if( xSendEventStructToIPTask( &xRxEvent, 0 ) == pdFALSE )\r
+ {\r
+ /* The buffer could not be sent to the IP task so the buffer must be released. */\r
+ vReleaseNetworkBufferAndDescriptor( pxBufferDescriptor );\r
+\r
+ /* Make a call to the standard trace macro to log the occurrence. */\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ clear_all_ether_rx_discriptors( 0 );\r
+ }\r
+ else\r
+ {\r
+ /* The message was successfully sent to the TCP/IP stack.\r
+ * Call the standard trace macro to log the occurrence. */\r
+ iptraceNETWORK_INTERFACE_RECEIVE();\r
+ R_NOP();\r
+ }\r
+ }\r
+ else\r
+ {\r
+ /* The Ethernet frame can be dropped, but the Ethernet buffer must be released. */\r
+ vReleaseNetworkBufferAndDescriptor( pxBufferDescriptor );\r
+ }\r
+ }\r
+ else\r
+ {\r
+ /* The event was lost because a network buffer was not available.\r
+ * Call the standard trace macro to log the occurrence. */\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ clear_all_ether_rx_discriptors( 1 );\r
+ FreeRTOS_printf( ( "R_ETHER_Read_ZC2: Cleared descriptors\n" ) );\r
+ }\r
+ }\r
+\r
+ if( xBytesReceived > 0 )\r
+ {\r
+ /* A packet was received. No need to check for the PHY status now,\r
+ * but set a timer to check it later on. */\r
+ vTaskSetTimeOutState( &xPhyTime );\r
+ xPhyRemTime = pdMS_TO_TICKS( PHY_LS_HIGH_CHECK_TIME_MS );\r
+\r
+ /* Indicate that the Link Status is high, so that\r
+ * xNetworkInterfaceOutput() can send packets. */\r
+ if( xPHYLinkStatus == 0 )\r
+ {\r
+ xPHYLinkStatus = 1;\r
+ FreeRTOS_printf( ( "prvEMACHandlerTask: PHY LS assume %d\n", xPHYLinkStatus ) );\r
+ }\r
+ }\r
+ else if( ( xTaskCheckForTimeOut( &xPhyTime, &xPhyRemTime ) != pdFALSE ) || ( FreeRTOS_IsNetworkUp() == pdFALSE ) )\r
+ {\r
+ R_ETHER_LinkProcess( 0 );\r
+\r
+ if( xPHYLinkStatus != xReportedStatus )\r
+ {\r
+ xPHYLinkStatus = xReportedStatus;\r
+ FreeRTOS_printf( ( "prvEMACHandlerTask: PHY LS now %d\n", xPHYLinkStatus ) );\r
+ }\r
+\r
+ vTaskSetTimeOutState( &xPhyTime );\r
+\r
+ if( xPHYLinkStatus != 0 )\r
+ {\r
+ xPhyRemTime = pdMS_TO_TICKS( PHY_LS_HIGH_CHECK_TIME_MS );\r
+ }\r
+ else\r
+ {\r
+ xPhyRemTime = pdMS_TO_TICKS( PHY_LS_LOW_CHECK_TIME_MS );\r
+ }\r
+ }\r
+ }\r
+} /* End of function prvEMACDeferredInterruptHandlerTask() */\r
+\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: vNetworkInterfaceAllocateRAMToBuffers ()\r
+ * Description : .\r
+ * Arguments : pxNetworkBuffers\r
+ * Return Value : none\r
+ **********************************************************************************************************************/\r
+void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )\r
+{\r
+ uint32_t ul;\r
+ uint8_t * buffer_address;\r
+\r
+ R_EXTERN_SEC( B_ETHERNET_BUFFERS_1 )\r
+\r
+ buffer_address = R_SECTOP( B_ETHERNET_BUFFERS_1 );\r
+\r
+ for( ul = 0; ul < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; ul++ )\r
+ {\r
+ pxNetworkBuffers[ ul ].pucEthernetBuffer = ( buffer_address + ( ETHER_CFG_BUFSIZE * ul ) );\r
+ }\r
+} /* End of function vNetworkInterfaceAllocateRAMToBuffers() */\r
+\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: prvLinkStatusChange ()\r
+ * Description : Function will be called when the Link Status of the phy has changed ( see ether_callback.c )\r
+ * Arguments : xStatus : true when statyus has become high\r
+ * Return Value : void\r
+ **********************************************************************************************************************/\r
+void prvLinkStatusChange( BaseType_t xStatus )\r
+{\r
+ if( xReportedStatus != xStatus )\r
+ {\r
+ xReportedStatus = xStatus;\r
+ }\r
+}\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: InitializeNetwork ()\r
+ * Description :\r
+ * Arguments : none\r
+ * Return Value : pdTRUE, pdFALSE\r
+ **********************************************************************************************************************/\r
+static int InitializeNetwork( void )\r
+{\r
+ ether_return_t eth_ret;\r
+ BaseType_t return_code = pdFALSE;\r
+ ether_param_t param;\r
+ uint8_t myethaddr[ 6 ] =\r
+ {\r
+ configMAC_ADDR0,\r
+ configMAC_ADDR1,\r
+ configMAC_ADDR2,\r
+ configMAC_ADDR3,\r
+ configMAC_ADDR4,\r
+ configMAC_ADDR5\r
+ }; /*XXX Fix me */\r
+\r
+ R_ETHER_PinSet_CHANNEL_0();\r
+ R_ETHER_Initial();\r
+ callback_ether_regist();\r
+\r
+ param.channel = ETHER_CHANNEL_0;\r
+ eth_ret = R_ETHER_Control( CONTROL_POWER_ON, param ); /* PHY mode settings, module stop cancellation */\r
+\r
+ if( ETHER_SUCCESS != eth_ret )\r
+ {\r
+ return pdFALSE;\r
+ }\r
+\r
+ eth_ret = R_ETHER_Open_ZC2( ETHER_CHANNEL_0, myethaddr, ETHER_FLAG_OFF );\r
+\r
+ if( ETHER_SUCCESS != eth_ret )\r
+ {\r
+ return pdFALSE;\r
+ }\r
+\r
+ return_code = xTaskCreate( prvEMACDeferredInterruptHandlerTask,\r
+ "ETHER_RECEIVE_CHECK_TASK",\r
+ 512u,\r
+ 0,\r
+ configMAX_PRIORITIES - 1,\r
+ ðer_receive_check_task_handle );\r
+\r
+ if( pdFALSE == return_code )\r
+ {\r
+ return pdFALSE;\r
+ }\r
+\r
+ return pdTRUE;\r
+} /* End of function InitializeNetwork() */\r
+\r
+\r
+/***********************************************************************************************************************\r
+ * Function Name: SendData ()\r
+ * Description :\r
+ * Arguments : pucBuffer, length\r
+ * Return Value : 0 success, negative fail\r
+ **********************************************************************************************************************/\r
+static int16_t SendData( uint8_t * pucBuffer,\r
+ size_t length ) /*TODO complete stub function */\r
+{\r
+ ether_return_t ret;\r
+ uint8_t * pwrite_buffer;\r
+ uint16_t write_buf_size;\r
+\r
+ /* (1) Retrieve the transmit buffer location controlled by the descriptor. */\r
+ ret = R_ETHER_Write_ZC2_GetBuf( ETHER_CHANNEL_0, ( void ** ) &pwrite_buffer, &write_buf_size );\r
+\r
+ if( ETHER_SUCCESS == ret )\r
+ {\r
+ if( write_buf_size >= length )\r
+ {\r
+ memcpy( pwrite_buffer, pucBuffer, length );\r
+ }\r
+\r
+ if( length < ETHER_BUFSIZE_MIN ) /*under minimum*/\r
+ {\r
+ memset( ( pwrite_buffer + length ), 0, ( ETHER_BUFSIZE_MIN - length ) ); /*padding*/\r
+ length = ETHER_BUFSIZE_MIN; /*resize*/\r
+ }\r
+\r
+ ret = R_ETHER_Write_ZC2_SetBuf( ETHER_CHANNEL_0, ( uint16_t ) length );\r
+ ret = R_ETHER_CheckWrite( ETHER_CHANNEL_0 );\r
+ }\r
+\r
+ if( ETHER_SUCCESS != ret )\r
+ {\r
+ return -5; /* XXX return meaningful value */\r
+ }\r
+ else\r
+ {\r
+ return 0;\r
+ }\r
+} /* End of function SendData() */\r
+\r
+\r
+/***********************************************************************************************************************\r
+* Function Name: EINT_Trig_isr\r
+* Description : Standard frame received interrupt handler\r
+* Arguments : ectrl - EDMAC and ETHERC control structure\r
+* Return Value : None\r
+* Note : This callback function is executed when EINT0 interrupt occurred.\r
+***********************************************************************************************************************/\r
+void EINT_Trig_isr( void * ectrl )\r
+{\r
+ ether_cb_arg_t * pdecode;\r
+ BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
+\r
+ pdecode = ( ether_cb_arg_t * ) ectrl;\r
+\r
+ if( pdecode->status_eesr & 0x00040000 ) /* EDMAC FR (Frame Receive Event) interrupt */\r
+ {\r
+ if( xTaskToNotify != NULL )\r
+ {\r
+ vTaskNotifyGiveFromISR( ether_receive_check_task_handle, &xHigherPriorityTaskWoken );\r
+ }\r
+\r
+ /* If xHigherPriorityTaskWoken is now set to pdTRUE then a context switch\r
+ * should be performed to ensure the interrupt returns directly to the highest\r
+ * priority task. The macro used for this purpose is dependent on the port in\r
+ * use and may be called portEND_SWITCHING_ISR(). */\r
+ portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
+ /*TODO complete interrupt handler for other events. */\r
+ }\r
+} /* End of function EINT_Trig_isr() */\r
+\r
+\r
+static void clear_all_ether_rx_discriptors( uint32_t event )\r
+{\r
+ int32_t xBytesReceived;\r
+ uint8_t * buffer_pointer;\r
+\r
+ /* Avoid compiler warning about unreferenced parameter. */\r
+ ( void ) event;\r
+\r
+ while( 1 )\r
+ {\r
+ /* See how much data was received. */\r
+ xBytesReceived = R_ETHER_Read_ZC2( ETHER_CHANNEL_0, ( void ** ) &buffer_pointer );\r
+\r
+ if( 0 > xBytesReceived )\r
+ {\r
+ /* This is an error. Ignored. */\r
+ }\r
+ else if( 0 < xBytesReceived )\r
+ {\r
+ R_ETHER_Read_ZC2_BufRelease( ETHER_CHANNEL_0 );\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ }\r
+ else\r
+ {\r
+ break;\r
+ }\r
+ }\r
+}\r
+\r
+/***********************************************************************************************************************\r
+ * End of file "NetworkInterface.c"\r
+ **********************************************************************************************************************/\r
--- /dev/null
+/***********************************************************************************************************************\r
+* DISCLAIMER\r
+* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No\r
+* other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all\r
+* applicable laws, including copyright laws.\r
+* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING\r
+* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,\r
+* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM\r
+* EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES\r
+* SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS\r
+* SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\r
+* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of\r
+* this software. By using this software, you agree to the additional terms and conditions found by accessing the\r
+* following link:\r
+* http://www.renesas.com/disclaimer\r
+*\r
+* Copyright (C) 2015 Renesas Electronics Corporation. All rights reserved.\r
+***********************************************************************************************************************/\r
+/***********************************************************************************************************************\r
+* File Name : ether_callback.c\r
+* Version : ----\r
+* Description : This module solves all the world's problems\r
+***********************************************************************************************************************/\r
+/**********************************************************************************************************************\r
+* History : DD.MM.YYYY Version Description\r
+* : 05.01.2015 ---- Clean up source code.\r
+***********************************************************************************************************************/\r
+\r
+/***********************************************************************************************************************\r
+Includes <System Includes> , "Project Includes"\r
+***********************************************************************************************************************/\r
+#include "r_ether_rx_if.h"\r
+\r
+/***********************************************************************************************************************\r
+Private global variables and functions\r
+***********************************************************************************************************************/\r
+int32_t callback_ether_regist(void);\r
+void callback_ether(void * pparam);\r
+static void callback_wakeon_lan(uint32_t channel);\r
+static void callback_link_on(uint32_t channel);\r
+static void callback_link_off(uint32_t channel);\r
+\r
+volatile uint8_t pause_enable = ETHER_FLAG_OFF;\r
+volatile uint8_t magic_packet_detect[ETHER_CHANNEL_MAX];\r
+volatile uint8_t link_detect[ETHER_CHANNEL_MAX];\r
+\r
+void EINT_Trig_isr(void *);\r
+\r
+/*\r
+ * When that Link Status changes, the following function will be called:\r
+ */\r
+void prvLinkStatusChange( BaseType_t xStatus );\r
+\r
+/***********************************************************************************************************************\r
+* Function Name: callback_ether\r
+* Description : Regist of callback function\r
+* Arguments : -\r
+* Return Value : 0: success, -1:failed\r
+***********************************************************************************************************************/\r
+int32_t callback_ether_regist(void)\r
+{\r
+ ether_param_t param;\r
+ ether_cb_t cb_func;\r
+\r
+ int32_t ret;\r
+\r
+ /* Set the callback function (LAN cable connect/disconnect event) */\r
+ cb_func.pcb_func = &callback_ether;\r
+ param.ether_callback = cb_func;\r
+ ret = R_ETHER_Control(CONTROL_SET_CALLBACK, param);\r
+ if (ETHER_SUCCESS != ret)\r
+ {\r
+ return -1;\r
+ }\r
+\r
+ /* Set the callback function (Ether interrupt event) */\r
+ cb_func.pcb_int_hnd = &EINT_Trig_isr;\r
+ param.ether_callback = cb_func;\r
+ ret = R_ETHER_Control(CONTROL_SET_INT_HANDLER, param);\r
+ if (ETHER_SUCCESS != ret)\r
+ {\r
+ return -1;\r
+ }\r
+ return 0;\r
+} /* End of function callback_ether_regist() */\r
+\r
+/***********************************************************************************************************************\r
+* Function Name: callback_ether\r
+* Description : Sample of the callback function\r
+* Arguments : pparam -\r
+*\r
+* Return Value : none\r
+***********************************************************************************************************************/\r
+void callback_ether(void * pparam)\r
+{\r
+ ether_cb_arg_t * pdecode;\r
+ uint32_t channel;\r
+\r
+ pdecode = (ether_cb_arg_t *)pparam;\r
+ channel = pdecode->channel; /* Get Ethernet channel number */\r
+\r
+ switch (pdecode->event_id)\r
+ {\r
+ /* Callback function that notifies user to have detected magic packet. */\r
+ case ETHER_CB_EVENT_ID_WAKEON_LAN:\r
+ callback_wakeon_lan(channel);\r
+ break;\r
+\r
+ /* Callback function that notifies user to have become Link up. */\r
+ case ETHER_CB_EVENT_ID_LINK_ON:\r
+ callback_link_on(channel);\r
+ break;\r
+\r
+ /* Callback function that notifies user to have become Link down. */\r
+ case ETHER_CB_EVENT_ID_LINK_OFF:\r
+ callback_link_off(channel);\r
+ break;\r
+\r
+ default:\r
+ break;\r
+ }\r
+} /* End of function callback_ether() */\r
+\r
+/***********************************************************************************************************************\r
+* Function Name: callback_wakeon_lan\r
+* Description :\r
+* Arguments : channel -\r
+* Ethernet channel number\r
+* Return Value : none\r
+***********************************************************************************************************************/\r
+static void callback_wakeon_lan(uint32_t channel)\r
+{\r
+ if (ETHER_CHANNEL_MAX > channel)\r
+ {\r
+ magic_packet_detect[channel] = 1;\r
+\r
+ /* Please add necessary processing when magic packet is detected. */\r
+ }\r
+} /* End of function callback_wakeon_lan() */\r
+\r
+/***********************************************************************************************************************\r
+* Function Name: callback_link_on\r
+* Description :\r
+* Arguments : channel -\r
+* Ethernet channel number\r
+* Return Value : none\r
+***********************************************************************************************************************/\r
+static void callback_link_on(uint32_t channel)\r
+{\r
+ if (ETHER_CHANNEL_MAX > channel)\r
+ {\r
+ link_detect[channel] = ETHER_FLAG_ON_LINK_ON;\r
+\r
+ /* Please add necessary processing when becoming Link up. */\r
+ prvLinkStatusChange( 1 );\r
+ }\r
+} /* End of function callback_link_on() */\r
+\r
+/***********************************************************************************************************************\r
+* Function Name: callback_link_off\r
+* Description :\r
+* Arguments : channel -\r
+* Ethernet channel number\r
+* Return Value : none\r
+***********************************************************************************************************************/\r
+static void callback_link_off(uint32_t channel)\r
+{\r
+ if (ETHER_CHANNEL_MAX > channel)\r
+ {\r
+ link_detect[channel] = ETHER_FLAG_ON_LINK_OFF;\r
+\r
+ /* Please add necessary processing when becoming Link down. */\r
+ prvLinkStatusChange( 0 );\r
+ }\r
+} /* End of function ether_cb_link_off() */\r
+\r
+/* End of File */\r
*/\r
\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
- * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
- * this software and associated documentation files (the "Software"), to deal in\r
- * the Software without restriction, including without limitation the rights to\r
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
- * the Software, and to permit persons to whom the Software is furnished to do so,\r
- * subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in all\r
- * copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
- *\r
- * http://aws.amazon.com/freertos\r
- * http://www.FreeRTOS.org\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
*/\r
\r
/* Standard includes. */\r
#include "FreeRTOS_Sockets.h"\r
#include "FreeRTOS_IP_Private.h"\r
#include "FreeRTOS_DNS.h"\r
+#include "FreeRTOS_ARP.h"\r
#include "NetworkBufferManagement.h"\r
#include "NetworkInterface.h"\r
#include "phyHandling.h"\r
\r
-#define __STM32_HAL_LEGACY 1\r
-\r
/* ST includes. */\r
#if defined( STM32F7xx )\r
#include "stm32f7xx_hal.h"\r
#include "stm32f4xx_hal.h"\r
#elif defined( STM32F2xx )\r
#include "stm32f2xx_hal.h"\r
-#else\r
+#elif !defined( _lint ) /* Lint does not like an #error */\r
#error What part?\r
#endif\r
\r
\r
#define ipFRAGMENT_OFFSET_BIT_MASK ( ( uint16_t ) 0x0fff ) /* The bits in the two byte IP header field that make up the fragment offset value. */\r
\r
+#if( ( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM == 0 ) || ( ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM == 0 ) )\r
+ #warning Consider enabling checksum offloading\r
+#endif\r
+\r
+#ifndef niDESCRIPTOR_WAIT_TIME_MS\r
+ #define niDESCRIPTOR_WAIT_TIME_MS 250uL\r
+#endif\r
+\r
/*\r
* Most users will want a PHY that negotiates about\r
* the connection properties: speed, dmix and duplex.\r
#warning Using MII, make sure if this is correct\r
#endif\r
\r
+typedef enum\r
+{\r
+ eMACInit, /* Must initialise MAC. */\r
+ eMACPass, /* Initialisation was successful. */\r
+ eMACFailed, /* Initialisation failed. */\r
+} eMAC_INIT_STATUS_TYPE;\r
+\r
+static eMAC_INIT_STATUS_TYPE xMacInitStatus = eMACInit;\r
+\r
/*-----------------------------------------------------------*/\r
\r
/*\r
*/\r
static void prvDMARxDescListInit( void );\r
\r
- /* After packets have been sent, the network\r
- buffers will be released. */\r
- static void vClearTXBuffers( void );\r
+/* After packets have been sent, the network\r
+buffers will be released. */\r
+static void vClearTXBuffers( void );\r
\r
/*-----------------------------------------------------------*/\r
\r
/* Ethernet handle. */\r
static ETH_HandleTypeDef xETH;\r
\r
- /* xTXDescriptorSemaphore is a counting semaphore with\r
- a maximum count of ETH_TXBUFNB, which is the number of\r
- DMA TX descriptors. */\r
- static SemaphoreHandle_t xTXDescriptorSemaphore = NULL;\r
+/* xTXDescriptorSemaphore is a counting semaphore with\r
+a maximum count of ETH_TXBUFNB, which is the number of\r
+DMA TX descriptors. */\r
+static SemaphoreHandle_t xTXDescriptorSemaphore = NULL;\r
\r
/*\r
* Note: it is adviced to define both\r
__ALIGN_BEGIN uint8_t Tx_Buff[ ETH_TXBUFNB ][ ETH_TX_BUF_SIZE ] __ALIGN_END;\r
#endif\r
\r
-#if( ipconfigZERO_COPY_TX_DRIVER != 0 )\r
- /* DMATxDescToClear points to the next TX DMA descriptor\r
- that must be cleared by vClearTXBuffers(). */\r
- static __IO ETH_DMADescTypeDef *DMATxDescToClear;\r
-#endif\r
+/* DMATxDescToClear points to the next TX DMA descriptor\r
+that must be cleared by vClearTXBuffers(). */\r
+static __IO ETH_DMADescTypeDef *DMATxDescToClear;\r
\r
/* Holds the handle of the task used as a deferred interrupt processor. The\r
handle is used so direct notifications can be sent to the task for all EMAC/DMA\r
#endif\r
\r
#if( ipconfigETHERNET_USE_FULL_DUPLEX != 0 )\r
- .duplex = PHY_DUPLEX_FULL,\r
+ .ucDuplex = PHY_DUPLEX_FULL,\r
#else\r
- .duplex = PHY_DUPLEX_HALF,\r
+ .ucDuplex = PHY_DUPLEX_HALF,\r
#endif\r
#endif\r
\r
{\r
BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
\r
+ ( void ) heth;\r
+\r
/* Ethernet RX-Complete callback function, elsewhere declared as weak. */\r
ulISREvents |= EMAC_IF_RX_EVENT;\r
/* Wakeup the prvEMACHandlerTask. */\r
}\r
/*-----------------------------------------------------------*/\r
\r
- void HAL_ETH_TxCpltCallback( ETH_HandleTypeDef *heth )\r
- {\r
- BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
-\r
- /* This call-back is only useful in case packets are being sent\r
- zero-copy. Once they're sent, the buffers will be released\r
- by the function vClearTXBuffers(). */\r
- ulISREvents |= EMAC_IF_TX_EVENT;\r
- /* Wakeup the prvEMACHandlerTask. */\r
- if( xEMACTaskHandle != NULL )\r
- {\r
- vTaskNotifyGiveFromISR( xEMACTaskHandle, &xHigherPriorityTaskWoken );\r
- portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
- }\r
+void HAL_ETH_TxCpltCallback( ETH_HandleTypeDef *heth )\r
+{\r
+BaseType_t xHigherPriorityTaskWoken = pdFALSE;\r
\r
+ ( void ) heth;\r
+\r
+ /* This call-back is only useful in case packets are being sent\r
+ zero-copy. Once they're sent, the buffers will be released\r
+ by the function vClearTXBuffers(). */\r
+ ulISREvents |= EMAC_IF_TX_EVENT;\r
+ /* Wakeup the prvEMACHandlerTask. */\r
+ if( xEMACTaskHandle != NULL )\r
+ {\r
+ vTaskNotifyGiveFromISR( xEMACTaskHandle, &xHigherPriorityTaskWoken );\r
+ portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
}\r
+}\r
/*-----------------------------------------------------------*/\r
\r
- static void vClearTXBuffers()\r
- {\r
- __IO ETH_DMADescTypeDef *txLastDescriptor = xETH.TxDesc;\r
+static void vClearTXBuffers()\r
+{\r
+__IO ETH_DMADescTypeDef *txLastDescriptor = xETH.TxDesc;\r
size_t uxCount = ( ( UBaseType_t ) ETH_TXBUFNB ) - uxSemaphoreGetCount( xTXDescriptorSemaphore );\r
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )\r
NetworkBufferDescriptor_t *pxNetworkBuffer;\r
uint8_t *ucPayLoad;\r
#endif\r
\r
- /* This function is called after a TX-completion interrupt.\r
- It will release each Network Buffer used in xNetworkInterfaceOutput().\r
- 'uxCount' represents the number of descriptors given to DMA for transmission.\r
- After sending a packet, the DMA will clear the 'ETH_DMATXDESC_OWN' bit. */\r
- while( ( uxCount > 0 ) && ( ( DMATxDescToClear->Status & ETH_DMATXDESC_OWN ) == 0 ) )\r
+ /* This function is called after a TX-completion interrupt.\r
+ It will release each Network Buffer used in xNetworkInterfaceOutput().\r
+ 'uxCount' represents the number of descriptors given to DMA for transmission.\r
+ After sending a packet, the DMA will clear the 'ETH_DMATXDESC_OWN' bit. */\r
+ while( ( uxCount > 0 ) && ( ( DMATxDescToClear->Status & ETH_DMATXDESC_OWN ) == 0 ) )\r
+ {\r
+ if( ( DMATxDescToClear == txLastDescriptor ) && ( uxCount != ETH_TXBUFNB ) )\r
{\r
- if( ( DMATxDescToClear == txLastDescriptor ) && ( uxCount != ETH_TXBUFNB ) )\r
- {\r
- break;\r
- }\r
+ break;\r
+ }\r
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )\r
{\r
ucPayLoad = ( uint8_t * )DMATxDescToClear->Buffer1Addr;\r
}\r
#endif /* ipconfigZERO_COPY_TX_DRIVER */\r
\r
- DMATxDescToClear = ( ETH_DMADescTypeDef * )( DMATxDescToClear->Buffer2NextDescAddr );\r
+ DMATxDescToClear = ( ETH_DMADescTypeDef * )( DMATxDescToClear->Buffer2NextDescAddr );\r
\r
- uxCount--;\r
- /* Tell the counting semaphore that one more TX descriptor is available. */\r
- xSemaphoreGive( xTXDescriptorSemaphore );\r
- }\r
+ uxCount--;\r
+ /* Tell the counting semaphore that one more TX descriptor is available. */\r
+ xSemaphoreGive( xTXDescriptorSemaphore );\r
}\r
+}\r
/*-----------------------------------------------------------*/\r
\r
BaseType_t xNetworkInterfaceInitialise( void )\r
HAL_StatusTypeDef hal_eth_init_status;\r
BaseType_t xResult;\r
\r
- if( xEMACTaskHandle == NULL )\r
+ if( xMacInitStatus == eMACInit )\r
{\r
- if( xTXDescriptorSemaphore == NULL )\r
- {\r
- xTXDescriptorSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) ETH_TXBUFNB, ( UBaseType_t ) ETH_TXBUFNB );\r
- configASSERT( xTXDescriptorSemaphore );\r
- }\r
-\r
- /* Initialise ETH */\r
+ xTXDescriptorSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) ETH_TXBUFNB, ( UBaseType_t ) ETH_TXBUFNB );\r
+ if( xTXDescriptorSemaphore == NULL )\r
+ {\r
+ xMacInitStatus = eMACFailed;\r
+ }\r
+ else\r
+ {\r
+ /* Initialise ETH */\r
\r
- xETH.Instance = ETH;\r
- xETH.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE;\r
- xETH.Init.Speed = ETH_SPEED_100M;\r
- xETH.Init.DuplexMode = ETH_MODE_FULLDUPLEX;\r
- /* Value of PhyAddress doesn't matter, will be probed for. */\r
- xETH.Init.PhyAddress = 0;\r
+ xETH.Instance = ETH;\r
+ xETH.Init.AutoNegotiation = ETH_AUTONEGOTIATION_ENABLE;\r
+ xETH.Init.Speed = ETH_SPEED_100M;\r
+ xETH.Init.DuplexMode = ETH_MODE_FULLDUPLEX;\r
+ /* Value of PhyAddress doesn't matter, will be probed for. */\r
+ xETH.Init.PhyAddress = 0;\r
\r
- xETH.Init.MACAddr = ( uint8_t *)FreeRTOS_GetMACAddress();\r
- xETH.Init.RxMode = ETH_RXINTERRUPT_MODE;\r
+ xETH.Init.MACAddr = ( uint8_t * ) FreeRTOS_GetMACAddress();\r
+ xETH.Init.RxMode = ETH_RXINTERRUPT_MODE;\r
\r
- /* using the ETH_CHECKSUM_BY_HARDWARE option:\r
- both the IP and the protocol checksums will be calculated\r
- by the peripheral. */\r
- xETH.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE;\r
+ #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM != 0 )\r
+ {\r
+ /* using the ETH_CHECKSUM_BY_HARDWARE option:\r
+ both the IP and the protocol checksums will be calculated\r
+ by the peripheral. */\r
+ xETH.Init.ChecksumMode = ETH_CHECKSUM_BY_HARDWARE;\r
+ }\r
+ #else\r
+ {\r
+ xETH.Init.ChecksumMode = ETH_CHECKSUM_BY_SOFTWARE;\r
+ }\r
+ #endif\r
\r
- #if( ipconfigUSE_RMII != 0 )\r
- {\r
- xETH.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII;\r
- }\r
- #else\r
- {\r
- xETH.Init.MediaInterface = ETH_MEDIA_INTERFACE_MII;\r
- }\r
- #endif /* ipconfigUSE_RMII */\r
+ #if( ipconfigUSE_RMII != 0 )\r
+ {\r
+ xETH.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII;\r
+ }\r
+ #else\r
+ {\r
+ xETH.Init.MediaInterface = ETH_MEDIA_INTERFACE_MII;\r
+ }\r
+ #endif /* ipconfigUSE_RMII */\r
\r
- hal_eth_init_status = HAL_ETH_Init( &xETH );\r
+ hal_eth_init_status = HAL_ETH_Init( &xETH );\r
\r
- /* Only for inspection by debugger. */\r
- ( void ) hal_eth_init_status;\r
+ /* Only for inspection by debugger. */\r
+ ( void ) hal_eth_init_status;\r
\r
- /* Set the TxDesc and RxDesc pointers. */\r
- xETH.TxDesc = DMATxDscrTab;\r
- xETH.RxDesc = DMARxDscrTab;\r
+ /* Set the TxDesc and RxDesc pointers. */\r
+ xETH.TxDesc = DMATxDscrTab;\r
+ xETH.RxDesc = DMARxDscrTab;\r
\r
- /* Make sure that all unused fields are cleared. */\r
- memset( &DMATxDscrTab, '\0', sizeof( DMATxDscrTab ) );\r
- memset( &DMARxDscrTab, '\0', sizeof( DMARxDscrTab ) );\r
+ /* Make sure that all unused fields are cleared. */\r
+ memset( &DMATxDscrTab, '\0', sizeof( DMATxDscrTab ) );\r
+ memset( &DMARxDscrTab, '\0', sizeof( DMARxDscrTab ) );\r
\r
/* Initialize Tx Descriptors list: Chain Mode */\r
DMATxDescToClear = DMATxDscrTab;\r
\r
- /* Initialise TX-descriptors. */\r
- prvDMATxDescListInit();\r
+ /* Initialise TX-descriptors. */\r
+ prvDMATxDescListInit();\r
\r
- /* Initialise RX-descriptors. */\r
- prvDMARxDescListInit();\r
+ /* Initialise RX-descriptors. */\r
+ prvDMARxDescListInit();\r
\r
- #if( ipconfigUSE_LLMNR != 0 )\r
- {\r
- /* Program the LLMNR address at index 1. */\r
- prvMACAddressConfig( &xETH, ETH_MAC_ADDRESS1, ( uint8_t *) xLLMNR_MACAddress );\r
- }\r
- #endif\r
+ #if( ipconfigUSE_LLMNR != 0 )\r
+ {\r
+ /* Program the LLMNR address at index 1. */\r
+ prvMACAddressConfig( &xETH, ETH_MAC_ADDRESS1, ( uint8_t *) xLLMNR_MACAddress );\r
+ }\r
+ #endif\r
\r
- /* Force a negotiation with the Switch or Router and wait for LS. */\r
- prvEthernetUpdateConfig( pdTRUE );\r
+ /* Force a negotiation with the Switch or Router and wait for LS. */\r
+ prvEthernetUpdateConfig( pdTRUE );\r
\r
- /* The deferred interrupt handler task is created at the highest\r
- possible priority to ensure the interrupt handler can return directly\r
- to it. The task's handle is stored in xEMACTaskHandle so interrupts can\r
- notify the task when there is something to process. */\r
- xTaskCreate( prvEMACHandlerTask, "EMAC", configEMAC_TASK_STACK_SIZE, NULL, niEMAC_HANDLER_TASK_PRIORITY, &xEMACTaskHandle );\r
+ /* The deferred interrupt handler task is created at the highest\r
+ possible priority to ensure the interrupt handler can return directly\r
+ to it. The task's handle is stored in xEMACTaskHandle so interrupts can\r
+ notify the task when there is something to process. */\r
+ if( xTaskCreate( prvEMACHandlerTask, "EMAC", configEMAC_TASK_STACK_SIZE, NULL, niEMAC_HANDLER_TASK_PRIORITY, &xEMACTaskHandle ) == pdPASS )\r
+ {\r
+ /* The xTXDescriptorSemaphore and the task are created successfully. */\r
+ xMacInitStatus = eMACPass;\r
+ }\r
+ else\r
+ {\r
+ xMacInitStatus = eMACFailed;\r
+ }\r
+ }\r
} /* if( xEMACTaskHandle == NULL ) */\r
\r
- if( xPhyObject.ulLinkStatusMask != 0 )\r
+ if( xMacInitStatus != eMACPass )\r
{\r
- xETH.Instance->DMAIER |= ETH_DMA_ALL_INTS;\r
- xResult = pdPASS;\r
- FreeRTOS_printf( ( "Link Status is high\n" ) ) ;\r
+ /* EMAC initialisation failed, return pdFAIL. */\r
+ xResult = pdFAIL;\r
}\r
else\r
{\r
- /* For now pdFAIL will be returned. But prvEMACHandlerTask() is running\r
- and it will keep on checking the PHY and set 'ulLinkStatusMask' when necessary. */\r
- xResult = pdFAIL;\r
+ if( xPhyObject.ulLinkStatusMask != 0uL )\r
+ {\r
+ xETH.Instance->DMAIER |= ETH_DMA_ALL_INTS;\r
+ xResult = pdPASS;\r
+ FreeRTOS_printf( ( "Link Status is high\n" ) ) ;\r
+ }\r
+ else\r
+ {\r
+ /* For now pdFAIL will be returned. But prvEMACHandlerTask() is running\r
+ and it will keep on checking the PHY and set 'ulLinkStatusMask' when necessary. */\r
+ xResult = pdFAIL;\r
+ }\r
}\r
/* When returning non-zero, the stack will become active and\r
start DHCP (in configured) */\r
/* Set the DMA Tx descriptors checksum insertion for TCP, UDP, and ICMP */\r
pxDMADescriptor->Status |= ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL;\r
}\r
+ else\r
+ {\r
+ pxDMADescriptor->Status &= ~( ( uint32_t ) ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL );\r
+ }\r
\r
/* Initialize the next descriptor with the Next Descriptor Polling Enable */\r
if( xIndex < ETH_TXBUFNB - 1 )\r
{\r
uint32_t ulTempReg;\r
\r
+ ( void ) heth;\r
+\r
/* Calculate the selected MAC address high register. */\r
ulTempReg = 0x80000000ul | ( ( uint32_t ) Addr[ 5 ] << 8 ) | ( uint32_t ) Addr[ 4 ];\r
\r
/* Open a do {} while ( 0 ) loop to be able to call break. */\r
do\r
{\r
+ if( xCheckLoopback( pxDescriptor, bReleaseAfterSend ) != 0 )\r
+ {\r
+ /* The packet has been sent back to the IP-task.\r
+ The IP-task will further handle it.\r
+ Do not release the descriptor. */\r
+ bReleaseAfterSend = pdFALSE;\r
+ break;\r
+ }\r
#if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM != 0 )\r
{\r
ProtocolPacket_t *pxPacket;\r
\r
- #if( ipconfigZERO_COPY_RX_DRIVER != 0 )\r
- {\r
- configASSERT( bReleaseAfterSend != 0 );\r
- }\r
- #endif /* ipconfigZERO_COPY_RX_DRIVER */\r
-\r
/* If the peripheral must calculate the checksum, it wants\r
the protocol checksum to have a value of zero. */\r
pxPacket = ( ProtocolPacket_t * ) ( pxDescriptor->pucEthernetBuffer );\r
\r
- if( pxPacket->xICMPPacket.xIPHeader.ucProtocol == ipPROTOCOL_ICMP )\r
+ if( pxPacket->xICMPPacket.xIPHeader.ucProtocol == ( uint8_t ) ipPROTOCOL_ICMP )\r
{\r
pxPacket->xICMPPacket.xICMPHeader.usChecksum = ( uint16_t )0u;\r
}\r
}\r
#else\r
{\r
+ configASSERT( bReleaseAfterSend != 0 );\r
+\r
/* Move the buffer. */\r
pxDmaTxDesc->Buffer1Addr = ( uint32_t )pxDescriptor->pucEthernetBuffer;\r
/* The Network Buffer has been passed to DMA, no need to release it. */\r
\r
/* Ask to set the IPv4 checksum.\r
Also need an Interrupt on Completion so that 'vClearTXBuffers()' will be called.. */\r
- pxDmaTxDesc->Status |= ETH_DMATXDESC_CIC_TCPUDPICMP_FULL | ETH_DMATXDESC_IC;\r
+ #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM != 0 )\r
+ {\r
+ pxDmaTxDesc->Status |= ETH_DMATXDESC_CIC_TCPUDPICMP_FULL | ETH_DMATXDESC_IC;\r
+ }\r
+ #else\r
+ {\r
+ pxDmaTxDesc->Status &= ~( ( uint32_t ) ETH_DMATXDESC_CIC );\r
+ pxDmaTxDesc->Status |= ETH_DMATXDESC_IC;\r
+ }\r
+ #endif\r
+ \r
\r
/* Prepare transmit descriptors to give to DMA. */\r
\r
\r
if( pxIPHeader->ucProtocol == ipPROTOCOL_UDP )\r
{\r
- uint16_t port = pxProtPacket->xUDPPacket.xUDPHeader.usDestinationPort;\r
+ uint16_t usSourcePort = FreeRTOS_ntohs( pxProtPacket->xUDPPacket.xUDPHeader.usSourcePort );\r
+ uint16_t usDestinationPort = FreeRTOS_ntohs( pxProtPacket->xUDPPacket.xUDPHeader.usDestinationPort );\r
\r
- if( ( xPortHasUDPSocket( port ) == pdFALSE )\r
+ if( ( xPortHasUDPSocket( pxProtPacket->xUDPPacket.xUDPHeader.usDestinationPort ) == pdFALSE )\r
#if ipconfigUSE_LLMNR == 1\r
- && ( port != FreeRTOS_ntohs( ipLLMNR_PORT ) )\r
+ && ( usDestinationPort != ipLLMNR_PORT )\r
+ && ( usSourcePort != ipLLMNR_PORT )\r
#endif\r
#if ipconfigUSE_NBNS == 1\r
- && ( port != FreeRTOS_ntohs( ipNBNS_PORT ) )\r
+ && ( usDestinationPort != ipNBNS_PORT )\r
+ && ( usSourcePort != ipNBNS_PORT )\r
#endif\r
#if ipconfigUSE_DNS == 1\r
- && ( pxProtPacket->xUDPPacket.xUDPHeader.usSourcePort != FreeRTOS_ntohs( ipDNS_PORT ) )\r
+ && ( usSourcePort != ipDNS_PORT )\r
#endif\r
) {\r
/* Drop this packet, not for this device. */\r
+ /* FreeRTOS_printf( ( "Drop: UDP port %d -> %d\n", usSourcePort, usDestinationPort ) ); */\r
return pdFALSE;\r
}\r
}\r
}\r
/*-----------------------------------------------------------*/\r
\r
+static void prvPassEthMessages( NetworkBufferDescriptor_t *pxDescriptor )\r
+{\r
+IPStackEvent_t xRxEvent;\r
+\r
+ xRxEvent.eEventType = eNetworkRxEvent;\r
+ xRxEvent.pvData = ( void * ) pxDescriptor;\r
+\r
+ if( xSendEventStructToIPTask( &xRxEvent, ( TickType_t ) 1000 ) != pdPASS )\r
+ {\r
+ /* The buffer could not be sent to the stack so must be released again.\r
+ This is a deferred handler taskr, not a real interrupt, so it is ok to\r
+ use the task level function here. */\r
+ #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
+ {\r
+ do\r
+ {\r
+ NetworkBufferDescriptor_t *pxNext = pxDescriptor->pxNextBuffer;\r
+ vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
+ pxDescriptor = pxNext;\r
+ } while( pxDescriptor != NULL );\r
+ }\r
+ #else\r
+ {\r
+ vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
+ }\r
+ #endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ FreeRTOS_printf( ( "prvPassEthMessages: Can not queue return packet!\n" ) );\r
+ }\r
+ else\r
+ {\r
+ iptraceNETWORK_INTERFACE_RECEIVE();\r
+ }\r
+}\r
+\r
static BaseType_t prvNetworkInterfaceInput( void )\r
{\r
NetworkBufferDescriptor_t *pxCurDescriptor;\r
NetworkBufferDescriptor_t *pxNewDescriptor = NULL;\r
-BaseType_t xReceivedLength, xAccepted;\r
+#if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
+ NetworkBufferDescriptor_t *pxFirstDescriptor = NULL;\r
+ NetworkBufferDescriptor_t *pxLastDescriptor = NULL;\r
+#endif\r
+BaseType_t xReceivedLength = 0;\r
__IO ETH_DMADescTypeDef *pxDMARxDescriptor;\r
-xIPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };\r
-const TickType_t xDescriptorWaitTime = pdMS_TO_TICKS( 250 );\r
+const TickType_t xDescriptorWaitTime = pdMS_TO_TICKS( niDESCRIPTOR_WAIT_TIME_MS );\r
uint8_t *pucBuffer;\r
\r
pxDMARxDescriptor = xETH.RxDesc;\r
\r
- if( ( pxDMARxDescriptor->Status & ETH_DMARXDESC_OWN) == 0 )\r
+ while( ( pxDMARxDescriptor->Status & ETH_DMARXDESC_OWN ) == 0u )\r
{\r
+ BaseType_t xAccepted = pdTRUE;\r
/* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */\r
xReceivedLength = ( ( pxDMARxDescriptor->Status & ETH_DMARXDESC_FL ) >> ETH_DMARXDESC_FRAMELENGTHSHIFT ) - 4;\r
\r
/* Chained Mode */ \r
/* Selects the next DMA Rx descriptor list for next buffer to read */ \r
xETH.RxDesc = ( ETH_DMADescTypeDef* )pxDMARxDescriptor->Buffer2NextDescAddr;\r
- }\r
- else\r
- {\r
- xReceivedLength = 0;\r
- }\r
\r
- /* Obtain the size of the packet and put it into the "usReceivedLength" variable. */\r
-\r
- /* get received frame */\r
- if( xReceivedLength > 0ul )\r
- {\r
- /* In order to make the code easier and faster, only packets in a single buffer\r
- will be accepted. This can be done by making the buffers large enough to\r
+ /* In order to make the code easier and faster, only packets in a single buffer\r
+ will be accepted. This can be done by making the buffers large enough to\r
hold a complete Ethernet packet (1536 bytes).\r
Therefore, two sanity checks: */\r
configASSERT( xReceivedLength <= ETH_RX_BUF_SIZE );\r
if( xAccepted != pdFALSE )\r
{\r
pxCurDescriptor->xDataLength = xReceivedLength;\r
- xRxEvent.pvData = ( void * ) pxCurDescriptor;\r
-\r
- /* Pass the data to the TCP/IP task for processing. */\r
- if( xSendEventStructToIPTask( &xRxEvent, xDescriptorWaitTime ) == pdFALSE )\r
+ #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
{\r
- /* Could not send the descriptor into the TCP/IP stack, it\r
- must be released. */\r
- vReleaseNetworkBufferAndDescriptor( pxCurDescriptor );\r
- iptraceETHERNET_RX_EVENT_LOST();\r
+ pxCurDescriptor->pxNextBuffer = NULL;\r
+\r
+ if( pxFirstDescriptor == NULL )\r
+ {\r
+ // Becomes the first message\r
+ pxFirstDescriptor = pxCurDescriptor;\r
+ }\r
+ else if( pxLastDescriptor != NULL )\r
+ {\r
+ // Add to the tail\r
+ pxLastDescriptor->pxNextBuffer = pxCurDescriptor;\r
+ }\r
+\r
+ pxLastDescriptor = pxCurDescriptor;\r
}\r
- else\r
+ #else\r
{\r
- iptraceNETWORK_INTERFACE_RECEIVE();\r
+ prvPassEthMessages( pxCurDescriptor );\r
}\r
+ #endif\r
}\r
\r
/* Release descriptors to DMA */\r
/* Resume DMA reception. */\r
xETH.Instance->DMARPDR = 0;\r
}\r
+ pxDMARxDescriptor = xETH.RxDesc;\r
}\r
\r
+ #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
+ {\r
+ if( pxFirstDescriptor != NULL )\r
+ {\r
+ prvPassEthMessages( pxFirstDescriptor );\r
+ }\r
+ }\r
+ #endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
+\r
return ( xReceivedLength > 0 );\r
}\r
/*-----------------------------------------------------------*/\r
\r
\r
BaseType_t xSTM32_PhyRead( BaseType_t xAddress, BaseType_t xRegister, uint32_t *pulValue )\r
- {\r
+{\r
uint16_t usPrevAddress = xETH.Init.PhyAddress;\r
BaseType_t xResult;\r
HAL_StatusTypeDef xHALResult;\r
xResult = -1;\r
}\r
return xResult;\r
- }\r
+}\r
/*-----------------------------------------------------------*/\r
\r
BaseType_t xSTM32_PhyWrite( BaseType_t xAddress, BaseType_t xRegister, uint32_t ulValue )\r
- {\r
+{\r
uint16_t usPrevAddress = xETH.Init.PhyAddress;\r
BaseType_t xResult;\r
HAL_StatusTypeDef xHALResult;\r
xETH.Init.PhyAddress = usPrevAddress;\r
\r
if( xHALResult == HAL_OK )\r
- {\r
+ {\r
xResult = 0;\r
- }\r
- else\r
- {\r
+ }\r
+ else\r
+ {\r
xResult = -1;\r
- }\r
- return xResult;\r
}\r
+ return xResult;\r
+}\r
/*-----------------------------------------------------------*/\r
\r
void vMACBProbePhy( void )\r
{\r
xPhyStartAutoNegotiation( &xPhyObject, xPhyGetMask( &xPhyObject ) );\r
\r
- /* Configure the MAC with the Duplex Mode fixed by the\r
- auto-negotiation process. */\r
+ /* Configure the MAC with the Duplex Mode fixed by the\r
+ auto-negotiation process. */\r
if( xPhyObject.xPhyProperties.ucDuplex == PHY_DUPLEX_FULL )\r
- {\r
- xETH.Init.DuplexMode = ETH_MODE_FULLDUPLEX;\r
- }\r
- else\r
- {\r
- xETH.Init.DuplexMode = ETH_MODE_HALFDUPLEX;\r
- }\r
+ {\r
+ xETH.Init.DuplexMode = ETH_MODE_FULLDUPLEX;\r
+ }\r
+ else\r
+ {\r
+ xETH.Init.DuplexMode = ETH_MODE_HALFDUPLEX;\r
+ }\r
\r
- /* Configure the MAC with the speed fixed by the\r
- auto-negotiation process. */\r
+ /* Configure the MAC with the speed fixed by the\r
+ auto-negotiation process. */\r
if( xPhyObject.xPhyProperties.ucSpeed == PHY_SPEED_10 )\r
- {\r
- xETH.Init.Speed = ETH_SPEED_10M;\r
- }\r
- else\r
- {\r
- xETH.Init.Speed = ETH_SPEED_100M;\r
- }\r
+ {\r
+ xETH.Init.Speed = ETH_SPEED_10M;\r
+ }\r
+ else\r
+ {\r
+ xETH.Init.Speed = ETH_SPEED_100M;\r
+ }\r
}\r
else /* AutoNegotiation Disable */\r
{\r
\r
/* Uncomment this in case BufferAllocation_1.c is used. */\r
\r
-#define niBUFFER_1_PACKET_SIZE 1536\r
-\r
void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )\r
{\r
-static __attribute__ ((section(".first_data"))) uint8_t ucNetworkPackets[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS * niBUFFER_1_PACKET_SIZE ] __attribute__ ( ( aligned( 32 ) ) );\r
+static __attribute__ ((section(".first_data"))) uint8_t ucNetworkPackets[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS * ETH_MAX_PACKET_SIZE ] __attribute__ ( ( aligned( 32 ) ) );\r
uint8_t *ucRAMBuffer = ucNetworkPackets;\r
uint32_t ul;\r
\r
{\r
pxNetworkBuffers[ ul ].pucEthernetBuffer = ucRAMBuffer + ipBUFFER_PADDING;\r
*( ( unsigned * ) ucRAMBuffer ) = ( unsigned ) ( &( pxNetworkBuffers[ ul ] ) );\r
- ucRAMBuffer += niBUFFER_1_PACKET_SIZE;\r
+ ucRAMBuffer += ETH_MAX_PACKET_SIZE;\r
}\r
}\r
/*-----------------------------------------------------------*/\r
ulISREvents &= ~EMAC_IF_RX_EVENT;\r
\r
xResult = prvNetworkInterfaceInput();\r
- if( xResult > 0 )\r
- {\r
- while( prvNetworkInterfaceInput() > 0 )\r
- {\r
- }\r
- }\r
}\r
\r
if( ( ulISREvents & EMAC_IF_TX_EVENT ) != 0 )\r
{\r
/* Code to release TX buffers if zero-copy is used. */\r
ulISREvents &= ~EMAC_IF_TX_EVENT;\r
- /* Check if DMA packets have been delivered. */\r
- vClearTXBuffers();\r
- }\r
+ /* Check if DMA packets have been delivered. */\r
+ vClearTXBuffers();\r
+ }\r
\r
if( ( ulISREvents & EMAC_IF_ERR_EVENT ) != 0 )\r
{\r
ulISREvents &= ~EMAC_IF_ERR_EVENT;\r
}\r
if( xPhyCheckLinkStatus( &xPhyObject, xResult ) != 0 )\r
- {\r
+ {\r
/* Something has changed to a Link Status, need re-check. */\r
- prvEthernetUpdateConfig( pdFALSE );\r
- }\r
+ prvEthernetUpdateConfig( pdFALSE );\r
+ }\r
}\r
}\r
/*-----------------------------------------------------------*/\r
STM32F439xx\r
\r
The driver has been tested on both Eval and Discovery boards with both STM32F4 and STM32F7.\r
+\r
+Recommened settings for STM32Fxx Network Interface:\r
+\r
+// Defined in FreeRTOSIPConfig.h\r
+\r
+#define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES 1\r
+#define ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM 1\r
+#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM 1\r
+#define ipconfigZERO_COPY_RX_DRIVER 1\r
+#define ipconfigZERO_COPY_TX_DRIVER 1\r
+#define ipconfigUSE_LINKED_RX_MESSAGES 1\r
+\r
+// Defined in stm32f4xx_hal_conf.h\r
+#define ETH_RXBUFNB 3 or 4\r
+#define ETH_TXBUFNB 2 or 3\r
+#define ETH_RX_BUF_SIZE ( ipconfigNETWORK_MTU + 36 )\r
+#define ETH_TX_BUF_SIZE ( ipconfigNETWORK_MTU + 36 )\r
+\r
+The best size for 'ETH_RXBUFNB' and 'ETH_TXBUFNB' depends on the speed of the CPU. These macro's define the number of DMA buffers for reception and for transmission.\r
+In general, if the CPU is very fast, you will need less buffers. You can obtain an estimate empirically.\r
+\r
+The optimal value of 'ETH_RX_BUF_SIZE' and 'ETH_TX_BUF_SIZE' depends on the actual value of 'ipconfigNETWORK_MTU'.\r
+When MTU is 1500, MTU+36 becomes a well-aligned buffer of 1536 bytes ( 0x600 ).\r
+When MTU is 1200, MTU+48 will make 1248 ( 0x4E0 ), which is also well aligned.\r
+\r
+Having well aligned buffers is important for CPU with memory cache. Often the caching system divides memory in blocks of 32 bytes. When two buffers share the same cache buffer, you are bound to see data errors.\r
+\r
+Without memory caching, let the size be at least a multiple of 8 ( for DMA ), and make it at least "ipconfigNETWORK_MTU + 14".\r
+\r
+The driver contains these files:\r
+\r
+ stm32fxx_hal_eth.c\r
+ stm32f2xx_hal_eth.h\r
+ stm32f4xx_hal_eth.h\r
+ stm32f7xx_hal_eth.h\r
+ stm32fxx_hal_eth.h\r
+\r
+These files are copied from ST's HAL library. These work both for STM32F4 and STM32F7.\r
+Please remove or rename these files from the HAL distribution that you are using.\r
+\r
*/\r
\r
/* Includes ------------------------------------------------------------------*/\r
-#define __STM32_HAL_LEGACY 1\r
\r
#if defined(STM32F7xx)\r
#include "stm32f7xx_hal.h"\r
- #include "stm32f7xx_hal_def.h"\r
#define stm_is_F7 1\r
#elif defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\r
#include "stm32f4xx_hal.h"\r
- #include "stm32f4xx_hal_def.h"\r
#define stm_is_F4 1\r
#elif defined(STM32F2xx)\r
#include "stm32f2xx_hal.h"\r
- #include "stm32f2xx_hal_def.h"\r
#define stm_is_F2 1\r
#else\r
#error For what part should this be compiled?\r
*/\r
HAL_StatusTypeDef HAL_ETH_Init(ETH_HandleTypeDef *heth)\r
{\r
- uint32_t tmpreg = 0;\r
- uint32_t hclk = 60000000;\r
+ uint32_t tmpreg = 0uL;\r
+ uint32_t hclk = 60000000uL;\r
uint32_t err = ETH_SUCCESS;\r
\r
/* Check the ETH peripheral state */\r
/* Clear CSR Clock Range CR[2:0] bits */\r
tmpreg &= ETH_MACMIIAR_CR_MASK;\r
\r
- /* Get hclk frequency value (168,000,000) */\r
+ /* Get hclk frequency value (e.g. 168,000,000) */\r
hclk = HAL_RCC_GetHCLKFreq();\r
\r
/* Set CR bits depending on hclk value */\r
- if( ( hclk >= 20000000 ) && ( hclk < 35000000 ) )\r
+ if(( hclk >= 20000000uL ) && ( hclk < 35000000uL ) )\r
{\r
/* CSR Clock Range between 20-35 MHz */\r
- tmpreg |= (uint32_t) ETH_MACMIIAR_CR_Div16;\r
+ tmpreg |= ( uint32_t) ETH_MACMIIAR_CR_Div16;\r
}\r
- else if( ( hclk >= 35000000 ) && ( hclk < 60000000 ) )\r
+ else if( ( hclk >= 35000000uL ) && ( hclk < 60000000uL ) )\r
{\r
/* CSR Clock Range between 35-60 MHz */\r
tmpreg |= ( uint32_t ) ETH_MACMIIAR_CR_Div26;\r
}\r
- else if((hclk >= 60000000 ) && ( hclk < 100000000 ) )\r
+ else if( ( hclk >= 60000000uL ) && ( hclk < 100000000uL ) )\r
{\r
/* CSR Clock Range between 60-100 MHz */\r
tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div42;\r
}\r
- else if((hclk >= 100000000 ) && ( hclk < 150000000))\r
+ else if( ( hclk >= 100000000uL ) && ( hclk < 150000000uL ) )\r
{\r
/* CSR Clock Range between 100-150 MHz */\r
tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div62;\r
}\r
- else /* ((hclk >= 150000000 ) && ( hclk <= 168000000)) */\r
+ else /* ( ( hclk >= 150000000uL ) && ( hclk <= 183000000uL ) ) */\r
{\r
- /* CSR Clock Range between 150-168 MHz */\r
+ /* CSR Clock Range between 150-183 MHz */\r
tmpreg |= (uint32_t)ETH_MACMIIAR_CR_Div102;\r
}\r
\r
return HAL_OK;\r
}\r
\r
-/**\r
- * @brief Initializes the DMA Tx descriptors in chain mode.\r
- * @param heth: pointer to a ETH_HandleTypeDef structure that contains\r
- * the configuration information for ETHERNET module\r
- * @param DMATxDescTab: Pointer to the first Tx desc list\r
- * @param TxBuff: Pointer to the first TxBuffer list\r
- * @param TxBuffCount: Number of the used Tx desc in the list\r
- * @retval HAL status\r
- */\r
-HAL_StatusTypeDef HAL_ETH_DMATxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *pxDMATable, uint8_t *ucDataBuffer, uint32_t ulBufferCount)\r
-{\r
- uint32_t i = 0;\r
- ETH_DMADescTypeDef *pxDMADescriptor;\r
-\r
- /* Process Locked */\r
- __HAL_LOCK( heth );\r
-\r
- /* Set the ETH peripheral state to BUSY */\r
- heth->State = HAL_ETH_STATE_BUSY;\r
-\r
- /* Set the TxDesc pointer with the first one of the pxDMATable list */\r
- heth->TxDesc = pxDMATable;\r
-\r
- /* Fill each DMA descriptor with the right values */\r
- for( i=0; i < ulBufferCount; i++ )\r
- {\r
- /* Get the pointer on the ith member of the descriptor list */\r
- pxDMADescriptor = pxDMATable + i;\r
-\r
- /* Set Second Address Chained bit */\r
- pxDMADescriptor->Status = ETH_DMATXDESC_TCH;\r
-\r
- pxDMADescriptor->ControlBufferSize = 0;\r
-\r
- /* Set Buffer1 address pointer */\r
- if( ucDataBuffer != NULL )\r
- {\r
- pxDMADescriptor->Buffer1Addr = ( uint32_t )( &ucDataBuffer[ i * ETH_TX_BUF_SIZE ] );\r
- }\r
- else\r
- {\r
- /* Buffer space is not provided because it uses zero-copy transmissions. */\r
- pxDMADescriptor->Buffer1Addr = ( uint32_t )0u;\r
- }\r
-\r
- if (heth->Init.ChecksumMode == ETH_CHECKSUM_BY_HARDWARE)\r
- {\r
- /* Set the DMA Tx descriptors checksum insertion for TCP, UDP, and ICMP */\r
- pxDMADescriptor->Status |= ETH_DMATXDESC_CHECKSUMTCPUDPICMPFULL;\r
- }\r
-\r
- /* Initialize the next descriptor with the Next Descriptor Polling Enable */\r
- if(i < ( ulBufferCount - 1 ) )\r
- {\r
- /* Set next descriptor address register with next descriptor base address */\r
- pxDMADescriptor->Buffer2NextDescAddr = ( uint32_t ) ( pxDMATable + i + 1 );\r
- }\r
- else\r
- {\r
- /* For last descriptor, set next descriptor address register equal to the first descriptor base address */\r
- pxDMADescriptor->Buffer2NextDescAddr = ( uint32_t ) pxDMATable;\r
- }\r
- }\r
-\r
- /* Set Transmit Descriptor List Address Register */\r
- heth->Instance->DMATDLAR = ( uint32_t ) pxDMATable;\r
-\r
- /* Set ETH HAL State to Ready */\r
- heth->State= HAL_ETH_STATE_READY;\r
-\r
- /* Process Unlocked */\r
- __HAL_UNLOCK( heth );\r
-\r
- /* Return function status */\r
- return HAL_OK;\r
-}\r
-\r
-/**\r
- * @brief Initializes the DMA Rx descriptors in chain mode.\r
- * @param heth: pointer to a ETH_HandleTypeDef structure that contains\r
- * the configuration information for ETHERNET module\r
- * @param DMARxDescTab: Pointer to the first Rx desc list\r
- * @param RxBuff: Pointer to the first RxBuffer list\r
- * @param RxBuffCount: Number of the used Rx desc in the list\r
- * @retval HAL status\r
- */\r
-HAL_StatusTypeDef HAL_ETH_DMARxDescListInit(ETH_HandleTypeDef *heth, ETH_DMADescTypeDef *pxDMATable, uint8_t *ucDataBuffer, uint32_t ulBufferCount)\r
-{\r
- uint32_t i = 0;\r
- ETH_DMADescTypeDef *pxDMADescriptor;\r
-\r
- /* Process Locked */\r
- __HAL_LOCK( heth );\r
-\r
- /* Set the ETH peripheral state to BUSY */\r
- heth->State = HAL_ETH_STATE_BUSY;\r
-\r
- /* Set the RxDesc pointer with the first one of the pxDMATable list */\r
- heth->RxDesc = pxDMATable;\r
-\r
- /* Fill each DMA descriptor with the right values */\r
- for(i=0; i < ulBufferCount; i++)\r
- {\r
- /* Get the pointer on the ith member of the descriptor list */\r
- pxDMADescriptor = pxDMATable+i;\r
-\r
- /* Set Own bit of the Rx descriptor Status */\r
- pxDMADescriptor->Status = ETH_DMARXDESC_OWN;\r
-\r
- /* Set Buffer1 size and Second Address Chained bit */\r
- pxDMADescriptor->ControlBufferSize = ETH_DMARXDESC_RCH | ETH_RX_BUF_SIZE;\r
-\r
- /* Set Buffer1 address pointer */\r
- if( ucDataBuffer != NULL )\r
- {\r
- pxDMADescriptor->Buffer1Addr = ( uint32_t )( &ucDataBuffer[ i * ETH_RX_BUF_SIZE ] );\r
- }\r
- else\r
- {\r
- /* Buffer space is not provided because it uses zero-copy reception. */\r
- pxDMADescriptor->Buffer1Addr = ( uint32_t )0u;\r
- }\r
-\r
- if( heth->Init.RxMode == ETH_RXINTERRUPT_MODE )\r
- {\r
- /* Enable Ethernet DMA Rx Descriptor interrupt */\r
- pxDMADescriptor->ControlBufferSize &= ~ETH_DMARXDESC_DIC;\r
- }\r
-\r
- /* Initialize the next descriptor with the Next Descriptor Polling Enable */\r
- if(i < (ulBufferCount-1))\r
- {\r
- /* Set next descriptor address register with next descriptor base address */\r
- pxDMADescriptor->Buffer2NextDescAddr = (uint32_t)(pxDMATable+i+1);\r
- }\r
- else\r
- {\r
- /* For last descriptor, set next descriptor address register equal to the first descriptor base address */\r
- pxDMADescriptor->Buffer2NextDescAddr = ( uint32_t ) pxDMATable;\r
- }\r
- }\r
-\r
- /* Set Receive Descriptor List Address Register */\r
- heth->Instance->DMARDLAR = ( uint32_t ) pxDMATable;\r
-\r
- /* Set ETH HAL State to Ready */\r
- heth->State= HAL_ETH_STATE_READY;\r
-\r
- /* Process Unlocked */\r
- __HAL_UNLOCK( heth );\r
-\r
- /* Return function status */\r
- return HAL_OK;\r
-}\r
-\r
/**\r
* @brief Initializes the ETH MSP.\r
* @param heth: pointer to a ETH_HandleTypeDef structure that contains\r
/* NOTE : This function Should not be modified, when the callback is needed,\r
the HAL_ETH_MspInit could be implemented in the user file\r
*/\r
+ ( void ) heth;\r
}\r
\r
/**\r
/* NOTE : This function Should not be modified, when the callback is needed,\r
the HAL_ETH_MspDeInit could be implemented in the user file\r
*/\r
+ ( void ) heth;\r
}\r
\r
/**\r
* @{\r
*/\r
\r
-/**\r
- * @brief Sends an Ethernet frame.\r
- * @param heth: pointer to a ETH_HandleTypeDef structure that contains\r
- * the configuration information for ETHERNET module\r
- * @param FrameLength: Amount of data to be sent\r
- * @retval HAL status\r
- */\r
-HAL_StatusTypeDef HAL_ETH_TransmitFrame(ETH_HandleTypeDef *heth, uint32_t FrameLength)\r
-{\r
- uint32_t bufcount = 0, size = 0, i = 0;\r
- __IO ETH_DMADescTypeDef *pxDmaTxDesc = heth->TxDesc;\r
- /* Process Locked */\r
- __HAL_LOCK( heth );\r
-\r
- /* Set the ETH peripheral state to BUSY */\r
- heth->State = HAL_ETH_STATE_BUSY;\r
-\r
- if( FrameLength == 0 )\r
- {\r
- /* Set ETH HAL state to READY */\r
- heth->State = HAL_ETH_STATE_READY;\r
-\r
- /* Process Unlocked */\r
- __HAL_UNLOCK( heth );\r
-\r
- return HAL_ERROR;\r
- }\r
-\r
- /* Check if the descriptor is owned by the ETHERNET DMA (when set) or CPU (when reset) */\r
- if( ( pxDmaTxDesc->Status & ETH_DMATXDESC_OWN ) != ( uint32_t ) RESET )\r
- {\r
- /* OWN bit set */\r
- heth->State = HAL_ETH_STATE_BUSY_TX;\r
-\r
- /* Process Unlocked */\r
- __HAL_UNLOCK( heth );\r
-\r
- return HAL_ERROR;\r
- }\r
-\r
- /* Get the number of needed Tx buffers for the current frame, rounding up. */\r
- bufcount = ( FrameLength + ETH_TX_BUF_SIZE - 1 ) / ETH_TX_BUF_SIZE;\r
-\r
- if (bufcount == 1)\r
- {\r
- /* Set LAST and FIRST segment */\r
- pxDmaTxDesc->Status |= ETH_DMATXDESC_FS | ETH_DMATXDESC_LS;\r
- /* Set frame size */\r
- pxDmaTxDesc->ControlBufferSize = ( FrameLength & ETH_DMATXDESC_TBS1 );\r
- /* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */\r
- pxDmaTxDesc->Status |= ETH_DMATXDESC_OWN;\r
- /* Point to next descriptor */\r
- heth->TxDesc = ( ETH_DMADescTypeDef * ) ( heth->TxDesc->Buffer2NextDescAddr );\r
- }\r
- else\r
- {\r
- for( i = 0; i < bufcount; i++ )\r
- {\r
- /* Clear FIRST and LAST segment bits */\r
- uint32_t ulStatus = heth->TxDesc->Status & ~( ETH_DMATXDESC_FS | ETH_DMATXDESC_LS );\r
-\r
- if( i == 0 )\r
- {\r
- /* Setting the first segment bit */\r
- heth->TxDesc->Status = ulStatus | ETH_DMATXDESC_FS;\r
- }\r
-\r
- /* Program size */\r
- if (i < (bufcount-1))\r
- {\r
- heth->TxDesc->ControlBufferSize = (ETH_TX_BUF_SIZE & ETH_DMATXDESC_TBS1);\r
- }\r
- else\r
- {\r
- /* Setting the last segment bit */\r
- heth->TxDesc->Status = ulStatus | ETH_DMATXDESC_LS;\r
- size = FrameLength - (bufcount-1)*ETH_TX_BUF_SIZE;\r
- heth->TxDesc->ControlBufferSize = (size & ETH_DMATXDESC_TBS1);\r
- }\r
-\r
- /* Set Own bit of the Tx descriptor Status: gives the buffer back to ETHERNET DMA */\r
- heth->TxDesc->Status |= ETH_DMATXDESC_OWN;\r
- /* point to next descriptor */\r
- heth->TxDesc = (ETH_DMADescTypeDef *)( heth->TxDesc->Buffer2NextDescAddr );\r
- }\r
- }\r
-\r
- __DSB();\r
-\r
- /* When Tx Buffer unavailable flag is set: clear it and resume transmission */\r
- if( ( heth->Instance->DMASR & ETH_DMASR_TBUS ) != ( uint32_t )RESET )\r
- {\r
- heth->Instance->DMACHTDR = ( uint32_t )pxDmaTxDesc;\r
-\r
- /* Clear TBUS ETHERNET DMA flag */\r
- heth->Instance->DMASR = ETH_DMASR_TBUS;\r
- /* Resume DMA transmission*/\r
- heth->Instance->DMATPDR = 0;\r
- }\r
-\r
- /* Set ETH HAL State to Ready */\r
- heth->State = HAL_ETH_STATE_READY;\r
-\r
- /* Process Unlocked */\r
- __HAL_UNLOCK( heth );\r
-\r
- /* Return function status */\r
- return HAL_OK;\r
-}\r
-\r
-/**\r
- * @brief Checks for received frames.\r
- * @param heth: pointer to a ETH_HandleTypeDef structure that contains\r
- * the configuration information for ETHERNET module\r
- * @retval HAL status\r
- */\r
-HAL_StatusTypeDef HAL_ETH_GetReceivedFrame_IT( ETH_HandleTypeDef *heth )\r
-{\r
- return HAL_ETH_GetReceivedFrame( heth );\r
-}\r
-\r
-HAL_StatusTypeDef HAL_ETH_GetReceivedFrame( ETH_HandleTypeDef *heth )\r
-{\r
-uint32_t ulCounter = 0;\r
-ETH_DMADescTypeDef *pxDescriptor = heth->RxDesc;\r
-HAL_StatusTypeDef xResult = HAL_ERROR;\r
-\r
- /* Process Locked */\r
- __HAL_LOCK( heth );\r
-\r
- /* Check the ETH state to BUSY */\r
- heth->State = HAL_ETH_STATE_BUSY;\r
-\r
- /* Scan descriptors owned by CPU */\r
- while( ( ( pxDescriptor->Status & ETH_DMARXDESC_OWN ) == 0ul ) && ( ulCounter < ETH_RXBUFNB ) )\r
- {\r
- uint32_t ulStatus = pxDescriptor->Status;\r
-\r
- /* Just for security. */\r
- ulCounter++;\r
-\r
- if( ( ulStatus & ( ETH_DMARXDESC_FS | ETH_DMARXDESC_LS ) ) == ( uint32_t )ETH_DMARXDESC_FS )\r
- {\r
- /* First segment in frame, but not the last. */\r
- heth->RxFrameInfos.FSRxDesc = pxDescriptor;\r
- heth->RxFrameInfos.LSRxDesc = ( ETH_DMADescTypeDef *)NULL;\r
- heth->RxFrameInfos.SegCount = 1;\r
- /* Point to next descriptor. */\r
- pxDescriptor = (ETH_DMADescTypeDef*) (pxDescriptor->Buffer2NextDescAddr);\r
- heth->RxDesc = pxDescriptor;\r
- }\r
- else if( ( ulStatus & ( ETH_DMARXDESC_LS | ETH_DMARXDESC_FS ) ) == 0ul )\r
- {\r
- /* This is an intermediate segment, not first, not last. */\r
- /* Increment segment count. */\r
- heth->RxFrameInfos.SegCount++;\r
- /* Move to the next descriptor. */\r
- pxDescriptor = ( ETH_DMADescTypeDef * ) ( pxDescriptor->Buffer2NextDescAddr );\r
- heth->RxDesc = pxDescriptor;\r
- }\r
- /* Must be a last segment */\r
- else\r
- {\r
- /* This is the last segment. */\r
- /* Check if last segment is first segment: one segment contains the frame */\r
- if( heth->RxFrameInfos.SegCount == 0 )\r
- {\r
- /* Remember the first segment. */\r
- heth->RxFrameInfos.FSRxDesc = pxDescriptor;\r
- }\r
-\r
- /* Increment segment count */\r
- heth->RxFrameInfos.SegCount++;\r
-\r
- /* Remember the last segment. */\r
- heth->RxFrameInfos.LSRxDesc = pxDescriptor;\r
-\r
- /* Get the Frame Length of the received packet: substruct 4 bytes of the CRC */\r
- heth->RxFrameInfos.length =\r
- ( ( ulStatus & ETH_DMARXDESC_FL ) >> ETH_DMARXDESC_FRAMELENGTHSHIFT ) - 4;\r
-\r
- /* Get the address of the buffer start address */\r
- heth->RxFrameInfos.buffer = heth->RxFrameInfos.FSRxDesc->Buffer1Addr;\r
-\r
- /* Point to next descriptor */\r
- heth->RxDesc = ( ETH_DMADescTypeDef * ) pxDescriptor->Buffer2NextDescAddr;\r
-\r
- /* Return OK status: a packet was received. */\r
- xResult = HAL_OK;\r
- break;\r
- }\r
- }\r
-\r
- /* Set ETH HAL State to Ready */\r
- heth->State = HAL_ETH_STATE_READY;\r
-\r
- /* Process Unlocked */\r
- __HAL_UNLOCK( heth );\r
-\r
- /* Return function status */\r
- return xResult;\r
-}\r
-\r
#define ETH_DMA_ALL_INTS \\r
( ETH_DMA_IT_TST | ETH_DMA_IT_PMT | ETH_DMA_IT_MMC | ETH_DMA_IT_NIS | ETH_DMA_IT_AIS | ETH_DMA_IT_ER | \\r
ETH_DMA_IT_FBE | ETH_DMA_IT_ET | ETH_DMA_IT_RWT | ETH_DMA_IT_RPS | ETH_DMA_IT_RBU | ETH_DMA_IT_R | \\r
/* NOTE : This function Should not be modified, when the callback is needed,\r
the HAL_ETH_TxCpltCallback could be implemented in the user file\r
*/\r
+ ( void ) heth;\r
}\r
\r
/**\r
/* NOTE : This function Should not be modified, when the callback is needed,\r
the HAL_ETH_TxCpltCallback could be implemented in the user file\r
*/\r
+ ( void ) heth;\r
}\r
\r
/**\r
/* NOTE : This function Should not be modified, when the callback is needed,\r
the HAL_ETH_TxCpltCallback could be implemented in the user file\r
*/\r
+ ( void ) heth;\r
}\r
\r
/**\r
*/\r
HAL_StatusTypeDef HAL_ETH_ReadPHYRegister(ETH_HandleTypeDef *heth, uint16_t PHYReg, uint32_t *RegValue)\r
{\r
-uint32_t tmpreg = 0;\r
-uint32_t tickstart = 0;\r
+uint32_t tmpreg = 0uL;\r
+uint32_t tickstart = 0uL;\r
HAL_StatusTypeDef xResult;\r
\r
/* Check parameters */\r
{\r
tmpreg = heth->Instance->MACMIIAR;\r
\r
- if( ( tmpreg & ETH_MACMIIAR_MB ) == 0ul )\r
+ if( ( tmpreg & ETH_MACMIIAR_MB ) == 0uL )\r
{\r
/* Get MACMIIDR value */\r
*RegValue = ( uint32_t ) heth->Instance->MACMIIDR;\r
return HAL_OK;\r
}\r
\r
+static void vRegisterDelay()\r
+{\r
+uint32_t uxCount;\r
+ /*\r
+ * Regarding the HAL delay functions, I noticed that HAL delay is being used to workaround the\r
+ * "Successive write operations to the same register might not be fully taken into account" errata.\r
+ * The workaround requires a delay of four TX_CLK/RX_CLK clock cycles. For a 10 Mbit connection,\r
+ * these clocks are running at 2.5 MHz, so this delay would be at most 1.6 microseconds.\r
+ * 180 Mhz = 288 loops\r
+ * 168 Mhz = 269 loops\r
+ * 100 Mhz = 160 loops\r
+ * 84 Mhz = 134 loops\r
+ */\r
+ #define WAIT_TIME_NS 1600uL /* 1.6 microseconds */\r
+ #define CPU_MAX_FREQ SystemCoreClock /* 84, 100, 168 or 180 MHz */\r
+ uint32_t NOP_COUNT = ( WAIT_TIME_NS * ( CPU_MAX_FREQ / 1000uL ) ) / 1000000uL;\r
+ for( uxCount = NOP_COUNT; uxCount > 0uL; uxCount-- )\r
+ {\r
+ __NOP();\r
+ }\r
+}\r
+\r
static void prvWriteMACFCR( ETH_HandleTypeDef *heth, uint32_t ulValue)\r
{\r
/* Enable the MAC transmission */\r
Read it back, wait a ms and */\r
( void ) heth->Instance->MACFCR;\r
\r
- HAL_Delay( ETH_REG_WRITE_DELAY );\r
+ vRegisterDelay();\r
\r
heth->Instance->MACFCR = ulValue;\r
}\r
Read it back, wait a ms and */\r
( void ) heth->Instance->DMAOMR;\r
\r
- HAL_Delay( ETH_REG_WRITE_DELAY );\r
+ vRegisterDelay();\r
\r
heth->Instance->DMAOMR = ulValue;\r
}\r
Read it back, wait a ms and */\r
( void ) heth->Instance->MACCR;\r
\r
- HAL_Delay( ETH_REG_WRITE_DELAY );\r
+ vRegisterDelay();\r
\r
heth->Instance->MACCR = ulValue;\r
}\r
*/\r
HAL_StatusTypeDef HAL_ETH_ConfigMAC(ETH_HandleTypeDef *heth, ETH_MACInitTypeDef *macconf)\r
{\r
- uint32_t tmpreg = 0;\r
+ uint32_t tmpreg = 0uL;\r
\r
/* Process Locked */\r
__HAL_LOCK( heth );\r
/* Wait until the write operation will be taken into account :\r
at least four TX_CLK/RX_CLK clock cycles */\r
tmpreg = heth->Instance->MACFFR;\r
- HAL_Delay(ETH_REG_WRITE_DELAY);\r
+ vRegisterDelay();\r
heth->Instance->MACFFR = tmpreg;\r
\r
/*--------------- ETHERNET MACHTHR and MACHTLR Configuration ---------------*/\r
/* Wait until the write operation will be taken into account :\r
at least four TX_CLK/RX_CLK clock cycles */\r
tmpreg = heth->Instance->MACVLANTR;\r
- HAL_Delay(ETH_REG_WRITE_DELAY);\r
+ vRegisterDelay();\r
heth->Instance->MACVLANTR = tmpreg;\r
}\r
else /* macconf == NULL : here we just configure Speed and Duplex mode */\r
tmpreg = heth->Instance->MACCR;\r
\r
/* Clear FES and DM bits */\r
- tmpreg &= ~((uint32_t)0x00004800);\r
+ tmpreg &= ~( ( uint32_t ) 0x00004800uL );\r
\r
tmpreg |= (uint32_t)(heth->Init.Speed | heth->Init.DuplexMode);\r
\r
*/\r
HAL_StatusTypeDef HAL_ETH_ConfigDMA(ETH_HandleTypeDef *heth, ETH_DMAInitTypeDef *dmaconf)\r
{\r
- uint32_t tmpreg = 0;\r
+ uint32_t tmpreg = 0uL;\r
\r
/* Process Locked */\r
__HAL_LOCK( heth );\r
/* Wait until the write operation will be taken into account:\r
at least four TX_CLK/RX_CLK clock cycles */\r
tmpreg = heth->Instance->DMABMR;\r
- HAL_Delay(ETH_REG_WRITE_DELAY);\r
+ vRegisterDelay();\r
heth->Instance->DMABMR = tmpreg;\r
\r
/* Set the ETH state to Ready */\r
{\r
ETH_MACInitTypeDef macinit;\r
ETH_DMAInitTypeDef dmainit;\r
- uint32_t tmpreg = 0;\r
+ uint32_t tmpreg = 0uL;\r
\r
if (err != ETH_SUCCESS) /* Auto-negotiation failed */\r
{\r
macinit.PromiscuousMode = ETH_PROMISCUOUS_MODE_DISABLE;\r
macinit.MulticastFramesFilter = ETH_MULTICASTFRAMESFILTER_PERFECT;\r
macinit.UnicastFramesFilter = ETH_UNICASTFRAMESFILTER_PERFECT;\r
- macinit.HashTableHigh = 0x0;\r
- macinit.HashTableLow = 0x0;\r
- macinit.PauseTime = 0x0;\r
+ macinit.HashTableHigh = 0x0uL;\r
+ macinit.HashTableLow = 0x0uL;\r
+ macinit.PauseTime = 0x0uL;\r
macinit.ZeroQuantaPause = ETH_ZEROQUANTAPAUSE_DISABLE;\r
macinit.PauseLowThreshold = ETH_PAUSELOWTHRESHOLD_MINUS4;\r
macinit.UnicastPauseFrameDetect = ETH_UNICASTPAUSEFRAMEDETECT_DISABLE;\r
macinit.ReceiveFlowControl = ETH_RECEIVEFLOWCONTROL_DISABLE;\r
macinit.TransmitFlowControl = ETH_TRANSMITFLOWCONTROL_DISABLE;\r
macinit.VLANTagComparison = ETH_VLANTAGCOMPARISON_16BIT;\r
- macinit.VLANTagIdentifier = 0x0;\r
+ macinit.VLANTagIdentifier = 0x0uL;\r
\r
/*------------------------ ETHERNET MACCR Configuration --------------------*/\r
/* Get the ETHERNET MACCR value */\r
/* Wait until the write operation will be taken into account:\r
at least four TX_CLK/RX_CLK clock cycles */\r
tmpreg = heth->Instance->MACFFR;\r
- HAL_Delay(ETH_REG_WRITE_DELAY);\r
+ vRegisterDelay();\r
heth->Instance->MACFFR = tmpreg;\r
\r
/*--------------- ETHERNET MACHTHR and MACHTLR Configuration --------------*/\r
/* Wait until the write operation will be taken into account:\r
at least four TX_CLK/RX_CLK clock cycles */\r
tmpreg = heth->Instance->MACVLANTR;\r
- HAL_Delay(ETH_REG_WRITE_DELAY);\r
+ vRegisterDelay();\r
heth->Instance->MACVLANTR = tmpreg;\r
\r
/* Ethernet DMA default initialization ************************************/\r
dmainit.RxDMABurstLength = ETH_RXDMABURSTLENGTH_32BEAT;\r
dmainit.TxDMABurstLength = ETH_TXDMABURSTLENGTH_32BEAT;\r
dmainit.EnhancedDescriptorFormat = ETH_DMAENHANCEDDESCRIPTOR_ENABLE;\r
- dmainit.DescriptorSkipLength = 0x0;\r
+ dmainit.DescriptorSkipLength = 0x0uL;\r
dmainit.DMAArbitration = ETH_DMAARBITRATION_ROUNDROBIN_RXTX_1_1;\r
\r
/* Get the ETHERNET DMAOMR value */\r
/* Wait until the write operation will be taken into account:\r
at least four TX_CLK/RX_CLK clock cycles */\r
tmpreg = heth->Instance->DMABMR;\r
- HAL_Delay(ETH_REG_WRITE_DELAY);\r
+ vRegisterDelay();\r
heth->Instance->DMABMR = tmpreg;\r
\r
if(heth->Init.RxMode == ETH_RXINTERRUPT_MODE)\r
{\r
uint32_t tmpreg;\r
\r
+ ( void ) heth;\r
+\r
/* Check the parameters */\r
assert_param( IS_ETH_MAC_ADDRESS0123( MacAddr ) );\r
\r
/* Calculate the selected MAC address high register */\r
- tmpreg = 0x80000000ul | ( ( uint32_t )Addr[ 5 ] << 8) | (uint32_t)Addr[ 4 ];\r
+ /* Register ETH_MACA0HR: Bit 31 MO: Always 1. */\r
+ tmpreg = 0x80000000uL | ( ( uint32_t )Addr[ 5 ] << 8) | (uint32_t)Addr[ 4 ];\r
/* Load the selected MAC address high register */\r
( * ( __IO uint32_t * ) ( ( uint32_t ) ( ETH_MAC_ADDR_HBASE + MacAddr ) ) ) = tmpreg;\r
/* Calculate the selected MAC address low register */\r
#define __STM32F4xx_HAL_ETH_H\r
#define __STM32F7xx_HAL_ETH_H\r
\r
+#if defined(STM32F7xx)\r
+ #include "stm32f7xx_hal_def.h"\r
+#elif defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\r
+ #include "stm32f4xx_hal_def.h"\r
+#elif defined(STM32F2xx)\r
+ #include "stm32f2xx_hal_def.h"\r
+#endif\r
+\r
#ifdef __cplusplus\r
extern "C" {\r
#endif\r
* @}\r
*/\r
\r
+#ifdef _lint\r
+ #ifdef __IO\r
+ #undef __IO\r
+ #endif\r
+ #define __IO\r
+\r
+ #ifdef ETH_TypeDef\r
+ #undef ETH_TypeDef\r
+ #endif\r
+ #define ETH_TypeDef void\r
+\r
+ #ifdef HAL_LockTypeDef\r
+ #undef HAL_LockTypeDef\r
+ #endif\r
+ #define HAL_LockTypeDef unsigned\r
+\r
+ #ifdef ETH_RX_BUF_SIZE\r
+ #undef ETH_RX_BUF_SIZE\r
+ #endif\r
+ #define ETH_RX_BUF_SIZE 1536\r
+\r
+ #ifdef ETH_TX_BUF_SIZE\r
+ #undef ETH_TX_BUF_SIZE\r
+ #endif\r
+ #define ETH_TX_BUF_SIZE 1536\r
+#endif\r
+\r
/* Exported types ------------------------------------------------------------*/\r
/** @defgroup ETH_Exported_Types ETH Exported Types\r
* @{\r
/** @defgroup ETH_MAC_Debug_flags ETH MAC Debug flags\r
* @{\r
*/\r
-#define ETH_MAC_TXFIFO_FULL ((uint32_t)0x02000000) /* Tx FIFO full */\r
-#define ETH_MAC_TXFIFONOT_EMPTY ((uint32_t)0x01000000) /* Tx FIFO not empty */\r
-#define ETH_MAC_TXFIFO_WRITE_ACTIVE ((uint32_t)0x00400000) /* Tx FIFO write active */\r
-#define ETH_MAC_TXFIFO_IDLE ((uint32_t)0x00000000) /* Tx FIFO read status: Idle */\r
-#define ETH_MAC_TXFIFO_READ ((uint32_t)0x00100000) /* Tx FIFO read status: Read (transferring data to the MAC transmitter) */\r
-#define ETH_MAC_TXFIFO_WAITING ((uint32_t)0x00200000) /* Tx FIFO read status: Waiting for TxStatus from MAC transmitter */\r
-#define ETH_MAC_TXFIFO_WRITING ((uint32_t)0x00300000) /* Tx FIFO read status: Writing the received TxStatus or flushing the TxFIFO */\r
-#define ETH_MAC_TRANSMISSION_PAUSE ((uint32_t)0x00080000) /* MAC transmitter in pause */\r
-#define ETH_MAC_TRANSMITFRAMECONTROLLER_IDLE ((uint32_t)0x00000000) /* MAC transmit frame controller: Idle */\r
-#define ETH_MAC_TRANSMITFRAMECONTROLLER_WAITING ((uint32_t)0x00020000) /* MAC transmit frame controller: Waiting for Status of previous frame or IFG/backoff period to be over */\r
-#define ETH_MAC_TRANSMITFRAMECONTROLLER_GENRATING_PCF ((uint32_t)0x00040000) /* MAC transmit frame controller: Generating and transmitting a Pause control frame (in full duplex mode) */\r
-#define ETH_MAC_TRANSMITFRAMECONTROLLER_TRANSFERRING ((uint32_t)0x00060000) /* MAC transmit frame controller: Transferring input frame for transmission */\r
-#define ETH_MAC_MII_TRANSMIT_ACTIVE ((uint32_t)0x00010000) /* MAC MII transmit engine active */\r
-#define ETH_MAC_RXFIFO_EMPTY ((uint32_t)0x00000000) /* Rx FIFO fill level: empty */\r
-#define ETH_MAC_RXFIFO_BELOW_THRESHOLD ((uint32_t)0x00000100) /* Rx FIFO fill level: fill-level below flow-control de-activate threshold */\r
-#define ETH_MAC_RXFIFO_ABOVE_THRESHOLD ((uint32_t)0x00000200) /* Rx FIFO fill level: fill-level above flow-control activate threshold */\r
-#define ETH_MAC_RXFIFO_FULL ((uint32_t)0x00000300) /* Rx FIFO fill level: full */\r
-#define ETH_MAC_READCONTROLLER_IDLE ((uint32_t)0x00000060) /* Rx FIFO read controller IDLE state */\r
-#define ETH_MAC_READCONTROLLER_READING_DATA ((uint32_t)0x00000060) /* Rx FIFO read controller Reading frame data */\r
-#define ETH_MAC_READCONTROLLER_READING_STATUS ((uint32_t)0x00000060) /* Rx FIFO read controller Reading frame status (or time-stamp) */\r
-#define ETH_MAC_READCONTROLLER_ FLUSHING ((uint32_t)0x00000060) /* Rx FIFO read controller Flushing the frame data and status */\r
-#define ETH_MAC_RXFIFO_WRITE_ACTIVE ((uint32_t)0x00000010) /* Rx FIFO write controller active */\r
-#define ETH_MAC_SMALL_FIFO_NOTACTIVE ((uint32_t)0x00000000) /* MAC small FIFO read / write controllers not active */\r
-#define ETH_MAC_SMALL_FIFO_READ_ACTIVE ((uint32_t)0x00000002) /* MAC small FIFO read controller active */\r
-#define ETH_MAC_SMALL_FIFO_WRITE_ACTIVE ((uint32_t)0x00000004) /* MAC small FIFO write controller active */\r
-#define ETH_MAC_SMALL_FIFO_RW_ACTIVE ((uint32_t)0x00000006) /* MAC small FIFO read / write controllers active */\r
-#define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE ((uint32_t)0x00000001) /* MAC MII receive protocol engine active */\r
+#ifndef ETH_MAC_TXFIFO_FULL\r
+ #define ETH_MAC_TXFIFO_FULL ((uint32_t)0x02000000) /* Tx FIFO full */\r
+ #define ETH_MAC_TXFIFONOT_EMPTY ((uint32_t)0x01000000) /* Tx FIFO not empty */\r
+ #define ETH_MAC_TXFIFO_WRITE_ACTIVE ((uint32_t)0x00400000) /* Tx FIFO write active */\r
+ #define ETH_MAC_TXFIFO_IDLE ((uint32_t)0x00000000) /* Tx FIFO read status: Idle */\r
+ #define ETH_MAC_TXFIFO_READ ((uint32_t)0x00100000) /* Tx FIFO read status: Read (transferring data to the MAC transmitter) */\r
+ #define ETH_MAC_TXFIFO_WAITING ((uint32_t)0x00200000) /* Tx FIFO read status: Waiting for TxStatus from MAC transmitter */\r
+ #define ETH_MAC_TXFIFO_WRITING ((uint32_t)0x00300000) /* Tx FIFO read status: Writing the received TxStatus or flushing the TxFIFO */\r
+ #define ETH_MAC_TRANSMISSION_PAUSE ((uint32_t)0x00080000) /* MAC transmitter in pause */\r
+ #define ETH_MAC_TRANSMITFRAMECONTROLLER_IDLE ((uint32_t)0x00000000) /* MAC transmit frame controller: Idle */\r
+ #define ETH_MAC_TRANSMITFRAMECONTROLLER_WAITING ((uint32_t)0x00020000) /* MAC transmit frame controller: Waiting for Status of previous frame or IFG/backoff period to be over */\r
+ #define ETH_MAC_TRANSMITFRAMECONTROLLER_GENRATING_PCF ((uint32_t)0x00040000) /* MAC transmit frame controller: Generating and transmitting a Pause control frame (in full duplex mode) */\r
+ #define ETH_MAC_TRANSMITFRAMECONTROLLER_TRANSFERRING ((uint32_t)0x00060000) /* MAC transmit frame controller: Transferring input frame for transmission */\r
+ #define ETH_MAC_MII_TRANSMIT_ACTIVE ((uint32_t)0x00010000) /* MAC MII transmit engine active */\r
+ #define ETH_MAC_RXFIFO_EMPTY ((uint32_t)0x00000000) /* Rx FIFO fill level: empty */\r
+ #define ETH_MAC_RXFIFO_BELOW_THRESHOLD ((uint32_t)0x00000100) /* Rx FIFO fill level: fill-level below flow-control de-activate threshold */\r
+ #define ETH_MAC_RXFIFO_ABOVE_THRESHOLD ((uint32_t)0x00000200) /* Rx FIFO fill level: fill-level above flow-control activate threshold */\r
+ #define ETH_MAC_RXFIFO_FULL ((uint32_t)0x00000300) /* Rx FIFO fill level: full */\r
+ #define ETH_MAC_READCONTROLLER_IDLE ((uint32_t)0x00000060) /* Rx FIFO read controller IDLE state */\r
+ #define ETH_MAC_READCONTROLLER_READING_DATA ((uint32_t)0x00000060) /* Rx FIFO read controller Reading frame data */\r
+ #define ETH_MAC_READCONTROLLER_READING_STATUS ((uint32_t)0x00000060) /* Rx FIFO read controller Reading frame status (or time-stamp) */\r
+ #define ETH_MAC_READCONTROLLER_ FLUSHING ((uint32_t)0x00000060) /* Rx FIFO read controller Flushing the frame data and status */\r
+ #define ETH_MAC_RXFIFO_WRITE_ACTIVE ((uint32_t)0x00000010) /* Rx FIFO write controller active */\r
+ #define ETH_MAC_SMALL_FIFO_NOTACTIVE ((uint32_t)0x00000000) /* MAC small FIFO read / write controllers not active */\r
+ #define ETH_MAC_SMALL_FIFO_READ_ACTIVE ((uint32_t)0x00000002) /* MAC small FIFO read controller active */\r
+ #define ETH_MAC_SMALL_FIFO_WRITE_ACTIVE ((uint32_t)0x00000004) /* MAC small FIFO write controller active */\r
+ #define ETH_MAC_SMALL_FIFO_RW_ACTIVE ((uint32_t)0x00000006) /* MAC small FIFO read / write controllers active */\r
+ #define ETH_MAC_MII_RECEIVE_PROTOCOL_ACTIVE ((uint32_t)0x00000001) /* MAC MII receive protocol engine active */\r
+#else\r
+ /* stm32_hal_legacy.h has probably been included. That file defines 'ETH_MAC_TXFIFO_FULL' and all macro's here below. */\r
+#endif\r
/**\r
* @}\r
*/\r
\r
if( ulCallCount > ulNextFaultCallCount )\r
{\r
- ulNextFaultCallCount = ipconfigRAND32() % xMAX_FAULT_INJECTION_RATE;\r
+ xApplicationGetRandomNumber( &( ulNextFaultCallCount ) );\r
+ ulNextFaultCallCount = ulNextFaultCallCount % xMAX_FAULT_INJECTION_RATE;\r
if( ulNextFaultCallCount < xMIN_FAULT_INJECTION_RATE )\r
{\r
ulNextFaultCallCount = xMIN_FAULT_INJECTION_RATE;\r
\r
ulCallCount = 0;\r
\r
- ulFault = ipconfigRAND32() % xNUM_FAULT_TYPES;\r
+ xApplicationGetRandomNumber( &( ulFault ) );\r
+ ulFault = ulFault % xNUM_FAULT_TYPES;\r
\r
if( ulFaultLogIndex < xFAULT_LOG_SIZE )\r
{\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
- * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
- * this software and associated documentation files (the "Software"), to deal in\r
- * the Software without restriction, including without limitation the rights to\r
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
- * the Software, and to permit persons to whom the Software is furnished to do so,\r
- * subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in all\r
- * copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
- *\r
- * http://aws.amazon.com/freertos\r
- * http://www.FreeRTOS.org\r
- */\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
\r
/* Standard includes. */\r
#include <stdint.h>\r
/* Provided memory configured as uncached. */\r
#include "uncached_memory.h"\r
\r
-#ifndef niEMAC_HANDLER_TASK_PRIORITY\r
- #define niEMAC_HANDLER_TASK_PRIORITY configMAX_PRIORITIES - 1\r
+#ifndef BMSR_LINK_STATUS\r
+ #define BMSR_LINK_STATUS 0x0004UL\r
#endif\r
\r
-#define niBMSR_LINK_STATUS 0x0004UL\r
-\r
#ifndef PHY_LS_HIGH_CHECK_TIME_MS\r
/* Check if the LinkSStatus in the PHY is still high after 15 seconds of not\r
receiving packets. */\r
possible priority to ensure the interrupt handler can return directly\r
to it. The task's handle is stored in xEMACTaskHandle so interrupts can\r
notify the task when there is something to process. */\r
- xTaskCreate( prvEMACHandlerTask, "EMAC", configEMAC_TASK_STACK_SIZE, NULL, niEMAC_HANDLER_TASK_PRIORITY, &xEMACTaskHandle );\r
+ xTaskCreate( prvEMACHandlerTask, "EMAC", configEMAC_TASK_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, &xEMACTaskHandle );\r
}\r
else\r
{\r
\r
BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxBuffer, BaseType_t bReleaseAfterSend )\r
{\r
- #if( ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM != 0 )\r
- {\r
- ProtocolPacket_t *pxPacket;\r
-\r
- /* If the peripheral must calculate the checksum, it wants\r
- the protocol checksum to have a value of zero. */\r
- pxPacket = ( ProtocolPacket_t * ) ( pxBuffer->pucEthernetBuffer );\r
- if( pxPacket->xICMPPacket.xIPHeader.ucProtocol == ipPROTOCOL_ICMP )\r
- {\r
- IPHeader_t *pxIPHeader = &( pxPacket->xUDPPacket.xIPHeader );\r
-\r
- pxPacket->xICMPPacket.xICMPHeader.usChecksum = ( uint16_t )0u;\r
- pxIPHeader->usHeaderChecksum = 0u;\r
- pxIPHeader->usHeaderChecksum = usGenerateChecksum( 0UL, ( uint8_t * ) &( pxIPHeader->ucVersionHeaderLength ), ipSIZE_OF_IPv4_HEADER );\r
- pxIPHeader->usHeaderChecksum = ~FreeRTOS_htons( pxIPHeader->usHeaderChecksum );\r
-\r
- usGenerateProtocolChecksum( (uint8_t*)&( pxPacket->xUDPPacket ), pxBuffer->xDataLength, pdTRUE );\r
- }\r
- }\r
- #endif /* ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM */\r
- if( ( ulPHYLinkStatus & niBMSR_LINK_STATUS ) != 0 )\r
+ if( ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != 0 )\r
{\r
iptraceNETWORK_INTERFACE_TRANSMIT();\r
emacps_send_message( &xEMACpsif, pxBuffer, bReleaseAfterSend );\r
}\r
ulPHYLinkStatus = ulReadMDIO( PHY_REG_01_BMSR );\r
\r
- if( ( ulPHYLinkStatus & niBMSR_LINK_STATUS ) != 0 )\r
+ if( ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != 0 )\r
{\r
xReturn = pdTRUE;\r
break;\r
{\r
BaseType_t xReturn;\r
\r
- if( ( ulPHYLinkStatus & niBMSR_LINK_STATUS ) == 0 )\r
+ if( ( ulPHYLinkStatus & BMSR_LINK_STATUS ) == 0 )\r
{\r
xReturn = pdFALSE;\r
}\r
{\r
TimeOut_t xPhyTime;\r
TickType_t xPhyRemTime;\r
+UBaseType_t uxLastMinBufferCount = 0;\r
UBaseType_t uxCurrentCount;\r
BaseType_t xResult = 0;\r
uint32_t xStatus;\r
const TickType_t ulMaxBlockTime = pdMS_TO_TICKS( 100UL );\r
-UBaseType_t uxLastMinBufferCount = 0;\r
-UBaseType_t uxCurrentBufferCount = 0;\r
\r
/* Remove compiler warnings about unused parameters. */\r
( void ) pvParameters;\r
\r
for( ;; )\r
{\r
- uxCurrentBufferCount = uxGetMinimumFreeNetworkBuffers();\r
- if( uxLastMinBufferCount != uxCurrentBufferCount )\r
+ uxCurrentCount = uxGetMinimumFreeNetworkBuffers();\r
+ if( uxLastMinBufferCount != uxCurrentCount )\r
{\r
/* The logging produced below may be helpful\r
while tuning +TCP: see how many buffers are in use. */\r
- uxLastMinBufferCount = uxCurrentBufferCount;\r
+ uxLastMinBufferCount = uxCurrentCount;\r
FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",\r
- uxGetNumberOfFreeNetworkBuffers(), uxCurrentBufferCount ) );\r
+ uxGetNumberOfFreeNetworkBuffers(), uxCurrentCount ) );\r
}\r
\r
#if( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
vTaskSetTimeOutState( &xPhyTime );\r
xPhyRemTime = pdMS_TO_TICKS( PHY_LS_HIGH_CHECK_TIME_MS );\r
xResult = 0;\r
- /* Indicate that the Link Status is high, so that\r
- xNetworkInterfaceOutput() can send packets. */\r
- ulPHYLinkStatus |= niBMSR_LINK_STATUS;\r
}\r
else if( xTaskCheckForTimeOut( &xPhyTime, &xPhyRemTime ) != pdFALSE )\r
{\r
xStatus = ulReadMDIO( PHY_REG_01_BMSR );\r
\r
- if( ( ulPHYLinkStatus & niBMSR_LINK_STATUS ) != ( xStatus & niBMSR_LINK_STATUS ) )\r
+ if( ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != ( xStatus & BMSR_LINK_STATUS ) )\r
{\r
ulPHYLinkStatus = xStatus;\r
- FreeRTOS_printf( ( "prvEMACHandlerTask: PHY LS now %d\n", ( ulPHYLinkStatus & niBMSR_LINK_STATUS ) != 0 ) );\r
+ FreeRTOS_printf( ( "prvEMACHandlerTask: PHY LS now %d\n", ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != 0 ) );\r
}\r
\r
vTaskSetTimeOutState( &xPhyTime );\r
- if( ( ulPHYLinkStatus & niBMSR_LINK_STATUS ) != 0 )\r
+ if( ( ulPHYLinkStatus & BMSR_LINK_STATUS ) != 0 )\r
{\r
xPhyRemTime = pdMS_TO_TICKS( PHY_LS_HIGH_CHECK_TIME_MS );\r
}\r
#include "xil_exception.h"\r
#include "xpseudo_asm.h"\r
#include "xil_cache.h"\r
+#include "xil_printf.h"\r
#include "xuartps.h"\r
#include "xscugic.h"\r
#include "xemacps.h" /* defines XEmacPs API */\r
/*\r
- * FreeRTOS+TCP V2.0.11\r
- * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
- * this software and associated documentation files (the "Software"), to deal in\r
- * the Software without restriction, including without limitation the rights to\r
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
- * the Software, and to permit persons to whom the Software is furnished to do so,\r
- * subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in all\r
- * copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
- *\r
- * http://aws.amazon.com/freertos\r
- * http://www.FreeRTOS.org\r
- */\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
+\r
+#include "Zynq/x_emacpsif.h"\r
+#include "Zynq/x_topology.h"\r
+#include "xstatus.h"\r
+\r
+#include "xparameters.h"\r
+#include "xparameters_ps.h"\r
+#include "xil_exception.h"\r
+#include "xil_mmu.h"\r
\r
#include "FreeRTOS.h"\r
#include "task.h"\r
#include "FreeRTOS_IP_Private.h"\r
#include "NetworkBufferManagement.h"\r
\r
-#include "Zynq/x_emacpsif.h"\r
-#include "Zynq/x_topology.h"\r
-#include "xstatus.h"\r
-\r
-#include "xparameters.h"\r
-#include "xparameters_ps.h"\r
-#include "xil_exception.h"\r
-#include "xil_mmu.h"\r
-\r
#include "uncached_memory.h"\r
\r
/* Two defines used to set or clear the EMAC interrupt */\r
#endif\r
#define TX_OFFSET ipconfigPACKET_FILLER_SIZE\r
\r
+#define RX_BUFFER_ALIGNMENT 14\r
+\r
/* Defined in NetworkInterface.c */\r
extern TaskHandle_t xEMACTaskHandle;\r
\r
break;\r
}\r
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )\r
+#warning ipconfigZERO_COPY_TX_DRIVER is defined\r
{\r
void *pvBuffer = pxDMA_tx_buffers[ tail ];\r
NetworkBufferDescriptor_t *pxBuffer;\r
/* Start transmit */\r
xemacpsif->txBusy = pdTRUE;\r
XEmacPs_WriteReg( ulBaseAddress, XEMACPS_NWCTRL_OFFSET, ( ulValue | XEMACPS_NWCTRL_STARTTX_MASK ) );\r
- /* Reading it back is important compiler is optimised. */\r
- XEmacPs_ReadReg( ulBaseAddress, XEMACPS_NWCTRL_OFFSET );\r
}\r
dsb();\r
\r
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );\r
}\r
\r
-static void prvPassEthMessages( NetworkBufferDescriptor_t *pxDescriptor )\r
+static NetworkBufferDescriptor_t *ethMsg = NULL;\r
+static NetworkBufferDescriptor_t *ethLast = NULL;\r
+\r
+static void passEthMessages( void )\r
{\r
IPStackEvent_t xRxEvent;\r
\r
xRxEvent.eEventType = eNetworkRxEvent;\r
- xRxEvent.pvData = ( void * ) pxDescriptor;\r
+ xRxEvent.pvData = ( void * ) ethMsg;\r
\r
if( xSendEventStructToIPTask( &xRxEvent, ( TickType_t ) 1000 ) != pdPASS )\r
{\r
/* The buffer could not be sent to the stack so must be released again.\r
This is a deferred handler taskr, not a real interrupt, so it is ok to\r
use the task level function here. */\r
- #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
- {\r
- do\r
- {\r
- NetworkBufferDescriptor_t *pxNext = pxDescriptor->pxNextBuffer;\r
- vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
- pxDescriptor = pxNext;\r
- } while( pxDescriptor != NULL );\r
- }\r
- #else\r
+ do\r
{\r
- vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
- }\r
- #endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
+ NetworkBufferDescriptor_t *xNext = ethMsg->pxNextBuffer;\r
+ vReleaseNetworkBufferAndDescriptor( ethMsg );\r
+ ethMsg = xNext;\r
+ } while( ethMsg != NULL );\r
+\r
iptraceETHERNET_RX_EVENT_LOST();\r
- FreeRTOS_printf( ( "prvPassEthMessages: Can not queue return packet!\n" ) );\r
+ FreeRTOS_printf( ( "passEthMessages: Can not queue return packet!\n" ) );\r
}\r
+\r
+ ethMsg = ethLast = NULL;\r
}\r
\r
int emacps_check_rx( xemacpsif_s *xemacpsif )\r
int rx_bytes;\r
volatile int msgCount = 0;\r
int head = xemacpsif->rxHead;\r
-#if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
- NetworkBufferDescriptor_t *pxFirstDescriptor = NULL;\r
- NetworkBufferDescriptor_t *pxLastDescriptor = NULL;\r
-#endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
\r
/* There seems to be an issue (SI# 692601), see comments below. */\r
resetrx_on_no_rxdata(xemacpsif);\r
break;\r
}\r
\r
- pxNewBuffer = pxGetNetworkBufferWithDescriptor( ipTOTAL_ETHERNET_FRAME_SIZE, ( TickType_t ) 0 );\r
+ pxNewBuffer = pxGetNetworkBufferWithDescriptor( ipTOTAL_ETHERNET_FRAME_SIZE + RX_BUFFER_ALIGNMENT, ( TickType_t ) 0 );\r
if( pxNewBuffer == NULL )\r
{\r
/* A packet has been received, but there is no replacement for this Network Buffer.\r
rx_bytes = xemacpsif->rxSegments[ head ].flags & XEMACPS_RXBUF_LEN_MASK;\r
\r
pxBuffer->xDataLength = rx_bytes;\r
+\r
if( ucIsCachedMemory( pxBuffer->pucEthernetBuffer ) != 0 )\r
{\r
Xil_DCacheInvalidateRange( ( ( uint32_t )pxBuffer->pucEthernetBuffer ) - ipconfigPACKET_FILLER_SIZE, (unsigned)rx_bytes );\r
/* store it in the receive queue, where it'll be processed by a\r
different handler. */\r
iptraceNETWORK_INTERFACE_RECEIVE();\r
- #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
- {\r
- pxBuffer->pxNextBuffer = NULL;\r
+ pxBuffer->pxNextBuffer = NULL;\r
\r
- if( pxFirstDescriptor == NULL )\r
- {\r
- // Becomes the first message\r
- pxFirstDescriptor = pxBuffer;\r
- }\r
- else if( pxLastDescriptor != NULL )\r
- {\r
- // Add to the tail\r
- pxLastDescriptor->pxNextBuffer = pxBuffer;\r
- }\r
-\r
- pxLastDescriptor = pxBuffer;\r
+ if( ethMsg == NULL )\r
+ {\r
+ // Becomes the first message\r
+ ethMsg = pxBuffer;\r
}\r
- #else\r
+ else if( ethLast != NULL )\r
{\r
- prvPassEthMessages( pxBuffer );\r
+ // Add to the tail\r
+ ethLast->pxNextBuffer = pxBuffer;\r
}\r
- #endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
\r
+ ethLast = pxBuffer;\r
msgCount++;\r
}\r
{\r
if( ucIsCachedMemory( pxNewBuffer->pucEthernetBuffer ) != 0 )\r
{\r
- Xil_DCacheInvalidateRange( ( ( uint32_t )pxNewBuffer->pucEthernetBuffer ) - ipconfigPACKET_FILLER_SIZE, (unsigned)ipTOTAL_ETHERNET_FRAME_SIZE );\r
+ Xil_DCacheInvalidateRange( ( ( uint32_t )pxNewBuffer->pucEthernetBuffer ) - ipconfigPACKET_FILLER_SIZE, (unsigned)ipTOTAL_ETHERNET_FRAME_SIZE + RX_BUFFER_ALIGNMENT);\r
}\r
{\r
uint32_t addr = ( ( uint32_t )pxNewBuffer->pucEthernetBuffer ) & XEMACPS_RXBUF_ADD_MASK;\r
addr |= XEMACPS_RXBUF_WRAP_MASK;\r
}\r
/* Clearing 'XEMACPS_RXBUF_NEW_MASK' 0x00000001 *< Used bit.. */\r
- xemacpsif->rxSegments[ head ].flags = 0;\r
xemacpsif->rxSegments[ head ].address = addr;\r
- if (xemacpsif->rxSegments[ head ].address)\r
- {\r
- // Just to read it\r
- }\r
+ xemacpsif->rxSegments[ head ].flags = 0;\r
}\r
}\r
\r
xemacpsif->rxHead = head;\r
}\r
\r
- #if( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
+ if( ethMsg != NULL )\r
{\r
- if( pxFirstDescriptor != NULL )\r
- {\r
- prvPassEthMessages( pxFirstDescriptor );\r
- }\r
+ passEthMessages( );\r
}\r
- #endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
\r
return msgCount;\r
}\r
xemacpsif->txSegments[ index ].address = ( uint32_t )ucTxBuffer;\r
xemacpsif->txSegments[ index ].flags = XEMACPS_TXBUF_USED_MASK;\r
#if( ipconfigZERO_COPY_TX_DRIVER != 0 )\r
- pxDMA_tx_buffers[ index ] = ( unsigned char * )NULL;\r
+ pxDMA_tx_buffers[ index ] = ( void* )NULL;\r
#else\r
- pxDMA_tx_buffers[ index ] = ( unsigned char * )( ucTxBuffer + TX_OFFSET );\r
+ pxDMA_tx_buffers[ index ] = ( void* )( ucTxBuffer + TX_OFFSET );\r
#endif\r
ucTxBuffer += xemacpsif->uTxUnitSize;\r
}\r
pxBuffer = pxDMA_rx_buffers[ iIndex ];\r
if( pxBuffer == NULL )\r
{\r
- pxBuffer = pxGetNetworkBufferWithDescriptor( ipTOTAL_ETHERNET_FRAME_SIZE, ( TickType_t ) 0 );\r
+ pxBuffer = pxGetNetworkBufferWithDescriptor( ipTOTAL_ETHERNET_FRAME_SIZE + RX_BUFFER_ALIGNMENT, ( TickType_t ) 0 );\r
if( pxBuffer == NULL )\r
{\r
FreeRTOS_printf( ("Unable to allocate a network buffer in recv_handler\n" ) );\r
if( ucIsCachedMemory( pxBuffer->pucEthernetBuffer ) != 0 )\r
{\r
Xil_DCacheInvalidateRange( ( ( uint32_t )pxBuffer->pucEthernetBuffer ) - ipconfigPACKET_FILLER_SIZE,\r
- (unsigned)ipTOTAL_ETHERNET_FRAME_SIZE );\r
+ (unsigned)ipTOTAL_ETHERNET_FRAME_SIZE + RX_BUFFER_ALIGNMENT);\r
}\r
}\r
\r
#include <stdio.h>\r
#include <stdlib.h>\r
\r
+#include "Zynq/x_emacpsif.h"\r
+\r
/* FreeRTOS includes. */\r
#include "FreeRTOS.h"\r
#include "task.h"\r
#include "queue.h"\r
\r
+///* FreeRTOS+TCP includes. */\r
/* FreeRTOS+TCP includes. */\r
#include "FreeRTOS_IP.h"\r
#include "FreeRTOS_Sockets.h"\r
#include "FreeRTOS_IP_Private.h"\r
#include "NetworkBufferManagement.h"\r
-#include "NetworkInterface.h"\r
-\r
-#include "Zynq/x_emacpsif.h"\r
\r
extern TaskHandle_t xEMACTaskHandle;\r
\r
*** to run it on a PEEP board\r
***/\r
\r
+unsigned int link_speed = 100;\r
+\r
void setup_isr( xemacpsif_s *xemacpsif )\r
{\r
/*\r
return xResult;\r
}\r
\r
+BaseType_t xNetworkInterfaceInitialise( void );\r
+\r
static void emacps_handle_error(void *arg, u8 Direction, u32 ErrorWord)\r
{\r
xemacpsif_s *xemacpsif;\r
}\r
}\r
\r
+extern XEmacPs_Config mac_config;\r
+\r
void HandleTxErrors(xemacpsif_s *xemacpsif)\r
{\r
u32 netctrlreg;\r
#include <stdio.h>\r
#include <stdlib.h>\r
\r
+#include "Zynq/x_emacpsif.h"\r
+//#include "lwipopts.h"\r
+#include "xparameters_ps.h"\r
+#include "xparameters.h"\r
+\r
/* FreeRTOS includes. */\r
#include "FreeRTOS.h"\r
#include "task.h"\r
#include "queue.h"\r
#include "semphr.h"\r
\r
+///* FreeRTOS+TCP includes. */\r
/* FreeRTOS+TCP includes. */\r
#include "FreeRTOS_IP.h"\r
#include "FreeRTOS_Sockets.h"\r
#include "FreeRTOS_IP_Private.h"\r
#include "NetworkBufferManagement.h"\r
\r
-#include "Zynq/x_emacpsif.h"\r
-#include "xparameters_ps.h"\r
-#include "xparameters.h"\r
-\r
-\r
int phy_detected = 0;\r
\r
/*** IMPORTANT: Define PEEP in xemacpsif.h and sys_arch_raw.c\r
\r
#define IEEE_CONTROL_REG_OFFSET 0\r
#define IEEE_STATUS_REG_OFFSET 1\r
-#define IEEE_PHYSID1_OFFSET 2\r
-#define IEEE_PHYSID2_OFFSET 3\r
#define IEEE_AUTONEGO_ADVERTISE_REG 4\r
#define IEEE_PARTNER_ABILITIES_1_REG_OFFSET 5\r
#define IEEE_1000_ADVERTISE_REG_OFFSET 9\r
#define IEEE_PAUSE_MASK 0x0400\r
#define IEEE_AUTONEG_ERROR_MASK 0x8000\r
\r
+#define PHY_DETECT_REG 1\r
+#define PHY_DETECT_MASK 0x1808\r
+\r
#define XEMACPS_GMII2RGMII_SPEED1000_FD 0x140\r
#define XEMACPS_GMII2RGMII_SPEED100_FD 0x2100\r
#define XEMACPS_GMII2RGMII_SPEED10_FD 0x100\r
\r
static int detect_phy(XEmacPs *xemacpsp)\r
{\r
- u16 id_lower, id_upper;\r
- u32 phy_addr, id;\r
-\r
- for (phy_addr = 0; phy_addr < 32; phy_addr++) {\r
- XEmacPs_PhyRead(xemacpsp, phy_addr, IEEE_PHYSID1_OFFSET, &id_lower);\r
-\r
- if ((id_lower != ( u16 )0xFFFFu) && (id_lower != ( u16 )0x0u)) {\r
-\r
- XEmacPs_PhyRead(xemacpsp, phy_addr, IEEE_PHYSID2_OFFSET, &id_upper);\r
- id = ( ( ( uint32_t ) id_upper ) << 16 ) | ( id_lower & 0xFFF0 );\r
- FreeRTOS_printf( ("XEmacPs detect_phy: %04lX at address %d.\n", id, phy_addr ) );\r
+ u16 phy_reg;\r
+ u32 phy_addr;\r
+\r
+ for (phy_addr = 31; phy_addr > 0; phy_addr--) {\r
+ XEmacPs_PhyRead(xemacpsp, phy_addr, PHY_DETECT_REG,\r
+ &phy_reg);\r
+\r
+ if ((phy_reg != 0xFFFF) &&\r
+ ((phy_reg & PHY_DETECT_MASK) == PHY_DETECT_MASK)) {\r
+ /* Found a valid PHY address */\r
+ FreeRTOS_printf( ("XEmacPs detect_phy: PHY detected at address %d.\r\n",\r
+ phy_addr));\r
+ FreeRTOS_printf( ("XEmacPs detect_phy: PHY detected.\n" ) );\r
phy_detected = phy_addr;\r
return phy_addr;\r
}\r
if (partner_capabilities & IEEE_AN1_ABILITY_MASK_10MBPS)\r
return 10;\r
\r
- FreeRTOS_printf( ( "%s: unknown PHY link speed, setting TEMAC speed to be 10 Mbps\n",\r
- __FUNCTION__ ) );\r
+ xil_printf("%s: unknown PHY link speed, setting TEMAC speed to be 10 Mbps\r\n",\r
+ __FUNCTION__);\r
return 10;\r
\r
} else {\r
case (IEEE_CTRL_LINKSPEED_10M):\r
return 10;\r
default:\r
- FreeRTOS_printf( ( "%s: unknown PHY link speed (%d), setting TEMAC speed to be 10 Mbps\n",\r
- __FUNCTION__, phylinkspeed ) );\r
+ xil_printf("%s: unknown PHY link speed (%d), setting TEMAC speed to be 10 Mbps\r\n",\r
+ __FUNCTION__, phylinkspeed);\r
return 10;\r
}\r
\r
#else\r
u32 phy_addr = detect_phy(xemacpsp);\r
#endif\r
- FreeRTOS_printf( ( "Start PHY autonegotiation \n" ) );\r
+ xil_printf("Start PHY autonegotiation \r\n");\r
\r
#if XPAR_GIGE_PCS_PMA_CORE_PRESENT == 1\r
#else\r
break;\r
}\r
#endif\r
- FreeRTOS_printf( ( "Waiting for PHY to complete autonegotiation.\n" ) );\r
+ xil_printf("Waiting for PHY to complete autonegotiation.\r\n");\r
\r
XEmacPs_PhyRead(xemacpsp, phy_addr, IEEE_STATUS_REG_OFFSET, &status);\r
while ( !(status & IEEE_STAT_AUTONEGOTIATE_COMPLETE) ) {\r
- vTaskDelay(1);\r
+ sleep(1);\r
#if XPAR_GIGE_PCS_PMA_CORE_PRESENT == 1\r
#else\r
XEmacPs_PhyRead(xemacpsp, phy_addr, IEEE_COPPER_SPECIFIC_STATUS_REG_2,\r
&temp);\r
if (temp & IEEE_AUTONEG_ERROR_MASK) {\r
- FreeRTOS_printf( ( "Auto negotiation error \n" ) );\r
+ xil_printf("Auto negotiation error \r\n");\r
}\r
#endif\r
XEmacPs_PhyRead(xemacpsp, phy_addr, IEEE_STATUS_REG_OFFSET,\r
&status);\r
}\r
\r
- FreeRTOS_printf( ( "autonegotiation complete \n" ) );\r
+ xil_printf("autonegotiation complete \r\n");\r
\r
#if XPAR_GIGE_PCS_PMA_CORE_PRESENT == 1\r
#else\r
#endif\r
\r
#if XPAR_GIGE_PCS_PMA_CORE_PRESENT == 1\r
- FreeRTOS_printf( ( "Waiting for Link to be up; Polling for SGMII core Reg \n" ) );\r
+ xil_printf("Waiting for Link to be up; Polling for SGMII core Reg \r\n");\r
XEmacPs_PhyRead(xemacpsp, phy_addr, 5, &temp);\r
while(!(temp & 0x8000)) {\r
XEmacPs_PhyRead(xemacpsp, phy_addr, 5, &temp);\r
XEmacPs_PhyRead(xemacpsp, phy_addr, 0, &temp);\r
return 10;\r
} else {\r
- FreeRTOS_printf( ( "get_IEEE_phy_speed(): Invalid speed bit value, Deafulting to Speed = 10 Mbps\n" ) );\r
+ xil_printf("get_IEEE_phy_speed(): Invalid speed bit value, Deafulting to Speed = 10 Mbps\r\n");\r
XEmacPs_PhyRead(xemacpsp, phy_addr, 0, &temp);\r
XEmacPs_PhyWrite(xemacpsp, phy_addr, 0, 0x0100);\r
return 10;\r
link_speed = 1000;\r
configure_IEEE_phy_speed(xemacpsp, link_speed);\r
convspeeddupsetting = XEMACPS_GMII2RGMII_SPEED1000_FD;\r
- vTaskDelay(1);\r
+ sleep(1);\r
#elif defined(ipconfigNIC_LINKSPEED100)\r
SetUpSLCRDivisors(xemacpsp->Config.BaseAddress,100);\r
link_speed = 100;\r
configure_IEEE_phy_speed(xemacpsp, link_speed);\r
convspeeddupsetting = XEMACPS_GMII2RGMII_SPEED100_FD;\r
- vTaskDelay(1);\r
+ sleep(1);\r
#elif defined(ipconfigNIC_LINKSPEED10)\r
SetUpSLCRDivisors(xemacpsp->Config.BaseAddress,10);\r
link_speed = 10;\r
configure_IEEE_phy_speed(xemacpsp, link_speed);\r
convspeeddupsetting = XEMACPS_GMII2RGMII_SPEED10_FD;\r
- vTaskDelay(1);\r
+ sleep(1);\r
#endif\r
if (conv_present) {\r
XEmacPs_PhyWrite(xemacpsp, convphyaddr,\r
XEMACPS_GMII2RGMII_REG_NUM, convspeeddupsetting);\r
}\r
\r
- FreeRTOS_printf( ( "link speed: %d\n", link_speed ) );\r
+ xil_printf("link speed: %d\r\n", link_speed);\r
return link_speed;\r
}\r
\r
--- /dev/null
+/*\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
+\r
+/* FreeRTOS includes. */\r
+#include "FreeRTOS.h"\r
+#include "list.h"\r
+\r
+/* FreeRTOS+TCP includes. */\r
+#include "FreeRTOS_IP.h"\r
+\r
+/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet\r
+driver will filter incoming packets and only pass the stack those packets it\r
+considers need processing. */\r
+#if( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )\r
+#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer\r
+#else\r
+#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )\r
+#endif\r
+\r
+BaseType_t xNetworkInterfaceInitialise( void )\r
+{\r
+ /* FIX ME. */\r
+ return pdFALSE;\r
+}\r
+\r
+BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxNetworkBuffer, BaseType_t xReleaseAfterSend )\r
+{\r
+ /* FIX ME. */\r
+ return pdFALSE;\r
+}\r
+\r
+void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )\r
+{\r
+ /* FIX ME. */\r
+}\r
+\r
+BaseType_t xGetPhyLinkStatus( void )\r
+{\r
+ /* FIX ME. */\r
+ return pdFALSE;\r
+}
\ No newline at end of file
--- /dev/null
+Update NetworkInterface.c and include other files needed by FreeRTOS+TCP here.
\ No newline at end of file
--- /dev/null
+// Copyright 2018 Espressif Systems (Shanghai) PTE LTD\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+\r
+/* Standard includes. */\r
+#include <stdint.h>\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+\r
+/* FreeRTOS includes. */\r
+#include "FreeRTOS.h"\r
+#include "task.h"\r
+#include "queue.h"\r
+#include "semphr.h"\r
+\r
+/* FreeRTOS+TCP includes. */\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_Sockets.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+#include "FreeRTOS_DNS.h"\r
+#include "NetworkBufferManagement.h"\r
+#include "NetworkInterface.h"\r
+\r
+#include "esp_log.h"\r
+#include "esp_wifi.h"\r
+#include "esp_wifi_internal.h"\r
+#include "tcpip_adapter.h"\r
+\r
+enum if_state_t {\r
+ INTERFACE_DOWN = 0,\r
+ INTERFACE_UP,\r
+};\r
+\r
+static const char *TAG = "NetInterface";\r
+volatile static uint32_t xInterfaceState = INTERFACE_DOWN;\r
+\r
+#if ( ipconfigHAS_PRINTF != 0 )\r
+ static void prvMonitorResources();\r
+#endif\r
+\r
+BaseType_t xNetworkInterfaceInitialise( void )\r
+{\r
+ static BaseType_t xMACAdrInitialized = pdFALSE;\r
+ uint8_t ucMACAddress[ ipMAC_ADDRESS_LENGTH_BYTES ];\r
+\r
+ if (xInterfaceState == INTERFACE_UP) {\r
+ if (xMACAdrInitialized == pdFALSE) {\r
+ esp_wifi_get_mac(ESP_IF_WIFI_STA, ucMACAddress);\r
+ FreeRTOS_UpdateMACAddress(ucMACAddress);\r
+ xMACAdrInitialized = pdTRUE;\r
+ }\r
+ return pdTRUE;\r
+ }\r
+ return pdFALSE;\r
+}\r
+\r
+BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t *const pxNetworkBuffer, BaseType_t xReleaseAfterSend )\r
+{\r
+ if (pxNetworkBuffer == NULL || pxNetworkBuffer->pucEthernetBuffer == NULL || pxNetworkBuffer->xDataLength == 0) {\r
+ ESP_LOGE(TAG, "Invalid params");\r
+ return pdFALSE;\r
+ }\r
+\r
+ esp_err_t ret;\r
+ if (xInterfaceState == INTERFACE_DOWN) {\r
+ ESP_LOGD(TAG, "Interface down");\r
+ ret = ESP_FAIL;\r
+ } else {\r
+ ret = esp_wifi_internal_tx(ESP_IF_WIFI_STA, pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength);\r
+ if (ret != ESP_OK) {\r
+ ESP_LOGE(TAG, "Failed to tx buffer %p, len %d, err %d", pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength, ret);\r
+ }\r
+ }\r
+\r
+#if ( ipconfigHAS_PRINTF != 0 )\r
+ prvMonitorResources();\r
+#endif\r
+ if (xReleaseAfterSend == pdTRUE) {\r
+ vReleaseNetworkBufferAndDescriptor(pxNetworkBuffer);\r
+ }\r
+\r
+ return ret == ESP_OK ? pdTRUE : pdFALSE;\r
+}\r
+\r
+void vNetworkNotifyIFDown()\r
+{\r
+ IPStackEvent_t xRxEvent = { eNetworkDownEvent, NULL };\r
+ if (xInterfaceState != INTERFACE_DOWN) {\r
+ xInterfaceState = INTERFACE_DOWN;\r
+ xSendEventStructToIPTask( &xRxEvent, 0 );\r
+ }\r
+}\r
+\r
+void vNetworkNotifyIFUp()\r
+{\r
+ xInterfaceState = INTERFACE_UP;\r
+}\r
+\r
+esp_err_t wlanif_input(void *netif, void *buffer, uint16_t len, void *eb)\r
+{\r
+ NetworkBufferDescriptor_t *pxNetworkBuffer;\r
+ IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };\r
+ const TickType_t xDescriptorWaitTime = pdMS_TO_TICKS( 250 );\r
+\r
+#if ( ipconfigHAS_PRINTF != 0 )\r
+ prvMonitorResources();\r
+#endif\r
+\r
+ if( eConsiderFrameForProcessing( buffer ) != eProcessBuffer ) {\r
+ ESP_LOGD(TAG, "Dropping packet");\r
+ esp_wifi_internal_free_rx_buffer(eb);\r
+ return ESP_OK;\r
+ }\r
+\r
+ pxNetworkBuffer = pxGetNetworkBufferWithDescriptor(len, xDescriptorWaitTime);\r
+ if (pxNetworkBuffer != NULL) {\r
+\r
+ /* Set the packet size, in case a larger buffer was returned. */\r
+ pxNetworkBuffer->xDataLength = len;\r
+\r
+ /* Copy the packet data. */\r
+ memcpy(pxNetworkBuffer->pucEthernetBuffer, buffer, len);\r
+ xRxEvent.pvData = (void *) pxNetworkBuffer;\r
+\r
+ if ( xSendEventStructToIPTask( &xRxEvent, xDescriptorWaitTime) == pdFAIL ) {\r
+ ESP_LOGE(TAG, "Failed to enqueue packet to network stack %p, len %d", buffer, len);\r
+ vReleaseNetworkBufferAndDescriptor(pxNetworkBuffer);\r
+ return ESP_FAIL;\r
+ }\r
+ esp_wifi_internal_free_rx_buffer(eb);\r
+ return ESP_OK;\r
+ } else {\r
+ ESP_LOGE(TAG, "Failed to get buffer descriptor");\r
+ return ESP_FAIL;\r
+ }\r
+}\r
+\r
+#if ( ipconfigHAS_PRINTF != 0 )\r
+ static void prvMonitorResources()\r
+ {\r
+ static UBaseType_t uxLastMinBufferCount = 0u;\r
+ static UBaseType_t uxCurrentBufferCount = 0u;\r
+ static size_t uxMinLastSize = 0uL;\r
+ size_t uxMinSize;\r
+\r
+ uxCurrentBufferCount = uxGetMinimumFreeNetworkBuffers();\r
+\r
+ if( uxLastMinBufferCount != uxCurrentBufferCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ * while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinBufferCount = uxCurrentBufferCount;\r
+ FreeRTOS_printf( ( "Network buffers: %lu lowest %lu\n",\r
+ uxGetNumberOfFreeNetworkBuffers(), uxCurrentBufferCount ) );\r
+ }\r
+\r
+ uxMinSize = xPortGetMinimumEverFreeHeapSize();\r
+\r
+ if( uxMinLastSize != uxMinSize )\r
+ {\r
+ uxMinLastSize = uxMinSize;\r
+ FreeRTOS_printf( ( "Heap: current %lu lowest %lu\n", xPortGetFreeHeapSize(), uxMinSize ) );\r
+ }\r
+\r
+ #if ( ipconfigCHECK_IP_QUEUE_SPACE != 0 )\r
+ {\r
+ static UBaseType_t uxLastMinQueueSpace = 0;\r
+ UBaseType_t uxCurrentCount = 0u;\r
+\r
+ uxCurrentCount = uxGetMinimumIPQueueSpace();\r
+\r
+ if( uxLastMinQueueSpace != uxCurrentCount )\r
+ {\r
+ /* The logging produced below may be helpful\r
+ * while tuning +TCP: see how many buffers are in use. */\r
+ uxLastMinQueueSpace = uxCurrentCount;\r
+ FreeRTOS_printf( ( "Queue space: lowest %lu\n", uxCurrentCount ) );\r
+ }\r
+ }\r
+ #endif /* ipconfigCHECK_IP_QUEUE_SPACE */\r
+ }\r
+#endif /* ( ipconfigHAS_PRINTF != 0 ) */\r
+/*-----------------------------------------------------------*/\r
-/*\r
- * FreeRTOS+TCP V2.0.11\r
- * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy of\r
- * this software and associated documentation files (the "Software"), to deal in\r
- * the Software without restriction, including without limitation the rights to\r
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
- * the Software, and to permit persons to whom the Software is furnished to do so,\r
- * subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in all\r
- * copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
- * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
- * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
- *\r
- * http://aws.amazon.com/freertos\r
- * http://www.FreeRTOS.org\r
- */\r
-\r
/*\r
* Handling of Ethernet PHY's\r
* PHY's communicate with an EMAC either through\r
#endif\r
\r
/* A generic user-provided function that reads from the PHY-port at 'xAddress'( 0-based ). A 16-bit value shall be stored in\r
- '*pusValue'. xRegister is the register number ( 0 .. 31 ). In fact all PHY registers are 16-bit.\r
+ '*pulValue'. xRegister is the register number ( 0 .. 31 ). In fact all PHY registers are 16-bit.\r
Return non-zero in case the action failed. */\r
typedef BaseType_t ( *xApplicationPhyReadHook_t )( BaseType_t xAddress, BaseType_t xRegister, uint32_t *pulValue );\r
\r
-/* A generic user-provided function that writes 'usValue' to the\r
+/* A generic user-provided function that writes 'ulValue' to the\r
PHY-port at 'xAddress' ( 0-based ). xRegister is the register number ( 0 .. 31 ).\r
Return non-zero in case the action failed. */\r
typedef BaseType_t ( *xApplicationPhyWriteHook_t )( BaseType_t xAddress, BaseType_t xRegister, uint32_t ulValue );\r
/* Discover all PHY's connected by polling 32 indexes ( zero-based ) */\r
BaseType_t xPhyDiscover( EthernetPhy_t *pxPhyObject );\r
\r
-/* Send a reset commando to the connected PHY ports and send configuration. */\r
+/* Send a reset command to the connected PHY ports and send configuration. */\r
BaseType_t xPhyConfigure( EthernetPhy_t *pxPhyObject, const PhyProperties_t *pxPhyProperties );\r
\r
-/* Give a commando to start auto negotiation on a set of PHY port's. */\r
+/* Give a command to start auto negotiation on a set of PHY port's. */\r
BaseType_t xPhyStartAutoNegotiation( EthernetPhy_t *pxPhyObject, uint32_t ulPhyMask );\r
\r
/* Do not use auto negotiation but use predefined values from 'pxPhyObject->xPhyPreferences'. */\r
last call to this function. */\r
BaseType_t xPhyCheckLinkStatus( EthernetPhy_t *pxPhyObject, BaseType_t xHadReception );\r
\r
-static __inline uint32_t xPhyGetMask( EthernetPhy_t *pxPhyObject )\r
-{\r
- return ( ( ( uint32_t ) 1u ) << pxPhyObject-> xPortCount ) - 1;\r
-}\r
+/* Get the bitmask of a given 'EthernetPhy_t'. */\r
+#define xPhyGetMask( pxPhyObject ) \\r
+ ( ( ( ( uint32_t ) 1u ) << ( pxPhyObject )->xPortCount ) - 1u )\r
\r
#ifdef __cplusplus\r
} /* extern "C" */\r
--- /dev/null
+/*\r
+FreeRTOS+TCP V2.0.11\r
+Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r
+\r
+Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+this software and associated documentation files (the "Software"), to deal in\r
+the Software without restriction, including without limitation the rights to\r
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\r
+the Software, and to permit persons to whom the Software is furnished to do so,\r
+subject to the following conditions:\r
+\r
+The above copyright notice and this permission notice shall be included in all\r
+copies or substantial portions of the Software.\r
+\r
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+\r
+ http://aws.amazon.com/freertos\r
+ http://www.FreeRTOS.org\r
+*/\r
+\r
+/* FreeRTOS includes. */\r
+#include "FreeRTOS.h"\r
+#include "list.h"\r
+\r
+/* FreeRTOS+TCP includes. */\r
+#include "FreeRTOS_IP.h"\r
+/* FreeRTOS+TCP includes. */\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_Sockets.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+#include "FreeRTOS_DNS.h"\r
+#include "NetworkBufferManagement.h"\r
+#include "NetworkInterface.h"\r
+\r
+#include "wifi-decl.h"\r
+#include "wmerrno.h"\r
+#include "wifi.h"\r
+\r
+#include <wmlog.h>\r
+\r
+#define net_e(...) \\r
+ wmlog_e("freertos_tcp", ##__VA_ARGS__)\r
+#define net_w(...) \\r
+ wmlog_w("freertos_tcp", ##__VA_ARGS__)\r
+#define net_d(...) \\r
+ wmlog("freertos_tcp", ##__VA_ARGS__)\r
+\r
+#if 0 //this is lwip structure.\r
+#define MAX_INTERFACES_SUPPORTED 3\r
+static struct netif *netif_arr[MAX_INTERFACES_SUPPORTED];\r
+#endif\r
+\r
+/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet\r
+driver will filter incoming packets and only pass the stack those packets it\r
+considers need processing. */\r
+#if( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )\r
+#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer\r
+#else\r
+#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )\r
+#endif\r
+\r
+#define IP_ADDR_ANY ((ip_addr_t *)&ip_addr_any)\r
+#define IP_ADDR_BROADCAST ((ip_addr_t *)&ip_addr_broadcast)\r
+\r
+/** 255.255.255.255 */\r
+#define IPADDR_NONE ((u32_t)0xffffffffUL)\r
+/** 127.0.0.1 */\r
+#define IPADDR_LOOPBACK ((u32_t)0x7f000001UL)\r
+/** 0.0.0.0 */\r
+#define IPADDR_ANY ((u32_t)0x00000000UL)\r
+/** 255.255.255.255 */\r
+#define IPADDR_BROADCAST ((u32_t)0xffffffffUL)\r
+\r
+/** 255.255.255.255 */\r
+#define INADDR_NONE IPADDR_NONE\r
+/** 127.0.0.1 */\r
+#define INADDR_LOOPBACK IPADDR_LOOPBACK\r
+/** 0.0.0.0 */\r
+#define INADDR_ANY IPADDR_ANY\r
+/** 255.255.255.255 */\r
+#define INADDR_BROADCAST IPADDR_BROADCAST\r
+\r
+enum if_state_t {\r
+ INTERFACE_DOWN = 0,\r
+ INTERFACE_UP,\r
+};\r
+struct ip_addr {\r
+ u32_t addr;\r
+};\r
+\r
+#define MLAN_BSS_TYPE_STA 0\r
+\r
+extern uint8_t outbuf[2048];\r
+extern bool mlan_is_amsdu(const t_u8 *rcvdata);\r
+extern t_u8 *mlan_get_payload(const t_u8 *rcvdata, t_u16 *payload_len, int *interface);\r
+extern int wrapper_wlan_handle_amsdu_rx_packet(const t_u8 *rcvdata, const t_u16 datalen);\r
+extern int wrapper_wlan_handle_rx_packet(const t_u16 datalen, const t_u8 *rcvdata, NetworkBufferDescriptor_t *pxNetworkBuffer);\r
+static volatile uint32_t xInterfaceState = INTERFACE_DOWN;\r
+\r
+static int process_data_packet(const t_u8 *databuf, const t_u16 datalen)\r
+{\r
+ int interface = BSS_TYPE_STA;\r
+ t_u8 *payload = NULL;\r
+ t_u16 payload_len = 0;\r
+ const TickType_t xDescriptorWaitTime = pdMS_TO_TICKS( 250 );\r
+\r
+ NetworkBufferDescriptor_t *pxNetworkBuffer;\r
+ IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };\r
+\r
+ payload = (t_u8 *)mlan_get_payload(databuf, &payload_len, &interface);\r
+\r
+ if( eConsiderFrameForProcessing( payload ) != eProcessBuffer ) {\r
+ net_d("Dropping packet\r\n");\r
+ return WM_SUCCESS;\r
+ }\r
+\r
+ pxNetworkBuffer = pxGetNetworkBufferWithDescriptor(/*payload_len*/datalen, xDescriptorWaitTime);\r
+\r
+ if (pxNetworkBuffer != NULL) {\r
+ /* Set the packet size, in case a larger buffer was returned. */\r
+ pxNetworkBuffer->xDataLength = payload_len;\r
+\r
+ /* Copy the packet data. */\r
+ memcpy(pxNetworkBuffer->pucEthernetBuffer, payload, payload_len);\r
+\r
+ xRxEvent.pvData = (void *) pxNetworkBuffer;\r
+ if ( xSendEventStructToIPTask( &xRxEvent, xDescriptorWaitTime) == pdFAIL ) {\r
+ wmprintf("Failed to enqueue packet to network stack %p, len %d", payload, payload_len);\r
+ vReleaseNetworkBufferAndDescriptor(pxNetworkBuffer);\r
+ return WM_FAIL;\r
+ }\r
+ }\r
+ return WM_SUCCESS;\r
+}\r
+\r
+/* Callback function called from the wifi module */\r
+void handle_data_packet(const t_u8 interface, const t_u8 *rcvdata,\r
+ const t_u16 datalen)\r
+{\r
+ if (interface == BSS_TYPE_STA)\r
+ process_data_packet(rcvdata, datalen);\r
+}\r
+\r
+BaseType_t xNetworkInterfaceInitialise( void )\r
+{\r
+ uint8_t ret;\r
+ mac_addr_t mac_addr;\r
+\r
+ ret = wifi_get_device_mac_addr(&mac_addr);\r
+ if (ret != WM_SUCCESS) {\r
+ net_d("Failed to get mac address");\r
+ }\r
+\r
+ FreeRTOS_UpdateMACAddress(mac_addr.mac);\r
+\r
+ return ( xInterfaceState == INTERFACE_UP && ret == WM_SUCCESS ) ? pdTRUE : pdFALSE;\r
+}\r
+\r
+void vNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )\r
+{\r
+ /* FIX ME. */\r
+}\r
+\r
+BaseType_t xGetPhyLinkStatus( void )\r
+{\r
+ /* FIX ME. */\r
+ return pdFALSE;\r
+}\r
+void vNetworkNotifyIFDown()\r
+{\r
+ IPStackEvent_t xRxEvent = { eNetworkDownEvent, NULL };\r
+ xInterfaceState = INTERFACE_DOWN;\r
+ if( xSendEventStructToIPTask( &xRxEvent, 0 ) != pdPASS ) {\r
+ /* Could not send the message, so it is still pending. */\r
+ net_e("Could not send network down event");\r
+ }\r
+ else {\r
+ /* Message was sent so it is not pending. */\r
+ net_d("Sent network down event");\r
+ }\r
+}\r
+\r
+void vNetworkNotifyIFUp()\r
+{\r
+ xInterfaceState = INTERFACE_UP;\r
+}\r
+\r
+BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t *const pxNetworkBuffer, BaseType_t xReleaseAfterSend )\r
+{\r
+ uint8_t pkt_len;\r
+\r
+ if (pxNetworkBuffer == NULL ||\r
+ pxNetworkBuffer->pucEthernetBuffer == NULL ||\r
+ pxNetworkBuffer->xDataLength == 0) {\r
+ net_d("Incorrect params");\r
+ return pdFALSE;\r
+ }\r
+ memset(outbuf, 0x00, sizeof(outbuf));\r
+ pkt_len = 22 + 4; /* sizeof(TxPD) + INTF_HEADER_LEN */\r
+ memcpy((u8_t *) outbuf + pkt_len, (u8_t *) pxNetworkBuffer->pucEthernetBuffer,\r
+ pxNetworkBuffer->xDataLength);\r
+ int ret = wifi_low_level_output(BSS_TYPE_STA, outbuf + pkt_len, pxNetworkBuffer->xDataLength);\r
+ if (ret != WM_SUCCESS) {\r
+ net_e("Failed output %p, length %d, error %d \r\n", pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength, ret);\r
+ }\r
+\r
+ if (xReleaseAfterSend != pdFALSE) {\r
+ vReleaseNetworkBufferAndDescriptor(pxNetworkBuffer);\r
+ }\r
+\r
+ return ret == WM_SUCCESS ? pdTRUE : pdFALSE;\r
+}\r
--- /dev/null
+/*\r
+ * FreeRTOS+TCP Labs Build 160919 (C) 2016 Real Time Engineers ltd.\r
+ * Authors include Hein Tibosch and Richard Barry\r
+ *\r
+ *******************************************************************************\r
+ ***** NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ***\r
+ *** ***\r
+ *** ***\r
+ *** FREERTOS+TCP IS STILL IN THE LAB (mainly because the FTP and HTTP ***\r
+ *** demos have a dependency on FreeRTOS+FAT, which is only in the Labs ***\r
+ *** download): ***\r
+ *** ***\r
+ *** FreeRTOS+TCP is functional and has been used in commercial products ***\r
+ *** for some time. Be aware however that we are still refining its ***\r
+ *** design, the source code does not yet quite conform to the strict ***\r
+ *** coding and style standards mandated by Real Time Engineers ltd., and ***\r
+ *** the documentation and testing is not necessarily complete. ***\r
+ *** ***\r
+ *** PLEASE REPORT EXPERIENCES USING THE SUPPORT RESOURCES FOUND ON THE ***\r
+ *** URL: http://www.FreeRTOS.org/contact Active early adopters may, at ***\r
+ *** the sole discretion of Real Time Engineers Ltd., be offered versions ***\r
+ *** under a license other than that described below. ***\r
+ *** ***\r
+ *** ***\r
+ ***** NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ******* NOTE ***\r
+ *******************************************************************************\r
+ *\r
+ * FreeRTOS+TCP can be used under two different free open source licenses. The\r
+ * license that applies is dependent on the processor on which FreeRTOS+TCP is\r
+ * executed, as follows:\r
+ *\r
+ * If FreeRTOS+TCP is executed on one of the processors listed under the Special\r
+ * License Arrangements heading of the FreeRTOS+TCP license information web\r
+ * page, then it can be used under the terms of the FreeRTOS Open Source\r
+ * License. If FreeRTOS+TCP is used on any other processor, then it can be used\r
+ * under the terms of the GNU General Public License V2. Links to the relevant\r
+ * licenses follow:\r
+ *\r
+ * The FreeRTOS+TCP License Information Page: http://www.FreeRTOS.org/tcp_license\r
+ * The FreeRTOS Open Source License: http://www.FreeRTOS.org/license\r
+ * The GNU General Public License Version 2: http://www.FreeRTOS.org/gpl-2.0.txt\r
+ *\r
+ * FreeRTOS+TCP is distributed in the hope that it will be useful. You cannot\r
+ * use FreeRTOS+TCP unless you agree that you use the software 'as is'.\r
+ * FreeRTOS+TCP is provided WITHOUT ANY WARRANTY; without even the implied\r
+ * warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR\r
+ * PURPOSE. Real Time Engineers Ltd. disclaims all conditions and terms, be they\r
+ * implied, expressed, or statutory.\r
+ *\r
+ * 1 tab == 4 spaces!\r
+ *\r
+ * http://www.FreeRTOS.org\r
+ * http://www.FreeRTOS.org/plus\r
+ * http://www.FreeRTOS.org/labs\r
+ *\r
+ */\r
+\r
+/******************************************************************************\r
+*\r
+* See the following web page for essential buffer allocation scheme usage and\r
+* configuration details:\r
+* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Ethernet_Buffer_Management.html\r
+*\r
+******************************************************************************/\r
+\r
+/* THIS FILE SHOULD NOT BE USED IF THE PROJECT INCLUDES A MEMORY ALLOCATOR\r
+ * THAT WILL FRAGMENT THE HEAP MEMORY. For example, heap_2 must not be used,\r
+ * heap_4 can be used. */\r
+\r
+/* Standard includes. */\r
+#include <stdint.h>\r
+\r
+/* FreeRTOS includes. */\r
+#include "FreeRTOS.h"\r
+#include "task.h"\r
+#include "semphr.h"\r
+\r
+/* FreeRTOS+TCP includes. */\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_UDP_IP.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+#include "NetworkInterface.h"\r
+#include "NetworkBufferManagement.h"\r
+\r
+#include "tcpip/tcpip.h"\r
+#include "tcpip/src/tcpip_private.h"\r
+\r
+#include "NetworkConfig.h"\r
+\r
+/* The obtained network buffer must be large enough to hold a packet that might\r
+ * replace the packet that was requested to be sent. */\r
+#if ipconfigUSE_TCP == 1\r
+ #define baMINIMAL_BUFFER_SIZE sizeof( TCPPacket_t )\r
+#else\r
+ #define baMINIMAL_BUFFER_SIZE sizeof( ARPPacket_t )\r
+#endif /* ipconfigUSE_TCP == 1 */\r
+\r
+/*_RB_ This is too complex not to have an explanation. */\r
+#if defined( ipconfigETHERNET_MINIMUM_PACKET_BYTES )\r
+ #define ASSERT_CONCAT_( a, b ) a ## b\r
+ #define ASSERT_CONCAT( a, b ) ASSERT_CONCAT_( a, b )\r
+ #define STATIC_ASSERT( e ) \\r
+ ; enum { ASSERT_CONCAT( assert_line_, __LINE__ ) = 1 / ( !!( e ) ) }\r
+\r
+ STATIC_ASSERT( ipconfigETHERNET_MINIMUM_PACKET_BYTES <= baMINIMAL_BUFFER_SIZE );\r
+#endif\r
+\r
+/* A list of free (available) NetworkBufferDescriptor_t structures. */\r
+static List_t xFreeBuffersList;\r
+\r
+/* Some statistics about the use of buffers. */\r
+static size_t uxMinimumFreeNetworkBuffers;\r
+\r
+/* Declares the pool of NetworkBufferDescriptor_t structures that are available\r
+ * to the system. All the network buffers referenced from xFreeBuffersList exist\r
+ * in this array. The array is not accessed directly except during initialisation,\r
+ * when the xFreeBuffersList is filled (as all the buffers are free when the system\r
+ * is booted). */\r
+static NetworkBufferDescriptor_t xNetworkBufferDescriptors[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];\r
+\r
+/* This constant is defined as false to let FreeRTOS_TCP_IP.c know that the\r
+ * network buffers have a variable size: resizing may be necessary */\r
+const BaseType_t xBufferAllocFixedSize = pdFALSE;\r
+\r
+/* The semaphore used to obtain network buffers. */\r
+static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;\r
+\r
+/*-----------------------------------------------------------*/\r
+\r
+#ifdef PIC32_USE_ETHERNET\r
+\r
+ /* PIC32 specific stuff */\r
+ /* */\r
+\r
+ /* MAC packet acknowledgment, once MAC is done with it */\r
+ static bool PIC32_MacPacketAcknowledge( TCPIP_MAC_PACKET * pPkt,\r
+ const void * param );\r
+\r
+ /* allocates a MAC packet that holds a data buffer that can be used by both: */\r
+ /* - the FreeRTOSIP (NetworkBufferDescriptor_t->pucEthernetBuffer) */\r
+ /* - the Harmony MAC driver: TCPIP_MAC_PACKET->pDSeg->segLoad */\r
+ /* from the beginning of the buffer: */\r
+ /* - 4 bytes pointer to the network descriptor (FreeRTOS) */\r
+ /* - 4 bytes pointer to the MAC packet (pic32_NetworkInterface.c) */\r
+ /* - 2 bytes offset from the MAC packet (Harmony MAC driver: segLoadOffset) */\r
+ /* */\r
+ /* NOTE: segLoadLen should NOT include: */\r
+ /* - the TCPIP_MAC_FRAME_OFFSET (== ipBUFFER_PADDING which should be == 10!) */\r
+ /* - the sizeof(TCPIP_MAC_ETHERNET_HEADER) */\r
+ /* These are added by the MAC packet allocation! */\r
+ /* */\r
+ static uint8_t * PIC32_PktAlloc( uint16_t pktLen,\r
+ uint16_t segLoadLen,\r
+ TCPIP_MAC_PACKET_ACK_FUNC ackF,\r
+ TCPIP_MAC_PACKET ** pPtrPkt )\r
+ {\r
+ uint8_t * pBuff = 0;\r
+\r
+ /* allocate standard packet */\r
+ TCPIP_MAC_PACKET * pPkt = TCPIP_PKT_PacketAlloc( pktLen, segLoadLen, 0 );\r
+\r
+ /* set the MAC packet pointer in the packet */\r
+ if( pPkt != 0 )\r
+ {\r
+ pBuff = pPkt->pDSeg->segLoad;\r
+ TCPIP_MAC_PACKET ** ppkt = ( TCPIP_MAC_PACKET ** ) ( pBuff - PIC32_BUFFER_PKT_PTR_OSSET );\r
+ configASSERT( ( ( uint32_t ) ppkt & ( sizeof( uint32_t ) - 1 ) ) == 0 );\r
+ *ppkt = pPkt; /* store the packet it comes from */\r
+ pPkt->ackFunc = ackF;\r
+ pPkt->ackParam = 0;\r
+ }\r
+\r
+ if( pPtrPkt != 0 )\r
+ {\r
+ *pPtrPkt = pPkt;\r
+ }\r
+\r
+ return pBuff;\r
+ }\r
+\r
+\r
+\r
+ /* standard PIC32 MAC allocation function for a MAC packet */\r
+ /* this packet saves room for the FreeRTOS network descriptor */\r
+ /* at the beginning of the data buffer */\r
+ /* see NetworkBufferAllocate */\r
+ /* Note: flags parameter is ignored since that's used in the Harmony stack only */\r
+ TCPIP_MAC_PACKET * PIC32_MacPacketAllocate( uint16_t pktLen,\r
+ uint16_t segLoadLen,\r
+ TCPIP_MAC_PACKET_FLAGS flags )\r
+ {\r
+ TCPIP_MAC_PACKET * pPkt;\r
+\r
+ PIC32_PktAlloc( pktLen, segLoadLen, 0, &pPkt );\r
+\r
+ return pPkt;\r
+ }\r
+\r
+ /* standard PIC32 MAC packet acknowledgment */\r
+ /* function called once MAC is done with it */\r
+ static bool PIC32_MacPacketAcknowledge( TCPIP_MAC_PACKET * pPkt,\r
+ const void * param )\r
+ {\r
+ configASSERT( ( pPkt != 0 ) );\r
+\r
+ TCPIP_PKT_PacketFree( pPkt );\r
+\r
+ return false;\r
+ }\r
+\r
+ /* associates the current MAC packet with a network descriptor */\r
+ /* mainly for RX packet */\r
+ void PIC32_MacAssociate( TCPIP_MAC_PACKET * pRxPkt,\r
+ NetworkBufferDescriptor_t * pxBufferDescriptor,\r
+ size_t pktLength )\r
+ {\r
+ uint8_t * pPktBuff = pRxPkt->pDSeg->segLoad;\r
+\r
+ pxBufferDescriptor->pucEthernetBuffer = pPktBuff;\r
+ pxBufferDescriptor->xDataLength = pktLength;\r
+\r
+ /* make sure this is a properly allocated packet */\r
+ TCPIP_MAC_PACKET ** ppkt = ( TCPIP_MAC_PACKET ** ) ( pPktBuff - PIC32_BUFFER_PKT_PTR_OSSET );\r
+ configASSERT( ( ( uint32_t ) ppkt & ( sizeof( uint32_t ) - 1 ) ) == 0 );\r
+\r
+ if( *ppkt != pRxPkt )\r
+ {\r
+ configASSERT( false );\r
+ }\r
+\r
+ /* set the proper descriptor info */\r
+ NetworkBufferDescriptor_t ** ppDcpt = ( NetworkBufferDescriptor_t ** ) ( pPktBuff - ipBUFFER_PADDING );\r
+ configASSERT( ( ( uint32_t ) ppDcpt & ( sizeof( uint32_t ) - 1 ) ) == 0 );\r
+ *ppDcpt = pxBufferDescriptor;\r
+ }\r
+\r
+ /* debug functionality */\r
+ void PIC32_MacPacketOrphan( TCPIP_MAC_PACKET * pPkt )\r
+ {\r
+ TCPIP_PKT_PacketFree( pPkt );\r
+ configASSERT( false );\r
+ }\r
+\r
+ /* FreeRTOS allocation functions */\r
+\r
+ /* allocates a buffer that can be used by both: */\r
+ /* - the FreeRTOSIP (NetworkBufferDescriptor_t->pucEthernetBuffer) */\r
+ /* - the Harmony MAC driver: TCPIP_MAC_PACKET */\r
+ /* See PIC32_PktAlloc for details */\r
+ /* */\r
+ /* NOTE: reqLength should NOT include the ipBUFFER_PADDING (which should be == 10!) */\r
+ /* or the sizeof(TCPIP_MAC_ETHERNET_HEADER) */\r
+ /* These are added by the MAC packet allocation! */\r
+ /* */\r
+ uint8_t * NetworkBufferAllocate( size_t reqLength )\r
+ {\r
+ return PIC32_PktAlloc( sizeof( TCPIP_MAC_PACKET ), reqLength, PIC32_MacPacketAcknowledge, 0 );\r
+ }\r
+\r
+ /* deallocates a network buffer previously allocated */\r
+ /* with NetworkBufferAllocate */\r
+ void NetworkBufferFree( uint8_t * pNetworkBuffer )\r
+ {\r
+ if( pNetworkBuffer != 0 )\r
+ {\r
+ TCPIP_MAC_PACKET ** ppkt = ( TCPIP_MAC_PACKET ** ) ( pNetworkBuffer - PIC32_BUFFER_PKT_PTR_OSSET );\r
+ configASSERT( ( ( uint32_t ) ppkt & ( sizeof( uint32_t ) - 1 ) ) == 0 );\r
+ TCPIP_MAC_PACKET * pPkt = *ppkt;\r
+ configASSERT( ( pPkt != 0 ) );\r
+\r
+ if( pPkt->ackFunc != 0 )\r
+ {\r
+ ( *pPkt->ackFunc )( pPkt, pPkt->ackParam );\r
+ }\r
+ else\r
+ { /* ??? */\r
+ PIC32_MacPacketOrphan( pPkt );\r
+ }\r
+ }\r
+ }\r
+\r
+#endif /* #ifdef PIC32_USE_ETHERNET */\r
+\r
+/*-----------------------------------------------------------*/\r
+\r
+BaseType_t xNetworkBuffersInitialise( void )\r
+{\r
+ BaseType_t xReturn, x;\r
+\r
+ /* Only initialise the buffers and their associated kernel objects if they\r
+ * have not been initialised before. */\r
+ if( xNetworkBufferSemaphore == NULL )\r
+ {\r
+ xNetworkBufferSemaphore = xSemaphoreCreateCounting( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );\r
+ configASSERT( xNetworkBufferSemaphore );\r
+\r
+ if( xNetworkBufferSemaphore != NULL )\r
+ {\r
+ #if ( configQUEUE_REGISTRY_SIZE > 0 )\r
+ {\r
+ vQueueAddToRegistry( xNetworkBufferSemaphore, "NetBufSem" );\r
+ }\r
+ #endif /* configQUEUE_REGISTRY_SIZE */\r
+\r
+ /* If the trace recorder code is included name the semaphore for viewing\r
+ * in FreeRTOS+Trace. */\r
+ #if ( ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 )\r
+ {\r
+ extern QueueHandle_t xNetworkEventQueue;\r
+ vTraceSetQueueName( xNetworkEventQueue, "IPStackEvent" );\r
+ vTraceSetQueueName( xNetworkBufferSemaphore, "NetworkBufferCount" );\r
+ }\r
+ #endif /* ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 */\r
+\r
+ vListInitialise( &xFreeBuffersList );\r
+\r
+ /* Initialise all the network buffers. No storage is allocated to\r
+ * the buffers yet. */\r
+ for( x = 0; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )\r
+ {\r
+ /* Initialise and set the owner of the buffer list items. */\r
+ xNetworkBufferDescriptors[ x ].pucEthernetBuffer = NULL;\r
+ vListInitialiseItem( &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );\r
+ listSET_LIST_ITEM_OWNER( &( xNetworkBufferDescriptors[ x ].xBufferListItem ), &xNetworkBufferDescriptors[ x ] );\r
+\r
+ /* Currently, all buffers are available for use. */\r
+ vListInsert( &xFreeBuffersList, &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );\r
+ }\r
+\r
+ uxMinimumFreeNetworkBuffers = ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;\r
+ }\r
+ }\r
+\r
+ if( xNetworkBufferSemaphore == NULL )\r
+ {\r
+ xReturn = pdFAIL;\r
+ }\r
+ else\r
+ {\r
+ xReturn = pdPASS;\r
+ }\r
+\r
+ return xReturn;\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes )\r
+{\r
+ uint8_t * pucEthernetBuffer;\r
+ size_t xSize = *pxRequestedSizeBytes;\r
+\r
+ if( xSize < baMINIMAL_BUFFER_SIZE )\r
+ {\r
+ /* Buffers must be at least large enough to hold a TCP-packet with\r
+ * headers, or an ARP packet, in case TCP is not included. */\r
+ xSize = baMINIMAL_BUFFER_SIZE;\r
+ }\r
+\r
+ /* Round up xSize to the nearest multiple of N bytes,\r
+ * where N equals 'sizeof( size_t )'. */\r
+ if( ( xSize & ( sizeof( size_t ) - 1u ) ) != 0u )\r
+ {\r
+ xSize = ( xSize | ( sizeof( size_t ) - 1u ) ) + 1u;\r
+ }\r
+\r
+ *pxRequestedSizeBytes = xSize;\r
+\r
+ /* Allocate a buffer large enough to store the requested Ethernet frame size\r
+ * and a pointer to a network buffer structure (hence the addition of\r
+ * ipBUFFER_PADDING bytes). */\r
+\r
+ #ifdef PIC32_USE_ETHERNET\r
+ pucEthernetBuffer = NetworkBufferAllocate( xSize - sizeof( TCPIP_MAC_ETHERNET_HEADER ) );\r
+ #else\r
+ pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xSize + ipBUFFER_PADDING );\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+\r
+ configASSERT( pucEthernetBuffer );\r
+\r
+ if( pucEthernetBuffer != NULL )\r
+ {\r
+ /* Enough space is left at the start of the buffer to place a pointer to\r
+ * the network buffer structure that references this Ethernet buffer.\r
+ * Return a pointer to the start of the Ethernet buffer itself. */\r
+ #ifndef PIC32_USE_ETHERNET\r
+ pucEthernetBuffer += ipBUFFER_PADDING;\r
+ #endif /* #ifndef PIC32_USE_ETHERNET */\r
+ }\r
+\r
+ return pucEthernetBuffer;\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer )\r
+{\r
+ /* There is space before the Ethernet buffer in which a pointer to the\r
+ * network buffer that references this Ethernet buffer is stored. Remove the\r
+ * space before freeing the buffer. */\r
+ #ifdef PIC32_USE_ETHERNET\r
+ NetworkBufferFree( pucEthernetBuffer );\r
+ #else\r
+ if( pucEthernetBuffer != NULL )\r
+ {\r
+ pucEthernetBuffer -= ipBUFFER_PADDING;\r
+ vPortFree( ( void * ) pucEthernetBuffer );\r
+ }\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,\r
+ TickType_t xBlockTimeTicks )\r
+{\r
+ NetworkBufferDescriptor_t * pxReturn = NULL;\r
+ size_t uxCount;\r
+\r
+ if( ( xRequestedSizeBytes != 0u ) && ( xRequestedSizeBytes < ( size_t ) baMINIMAL_BUFFER_SIZE ) )\r
+ {\r
+ /* ARP packets can replace application packets, so the storage must be\r
+ * at least large enough to hold an ARP. */\r
+ xRequestedSizeBytes = baMINIMAL_BUFFER_SIZE;\r
+ }\r
+\r
+ #ifdef PIC32_USE_ETHERNET\r
+ if( xRequestedSizeBytes != 0u )\r
+ {\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+ xRequestedSizeBytes += 2u;\r
+\r
+ if( ( xRequestedSizeBytes & ( sizeof( size_t ) - 1u ) ) != 0u )\r
+ {\r
+ xRequestedSizeBytes = ( xRequestedSizeBytes | ( sizeof( size_t ) - 1u ) ) + 1u;\r
+ }\r
+ #ifdef PIC32_USE_ETHERNET\r
+ }\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+\r
+ /* If there is a semaphore available, there is a network buffer available. */\r
+ if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )\r
+ {\r
+ /* Protect the structure as it is accessed from tasks and interrupts. */\r
+ taskENTER_CRITICAL();\r
+ {\r
+ pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );\r
+ uxListRemove( &( pxReturn->xBufferListItem ) );\r
+ }\r
+ taskEXIT_CRITICAL();\r
+\r
+ /* Reading UBaseType_t, no critical section needed. */\r
+ uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );\r
+\r
+ if( uxMinimumFreeNetworkBuffers > uxCount )\r
+ {\r
+ uxMinimumFreeNetworkBuffers = uxCount;\r
+ }\r
+\r
+ /* Allocate storage of exactly the requested size to the buffer. */\r
+ configASSERT( pxReturn->pucEthernetBuffer == NULL );\r
+\r
+ if( xRequestedSizeBytes > 0 )\r
+ {\r
+ /* Extra space is obtained so a pointer to the network buffer can\r
+ * be stored at the beginning of the buffer. */\r
+\r
+ #ifdef PIC32_USE_ETHERNET\r
+ pxReturn->pucEthernetBuffer = NetworkBufferAllocate( xRequestedSizeBytes - sizeof( TCPIP_MAC_ETHERNET_HEADER ) );\r
+ #else\r
+ pxReturn->pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xRequestedSizeBytes + ipBUFFER_PADDING );\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+\r
+ if( pxReturn->pucEthernetBuffer == NULL )\r
+ {\r
+ /* The attempt to allocate storage for the buffer payload failed,\r
+ * so the network buffer structure cannot be used and must be\r
+ * released. */\r
+ vReleaseNetworkBufferAndDescriptor( pxReturn );\r
+ pxReturn = NULL;\r
+ }\r
+ else\r
+ {\r
+ /* Store a pointer to the network buffer structure in the\r
+ * buffer storage area, then move the buffer pointer on past the\r
+ * stored pointer so the pointer value is not overwritten by the\r
+ * application when the buffer is used. */\r
+ #ifdef PIC32_USE_ETHERNET\r
+ *( ( NetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer - ipBUFFER_PADDING ) ) = pxReturn;\r
+ #else\r
+ *( ( NetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer ) ) = pxReturn;\r
+ pxReturn->pucEthernetBuffer += ipBUFFER_PADDING;\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+\r
+ /* Store the actual size of the allocated buffer, which may be\r
+ * greater than the original requested size. */\r
+ pxReturn->xDataLength = xRequestedSizeBytes;\r
+\r
+ #if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )\r
+ {\r
+ /* make sure the buffer is not linked */\r
+ pxReturn->pxNextBuffer = NULL;\r
+ }\r
+ #endif /* ipconfigUSE_LINKED_RX_MESSAGES */\r
+ }\r
+ }\r
+ else\r
+ {\r
+ /* A descriptor is being returned without an associated buffer being\r
+ * allocated. */\r
+ }\r
+ }\r
+\r
+ if( pxReturn == NULL )\r
+ {\r
+ iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();\r
+ }\r
+ else\r
+ {\r
+ iptraceNETWORK_BUFFER_OBTAINED( pxReturn );\r
+ }\r
+\r
+ return pxReturn;\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )\r
+{\r
+ BaseType_t xListItemAlreadyInFreeList;\r
+\r
+ /* Ensure the buffer is returned to the list of free buffers before the\r
+ * counting semaphore is 'given' to say a buffer is available. Release the\r
+ * storage allocated to the buffer payload. THIS FILE SHOULD NOT BE USED\r
+ * IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP\r
+ * MEMORY. For example, heap_2 must not be used, heap_4 can be used. */\r
+ vReleaseNetworkBuffer( pxNetworkBuffer->pucEthernetBuffer );\r
+ pxNetworkBuffer->pucEthernetBuffer = NULL;\r
+\r
+ taskENTER_CRITICAL();\r
+ {\r
+ xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );\r
+\r
+ if( xListItemAlreadyInFreeList == pdFALSE )\r
+ {\r
+ vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );\r
+ }\r
+ }\r
+ taskEXIT_CRITICAL();\r
+\r
+ /*\r
+ * Update the network state machine, unless the program fails to release its 'xNetworkBufferSemaphore'.\r
+ * The program should only try to release its semaphore if 'xListItemAlreadyInFreeList' is false.\r
+ */\r
+ if( xListItemAlreadyInFreeList == pdFALSE )\r
+ {\r
+ if ( xSemaphoreGive( xNetworkBufferSemaphore ) == pdTRUE )\r
+ {\r
+ iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );\r
+ }\r
+ }\r
+ else\r
+ {\r
+ iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );\r
+ }\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+/*\r
+ * Returns the number of free network buffers\r
+ */\r
+UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )\r
+{\r
+ return listCURRENT_LIST_LENGTH( &xFreeBuffersList );\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+UBaseType_t uxGetMinimumFreeNetworkBuffers( void )\r
+{\r
+ return uxMinimumFreeNetworkBuffers;\r
+}\r
+/*-----------------------------------------------------------*/\r
+\r
+NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,\r
+ size_t xNewSizeBytes )\r
+{\r
+ size_t xOriginalLength;\r
+ uint8_t * pucBuffer;\r
+\r
+ #ifdef PIC32_USE_ETHERNET\r
+ xOriginalLength = pxNetworkBuffer->xDataLength;\r
+ #else\r
+ xOriginalLength = pxNetworkBuffer->xDataLength + ipBUFFER_PADDING;\r
+ xNewSizeBytes = xNewSizeBytes + ipBUFFER_PADDING;\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+ \r
+ pucBuffer = pucGetNetworkBuffer( &( xNewSizeBytes ) );\r
+\r
+ if( pucBuffer == NULL )\r
+ {\r
+ /* In case the allocation fails, return NULL. */\r
+ pxNetworkBuffer = NULL;\r
+ }\r
+ else\r
+ {\r
+ pxNetworkBuffer->xDataLength = xNewSizeBytes;\r
+ if( xNewSizeBytes > xOriginalLength )\r
+ {\r
+ xNewSizeBytes = xOriginalLength;\r
+ }\r
+\r
+ #ifdef PIC32_USE_ETHERNET\r
+ memcpy( pucBuffer, pxNetworkBuffer->pucEthernetBuffer, xNewSizeBytes );\r
+ *( ( NetworkBufferDescriptor_t ** ) ( pucBuffer - ipBUFFER_PADDING ) ) = pxNetworkBuffer;\r
+ #else\r
+ memcpy( pucBuffer - ipBUFFER_PADDING, pxNetworkBuffer->pucEthernetBuffer - ipBUFFER_PADDING, xNewSizeBytes );\r
+ #endif /* #ifdef PIC32_USE_ETHERNET */\r
+\r
+ vReleaseNetworkBuffer( pxNetworkBuffer->pucEthernetBuffer );\r
+ pxNetworkBuffer->pucEthernetBuffer = pucBuffer;\r
+ }\r
+\r
+ return pxNetworkBuffer;\r
+}\r
--- /dev/null
+/*******************************************************************************\r
+* Network Interface file\r
+*\r
+* Summary:\r
+* Network Interface file for FreeRTOS-Plus-TCP stack\r
+*\r
+* Description:\r
+* - Interfaces PIC32 to the FreeRTOS TCP/IP stack\r
+*******************************************************************************/\r
+\r
+/*******************************************************************************\r
+* File Name: pic32_NetworkInterface.c\r
+* Copyright 2017 Microchip Technology Incorporated and its subsidiaries.\r
+*\r
+* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+* this software and associated documentation files (the "Software"), to deal in\r
+* the Software without restriction, including without limitation the rights to\r
+* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r
+* of the Software, and to permit persons to whom the Software is furnished to do\r
+* so, subject to the following conditions:\r
+* The above copyright notice and this permission notice shall be included in all\r
+* copies or substantial portions of the Software.\r
+*\r
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
+* SOFTWARE\r
+*******************************************************************************/\r
+#include <sys/kmem.h>\r
+\r
+#include "FreeRTOS.h"\r
+#include "semphr.h"\r
+#include "event_groups.h"\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+\r
+#include "NetworkInterface.h"\r
+#include "NetworkBufferManagement.h"\r
+\r
+\r
+#include "NetworkInterface.h"\r
+#include "NetworkConfig.h"\r
+\r
+#include "peripheral/eth/plib_eth.h"\r
+\r
+#include "system_config.h"\r
+#include "system/console/sys_console.h"\r
+#include "system/debug/sys_debug.h"\r
+#include "system/command/sys_command.h"\r
+\r
+#include "driver/ethmac/drv_ethmac.h"\r
+#include "driver/miim/drv_miim.h"\r
+\r
+#include "tcpip/tcpip.h"\r
+#include "tcpip/src/tcpip_private.h"\r
+#include "tcpip/src/link_list.h"\r
+\r
+#ifdef PIC32_USE_ETHERNET\r
+\r
+ /* local definitions and data */\r
+\r
+ /* debug messages */\r
+ #if ( PIC32_MAC_DEBUG_MESSAGES != 0 )\r
+ #define PIC32_MAC_DbgPrint( format, ... ) SYS_CONSOLE_PRINT( format, ## __VA_ARGS__ )\r
+ #else\r
+ #define PIC32_MAC_DbgPrint( format, ... )\r
+ #endif /* (PIC32_MAC_DEBUG_MESSAGES != 0) */\r
+\r
+ typedef enum\r
+ {\r
+ PIC32_MAC_EVENT_INIT_NONE = 0x000, /* no event/invalid */\r
+\r
+ PIC32_MAC_EVENT_INIT_DONE = 0x001, /* initialization done event */\r
+ PIC32_MAC_EVENT_TIMEOUT = 0x002, /* periodic timeout event */\r
+ PIC32_MAC_EVENT_IF_PENDING = 0x004, /* an interface event signal: RX, TX, errors. etc. */\r
+ } PIC32_MAC_EVENT_TYPE;\r
+\r
+ typedef enum\r
+ {\r
+ eMACInit, /* Must initialise MAC. */\r
+ eMACPass, /* Initialisation was successful. */\r
+ eMACFailed, /* Initialisation failed. */\r
+ } eMAC_INIT_STATUS_TYPE;\r
+\r
+ static TCPIP_STACK_HEAP_HANDLE macHeapHandle;\r
+\r
+ static const TCPIP_MAC_OBJECT * macObject; /* the one and only MAC object; */\r
+\r
+ static SYS_MODULE_OBJ macObjHandle; /* the MAC object instance, obtained at initialization */\r
+ static TCPIP_MAC_HANDLE macCliHandle; /* client handle */\r
+ static volatile SYS_STATUS macObjStatus; /* current MAC status */\r
+\r
+ static TaskHandle_t macTaskHandle;\r
+\r
+ static TimerHandle_t macTmrHandle;\r
+\r
+ static bool macLinkStatus; /* true if link is ON */\r
+\r
+ static eMAC_INIT_STATUS_TYPE xMacInitStatus = eMACInit;\r
+\r
+ /* local prototypes */\r
+ static bool StartInitMac( void );\r
+ static void StartInitCleanup( void );\r
+\r
+ static void SetMacCtrl( TCPIP_MAC_MODULE_CTRL * pMacCtrl );\r
+\r
+ static bool MacSyncFunction( void * synchHandle,\r
+ TCPIP_MAC_SYNCH_REQUEST req );\r
+\r
+ /* the PIC32 MAC task function */\r
+ static void MacHandlerTask( void * params );\r
+\r
+ /* MAC interrupt event function */\r
+ static void MAC_EventFunction( TCPIP_MAC_EVENT event,\r
+ const void * eventParam );\r
+\r
+ /* timer callback for link maintenance, etc; */\r
+ static void MacTmrCallback( TimerHandle_t xTimer );\r
+\r
+ /* MAC RX packets functions */\r
+ static void MacRxPackets( void );\r
+ static void MacProcessRxPacket( TCPIP_MAC_PACKET * pRxPkt );\r
+\r
+\r
+ /* memory allocation mapping to FreeRTOS */\r
+ static void * _malloc( size_t nBytes )\r
+ {\r
+ return pvPortMalloc( nBytes );\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void * _calloc( size_t nElems,\r
+ size_t elemSize )\r
+ {\r
+ size_t nBytes = nElems * elemSize;\r
+\r
+ void * ptr = pvPortMalloc( nBytes );\r
+\r
+ if( ptr != 0 )\r
+ {\r
+ memset( ptr, 0, nBytes );\r
+ }\r
+\r
+ return ptr;\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void _free( void * pBuff )\r
+ {\r
+ vPortFree( pBuff );\r
+ }\r
+\r
+ /* extern references */\r
+ /* */\r
+ /* use the configuration data from the system_init.c */\r
+ extern const TCPIP_NETWORK_CONFIG TCPIP_HOSTS_CONFIGURATION[];\r
+\r
+ /* BufferAllocation_2.c:: packet allocation function */\r
+ extern TCPIP_MAC_PACKET * PIC32_MacPacketAllocate( uint16_t pktLen,\r
+ uint16_t segLoadLen,\r
+ TCPIP_MAC_PACKET_FLAGS flags );\r
+\r
+ extern void PIC32_MacAssociate( TCPIP_MAC_PACKET * pRxPkt,\r
+ NetworkBufferDescriptor_t * pxBufferDescriptor,\r
+ size_t pktLength );\r
+ extern void PIC32_MacPacketOrphan( TCPIP_MAC_PACKET * pPkt );\r
+\r
+ /* cannot use the system_init.c::tcpipHeapConfig because FreeRTOS does not have a calloc function! */\r
+ /* we build it here! */\r
+\r
+ /* make sure we're running with external heap! Redirect to FreeRTOS. */\r
+ #if !defined( TCPIP_STACK_USE_EXTERNAL_HEAP ) || defined( TCPIP_STACK_USE_INTERNAL_HEAP ) || defined( TCPIP_STACK_USE_INTERNAL_HEAP_POOL )\r
+ #error "TCPIP_STACK_USE_EXTERNAL_HEAP should be defined for this project!"\r
+ #endif\r
+\r
+ static const TCPIP_STACK_HEAP_EXTERNAL_CONFIG tcpipHeapConfig =\r
+ {\r
+ .heapType = TCPIP_STACK_HEAP_TYPE_EXTERNAL_HEAP,\r
+ .heapFlags = TCPIP_STACK_HEAP_FLAG_ALLOC_UNCACHED | TCPIP_STACK_HEAP_FLAG_NO_MTHREAD_SYNC,\r
+ .heapUsage = TCPIP_STACK_HEAP_USE_DEFAULT,\r
+ .malloc_fnc = _malloc,\r
+ .calloc_fnc = _calloc,\r
+ .free_fnc = _free,\r
+ };\r
+\r
+ #if ( PIC32_MAC_DEBUG_COMMANDS != 0 )\r
+ static int _Command_MacInfo( SYS_CMD_DEVICE_NODE * pCmdIO,\r
+ int argc,\r
+ char ** argv );\r
+ static int _Command_NetInfo( SYS_CMD_DEVICE_NODE * pCmdIO,\r
+ int argc,\r
+ char ** argv );\r
+ static int _Command_Version( SYS_CMD_DEVICE_NODE * pCmdIO,\r
+ int argc,\r
+ char ** argv );\r
+\r
+ static const SYS_CMD_DESCRIPTOR macCmdTbl[] =\r
+ {\r
+ { "macinfo", _Command_MacInfo, ": Check MAC statistics" },\r
+ { "netinfo", _Command_NetInfo, ": Net info" },\r
+ { "version", _Command_Version, ": Version info" },\r
+ };\r
+ #endif /* (PIC32_MAC_DEBUG_COMMANDS != 0) */\r
+\r
+\r
+ /* FreeRTOS implementation functions */\r
+ BaseType_t xNetworkInterfaceInitialise( void )\r
+ {\r
+ BaseType_t xResult;\r
+\r
+ if( xMacInitStatus == eMACInit )\r
+ {\r
+ /* This is the first time this function is called. */\r
+ if( StartInitMac() != false )\r
+ {\r
+ /* Indicate that the MAC initialisation succeeded. */\r
+ xMacInitStatus = eMACPass;\r
+ }\r
+ else\r
+ {\r
+ xMacInitStatus = eMACFailed;\r
+ }\r
+ }\r
+\r
+ if( xMacInitStatus == eMACPass )\r
+ {\r
+ xResult = xGetPhyLinkStatus();\r
+ }\r
+ else\r
+ {\r
+ xResult = pdFAIL;\r
+ }\r
+\r
+ PIC32_MAC_DbgPrint( "xNetworkInterfaceInitialise: %d %d\r\n", ( int ) xMacInitStatus, ( int ) xResult );\r
+\r
+ return xResult;\r
+ }\r
+\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxDescriptor,\r
+ BaseType_t xReleaseAfterSend )\r
+ {\r
+ TCPIP_MAC_RES macRes;\r
+ TCPIP_MAC_PACKET * pTxPkt;\r
+\r
+ BaseType_t retRes = pdFALSE;\r
+\r
+\r
+ if( ( pxDescriptor != 0 ) && ( pxDescriptor->pucEthernetBuffer != 0 ) && ( pxDescriptor->xDataLength != 0 ) )\r
+ {\r
+ TCPIP_MAC_PACKET ** ppkt = ( TCPIP_MAC_PACKET ** ) ( pxDescriptor->pucEthernetBuffer - PIC32_BUFFER_PKT_PTR_OSSET );\r
+ configASSERT( ( ( uint32_t ) ppkt & ( sizeof( uint32_t ) - 1 ) ) == 0 );\r
+ pTxPkt = *ppkt;\r
+ configASSERT( pTxPkt != 0 );\r
+\r
+ /* prepare the packet for transmission */\r
+ /* set the correct data length: */\r
+ configASSERT( pTxPkt->pDSeg->segSize >= pTxPkt->pDSeg->segLen );\r
+ pTxPkt->pDSeg->segLen = pxDescriptor->xDataLength;\r
+ pTxPkt->next = 0; /* unlink it */\r
+ macRes = ( macObject->TCPIP_MAC_PacketTx )( macCliHandle, pTxPkt );\r
+\r
+ if( macRes >= 0 )\r
+ {\r
+ retRes = pdTRUE;\r
+ pxDescriptor->pucEthernetBuffer = 0; /* it will be released by the MAC driver once it's transmitted */\r
+ iptraceNETWORK_INTERFACE_TRANSMIT();\r
+ }\r
+\r
+ /* else same error occurred; this normally should not happen! But the buffer is left in there so it shold be freed! */\r
+\r
+ /* The buffer has been sent so can be released. */\r
+ if( xReleaseAfterSend != pdFALSE )\r
+ {\r
+ vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
+ }\r
+ }\r
+\r
+ return retRes;\r
+ }\r
+\r
+\r
+ /************************************* Section: helper functions ************************************************** */\r
+ /* */\r
+\r
+ void PIC32_GetMACAddress( uint8_t macAdd[ 6 ] )\r
+ {\r
+ #if defined( __PIC32MZ__ ) || defined( __PIC32MX__ )\r
+ PLIB_ETH_MACGetAddress( ETH_ID_0, macAdd );\r
+ #else\r
+ #error "MAC Address: not supported architecture!"\r
+ #endif\r
+ }\r
+\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ const void * const PIC32_GetMacConfigData( void )\r
+ {\r
+ #if defined( __PIC32MZ__ ) || defined( __PIC32MX__ )\r
+ extern const TCPIP_MODULE_MAC_PIC32INT_CONFIG tcpipMACPIC32INTInitData;\r
+\r
+ return &tcpipMACPIC32INTInitData;\r
+ #else\r
+ #error "MAC Address: not supported architecture!"\r
+ #endif\r
+ }\r
+\r
+ /************************************* Section: worker code ************************************************** */\r
+ /* */\r
+\r
+\r
+ static bool StartInitMac( void )\r
+ {\r
+ TCPIP_MAC_MODULE_CTRL macCtrl;\r
+ SYS_MODULE_INIT moduleInit;\r
+ EventBits_t evBits;\r
+\r
+\r
+ /* perform some initialization of all variables so that we can cleanup what failed */\r
+ /* if something failed, the routine will be called again and again by FreeRTOS! */\r
+ macHeapHandle = 0;\r
+ macObjHandle = 0;\r
+ macCliHandle = 0;\r
+ macTmrHandle = 0;\r
+ macTaskHandle = 0;\r
+ macObject = TCPIP_HOSTS_CONFIGURATION[ 0 ].pMacObject; /* the MAC object we use */\r
+ macObjStatus = SYS_STATUS_UNINITIALIZED;\r
+ macLinkStatus = false;\r
+\r
+ int netUpFail = 0;\r
+\r
+ while( true )\r
+ {\r
+ /* start the allocator */\r
+ macHeapHandle = TCPIP_HEAP_Create( ( const TCPIP_STACK_HEAP_CONFIG * ) &tcpipHeapConfig, 0 );\r
+\r
+ if( macHeapHandle == 0 )\r
+ {\r
+ netUpFail = 1;\r
+ break;\r
+ }\r
+\r
+ if( TCPIP_PKT_Initialize( macHeapHandle, 0, 0 ) == false )\r
+ {\r
+ netUpFail = 2;\r
+ break;\r
+ }\r
+\r
+ moduleInit.sys.powerState = SYS_MODULE_POWER_RUN_FULL;\r
+\r
+ /* Initialize the MAC. MAC address is defined to 0x000000000000 in\r
+ * FreeRTOSConfig.h and therefore it will be initialized to the\r
+ * factory programmed MAC address. */\r
+ SetMacCtrl( &macCtrl );\r
+ /* Set the mac address in the FreeRTOS+TCP stack. */\r
+ FreeRTOS_UpdateMACAddress( macCtrl.ifPhyAddress.v );\r
+\r
+ TCPIP_MAC_INIT macInit =\r
+ {\r
+ .moduleInit = { moduleInit.value },\r
+ .macControl = &macCtrl,\r
+ .moduleData = PIC32_GetMacConfigData(),\r
+ };\r
+\r
+ macObjHandle = ( macObject->TCPIP_MAC_Initialize )( TCPIP_MODULE_MAC_PIC32INT, &macInit.moduleInit );\r
+\r
+ if( macObjHandle == SYS_MODULE_OBJ_INVALID )\r
+ {\r
+ macObjHandle = 0;\r
+ netUpFail = 4;\r
+ break;\r
+ }\r
+\r
+ /* open the MAC */\r
+ macCliHandle = ( macObject->TCPIP_MAC_Open )( TCPIP_MODULE_MAC_PIC32INT, DRV_IO_INTENT_READWRITE );\r
+\r
+ if( macCliHandle == DRV_HANDLE_INVALID )\r
+ {\r
+ macCliHandle = 0;\r
+ netUpFail = 5;\r
+ break;\r
+ }\r
+\r
+ if( !( macObject->TCPIP_MAC_EventMaskSet )( macCliHandle, ( TCPIP_MAC_EV_RX_DONE | TCPIP_MAC_EV_TX_DONE | TCPIP_MAC_EV_RXTX_ERRORS ), true ) )\r
+ {\r
+ netUpFail = 6;\r
+ break;\r
+ }\r
+\r
+ /* completed the MAC initialization */\r
+ /* continue the initialization */\r
+ macTmrHandle = xTimerCreate( PIC32_MAC_TIMER_NAME, PIC32_MAC_TIMER_PERIOD, pdTRUE, 0, MacTmrCallback );\r
+\r
+ if( ( macTmrHandle == 0 ) || ( xTimerStart( macTmrHandle, 0 ) != pdPASS ) )\r
+ {\r
+ netUpFail = 8;\r
+ break;\r
+ }\r
+\r
+ /* spawn the PIC32 MAC task function */\r
+ /* and wait for its event signal */\r
+ macObjStatus = SYS_STATUS_BUSY;\r
+\r
+ if( xTaskCreate( MacHandlerTask, PIC32_MAC_TASK_NAME, PIC32_MAC_TASK_STACK_SIZE, xTaskGetCurrentTaskHandle(), PIC32_MAC_TASK_PRI, &macTaskHandle ) != pdPASS )\r
+ { /* failed */\r
+ netUpFail = 9;\r
+ break;\r
+ }\r
+\r
+ xTaskNotifyWait( PIC32_MAC_EVENT_INIT_DONE, PIC32_MAC_EVENT_INIT_DONE, &evBits, PIC32_MAC_INIT_TIMEOUT );\r
+\r
+ if( ( evBits & PIC32_MAC_EVENT_INIT_DONE ) == 0 )\r
+ { /* timed out */\r
+ netUpFail = 10;\r
+ break;\r
+ }\r
+\r
+ if( macObjStatus != SYS_STATUS_READY )\r
+ { /* failed somehow ??? */\r
+ netUpFail = 11;\r
+ break;\r
+ }\r
+\r
+ netUpFail = 0;\r
+ break;\r
+ }\r
+\r
+ if( netUpFail == 0 )\r
+ {\r
+ PIC32_MAC_DbgPrint( " MAC Init success!\r\n" );\r
+\r
+ #if ( PIC32_MAC_DEBUG_COMMANDS != 0 )\r
+ /* create command group */\r
+ if( !SYS_CMD_ADDGRP( macCmdTbl, sizeof( macCmdTbl ) / sizeof( *macCmdTbl ), "mac", ": mac commands" ) )\r
+ {\r
+ PIC32_MAC_DbgPrint( "Failed to create MAC Commands\r\n" );\r
+ }\r
+ #endif /* (PIC32_MAC_DEBUG_COMMANDS != 0) */\r
+\r
+ return true;\r
+ }\r
+ else\r
+ {\r
+ StartInitCleanup();\r
+ PIC32_MAC_DbgPrint( "MAC Init failed: %d!\r\n", netUpFail );\r
+\r
+ return false;\r
+ }\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void StartInitCleanup( void )\r
+ {\r
+ if( macHeapHandle != 0 )\r
+ {\r
+ TCPIP_HEAP_Delete( macHeapHandle );\r
+ macHeapHandle = 0;\r
+ }\r
+\r
+ if( macObjHandle != 0 )\r
+ {\r
+ ( macObject->TCPIP_MAC_Deinitialize )( macObjHandle );\r
+ macObjHandle = 0;\r
+ }\r
+\r
+ if( macTmrHandle != 0 )\r
+ {\r
+ xTimerDelete( macTmrHandle, portMAX_DELAY );\r
+ macTmrHandle = 0;\r
+ }\r
+\r
+ if( macTaskHandle != 0 )\r
+ {\r
+ vTaskDelete( macTaskHandle );\r
+ macTaskHandle = 0;\r
+ }\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void SetMacCtrl( TCPIP_MAC_MODULE_CTRL * pMacCtrl )\r
+ {\r
+ TCPIP_MAC_ADDR macAdd;\r
+ uint8_t unsetMACAddr[ 6 ] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /* not set MAC address */\r
+\r
+ pMacCtrl->nIfs = 1;\r
+\r
+ pMacCtrl->mallocF = TCPIP_HEAP_MallocOutline;\r
+ pMacCtrl->callocF = TCPIP_HEAP_CallocOutline;\r
+ pMacCtrl->freeF = TCPIP_HEAP_FreeOutline;\r
+ pMacCtrl->memH = macHeapHandle;\r
+\r
+\r
+ pMacCtrl->pktAllocF = PIC32_MacPacketAllocate;\r
+ pMacCtrl->pktFreeF = ( TCPIP_MAC_PKT_FreeF ) _TCPIP_PKT_FREE_FNC;\r
+ pMacCtrl->pktAckF = ( TCPIP_MAC_PKT_AckF ) _TCPIP_PKT_ACK_FNC;\r
+\r
+ pMacCtrl->synchF = MacSyncFunction;\r
+\r
+ pMacCtrl->eventF = MAC_EventFunction;\r
+ pMacCtrl->eventParam = 0;\r
+\r
+ pMacCtrl->moduleId = TCPIP_MODULE_MAC_PIC32INT;\r
+ pMacCtrl->netIx = 0;\r
+ pMacCtrl->macAction = TCPIP_MAC_ACTION_INIT;\r
+ pMacCtrl->powerMode = TCPIP_MAC_POWER_FULL;\r
+\r
+ macAdd.v[ 0 ] = configMAC_ADDR0;\r
+ macAdd.v[ 1 ] = configMAC_ADDR1;\r
+ macAdd.v[ 2 ] = configMAC_ADDR2;\r
+ macAdd.v[ 3 ] = configMAC_ADDR3;\r
+ macAdd.v[ 4 ] = configMAC_ADDR4;\r
+ macAdd.v[ 5 ] = configMAC_ADDR5;\r
+\r
+ if( memcmp( macAdd.v, unsetMACAddr, sizeof( unsetMACAddr ) ) == 0 )\r
+ { /* if unspecified we use the factory pre-programmed address */\r
+ PIC32_GetMACAddress( pMacCtrl->ifPhyAddress.v );\r
+ }\r
+ else\r
+ { /* use the config suggested one */\r
+ memcpy( pMacCtrl->ifPhyAddress.v, macAdd.v, sizeof( macAdd ) );\r
+ }\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static bool MacSyncFunction( void * synchHandle,\r
+ TCPIP_MAC_SYNCH_REQUEST req )\r
+ {\r
+ switch( req )\r
+ {\r
+ case TCPIP_MAC_SYNCH_REQUEST_OBJ_CREATE:\r
+ vSemaphoreCreateBinary( *( SemaphoreHandle_t * ) synchHandle );\r
+\r
+ return ( *( SemaphoreHandle_t * ) synchHandle == NULL ) ? false : true;\r
+\r
+ case TCPIP_MAC_SYNCH_REQUEST_OBJ_DELETE:\r
+ vSemaphoreDelete( *( SemaphoreHandle_t * ) synchHandle );\r
+ *( SemaphoreHandle_t * ) synchHandle = NULL;\r
+\r
+ return true;\r
+\r
+ case TCPIP_MAC_SYNCH_REQUEST_OBJ_LOCK:\r
+\r
+ return ( xSemaphoreTake( *( SemaphoreHandle_t * ) synchHandle, portMAX_DELAY ) == pdTRUE ) ? true : false;\r
+\r
+ case TCPIP_MAC_SYNCH_REQUEST_OBJ_UNLOCK:\r
+\r
+ return ( xSemaphoreGive( *( SemaphoreHandle_t * ) synchHandle ) == pdTRUE ) ? true : false;\r
+\r
+ case TCPIP_MAC_SYNCH_REQUEST_CRIT_ENTER:\r
+ vTaskSuspendAll();\r
+\r
+ return true;\r
+\r
+ case TCPIP_MAC_SYNCH_REQUEST_CRIT_LEAVE:\r
+ xTaskResumeAll();\r
+\r
+ return true;\r
+\r
+ default:\r
+\r
+ return false;\r
+ }\r
+ }\r
+\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void MacHandlerTask( void * params )\r
+ {\r
+ EventBits_t evBits;\r
+\r
+ /* perform the MAC initialization */\r
+ while( macObjStatus == SYS_STATUS_BUSY )\r
+ {\r
+ /* process the underlying MAC module tasks */\r
+ ( macObject->TCPIP_MAC_Tasks )( macObjHandle );\r
+\r
+ SYS_STATUS macStatus = ( macObject->TCPIP_MAC_Status )( macObjHandle );\r
+\r
+ if( macStatus == SYS_STATUS_BUSY )\r
+ { /* still pending */\r
+ vTaskDelay( PIC32_MAC_TASK_INIT_PENDING_DELAY );\r
+ }\r
+ else\r
+ { /* completed ...somehow */\r
+ macObjStatus = macStatus;\r
+\r
+ xTaskNotify( ( TaskHandle_t ) params, PIC32_MAC_EVENT_INIT_DONE, eSetBits );\r
+\r
+ if( macStatus != SYS_STATUS_READY )\r
+ { /* failed miserably */\r
+ vTaskDelete( 0 );\r
+ }\r
+\r
+ /* done, up and running */\r
+ }\r
+ }\r
+\r
+ while( true )\r
+ {\r
+ xTaskNotifyWait( PIC32_MAC_EVENT_TIMEOUT | PIC32_MAC_EVENT_IF_PENDING, PIC32_MAC_EVENT_TIMEOUT | PIC32_MAC_EVENT_IF_PENDING, &evBits, portMAX_DELAY );\r
+\r
+ if( ( evBits & PIC32_MAC_EVENT_TIMEOUT ) != 0 )\r
+ { /* timeout occurred... */\r
+ ( macObject->TCPIP_MAC_Tasks )( macObjHandle );\r
+ bool linkCurr = ( macObject->TCPIP_MAC_LinkCheck )( macCliHandle ); /* check link status */\r
+\r
+ if( macLinkStatus != linkCurr )\r
+ { /* link status changed; some event could ve fired here if needed */\r
+ PIC32_MAC_DbgPrint( " MAC link: %s!\r\n", linkCurr ? "ON" : "OFF" );\r
+ macLinkStatus = linkCurr;\r
+ }\r
+ }\r
+\r
+ if( ( evBits & PIC32_MAC_EVENT_IF_PENDING ) != 0 )\r
+ { /* IF events signal */\r
+ TCPIP_MAC_EVENT activeEvents = ( macObject->TCPIP_MAC_EventPendingGet )( macCliHandle );\r
+\r
+ if( activeEvents != TCPIP_MAC_EV_NONE )\r
+ {\r
+ /* acknowledge the events */\r
+ ( macObject->TCPIP_MAC_EventAcknowledge )( macCliHandle, activeEvents );\r
+\r
+ /* check for RX */\r
+ if( ( activeEvents & ( TCPIP_MAC_EV_RX_DONE | TCPIP_MAC_EV_RX_OVFLOW | TCPIP_MAC_EV_RX_BUFNA ) ) != 0 )\r
+ { /* RX packets available */\r
+ MacRxPackets();\r
+ }\r
+\r
+ /* call the driver process function; */\r
+ /* PIC32 driver requests it through TCPIP_MAC_ParametersGet() which is bypassed here! */\r
+ ( macObject->TCPIP_MAC_Process )( macCliHandle );\r
+ }\r
+ }\r
+\r
+ /* do what you have to do and then wait for another event... */\r
+ }\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void MacTmrCallback( TimerHandle_t xTimer )\r
+ {\r
+ xTaskNotify( macTaskHandle, PIC32_MAC_EVENT_TIMEOUT, eSetBits );\r
+ }\r
+\r
+ /* MAC interrupt event function */\r
+ /* MAC signals an event, probably from within ISR */\r
+ /* we care just for RX related events */\r
+ static void MAC_EventFunction( TCPIP_MAC_EVENT event,\r
+ const void * eventParam )\r
+ {\r
+ BaseType_t xHigherPriorityTaskWoken;\r
+\r
+ if( ( event & ( TCPIP_MAC_EV_RX_DONE | TCPIP_MAC_EV_TX_DONE | TCPIP_MAC_EV_RXTX_ERRORS ) ) != 0 )\r
+ {\r
+ xHigherPriorityTaskWoken = pdFALSE;\r
+ xTaskNotifyFromISR( macTaskHandle, PIC32_MAC_EVENT_IF_PENDING, eSetBits, &xHigherPriorityTaskWoken );\r
+\r
+ if( xHigherPriorityTaskWoken )\r
+ {\r
+ portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );\r
+ }\r
+ }\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ BaseType_t xGetPhyLinkStatus( void )\r
+ {\r
+ return macLinkStatus == true ? pdPASS : pdFAIL;\r
+ }\r
+\r
+\r
+ /* receive packets from the MAC driver */\r
+ static void MacRxPackets( void )\r
+ {\r
+ TCPIP_MAC_PACKET * pRxPkt;\r
+\r
+ /* get all the new MAC packets */\r
+ while( ( pRxPkt = ( macObject->TCPIP_MAC_PacketRx )( macCliHandle, 0, 0 ) ) != 0 )\r
+ {\r
+ MacProcessRxPacket( pRxPkt );\r
+ }\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static void MacProcessRxPacket( TCPIP_MAC_PACKET * pRxPkt )\r
+ {\r
+ bool pktSuccess, pktLost;\r
+ size_t pktLength;\r
+ TCPIP_MAC_DATA_SEGMENT * pSeg;\r
+ uint8_t * pPktBuff;\r
+ NetworkBufferDescriptor_t * pxBufferDescriptor;\r
+ IPStackEvent_t xRxEvent;\r
+\r
+ pxBufferDescriptor = 0;\r
+ pktSuccess = pktLost = false;\r
+\r
+ while( true )\r
+ {\r
+ pktLength = 0;\r
+ int nSegs = 0;\r
+ pSeg = pRxPkt->pDSeg;\r
+ pPktBuff = pSeg->segLoad;\r
+\r
+ /* calculate the packet size */\r
+ do\r
+ {\r
+ pktLength += pSeg->segLen;\r
+ pSeg = pSeg->next;\r
+ nSegs++;\r
+ } while( pSeg != 0 );\r
+\r
+ if( nSegs > 1 )\r
+ { /* no support in FreeRTOS for multi segment packets! */\r
+ break;\r
+ }\r
+\r
+ /* sizeof(TCPIP_MAC_ETHERNET_HEADER) is subtracted by the driver */\r
+ /* but FreeRTOS needs the whole frame! */\r
+ pktLength += sizeof( TCPIP_MAC_ETHERNET_HEADER );\r
+\r
+ if( eConsiderFrameForProcessing( pPktBuff ) != eProcessBuffer )\r
+ {\r
+ break;\r
+ }\r
+\r
+ /* get the network descriptor (no data buffer) to hold this packet */\r
+ pxBufferDescriptor = pxGetNetworkBufferWithDescriptor( 0, 0 );\r
+\r
+ if( pxBufferDescriptor == 0 )\r
+ {\r
+ pktLost = true;\r
+ break;\r
+ }\r
+\r
+ PIC32_MacAssociate( pRxPkt, pxBufferDescriptor, pktLength );\r
+\r
+ xRxEvent.eEventType = eNetworkRxEvent;\r
+ xRxEvent.pvData = ( void * ) pxBufferDescriptor;\r
+\r
+ /* Send the data to the TCP/IP stack */\r
+ if( xSendEventStructToIPTask( &xRxEvent, 0 ) == pdFALSE )\r
+ { /* failed */\r
+ pktLost = true;\r
+ }\r
+ else\r
+ { /* success */\r
+ pktSuccess = true;\r
+ iptraceNETWORK_INTERFACE_RECEIVE();\r
+ }\r
+\r
+ break;\r
+ }\r
+\r
+ if( !pktSuccess )\r
+ { /* smth went wrong; nothing sent to the */\r
+ if( pxBufferDescriptor != 0 )\r
+ {\r
+ pxBufferDescriptor->pucEthernetBuffer = 0;\r
+ vReleaseNetworkBufferAndDescriptor( pxBufferDescriptor );\r
+ }\r
+\r
+ if( pktLost )\r
+ {\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ }\r
+\r
+ /* acknowledge the packet to the MAC driver */\r
+ if( pRxPkt->ackFunc )\r
+ {\r
+ ( *pRxPkt->ackFunc )( pRxPkt, pRxPkt->ackParam );\r
+ }\r
+ else\r
+ {\r
+ PIC32_MacPacketOrphan( pRxPkt );\r
+ }\r
+ }\r
+ }\r
+\r
+ #if ( PIC32_MAC_DEBUG_COMMANDS != 0 )\r
+ /* */\r
+ static int _Command_MacInfo( SYS_CMD_DEVICE_NODE * pCmdIO,\r
+ int argc,\r
+ char ** argv )\r
+ {\r
+ TCPIP_MAC_RES macRes;\r
+ TCPIP_MAC_RX_STATISTICS rxStatistics;\r
+ TCPIP_MAC_TX_STATISTICS txStatistics;\r
+ TCPIP_MAC_STATISTICS_REG_ENTRY regEntries[ 8 ];\r
+ TCPIP_MAC_STATISTICS_REG_ENTRY * pRegEntry;\r
+ int jx, hwEntries;\r
+ char entryName[ sizeof( pRegEntry->registerName ) + 1 ];\r
+\r
+ const void * cmdIoParam = pCmdIO->cmdIoParam;\r
+\r
+ if( argc != 1 )\r
+ {\r
+ ( *pCmdIO->pCmdApi->msg )( cmdIoParam, "Usage: macinfo \r\n" );\r
+ ( *pCmdIO->pCmdApi->msg )( cmdIoParam, "Ex: macinfo \r\n" );\r
+\r
+ return false;\r
+ }\r
+\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "Interface: %s driver statistics\r\n", macObject->macName );\r
+ macRes = ( macObject->TCPIP_MAC_StatisticsGet )( macCliHandle, &rxStatistics, &txStatistics );\r
+\r
+ if( macRes == TCPIP_MAC_RES_OK )\r
+ {\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "\tnRxOkPackets: %d, nRxPendBuffers: %d, nRxSchedBuffers: %d, ",\r
+ rxStatistics.nRxOkPackets, rxStatistics.nRxPendBuffers, rxStatistics.nRxSchedBuffers );\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "nRxErrorPackets: %d, nRxFragmentErrors: %d\r\n", rxStatistics.nRxErrorPackets, rxStatistics.nRxFragmentErrors );\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "\tnTxOkPackets: %d, nTxPendBuffers: %d, nTxErrorPackets: %d, nTxQueueFull: %d\r\n",\r
+ txStatistics.nTxOkPackets, txStatistics.nTxPendBuffers, txStatistics.nTxErrorPackets, txStatistics.nTxQueueFull );\r
+ }\r
+ else\r
+ {\r
+ ( *pCmdIO->pCmdApi->msg )( cmdIoParam, "\tnot supported\r\n" );\r
+ }\r
+\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "Interface: %s hardware statistics\r\n", macObject->macName );\r
+ macRes = ( macObject->TCPIP_MAC_RegisterStatisticsGet )( macCliHandle, regEntries, sizeof( regEntries ) / sizeof( *regEntries ), &hwEntries );\r
+\r
+ if( macRes == TCPIP_MAC_RES_OK )\r
+ {\r
+ entryName[ sizeof( entryName ) - 1 ] = 0;\r
+\r
+ for( jx = 0, pRegEntry = regEntries; jx < hwEntries && jx < sizeof( regEntries ) / sizeof( *regEntries ); jx++, pRegEntry++ )\r
+ {\r
+ strncpy( entryName, pRegEntry->registerName, sizeof( entryName ) - 1 );\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "\t%s: 0x%8x\r\n", entryName, pRegEntry->registerValue );\r
+ }\r
+ }\r
+ else\r
+ {\r
+ ( *pCmdIO->pCmdApi->msg )( cmdIoParam, "\tnot supported\r\n" );\r
+ }\r
+\r
+ return true;\r
+ }\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ static int _Command_NetInfo( SYS_CMD_DEVICE_NODE * pCmdIO,\r
+ int argc,\r
+ char ** argv )\r
+ {\r
+ const void * cmdIoParam = pCmdIO->cmdIoParam;\r
+\r
+ union\r
+ {\r
+ uint32_t ul;\r
+ uint8_t b[ 4 ];\r
+ }\r
+ sUl;\r
+\r
+ sUl.ul = FreeRTOS_GetIPAddress();\r
+\r
+ bool linkUp = FreeRTOS_IsNetworkUp() == pdTRUE;\r
+\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "IP address: %d.%d.%d.%d\r\n", sUl.b[ 0 ], sUl.b[ 1 ], sUl.b[ 2 ], sUl.b[ 3 ] );\r
+ ( *pCmdIO->pCmdApi->print )( cmdIoParam, "Link is: %s\r\n", linkUp ? "Up" : "Down" );\r
+\r
+ return true;\r
+ }\r
+\r
+#include "aws_application_version.h"\r
+\r
+static int _Command_Version(SYS_CMD_DEVICE_NODE* pCmdIO, int argc, char** argv)\r
+{\r
+ configPRINTF( ( "App version - maj: %d, min: %d, build: %d\r\n", xAppFirmwareVersion.u.x.ucMajor, xAppFirmwareVersion.u.x.ucMinor, xAppFirmwareVersion.u.x.usBuild) );\r
+ return 0;\r
+}\r
+\r
+ #endif /* (PIC32_MAC_DEBUG_COMMANDS != 0) */\r
+#endif /* #ifdef PIC32_USE_ETHERNET */\r
--- /dev/null
+/*******************************************************************************\r
+* Network Interface file\r
+*\r
+* Summary:\r
+* Network Interface file for FreeRTOS-Plus-TCP stack\r
+*\r
+* Description:\r
+* - Interfaces PIC32 to the FreeRTOS TCP/IP stack\r
+*******************************************************************************/\r
+\r
+/*******************************************************************************\r
+* File Name: pic32_NetworkInterface.c\r
+* Copyright 2017 Microchip Technology Incorporated and its subsidiaries.\r
+*\r
+* Permission is hereby granted, free of charge, to any person obtaining a copy of\r
+* this software and associated documentation files (the "Software"), to deal in\r
+* the Software without restriction, including without limitation the rights to\r
+* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r
+* of the Software, and to permit persons to whom the Software is furnished to do\r
+* so, subject to the following conditions:\r
+* The above copyright notice and this permission notice shall be included in all\r
+* copies or substantial portions of the Software.\r
+*\r
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
+* SOFTWARE\r
+*******************************************************************************/\r
+#ifndef PIC32_USE_ETHERNET\r
+#include <sys/kmem.h>\r
+\r
+#include "FreeRTOS.h"\r
+#include "semphr.h"\r
+#include "event_groups.h"\r
+#include "FreeRTOS_IP.h"\r
+#include "FreeRTOS_IP_Private.h"\r
+\r
+#include "NetworkInterface.h"\r
+#include "NetworkBufferManagement.h"\r
+#include "peripheral/eth/plib_eth.h"\r
+\r
+#include "system_config.h"\r
+#include "system/console/sys_console.h"\r
+#include "system/debug/sys_debug.h"\r
+#include "system/command/sys_command.h"\r
+\r
+#include "driver/ethmac/drv_ethmac.h"\r
+#include "driver/miim/drv_miim.h"\r
+#include "m2m_types.h"\r
+\r
+#include "tcpip/tcpip.h"\r
+#include "tcpip/src/tcpip_private.h"\r
+#include "tcpip/src/link_list.h"\r
+#include "wilc1000_task.h"\r
+\r
+#include "NetworkConfig.h"\r
+\r
+\r
+ #include "iot_wifi.h"\r
+\r
+ /* local definitions and data */\r
+\r
+\r
+ /* FreeRTOS implementation functions */\r
+ BaseType_t xNetworkInterfaceInitialise( void )\r
+ {\r
+ WIFINetworkParams_t xNetworkParams;\r
+\r
+ xNetworkParams.pcSSID = clientcredentialWIFI_SSID;\r
+ xNetworkParams.ucSSIDLength = sizeof( clientcredentialWIFI_SSID );\r
+ xNetworkParams.pcPassword = clientcredentialWIFI_PASSWORD;\r
+ xNetworkParams.ucPasswordLength = sizeof( clientcredentialWIFI_PASSWORD );\r
+ xNetworkParams.xSecurity = clientcredentialWIFI_SECURITY;\r
+ xNetworkParams.cChannel = M2M_WIFI_CH_ALL; /* Scan all channels (255) */\r
+\r
+ /*Turn WiFi ON */\r
+ if( WIFI_On() != eWiFiSuccess )\r
+ {\r
+ return pdFAIL;\r
+ }\r
+\r
+ /* Connect to the AP */\r
+ if( WIFI_ConnectAP( &xNetworkParams ) != eWiFiSuccess )\r
+ {\r
+ return pdFAIL;\r
+ }\r
+\r
+ return pdPASS;\r
+ }\r
+\r
+\r
+ /*-----------------------------------------------------------*/\r
+\r
+ BaseType_t xNetworkInterfaceOutput( NetworkBufferDescriptor_t * const pxDescriptor,\r
+ BaseType_t xReleaseAfterSend )\r
+ {\r
+ BaseType_t retRes = pdFALSE;\r
+\r
+ if( ( pxDescriptor != 0 ) && ( pxDescriptor->pucEthernetBuffer != 0 ) && ( pxDescriptor->xDataLength != 0 ) )\r
+ {\r
+ /* There you go */\r
+ if( WDRV_EXT_DataSend( pxDescriptor->xDataLength, pxDescriptor->pucEthernetBuffer ) == 0 )\r
+ {\r
+ retRes = pdTRUE;\r
+ }\r
+\r
+ /* The buffer has been sent so can be released. */\r
+ if( xReleaseAfterSend != pdFALSE )\r
+ {\r
+ vReleaseNetworkBufferAndDescriptor( pxDescriptor );\r
+ }\r
+ }\r
+\r
+ return retRes;\r
+ }\r
+\r
+\r
+ /************************************* Section: helper functions ************************************************** */\r
+ /* */\r
+\r
+\r
+\r
+ /************************************* Section: worker code ************************************************** */\r
+ /* */\r
+\r
+ void xNetworkFrameReceived( uint32_t len,\r
+ uint8_t const * const frame )\r
+ {\r
+ bool pktSuccess, pktLost;\r
+ NetworkBufferDescriptor_t * pxNetworkBuffer = NULL;\r
+ IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };\r
+\r
+ pktSuccess = pktLost = false;\r
+\r
+ while( true )\r
+ {\r
+ if( eConsiderFrameForProcessing( frame ) != eProcessBuffer )\r
+ {\r
+ break;\r
+ }\r
+\r
+ /* get the network descriptor (no data buffer) to hold this packet */\r
+ pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( len, 0 );\r
+\r
+ if( pxNetworkBuffer == NULL )\r
+ {\r
+ pktLost = true;\r
+ break;\r
+ }\r
+\r
+ /* Set the actual packet length, in case a larger buffer was \r
+ returned. */\r
+ pxNetworkBuffer->xDataLength = len;\r
+ \r
+ /* Copy the packet. */\r
+ memcpy( pxNetworkBuffer->pucEthernetBuffer, frame, len );\r
+\r
+ /* Send the data to the TCP/IP stack. */\r
+ xRxEvent.pvData = ( void * ) pxNetworkBuffer;\r
+\r
+ if( xSendEventStructToIPTask( &xRxEvent, 0 ) == pdFALSE )\r
+ { /* failed */\r
+ pktLost = true;\r
+ }\r
+ else\r
+ { /* success */\r
+ pktSuccess = true;\r
+ iptraceNETWORK_INTERFACE_RECEIVE();\r
+ }\r
+\r
+ break;\r
+ }\r
+\r
+ if( !pktSuccess )\r
+ { /* smth went wrong; nothing sent to the */\r
+ if( pxNetworkBuffer != NULL )\r
+ {\r
+ pxNetworkBuffer->pucEthernetBuffer = 0;\r
+ vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );\r
+ }\r
+\r
+ if( pktLost )\r
+ {\r
+ iptraceETHERNET_RX_EVENT_LOST();\r
+ }\r
+ }\r
+ }\r
+\r
+#endif /* #ifndef PIC32_USE_ETHERNET */\r