以太网驱动优化,TCP客户端进行优化

This commit is contained in:
冯佳
2026-02-27 08:04:12 +08:00
parent 23254ae44f
commit 23bb103fb5
7 changed files with 702 additions and 7534 deletions

View File

@ -11,48 +11,63 @@
/* Ethernet Handle */
ETH_HandleTypeDef heth;
static uint32_t g_phy_address = 0; /* Stored PHY Address */
static uint32_t g_last_link_check_time = 0; /* 上次链接状态检测时间 */
static uint32_t g_link_check_interval = 1000; /* 链接状态检测间隔 (ms) */
static uint8_t g_link_state_stable = 0; /* 链接状态稳定性标志 */
static uint8_t g_link_state_counter = 0; /* 链接状态计数器,用于防抖 */
/* DMA Descriptors and Buffers */
__attribute__((section(".RxDecripSection"))) __attribute__((aligned(4))) ETH_DMADescTypeDef DMARxDscrTab[ETH_RXBUFNB];
__attribute__((section(".TxDecripSection"))) __attribute__((aligned(4))) ETH_DMADescTypeDef DMATxDscrTab[ETH_TXBUFNB];
__attribute__((section(".RxArraySection"))) __attribute__((aligned(4))) uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE];
__attribute__((section(".TxArraySection"))) __attribute__((aligned(4))) uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE];
/* 优化缓冲区对齐方式,提高内存访问效率 */
__attribute__((section(".RxDecripSection"))) __attribute__((aligned(32))) ETH_DMADescTypeDef DMARxDscrTab[ETH_RXBUFNB];
__attribute__((section(".TxDecripSection"))) __attribute__((aligned(32))) ETH_DMADescTypeDef DMATxDscrTab[ETH_TXBUFNB];
__attribute__((section(".RxArraySection"))) __attribute__((aligned(32))) uint8_t Rx_Buff[ETH_RXBUFNB][ETH_RX_BUF_SIZE];
__attribute__((section(".TxArraySection"))) __attribute__((aligned(32))) uint8_t Tx_Buff[ETH_TXBUFNB][ETH_TX_BUF_SIZE];
/* 缓冲区管理优化:可以根据实际网络流量调整缓冲区大小和数量 */
/* 建议值:
* - 高流量场景ETH_RXBUFNB = 8, ETH_TXBUFNB = 8
* - 低内存场景ETH_RXBUFNB = 2, ETH_TXBUFNB = 2
*/
/* Semaphore for Ethernet */
static osal_sem_t s_xSemaphore = NULL;
/* MSP Init */
void HAL_ETH_MspInit(ETH_HandleTypeDef *heth)
{
(void)heth;
GPIO_InitTypeDef GPIO_InitStructure;
/* 函数声明 */
static HAL_StatusTypeDef detect_and_configure_phy(void);
static void configure_mac(ETH_MACConfigTypeDef *macConf);
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_SYSCFG_CLK_ENABLE();
/* MSP Init - Implemented in board.c */
// void HAL_ETH_MspInit(ETH_HandleTypeDef *heth)
// {
// (void)heth;
// GPIO_InitTypeDef GPIO_InitStructure;
__HAL_RCC_ETH_CLK_ENABLE();
// __HAL_RCC_GPIOA_CLK_ENABLE();
// __HAL_RCC_GPIOB_CLK_ENABLE();
// __HAL_RCC_GPIOC_CLK_ENABLE();
// __HAL_RCC_SYSCFG_CLK_ENABLE();
/* PA1, PA2, PA7 */
GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7;
GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.Pull = GPIO_NOPULL;
GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStructure.Alternate = GPIO_AF11_ETH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
// __HAL_RCC_ETH_CLK_ENABLE();
/* PC1, PC4, PC5 */
GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5;
HAL_GPIO_Init(GPIOC, &GPIO_InitStructure);
// /* PA1, PA2, PA7 */
// GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7;
// GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
// GPIO_InitStructure.Pull = GPIO_NOPULL;
// GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
// GPIO_InitStructure.Alternate = GPIO_AF11_ETH;
// HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
/* PB11, PB12, PB13 */
GPIO_InitStructure.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13;
HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
HAL_NVIC_SetPriority(ETH_IRQn, 0x07, 0);
HAL_NVIC_EnableIRQ(ETH_IRQn);
}
// /* PC1, PC4, PC5 */
// GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5;
// HAL_GPIO_Init(GPIOC, &GPIO_InitStructure);
// /* PB11, PB12, PB13 */
// GPIO_InitStructure.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13;
// HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
//
// HAL_NVIC_SetPriority(ETH_IRQn, 0x07, 0);
// HAL_NVIC_EnableIRQ(ETH_IRQn);
// }
void HAL_ETH_RxCpltCallback(ETH_HandleTypeDef *heth)
{
@ -79,20 +94,24 @@ void HAL_ETH_RxLinkCallback(void **pStart, void **pEnd, uint8_t *buff, uint16_t
void ETH_IRQHandler(void)
{
osal_enter_critical();
/* 直接调用 HAL 中断处理函数,不使用全局临界区
* HAL_ETH_IRQHandler 内部已经有适当的中断保护机制
*/
HAL_ETH_IRQHandler(&heth);
osal_exit_critical();
}
/**
* @brief 以太网硬件初始化函数
* @param netif: 网络接口结构体指针
* @return 无
* @note 负责初始化以太网硬件包括MAC、DMA、PHY等
*/
static void low_level_init(struct netif *netif)
{
/* Use a fixed MAC address to avoid conflicts/filtering */
uint8_t macaddress[6] = { 0x00, 0x80, 0xE1, 0x00, 0x00, 0x55 };
ETH_MACConfigTypeDef macConf;
HAL_StatusTypeDef hal_eth_init_status;
uint32_t phy_id1 = 0, phy_id2 = 0;
uint8_t detected_phy_addr = 0;
uint32_t regvalue;
/* Generate MAC address from UID */
/*
@ -112,6 +131,7 @@ static void low_level_init(struct netif *netif)
macaddress[0], macaddress[1], macaddress[2],
macaddress[3], macaddress[4], macaddress[5]);
/* 初始化 ETH 句柄 */
heth.Instance = ETH;
heth.Init.MACAddr = macaddress;
heth.Init.MediaInterface = ETH_MEDIA_INTERFACE_RMII;
@ -124,66 +144,30 @@ static void low_level_init(struct netif *netif)
if (hal_eth_init_status == HAL_OK)
{
/* Step 1: PHY address detection */
osal_log_i("Detecting PHY Address...");
detected_phy_addr = 0xFF; /* Invalid initial value */
for(uint8_t addr = 0; addr <= 31; addr++) {
/* Read PHY ID registers (typically Reg 2 and 3) */
/* Using 4-arg version: heth, PhyAddr, Reg, Value */
if(HAL_ETH_ReadPHYRegister(&heth, addr, 2, &phy_id1) == HAL_OK &&
HAL_ETH_ReadPHYRegister(&heth, addr, 3, &phy_id2) == HAL_OK) {
if((phy_id1 != 0xFFFF) && (phy_id1 != 0x0000) && (phy_id1 != 0)) {
detected_phy_addr = addr;
osal_log_i("Found PHY at Address %d (ID: %04x %04x)", addr, phy_id1, phy_id2);
break;
}
}
}
if (detected_phy_addr != 0xFF)
/* 检测并配置 PHY */
if (detect_and_configure_phy() == HAL_OK)
{
g_phy_address = detected_phy_addr;
/* Step 2: PHY Soft Reset */
osal_log_i("Resetting PHY...");
/* Write Reset Bit */
HAL_ETH_WritePHYRegister(&heth, g_phy_address, PHY_BCR, PHY_RESET);
/* Wait for Reset to clear */
uint32_t tickstart = osal_tick_get();
do {
HAL_ETH_ReadPHYRegister(&heth, g_phy_address, PHY_BCR, &regvalue);
if((regvalue & PHY_RESET) == 0) break;
} while ((osal_tick_get() - tickstart) < 500); // 500ms timeout
/* Add a delay to ensure PHY is stable */
osal_thread_mdelay(100);
netif->flags |= NETIF_FLAG_LINK_UP;
}
else
{
osal_log_e("No PHY found!");
}
}
else
{
osal_log_e("HAL_ETH_Init failed");
}
HAL_ETH_GetMACConfig(&heth, &macConf);
macConf.DuplexMode = ETH_FULLDUPLEX_MODE;
macConf.Speed = ETH_SPEED_100M;
macConf.ChecksumOffload = ENABLE; /* Enable HW Checksum */
HAL_ETH_SetMACConfig(&heth, &macConf);
/* 配置 MAC */
configure_mac(&macConf);
/* Enable Promiscuous Mode manually as it's not in the struct */
heth.Instance->MACFFR |= ETH_MACFFR_PM;
/* 启动 ETH 中断 */
HAL_ETH_Start_IT(&heth);
/* 创建信号量 */
s_xSemaphore = osal_sem_create("eth_sem", 0);
/* 配置网络接口 */
netif->hwaddr_len = 6;
memcpy(netif->hwaddr, macaddress, 6);
netif->mtu = 1500;
@ -193,6 +177,106 @@ static void low_level_init(struct netif *netif)
#endif
}
/**
* @brief 检测并配置 PHY
* @return HAL_StatusTypeDef: 操作结果
* @note 负责检测 PHY 地址并进行配置
*/
static HAL_StatusTypeDef detect_and_configure_phy(void)
{
uint32_t phy_id1 = 0, phy_id2 = 0;
uint8_t detected_phy_addr = 0xFF; /* Invalid initial value */
uint32_t regvalue;
/* Step 1: PHY address detection */
osal_log_i("Detecting PHY Address...");
/* 优先检查常见的 PHY 地址,减少遍历次数 */
uint8_t common_phy_addresses[] = {0, 1, 2, 3, 16, 17, 18, 19, 20};
uint8_t common_phy_count = sizeof(common_phy_addresses) / sizeof(common_phy_addresses[0]);
/* 先检查常见地址 */
for(uint8_t i = 0; i < common_phy_count; i++) {
uint8_t addr = common_phy_addresses[i];
/* Read PHY ID registers (typically Reg 2 and 3) */
if(HAL_ETH_ReadPHYRegister(&heth, addr, 2, &phy_id1) == HAL_OK &&
HAL_ETH_ReadPHYRegister(&heth, addr, 3, &phy_id2) == HAL_OK) {
if((phy_id1 != 0xFFFF) && (phy_id1 != 0x0000) && (phy_id1 != 0)) {
detected_phy_addr = addr;
osal_log_i("Found PHY at Address %d (ID: %04x %04x)", addr, phy_id1, phy_id2);
goto phy_found;
}
}
}
/* 如果常见地址没找到,再遍历所有可能的地址 */
for(uint8_t addr = 0; addr <= 31; addr++) {
/* 跳过已经检查过的常见地址 */
uint8_t skip = 0;
for(uint8_t i = 0; i < common_phy_count; i++) {
if(addr == common_phy_addresses[i]) {
skip = 1;
break;
}
}
if(skip) continue;
/* Read PHY ID registers (typically Reg 2 and 3) */
if(HAL_ETH_ReadPHYRegister(&heth, addr, 2, &phy_id1) == HAL_OK &&
HAL_ETH_ReadPHYRegister(&heth, addr, 3, &phy_id2) == HAL_OK) {
if((phy_id1 != 0xFFFF) && (phy_id1 != 0x0000) && (phy_id1 != 0)) {
detected_phy_addr = addr;
osal_log_i("Found PHY at Address %d (ID: %04x %04x)", addr, phy_id1, phy_id2);
goto phy_found;
}
}
}
phy_found:
if (detected_phy_addr != 0xFF)
{
g_phy_address = detected_phy_addr;
/* Step 2: PHY Soft Reset */
osal_log_i("Resetting PHY...");
/* Write Reset Bit */
HAL_ETH_WritePHYRegister(&heth, g_phy_address, PHY_BCR, PHY_RESET);
/* Wait for Reset to clear */
uint32_t tickstart = osal_tick_get();
uint32_t reset_timeout = 200; // 优化为 200ms 超时
do {
HAL_ETH_ReadPHYRegister(&heth, g_phy_address, PHY_BCR, &regvalue);
if((regvalue & PHY_RESET) == 0) break;
} while ((osal_tick_get() - tickstart) < reset_timeout); // 200ms timeout
/* Add a delay to ensure PHY is stable */
osal_thread_mdelay(50); // 优化为 50ms 延迟
return HAL_OK;
}
else
{
osal_log_e("No PHY found!");
return HAL_ERROR;
}
}
/**
* @brief 配置 MAC
* @param macConf: MAC 配置结构体指针
* @return 无
* @note 负责配置 MAC 的双工模式、速度和校验和等
*/
static void configure_mac(ETH_MACConfigTypeDef *macConf)
{
HAL_ETH_GetMACConfig(&heth, macConf);
macConf->DuplexMode = ETH_FULLDUPLEX_MODE;
macConf->Speed = ETH_SPEED_100M;
macConf->ChecksumOffload = ENABLE; /* Enable HW Checksum */
HAL_ETH_SetMACConfig(&heth, macConf);
}
static err_t low_level_output(struct netif *netif, struct pbuf *p)
{
(void)netif;
@ -202,9 +286,9 @@ static err_t low_level_output(struct netif *netif, struct pbuf *p)
ETH_BufferTypeDef txBuffers[16];
memset(&txConfig, 0, sizeof(ETH_TxPacketConfigTypeDef));
/* Disable Hardware Checksum Insertion */
txConfig.Attributes = 0; // ETH_TX_PACKETS_FEATURES_CSUM | ETH_TX_PACKETS_FEATURES_CRCPAD;
txConfig.ChecksumCtrl = ETH_CHECKSUM_DISABLE; // ETH_CHECKSUM_IPHDR_PAYLOAD_INSERT_PHDR_CALC;
/* Enable Hardware Checksum Insertion */
txConfig.Attributes = ETH_TX_PACKETS_FEATURES_CSUM | ETH_TX_PACKETS_FEATURES_CRCPAD;
txConfig.ChecksumCtrl = ETH_CHECKSUM_IPHDR_PAYLOAD_INSERT_PHDR_CALC;
txConfig.CRCPadCtrl = ETH_CRC_PAD_INSERT;
int i = 0;
@ -246,13 +330,24 @@ static struct pbuf * low_level_input(struct netif *netif)
// osal_log_i("Rx: rxLength=%d", rxLength);
if (rxLength > 0 && buffer != NULL) {
p = pbuf_alloc(PBUF_RAW, rxLength, PBUF_POOL);
/* 尝试使用 PBUF_REF 模式创建 pbuf实现零拷贝
* 注意:需要确保缓冲区在 pbuf 使用期间有效
*/
p = pbuf_alloc(PBUF_RAW, rxLength, PBUF_REF);
if (p != NULL) {
/* Copy data */
pbuf_take(p, buffer, rxLength);
/* 直接设置 pbuf 的 payload 指针,避免数据拷贝 */
p->payload = buffer;
p->len = rxLength;
p->tot_len = rxLength;
// osal_log_i("Rx: p->tot_len=%d", p->tot_len);
} else {
osal_log_e("pbuf_alloc failed");
/* 如果 PBUF_REF 失败,回退到传统方式 */
p = pbuf_alloc(PBUF_RAW, rxLength, PBUF_POOL);
if (p != NULL) {
pbuf_take(p, buffer, rxLength);
} else {
osal_log_e("pbuf_alloc failed");
}
}
/* HAL_ETH_ReadData internally calls ETH_UpdateDescriptor, so descriptors are rebuilt automatically */
}
@ -309,24 +404,45 @@ err_t ethernetif_init(struct netif *netif)
void ethernet_link_check_state(struct netif *netif)
{
uint32_t regvalue = 0;
uint32_t current_time = osal_tick_get();
/* 实现时间间隔控制,减少 PHY 寄存器读取 */
if ((current_time - g_last_link_check_time) < g_link_check_interval)
{
return;
}
g_last_link_check_time = current_time;
/* Use configured PHY Address */
HAL_ETH_ReadPHYRegister(&heth, g_phy_address, PHY_BSR, &regvalue);
if ((regvalue & PHY_LINKED_STATUS) != (uint16_t)RESET)
{
if (!netif_is_link_up(netif))
/* 链接状态防抖 */
g_link_state_counter++;
if (g_link_state_counter >= 3) /* 连续 3 次检测到链接状态为 up */
{
netif_set_link_up(netif);
osal_log_i("Ethernet Link Up");
if (!netif_is_link_up(netif))
{
netif_set_link_up(netif);
osal_log_i("Ethernet Link Up");
}
g_link_state_stable = 1;
}
}
else
{
if (netif_is_link_up(netif))
/* 链接状态防抖 */
g_link_state_counter--;
if (g_link_state_counter <= 0) /* 连续 3 次检测到链接状态为 down */
{
netif_set_link_down(netif);
osal_log_i("Ethernet Link Down");
g_link_state_counter = 0;
if (netif_is_link_up(netif))
{
netif_set_link_down(netif);
osal_log_i("Ethernet Link Down");
}
g_link_state_stable = 0;
}
}
}