add initial Setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
niklasschoeningandClaude Opus 5.5 committed 2026-10-16 18:25:42 +02:00
commit bdb5db2009
1955 files changed
+1004711

No files matched your search

@@ -0,0 +1,453 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/******************************************************************************
*
* See the following web page for essential buffer allocation scheme usage and
* configuration details:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/05-Buffer-management
*
******************************************************************************/
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
/* For an Ethernet interrupt to be able to obtain a network buffer there must
* be at least this number of buffers available. */
#define baINTERRUPT_BUFFER_GET_THRESHOLD ( 3 )
/* A list of free (available) NetworkBufferDescriptor_t structures. */
static List_t xFreeBuffersList;
/* Some statistics about the use of buffers. */
static UBaseType_t uxMinimumFreeNetworkBuffers = 0U;
/* Declares the pool of NetworkBufferDescriptor_t structures that are available
* to the system. All the network buffers referenced from xFreeBuffersList exist
* in this array. The array is not accessed directly except during initialisation,
* when the xFreeBuffersList is filled (as all the buffers are free when the system
* is booted). */
static NetworkBufferDescriptor_t xNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];
/* This constant is defined as true to let FreeRTOS_TCP_IP.c know that the
* network buffers have constant size, large enough to hold the biggest Ethernet
* packet. No resizing will be done. */
const BaseType_t xBufferAllocFixedSize = pdTRUE;
static size_t uxMaxNetworkInterfaceAllocatedSizeBytes;
/* The semaphore used to obtain network buffers. */
static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;
#if ( ipconfigTCP_IP_SANITY != 0 )
static char cIsLow = pdFALSE;
UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc );
#else
static UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc );
#endif /* ipconfigTCP_IP_SANITY */
static void prvShowWarnings( void );
/* The user can define their own ipconfigBUFFER_ALLOC_LOCK() and
* ipconfigBUFFER_ALLOC_UNLOCK() macros, especially for use form an ISR. If these
* are not defined then default them to call the normal enter/exit critical
* section macros. */
#if !defined( ipconfigBUFFER_ALLOC_LOCK )
#define ipconfigBUFFER_ALLOC_INIT() do {} while( ipFALSE_BOOL )
#define ipconfigBUFFER_ALLOC_LOCK_FROM_ISR() \
UBaseType_t uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \
{
#define ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR() \
portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \
}
#define ipconfigBUFFER_ALLOC_LOCK() taskENTER_CRITICAL()
#define ipconfigBUFFER_ALLOC_UNLOCK() taskEXIT_CRITICAL()
#endif /* ipconfigBUFFER_ALLOC_LOCK */
/*-----------------------------------------------------------*/
#if ( ipconfigTCP_IP_SANITY != 0 )
/* HT: SANITY code will be removed as soon as the library is stable
* and and ready to become public
* Function below gives information about the use of buffers */
#define WARN_LOW ( 2 )
#define WARN_HIGH ( ( 5 * ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ) / 10 )
#endif /* ipconfigTCP_IP_SANITY */
/*-----------------------------------------------------------*/
#if ( ipconfigTCP_IP_SANITY != 0 )
BaseType_t prvIsFreeBuffer( const NetworkBufferDescriptor_t * pxDescr )
{
return ( bIsValidNetworkDescriptor( pxDescr ) != 0 ) &&
( listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxDescr->xBufferListItem ) ) != 0 );
}
/*-----------------------------------------------------------*/
static void prvShowWarnings( void )
{
UBaseType_t uxCount = uxGetNumberOfFreeNetworkBuffers();
if( ( ( cIsLow == 0 ) && ( uxCount <= WARN_LOW ) ) || ( ( cIsLow != 0 ) && ( uxCount >= WARN_HIGH ) ) )
{
cIsLow = !cIsLow;
FreeRTOS_debug_printf( ( "*** Warning *** %s %lu buffers left\n", cIsLow ? "only" : "now", uxCount ) );
}
}
/*-----------------------------------------------------------*/
UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc )
{
uint32_t offset = ( uint32_t ) ( ( ( const char * ) pxDesc ) - ( ( const char * ) xNetworkBuffers ) );
if( ( offset >= sizeof( xNetworkBuffers ) ) ||
( ( offset % sizeof( xNetworkBuffers[ 0 ] ) ) != 0 ) )
{
return pdFALSE;
}
return ( UBaseType_t ) ( pxDesc - xNetworkBuffers ) + 1;
}
/*-----------------------------------------------------------*/
#else /* if ( ipconfigTCP_IP_SANITY != 0 ) */
static UBaseType_t bIsValidNetworkDescriptor( const NetworkBufferDescriptor_t * pxDesc )
{
( void ) pxDesc;
return ( UBaseType_t ) pdTRUE;
}
/*-----------------------------------------------------------*/
static void prvShowWarnings( void )
{
}
/*-----------------------------------------------------------*/
#endif /* ipconfigTCP_IP_SANITY */
BaseType_t xNetworkBuffersInitialise( void )
{
BaseType_t xReturn;
uint32_t x;
/* Only initialise the buffers and their associated kernel objects if they
* have not been initialised before. */
if( xNetworkBufferSemaphore == NULL )
{
/* In case alternative locking is used, the mutexes can be initialised
* here */
ipconfigBUFFER_ALLOC_INIT();
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
{
static StaticSemaphore_t xNetworkBufferSemaphoreBuffer;
xNetworkBufferSemaphore = xSemaphoreCreateCountingStatic(
( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
&xNetworkBufferSemaphoreBuffer );
}
#else
{
xNetworkBufferSemaphore = xSemaphoreCreateCounting( ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );
}
#endif /* configSUPPORT_STATIC_ALLOCATION */
configASSERT( xNetworkBufferSemaphore != NULL );
if( xNetworkBufferSemaphore != NULL )
{
vListInitialise( &xFreeBuffersList );
/* Initialise all the network buffers. The buffer storage comes
* from the network interface, and different hardware has different
* requirements. */
uxMaxNetworkInterfaceAllocatedSizeBytes = uxNetworkInterfaceAllocateRAMToBuffers( xNetworkBuffers );
/* The allocated buffer should hold atleast ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER bytes */
configASSERT( ( uxMaxNetworkInterfaceAllocatedSizeBytes >= ( ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ) ) );
for( x = 0U; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )
{
/* Initialise and set the owner of the buffer list items. */
vListInitialiseItem( &( xNetworkBuffers[ x ].xBufferListItem ) );
listSET_LIST_ITEM_OWNER( &( xNetworkBuffers[ x ].xBufferListItem ), &xNetworkBuffers[ x ] );
/* Currently, all buffers are available for use. */
vListInsert( &xFreeBuffersList, &( xNetworkBuffers[ x ].xBufferListItem ) );
}
uxMinimumFreeNetworkBuffers = ( UBaseType_t ) ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;
}
}
if( xNetworkBufferSemaphore == NULL )
{
xReturn = pdFAIL;
}
else
{
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
TickType_t xBlockTimeTicks )
{
NetworkBufferDescriptor_t * pxReturn = NULL;
BaseType_t xInvalid = pdFALSE;
UBaseType_t uxCount;
if( ( xNetworkBufferSemaphore != NULL ) &&
( xRequestedSizeBytes <= uxMaxNetworkInterfaceAllocatedSizeBytes ) )
{
/* If there is a semaphore available, there is a network buffer
* available. */
if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )
{
/* Protect the structure as it is accessed from tasks and
* interrupts. */
ipconfigBUFFER_ALLOC_LOCK();
{
pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
if( ( bIsValidNetworkDescriptor( pxReturn ) != pdFALSE_UNSIGNED ) &&
listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxReturn->xBufferListItem ) ) )
{
( void ) uxListRemove( &( pxReturn->xBufferListItem ) );
}
else
{
xInvalid = pdTRUE;
}
}
ipconfigBUFFER_ALLOC_UNLOCK();
if( xInvalid == pdTRUE )
{
/* _RB_ Can printf() be called from an interrupt? (comment
* above says this can be called from an interrupt too) */
/* _HT_ The function shall not be called from an ISR. Comment
* was indeed misleading. Hopefully clear now?
* So the printf()is OK here. */
FreeRTOS_debug_printf( ( "pxGetNetworkBufferWithDescriptor: INVALID BUFFER: %p (valid %lu)\n",
pxReturn, bIsValidNetworkDescriptor( pxReturn ) ) );
pxReturn = NULL;
}
else
{
/* Reading UBaseType_t, no critical section needed. */
uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );
/* For stats, latch the lowest number of network buffers since
* booting. */
if( uxMinimumFreeNetworkBuffers > uxCount )
{
uxMinimumFreeNetworkBuffers = uxCount;
}
pxReturn->xDataLength = xRequestedSizeBytes;
pxReturn->pxInterface = NULL;
pxReturn->pxEndPoint = NULL;
#if ( ipconfigTCP_IP_SANITY != 0 )
{
prvShowWarnings();
}
#endif /* ipconfigTCP_IP_SANITY */
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
/* make sure the buffer is not linked */
pxReturn->pxNextBuffer = NULL;
}
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */
}
iptraceNETWORK_BUFFER_OBTAINED( pxReturn );
}
else
{
FreeRTOS_printf( ( "pxGetNetworkBufferWithDescriptor: module not initialised or `xRequestedSizeBytes` too small" ) );
/* lint wants to see at least a comment. */
iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();
}
}
return pxReturn;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxNetworkBufferGetFromISR( size_t xRequestedSizeBytes )
{
NetworkBufferDescriptor_t * pxReturn = NULL;
/* The current implementation only has a single size memory block, so
* the requested size parameter is not used (yet). */
( void ) xRequestedSizeBytes;
/* If there is a semaphore available then there is a buffer available, but,
* as this is called from an interrupt, only take a buffer if there are at
* least baINTERRUPT_BUFFER_GET_THRESHOLD buffers remaining. This prevents,
* to a certain degree at least, a rapidly executing interrupt exhausting
* buffer and in so doing preventing tasks from continuing. */
if( uxQueueMessagesWaitingFromISR( ( QueueHandle_t ) xNetworkBufferSemaphore ) > ( UBaseType_t ) baINTERRUPT_BUFFER_GET_THRESHOLD )
{
if( xSemaphoreTakeFromISR( xNetworkBufferSemaphore, NULL ) == pdPASS )
{
/* Protect the structure as it is accessed from tasks and interrupts. */
ipconfigBUFFER_ALLOC_LOCK_FROM_ISR();
{
pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
uxListRemove( &( pxReturn->xBufferListItem ) );
}
ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR();
iptraceNETWORK_BUFFER_OBTAINED_FROM_ISR( pxReturn );
}
}
if( pxReturn == NULL )
{
iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER_FROM_ISR();
}
return pxReturn;
}
/*-----------------------------------------------------------*/
BaseType_t vNetworkBufferReleaseFromISR( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
/* Ensure the buffer is returned to the list of free buffers before the
* counting semaphore is 'given' to say a buffer is available. */
ipconfigBUFFER_ALLOC_LOCK_FROM_ISR();
{
vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
}
ipconfigBUFFER_ALLOC_UNLOCK_FROM_ISR();
( void ) xSemaphoreGiveFromISR( xNetworkBufferSemaphore, &xHigherPriorityTaskWoken );
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
return xHigherPriorityTaskWoken;
}
/*-----------------------------------------------------------*/
void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
BaseType_t xListItemAlreadyInFreeList;
if( bIsValidNetworkDescriptor( pxNetworkBuffer ) == pdFALSE_UNSIGNED )
{
FreeRTOS_debug_printf( ( "vReleaseNetworkBufferAndDescriptor: Invalid buffer %p\n", pxNetworkBuffer ) );
}
else
{
/* Ensure the buffer is returned to the list of free buffers before the
* counting semaphore is 'given' to say a buffer is available. */
ipconfigBUFFER_ALLOC_LOCK();
{
{
xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
if( xListItemAlreadyInFreeList == pdFALSE )
{
vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
}
}
}
ipconfigBUFFER_ALLOC_UNLOCK();
if( xListItemAlreadyInFreeList )
{
FreeRTOS_debug_printf( ( "vReleaseNetworkBufferAndDescriptor: %p ALREADY RELEASED (now %lu)\n",
pxNetworkBuffer, uxGetNumberOfFreeNetworkBuffers() ) );
}
else
{
( void ) xSemaphoreGive( xNetworkBufferSemaphore );
prvShowWarnings();
}
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
UBaseType_t uxGetMinimumFreeNetworkBuffers( void )
{
return uxMinimumFreeNetworkBuffers;
}
/*-----------------------------------------------------------*/
UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )
{
return listCURRENT_LIST_LENGTH( &xFreeBuffersList );
}
NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t xNewSizeBytes )
{
if( xNewSizeBytes <= uxMaxNetworkInterfaceAllocatedSizeBytes )
{
/* In BufferAllocation_1.c all network buffer are allocated with a
* maximum size of 'ipTOTAL_ETHERNET_FRAME_SIZE'.No need to resize the
* network buffer. */
pxNetworkBuffer->xDataLength = xNewSizeBytes;
}
else
{
pxNetworkBuffer = NULL;
}
return pxNetworkBuffer;
}
/*#endif */ /* ipconfigINCLUDE_TEST_CODE */
@@ -0,0 +1,501 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/******************************************************************************
*
* See the following web page for essential buffer allocation scheme usage and
* configuration details:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/05-Buffer-management
*
******************************************************************************/
/* THIS FILE SHOULD NOT BE USED IF THE PROJECT INCLUDES A MEMORY ALLOCATOR
* THAT WILL FRAGMENT THE HEAP MEMORY. For example, heap_2 must not be used,
* heap_4 can be used. */
/* Standard includes. */
#include <stdint.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkInterface.h"
#include "NetworkBufferManagement.h"
/* The obtained network buffer must be large enough to hold a packet that might
* replace the packet that was requested to be sent. */
#if ipconfigUSE_TCP == 1
#define baMINIMAL_BUFFER_SIZE sizeof( TCPPacket_t )
#else
#define baMINIMAL_BUFFER_SIZE sizeof( ARPPacket_t )
#endif /* ipconfigUSE_TCP == 1 */
#define baALIGNMENT_BYTES ( sizeof( size_t ) )
#define baALIGNMENT_MASK ( baALIGNMENT_BYTES - 1U )
#define baADD_WILL_OVERFLOW( a, b ) ( ( a ) > ( SIZE_MAX - ( b ) ) )
STATIC_ASSERT( ipconfigETHERNET_MINIMUM_PACKET_BYTES <= baMINIMAL_BUFFER_SIZE );
/* A list of free (available) NetworkBufferDescriptor_t structures. */
static List_t xFreeBuffersList;
/* Some statistics about the use of buffers. */
static size_t uxMinimumFreeNetworkBuffers;
/* This constant is defined as false to let FreeRTOS_TCP_IP.c know that the
* network buffers have a variable size: resizing may be necessary */
const BaseType_t xBufferAllocFixedSize = pdFALSE;
/* The semaphore used to obtain network buffers. */
static SemaphoreHandle_t xNetworkBufferSemaphore = NULL;
/*-----------------------------------------------------------*/
BaseType_t xNetworkBuffersInitialise( void )
{
/* Declares the pool of NetworkBufferDescriptor_t structures that are available
* to the system. All the network buffers referenced from xFreeBuffersList exist
* in this array. The array is not accessed directly except during initialisation,
* when the xFreeBuffersList is filled (as all the buffers are free when the system
* is booted). */
static NetworkBufferDescriptor_t xNetworkBufferDescriptors[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ];
BaseType_t xReturn;
uint32_t x;
/* Only initialise the buffers and their associated kernel objects if they
* have not been initialised before. */
if( xNetworkBufferSemaphore == NULL )
{
#if ( configSUPPORT_STATIC_ALLOCATION == 1 )
{
static StaticSemaphore_t xNetworkBufferSemaphoreBuffer;
xNetworkBufferSemaphore = xSemaphoreCreateCountingStatic(
ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS,
&xNetworkBufferSemaphoreBuffer );
}
#else
{
xNetworkBufferSemaphore = xSemaphoreCreateCounting( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS, ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS );
}
#endif /* configSUPPORT_STATIC_ALLOCATION */
configASSERT( xNetworkBufferSemaphore != NULL );
if( xNetworkBufferSemaphore != NULL )
{
#if ( configQUEUE_REGISTRY_SIZE > 0 )
{
vQueueAddToRegistry( xNetworkBufferSemaphore, "NetBufSem" );
}
#endif /* configQUEUE_REGISTRY_SIZE */
/* If the trace recorder code is included name the semaphore for viewing
* in FreeRTOS+Trace. */
#if ( ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 )
{
extern QueueHandle_t xNetworkEventQueue;
vTraceSetQueueName( xNetworkEventQueue, "IPStackEvent" );
vTraceSetQueueName( xNetworkBufferSemaphore, "NetworkBufferCount" );
}
#endif /* ipconfigINCLUDE_EXAMPLE_FREERTOS_PLUS_TRACE_CALLS == 1 */
vListInitialise( &xFreeBuffersList );
/* Initialise all the network buffers. No storage is allocated to
* the buffers yet. */
for( x = 0U; x < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; x++ )
{
/* Initialise and set the owner of the buffer list items. */
xNetworkBufferDescriptors[ x ].pucEthernetBuffer = NULL;
vListInitialiseItem( &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
listSET_LIST_ITEM_OWNER( &( xNetworkBufferDescriptors[ x ].xBufferListItem ), &xNetworkBufferDescriptors[ x ] );
/* Currently, all buffers are available for use. */
vListInsert( &xFreeBuffersList, &( xNetworkBufferDescriptors[ x ].xBufferListItem ) );
}
uxMinimumFreeNetworkBuffers = ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS;
}
}
if( xNetworkBufferSemaphore == NULL )
{
xReturn = pdFAIL;
}
else
{
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/
uint8_t * pucGetNetworkBuffer( size_t * pxRequestedSizeBytes )
{
uint8_t * pucEthernetBuffer = NULL;
size_t uxMaxAllowedBytes = ( SIZE_MAX >> 1 );
size_t xSize = *pxRequestedSizeBytes;
size_t xBytesRequiredForAlignment, xAllocatedBytes;
BaseType_t xIntegerOverflowed = pdFALSE;
if( xSize < baMINIMAL_BUFFER_SIZE )
{
/* Buffers must be at least large enough to hold a TCP-packet with
* headers, or an ARP packet, in case TCP is not included. */
xSize = baMINIMAL_BUFFER_SIZE;
}
/* Round up xSize to the nearest multiple of N bytes,
* where N equals 'sizeof( size_t )'. */
if( ( xSize & baALIGNMENT_MASK ) != 0U )
{
xBytesRequiredForAlignment = baALIGNMENT_BYTES - ( xSize & baALIGNMENT_MASK );
if( baADD_WILL_OVERFLOW( xSize, xBytesRequiredForAlignment ) == ipFALSE_BOOL )
{
xSize += xBytesRequiredForAlignment;
}
else
{
xIntegerOverflowed = pdTRUE;
}
}
if( baADD_WILL_OVERFLOW( xSize, ipBUFFER_PADDING ) == ipFALSE_BOOL )
{
xAllocatedBytes = xSize + ipBUFFER_PADDING;
}
else
{
xIntegerOverflowed = pdTRUE;
}
if( ( xIntegerOverflowed == pdFALSE ) && ( xAllocatedBytes <= uxMaxAllowedBytes ) )
{
*pxRequestedSizeBytes = xSize;
/* Allocate a buffer large enough to store the requested Ethernet frame size
* and a pointer to a network buffer structure (hence the addition of
* ipBUFFER_PADDING bytes). */
pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xAllocatedBytes );
configASSERT( pucEthernetBuffer != NULL );
if( pucEthernetBuffer != NULL )
{
/* Enough space is left at the start of the buffer to place a pointer to
* the network buffer structure that references this Ethernet buffer.
* Return a pointer to the start of the Ethernet buffer itself. */
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pucEthernetBuffer += ipBUFFER_PADDING;
}
}
return pucEthernetBuffer;
}
/*-----------------------------------------------------------*/
void vReleaseNetworkBuffer( uint8_t * pucEthernetBuffer )
{
uint8_t * pucEthernetBufferCopy = pucEthernetBuffer;
/* There is space before the Ethernet buffer in which a pointer to the
* network buffer that references this Ethernet buffer is stored. Remove the
* space before freeing the buffer. */
if( pucEthernetBufferCopy != NULL )
{
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pucEthernetBufferCopy -= ipBUFFER_PADDING;
vPortFree( ( void * ) pucEthernetBufferCopy );
}
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxGetNetworkBufferWithDescriptor( size_t xRequestedSizeBytes,
TickType_t xBlockTimeTicks )
{
NetworkBufferDescriptor_t * pxReturn = NULL;
size_t uxCount;
size_t uxMaxAllowedBytes = ( SIZE_MAX >> 1 );
size_t xRequestedSizeBytesCopy = xRequestedSizeBytes;
size_t xBytesRequiredForAlignment, xAllocatedBytes;
BaseType_t xIntegerOverflowed = pdFALSE;
if( ( xRequestedSizeBytesCopy < ( size_t ) baMINIMAL_BUFFER_SIZE ) )
{
/* ARP packets can replace application packets, so the storage must be
* at least large enough to hold an ARP. */
xRequestedSizeBytesCopy = baMINIMAL_BUFFER_SIZE;
}
/* Add 2 bytes to xRequestedSizeBytesCopy and round up xRequestedSizeBytesCopy
* to the nearest multiple of N bytes, where N equals 'sizeof( size_t )'. */
if( baADD_WILL_OVERFLOW( xRequestedSizeBytesCopy, 2U ) == ipFALSE_BOOL )
{
xRequestedSizeBytesCopy += 2U;
}
else
{
xIntegerOverflowed = pdTRUE;
}
if( ( xRequestedSizeBytesCopy & baALIGNMENT_MASK ) != 0U )
{
xBytesRequiredForAlignment = baALIGNMENT_BYTES - ( xRequestedSizeBytesCopy & baALIGNMENT_MASK );
if( baADD_WILL_OVERFLOW( xRequestedSizeBytesCopy, xBytesRequiredForAlignment ) == ipFALSE_BOOL )
{
xRequestedSizeBytesCopy += xBytesRequiredForAlignment;
}
else
{
xIntegerOverflowed = pdTRUE;
}
}
if( baADD_WILL_OVERFLOW( xRequestedSizeBytesCopy, ipBUFFER_PADDING ) == ipFALSE_BOOL )
{
xAllocatedBytes = xRequestedSizeBytesCopy + ipBUFFER_PADDING;
}
else
{
xIntegerOverflowed = pdTRUE;
}
if( ( xIntegerOverflowed == pdFALSE ) && ( xAllocatedBytes <= uxMaxAllowedBytes ) && ( xNetworkBufferSemaphore != NULL ) )
{
/* If there is a semaphore available, there is a network buffer available. */
if( xSemaphoreTake( xNetworkBufferSemaphore, xBlockTimeTicks ) == pdPASS )
{
/* Protect the structure as it is accessed from tasks and interrupts. */
taskENTER_CRITICAL();
{
pxReturn = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &xFreeBuffersList );
( void ) uxListRemove( &( pxReturn->xBufferListItem ) );
}
taskEXIT_CRITICAL();
/* Reading UBaseType_t, no critical section needed. */
uxCount = listCURRENT_LIST_LENGTH( &xFreeBuffersList );
if( uxMinimumFreeNetworkBuffers > uxCount )
{
uxMinimumFreeNetworkBuffers = uxCount;
}
/* Allocate storage of exactly the requested size to the buffer. */
configASSERT( pxReturn->pucEthernetBuffer == NULL );
if( xRequestedSizeBytesCopy > 0U )
{
/* Extra space is obtained so a pointer to the network buffer can
* be stored at the beginning of the buffer. */
pxReturn->pucEthernetBuffer = ( uint8_t * ) pvPortMalloc( xAllocatedBytes );
if( pxReturn->pucEthernetBuffer == NULL )
{
/* The attempt to allocate storage for the buffer payload failed,
* so the network buffer structure cannot be used and must be
* released. */
vReleaseNetworkBufferAndDescriptor( pxReturn );
pxReturn = NULL;
}
else
{
/* Store a pointer to the network buffer structure in the
* buffer storage area, then move the buffer pointer on past the
* stored pointer so the pointer value is not overwritten by the
* application when the buffer is used. */
/* MISRA Ref 11.3.1 [Misaligned access] */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-113 */
/* coverity[misra_c_2012_rule_11_3_violation] */
*( ( NetworkBufferDescriptor_t ** ) ( pxReturn->pucEthernetBuffer ) ) = pxReturn;
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pxReturn->pucEthernetBuffer += ipBUFFER_PADDING;
/* Store the actual size of the allocated buffer, which may be
* greater than the original requested size. */
pxReturn->xDataLength = xRequestedSizeBytesCopy;
pxReturn->pxInterface = NULL;
pxReturn->pxEndPoint = NULL;
#if ( ipconfigUSE_LINKED_RX_MESSAGES != 0 )
{
/* make sure the buffer is not linked */
pxReturn->pxNextBuffer = NULL;
}
#endif /* ipconfigUSE_LINKED_RX_MESSAGES */
}
}
else
{
/* A descriptor is being returned without an associated buffer being
* allocated. */
}
}
}
if( pxReturn == NULL )
{
iptraceFAILED_TO_OBTAIN_NETWORK_BUFFER();
}
else
{
/* No action. */
iptraceNETWORK_BUFFER_OBTAINED( pxReturn );
}
return pxReturn;
}
/*-----------------------------------------------------------*/
void vReleaseNetworkBufferAndDescriptor( NetworkBufferDescriptor_t * const pxNetworkBuffer )
{
BaseType_t xListItemAlreadyInFreeList;
/* Ensure the buffer is returned to the list of free buffers before the
* counting semaphore is 'given' to say a buffer is available. Release the
* storage allocated to the buffer payload. THIS FILE SHOULD NOT BE USED
* IF THE PROJECT INCLUDES A MEMORY ALLOCATOR THAT WILL FRAGMENT THE HEAP
* MEMORY. For example, heap_2 must not be used, heap_4 can be used. */
vReleaseNetworkBuffer( pxNetworkBuffer->pucEthernetBuffer );
pxNetworkBuffer->pucEthernetBuffer = NULL;
pxNetworkBuffer->xDataLength = 0U;
taskENTER_CRITICAL();
{
xListItemAlreadyInFreeList = listIS_CONTAINED_WITHIN( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
if( xListItemAlreadyInFreeList == pdFALSE )
{
vListInsertEnd( &xFreeBuffersList, &( pxNetworkBuffer->xBufferListItem ) );
}
}
taskEXIT_CRITICAL();
/*
* Update the network state machine, unless the program fails to release its 'xNetworkBufferSemaphore'.
* The program should only try to release its semaphore if 'xListItemAlreadyInFreeList' is false.
*/
if( xListItemAlreadyInFreeList == pdFALSE )
{
if( xSemaphoreGive( xNetworkBufferSemaphore ) == pdTRUE )
{
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
}
}
else
{
/* No action. */
iptraceNETWORK_BUFFER_RELEASED( pxNetworkBuffer );
}
}
/*-----------------------------------------------------------*/
/*
* Returns the number of free network buffers
*/
UBaseType_t uxGetNumberOfFreeNetworkBuffers( void )
{
return listCURRENT_LIST_LENGTH( &xFreeBuffersList );
}
/*-----------------------------------------------------------*/
UBaseType_t uxGetMinimumFreeNetworkBuffers( void )
{
return uxMinimumFreeNetworkBuffers;
}
/*-----------------------------------------------------------*/
NetworkBufferDescriptor_t * pxResizeNetworkBufferWithDescriptor( NetworkBufferDescriptor_t * pxNetworkBuffer,
size_t xNewSizeBytes )
{
size_t xOriginalLength;
uint8_t * pucBuffer;
size_t uxSizeBytes = xNewSizeBytes;
NetworkBufferDescriptor_t * pxNetworkBufferCopy = pxNetworkBuffer;
xOriginalLength = pxNetworkBufferCopy->xDataLength + ipBUFFER_PADDING;
if( baADD_WILL_OVERFLOW( uxSizeBytes, ipBUFFER_PADDING ) == ipFALSE_BOOL )
{
uxSizeBytes = uxSizeBytes + ipBUFFER_PADDING;
pucBuffer = pucGetNetworkBuffer( &( uxSizeBytes ) );
if( pucBuffer == NULL )
{
/* In case the allocation fails, return NULL. */
pxNetworkBufferCopy = NULL;
}
else
{
pxNetworkBufferCopy->xDataLength = uxSizeBytes;
if( uxSizeBytes > xOriginalLength )
{
uxSizeBytes = xOriginalLength;
}
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
( void ) memcpy( pucBuffer - ipBUFFER_PADDING,
/* MISRA Ref 18.4.1 [Usage of +, -, += and -= operators on expression of pointer type]. */
/* More details at: https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/blob/main/MISRA.md#rule-184. */
/* coverity[misra_c_2012_rule_18_4_violation] */
pxNetworkBufferCopy->pucEthernetBuffer - ipBUFFER_PADDING,
uxSizeBytes );
vReleaseNetworkBuffer( pxNetworkBufferCopy->pucEthernetBuffer );
pxNetworkBufferCopy->pucEthernetBuffer = pucBuffer;
}
}
else
{
pxNetworkBufferCopy = NULL;
}
return pxNetworkBufferCopy;
}
@@ -0,0 +1,37 @@
add_library( freertos_plus_tcp_port STATIC )
target_sources( freertos_plus_tcp_port
PRIVATE
BufferManagement/BufferAllocation_${FREERTOS_PLUS_TCP_BUFFER_ALLOCATION}.c
# Note: There's NetworkInterface/pic32mzef that has it's own BufferAllocation_2.c
)
target_include_directories( freertos_plus_tcp_port
PUBLIC
# Using Cmake to detect except for unknown compilers.
$<$<STREQUAL:${FREERTOS_PLUS_TCP_COMPILER},CCS>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/CCS>
$<$<C_COMPILER_ID:CCS>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/CCS>
$<$<C_COMPILER_ID:GNU,Clang,ARMClang>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/GCC>
$<$<C_COMPILER_ID:Tasking>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/Tasking>
$<$<C_COMPILER_ID:IAR>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/IAR>
$<$<C_COMPILER_ID:ARMCC>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/Keil>
$<$<C_COMPILER_ID:MSVC>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/MSVC>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_COMPILER},Renesas>:${CMAKE_CURRENT_SOURCE_DIR}/Compiler/Renesas>
)
target_compile_options( freertos_plus_tcp_port
PRIVATE
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-cast-align>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-extra-semi-stmt>
$<$<COMPILE_LANG_AND_ID:C,GNU>:-Wno-pedantic> # Strange definition for STATIC_ASSERT
)
target_link_libraries( freertos_plus_tcp_port
PRIVATE
freertos_kernel
freertos_plus_tcp
freertos_plus_tcp_network_if
)
#------------------------------------------------------------------------------
add_subdirectory(NetworkInterface)
@@ -0,0 +1,34 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
__attribute__( ( packed ) );
@@ -0,0 +1,35 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
/* Nothing to do here. */
@@ -0,0 +1,36 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
;
#pragma pack( pop )
@@ -0,0 +1,35 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* https://freertos.org/Documentation/03-Libraries/02-FreeRTOS-plus/02-FreeRTOS-plus-TCP/10-Porting/02-Embedded_Compiler_Porting
*
*****************************************************************************/
#pragma pack( push, 1 )
@@ -0,0 +1,57 @@
add_library( freertos_plus_tcp_network_if_common STATIC )
target_sources( freertos_plus_tcp_network_if_common
PRIVATE
Common/phyHandling.c
include/phyHandling.h
)
target_include_directories( freertos_plus_tcp_network_if_common
PUBLIC
include
)
target_compile_options( freertos_plus_tcp_network_if_common
PRIVATE
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-conditional-uninitialized>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-implicit-int-conversion>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-padded>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-uninitialized>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-unused-but-set-variable>
$<$<COMPILE_LANG_AND_ID:C,Clang>:-Wno-unused-macros>
)
target_link_libraries( freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
#------------------------------------------------------------------------------
add_subdirectory(ATSAM4E)
add_subdirectory(ATSAME5x)
#add_subdirectory(board_family) - This is only an example.
add_subdirectory(DriverSAM)
add_subdirectory(esp32)
add_subdirectory(ksz8851snl)
add_subdirectory(libslirp)
add_subdirectory(linux)
add_subdirectory(loopback)
add_subdirectory(LPC17xx)
add_subdirectory(LPC18xx)
add_subdirectory(LPC54018)
add_subdirectory(M487)
add_subdirectory(MPS2_AN385)
add_subdirectory(MPS3_AN552)
add_subdirectory(MPS4_CS315)
add_subdirectory(NXP1060)
add_subdirectory(mw300_rd)
add_subdirectory(pic32mzef)
add_subdirectory(RX)
add_subdirectory(SH2A)
add_subdirectory(STM32)
add_subdirectory(ThirdParty/MSP432)
add_subdirectory(TM4C)
add_subdirectory(WinPCap)
add_subdirectory(xilinx_ultrascale)
add_subdirectory(Zynq)
@@ -0,0 +1,831 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @brief
* Handling of Ethernet PHY's
* PHY's communicate with an EMAC either through
* a Media-Independent Interface (MII), or a Reduced Media-Independent Interface (RMII).
* The EMAC can poll for PHY ports on 32 different addresses. Each of the PHY ports
* shall be treated independently.
*
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "phyHandling.h"
#define phyMIN_PHY_ADDRESS 0
#define phyMAX_PHY_ADDRESS 31
/* As the following 3 macro's are OK in most situations, and so they're not
* included in 'FreeRTOSIPConfigDefaults.h'.
* Users can change their values in the project's 'FreeRTOSIPConfig.h'. */
#ifndef phyPHY_MAX_RESET_TIME_MS
#define phyPHY_MAX_RESET_TIME_MS 1000U
#endif
#ifndef phyPHY_MAX_NEGOTIATE_TIME_MS
#define phyPHY_MAX_NEGOTIATE_TIME_MS 3000U
#endif
#ifndef phySHORT_DELAY_MS
#define phySHORT_DELAY_MS 50U
#endif
/* Naming and numbering of basic PHY registers. */
#define phyREG_00_BMCR 0x00U /* Basic Mode Control Register. */
#define phyREG_01_BMSR 0x01U /* Basic Mode Status Register. */
#define phyREG_02_PHYSID1 0x02U /* PHYS ID 1 */
#define phyREG_03_PHYSID2 0x03U /* PHYS ID 2 */
#define phyREG_04_ADVERTISE 0x04U /* Advertisement control reg */
/* Naming and numbering of extended PHY registers. */
#define PHYREG_10_PHYSTS 0x10U /* 16 PHY status register Offset */
#define phyREG_19_PHYCR 0x19U /* 25 RW PHY Control Register */
#define phyREG_1F_PHYSPCS 0x1FU /* 31 RW PHY Special Control Status */
/* Bit fields for 'phyREG_00_BMCR', the 'Basic Mode Control Register'. */
#define phyBMCR_FULL_DUPLEX 0x0100U /* Full duplex. */
#define phyBMCR_AN_RESTART 0x0200U /* Auto negotiation restart. */
#define phyBMCR_ISOLATE 0x0400U /* 1 = Isolates 0 = Normal operation. */
#define phyBMCR_AN_ENABLE 0x1000U /* Enable auto negotiation. */
#define phyBMCR_SPEED_100 0x2000U /* Select 100Mbps. */
#define phyBMCR_RESET 0x8000U /* Reset the PHY. */
/* Bit fields for 'phyREG_19_PHYCR', the 'PHY Control Register'. */
#define PHYCR_MDIX_EN 0x8000U /* Enable Auto MDIX. */
#define PHYCR_MDIX_FORCE 0x4000U /* Force MDIX crossed. */
#define phyBMSR_AN_COMPLETE 0x0020U /* Auto-Negotiation process completed */
#define phyBMSR_LINK_STATUS 0x0004U
#define phyPHYSTS_LINK_STATUS 0x0001U /* PHY Link mask */
#define phyPHYSTS_SPEED_STATUS 0x0002U /* PHY Speed mask */
#define phyPHYSTS_DUPLEX_STATUS 0x0004U /* PHY Duplex mask */
/* Bit fields for 'phyREG_1F_PHYSPCS
* 001 = 10BASE-T half-duplex
* 101 = 10BASE-T full-duplex
* 010 = 100BASE-TX half-duplex
* 110 = 100BASE-TX full-duplex
*/
#define phyPHYSPCS_SPEED_MASK 0x000CU
#define phyPHYSPCS_SPEED_10 0x0004U
#define phyPHYSPCS_FULL_DUPLEX 0x0010U
/*
* Description of all capabilities that can be advertised to
* the peer (usually a switch or router).
*/
#define phyADVERTISE_CSMA 0x0001U /* Supports IEEE 802.3u: Fast Ethernet at 100 Mbit/s */
#define phyADVERTISE_10HALF 0x0020U /* Try for 10mbps half-duplex. */
#define phyADVERTISE_10FULL 0x0040U /* Try for 10mbps full-duplex. */
#define phyADVERTISE_100HALF 0x0080U /* Try for 100mbps half-duplex. */
#define phyADVERTISE_100FULL 0x0100U /* Try for 100mbps full-duplex. */
#define phyADVERTISE_ALL \
( phyADVERTISE_10HALF | phyADVERTISE_10FULL | \
phyADVERTISE_100HALF | phyADVERTISE_100FULL | \
phyADVERTISE_CSMA )
/* Send a reset command to a set of PHY-ports. */
static uint32_t xPhyReset( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask );
static BaseType_t xHas_1F_PHYSPCS( uint32_t ulPhyID )
{
BaseType_t xResult = pdFALSE;
switch( ulPhyID )
{
case PHY_ID_LAN8720:
case PHY_ID_LAN8742A:
case PHY_ID_KSZ8041:
/*
* case PHY_ID_KSZ8051: // same ID as 8041
* case PHY_ID_KSZ8081: // same ID as 8041
*/
case PHY_ID_KSZ8081MNXIA:
case PHY_ID_KSZ8863:
default:
/* Most PHY's have a 1F_PHYSPCS */
xResult = pdTRUE;
break;
case PHY_ID_DP83848I:
case PHY_ID_DP83TC811S:
case PHY_ID_TM4C129X:
case PHY_ID_MV88E6071:
/* Has no 0x1F register "PHY Special Control Status". */
break;
}
return xResult;
}
/*-----------------------------------------------------------*/
static BaseType_t xHas_19_PHYCR( uint32_t ulPhyID )
{
BaseType_t xResult = pdFALSE;
switch( ulPhyID )
{
case PHY_ID_LAN8742A:
case PHY_ID_DP83848I:
case PHY_ID_TM4C129X:
xResult = pdTRUE;
break;
case PHY_ID_MV88E6071: /* Marvell 88E6071 */
default:
/* Most PHY's do not have a 19_PHYCR */
break;
}
return xResult;
}
/*-----------------------------------------------------------*/
/* Initialise the struct and assign a PHY-read and -write function. */
void vPhyInitialise( EthernetPhy_t * pxPhyObject,
xApplicationPhyReadHook_t fnPhyRead,
xApplicationPhyWriteHook_t fnPhyWrite )
{
memset( ( void * ) pxPhyObject, 0, sizeof( *pxPhyObject ) );
pxPhyObject->fnPhyRead = fnPhyRead;
pxPhyObject->fnPhyWrite = fnPhyWrite;
}
/*-----------------------------------------------------------*/
/* Discover all PHY's connected by polling 32 indexes ( zero-based ) */
BaseType_t xPhyDiscover( EthernetPhy_t * pxPhyObject )
{
BaseType_t xPhyAddress;
pxPhyObject->xPortCount = 0;
for( xPhyAddress = phyMIN_PHY_ADDRESS; xPhyAddress <= phyMAX_PHY_ADDRESS; xPhyAddress++ )
{
uint32_t ulLowerID = 0U;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_03_PHYSID2, &ulLowerID );
/* A valid PHY id can not be all zeros or all ones. */
if( ( ulLowerID != ( uint16_t ) ~0U ) && ( ulLowerID != ( uint16_t ) 0U ) )
{
uint32_t ulUpperID;
uint32_t ulPhyID;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_02_PHYSID1, &ulUpperID );
ulPhyID = ( ( ( uint32_t ) ulUpperID ) << 16 ) | ( ulLowerID & 0xFFF0U );
pxPhyObject->ucPhyIndexes[ pxPhyObject->xPortCount ] = ( uint8_t ) xPhyAddress;
pxPhyObject->ulPhyIDs[ pxPhyObject->xPortCount ] = ulPhyID;
pxPhyObject->xPortCount++;
/* See if there is more storage space. */
if( pxPhyObject->xPortCount == ipconfigPHY_MAX_PORTS )
{
break;
}
}
}
if( pxPhyObject->xPortCount > 0 )
{
FreeRTOS_printf( ( "PHY ID %X\n", ( unsigned int ) pxPhyObject->ulPhyIDs[ 0 ] ) );
}
return pxPhyObject->xPortCount;
}
/*-----------------------------------------------------------*/
/* Send a reset command to a set of PHY-ports. */
static uint32_t xPhyReset( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask )
{
uint32_t ulDoneMask, ulConfig;
TickType_t xRemainingTime;
TimeOut_t xTimer;
BaseType_t xPhyIndex;
/* A bit-mask of PHY ports that are ready. */
ulDoneMask = 0U;
/* Set the RESET bits high. */
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* Read Control register. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig | phyBMCR_RESET );
}
xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( phyPHY_MAX_RESET_TIME_MS );
vTaskSetTimeOutState( &xTimer );
/* The reset should last less than a second. */
for( ; ; )
{
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
if( ( ulConfig & phyBMCR_RESET ) == 0 )
{
FreeRTOS_printf( ( "xPhyReset: phyBMCR_RESET %d ready\n", ( int ) xPhyIndex ) );
ulDoneMask |= ( 1U << xPhyIndex );
}
}
if( ulDoneMask == ulPhyMask )
{
break;
}
if( xTaskCheckForTimeOut( &xTimer, &xRemainingTime ) != pdFALSE )
{
FreeRTOS_printf( ( "xPhyReset: phyBMCR_RESET timed out ( done 0x%02X )\n", ( unsigned int ) ulDoneMask ) );
break;
}
/* Block for a while */
vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );
}
/* Clear the reset bits. */
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
if( ( ulDoneMask & ( 1U << xPhyIndex ) ) == 0U )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* The reset operation timed out, clear the bit manually. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulConfig & ~phyBMCR_RESET );
}
}
vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );
return ulDoneMask;
}
/*-----------------------------------------------------------*/
BaseType_t xPhyConfigure( EthernetPhy_t * pxPhyObject,
const PhyProperties_t * pxPhyProperties )
{
uint32_t ulConfig, ulAdvertise;
BaseType_t xPhyIndex;
if( pxPhyObject->xPortCount < 1 )
{
FreeRTOS_printf( ( "xPhyConfigure: No PHY's detected.\n" ) );
return -1;
}
/* The expected ID for the 'LAN8742A' is 0x0007c130. */
/* The expected ID for the 'LAN8720' is 0x0007c0f0. */
/* The expected ID for the 'DP83848I' is 0x20005C90. */
/* Set advertise register. */
if( ( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_AUTO ) && ( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_AUTO ) )
{
ulAdvertise = phyADVERTISE_ALL;
/* Reset auto-negotiation capability. */
}
else
{
/* Always select protocol 802.3u. */
ulAdvertise = phyADVERTISE_CSMA;
if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_AUTO )
{
if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL )
{
ulAdvertise |= phyADVERTISE_10FULL | phyADVERTISE_100FULL;
}
else
{
ulAdvertise |= phyADVERTISE_10HALF | phyADVERTISE_100HALF;
}
}
else if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_AUTO )
{
if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_10 )
{
ulAdvertise |= phyADVERTISE_10FULL | phyADVERTISE_10HALF;
}
else
{
ulAdvertise |= phyADVERTISE_100FULL | phyADVERTISE_100HALF;
}
}
else if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_100 )
{
if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL )
{
ulAdvertise |= phyADVERTISE_100FULL;
}
else
{
ulAdvertise |= phyADVERTISE_100HALF;
}
}
else
{
if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL )
{
ulAdvertise |= phyADVERTISE_10FULL;
}
else
{
ulAdvertise |= phyADVERTISE_10HALF;
}
}
}
/* Send a reset command to a set of PHY-ports. */
xPhyReset( pxPhyObject, xPhyGetMask( pxPhyObject ) );
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++ )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
uint32_t ulPhyID = pxPhyObject->ulPhyIDs[ xPhyIndex ];
/* Write advertise register. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_04_ADVERTISE, ulAdvertise );
/*
* AN_EN AN1 AN0 Forced Mode
* 0 0 0 10BASE-T, Half-Duplex
* 0 0 1 10BASE-T, Full-Duplex
* 0 1 0 100BASE-TX, Half-Duplex
* 0 1 1 100BASE-TX, Full-Duplex
* AN_EN AN1 AN0 Advertised Mode
* 1 0 0 10BASE-T, Half/Full-Duplex
* 1 0 1 100BASE-TX, Half/Full-Duplex
* 1 1 0 10BASE-T Half-Duplex
* 100BASE-TX, Half-Duplex
* 1 1 1 10BASE-T, Half/Full-Duplex
* 100BASE-TX, Half/Full-Duplex
*/
/* Read Control register. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_00_BMCR, &ulConfig );
ulConfig &= ~( phyBMCR_SPEED_100 | phyBMCR_FULL_DUPLEX );
ulConfig |= phyBMCR_AN_ENABLE;
if( ( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_100 ) || ( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_AUTO ) )
{
ulConfig |= phyBMCR_SPEED_100;
}
else if( pxPhyProperties->ucSpeed == ( uint8_t ) PHY_SPEED_10 )
{
ulConfig &= ~phyBMCR_SPEED_100;
}
if( ( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_FULL ) || ( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_AUTO ) )
{
ulConfig |= phyBMCR_FULL_DUPLEX;
}
else if( pxPhyProperties->ucDuplex == ( uint8_t ) PHY_DUPLEX_HALF )
{
ulConfig &= ~phyBMCR_FULL_DUPLEX;
}
if( xHas_19_PHYCR( ulPhyID ) )
{
uint32_t ulPhyControl;
/* Read PHY Control register. */
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_19_PHYCR, &ulPhyControl );
/* Clear bits which might get set: */
ulPhyControl &= ~( PHYCR_MDIX_EN | PHYCR_MDIX_FORCE );
if( pxPhyProperties->ucMDI_X == PHY_MDIX_AUTO )
{
ulPhyControl |= PHYCR_MDIX_EN;
}
else if( pxPhyProperties->ucMDI_X == PHY_MDIX_CROSSED )
{
/* Force direct link = Use crossed RJ45 cable. */
ulPhyControl &= ~PHYCR_MDIX_FORCE;
}
else
{
/* Force crossed link = Use direct RJ45 cable. */
ulPhyControl |= PHYCR_MDIX_FORCE;
}
/* update PHY Control Register. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_19_PHYCR, ulPhyControl );
}
FreeRTOS_printf( ( "+TCP: advertise: %04X config %04X\n", ( unsigned int ) ulAdvertise, ( unsigned int ) ulConfig ) );
}
/* Keep these values for later use. */
pxPhyObject->ulBCRValue = ulConfig & ~phyBMCR_ISOLATE;
pxPhyObject->ulACRValue = ulAdvertise;
return 0;
}
/*-----------------------------------------------------------*/
/* xPhyFixedValue(): this function is called in case auto-negotiation is disabled.
* The caller has set the values in 'xPhyPreferences' (ucDuplex and ucSpeed).
* The PHY register phyREG_00_BMCR will be set for every connected PHY that matches
* with ulPhyMask. */
BaseType_t xPhyFixedValue( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask )
{
BaseType_t xPhyIndex;
uint32_t ulValue, ulBitMask = ( uint32_t ) 1U;
ulValue = ( uint32_t ) 0U;
if( pxPhyObject->xPhyPreferences.ucDuplex == PHY_DUPLEX_FULL )
{
ulValue |= phyBMCR_FULL_DUPLEX;
}
if( pxPhyObject->xPhyPreferences.ucSpeed == PHY_SPEED_100 )
{
ulValue |= phyBMCR_SPEED_100;
}
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
if( ( ulPhyMask & ulBitMask ) != 0lu )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* Enable Auto-Negotiation. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, ulValue );
}
}
return 0;
}
/*-----------------------------------------------------------*/
/* xPhyStartAutoNegotiation() is the alternative xPhyFixedValue():
* It sets the BMCR_AN_RESTART bit and waits for the auto-negotiation completion
* ( phyBMSR_AN_COMPLETE ). */
BaseType_t xPhyStartAutoNegotiation( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask )
{
uint32_t xPhyIndex, ulDoneMask, ulBitMask;
uint32_t ulRegValue;
TickType_t xRemainingTime;
TimeOut_t xTimer;
if( ulPhyMask == ( uint32_t ) 0U )
{
return 0;
}
for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++ )
{
if( ( ulPhyMask & ( 1lu << xPhyIndex ) ) != 0lu )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
/* Enable Auto-Negotiation. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_04_ADVERTISE, pxPhyObject->ulACRValue );
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, pxPhyObject->ulBCRValue | phyBMCR_AN_RESTART );
}
}
xRemainingTime = ( TickType_t ) pdMS_TO_TICKS( phyPHY_MAX_NEGOTIATE_TIME_MS );
vTaskSetTimeOutState( &xTimer );
ulDoneMask = 0;
/* Wait until the auto-negotiation will be completed */
for( ; ; )
{
ulBitMask = ( uint32_t ) 1U;
for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
if( ( ulPhyMask & ulBitMask ) != 0lu )
{
if( ( ulDoneMask & ulBitMask ) == 0lu )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulRegValue );
if( ( ulRegValue & phyBMSR_AN_COMPLETE ) != 0 )
{
ulDoneMask |= ulBitMask;
}
}
}
}
if( ulPhyMask == ulDoneMask )
{
break;
}
if( xTaskCheckForTimeOut( &xTimer, &xRemainingTime ) != pdFALSE )
{
FreeRTOS_printf( ( "xPhyStartAutoNegotiation: phyBMSR_AN_COMPLETE timed out ( done 0x%02X )\n", ( unsigned int ) ulDoneMask ) );
break;
}
vTaskDelay( pdMS_TO_TICKS( phySHORT_DELAY_MS ) );
}
if( ulDoneMask != ( uint32_t ) 0U )
{
ulBitMask = ( uint32_t ) 1U;
pxPhyObject->ulLinkStatusMask &= ~( ulDoneMask );
for( xPhyIndex = 0; xPhyIndex < ( uint32_t ) pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
uint32_t ulPhyID = pxPhyObject->ulPhyIDs[ xPhyIndex ];
if( ( ulDoneMask & ulBitMask ) == ( uint32_t ) 0U )
{
continue;
}
/* Clear the 'phyBMCR_AN_RESTART' bit. */
pxPhyObject->fnPhyWrite( xPhyAddress, phyREG_00_BMCR, pxPhyObject->ulBCRValue );
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulRegValue );
if( ( ulRegValue & phyBMSR_LINK_STATUS ) != 0U )
{
pxPhyObject->ulLinkStatusMask |= ulBitMask;
}
if( ulPhyID == PHY_ID_KSZ8081MNXIA )
{
uint32_t ulControlStatus;
pxPhyObject->fnPhyRead( xPhyAddress, 0x1E, &ulControlStatus );
switch( ulControlStatus & 0x07 )
{
case 0x01:
case 0x05:
/* [001] = 10BASE-T half-duplex */
/* [101] = 10BASE-T full-duplex */
/* 10 Mbps. */
ulRegValue |= phyPHYSTS_SPEED_STATUS;
break;
case 0x02:
case 0x06:
/* [010] = 100BASE-TX half-duplex */
/* [110] = 100BASE-TX full-duplex */
break;
}
switch( ulControlStatus & 0x07 )
{
case 0x05:
case 0x06:
/* [101] = 10BASE-T full-duplex */
/* [110] = 100BASE-TX full-duplex */
/* Full duplex. */
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
break;
case 0x01:
case 0x02:
/* [001] = 10BASE-T half-duplex */
/* [010] = 100BASE-TX half-duplex */
break;
}
}
else if( ulPhyID == PHY_ID_KSZ8795 )
{
/* KSZ8795 has a different mapping for the Port Operation Mode Indication field
* in the phyREG_1F_PHYSPCS than other similar PHYs:
* 010 = 10BASE-T half-duplex
* 101 = 10BASE-T full-duplex
* 011 = 100BASE-TX half-duplex
* 110 = 100BASE-TX full-duplex
*/
uint32_t ulControlStatus = 0u;
uint32_t ulPortOperationMode = 0u;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_1F_PHYSPCS, &ulControlStatus );
ulPortOperationMode = ( ulControlStatus >> 8u ) & 0x07u;
ulRegValue = 0;
/* Detect 10baseT operation */
if( ( 0x02u == ulPortOperationMode ) || ( 0x05u == ulPortOperationMode ) )
{
ulRegValue |= phyPHYSTS_SPEED_STATUS;
}
/* Detect full duplex operation */
if( ( 0x05u == ulPortOperationMode ) || ( 0x06u == ulPortOperationMode ) )
{
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
}
}
else if( ulPhyID == PHY_ID_ADIN1200 )
{
/* ADIN1200 get the resolved speed information from register 0x1A (PHY_STATUS_1)
*/
uint32_t ulControlStatus = 0u;
uint32_t ulPortOperationMode = 0u;
pxPhyObject->fnPhyRead( xPhyAddress, 0x1A, &ulControlStatus );
/* Bits 7-9 indicate the speed and duplex. */
ulPortOperationMode = ( ulControlStatus >> 7u ) & 0x07u;
ulRegValue = 0;
/* Detect 10Mb operation */
if( ( ulPortOperationMode & 0x2 ) == 0 )
{
/* phyPHYSTS_SPEED_STATUS: 1=10Mb, 0=100Mb */
ulRegValue |= phyPHYSTS_SPEED_STATUS;
}
/* Detect full duplex operation */
if( ulPortOperationMode & 0x1 )
{
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
}
}
else if( xHas_1F_PHYSPCS( ulPhyID ) )
{
/* 31 RW PHY Special Control Status */
uint32_t ulControlStatus;
pxPhyObject->fnPhyRead( xPhyAddress, phyREG_1F_PHYSPCS, &ulControlStatus );
ulRegValue = 0;
if( ( ulControlStatus & phyPHYSPCS_FULL_DUPLEX ) != 0 )
{
ulRegValue |= phyPHYSTS_DUPLEX_STATUS;
}
if( ( ulControlStatus & phyPHYSPCS_SPEED_MASK ) == phyPHYSPCS_SPEED_10 )
{
ulRegValue |= phyPHYSTS_SPEED_STATUS;
}
}
else
{
/* Read the result of the auto-negotiation. */
pxPhyObject->fnPhyRead( xPhyAddress, PHYREG_10_PHYSTS, &ulRegValue );
}
FreeRTOS_printf( ( "Autonego ready: %08x: %s duplex %u mbit %s status\n",
( unsigned int ) ulRegValue,
( ulRegValue & phyPHYSTS_DUPLEX_STATUS ) ? "full" : "half",
( ulRegValue & phyPHYSTS_SPEED_STATUS ) ? 10 : 100,
( ( pxPhyObject->ulLinkStatusMask & ulBitMask ) != 0U ) ? "high" : "low" ) );
if( ( ulRegValue & phyPHYSTS_DUPLEX_STATUS ) != ( uint32_t ) 0U )
{
pxPhyObject->xPhyProperties.ucDuplex = PHY_DUPLEX_FULL;
}
else
{
pxPhyObject->xPhyProperties.ucDuplex = PHY_DUPLEX_HALF;
}
if( ( ulRegValue & phyPHYSTS_SPEED_STATUS ) != 0 )
{
pxPhyObject->xPhyProperties.ucSpeed = PHY_SPEED_10;
}
else
{
pxPhyObject->xPhyProperties.ucSpeed = PHY_SPEED_100;
}
}
} /* if( ulDoneMask != ( uint32_t) 0U ) */
return 0;
}
/*-----------------------------------------------------------*/
BaseType_t xPhyCheckLinkStatus( EthernetPhy_t * pxPhyObject,
BaseType_t xHadReception )
{
uint32_t ulStatus, ulBitMask = 1U;
BaseType_t xPhyIndex;
BaseType_t xNeedCheck = pdFALSE;
if( xHadReception > 0 )
{
/* A packet was received. No need to check for the PHY status now,
* but set a timer to check it later on. */
vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
if( ( pxPhyObject->ulLinkStatusMask & ulBitMask ) == 0UL )
{
pxPhyObject->ulLinkStatusMask |= ulBitMask;
FreeRTOS_printf( ( "xPhyCheckLinkStatus: PHY LS now %02X\n", ( unsigned int ) pxPhyObject->ulLinkStatusMask ) );
xNeedCheck = pdTRUE;
}
}
}
else if( xTaskCheckForTimeOut( &( pxPhyObject->xLinkStatusTimer ), &( pxPhyObject->xLinkStatusRemaining ) ) != pdFALSE )
{
/* Frequent checking the PHY Link Status can affect for the performance of Ethernet controller.
* As long as packets are received, no polling is needed.
* Otherwise, polling will be done when the 'xLinkStatusTimer' expires. */
for( xPhyIndex = 0; xPhyIndex < pxPhyObject->xPortCount; xPhyIndex++, ulBitMask <<= 1 )
{
BaseType_t xPhyAddress = pxPhyObject->ucPhyIndexes[ xPhyIndex ];
if( pxPhyObject->fnPhyRead( xPhyAddress, phyREG_01_BMSR, &ulStatus ) == 0 )
{
if( !!( pxPhyObject->ulLinkStatusMask & ulBitMask ) != !!( ulStatus & phyBMSR_LINK_STATUS ) )
{
if( ( ulStatus & phyBMSR_LINK_STATUS ) != 0 )
{
pxPhyObject->ulLinkStatusMask |= ulBitMask;
}
else
{
pxPhyObject->ulLinkStatusMask &= ~( ulBitMask );
}
FreeRTOS_printf( ( "xPhyCheckLinkStatus: PHY LS now %02X\n", ( unsigned int ) pxPhyObject->ulLinkStatusMask ) );
xNeedCheck = pdTRUE;
}
}
}
vTaskSetTimeOutState( &( pxPhyObject->xLinkStatusTimer ) );
if( ( pxPhyObject->ulLinkStatusMask & ( ulBitMask >> 1 ) ) != 0 )
{
/* The link status is high, so don't poll the PHY too often. */
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_HIGH_CHECK_TIME_MS );
}
else
{
/* The link status is low, polling may be done more frequently. */
pxPhyObject->xLinkStatusRemaining = pdMS_TO_TICKS( ipconfigPHY_LS_LOW_CHECK_TIME_MS );
}
}
return xNeedCheck;
}
/*-----------------------------------------------------------*/
@@ -0,0 +1,10 @@
Network drivers are provided as examples only, and do not form part of the
FreeRTOS+TCP stack itself. They:
+ May be based on driver code provided by the chip vendors,
+ May not have been tested in all possible configurations,
+ Will not necessarily be optimised.
+ May have a dependency on a particular PHY part number.
+ May not necessarily comply with any particular coding standard.
+ May have dependencies on chip company libraries.
+ May include other hardware board dependencies.
@@ -0,0 +1,46 @@
if (NOT ( (FREERTOS_PLUS_TCP_NETWORK_IF STREQUAL "STM32") ) )
return()
endif()
#------------------------------------------------------------------------------
add_library( freertos_plus_tcp_network_if STATIC )
set( FREERTOS_PLUS_TCP_STM32_IF_DRIVER "None" CACHE STRING "The driver sources to use with STM32 Network interface" )
target_sources( freertos_plus_tcp_network_if
PRIVATE
NetworkInterface.c
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F4>:
Drivers/F4/stm32f4xx_hal_eth.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F7>:
Drivers/F7/stm32f7xx_hal_eth.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H5>:
Drivers/H5/stm32h5xx_hal_eth_ex.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H5>:
Drivers/H5/stm32h5xx_hal_eth.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H7>:
Drivers/H7/stm32h7xx_hal_eth_ex.c>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H7>:
Drivers/H7/stm32h7xx_hal_eth.c>
)
target_include_directories( freertos_plus_tcp_network_if
PUBLIC
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F4>:
Drivers/F4>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},F7>:
Drivers/F7>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H5>:
Drivers/H5>
$<$<STREQUAL:${FREERTOS_PLUS_TCP_STM32_IF_DRIVER},H7>:
Drivers/H7>
)
target_link_libraries( freertos_plus_tcp_network_if
PUBLIC
freertos_plus_tcp_port
freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
@@ -0,0 +1,681 @@
/**
******************************************************************************
* @file stm32h5xx_hal_eth_ex.c
* @author MCD Application Team
* @brief ETH HAL Extended module driver.
*
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32h5xx_hal.h"
/** @addtogroup STM32H5xx_HAL_Driver
* @{
*/
#ifdef HAL_ETH_MODULE_ENABLED
#if defined( ETH )
/** @defgroup ETHEx ETHEx
* @brief ETH HAL Extended module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ETHEx_Private_Constants ETHEx Private Constants
* @{
*/
#define ETH_MACL4CR_MASK \
( ETH_MACL3L4CR_L4PEN | ETH_MACL3L4CR_L4SPM | \
ETH_MACL3L4CR_L4SPIM | ETH_MACL3L4CR_L4DPM | \
ETH_MACL3L4CR_L4DPIM )
#define ETH_MACL3CR_MASK \
( ETH_MACL3L4CR_L3PEN | ETH_MACL3L4CR_L3SAM | \
ETH_MACL3L4CR_L3SAIM | ETH_MACL3L4CR_L3DAM | \
ETH_MACL3L4CR_L3DAIM | ETH_MACL3L4CR_L3HSBM | \
ETH_MACL3L4CR_L3HDBM )
#define ETH_MACRXVLAN_MASK \
( ETH_MACVTR_EIVLRXS | ETH_MACVTR_EIVLS | \
ETH_MACVTR_ERIVLT | ETH_MACVTR_EDVLP | \
ETH_MACVTR_VTHM | ETH_MACVTR_EVLRXS | \
ETH_MACVTR_EVLS | ETH_MACVTR_DOVLTC | \
ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL | \
ETH_MACVTR_VTIM | ETH_MACVTR_ETV )
#define ETH_MACTXVLAN_MASK \
( ETH_MACVIR_VLTI | ETH_MACVIR_CSVL | \
ETH_MACVIR_VLP | ETH_MACVIR_VLC )
#define ETH_MAC_L4_SRSP_MASK 0x0000FFFFU
#define ETH_MAC_L4_DSTP_MASK 0xFFFF0000U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup ETHEx_Exported_Functions ETH Extended Exported Functions
* @{
*/
/** @defgroup ETHEx_Exported_Functions_Group1 Extended features functions
* @brief Extended features functions
*
* @verbatim
* ===============================================================================
##### Extended features functions #####
#####===============================================================================
#####[..] This section provides functions allowing to:
#####(+) Configure ARP offload module
#####(+) Configure L3 and L4 filters
#####(+) Configure Extended VLAN features
#####(+) Configure Energy Efficient Ethernet module
#####
#####@endverbatim
* @{
*/
/**
* @brief Enables ARP Offload.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None
*/
void HAL_ETHEx_EnableARPOffload( ETH_HandleTypeDef * heth )
{
SET_BIT( heth->Instance->MACCR, ETH_MACCR_ARP );
}
/**
* @brief Disables ARP Offload.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None
*/
void HAL_ETHEx_DisableARPOffload( ETH_HandleTypeDef * heth )
{
CLEAR_BIT( heth->Instance->MACCR, ETH_MACCR_ARP );
}
/**
* @brief Set the ARP Match IP address
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param IpAddress: IP Address to be matched for incoming ARP requests
* @retval None
*/
void HAL_ETHEx_SetARPAddressMatch( ETH_HandleTypeDef * heth,
uint32_t IpAddress )
{
WRITE_REG( heth->Instance->MACARPAR, IpAddress );
}
/**
* @brief Configures the L4 Filter, this function allow to:
* set the layer 4 protocol to be matched (TCP or UDP)
* enable/disable L4 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L4 filter to configured, this parameter must be one of the following
* ETH_L4_FILTER_0
* ETH_L4_FILTER_1
* @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure
* that contains L4 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_SetL4FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L4FilterConfigTypeDef * pL4FilterConfig )
{
if( pL4FilterConfig == NULL )
{
return HAL_ERROR;
}
if( Filter == ETH_L4_FILTER_0 )
{
/* Write configuration to MACL3L4C0R register */
MODIFY_REG( heth->Instance->MACL3L4C0R, ETH_MACL4CR_MASK, ( pL4FilterConfig->Protocol |
pL4FilterConfig->SrcPortFilterMatch |
pL4FilterConfig->DestPortFilterMatch ) );
/* Write configuration to MACL4A0R register */
WRITE_REG( heth->Instance->MACL4A0R, ( pL4FilterConfig->SourcePort | ( pL4FilterConfig->DestinationPort << 16 ) ) );
}
else /* Filter == ETH_L4_FILTER_1 */
{
/* Write configuration to MACL3L4C1R register */
MODIFY_REG( heth->Instance->MACL3L4C1R, ETH_MACL4CR_MASK, ( pL4FilterConfig->Protocol |
pL4FilterConfig->SrcPortFilterMatch |
pL4FilterConfig->DestPortFilterMatch ) );
/* Write configuration to MACL4A1R register */
WRITE_REG( heth->Instance->MACL4A1R, ( pL4FilterConfig->SourcePort | ( pL4FilterConfig->DestinationPort << 16 ) ) );
}
/* Enable L4 filter */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
return HAL_OK;
}
/**
* @brief Configures the L4 Filter, this function allow to:
* set the layer 4 protocol to be matched (TCP or UDP)
* enable/disable L4 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L4 filter to configured, this parameter must be one of the following
* ETH_L4_FILTER_0
* ETH_L4_FILTER_1
* @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure
* that contains L4 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_GetL4FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L4FilterConfigTypeDef * pL4FilterConfig )
{
if( pL4FilterConfig == NULL )
{
return HAL_ERROR;
}
if( Filter == ETH_L4_FILTER_0 )
{
/* Get configuration from MACL3L4C0R register */
pL4FilterConfig->Protocol = READ_BIT( heth->Instance->MACL3L4C0R, ETH_MACL3L4CR_L4PEN );
pL4FilterConfig->DestPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C0R,
( ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM ) );
pL4FilterConfig->SrcPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C0R,
( ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM ) );
/* Get configuration from MACL4A0R register */
pL4FilterConfig->DestinationPort = ( READ_BIT( heth->Instance->MACL4A0R, ETH_MAC_L4_DSTP_MASK ) >> 16 );
pL4FilterConfig->SourcePort = READ_BIT( heth->Instance->MACL4A0R, ETH_MAC_L4_SRSP_MASK );
}
else /* Filter == ETH_L4_FILTER_1 */
{
/* Get configuration from MACL3L4C1R register */
pL4FilterConfig->Protocol = READ_BIT( heth->Instance->MACL3L4C1R, ETH_MACL3L4CR_L4PEN );
pL4FilterConfig->DestPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C1R,
( ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM ) );
pL4FilterConfig->SrcPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C1R,
( ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM ) );
/* Get configuration from MACL4A1R register */
pL4FilterConfig->DestinationPort = ( READ_BIT( heth->Instance->MACL4A1R, ETH_MAC_L4_DSTP_MASK ) >> 16 );
pL4FilterConfig->SourcePort = READ_BIT( heth->Instance->MACL4A1R, ETH_MAC_L4_SRSP_MASK );
}
return HAL_OK;
}
/**
* @brief Configures the L3 Filter, this function allow to:
* set the layer 3 protocol to be matched (IPv4 or IPv6)
* enable/disable L3 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L3 filter to configured, this parameter must be one of the following
* ETH_L3_FILTER_0
* ETH_L3_FILTER_1
* @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure
* that contains L3 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_SetL3FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L3FilterConfigTypeDef * pL3FilterConfig )
{
if( pL3FilterConfig == NULL )
{
return HAL_ERROR;
}
if( Filter == ETH_L3_FILTER_0 )
{
/* Write configuration to MACL3L4C0R register */
MODIFY_REG( heth->Instance->MACL3L4C0R, ETH_MACL3CR_MASK, ( pL3FilterConfig->Protocol |
pL3FilterConfig->SrcAddrFilterMatch |
pL3FilterConfig->DestAddrFilterMatch |
( pL3FilterConfig->SrcAddrHigherBitsMatch << 6 ) |
( pL3FilterConfig->DestAddrHigherBitsMatch << 11 ) ) );
}
else /* Filter == ETH_L3_FILTER_1 */
{
/* Write configuration to MACL3L4C1R register */
MODIFY_REG( heth->Instance->MACL3L4C1R, ETH_MACL3CR_MASK, ( pL3FilterConfig->Protocol |
pL3FilterConfig->SrcAddrFilterMatch |
pL3FilterConfig->DestAddrFilterMatch |
( pL3FilterConfig->SrcAddrHigherBitsMatch << 6 ) |
( pL3FilterConfig->DestAddrHigherBitsMatch << 11 ) ) );
}
if( Filter == ETH_L3_FILTER_0 )
{
/* Check if IPv6 protocol is selected */
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
/* Set the IPv6 address match */
/* Set Bits[31:0] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip6Addr[ 0 ] );
/* Set Bits[63:32] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip6Addr[ 1 ] );
/* update Bits[95:64] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A2R0R, pL3FilterConfig->Ip6Addr[ 2 ] );
/* update Bits[127:96] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A3R0R, pL3FilterConfig->Ip6Addr[ 3 ] );
}
else /* IPv4 protocol is selected */
{
/* Set the IPv4 source address match */
WRITE_REG( heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip4SrcAddr );
/* Set the IPv4 destination address match */
WRITE_REG( heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip4DestAddr );
}
}
else /* Filter == ETH_L3_FILTER_1 */
{
/* Check if IPv6 protocol is selected */
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
/* Set the IPv6 address match */
/* Set Bits[31:0] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip6Addr[ 0 ] );
/* Set Bits[63:32] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[ 1 ] );
/* update Bits[95:64] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[ 2 ] );
/* update Bits[127:96] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[ 3 ] );
}
else /* IPv4 protocol is selected */
{
/* Set the IPv4 source address match */
WRITE_REG( heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4SrcAddr );
/* Set the IPv4 destination address match */
WRITE_REG( heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4DestAddr );
}
}
/* Enable L3 filter */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
return HAL_OK;
}
/**
* @brief Configures the L3 Filter, this function allow to:
* set the layer 3 protocol to be matched (IPv4 or IPv6)
* enable/disable L3 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L3 filter to configured, this parameter must be one of the following
* ETH_L3_FILTER_0
* ETH_L3_FILTER_1
* @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure
* that will contain the L3 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_GetL3FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L3FilterConfigTypeDef * pL3FilterConfig )
{
if( pL3FilterConfig == NULL )
{
return HAL_ERROR;
}
pL3FilterConfig->Protocol = READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
ETH_MACL3L4CR_L3PEN );
pL3FilterConfig->SrcAddrFilterMatch = READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
( ETH_MACL3L4CR_L3SAM | ETH_MACL3L4CR_L3SAIM ) );
pL3FilterConfig->DestAddrFilterMatch = READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
( ETH_MACL3L4CR_L3DAM | ETH_MACL3L4CR_L3DAIM ) );
pL3FilterConfig->SrcAddrHigherBitsMatch = ( READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
ETH_MACL3L4CR_L3HSBM ) >> 6 );
pL3FilterConfig->DestAddrHigherBitsMatch = ( READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
ETH_MACL3L4CR_L3HDBM ) >> 11 );
if( Filter == ETH_L3_FILTER_0 )
{
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
WRITE_REG( pL3FilterConfig->Ip6Addr[ 0 ], heth->Instance->MACL3A0R0R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 1 ], heth->Instance->MACL3A1R0R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 2 ], heth->Instance->MACL3A2R0R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 3 ], heth->Instance->MACL3A3R0R );
}
else
{
WRITE_REG( pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R0R );
WRITE_REG( pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R0R );
}
}
else /* ETH_L3_FILTER_1 */
{
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
WRITE_REG( pL3FilterConfig->Ip6Addr[ 0 ], heth->Instance->MACL3A0R1R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 1 ], heth->Instance->MACL3A1R1R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 2 ], heth->Instance->MACL3A2R1R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 3 ], heth->Instance->MACL3A3R1R );
}
else
{
WRITE_REG( pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R1R );
WRITE_REG( pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R1R );
}
}
return HAL_OK;
}
/**
* @brief Enables L3 and L4 filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_EnableL3L4Filtering( ETH_HandleTypeDef * heth )
{
/* Enable L3/L4 filter */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
}
/**
* @brief Disables L3 and L4 filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_DisableL3L4Filtering( ETH_HandleTypeDef * heth )
{
/* Disable L3/L4 filter */
CLEAR_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
}
/**
* @brief Get the VLAN Configuration for Receive Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure
* that will contain the VLAN filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_GetRxVLANConfig( const ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig )
{
if( pVlanConfig == NULL )
{
return HAL_ERROR;
}
pVlanConfig->InnerVLANTagInStatus = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_EIVLRXS ) >> 31 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->StripInnerVLANTag = READ_BIT( heth->Instance->MACVTR, ETH_MACVTR_EIVLS );
pVlanConfig->InnerVLANTag = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_ERIVLT ) >> 27 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->DoubleVLANProcessing = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_EDVLP ) >> 26 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagHashTableMatch = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_VTHM ) >> 25 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagInStatus = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_EVLRXS ) >> 24 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->StripVLANTag = READ_BIT( heth->Instance->MACVTR, ETH_MACVTR_EVLS );
pVlanConfig->VLANTypeCheck = READ_BIT( heth->Instance->MACVTR,
( ETH_MACVTR_DOVLTC | ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL ) );
pVlanConfig->VLANTagInverceMatch = ( ( READ_BIT( heth->Instance->MACVTR, ETH_MACVTR_VTIM ) >> 17 ) == 0U )
? DISABLE : ENABLE;
return HAL_OK;
}
/**
* @brief Set the VLAN Configuration for Receive Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure
* that contains VLAN filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_SetRxVLANConfig( ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig )
{
if( pVlanConfig == NULL )
{
return HAL_ERROR;
}
/* Write config to MACVTR */
MODIFY_REG( heth->Instance->MACVTR, ETH_MACRXVLAN_MASK, ( ( ( uint32_t ) pVlanConfig->InnerVLANTagInStatus << 31 ) |
pVlanConfig->StripInnerVLANTag |
( ( uint32_t ) pVlanConfig->InnerVLANTag << 27 ) |
( ( uint32_t ) pVlanConfig->DoubleVLANProcessing << 26 ) |
( ( uint32_t ) pVlanConfig->VLANTagHashTableMatch << 25 ) |
( ( uint32_t ) pVlanConfig->VLANTagInStatus << 24 ) |
pVlanConfig->StripVLANTag |
pVlanConfig->VLANTypeCheck |
( ( uint32_t ) pVlanConfig->VLANTagInverceMatch << 17 ) ) );
return HAL_OK;
}
/**
* @brief Set the VLAN Hash Table
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANHashTable: VLAN hash table 16 bit value
* @retval None
*/
void HAL_ETHEx_SetVLANHashTable( ETH_HandleTypeDef * heth,
uint32_t VLANHashTable )
{
MODIFY_REG( heth->Instance->MACVHTR, ETH_MACVHTR_VLHT, VLANHashTable );
}
/**
* @brief Get the VLAN Configuration for Transmit Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANTag: Selects the vlan tag, this parameter must be one of the following
* ETH_OUTER_TX_VLANTAG
* ETH_INNER_TX_VLANTAG
* @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure
* that will contain the Tx VLAN filter configuration.
* @retval HAL Status.
*/
HAL_StatusTypeDef HAL_ETHEx_GetTxVLANConfig( const ETH_HandleTypeDef * heth,
uint32_t VLANTag,
ETH_TxVLANConfigTypeDef * pVlanConfig )
{
if( pVlanConfig == NULL )
{
return HAL_ERROR;
}
if( VLANTag == ETH_INNER_TX_VLANTAG )
{
pVlanConfig->SourceTxDesc = ( ( READ_BIT( heth->Instance->MACIVIR, ETH_MACVIR_VLTI ) >> 20 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->SVLANType = ( ( READ_BIT( heth->Instance->MACIVIR, ETH_MACVIR_CSVL ) >> 19 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagControl = READ_BIT( heth->Instance->MACIVIR, ( ETH_MACVIR_VLP | ETH_MACVIR_VLC ) );
}
else
{
pVlanConfig->SourceTxDesc = ( ( READ_BIT( heth->Instance->MACVIR, ETH_MACVIR_VLTI ) >> 20 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->SVLANType = ( ( READ_BIT( heth->Instance->MACVIR, ETH_MACVIR_CSVL ) >> 19 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagControl = READ_BIT( heth->Instance->MACVIR, ( ETH_MACVIR_VLP | ETH_MACVIR_VLC ) );
}
return HAL_OK;
}
/**
* @brief Set the VLAN Configuration for Transmit Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANTag: Selects the vlan tag, this parameter must be one of the following
* ETH_OUTER_TX_VLANTAG
* ETH_INNER_TX_VLANTAG
* @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure
* that contains Tx VLAN filter configuration.
* @retval HAL Status
*/
HAL_StatusTypeDef HAL_ETHEx_SetTxVLANConfig( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
const ETH_TxVLANConfigTypeDef * pVlanConfig )
{
if( VLANTag == ETH_INNER_TX_VLANTAG )
{
MODIFY_REG( heth->Instance->MACIVIR, ETH_MACTXVLAN_MASK, ( ( ( uint32_t ) pVlanConfig->SourceTxDesc << 20 ) |
( ( uint32_t ) pVlanConfig->SVLANType << 19 ) |
pVlanConfig->VLANTagControl ) );
/* Enable Double VLAN processing */
SET_BIT( heth->Instance->MACVTR, ETH_MACVTR_EDVLP );
}
else
{
MODIFY_REG( heth->Instance->MACVIR, ETH_MACTXVLAN_MASK, ( ( ( uint32_t ) pVlanConfig->SourceTxDesc << 20 ) |
( ( uint32_t ) pVlanConfig->SVLANType << 19 ) |
pVlanConfig->VLANTagControl ) );
}
return HAL_OK;
}
/**
* @brief Set the VLAN Tag Identifier for Transmit Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANTag: Selects the vlan tag, this parameter must be one of the following
* ETH_OUTER_TX_VLANTAG
* ETH_INNER_TX_VLANTAG
* @param VLANIdentifier: VLAN Identifier 16 bit value
* @retval None
*/
void HAL_ETHEx_SetTxVLANIdentifier( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
uint32_t VLANIdentifier )
{
if( VLANTag == ETH_INNER_TX_VLANTAG )
{
MODIFY_REG( heth->Instance->MACIVIR, ETH_MACVIR_VLT, VLANIdentifier );
}
else
{
MODIFY_REG( heth->Instance->MACVIR, ETH_MACVIR_VLT, VLANIdentifier );
}
}
/**
* @brief Enables the VLAN Tag Filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_EnableVLANProcessing( ETH_HandleTypeDef * heth )
{
/* Enable VLAN processing */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_VTFE );
}
/**
* @brief Disables the VLAN Tag Filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_DisableVLANProcessing( ETH_HandleTypeDef * heth )
{
/* Disable VLAN processing */
CLEAR_BIT( heth->Instance->MACPFR, ETH_MACPFR_VTFE );
}
/**
* @brief Enters the Low Power Idle (LPI) mode
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param TxAutomate: Enable/Disable automate enter/exit LPI mode.
* @param TxClockStop: Enable/Disable Tx clock stop in LPI mode.
* @retval None
*/
void HAL_ETHEx_EnterLPIMode( ETH_HandleTypeDef * heth,
FunctionalState TxAutomate,
FunctionalState TxClockStop )
{
/* Enable LPI Interrupts */
__HAL_ETH_MAC_ENABLE_IT( heth, ETH_MACIER_LPIIE );
/* Write to LPI Control register: Enter low power mode */
MODIFY_REG( heth->Instance->MACLCSR, ( ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE ),
( ( ( uint32_t ) TxAutomate << 19 ) |
( ( uint32_t ) TxClockStop << 21 ) |
ETH_MACLCSR_LPIEN ) );
}
/**
* @brief Exits the Low Power Idle (LPI) mode.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None
*/
void HAL_ETHEx_ExitLPIMode( ETH_HandleTypeDef * heth )
{
/* Clear the LPI Config and exit low power mode */
CLEAR_BIT( heth->Instance->MACLCSR, ( ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE ) );
/* Enable LPI Interrupts */
__HAL_ETH_MAC_DISABLE_IT( heth, ETH_MACIER_LPIIE );
}
/**
* @brief Returns the ETH MAC LPI event
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval ETH MAC WakeUp event
*/
uint32_t HAL_ETHEx_GetMACLPIEvent( const ETH_HandleTypeDef * heth )
{
return heth->MACLPIEvent;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ETH */
#endif /* HAL_ETH_MODULE_ENABLED */
/**
* @}
*/
@@ -0,0 +1,400 @@
/**
******************************************************************************
* @file stm32h5xx_hal_eth_ex.h
* @author MCD Application Team
* @brief Header file of ETH HAL Extended module.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32H5xx_HAL_ETH_EX_H
#define STM32H5xx_HAL_ETH_EX_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined( ETH )
/* Includes ------------------------------------------------------------------*/
#include "stm32h5xx_hal_def.h"
/** @addtogroup STM32H5xx_HAL_Driver
* @{
*/
/** @addtogroup ETHEx
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup ETHEx_Exported_Types ETHEx Exported Types
* @{
*/
/**
* @brief ETH RX VLAN structure definition
*/
typedef struct
{
FunctionalState InnerVLANTagInStatus; /*!< Enables or disables Inner VLAN Tag in Rx Status */
uint32_t StripInnerVLANTag; /*!< Sets the Inner VLAN Tag Stripping on Receive
* This parameter can be a value of
* @ref ETHEx_Rx_Inner_VLAN_Tag_Stripping */
FunctionalState InnerVLANTag; /*!< Enables or disables Inner VLAN Tag */
FunctionalState DoubleVLANProcessing; /*!< Enable or Disable double VLAN processing */
FunctionalState VLANTagHashTableMatch; /*!< Enable or Disable VLAN Tag Hash Table Match */
FunctionalState VLANTagInStatus; /*!< Enable or Disable VLAN Tag in Rx status */
uint32_t StripVLANTag; /*!< Set the VLAN Tag Stripping on Receive
* This parameter can be a value of @ref ETHEx_Rx_VLAN_Tag_Stripping */
uint32_t VLANTypeCheck; /*!< Enable or Disable VLAN Type Check
* This parameter can be a value of @ref ETHEx_VLAN_Type_Check */
FunctionalState VLANTagInverceMatch; /*!< Enable or disable VLAN Tag Inverse Match */
} ETH_RxVLANConfigTypeDef;
/**
*
*/
/**
* @brief ETH TX VLAN structure definition
*/
typedef struct
{
FunctionalState SourceTxDesc; /*!< Enable or Disable VLAN tag source from DMA tx descriptors */
FunctionalState SVLANType; /*!< Enable or Disable insertion of SVLAN type */
uint32_t VLANTagControl; /*!< Sets the VLAN tag control in tx packets
* This parameter can be a value of @ref ETHEx_VLAN_Tag_Control */
} ETH_TxVLANConfigTypeDef;
/**
*
*/
/**
* @brief ETH L3 filter structure definition
*/
typedef struct
{
uint32_t Protocol; /*!< Sets the L3 filter protocol to IPv4 or IPv6
* This parameter can be a value of @ref ETHEx_L3_Protocol */
uint32_t SrcAddrFilterMatch; /*!< Sets the L3 filter source address match
* This parameter can be a value of @ref ETHEx_L3_Source_Match */
uint32_t DestAddrFilterMatch; /*!< Sets the L3 filter destination address match
* This parameter can be a value of @ref ETHEx_L3_Destination_Match */
uint32_t SrcAddrHigherBitsMatch; /*!< Sets the L3 filter source address higher bits match
* This parameter can be a value from 0 to 31 */
uint32_t DestAddrHigherBitsMatch; /*!< Sets the L3 filter destination address higher bits match
* This parameter can be a value from 0 to 31 */
uint32_t Ip4SrcAddr; /*!< Sets the L3 filter IPv4 source address if IPv4 protocol is used
* This parameter can be a value from 0x0 to 0xFFFFFFFF */
uint32_t Ip4DestAddr; /*!< Sets the L3 filter IPv4 destination address if IPv4 protocol is used
* This parameter can be a value from 0 to 0xFFFFFFFF */
uint32_t Ip6Addr[ 4 ]; /*!< Sets the L3 filter IPv6 address if IPv6 protocol is used
* This parameter must be a table of 4 words (4* 32 bits) */
} ETH_L3FilterConfigTypeDef;
/**
*
*/
/**
* @brief ETH L4 filter structure definition
*/
typedef struct
{
uint32_t Protocol; /*!< Sets the L4 filter protocol to TCP or UDP
* This parameter can be a value of @ref ETHEx_L4_Protocol */
uint32_t SrcPortFilterMatch; /*!< Sets the L4 filter source port match
* This parameter can be a value of @ref ETHEx_L4_Source_Match */
uint32_t DestPortFilterMatch; /*!< Sets the L4 filter destination port match
* This parameter can be a value of @ref ETHEx_L4_Destination_Match */
uint32_t SourcePort; /*!< Sets the L4 filter source port
* This parameter must be a value from 0x0 to 0xFFFF */
uint32_t DestinationPort; /*!< Sets the L4 filter destination port
* This parameter must be a value from 0x0 to 0xFFFF */
} ETH_L4FilterConfigTypeDef;
/**
*
*/
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup ETHEx_Exported_Constants ETHEx Exported Constants
* @{
*/
/** @defgroup ETHEx_LPI_Event ETHEx LPI Event
* @{
*/
#define ETH_TX_LPI_ENTRY ETH_MACLCSR_TLPIEN
#define ETH_TX_LPI_EXIT ETH_MACLCSR_TLPIEX
#define ETH_RX_LPI_ENTRY ETH_MACLCSR_RLPIEN
#define ETH_RX_LPI_EXIT ETH_MACLCSR_RLPIEX
/**
* @}
*/
/** @defgroup ETHEx_L3_Filter ETHEx L3 Filter
* @{
*/
#define ETH_L3_FILTER_0 0x00000000U
#define ETH_L3_FILTER_1 0x0000000CU
/**
* @}
*/
/** @defgroup ETHEx_L4_Filter ETHEx L4 Filter
* @{
*/
#define ETH_L4_FILTER_0 0x00000000U
#define ETH_L4_FILTER_1 0x0000000CU
/**
* @}
*/
/** @defgroup ETHEx_L3_Protocol ETHEx L3 Protocol
* @{
*/
#define ETH_L3_IPV6_MATCH ETH_MACL3L4CR_L3PEN
#define ETH_L3_IPV4_MATCH 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L3_Source_Match ETHEx L3 Source Match
* @{
*/
#define ETH_L3_SRC_ADDR_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L3SAM
#define ETH_L3_SRC_ADDR_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L3SAM | ETH_MACL3L4CR_L3SAIM )
#define ETH_L3_SRC_ADDR_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L3_Destination_Match ETHEx L3 Destination Match
* @{
*/
#define ETH_L3_DEST_ADDR_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L3DAM
#define ETH_L3_DEST_ADDR_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L3DAM | ETH_MACL3L4CR_L3DAIM )
#define ETH_L3_DEST_ADDR_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L4_Protocol ETHEx L4 Protocol
* @{
*/
#define ETH_L4_UDP_MATCH ETH_MACL3L4CR_L4PEN
#define ETH_L4_TCP_MATCH 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L4_Source_Match ETHEx L4 Source Match
* @{
*/
#define ETH_L4_SRC_PORT_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L4SPM
#define ETH_L4_SRC_PORT_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM )
#define ETH_L4_SRC_PORT_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L4_Destination_Match ETHEx L4 Destination Match
* @{
*/
#define ETH_L4_DEST_PORT_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L4DPM
#define ETH_L4_DEST_PORT_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM )
#define ETH_L4_DEST_PORT_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_Rx_Inner_VLAN_Tag_Stripping ETHEx Rx Inner VLAN Tag Stripping
* @{
*/
#define ETH_INNERVLANTAGRXSTRIPPING_NONE ETH_MACVTR_EIVLS_DONOTSTRIP
#define ETH_INNERVLANTAGRXSTRIPPING_IFPASS ETH_MACVTR_EIVLS_STRIPIFPASS
#define ETH_INNERVLANTAGRXSTRIPPING_IFFAILS ETH_MACVTR_EIVLS_STRIPIFFAILS
#define ETH_INNERVLANTAGRXSTRIPPING_ALWAYS ETH_MACVTR_EIVLS_ALWAYSSTRIP
/**
* @}
*/
/** @defgroup ETHEx_Rx_VLAN_Tag_Stripping ETHEx Rx VLAN Tag Stripping
* @{
*/
#define ETH_VLANTAGRXSTRIPPING_NONE ETH_MACVTR_EVLS_DONOTSTRIP
#define ETH_VLANTAGRXSTRIPPING_IFPASS ETH_MACVTR_EVLS_STRIPIFPASS
#define ETH_VLANTAGRXSTRIPPING_IFFAILS ETH_MACVTR_EVLS_STRIPIFFAILS
#define ETH_VLANTAGRXSTRIPPING_ALWAYS ETH_MACVTR_EVLS_ALWAYSSTRIP
/**
* @}
*/
/** @defgroup ETHEx_VLAN_Type_Check ETHEx VLAN Type Check
* @{
*/
#define ETH_VLANTYPECHECK_DISABLE ETH_MACVTR_DOVLTC
#define ETH_VLANTYPECHECK_SVLAN ( ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL )
#define ETH_VLANTYPECHECK_CVLAN 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_VLAN_Tag_Control ETHEx_VLAN_Tag_Control
* @{
*/
#define ETH_VLANTAGCONTROL_NONE ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_NOVLANTAG )
#define ETH_VLANTAGCONTROL_DELETE ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_VLANTAGDELETE )
#define ETH_VLANTAGCONTROL_INSERT ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_VLANTAGINSERT )
#define ETH_VLANTAGCONTROL_REPLACE ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_VLANTAGREPLACE )
/**
* @}
*/
/** @defgroup ETHEx_Tx_VLAN_Tag ETHEx Tx VLAN Tag
* @{
*/
#define ETH_INNER_TX_VLANTAG 0x00000001U
#define ETH_OUTER_TX_VLANTAG 0x00000000U
/**
* @}
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup ETHEx_Exported_Functions
* @{
*/
/** @addtogroup ETHEx_Exported_Functions_Group1
* @{
*/
/* MAC ARP Offloading APIs ***************************************************/
void HAL_ETHEx_EnableARPOffload( ETH_HandleTypeDef * heth );
void HAL_ETHEx_DisableARPOffload( ETH_HandleTypeDef * heth );
void HAL_ETHEx_SetARPAddressMatch( ETH_HandleTypeDef * heth,
uint32_t IpAddress );
/* MAC L3 L4 Filtering APIs ***************************************************/
void HAL_ETHEx_EnableL3L4Filtering( ETH_HandleTypeDef * heth );
void HAL_ETHEx_DisableL3L4Filtering( ETH_HandleTypeDef * heth );
HAL_StatusTypeDef HAL_ETHEx_GetL3FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L3FilterConfigTypeDef * pL3FilterConfig );
HAL_StatusTypeDef HAL_ETHEx_GetL4FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L4FilterConfigTypeDef * pL4FilterConfig );
HAL_StatusTypeDef HAL_ETHEx_SetL3FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L3FilterConfigTypeDef * pL3FilterConfig );
HAL_StatusTypeDef HAL_ETHEx_SetL4FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L4FilterConfigTypeDef * pL4FilterConfig );
/* MAC VLAN Processing APIs ************************************************/
void HAL_ETHEx_EnableVLANProcessing( ETH_HandleTypeDef * heth );
void HAL_ETHEx_DisableVLANProcessing( ETH_HandleTypeDef * heth );
HAL_StatusTypeDef HAL_ETHEx_GetRxVLANConfig( const ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig );
HAL_StatusTypeDef HAL_ETHEx_SetRxVLANConfig( ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig );
void HAL_ETHEx_SetVLANHashTable( ETH_HandleTypeDef * heth,
uint32_t VLANHashTable );
HAL_StatusTypeDef HAL_ETHEx_GetTxVLANConfig( const ETH_HandleTypeDef * heth,
uint32_t VLANTag,
ETH_TxVLANConfigTypeDef * pVlanConfig );
HAL_StatusTypeDef HAL_ETHEx_SetTxVLANConfig( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
const ETH_TxVLANConfigTypeDef * pVlanConfig );
void HAL_ETHEx_SetTxVLANIdentifier( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
uint32_t VLANIdentifier );
/* Energy Efficient Ethernet APIs *********************************************/
void HAL_ETHEx_EnterLPIMode( ETH_HandleTypeDef * heth,
FunctionalState TxAutomate,
FunctionalState TxClockStop );
void HAL_ETHEx_ExitLPIMode( ETH_HandleTypeDef * heth );
uint32_t HAL_ETHEx_GetMACLPIEvent( const ETH_HandleTypeDef * heth );
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ETH */
#ifdef __cplusplus
}
#endif
#endif /* STM32H5xx_HAL_ETH_EX_H */
@@ -0,0 +1,681 @@
/**
******************************************************************************
* @file stm32h7xx_hal_eth_ex.c
* @author MCD Application Team
* @brief ETH HAL Extended module driver.
*
******************************************************************************
* @attention
*
* Copyright (c) 2017 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_hal.h"
/** @addtogroup STM32H7xx_HAL_Driver
* @{
*/
#ifdef HAL_ETH_MODULE_ENABLED
#if defined( ETH )
/** @defgroup ETHEx ETHEx
* @brief ETH HAL Extended module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ETHEx_Private_Constants ETHEx Private Constants
* @{
*/
#define ETH_MACL4CR_MASK \
( ETH_MACL3L4CR_L4PEN | ETH_MACL3L4CR_L4SPM | \
ETH_MACL3L4CR_L4SPIM | ETH_MACL3L4CR_L4DPM | \
ETH_MACL3L4CR_L4DPIM )
#define ETH_MACL3CR_MASK \
( ETH_MACL3L4CR_L3PEN | ETH_MACL3L4CR_L3SAM | \
ETH_MACL3L4CR_L3SAIM | ETH_MACL3L4CR_L3DAM | \
ETH_MACL3L4CR_L3DAIM | ETH_MACL3L4CR_L3HSBM | \
ETH_MACL3L4CR_L3HDBM )
#define ETH_MACRXVLAN_MASK \
( ETH_MACVTR_EIVLRXS | ETH_MACVTR_EIVLS | \
ETH_MACVTR_ERIVLT | ETH_MACVTR_EDVLP | \
ETH_MACVTR_VTHM | ETH_MACVTR_EVLRXS | \
ETH_MACVTR_EVLS | ETH_MACVTR_DOVLTC | \
ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL | \
ETH_MACVTR_VTIM | ETH_MACVTR_ETV )
#define ETH_MACTXVLAN_MASK \
( ETH_MACVIR_VLTI | ETH_MACVIR_CSVL | \
ETH_MACVIR_VLP | ETH_MACVIR_VLC )
#define ETH_MAC_L4_SRSP_MASK 0x0000FFFFU
#define ETH_MAC_L4_DSTP_MASK 0xFFFF0000U
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup ETHEx_Exported_Functions ETH Extended Exported Functions
* @{
*/
/** @defgroup ETHEx_Exported_Functions_Group1 Extended features functions
* @brief Extended features functions
*
* @verbatim
* ===============================================================================
##### Extended features functions #####
#####===============================================================================
#####[..] This section provides functions allowing to:
#####(+) Configure ARP offload module
#####(+) Configure L3 and L4 filters
#####(+) Configure Extended VLAN features
#####(+) Configure Energy Efficient Ethernet module
#####
#####@endverbatim
* @{
*/
/**
* @brief Enables ARP Offload.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None
*/
void HAL_ETHEx_EnableARPOffload( ETH_HandleTypeDef * heth )
{
SET_BIT( heth->Instance->MACCR, ETH_MACCR_ARP );
}
/**
* @brief Disables ARP Offload.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None
*/
void HAL_ETHEx_DisableARPOffload( ETH_HandleTypeDef * heth )
{
CLEAR_BIT( heth->Instance->MACCR, ETH_MACCR_ARP );
}
/**
* @brief Set the ARP Match IP address
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param IpAddress: IP Address to be matched for incoming ARP requests
* @retval None
*/
void HAL_ETHEx_SetARPAddressMatch( ETH_HandleTypeDef * heth,
uint32_t IpAddress )
{
WRITE_REG( heth->Instance->MACARPAR, IpAddress );
}
/**
* @brief Configures the L4 Filter, this function allow to:
* set the layer 4 protocol to be matched (TCP or UDP)
* enable/disable L4 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L4 filter to configured, this parameter must be one of the following
* ETH_L4_FILTER_0
* ETH_L4_FILTER_1
* @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure
* that contains L4 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_SetL4FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L4FilterConfigTypeDef * pL4FilterConfig )
{
if( pL4FilterConfig == NULL )
{
return HAL_ERROR;
}
if( Filter == ETH_L4_FILTER_0 )
{
/* Write configuration to MACL3L4C0R register */
MODIFY_REG( heth->Instance->MACL3L4C0R, ETH_MACL4CR_MASK, ( pL4FilterConfig->Protocol |
pL4FilterConfig->SrcPortFilterMatch |
pL4FilterConfig->DestPortFilterMatch ) );
/* Write configuration to MACL4A0R register */
WRITE_REG( heth->Instance->MACL4A0R, ( pL4FilterConfig->SourcePort | ( pL4FilterConfig->DestinationPort << 16 ) ) );
}
else /* Filter == ETH_L4_FILTER_1 */
{
/* Write configuration to MACL3L4C1R register */
MODIFY_REG( heth->Instance->MACL3L4C1R, ETH_MACL4CR_MASK, ( pL4FilterConfig->Protocol |
pL4FilterConfig->SrcPortFilterMatch |
pL4FilterConfig->DestPortFilterMatch ) );
/* Write configuration to MACL4A1R register */
WRITE_REG( heth->Instance->MACL4A1R, ( pL4FilterConfig->SourcePort | ( pL4FilterConfig->DestinationPort << 16 ) ) );
}
/* Enable L4 filter */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
return HAL_OK;
}
/**
* @brief Configures the L4 Filter, this function allow to:
* set the layer 4 protocol to be matched (TCP or UDP)
* enable/disable L4 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L4 filter to configured, this parameter must be one of the following
* ETH_L4_FILTER_0
* ETH_L4_FILTER_1
* @param pL4FilterConfig: pointer to a ETH_L4FilterConfigTypeDef structure
* that contains L4 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_GetL4FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L4FilterConfigTypeDef * pL4FilterConfig )
{
if( pL4FilterConfig == NULL )
{
return HAL_ERROR;
}
if( Filter == ETH_L4_FILTER_0 )
{
/* Get configuration from MACL3L4C0R register */
pL4FilterConfig->Protocol = READ_BIT( heth->Instance->MACL3L4C0R, ETH_MACL3L4CR_L4PEN );
pL4FilterConfig->DestPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C0R,
( ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM ) );
pL4FilterConfig->SrcPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C0R,
( ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM ) );
/* Get configuration from MACL4A0R register */
pL4FilterConfig->DestinationPort = ( READ_BIT( heth->Instance->MACL4A0R, ETH_MAC_L4_DSTP_MASK ) >> 16 );
pL4FilterConfig->SourcePort = READ_BIT( heth->Instance->MACL4A0R, ETH_MAC_L4_SRSP_MASK );
}
else /* Filter == ETH_L4_FILTER_1 */
{
/* Get configuration from MACL3L4C1R register */
pL4FilterConfig->Protocol = READ_BIT( heth->Instance->MACL3L4C1R, ETH_MACL3L4CR_L4PEN );
pL4FilterConfig->DestPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C1R,
( ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM ) );
pL4FilterConfig->SrcPortFilterMatch = READ_BIT( heth->Instance->MACL3L4C1R,
( ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM ) );
/* Get configuration from MACL4A1R register */
pL4FilterConfig->DestinationPort = ( READ_BIT( heth->Instance->MACL4A1R, ETH_MAC_L4_DSTP_MASK ) >> 16 );
pL4FilterConfig->SourcePort = READ_BIT( heth->Instance->MACL4A1R, ETH_MAC_L4_SRSP_MASK );
}
return HAL_OK;
}
/**
* @brief Configures the L3 Filter, this function allow to:
* set the layer 3 protocol to be matched (IPv4 or IPv6)
* enable/disable L3 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L3 filter to configured, this parameter must be one of the following
* ETH_L3_FILTER_0
* ETH_L3_FILTER_1
* @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure
* that contains L3 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_SetL3FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L3FilterConfigTypeDef * pL3FilterConfig )
{
if( pL3FilterConfig == NULL )
{
return HAL_ERROR;
}
if( Filter == ETH_L3_FILTER_0 )
{
/* Write configuration to MACL3L4C0R register */
MODIFY_REG( heth->Instance->MACL3L4C0R, ETH_MACL3CR_MASK, ( pL3FilterConfig->Protocol |
pL3FilterConfig->SrcAddrFilterMatch |
pL3FilterConfig->DestAddrFilterMatch |
( pL3FilterConfig->SrcAddrHigherBitsMatch << 6 ) |
( pL3FilterConfig->DestAddrHigherBitsMatch << 11 ) ) );
}
else /* Filter == ETH_L3_FILTER_1 */
{
/* Write configuration to MACL3L4C1R register */
MODIFY_REG( heth->Instance->MACL3L4C1R, ETH_MACL3CR_MASK, ( pL3FilterConfig->Protocol |
pL3FilterConfig->SrcAddrFilterMatch |
pL3FilterConfig->DestAddrFilterMatch |
( pL3FilterConfig->SrcAddrHigherBitsMatch << 6 ) |
( pL3FilterConfig->DestAddrHigherBitsMatch << 11 ) ) );
}
if( Filter == ETH_L3_FILTER_0 )
{
/* Check if IPv6 protocol is selected */
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
/* Set the IPv6 address match */
/* Set Bits[31:0] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip6Addr[ 0 ] );
/* Set Bits[63:32] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip6Addr[ 1 ] );
/* update Bits[95:64] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A2R0R, pL3FilterConfig->Ip6Addr[ 2 ] );
/* update Bits[127:96] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A3R0R, pL3FilterConfig->Ip6Addr[ 3 ] );
}
else /* IPv4 protocol is selected */
{
/* Set the IPv4 source address match */
WRITE_REG( heth->Instance->MACL3A0R0R, pL3FilterConfig->Ip4SrcAddr );
/* Set the IPv4 destination address match */
WRITE_REG( heth->Instance->MACL3A1R0R, pL3FilterConfig->Ip4DestAddr );
}
}
else /* Filter == ETH_L3_FILTER_1 */
{
/* Check if IPv6 protocol is selected */
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
/* Set the IPv6 address match */
/* Set Bits[31:0] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip6Addr[ 0 ] );
/* Set Bits[63:32] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[ 1 ] );
/* update Bits[95:64] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[ 2 ] );
/* update Bits[127:96] of 128-bit IP addr */
WRITE_REG( heth->Instance->MACL3A1R1R, pL3FilterConfig->Ip6Addr[ 3 ] );
}
else /* IPv4 protocol is selected */
{
/* Set the IPv4 source address match */
WRITE_REG( heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4SrcAddr );
/* Set the IPv4 destination address match */
WRITE_REG( heth->Instance->MACL3A0R1R, pL3FilterConfig->Ip4DestAddr );
}
}
/* Enable L3 filter */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
return HAL_OK;
}
/**
* @brief Configures the L3 Filter, this function allow to:
* set the layer 3 protocol to be matched (IPv4 or IPv6)
* enable/disable L3 source/destination port perfect/inverse match.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param Filter: L3 filter to configured, this parameter must be one of the following
* ETH_L3_FILTER_0
* ETH_L3_FILTER_1
* @param pL3FilterConfig: pointer to a ETH_L3FilterConfigTypeDef structure
* that will contain the L3 filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_GetL3FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L3FilterConfigTypeDef * pL3FilterConfig )
{
if( pL3FilterConfig == NULL )
{
return HAL_ERROR;
}
pL3FilterConfig->Protocol = READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
ETH_MACL3L4CR_L3PEN );
pL3FilterConfig->SrcAddrFilterMatch = READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
( ETH_MACL3L4CR_L3SAM | ETH_MACL3L4CR_L3SAIM ) );
pL3FilterConfig->DestAddrFilterMatch = READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
( ETH_MACL3L4CR_L3DAM | ETH_MACL3L4CR_L3DAIM ) );
pL3FilterConfig->SrcAddrHigherBitsMatch = ( READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
ETH_MACL3L4CR_L3HSBM ) >> 6 );
pL3FilterConfig->DestAddrHigherBitsMatch = ( READ_BIT( *( ( __IO uint32_t * ) ( &( heth->Instance->MACL3L4C0R ) + Filter ) ),
ETH_MACL3L4CR_L3HDBM ) >> 11 );
if( Filter == ETH_L3_FILTER_0 )
{
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
WRITE_REG( pL3FilterConfig->Ip6Addr[ 0 ], heth->Instance->MACL3A0R0R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 1 ], heth->Instance->MACL3A1R0R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 2 ], heth->Instance->MACL3A2R0R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 3 ], heth->Instance->MACL3A3R0R );
}
else
{
WRITE_REG( pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R0R );
WRITE_REG( pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R0R );
}
}
else /* ETH_L3_FILTER_1 */
{
if( pL3FilterConfig->Protocol != ETH_L3_IPV4_MATCH )
{
WRITE_REG( pL3FilterConfig->Ip6Addr[ 0 ], heth->Instance->MACL3A0R1R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 1 ], heth->Instance->MACL3A1R1R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 2 ], heth->Instance->MACL3A2R1R );
WRITE_REG( pL3FilterConfig->Ip6Addr[ 3 ], heth->Instance->MACL3A3R1R );
}
else
{
WRITE_REG( pL3FilterConfig->Ip4SrcAddr, heth->Instance->MACL3A0R1R );
WRITE_REG( pL3FilterConfig->Ip4DestAddr, heth->Instance->MACL3A1R1R );
}
}
return HAL_OK;
}
/**
* @brief Enables L3 and L4 filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_EnableL3L4Filtering( ETH_HandleTypeDef * heth )
{
/* Enable L3/L4 filter */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
}
/**
* @brief Disables L3 and L4 filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_DisableL3L4Filtering( ETH_HandleTypeDef * heth )
{
/* Disable L3/L4 filter */
CLEAR_BIT( heth->Instance->MACPFR, ETH_MACPFR_IPFE );
}
/**
* @brief Get the VLAN Configuration for Receive Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure
* that will contain the VLAN filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_GetRxVLANConfig( const ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig )
{
if( pVlanConfig == NULL )
{
return HAL_ERROR;
}
pVlanConfig->InnerVLANTagInStatus = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_EIVLRXS ) >> 31 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->StripInnerVLANTag = READ_BIT( heth->Instance->MACVTR, ETH_MACVTR_EIVLS );
pVlanConfig->InnerVLANTag = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_ERIVLT ) >> 27 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->DoubleVLANProcessing = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_EDVLP ) >> 26 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagHashTableMatch = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_VTHM ) >> 25 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagInStatus = ( ( READ_BIT( heth->Instance->MACVTR,
ETH_MACVTR_EVLRXS ) >> 24 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->StripVLANTag = READ_BIT( heth->Instance->MACVTR, ETH_MACVTR_EVLS );
pVlanConfig->VLANTypeCheck = READ_BIT( heth->Instance->MACVTR,
( ETH_MACVTR_DOVLTC | ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL ) );
pVlanConfig->VLANTagInverceMatch = ( ( READ_BIT( heth->Instance->MACVTR, ETH_MACVTR_VTIM ) >> 17 ) == 0U )
? DISABLE : ENABLE;
return HAL_OK;
}
/**
* @brief Set the VLAN Configuration for Receive Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param pVlanConfig: pointer to a ETH_RxVLANConfigTypeDef structure
* that contains VLAN filter configuration.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_ETHEx_SetRxVLANConfig( ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig )
{
if( pVlanConfig == NULL )
{
return HAL_ERROR;
}
/* Write config to MACVTR */
MODIFY_REG( heth->Instance->MACVTR, ETH_MACRXVLAN_MASK, ( ( ( uint32_t ) pVlanConfig->InnerVLANTagInStatus << 31 ) |
pVlanConfig->StripInnerVLANTag |
( ( uint32_t ) pVlanConfig->InnerVLANTag << 27 ) |
( ( uint32_t ) pVlanConfig->DoubleVLANProcessing << 26 ) |
( ( uint32_t ) pVlanConfig->VLANTagHashTableMatch << 25 ) |
( ( uint32_t ) pVlanConfig->VLANTagInStatus << 24 ) |
pVlanConfig->StripVLANTag |
pVlanConfig->VLANTypeCheck |
( ( uint32_t ) pVlanConfig->VLANTagInverceMatch << 17 ) ) );
return HAL_OK;
}
/**
* @brief Set the VLAN Hash Table
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANHashTable: VLAN hash table 16 bit value
* @retval None
*/
void HAL_ETHEx_SetVLANHashTable( ETH_HandleTypeDef * heth,
uint32_t VLANHashTable )
{
MODIFY_REG( heth->Instance->MACVHTR, ETH_MACVHTR_VLHT, VLANHashTable );
}
/**
* @brief Get the VLAN Configuration for Transmit Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANTag: Selects the vlan tag, this parameter must be one of the following
* ETH_OUTER_TX_VLANTAG
* ETH_INNER_TX_VLANTAG
* @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure
* that will contain the Tx VLAN filter configuration.
* @retval HAL Status.
*/
HAL_StatusTypeDef HAL_ETHEx_GetTxVLANConfig( const ETH_HandleTypeDef * heth,
uint32_t VLANTag,
ETH_TxVLANConfigTypeDef * pVlanConfig )
{
if( pVlanConfig == NULL )
{
return HAL_ERROR;
}
if( VLANTag == ETH_INNER_TX_VLANTAG )
{
pVlanConfig->SourceTxDesc = ( ( READ_BIT( heth->Instance->MACIVIR, ETH_MACVIR_VLTI ) >> 20 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->SVLANType = ( ( READ_BIT( heth->Instance->MACIVIR, ETH_MACVIR_CSVL ) >> 19 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagControl = READ_BIT( heth->Instance->MACIVIR, ( ETH_MACVIR_VLP | ETH_MACVIR_VLC ) );
}
else
{
pVlanConfig->SourceTxDesc = ( ( READ_BIT( heth->Instance->MACVIR, ETH_MACVIR_VLTI ) >> 20 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->SVLANType = ( ( READ_BIT( heth->Instance->MACVIR, ETH_MACVIR_CSVL ) >> 19 ) == 0U ) ? DISABLE : ENABLE;
pVlanConfig->VLANTagControl = READ_BIT( heth->Instance->MACVIR, ( ETH_MACVIR_VLP | ETH_MACVIR_VLC ) );
}
return HAL_OK;
}
/**
* @brief Set the VLAN Configuration for Transmit Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANTag: Selects the vlan tag, this parameter must be one of the following
* ETH_OUTER_TX_VLANTAG
* ETH_INNER_TX_VLANTAG
* @param pVlanConfig: pointer to a ETH_TxVLANConfigTypeDef structure
* that contains Tx VLAN filter configuration.
* @retval HAL Status
*/
HAL_StatusTypeDef HAL_ETHEx_SetTxVLANConfig( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
const ETH_TxVLANConfigTypeDef * pVlanConfig )
{
if( VLANTag == ETH_INNER_TX_VLANTAG )
{
MODIFY_REG( heth->Instance->MACIVIR, ETH_MACTXVLAN_MASK, ( ( ( uint32_t ) pVlanConfig->SourceTxDesc << 20 ) |
( ( uint32_t ) pVlanConfig->SVLANType << 19 ) |
pVlanConfig->VLANTagControl ) );
/* Enable Double VLAN processing */
SET_BIT( heth->Instance->MACVTR, ETH_MACVTR_EDVLP );
}
else
{
MODIFY_REG( heth->Instance->MACVIR, ETH_MACTXVLAN_MASK, ( ( ( uint32_t ) pVlanConfig->SourceTxDesc << 20 ) |
( ( uint32_t ) pVlanConfig->SVLANType << 19 ) |
pVlanConfig->VLANTagControl ) );
}
return HAL_OK;
}
/**
* @brief Set the VLAN Tag Identifier for Transmit Packets.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param VLANTag: Selects the vlan tag, this parameter must be one of the following
* ETH_OUTER_TX_VLANTAG
* ETH_INNER_TX_VLANTAG
* @param VLANIdentifier: VLAN Identifier 16 bit value
* @retval None
*/
void HAL_ETHEx_SetTxVLANIdentifier( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
uint32_t VLANIdentifier )
{
if( VLANTag == ETH_INNER_TX_VLANTAG )
{
MODIFY_REG( heth->Instance->MACIVIR, ETH_MACVIR_VLT, VLANIdentifier );
}
else
{
MODIFY_REG( heth->Instance->MACVIR, ETH_MACVIR_VLT, VLANIdentifier );
}
}
/**
* @brief Enables the VLAN Tag Filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_EnableVLANProcessing( ETH_HandleTypeDef * heth )
{
/* Enable VLAN processing */
SET_BIT( heth->Instance->MACPFR, ETH_MACPFR_VTFE );
}
/**
* @brief Disables the VLAN Tag Filtering process.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None.
*/
void HAL_ETHEx_DisableVLANProcessing( ETH_HandleTypeDef * heth )
{
/* Disable VLAN processing */
CLEAR_BIT( heth->Instance->MACPFR, ETH_MACPFR_VTFE );
}
/**
* @brief Enters the Low Power Idle (LPI) mode
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @param TxAutomate: Enable/Disable automate enter/exit LPI mode.
* @param TxClockStop: Enable/Disable Tx clock stop in LPI mode.
* @retval None
*/
void HAL_ETHEx_EnterLPIMode( ETH_HandleTypeDef * heth,
FunctionalState TxAutomate,
FunctionalState TxClockStop )
{
/* Enable LPI Interrupts */
__HAL_ETH_MAC_ENABLE_IT( heth, ETH_MACIER_LPIIE );
/* Write to LPI Control register: Enter low power mode */
MODIFY_REG( heth->Instance->MACLCSR, ( ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE ),
( ( ( uint32_t ) TxAutomate << 19 ) |
( ( uint32_t ) TxClockStop << 21 ) |
ETH_MACLCSR_LPIEN ) );
}
/**
* @brief Exits the Low Power Idle (LPI) mode.
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval None
*/
void HAL_ETHEx_ExitLPIMode( ETH_HandleTypeDef * heth )
{
/* Clear the LPI Config and exit low power mode */
CLEAR_BIT( heth->Instance->MACLCSR, ( ETH_MACLCSR_LPIEN | ETH_MACLCSR_LPITXA | ETH_MACLCSR_LPITCSE ) );
/* Enable LPI Interrupts */
__HAL_ETH_MAC_DISABLE_IT( heth, ETH_MACIER_LPIIE );
}
/**
* @brief Returns the ETH MAC LPI event
* @param heth: pointer to a ETH_HandleTypeDef structure that contains
* the configuration information for ETHERNET module
* @retval ETH MAC WakeUp event
*/
uint32_t HAL_ETHEx_GetMACLPIEvent( const ETH_HandleTypeDef * heth )
{
return heth->MACLPIEvent;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ETH */
#endif /* HAL_ETH_MODULE_ENABLED */
/**
* @}
*/
@@ -0,0 +1,400 @@
/**
******************************************************************************
* @file stm32h7xx_hal_eth_ex.h
* @author MCD Application Team
* @brief Header file of ETH HAL Extended module.
******************************************************************************
* @attention
*
* Copyright (c) 2017 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32H7xx_HAL_ETH_EX_H
#define STM32H7xx_HAL_ETH_EX_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined( ETH )
/* Includes ------------------------------------------------------------------*/
#include "stm32h7xx_hal_def.h"
/** @addtogroup STM32H7xx_HAL_Driver
* @{
*/
/** @addtogroup ETHEx
* @{
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup ETHEx_Exported_Types ETHEx Exported Types
* @{
*/
/**
* @brief ETH RX VLAN structure definition
*/
typedef struct
{
FunctionalState InnerVLANTagInStatus; /*!< Enables or disables Inner VLAN Tag in Rx Status */
uint32_t StripInnerVLANTag; /*!< Sets the Inner VLAN Tag Stripping on Receive
* This parameter can be a value of
* @ref ETHEx_Rx_Inner_VLAN_Tag_Stripping */
FunctionalState InnerVLANTag; /*!< Enables or disables Inner VLAN Tag */
FunctionalState DoubleVLANProcessing; /*!< Enable or Disable double VLAN processing */
FunctionalState VLANTagHashTableMatch; /*!< Enable or Disable VLAN Tag Hash Table Match */
FunctionalState VLANTagInStatus; /*!< Enable or Disable VLAN Tag in Rx status */
uint32_t StripVLANTag; /*!< Set the VLAN Tag Stripping on Receive
* This parameter can be a value of @ref ETHEx_Rx_VLAN_Tag_Stripping */
uint32_t VLANTypeCheck; /*!< Enable or Disable VLAN Type Check
* This parameter can be a value of @ref ETHEx_VLAN_Type_Check */
FunctionalState VLANTagInverceMatch; /*!< Enable or disable VLAN Tag Inverse Match */
} ETH_RxVLANConfigTypeDef;
/**
*
*/
/**
* @brief ETH TX VLAN structure definition
*/
typedef struct
{
FunctionalState SourceTxDesc; /*!< Enable or Disable VLAN tag source from DMA tx descriptors */
FunctionalState SVLANType; /*!< Enable or Disable insertion of SVLAN type */
uint32_t VLANTagControl; /*!< Sets the VLAN tag control in tx packets
* This parameter can be a value of @ref ETHEx_VLAN_Tag_Control */
} ETH_TxVLANConfigTypeDef;
/**
*
*/
/**
* @brief ETH L3 filter structure definition
*/
typedef struct
{
uint32_t Protocol; /*!< Sets the L3 filter protocol to IPv4 or IPv6
* This parameter can be a value of @ref ETHEx_L3_Protocol */
uint32_t SrcAddrFilterMatch; /*!< Sets the L3 filter source address match
* This parameter can be a value of @ref ETHEx_L3_Source_Match */
uint32_t DestAddrFilterMatch; /*!< Sets the L3 filter destination address match
* This parameter can be a value of @ref ETHEx_L3_Destination_Match */
uint32_t SrcAddrHigherBitsMatch; /*!< Sets the L3 filter source address higher bits match
* This parameter can be a value from 0 to 31 */
uint32_t DestAddrHigherBitsMatch; /*!< Sets the L3 filter destination address higher bits match
* This parameter can be a value from 0 to 31 */
uint32_t Ip4SrcAddr; /*!< Sets the L3 filter IPv4 source address if IPv4 protocol is used
* This parameter can be a value from 0x0 to 0xFFFFFFFF */
uint32_t Ip4DestAddr; /*!< Sets the L3 filter IPv4 destination address if IPv4 protocol is used
* This parameter can be a value from 0 to 0xFFFFFFFF */
uint32_t Ip6Addr[ 4 ]; /*!< Sets the L3 filter IPv6 address if IPv6 protocol is used
* This parameter must be a table of 4 words (4* 32 bits) */
} ETH_L3FilterConfigTypeDef;
/**
*
*/
/**
* @brief ETH L4 filter structure definition
*/
typedef struct
{
uint32_t Protocol; /*!< Sets the L4 filter protocol to TCP or UDP
* This parameter can be a value of @ref ETHEx_L4_Protocol */
uint32_t SrcPortFilterMatch; /*!< Sets the L4 filter source port match
* This parameter can be a value of @ref ETHEx_L4_Source_Match */
uint32_t DestPortFilterMatch; /*!< Sets the L4 filter destination port match
* This parameter can be a value of @ref ETHEx_L4_Destination_Match */
uint32_t SourcePort; /*!< Sets the L4 filter source port
* This parameter must be a value from 0x0 to 0xFFFF */
uint32_t DestinationPort; /*!< Sets the L4 filter destination port
* This parameter must be a value from 0x0 to 0xFFFF */
} ETH_L4FilterConfigTypeDef;
/**
*
*/
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup ETHEx_Exported_Constants ETHEx Exported Constants
* @{
*/
/** @defgroup ETHEx_LPI_Event ETHEx LPI Event
* @{
*/
#define ETH_TX_LPI_ENTRY ETH_MACLCSR_TLPIEN
#define ETH_TX_LPI_EXIT ETH_MACLCSR_TLPIEX
#define ETH_RX_LPI_ENTRY ETH_MACLCSR_RLPIEN
#define ETH_RX_LPI_EXIT ETH_MACLCSR_RLPIEX
/**
* @}
*/
/** @defgroup ETHEx_L3_Filter ETHEx L3 Filter
* @{
*/
#define ETH_L3_FILTER_0 0x00000000U
#define ETH_L3_FILTER_1 0x0000000CU
/**
* @}
*/
/** @defgroup ETHEx_L4_Filter ETHEx L4 Filter
* @{
*/
#define ETH_L4_FILTER_0 0x00000000U
#define ETH_L4_FILTER_1 0x0000000CU
/**
* @}
*/
/** @defgroup ETHEx_L3_Protocol ETHEx L3 Protocol
* @{
*/
#define ETH_L3_IPV6_MATCH ETH_MACL3L4CR_L3PEN
#define ETH_L3_IPV4_MATCH 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L3_Source_Match ETHEx L3 Source Match
* @{
*/
#define ETH_L3_SRC_ADDR_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L3SAM
#define ETH_L3_SRC_ADDR_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L3SAM | ETH_MACL3L4CR_L3SAIM )
#define ETH_L3_SRC_ADDR_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L3_Destination_Match ETHEx L3 Destination Match
* @{
*/
#define ETH_L3_DEST_ADDR_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L3DAM
#define ETH_L3_DEST_ADDR_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L3DAM | ETH_MACL3L4CR_L3DAIM )
#define ETH_L3_DEST_ADDR_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L4_Protocol ETHEx L4 Protocol
* @{
*/
#define ETH_L4_UDP_MATCH ETH_MACL3L4CR_L4PEN
#define ETH_L4_TCP_MATCH 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L4_Source_Match ETHEx L4 Source Match
* @{
*/
#define ETH_L4_SRC_PORT_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L4SPM
#define ETH_L4_SRC_PORT_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L4SPM | ETH_MACL3L4CR_L4SPIM )
#define ETH_L4_SRC_PORT_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_L4_Destination_Match ETHEx L4 Destination Match
* @{
*/
#define ETH_L4_DEST_PORT_PERFECT_MATCH_ENABLE ETH_MACL3L4CR_L4DPM
#define ETH_L4_DEST_PORT_INVERSE_MATCH_ENABLE ( ETH_MACL3L4CR_L4DPM | ETH_MACL3L4CR_L4DPIM )
#define ETH_L4_DEST_PORT_MATCH_DISABLE 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_Rx_Inner_VLAN_Tag_Stripping ETHEx Rx Inner VLAN Tag Stripping
* @{
*/
#define ETH_INNERVLANTAGRXSTRIPPING_NONE ETH_MACVTR_EIVLS_DONOTSTRIP
#define ETH_INNERVLANTAGRXSTRIPPING_IFPASS ETH_MACVTR_EIVLS_STRIPIFPASS
#define ETH_INNERVLANTAGRXSTRIPPING_IFFAILS ETH_MACVTR_EIVLS_STRIPIFFAILS
#define ETH_INNERVLANTAGRXSTRIPPING_ALWAYS ETH_MACVTR_EIVLS_ALWAYSSTRIP
/**
* @}
*/
/** @defgroup ETHEx_Rx_VLAN_Tag_Stripping ETHEx Rx VLAN Tag Stripping
* @{
*/
#define ETH_VLANTAGRXSTRIPPING_NONE ETH_MACVTR_EVLS_DONOTSTRIP
#define ETH_VLANTAGRXSTRIPPING_IFPASS ETH_MACVTR_EVLS_STRIPIFPASS
#define ETH_VLANTAGRXSTRIPPING_IFFAILS ETH_MACVTR_EVLS_STRIPIFFAILS
#define ETH_VLANTAGRXSTRIPPING_ALWAYS ETH_MACVTR_EVLS_ALWAYSSTRIP
/**
* @}
*/
/** @defgroup ETHEx_VLAN_Type_Check ETHEx VLAN Type Check
* @{
*/
#define ETH_VLANTYPECHECK_DISABLE ETH_MACVTR_DOVLTC
#define ETH_VLANTYPECHECK_SVLAN ( ETH_MACVTR_ERSVLM | ETH_MACVTR_ESVL )
#define ETH_VLANTYPECHECK_CVLAN 0x00000000U
/**
* @}
*/
/** @defgroup ETHEx_VLAN_Tag_Control ETHEx_VLAN_Tag_Control
* @{
*/
#define ETH_VLANTAGCONTROL_NONE ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_NOVLANTAG )
#define ETH_VLANTAGCONTROL_DELETE ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_VLANTAGDELETE )
#define ETH_VLANTAGCONTROL_INSERT ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_VLANTAGINSERT )
#define ETH_VLANTAGCONTROL_REPLACE ( ETH_MACVIR_VLP | ETH_MACVIR_VLC_VLANTAGREPLACE )
/**
* @}
*/
/** @defgroup ETHEx_Tx_VLAN_Tag ETHEx Tx VLAN Tag
* @{
*/
#define ETH_INNER_TX_VLANTAG 0x00000001U
#define ETH_OUTER_TX_VLANTAG 0x00000000U
/**
* @}
*/
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup ETHEx_Exported_Functions
* @{
*/
/** @addtogroup ETHEx_Exported_Functions_Group1
* @{
*/
/* MAC ARP Offloading APIs ***************************************************/
void HAL_ETHEx_EnableARPOffload( ETH_HandleTypeDef * heth );
void HAL_ETHEx_DisableARPOffload( ETH_HandleTypeDef * heth );
void HAL_ETHEx_SetARPAddressMatch( ETH_HandleTypeDef * heth,
uint32_t IpAddress );
/* MAC L3 L4 Filtering APIs ***************************************************/
void HAL_ETHEx_EnableL3L4Filtering( ETH_HandleTypeDef * heth );
void HAL_ETHEx_DisableL3L4Filtering( ETH_HandleTypeDef * heth );
HAL_StatusTypeDef HAL_ETHEx_GetL3FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L3FilterConfigTypeDef * pL3FilterConfig );
HAL_StatusTypeDef HAL_ETHEx_GetL4FilterConfig( const ETH_HandleTypeDef * heth,
uint32_t Filter,
ETH_L4FilterConfigTypeDef * pL4FilterConfig );
HAL_StatusTypeDef HAL_ETHEx_SetL3FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L3FilterConfigTypeDef * pL3FilterConfig );
HAL_StatusTypeDef HAL_ETHEx_SetL4FilterConfig( ETH_HandleTypeDef * heth,
uint32_t Filter,
const ETH_L4FilterConfigTypeDef * pL4FilterConfig );
/* MAC VLAN Processing APIs ************************************************/
void HAL_ETHEx_EnableVLANProcessing( ETH_HandleTypeDef * heth );
void HAL_ETHEx_DisableVLANProcessing( ETH_HandleTypeDef * heth );
HAL_StatusTypeDef HAL_ETHEx_GetRxVLANConfig( const ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig );
HAL_StatusTypeDef HAL_ETHEx_SetRxVLANConfig( ETH_HandleTypeDef * heth,
ETH_RxVLANConfigTypeDef * pVlanConfig );
void HAL_ETHEx_SetVLANHashTable( ETH_HandleTypeDef * heth,
uint32_t VLANHashTable );
HAL_StatusTypeDef HAL_ETHEx_GetTxVLANConfig( const ETH_HandleTypeDef * heth,
uint32_t VLANTag,
ETH_TxVLANConfigTypeDef * pVlanConfig );
HAL_StatusTypeDef HAL_ETHEx_SetTxVLANConfig( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
const ETH_TxVLANConfigTypeDef * pVlanConfig );
void HAL_ETHEx_SetTxVLANIdentifier( ETH_HandleTypeDef * heth,
uint32_t VLANTag,
uint32_t VLANIdentifier );
/* Energy Efficient Ethernet APIs *********************************************/
void HAL_ETHEx_EnterLPIMode( ETH_HandleTypeDef * heth,
FunctionalState TxAutomate,
FunctionalState TxClockStop );
void HAL_ETHEx_ExitLPIMode( ETH_HandleTypeDef * heth );
uint32_t HAL_ETHEx_GetMACLPIEvent( const ETH_HandleTypeDef * heth );
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* ETH */
#ifdef __cplusplus
}
#endif
#endif /* STM32H7xx_HAL_ETH_EX_H */
@@ -0,0 +1,25 @@
if (NOT ( (FREERTOS_PLUS_TCP_NETWORK_IF STREQUAL "STM32FXX") ) )
return()
endif()
#------------------------------------------------------------------------------
add_library( freertos_plus_tcp_network_if STATIC )
target_sources( freertos_plus_tcp_network_if
PRIVATE
NetworkInterface.c
# stm32f2xx_hal_eth.h
# stm32f4xx_hal_eth.h
stm32f7xx_hal_eth.h # Only one of these ?
stm32fxx_hal_eth.c
stm32fxx_hal_eth.h
)
target_link_libraries( freertos_plus_tcp_network_if
PUBLIC
freertos_plus_tcp_port
freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
@@ -0,0 +1,140 @@
This is a FreeRTOS+TCP driver that works for STM32Fxx parts.
CONFIGURATION AND RUNNING
=========================
The code of stm32fxx_hal_eth.c is based on the ETH drivers as provided by ST.
These modules should be included:
- portable/NetworkInterface/STM32Fxx/NetworkInterface.c
- portable/NetworkInterface/STM32Fxx/stm32fxx_hal_eth.c
When initialising the EMAC, the driver will call the function `HAL_ETH_MspInit()`, which should do the following:
- Enable the Ethernet interface clock using:
```cpp
__HAL_RCC_ETHMAC_CLK_ENABLE();
__HAL_RCC_ETHMACTX_CLK_ENABLE();
__HAL_RCC_ETHMACRX_CLK_ENABLE();
```
- Initialize the related GPIO clocks
- Configure Ethernet pin-out
Please check the schematic of your hardware to see which pins are used.
Also check if either MII or RMII is used ( define `ipconfigUSE_RMII`
as 0 or 1 ).
- Configure Ethernet NVIC interrupt (IT mode)
Choose a proper interrupt priority, defined in FreeRTOSIPConfig.h as e.g. :
```cpp
#define ipconfigMAC_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY )
```
The function `HAL_ETH_MspInit()` must be provided by the application. Make sure that your copy of the function is called,
and not a dummy defined as "weak".
It is assumed that one of these macros is defined at the highest level:
STM32F1xx
STM32F2xx
STM32F4xx
STM32F7xx
For instance, you can pass it to the compiler with the `-D` option:
gcc ... -D STM32F4xx=1
And sub-models may also be indicated, such as `STM32F401xC` or `STM32F407xx`.
The driver has been tested on both Eval and Discovery boards with STM32F1, STM32F2, STM32F4 and STM32F7. The F1 and F2 boards
have only be tested by customers who reported about it on the FreeRTOS forum.
Note that it is required to define `HAL_ETH_MODULE_ENABLED` in your STM32 configuration file. The name of this file is one out
of:
stm32f1xx_hal_conf.h
stm32f2xx_hal_conf.h
stm32f4xx_hal_conf.h
stm32f7xx_hal_conf.h
This configuration file defines the HAL modules that will be used. Here are some examples of the module macros:
~~~c
#define HAL_MODULE_ENABLED
#define HAL_ETH_MODULE_ENABLED /* <= this one is needed to get Ethernet. */
#define HAL_SRAM_MODULE_ENABLED
#define HAL_RNG_MODULE_ENABLED
#define HAL_RTC_MODULE_ENABLED
/* etc. */
~~~
Recommended settings for STM32Fxx Network Interface:
**Defined in FreeRTOSIPConfig.h**
```cpp
#define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES 1
#define ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM 1
#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM 1
#define ipconfigZERO_COPY_RX_DRIVER 1
#define ipconfigZERO_COPY_TX_DRIVER 1
#define ipconfigUSE_LINKED_RX_MESSAGES 1
#define ipconfigSUPPORT_NETWORK_DOWN_EVENT 1
```
**Defined in stm32f4xx_hal_conf.h**
```cpp
#define ETH_RXBUFNB 3 or 4
#define ETH_TXBUFNB 1 or 2
#define ETH_RX_BUF_SIZE ( ipconfigNETWORK_MTU + 36 )
#define ETH_TX_BUF_SIZE ( ipconfigNETWORK_MTU + 36 )
```
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. In general, if the CPU is very fast, you will need less buffers. You can obtain an estimate
empirically.
The optimal value of `ETH_RX_BUF_SIZE` and `ETH_TX_BUF_SIZE` depends on the actual value of `ipconfigNETWORK_MTU`.
When MTU is 1500, MTU+36 becomes a well-aligned buffer of 1536 bytes ( 0x600 ).
When MTU is 1200, MTU+48 will make 1248 ( 0x4E0 ), which is also well aligned.
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.
Without memory caching, let the size be at least a multiple of 8 ( for DMA ), and make it at least "ipconfigNETWORK_MTU + 14".
STM32F7xx only:
NetworkInterface.c will place the 2 DMA tables in a special section called 'first_data'.
In case 'BufferAllocation_1.c' is used, the network packets will also be declared in this section 'first_data'.
As long as the part has no caching, this section can be placed anywhere in RAM.
On an STM32F7 with an L1 data cache, it shall be placed in the first 64KB of RAM, which is always uncached.
The linker script must be changed for this, for instance as follows:
```assembly
.data :
{
. = ALIGN(4);
_sdata = .; // create a global symbol at data start
+ *(.first_data) // .first_data sections
*(.data) // .data sections
*(.data*) // .data* sections
. = ALIGN(4);
_edata = .; // define a global symbol at data end
} >RAM AT> FLASH
```
The driver contains these files:
- NetworkInterface.c
- stm32fxx_hal_eth.c
- stm32f2xx_hal_eth.h
- stm32f4xx_hal_eth.h
- stm32f7xx_hal_eth.h
- stm32fxx_hal_eth.h
These files are copied from ST's HAL library. These work both for STM32F4 and STM32F7.
Please remove or rename these files from the HAL distribution that you are using.
@@ -0,0 +1,6 @@
/*
* The Ethernet header files for STM32F2, STM32F4 and STM32F7 have been merged to
* a single module that works for both parts: "stm32fxx_hal_eth"
*/
#include "stm32fxx_hal_eth.h"
@@ -0,0 +1,6 @@
/*
* The Ethernet header files for STM32F2, STM32F4 and STM32F7 have been merged to
* a single module that works for both parts: "stm32fxx_hal_eth"
*/
#include "stm32fxx_hal_eth.h"
@@ -0,0 +1,6 @@
/*
* The Ethernet header files for STM32F2, STM32F4 and STM32F7 have been merged to
* a single module that works for both parts: "stm32fxx_hal_eth"
*/
#include "stm32fxx_hal_eth.h"
@@ -0,0 +1,23 @@
if (NOT ( (FREERTOS_PLUS_TCP_NETWORK_IF STREQUAL "STM32HXX") ) )
return()
endif()
#------------------------------------------------------------------------------
add_library( freertos_plus_tcp_network_if STATIC )
target_sources( freertos_plus_tcp_network_if
PRIVATE
NetworkInterface.c
stm32h7xx_hal_eth.h
stm32hxx_hal_eth.c
stm32hxx_hal_eth.h
)
target_link_libraries( freertos_plus_tcp_network_if
PUBLIC
freertos_plus_tcp_port
freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
@@ -0,0 +1,127 @@
FreeRTOS+TCP driver for STM32H7xx.
Some STM32 network settings are stored in 'stm32h7xx_hal_conf.h'.
Number of DMA descriptors, for transmission and for reception.
The descriptors for transmission are protected with a counting semaphore.
By the time that a packet has been sent, the other TX descriptor becomes
available already.
The number of descriptors has an influence on the performance. But that also depends on the size
of the TCP buffers and TCP window sizes.
When ETH_RX_DESC_CNT is too low, the adapter may miss incoming packets, they will be dropped.
When ETH_RX_DESC_CNT is low, sending packets becomes slower.
Here are settings give a high performance for iperf3:
~~~
/* ########################### Ethernet Configuration ######################### */
#define ETH_TX_DESC_CNT 14U /* number of Ethernet Tx DMA descriptors */
#define ETH_RX_DESC_CNT 8U /* number of Ethernet Rx DMA descriptors */
~~~
Two more defines that are needed:
~~~
#define HAL_ETH_MODULE_ENABLED
#define USE_HAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */
~~~
The following macro's are **not** used by the FreeRTOS driver:
#define ETH_MAC_ADDR0 ((uint8_t)0x02)
#define ETH_MAC_ADDR1 ((uint8_t)0x00)
...
All memory that is shared between the CPU and the DMA ETH peripheral, should be
located in special RAM area called ".ethernet_data". This shall be declared in
the linker file (.ld).
It is possible to use the AXI SRAM for this, but RAM{1,2,3} are also connected
to the Ethernet MAC.
Here is an example of the changes to the linker file:
RAM_D1 (xrw) : ORIGIN = 0x24000000, LENGTH = 512K /* should already exist in MEMORY section */
.ethernet_data : /* inside SECTIONS section, before /DISCARD/ */
{
PROVIDE_HIDDEN (__ethernet_data_start = .);
KEEP (*(SORT(.ethernet_data.*)))
KEEP (*(.ethernet_data*))
PROVIDE_HIDDEN (__ethernet_data_end = .);
} >RAM_D1
Here is a table of 3 types of STH32H7 :
|RAM area |H747|H743|H742|Location |
|-----------|----|----|----|----------|
|DTCM |128k|128k|128k|0x20000000|
|AXI-SRAM |511k|511k|384k|0x24000000|
|SRAM1 |128k|128k|32k |0x30000000|
|SRAM2 |128k|128k|16k |0x30020000|
|SRAM3 |32k | 32k| - |0x30040000|
|SRAM4 |64k |64k |64k |0x38000000|
|Backup SRAM|4k |4k |4k |0x38800000|
Please make sure that the addresses and lengths are correct for your model of STM32H7xx.
If you use a memory that is not supported, it will result in a DMA errors.
Don't redefine a new memory area (like AXI-SRAM, RAM_D1) if it already exists in the
MEMORY section, just take note of it's name for defining the section .ethernet_data later
in that same file.
In FreeRTOSIPConfig.h :
Define the total number of network buffer descriptors, e.g. 64:
~~~
#define ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ( 64 )
~~~
It is recommended to use the zero-copy method for both reception and transmission:
~~~
#define ipconfigZERO_COPY_RX_DRIVER ( 1 )
#define ipconfigZERO_COPY_TX_DRIVER ( 1 )
~~~
The copy-method also works well, may just a little slower.
Checksum cal be calculated in the Ethernet MAC, which is faster than doing manual calculations:
~~~
/* The checksums will be checked and calculated by the STM32F4x ETH peripheral. */
#define ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM ( 1 )
#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM ( 1 )
~~~
The most important DMAC registers, along with their names which are used in the reference manual:
__IO uint32_t DMAMR; // ETH_DMAMR DMA mode register
__IO uint32_t DMAISR; // ETH_DMAISR DMA Interrupt status register
__IO uint32_t DMADSR; // ETH_DMADSR DMA Debug status register
__IO uint32_t DMACCR; // ETH_DMACCR DMA Channel control register
__IO uint32_t DMACTCR; // ETH_DMACTXCR Channel Tx transmit control register
__IO uint32_t DMACRCR; // ETH_DMACRXCR Channel Rx receive control register
__IO uint32_t DMACTDLAR; // ETH_DMACTXDLAR Channel Tx descriptor list address register
__IO uint32_t DMACRDLAR; // ETH_DMACRXDLAR Channel Rx descriptor list address register
__IO uint32_t DMACTDTPR; // ETH_DMACTXDTPR Channel TX tail pointer
__IO uint32_t DMACRDTPR; // ETH_DMACRXDTPR Channel RX tail pointer
__IO uint32_t DMACTDRLR; // ETH_DMACTXRLR Channel Tx descriptor ring length register
__IO uint32_t DMACRDRLR; // ETH_DMACRXRLR Channel Rx descriptor ring length register
__IO uint32_t DMACIER; // ETH_DMACIER Channel interrupt enable register
__IO uint32_t DMACRIWTR; // ETH_DMACRXIWTR Channel Rx interrupt watchdog timer register
__IO uint32_t DMACCATDR; // ETH_DMACCATXDR Channel Tx current application transmit descriptor register
__IO uint32_t DMACCARDR; // ETH_DMACCARXDR Channel Rx current application receive descriptor register
__IO uint32_t DMACCATBR; // ETH_DMACCATXBR Channel Tx current application transmit buffer register
__IO uint32_t DMACCARBR; // ETH_DMACCARXBR Channel Rx current application receive buffer register
__IO uint32_t DMACSR; // ETH_DMACSR Channel status register
As most EMAC's, the STM32H7 EMAC is able to put packets in multiple linked DMA segments.
FreeRTOS+TCP never uses this feature. Each packet is stored in a single buffer called
`NetworkBufferDescriptor_t`.
@@ -0,0 +1,6 @@
/*
* The Ethernet header files for STM32F2, STM32F4 and STM32F7 have been merged to
* a single module that works for both parts: "stm32hxx_hal_eth"
*/
#include "stm32hxx_hal_eth.h"
@@ -0,0 +1,25 @@
if (NOT ( (FREERTOS_PLUS_TCP_NETWORK_IF STREQUAL "WIN_PCAP") ) )
return()
endif()
find_package(PCAP REQUIRED)
#------------------------------------------------------------------------------
add_library( freertos_plus_tcp_network_if STATIC )
target_sources( freertos_plus_tcp_network_if
PRIVATE
FaultInjection.c
NetworkInterface.c
)
target_link_libraries( freertos_plus_tcp_network_if
PUBLIC
freertos_plus_tcp_port
freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
${PCAP_LIBRARY}
)
@@ -0,0 +1,188 @@
#define xBUFFER_CACHE_SIZE 10
#define xMAX_FAULT_INJECTION_RATE 15
#define xMIN_FAULT_INJECTION_RATE 3
#define xNUM_FAULT_TYPES 1
static NetworkBufferDescriptor_t * xNetworkBufferCache[ xBUFFER_CACHE_SIZE ] = { 0 };
#define xFAULT_LOG_SIZE 2048
uint32_t ulInjectedFault[ xFAULT_LOG_SIZE ];
uint32_t ulFaultLogIndex = 0;
static BaseType_t prvCachePacket( NetworkBufferDescriptor_t * pxNetworkBufferIn )
{
BaseType_t x, xReturn = pdFALSE;
for( x = 0; x < xBUFFER_CACHE_SIZE; x++ )
{
if( xNetworkBufferCache[ x ] == NULL )
{
xNetworkBufferCache[ x ] = pxNetworkBufferIn;
xReturn = pdTRUE;
break;
}
}
return xReturn;
}
/*-----------------------------------------------------------*/
static NetworkBufferDescriptor_t * prvGetCachedPacket( void )
{
BaseType_t x;
NetworkBufferDescriptor_t * pxReturn = NULL;
for( x = ( xBUFFER_CACHE_SIZE - 1 ); x >= 0; x-- )
{
if( xNetworkBufferCache[ x ] != NULL )
{
pxReturn = xNetworkBufferCache[ x ];
xNetworkBufferCache[ x ] = NULL;
break;
}
}
return pxReturn;
}
/*-----------------------------------------------------------*/
static NetworkBufferDescriptor_t * prvDuplicatePacket( NetworkBufferDescriptor_t * pxOriginalPacket,
const uint8_t * pucPacketData )
{
NetworkBufferDescriptor_t * pxReturn;
/* Obtain a new descriptor. */
pxReturn = pxGetNetworkBufferWithDescriptor( pxOriginalPacket->xDataLength, 0 );
if( pxReturn != NULL )
{
/* Copy in the packet data. */
pxReturn->xDataLength = pxOriginalPacket->xDataLength;
memcpy( pxReturn->pucEthernetBuffer, pucPacketData, pxOriginalPacket->xDataLength );
}
return pxReturn;
}
/*-----------------------------------------------------------*/
static NetworkBufferDescriptor_t * prvRxFaultInjection( NetworkBufferDescriptor_t * pxNetworkBufferIn,
const uint8_t * pucPacketData )
{
static uint32_t ulCallCount = 0, ulNextFaultCallCount = 0;
NetworkBufferDescriptor_t * pxReturn = pxNetworkBufferIn;
IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };
uint32_t ulFault;
return pxNetworkBufferIn;
ulCallCount++;
if( ulCallCount > ulNextFaultCallCount )
{
xApplicationGetRandomNumber( &( ulNextFaultCallCount ) );
ulNextFaultCallCount = ulNextFaultCallCount % xMAX_FAULT_INJECTION_RATE;
if( ulNextFaultCallCount < xMIN_FAULT_INJECTION_RATE )
{
ulNextFaultCallCount = xMIN_FAULT_INJECTION_RATE;
}
ulCallCount = 0;
xApplicationGetRandomNumber( &( ulFault ) );
ulFault = ulFault % xNUM_FAULT_TYPES;
if( ulFaultLogIndex < xFAULT_LOG_SIZE )
{
ulInjectedFault[ ulFaultLogIndex ] = ulFault;
ulFaultLogIndex++;
}
switch( ulFault )
{
case 0:
/* Just drop the packet. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBufferIn );
pxReturn = NULL;
break;
case 1:
/* Store the packet in the cache for later. */
if( prvCachePacket( pxNetworkBufferIn ) == pdTRUE )
{
/* The packet may get sent later, it is not being sent
* now. */
pxReturn = NULL;
}
break;
case 2:
/* Send a cached packet. */
pxReturn = prvGetCachedPacket();
if( pxReturn != NULL )
{
/* A cached packet was obtained so drop the original
* packet. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBufferIn );
}
else
{
/* Could not obtain a packet from the cache so just return
* the packet that was passed in. */
pxReturn = pxNetworkBufferIn;
}
break;
case 4:
/* Send a duplicate of the packet right away. */
pxReturn = prvDuplicatePacket( pxNetworkBufferIn, pucPacketData );
/* Send the original packet to the stack. */
xRxEvent.pvData = ( void * ) pxNetworkBufferIn;
if( xSendEventStructToIPTask( &xRxEvent, ( TickType_t ) 0 ) == pdFAIL )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBufferIn );
}
break;
case 5:
/* Send both a cached packet and the current packet. */
xRxEvent.pvData = ( void * ) prvGetCachedPacket();
if( xRxEvent.pvData != NULL )
{
if( xSendEventStructToIPTask( &xRxEvent, ( TickType_t ) 0 ) == pdFAIL )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBufferIn );
}
}
break;
case 6:
case 7:
case 8:
/* Store the packet in the cache for later. */
if( prvCachePacket( pxNetworkBufferIn ) == pdTRUE )
{
/* The packet may get sent later, it is not being sent
* now. */
pxReturn = NULL;
}
break;
}
}
return pxReturn;
}
/*-----------------------------------------------------------*/
@@ -0,0 +1,984 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
#include <stdlib.h>
/* WinPCap includes. */
#define HAVE_REMOTE
#include "pcap.h"
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_IP.h"
#include "FreeRTOS_IP_Private.h"
#include "NetworkBufferManagement.h"
#include "FreeRTOS_Routing.h"
/* Thread-safe circular buffers are being used to pass data to and from the PCAP
* access functions. */
#include "Win32-Extensions.h"
#include "FreeRTOS_Stream_Buffer.h"
/* Sizes of the thread safe circular buffers used to pass data to and from the
* WinPCAP Windows threads. */
#define xSEND_BUFFER_SIZE 32768
#define xRECV_BUFFER_SIZE 32768
/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1, then the Ethernet
* driver will filter incoming packets and only pass the stack those packets it
* considers need processing. */
#if ( ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES == 0 )
#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eProcessBuffer
#else
#define ipCONSIDER_FRAME_FOR_PROCESSING( pucEthernetBuffer ) eConsiderFrameForProcessing( ( pucEthernetBuffer ) )
#endif
/* Used to insert test code only. */
#define niDISRUPT_PACKETS 0
/*-----------------------------------------------------------*/
/*
* Windows threads that are outside of the control of the FreeRTOS simulator are
* used to interface with the WinPCAP libraries.
*/
DWORD WINAPI prvWinPcapRecvThread( void * pvParam );
DWORD WINAPI prvWinPcapSendThread( void * pvParam );
/*
* A pointer to the network interface is needed later when receiving packets.
*/
static NetworkInterface_t * pxMyInterface;
/*
* Print out a numbered list of network interfaces that are available on the
* host computer.
*/
static pcap_if_t * prvPrintAvailableNetworkInterfaces( void );
/*
* Open the network interface. The number of the interface to be opened is set
* by the configNETWORK_INTERFACE_TO_USE constant in FreeRTOSConfig.h.
*/
static void prvOpenSelectedNetworkInterface( pcap_if_t * pxAllNetworkInterfaces,
const NetworkInterface_t * pxInterface );
static int prvOpenInterface( const char * pucName,
const NetworkInterface_t * pxInterface );
/*
* Configure the capture filter to allow blocking reads, and to filter out
* packets that are not of interest to this demo.
*/
static void prvConfigureCaptureBehaviour( const NetworkInterface_t * pxInterface );
/*
* A function that simulates Ethernet interrupts by periodically polling the
* WinPCap interface for new data.
*/
static void prvInterruptSimulatorTask( void * pvParameters );
/*
* Create the buffers that are used to pass data between the FreeRTOS simulator
* and the Win32 threads that manage WinPCAP.
*/
static void prvCreateThreadSafeBuffers( void );
/*
* This function is equivalent to uxStreamBufferAdd from
* FreeRTOS_Stream_Buffer.c in the case that the stream buffer is being used
* as a normal circular buffer (i.e. only the tail and head pointers are
* needed). Thus, this function does not take the offset argument, and does not
* update the front pointer of the stream buffer. This allows the removal of
* the calls to vTaskSuspendAll and xTaskResumeAll, as the head and front
* pointer no longer need to be atomically updated, allowing this function to be
* safely used by a Windows thread.
*/
static size_t prvStreamBufferAdd( StreamBuffer_t * pxBuffer,
const uint8_t * pucData,
size_t uxByteCount );
/*
* Utility function used to format print messages only.
*/
static const char * prvRemoveSpaces( char * pcBuffer,
int aBuflen,
const char * pcMessage );
/*
* This function will return pdTRUE if the packet is targeted at
* the MAC address of this device, in other words when is was bounced-
* back by the WinPCap interface.
*/
static BaseType_t xPacketBouncedBack( const uint8_t * pucBuffer );
/*-----------------------------------------------------------*/
/* Required by the WinPCap library. */
static char cErrorBuffer[ PCAP_ERRBUF_SIZE ];
/* An event used to wake up the Win32 thread that sends data through the WinPCAP
* library. */
static void * pvSendEvent = NULL;
/* _HT_ made the PCAP interface number configurable through the program's
* parameters in order to test in different machines. */
static BaseType_t xConfigNetworkInterfaceToUse = configNETWORK_INTERFACE_TO_USE;
/* Handles to the Windows threads that handle the PCAP IO. */
static HANDLE vWinPcapRecvThreadHandle = NULL;
static HANDLE vWinPcapSendThreadHandle = NULL;
/* The interface being used by WinPCap. */
static pcap_t * pxOpenedInterfaceHandle = NULL;
/* Circular buffers used by the PCAP Win32 threads. */
static StreamBuffer_t * xSendBuffer = NULL;
static StreamBuffer_t * xRecvBuffer = NULL;
/* Logs the number of WinPCAP send failures, for viewing in the debugger only. */
static volatile uint32_t ulWinPCAPSendFailures = 0;
/*-----------------------------------------------------------*/
static BaseType_t xWinPcap_NetworkInterfaceInitialise( NetworkInterface_t * pxInterface );
static BaseType_t xWinPcap_NetworkInterfaceOutput( NetworkInterface_t * pxInterface,
NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t bReleaseAfterSend );
static BaseType_t xWinPcap_GetPhyLinkStatus( NetworkInterface_t * pxInterface );
NetworkInterface_t * pxWinPcap_FillInterfaceDescriptor( BaseType_t xEMACIndex,
NetworkInterface_t * pxInterface );
/*-----------------------------------------------------------*/
static BaseType_t xWinPcap_NetworkInterfaceInitialise( NetworkInterface_t * pxInterface )
{
BaseType_t xReturn = pdFALSE;
pcap_if_t * pxAllNetworkInterfaces;
( void ) pxInterface;
/* Query the computer the simulation is being executed on to find the
* network interfaces it has installed. */
pxAllNetworkInterfaces = prvPrintAvailableNetworkInterfaces();
/* Open the network interface. The number of the interface to be opened is
* set by the configNETWORK_INTERFACE_TO_USE constant in FreeRTOSConfig.h.
* Calling this function will set the pxOpenedInterfaceHandle variable. If,
* after calling this function, pxOpenedInterfaceHandle is equal to NULL, then
* the interface could not be opened. */
if( pxAllNetworkInterfaces != NULL )
{
prvOpenSelectedNetworkInterface( pxAllNetworkInterfaces, pxInterface );
}
if( pxOpenedInterfaceHandle != NULL )
{
xReturn = pdPASS;
}
return xReturn;
}
/*-----------------------------------------------------------*/
static void prvCreateThreadSafeBuffers( void )
{
/* The buffer used to pass data to be transmitted from a FreeRTOS task to
* the Win32 thread that sends via the WinPCAP library. */
if( xSendBuffer == NULL )
{
xSendBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xSendBuffer ) - sizeof( xSendBuffer->ucArray ) + xSEND_BUFFER_SIZE + 1 );
configASSERT( xSendBuffer );
memset( xSendBuffer, '\0', sizeof( *xSendBuffer ) - sizeof( xSendBuffer->ucArray ) );
xSendBuffer->LENGTH = xSEND_BUFFER_SIZE + 1;
}
/* The buffer used to pass received data from the Win32 thread that receives
* via the WinPCAP library to the FreeRTOS task. */
if( xRecvBuffer == NULL )
{
xRecvBuffer = ( StreamBuffer_t * ) malloc( sizeof( *xRecvBuffer ) - sizeof( xRecvBuffer->ucArray ) + xRECV_BUFFER_SIZE + 1 );
configASSERT( xRecvBuffer );
memset( xRecvBuffer, '\0', sizeof( *xRecvBuffer ) - sizeof( xRecvBuffer->ucArray ) );
xRecvBuffer->LENGTH = xRECV_BUFFER_SIZE + 1;
}
}
/*-----------------------------------------------------------*/
static size_t prvStreamBufferAdd( StreamBuffer_t * pxBuffer,
const uint8_t * pucData,
size_t uxByteCount )
{
size_t uxSpace, uxNextHead, uxFirst;
size_t uxCount = uxByteCount;
uxSpace = uxStreamBufferGetSpace( pxBuffer );
/* The number of bytes that can be written is the minimum of the number of
* bytes requested and the number available. */
uxCount = FreeRTOS_min_size_t( uxSpace, uxCount );
if( uxCount != 0U )
{
uxNextHead = pxBuffer->uxHead;
if( pucData != NULL )
{
/* Calculate the number of bytes that can be added in the first
* write - which may be less than the total number of bytes that need
* to be added if the buffer will wrap back to the beginning. */
uxFirst = FreeRTOS_min_size_t( pxBuffer->LENGTH - uxNextHead, uxCount );
/* Write as many bytes as can be written in the first write. */
( void ) memcpy( &( pxBuffer->ucArray[ uxNextHead ] ), pucData, uxFirst );
/* If the number of bytes written was less than the number that
* could be written in the first write... */
if( uxCount > uxFirst )
{
/* ...then write the remaining bytes to the start of the
* buffer. */
( void ) memcpy( pxBuffer->ucArray, &( pucData[ uxFirst ] ), uxCount - uxFirst );
}
}
uxNextHead += uxCount;
if( uxNextHead >= pxBuffer->LENGTH )
{
uxNextHead -= pxBuffer->LENGTH;
}
pxBuffer->uxHead = uxNextHead;
}
return uxCount;
}
/*-----------------------------------------------------------*/
static BaseType_t xWinPcap_NetworkInterfaceOutput( NetworkInterface_t * pxInterface,
NetworkBufferDescriptor_t * const pxNetworkBuffer,
BaseType_t bReleaseAfterSend )
{
size_t xSpace;
( void ) pxInterface;
iptraceNETWORK_INTERFACE_TRANSMIT();
configASSERT( xIsCallingFromIPTask() == pdTRUE );
/* Both the length of the data being sent and the actual data being sent
* are placed in the thread safe buffer used to pass data between the FreeRTOS
* tasks and the Win32 thread that sends data via the WinPCAP library. Drop
* the packet if there is insufficient space in the buffer to hold both. */
xSpace = uxStreamBufferGetSpace( xSendBuffer );
if( ( pxNetworkBuffer->xDataLength <= ( ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ) ) &&
( xSpace >= ( pxNetworkBuffer->xDataLength + sizeof( pxNetworkBuffer->xDataLength ) ) ) )
{
/* First write in the length of the data, then write in the data
* itself. */
uxStreamBufferAdd( xSendBuffer, 0, ( const uint8_t * ) &( pxNetworkBuffer->xDataLength ), sizeof( pxNetworkBuffer->xDataLength ) );
uxStreamBufferAdd( xSendBuffer, 0, ( const uint8_t * ) pxNetworkBuffer->pucEthernetBuffer, pxNetworkBuffer->xDataLength );
}
else
{
FreeRTOS_debug_printf( ( "xNetworkInterfaceOutput: send buffers full to store %lu\n", pxNetworkBuffer->xDataLength ) );
}
/* Kick the Tx task in either case in case it doesn't know the buffer is
* full. */
SetEvent( pvSendEvent );
/* The buffer has been sent so can be released. */
if( bReleaseAfterSend != pdFALSE )
{
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
}
return pdPASS;
}
/*-----------------------------------------------------------*/
static BaseType_t xWinPcap_GetPhyLinkStatus( NetworkInterface_t * pxInterface )
{
BaseType_t xResult = pdFALSE;
( void ) pxInterface;
if( pxOpenedInterfaceHandle != NULL )
{
xResult = pdTRUE;
}
return xResult;
}
/*-----------------------------------------------------------*/
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE != 0 )
/* Do not call the following function directly. It is there for downward compatibility.
* The function FreeRTOS_IPInit() will call it to initialice the interface and end-point
* objects. See the description in FreeRTOS_Routing.h. */
NetworkInterface_t * pxFillInterfaceDescriptor( BaseType_t xEMACIndex,
NetworkInterface_t * pxInterface )
{
return pxWinPcap_FillInterfaceDescriptor( xEMACIndex, pxInterface );
}
#endif
/*-----------------------------------------------------------*/
NetworkInterface_t * pxWinPcap_FillInterfaceDescriptor( BaseType_t xEMACIndex,
NetworkInterface_t * pxInterface )
{
static char pcName[ 17 ];
/* This function pxWinPcap_FillInterfaceDescriptor() adds a network-interface.
* Make sure that the object pointed to by 'pxInterface'
* is declared static or global, and that it will remain to exist. */
pxMyInterface = pxInterface;
snprintf( pcName, sizeof( pcName ), "eth%ld", xEMACIndex );
memset( pxInterface, '\0', sizeof( *pxInterface ) );
pxInterface->pcName = pcName; /* Just for logging, debugging. */
pxInterface->pvArgument = ( void * ) xEMACIndex; /* Has only meaning for the driver functions. */
pxInterface->pfInitialise = xWinPcap_NetworkInterfaceInitialise;
pxInterface->pfOutput = xWinPcap_NetworkInterfaceOutput;
pxInterface->pfGetPhyLinkStatus = xWinPcap_GetPhyLinkStatus;
FreeRTOS_AddNetworkInterface( pxInterface );
return pxInterface;
}
/*-----------------------------------------------------------*/
#ifdef configNETWORK_INTERFACE_TYPE_TO_USE
/* In earlier versions of this network interface,
* `configNETWORK_INTERFACE_TO_USE` indicated the interface
* sequence number to be used. On some laptops with dynamic
* adapters, the numbering of interfaces changes all the time.
* The new macro 'configNETWORK_INTERFACE_TYPE_TO_USE' can be
* used to define the name of the interface to use, e.g. "Realtek"
* Note that a sort of strcasestr() is used to find a match between
* an interface name and e.g. "Realtek".
*/
static BaseType_t xDesiredAdapter( const char * pcDescription )
{
size_t uxIndex;
size_t uxLength;
size_t uxKeyLength = strlen( configNETWORK_INTERFACE_TYPE_TO_USE );
BaseType_t xMatchFound = pdFALSE;
if( ( pcDescription != NULL ) && ( pcDescription[ 0 ] != 0 ) )
{
uxLength = strlen( pcDescription );
if( uxKeyLength <= uxLength )
{
for( uxIndex = 0U; ( uxIndex <= uxLength - uxKeyLength ) && ( xMatchFound == 0 ); uxIndex++ )
{
if( strncasecmp( configNETWORK_INTERFACE_TYPE_TO_USE, &( pcDescription[ uxIndex ] ), uxKeyLength ) == 0 )
{
xMatchFound = pdTRUE;
break;
}
}
}
}
return xMatchFound;
}
#endif /* ifdef configNETWORK_INTERFACE_TYPE_TO_USE */
/*-----------------------------------------------------------*/
static pcap_if_t * prvPrintAvailableNetworkInterfaces( void )
{
pcap_if_t * pxAllNetworkInterfaces = NULL, * xInterface;
int32_t lInterfaceNumber = 1;
char cBuffer[ 512 ];
static BaseType_t xInvalidInterfaceDetected = pdFALSE;
if( xInvalidInterfaceDetected == pdFALSE )
{
if( pcap_findalldevs_ex( PCAP_SRC_IF_STRING, NULL, &pxAllNetworkInterfaces, cErrorBuffer ) == -1 )
{
printf( "Could not obtain a list of network interfaces\n%s\n", cErrorBuffer );
pxAllNetworkInterfaces = NULL;
}
else
{
printf( "\r\n\r\nThe following network interfaces are available:\r\n\r\n" );
}
if( pxAllNetworkInterfaces != NULL )
{
/* Print out the list of network interfaces. The first in the list
* is interface '1', not interface '0'. */
for( xInterface = pxAllNetworkInterfaces; xInterface != NULL; xInterface = xInterface->next )
{
/* The descriptions of the devices can be full of spaces, clean them
* a little. printf() can only be used here because the network is not
* up yet - so no other network tasks will be running. */
printf( "Interface %d - %s\n", lInterfaceNumber, prvRemoveSpaces( cBuffer, sizeof( cBuffer ), xInterface->name ) );
printf( " (%s)\n", prvRemoveSpaces( cBuffer, sizeof( cBuffer ), xInterface->description ? xInterface->description : "No description" ) );
printf( "\n" );
#ifdef configNETWORK_INTERFACE_TYPE_TO_USE
{
if( xInterface->description != NULL )
{
if( xDesiredAdapter( xInterface->description ) )
{
printf( "The description of adapter %d matches with '%s'\n", lInterfaceNumber, configNETWORK_INTERFACE_TYPE_TO_USE );
xConfigNetworkInterfaceToUse = lInterfaceNumber;
}
}
}
#endif /* ifdef configNETWORK_INTERFACE_TYPE_TO_USE */
lInterfaceNumber++;
}
}
if( lInterfaceNumber == 1 )
{
/* The interface number was never incremented, so the above for() loop
* did not execute meaning no interfaces were found. */
printf( " \nNo network interfaces were found.\n" );
pxAllNetworkInterfaces = NULL;
}
printf( "\r\nThe interface that will be opened is set by " );
printf( "\"configNETWORK_INTERFACE_TO_USE\", which\r\nshould be defined in FreeRTOSConfig.h\r\n" );
if( ( xConfigNetworkInterfaceToUse < 1L ) || ( xConfigNetworkInterfaceToUse >= lInterfaceNumber ) )
{
printf( "\r\nERROR: configNETWORK_INTERFACE_TO_USE is set to %d, which is an invalid value.\r\n", xConfigNetworkInterfaceToUse );
printf( "Please set configNETWORK_INTERFACE_TO_USE to one of the interface numbers listed above,\r\n" );
printf( "then re-compile and re-start the application. Only Ethernet (as opposed to WiFi)\r\n" );
printf( "interfaces are supported.\r\n\r\nHALTING\r\n\r\n\r\n" );
xInvalidInterfaceDetected = pdTRUE;
if( pxAllNetworkInterfaces != NULL )
{
/* Free the device list, as no devices are going to be opened. */
pcap_freealldevs( pxAllNetworkInterfaces );
pxAllNetworkInterfaces = NULL;
}
}
else
{
printf( "Attempting to open interface number %d.\n", xConfigNetworkInterfaceToUse );
}
}
return pxAllNetworkInterfaces;
}
/*-----------------------------------------------------------*/
static int prvOpenInterface( const char * pucName,
const NetworkInterface_t * pxInterface )
{
static char pucInterfaceName[ 256 ];
if( pucName != NULL )
{
strncpy( pucInterfaceName, pucName, sizeof( pucInterfaceName ) );
}
pxOpenedInterfaceHandle = pcap_open( pucInterfaceName, /* The name of the selected interface. */
ipTOTAL_ETHERNET_FRAME_SIZE, /* The size of the packet to capture. */
PCAP_OPENFLAG_PROMISCUOUS, /* Open in promiscuous mode as the MAC and
* IP address is going to be "simulated", and
* not be the real MAC and IP address. This allows
* traffic to the simulated IP address to be routed
* to uIP, and traffic to the real IP address to be
* routed to the Windows TCP/IP stack. */
100,
NULL, /* No authentication is required as this is
* not a remote capture session. */
cErrorBuffer
);
if( pxOpenedInterfaceHandle == NULL )
{
printf( "\n%s is not supported by WinPcap and cannot be opened\n", pucInterfaceName );
return 1;
}
else
{
/* Configure the capture filter to allow blocking reads, and to filter
* out packets that are not of interest to this demo. */
prvConfigureCaptureBehaviour( pxInterface );
}
return 0;
}
/*-----------------------------------------------------------*/
static void prvOpenSelectedNetworkInterface( pcap_if_t * pxAllNetworkInterfaces,
const NetworkInterface_t * pxInterface )
{
pcap_if_t * pxPCAPInterface;
int32_t x;
/* Walk the list of devices until the selected device is located. */
pxPCAPInterface = pxAllNetworkInterfaces;
for( x = 0L; x < ( xConfigNetworkInterfaceToUse - 1L ); x++ )
{
pxPCAPInterface = pxPCAPInterface->next;
}
/* Open the selected interface. */
if( prvOpenInterface( pxPCAPInterface->name, pxInterface ) == 0 )
{
printf( "Successfully opened interface number %d.\n", x + 1 );
}
else
{
printf( "Failed to open interface number %d.\n", x + 1 );
}
/* The device list is no longer required. */
pcap_freealldevs( pxAllNetworkInterfaces );
}
/*-----------------------------------------------------------*/
static void prvConfigureCaptureBehaviour( const NetworkInterface_t * pxInterface )
{
struct bpf_program xFilterCode;
uint32_t ulNetMask;
const uint8_t * pucMAC;
NetworkEndPoint_t * pxEndPoint;
/* Find the MAC address of the very first end-point. */
pxEndPoint = FreeRTOS_FirstEndPoint( pxInterface );
/* Make sure that at least one end-point is defined. */
configASSERT( pxEndPoint != NULL );
pucMAC = pxEndPoint->xMACAddress.ucBytes;
/* Set up a filter so only the packets of interest are passed to the IP
* stack. cErrorBuffer is used for convenience to create the string. Don't
* confuse this with an error message. */
snprintf( cErrorBuffer, sizeof( cErrorBuffer ), "broadcast or multicast or ether host %x:%x:%x:%x:%x:%x",
pucMAC[ 0 ], pucMAC[ 1 ], pucMAC[ 2 ], pucMAC[ 3 ], pucMAC[ 4 ], pucMAC[ 5 ] );
ulNetMask = FreeRTOS_inet_addr_quick( configNET_MASK0, configNET_MASK1, configNET_MASK2, configNET_MASK3 );
if( pcap_compile( pxOpenedInterfaceHandle, &xFilterCode, cErrorBuffer, 1, ulNetMask ) < 0 )
{
printf( "\nThe packet filter string is invalid\n" );
}
else
{
if( pcap_setfilter( pxOpenedInterfaceHandle, &xFilterCode ) < 0 )
{
printf( "\nAn error occurred setting the packet filter.\n" );
}
/* When pcap_compile() succeeds, it allocates memory for the memory pointed to by the bpf_program struct
* parameter.pcap_freecode() will free that memory. */
pcap_freecode( &xFilterCode );
}
/* Create the buffers used to pass packets between the FreeRTOS simulator
* and the Win32 threads that are handling WinPCAP. */
prvCreateThreadSafeBuffers();
if( pvSendEvent == NULL )
{
/* Create event used to signal the Win32 WinPCAP Tx thread. */
pvSendEvent = CreateEvent( NULL, FALSE, TRUE, NULL );
/* Create the Win32 thread that handles WinPCAP Rx. */
vWinPcapRecvThreadHandle = CreateThread(
NULL, /* Pointer to thread security attributes. */
0, /* Initial thread stack size, in bytes. */
prvWinPcapRecvThread, /* Pointer to thread function. */
NULL, /* Argument for new thread. */
0, /* Creation flags. */
NULL );
/* Use the cores that are not used by the FreeRTOS tasks. */
SetThreadAffinityMask( vWinPcapRecvThreadHandle, ~0x01u );
/* Create the Win32 thread that handlers WinPCAP Tx. */
vWinPcapSendThreadHandle = CreateThread(
NULL, /* Pointer to thread security attributes. */
0, /* initial thread stack size, in bytes. */
prvWinPcapSendThread, /* Pointer to thread function. */
NULL, /* Argument for new thread. */
0, /* Creation flags. */
NULL );
/* Use the cores that are not used by the FreeRTOS tasks. */
SetThreadAffinityMask( vWinPcapSendThreadHandle, ~0x01u );
/* Create a task that simulates an interrupt in a real system. This will
* block waiting for packets, then send a message to the IP task when data
* is available. */
xTaskCreate( prvInterruptSimulatorTask, "MAC_ISR", configMINIMAL_STACK_SIZE, NULL, configMAC_ISR_SIMULATOR_PRIORITY, NULL );
}
}
/*-----------------------------------------------------------*/
/* WinPCAP function. */
void pcap_callback( u_char * user,
const struct pcap_pkthdr * pkt_header,
const u_char * pkt_data )
{
( void ) user;
/* THIS IS CALLED FROM A WINDOWS THREAD - DO NOT ATTEMPT ANY FREERTOS CALLS
* OR TO PRINT OUT MESSAGES HERE. */
/* Pass data to the FreeRTOS simulator on a thread safe circular buffer. */
if( ( pkt_header->caplen <= ( ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ) ) &&
( uxStreamBufferGetSpace( xRecvBuffer ) >= ( ( ( size_t ) pkt_header->caplen ) + sizeof( *pkt_header ) ) ) )
{
/* The received packets will be written to a C source file,
* only if 'ipconfigUSE_DUMP_PACKETS' is defined.
* Otherwise, there is no action. */
iptraceDUMP_PACKET( ( const uint8_t * ) pkt_data, ( size_t ) pkt_header->caplen, pdTRUE );
/* NOTE. The prvStreamBufferAdd function is used here in place of
* uxStreamBufferAdd since the uxStreamBufferAdd call will suspend
* the FreeRTOS scheduler to atomically update the head and front
* of the stream buffer. Since xRecvBuffer is being used as a regular
* circular buffer (i.e. only the head and tail are needed), this call
* only updates the head of the buffer, removing the need to suspend
* the scheduler, and allowing this function to be safely called from
* a Windows thread. */
prvStreamBufferAdd( xRecvBuffer, ( const uint8_t * ) pkt_header, sizeof( *pkt_header ) );
prvStreamBufferAdd( xRecvBuffer, ( const uint8_t * ) pkt_data, ( size_t ) pkt_header->caplen );
}
}
/*-----------------------------------------------------------*/
DWORD WINAPI prvWinPcapRecvThread( void * pvParam )
{
( void ) pvParam;
/* THIS IS A WINDOWS THREAD - DO NOT ATTEMPT ANY FREERTOS CALLS OR TO PRINT
* OUT MESSAGES HERE. */
for( ; ; )
{
pcap_dispatch( pxOpenedInterfaceHandle, 1, pcap_callback, ( u_char * ) "mydata" );
}
}
/*-----------------------------------------------------------*/
DWORD WINAPI prvWinPcapSendThread( void * pvParam )
{
size_t xLength;
uint8_t ucBuffer[ ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ];
static char cErrorMessage[ 1024 ];
const DWORD xMaxMSToWait = 1000;
/* THIS IS A WINDOWS THREAD - DO NOT ATTEMPT ANY FREERTOS CALLS OR TO PRINT
* OUT MESSAGES HERE. */
/* Remove compiler warnings about unused parameters. */
( void ) pvParam;
for( ; ; )
{
/* Wait until notified of something to send. */
WaitForSingleObject( pvSendEvent, xMaxMSToWait );
/* Is there more than the length value stored in the circular buffer
* used to pass data from the FreeRTOS simulator into this Win32 thread? */
while( uxStreamBufferGetSize( xSendBuffer ) > sizeof( xLength ) )
{
uxStreamBufferGet( xSendBuffer, 0, ( uint8_t * ) &xLength, sizeof( xLength ), pdFALSE );
uxStreamBufferGet( xSendBuffer, 0, ( uint8_t * ) ucBuffer, xLength, pdFALSE );
/* The packets sent will be written to a C source file,
* only if 'ipconfigUSE_DUMP_PACKETS' is defined.
* Otherwise, there is no action. */
iptraceDUMP_PACKET( ucBuffer, xLength, pdFALSE );
if( pcap_sendpacket( pxOpenedInterfaceHandle, ucBuffer, xLength ) != 0 )
{
ulWinPCAPSendFailures++;
}
}
}
}
/*-----------------------------------------------------------*/
static BaseType_t xPacketBouncedBack( const uint8_t * pucBuffer )
{
static BaseType_t xHasWarned = pdFALSE;
EthernetHeader_t * pxEtherHeader;
NetworkEndPoint_t * pxEndPoint;
BaseType_t xResult = pdFALSE;
pxEtherHeader = ( EthernetHeader_t * ) pucBuffer;
/* Sometimes, packets are bounced back by the driver and we need not process them. Check
* whether this packet is one such packet. */
for( pxEndPoint = FreeRTOS_FirstEndPoint( NULL );
pxEndPoint != NULL;
pxEndPoint = FreeRTOS_NextEndPoint( NULL, pxEndPoint ) )
{
if( memcmp( pxEndPoint->xMACAddress.ucBytes, pxEtherHeader->xSourceAddress.ucBytes, ipMAC_ADDRESS_LENGTH_BYTES ) == 0 )
{
if( xHasWarned == pdFALSE )
{
xHasWarned = pdTRUE;
FreeRTOS_printf( ( "Bounced back by WinPCAP interface: %02x:%02x:%02x:%02x:%02x:%02x\n",
pxEndPoint->xMACAddress.ucBytes[ 0 ],
pxEndPoint->xMACAddress.ucBytes[ 1 ],
pxEndPoint->xMACAddress.ucBytes[ 2 ],
pxEndPoint->xMACAddress.ucBytes[ 3 ],
pxEndPoint->xMACAddress.ucBytes[ 4 ],
pxEndPoint->xMACAddress.ucBytes[ 5 ] ) );
}
xResult = pdTRUE;
break;
}
}
return xResult;
}
/*-----------------------------------------------------------*/
static void prvInterruptSimulatorTask( void * pvParameters )
{
struct pcap_pkthdr xHeader;
static struct pcap_pkthdr * pxHeader;
const uint8_t * pucPacketData;
uint8_t ucRecvBuffer[ ipconfigNETWORK_MTU + ipSIZE_OF_ETH_HEADER ];
NetworkBufferDescriptor_t * pxNetworkBuffer;
IPStackEvent_t xRxEvent = { eNetworkRxEvent, NULL };
eFrameProcessingResult_t eResult;
/* Remove compiler warnings about unused parameters. */
( void ) pvParameters;
for( ; ; )
{
/* Does the circular buffer used to pass data from the Win32 thread that
* handles WinPCAP Rx into the FreeRTOS simulator contain another packet? */
if( uxStreamBufferGetSize( xRecvBuffer ) > sizeof( xHeader ) )
{
/* Get the next packet. */
uxStreamBufferGet( xRecvBuffer, 0, ( uint8_t * ) &xHeader, sizeof( xHeader ), pdFALSE );
uxStreamBufferGet( xRecvBuffer, 0, ( uint8_t * ) ucRecvBuffer, ( size_t ) xHeader.len, pdFALSE );
pucPacketData = ucRecvBuffer;
pxHeader = &xHeader;
iptraceNETWORK_INTERFACE_RECEIVE();
/* Check for minimal size. */
if( pxHeader->len >= sizeof( EthernetHeader_t ) )
{
eResult = ipCONSIDER_FRAME_FOR_PROCESSING( pucPacketData );
}
else
{
eResult = eReleaseBuffer;
}
if( eResult == eProcessBuffer )
{
/* Will the data fit into the frame buffer? */
if( pxHeader->len <= ipTOTAL_ETHERNET_FRAME_SIZE )
{
BaseType_t xBounced = xPacketBouncedBack( pucPacketData );
/* Obtain a buffer into which the data can be placed. This
* is only an interrupt simulator, not a real interrupt, so it
* is ok to call the task level function here, but note that
* some buffer implementations cannot be called from a real
* interrupt. */
if( xBounced == pdFALSE )
{
pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( pxHeader->len, 0 );
}
else
{
pxNetworkBuffer = NULL;
}
if( pxNetworkBuffer != NULL )
{
memcpy( pxNetworkBuffer->pucEthernetBuffer, pucPacketData, pxHeader->len );
pxNetworkBuffer->xDataLength = ( size_t ) pxHeader->len;
#if ( niDISRUPT_PACKETS == 1 )
{
pxNetworkBuffer = vRxFaultInjection( pxNetworkBuffer, pucPacketData );
}
#endif /* niDISRUPT_PACKETS */
if( pxNetworkBuffer != NULL )
{
xRxEvent.pvData = ( void * ) pxNetworkBuffer;
pxNetworkBuffer->pxInterface = pxMyInterface;
pxNetworkBuffer->pxEndPoint = FreeRTOS_MatchingEndpoint( pxMyInterface, pxNetworkBuffer->pucEthernetBuffer );
/* Just for now, make sure that there is a valid end-point. */
if( pxNetworkBuffer->pxEndPoint == NULL )
{
FreeRTOS_printf( ( "Network interface: dropped packet\n" ) );
vReleaseNetworkBufferAndDescriptor( BUFFER_FROM_WHERE_CALL( 153 ) pxNetworkBuffer );
}
else
{
/* Data was received and stored. Send a message to
* the IP task to let it know. */
if( xSendEventStructToIPTask( &xRxEvent, ( TickType_t ) 0 ) == pdFAIL )
{
/* The buffer could not be sent to the stack so
* must be released again. This is only an
* interrupt simulator, not a real interrupt, so it
* is ok to use the task level function here, but
* note no all buffer implementations will allow
* this function to be executed from a real
* interrupt. */
vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
iptraceETHERNET_RX_EVENT_LOST();
}
}
}
else
{
/* The packet was already released or stored inside
* vRxFaultInjection(). Don't release it here. */
}
}
else
{
iptraceETHERNET_RX_EVENT_LOST();
}
}
else
{
/* Log that a packet was dropped because it would have
* overflowed the buffer, but there may be more buffers to
* process. */
}
}
}
else
{
/* There is no real way of simulating an interrupt. Make sure
* other tasks can run. */
vTaskDelay( configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY );
}
}
}
/*-----------------------------------------------------------*/
static const char * prvRemoveSpaces( char * pcBuffer,
int aBuflen,
const char * pcMessage )
{
char * pcTarget = pcBuffer;
/* Utility function used to format messages being printed only. */
while( ( *pcMessage != 0 ) && ( pcTarget < ( pcBuffer + aBuflen - 1 ) ) )
{
*( pcTarget++ ) = *pcMessage;
if( isspace( *pcMessage ) != pdFALSE )
{
while( isspace( *pcMessage ) != pdFALSE )
{
pcMessage++;
}
}
else
{
pcMessage++;
}
}
*pcTarget = '\0';
return pcBuffer;
}
/*-----------------------------------------------------------*/
#define BUFFER_SIZE ( ipTOTAL_ETHERNET_FRAME_SIZE + ipBUFFER_PADDING )
#define BUFFER_SIZE_ROUNDED_UP ( ( BUFFER_SIZE + 7 ) & ~0x07UL )
size_t uxNetworkInterfaceAllocateRAMToBuffers( NetworkBufferDescriptor_t pxNetworkBuffers[ ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ] )
{
static uint8_t * pucNetworkPacketBuffers = NULL;
size_t uxIndex;
if( pucNetworkPacketBuffers == NULL )
{
pucNetworkPacketBuffers = ( uint8_t * ) malloc( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS * BUFFER_SIZE_ROUNDED_UP );
}
if( pucNetworkPacketBuffers == NULL )
{
FreeRTOS_printf( ( "Failed to allocate memory for pxNetworkBuffers" ) );
configASSERT( 0 );
}
else
{
for( uxIndex = 0; uxIndex < ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS; uxIndex++ )
{
size_t uxOffset = uxIndex * BUFFER_SIZE_ROUNDED_UP;
NetworkBufferDescriptor_t ** ppDescriptor;
/* At the beginning of each pbuff is a pointer to the relevant descriptor */
ppDescriptor = ( NetworkBufferDescriptor_t ** ) &( pucNetworkPacketBuffers[ uxOffset ] );
/* Set this pointer to the address of the correct descriptor */
*ppDescriptor = &( pxNetworkBuffers[ uxIndex ] );
/* pucEthernetBuffer is set to point ipBUFFER_PADDING bytes in from the
* beginning of the allocated buffer. */
pxNetworkBuffers[ uxIndex ].pucEthernetBuffer = &( pucNetworkPacketBuffers[ uxOffset + ipBUFFER_PADDING ] );
}
}
return( BUFFER_SIZE_ROUNDED_UP - ipBUFFER_PADDING );
}
@@ -0,0 +1,157 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/**
* @brief
* Handling of Ethernet PHY's
* PHY's communicate with an EMAC either through
* a Media-Independent Interface (MII), or a Reduced Media-Independent Interface (RMII).
* The EMAC can poll for PHY ports on 32 different addresses. Each of the PHY ports
* shall be treated independently.
*
*/
#ifndef PHYHANDLING_H
#define PHYHANDLING_H
#ifdef __cplusplus
extern "C" {
#endif
/* A generic user-provided function that reads from the PHY-port at 'xAddress'( 0-based ). A 16-bit value shall be stored in
* '*pulValue'. xRegister is the register number ( 0 .. 31 ). In fact all PHY registers are 16-bit.
* Return non-zero in case the action failed. */
typedef BaseType_t ( * xApplicationPhyReadHook_t )( BaseType_t xAddress,
BaseType_t xRegister,
uint32_t * pulValue );
/* A generic user-provided function that writes 'ulValue' to the
* PHY-port at 'xAddress' ( 0-based ). xRegister is the register number ( 0 .. 31 ).
* Return non-zero in case the action failed. */
typedef BaseType_t ( * xApplicationPhyWriteHook_t )( BaseType_t xAddress,
BaseType_t xRegister,
uint32_t ulValue );
typedef struct xPhyProperties
{
uint8_t ucSpeed;
uint8_t ucMDI_X; /* MDI-X : Medium Dependent Interface - Crossover */
uint8_t ucDuplex;
uint8_t ucSpare;
} PhyProperties_t;
typedef struct xEthernetPhy
{
xApplicationPhyReadHook_t fnPhyRead;
xApplicationPhyWriteHook_t fnPhyWrite;
uint32_t ulPhyIDs[ ipconfigPHY_MAX_PORTS ];
uint8_t ucPhyIndexes[ ipconfigPHY_MAX_PORTS ];
TimeOut_t xLinkStatusTimer;
TickType_t xLinkStatusRemaining;
BaseType_t xPortCount;
uint32_t ulBCRValue;
uint32_t ulACRValue;
uint32_t ulLinkStatusMask;
PhyProperties_t xPhyPreferences;
PhyProperties_t xPhyProperties;
} EthernetPhy_t;
/* Some defines used internally here to indicate preferences about speed, MDIX
* (wired direct or crossed), and duplex (half or full). */
/* Values for PhyProperties_t::ucSpeed : */
#define PHY_SPEED_10 1
#define PHY_SPEED_100 2
#define PHY_SPEED_AUTO 3
/* Values for PhyProperties_t::ucMDI_X : */
#define PHY_MDIX_DIRECT 1
#define PHY_MDIX_CROSSED 2
#define PHY_MDIX_AUTO 3
/* Values for PhyProperties_t::ucDuplex : */
#define PHY_DUPLEX_HALF 1
#define PHY_DUPLEX_FULL 2
#define PHY_DUPLEX_AUTO 3
/* ID's of supported PHY's : */
#define PHY_ID_LAN8742A 0x0007c130
#define PHY_ID_LAN8720 0x0007c0f0
#define PHY_ID_KSZ8041 0x000010A1
#define PHY_ID_KSZ8051 0x000010A1
#define PHY_ID_KSZ8081 0x000010A1
#define PHY_ID_KSZ8863 0x00221430
#define PHY_ID_KSZ8795 0x00221550
#define PHY_ID_KSZ8081MNXIA 0x00221560
#define PHY_ID_DP83848I 0x20005C90
#define PHY_ID_DP83TC811S 0x2000A250
#define PHY_ID_TM4C129X 0x2000A221
#define PHY_ID_MV88E6071 0xFF000710
#define PHY_ID_ADIN1200 0x0283BC20
/* Initialise the struct and assign a PHY-read and -write function. */
void vPhyInitialise( EthernetPhy_t * pxPhyObject,
xApplicationPhyReadHook_t fnPhyRead,
xApplicationPhyWriteHook_t fnPhyWrite );
/* Discover all PHY's connected by polling 32 indexes ( zero-based ) */
BaseType_t xPhyDiscover( EthernetPhy_t * pxPhyObject );
/* Send a reset command to the connected PHY ports and send configuration. */
BaseType_t xPhyConfigure( EthernetPhy_t * pxPhyObject,
const PhyProperties_t * pxPhyProperties );
/* Give a command to start auto negotiation on a set of PHY port's. */
BaseType_t xPhyStartAutoNegotiation( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask );
/* Do not use auto negotiation but use predefined values from 'pxPhyObject->xPhyPreferences'. */
BaseType_t xPhyFixedValue( EthernetPhy_t * pxPhyObject,
uint32_t ulPhyMask );
/* Check the current Link Status.
* 'xHadReception' : make this true if a packet has been received since the
* last call to this function. */
BaseType_t xPhyCheckLinkStatus( EthernetPhy_t * pxPhyObject,
BaseType_t xHadReception );
/* Get the bitmask of a given 'EthernetPhy_t'. */
#define xPhyGetMask( pxPhyObject ) \
( ( ( ( uint32_t ) 1u ) << ( pxPhyObject )->xPortCount ) - 1u )
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* PHYHANDLING_H */
@@ -0,0 +1,20 @@
if (NOT (FREERTOS_PLUS_TCP_NETWORK_IF STREQUAL "LOOPBACK") )
return()
endif()
#------------------------------------------------------------------------------
add_library( freertos_plus_tcp_network_if STATIC )
target_sources( freertos_plus_tcp_network_if
PRIVATE
loopbackNetworkInterface.c
)
target_link_libraries( freertos_plus_tcp_network_if
PUBLIC
freertos_plus_tcp_port
freertos_plus_tcp_network_if_common
PRIVATE
freertos_kernel
freertos_plus_tcp
)
@@ -0,0 +1,195 @@
/*
* FreeRTOS+TCP
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://aws.amazon.com/freertos
* http://www.FreeRTOS.org
*/
/* Standard includes. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* FreeRTOS+TCP includes. */
#include "FreeRTOS_ARP.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_DNS.h"
#include "FreeRTOS_Routing.h"
#include "FreeRTOS_ND.h"
#include "NetworkBufferManagement.h"
#include "NetworkInterface.h"
#if ( ipconfigUSE_LOOPBACK == 0 )
#error Please define ipconfigUSE_LOOPBACK as 1 if you want to use the loop-back interface
#endif
#define ipICMP_ECHO_REQUEST ( ( uint8_t ) 8 )
#define ipICMP_ECHO_REPLY ( ( uint8_t ) 0 )
/*-----------------------------------------------------------*/
NetworkInterface_t * xLoopbackInterface;
static BaseType_t prvLoopback_Initialise( NetworkInterface_t * pxInterface );
static BaseType_t prvLoopback_Output( NetworkInterface_t * pxInterface,
NetworkBufferDescriptor_t * const pxGivenDescriptor,
BaseType_t bReleaseAfterSend );
static BaseType_t prvLoopback_GetPhyLinkStatus( NetworkInterface_t * pxInterface );
NetworkInterface_t * pxLoopback_FillInterfaceDescriptor( BaseType_t xEMACIndex,
NetworkInterface_t * pxInterface );
/*-----------------------------------------------------------*/
static BaseType_t prvLoopback_Initialise( NetworkInterface_t * pxInterface )
{
/* When returning non-zero, the stack will become active and
* start DHCP (in configured) */
( void ) pxInterface;
return pdTRUE;
}
/*-----------------------------------------------------------*/
#if ( ipconfigIPv4_BACKWARD_COMPATIBLE != 0 )
/* Do not call the following function directly. It is there for downward compatibility.
* The function FreeRTOS_IPInit() will call it to initialice the interface and end-point
* objects. See the description in FreeRTOS_Routing.h. */
NetworkInterface_t * pxFillInterfaceDescriptor( BaseType_t xEMACIndex,
NetworkInterface_t * pxInterface )
{
return pxLoopback_FillInterfaceDescriptor( xEMACIndex, pxInterface );
}
#endif /* ( ipconfigIPv4_BACKWARD_COMPATIBLE != 0 ) */
/*-----------------------------------------------------------*/
NetworkInterface_t * pxLoopback_FillInterfaceDescriptor( BaseType_t xEMACIndex,
NetworkInterface_t * pxInterface )
{
/* This function pxLoopback_FillInterfaceDescriptor() adds a network-interface.
* Make sure that the object pointed to by 'pxInterface'
* is declared static or global, and that it will remain to exist. */
memset( pxInterface, '\0', sizeof( *pxInterface ) );
pxInterface->pcName = "Loopback"; /* Just for logging, debugging. */
pxInterface->pvArgument = ( void * ) xEMACIndex; /* Has only meaning for the driver functions. */
pxInterface->pfInitialise = prvLoopback_Initialise;
pxInterface->pfOutput = prvLoopback_Output;
pxInterface->pfGetPhyLinkStatus = prvLoopback_GetPhyLinkStatus;
FreeRTOS_AddNetworkInterface( pxInterface );
xLoopbackInterface = pxInterface;
return pxInterface;
}
/*-----------------------------------------------------------*/
static BaseType_t prvLoopback_GetPhyLinkStatus( NetworkInterface_t * pxInterface )
{
/* This function returns true if the Link Status in the PHY is high. */
( void ) pxInterface;
return pdTRUE;
}
/*-----------------------------------------------------------*/
static BaseType_t prvLoopback_Output( NetworkInterface_t * pxInterface,
NetworkBufferDescriptor_t * const pxGivenDescriptor,
BaseType_t bReleaseAfterSend )
{
NetworkBufferDescriptor_t * pxDescriptor = pxGivenDescriptor;
( void ) pxInterface;
IPPacket_t * a = ( IPPacket_t * ) ( pxDescriptor->pucEthernetBuffer );
if( a->xEthernetHeader.usFrameType == ipIPv4_FRAME_TYPE )
{
usGenerateProtocolChecksum( pxDescriptor->pucEthernetBuffer, pxDescriptor->xDataLength, pdTRUE );
}
{
const MACAddress_t * pxMACAddress = &( pxDescriptor->pxEndPoint->xMACAddress );
if( pxDescriptor->pxEndPoint->bits.bIPv6 != 0 )
{
#if ( ipconfigUSE_IPv6 != 0 )
if( xIsIPv6Loopback( &( pxDescriptor->xIPAddress.xIP_IPv6 ) ) != pdFALSE )
{
vNDRefreshCacheEntry( pxMACAddress, &( pxDescriptor->xIPAddress.xIP_IPv6 ), pxDescriptor->pxEndPoint );
}
#endif
}
else
{
#if ( ipconfigUSE_IPv4 != 0 )
if( xIsIPv4Loopback( pxDescriptor->xIPAddress.ulIP_IPv4 ) != pdFALSE )
{
vARPRefreshCacheEntry( pxMACAddress, pxDescriptor->xIPAddress.ulIP_IPv4, pxDescriptor->pxEndPoint );
}
#endif
}
}
if( bReleaseAfterSend == pdFALSE )
{
NetworkBufferDescriptor_t * pxNewDescriptor =
pxDuplicateNetworkBufferWithDescriptor( pxDescriptor, pxDescriptor->xDataLength );
pxDescriptor = pxNewDescriptor;
}
if( pxDescriptor != NULL )
{
IPStackEvent_t xRxEvent;
xRxEvent.eEventType = eNetworkRxEvent;
xRxEvent.pvData = ( void * ) pxDescriptor;
pxDescriptor->pxInterface = xLoopbackInterface;
pxDescriptor->pxEndPoint = FreeRTOS_MatchingEndpoint( xLoopbackInterface, pxDescriptor->pucEthernetBuffer );
if( pxDescriptor->pxEndPoint == NULL )
{
vReleaseNetworkBufferAndDescriptor( pxDescriptor );
iptraceETHERNET_RX_EVENT_LOST();
FreeRTOS_printf( ( "prvLoopback_Output: Can not find a proper endpoint\n" ) );
}
else if( xSendEventStructToIPTask( &xRxEvent, 0u ) != pdTRUE )
{
/* Sending failed, release the descriptor. */
vReleaseNetworkBufferAndDescriptor( pxDescriptor );
iptraceETHERNET_RX_EVENT_LOST();
FreeRTOS_printf( ( "prvLoopback_Output: Can not queue return packet!\n" ) );
}
}
/* The return value is actually ignored by the IP-stack. */
return pdTRUE;
}
/*-----------------------------------------------------------*/