基于小梅哥AC620开发板的NIOS II LWIP百兆以太网例程

Altera FPGA NIOS使用Triple-Speed Ethernet三速以太网IP核驱动RTL8201CP百兆网口,并使用lwip2.1.2协议栈建立http服务器,支持IPv6

Quartus II 13.0工程下载地址:百度网盘 请输入提取码(提取码:jqpv,内含三速以太网license.dat)

基于小梅哥AC620开发板的NIOS II LWIP百兆以太网例程移植到自己做的板子上:基于小梅哥AC620开发板的NIOS II LWIP百兆以太网例程移植到自己做的板子上_ZLK1214的专栏-CSDN博客

如果是自己建工程的话,添加完lwip后,需要把lwip-2.1.2/include添加到头文件包含路径中,否则会提示很多变量和函数未定义。 

Quartus II 13.0sp1 NIOS添加include头文件包含路径的方法_ZLK1214的专栏-CSDN博客

易错点:如果电脑上的quartus ii没有破解三速以太网ip核,综合生成的文件是main_time_limited.sof,原来的main.sof并没有修改。
不注意的话,烧写的是main.sof,再运行程序,就会报错,提示timestamp不匹配。
综合完成后请一定要核对烧写的sof文件的修改日期,否则会一直提示timestamp不匹配。 

【开发板】

开发板型号:小梅哥AC620
FPGA型号:EP4CE10F17C8N
晶振频率:50MHz
SDRAM型号:W9812G6KH-6(容量为16MB)
PHY芯片型号:RTL8201CP(MII接口,百兆以太网PHY芯片)

【电路图】

【程序功能展示】

1. ping通开发板的NetBIOS设备名,IPv4地址和IPv6地址

2. 访问开发板上的http服务器(设备名方式、IPv6方式):

3. 在路由器管理页面看到开发板的信息:

4. PHY芯片自动协商网口速率和双工模式,程序带网口热插拔检测:

5. DHCP获取IPv4地址,SLAAC获取IPv6地址:

【开发环境】

Verilog开发环境:

C语言开发环境:

【Qsys连线】

基本架构:三速以太网IP核负责收发PHY芯片的数据包,通过SGDMA将数据包内容传输给C语言处理。NIOS II核负责运行C语言程序,其中包括了lwip2.1.2协议栈。Interval Timer负责提供毫秒计数器,供lwip的sys_now函数使用。
NIOS从onchip memory中启动(也就是reset和exception vector位于onchip memory),但程序运行在SDRAM中,SGDMA的描述符和缓冲区全部位于SDRAM中。


提示:uart_0、sysid_qsys_0、timer_0、eth_tse_0、sgdma_0和sgdma_1不包含程序代码,不用连接到nios2的instruction_master上。

三速以太网IP核配置的是10/100Mb Small MAC模式,选择MII接口,使能了MDIO接口和半双工模式的支持。

【主要程序代码】

main.v:

请注意MII接口的eth_tx_clk和eth_rx_clk都是输入信号,由PHY芯片提供,而且必须要经过ALTCLKCTRL IP核的缓冲后才能使用

module main(
    input clock,
    input uart_rx,
    output uart_tx,
    output sdram_clk,
    output [11:0] sdram_addr,
    output [1:0] sdram_ba,
    output sdram_cas_n,
    output sdram_cke,
    output sdram_cs_n,
    inout [15:0] sdram_dq,
    output [1:0] sdram_dqm,
    output sdram_ras_n,
    output sdram_we_n,
    output eth_rst_n,
    output eth_mdc,
    inout eth_mdio,
    input eth_col,
    input eth_crs,
    input eth_tx_clk,
    output eth_tx_en,
    output [3:0] eth_txd,
    input eth_rx_clk,
    input eth_rx_dv,
    input [3:0] eth_rxd,
    input eth_rx_er
    );
    
    /* 产生复位信号 */
    wire nrst;
    Reset reset(clock, nrst);
    
    /* PLL倍频 */
    wire altpll_c0;
    wire altpll_locked;
    altpll_0 altpll_0(
        .areset(~nrst),
        .inclk0(clock),
        .c0(altpll_c0), // 频率等于clock, 但相位相差63度, 供SDRAM使用
        .locked(altpll_locked)
    );
    
    /* 缓冲eth_rx_clk和eth_tx_clk时钟输入信号, 避免CRC错误 */
    wire eth_rx_clk_g;
    wire eth_tx_clk_g;
    altclkctrl_0 altclkctrl_0(
        .inclk(eth_rx_clk),
        .outclk(eth_rx_clk_g)
    );
    altclkctrl_1 altclkctrl_1(
        .inclk(eth_tx_clk),
        .outclk(eth_tx_clk_g)
    );
    
    /* NIOS II */
    wire eth_tse_0_mac_mdio_connection_mdio_oen;
    wire eth_tse_0_mac_mdio_connection_mdio_out;
    
    wire eth_tse_0_mac_mii_connection_mii_tx_err;
    
    wire eth_tse_0_mac_misc_connection_ff_rx_a_empty;
    wire eth_tse_0_mac_misc_connection_ff_rx_a_full;
    wire eth_tse_0_mac_misc_connection_ff_rx_dsav;
    wire eth_tse_0_mac_misc_connection_ff_tx_a_empty;
    wire eth_tse_0_mac_misc_connection_ff_tx_a_full;
    wire eth_tse_0_mac_misc_connection_ff_tx_septy;
    wire eth_tse_0_mac_misc_connection_magic_wakeup;
    wire [17:0] eth_tse_0_mac_misc_connection_rx_err_stat;
    wire [3:0] eth_tse_0_mac_misc_connection_rx_frm_type;
    wire eth_tse_0_mac_misc_connection_tx_ff_uflow;
    
    wire eth_tse_0_mac_status_connection_ena_10;
    wire eth_tse_0_mac_status_connection_eth_mode;
    
    assign sdram_clk = altpll_c0;
    assign eth_mdio = (!eth_tse_0_mac_mdio_connection_mdio_oen) ? eth_tse_0_mac_mdio_connection_mdio_out : 1'bz;
    assign eth_rst_n = altpll_locked;
    
    nios nios(
        .clk_clk(clock),
        .reset_reset_n(altpll_locked),
        .eth_tse_0_mac_mdio_connection_mdc(eth_mdc),
        .eth_tse_0_mac_mdio_connection_mdio_in(eth_mdio),
        .eth_tse_0_mac_mdio_connection_mdio_oen(eth_tse_0_mac_mdio_connection_mdio_oen),
        .eth_tse_0_mac_mdio_connection_mdio_out(eth_tse_0_mac_mdio_connection_mdio_out),
        
        .eth_tse_0_mac_mii_connection_mii_rx_d(eth_rxd),
        .eth_tse_0_mac_mii_connection_mii_rx_dv(eth_rx_dv),
        .eth_tse_0_mac_mii_connection_mii_rx_err(eth_rx_er),
        .eth_tse_0_mac_mii_connection_mii_tx_d(eth_txd),
        .eth_tse_0_mac_mii_connection_mii_tx_en(eth_tx_en),
        .eth_tse_0_mac_mii_connection_mii_tx_err(eth_tse_0_mac_mii_connection_mii_tx_err),
        
        .eth_tse_0_mac_misc_connection_ff_rx_a_empty(eth_tse_0_mac_misc_connection_ff_rx_a_empty),
        .eth_tse_0_mac_misc_connection_ff_rx_a_full(eth_tse_0_mac_misc_connection_ff_rx_a_full),
        .eth_tse_0_mac_misc_connection_ff_rx_dsav(eth_tse_0_mac_misc_connection_ff_rx_dsav),
        .eth_tse_0_mac_misc_connection_ff_tx_a_empty(eth_tse_0_mac_misc_connection_ff_tx_a_empty),
        .eth_tse_0_mac_misc_connection_ff_tx_a_full(eth_tse_0_mac_misc_connection_ff_tx_a_full),
        .eth_tse_0_mac_misc_connection_ff_tx_crc_fwd(1'b0),
        .eth_tse_0_mac_misc_connection_ff_tx_septy(eth_tse_0_mac_misc_connection_ff_tx_septy),
        .eth_tse_0_mac_misc_connection_magic_sleep_n(1'b1),
        .eth_tse_0_mac_misc_connection_magic_wakeup(eth_tse_0_mac_misc_connection_magic_wakeup),
        .eth_tse_0_mac_misc_connection_rx_err_stat(eth_tse_0_mac_misc_connection_rx_err_stat),
        .eth_tse_0_mac_misc_connection_rx_frm_type(eth_tse_0_mac_misc_connection_rx_frm_type),
        .eth_tse_0_mac_misc_connection_tx_ff_uflow(eth_tse_0_mac_misc_connection_tx_ff_uflow),
        .eth_tse_0_mac_misc_connection_xoff_gen(1'b0),
        .eth_tse_0_mac_misc_connection_xon_gen(1'b0),
        
        .eth_tse_0_mac_status_connection_ena_10(eth_tse_0_mac_status_connection_ena_10),
        .eth_tse_0_mac_status_connection_eth_mode(eth_tse_0_mac_status_connection_eth_mode),
        .eth_tse_0_mac_status_connection_set_10(1'b0),
        .eth_tse_0_mac_status_connection_set_1000(1'b0),
        
        .eth_tse_0_pcs_mac_rx_clock_connection_clk(eth_rx_clk_g),
        .eth_tse_0_pcs_mac_tx_clock_connection_clk(eth_tx_clk_g),
        
        .new_sdram_controller_0_wire_addr(sdram_addr),
        .new_sdram_controller_0_wire_ba(sdram_ba),
        .new_sdram_controller_0_wire_cas_n(sdram_cas_n),
        .new_sdram_controller_0_wire_cke(sdram_cke),
        .new_sdram_controller_0_wire_cs_n(sdram_cs_n),
        .new_sdram_controller_0_wire_dq(sdram_dq),
        .new_sdram_controller_0_wire_dqm(sdram_dqm),
        .new_sdram_controller_0_wire_ras_n(sdram_ras_n),
        .new_sdram_controller_0_wire_we_n(sdram_we_n),
        
        .uart_0_external_connection_rxd(uart_rx),
        .uart_0_external_connection_txd(uart_tx)
    );
    
endmodule

hello_world.c:

/*
 * "Hello World" example.
 *
 * This example prints 'Hello from Nios II' to the STDOUT stream. It runs on
 * the Nios II 'standard', 'full_featured', 'fast', and 'low_cost' example
 * designs. It runs with or without the MicroC/OS-II RTOS and requires a STDOUT
 * device in your system's hardware.
 * The memory footprint of this hosted application is ~69 kbytes by default
 * using the standard reference design.
 *
 * For a reduced footprint version of this template, and an explanation of how
 * to reduce the memory footprint for a given application, see the
 * "small_hello_world" template.
 *
 */

#include <lwip/apps/httpd.h>
#include <lwip/apps/netbiosns.h>
#include <lwip/dhcp.h>
#include <lwip/dns.h>
#include <lwip/init.h>
#include <lwip/netif.h>
#include <lwip/timeouts.h>
#include <netif/ethernetif.h>
#include <stdio.h>
#include <sys/alt_alarm.h>
#include <system.h>

static struct netif netif_rtl8201cp;

alt_u32 sys_now(void)
{
	// BSP Editor里面Settings -> Common -> hal -> sys_clk_timer必须选择一个定时器
	// 而且该定时器的计时间隔必须为1ms
	LWIP_ASSERT("incorrect tick rate", alt_ticks_per_second() == 1000);
	return alt_nticks();
}

static void display_ip(void)
{
	const ip_addr_t *addr;
	static uint8_t ip_displayed = 0;
	static uint8_t ip6_displayed = 0;
	int i, ip_present;
	int dns = 0;

	if (netif_dhcp_data(&netif_rtl8201cp) == NULL)
		ip_present = 1; // 使用静态IP地址
	else if (dhcp_supplied_address(&netif_rtl8201cp))
		ip_present = 2; // 使用DHCP获得IP地址, 且已成功获取到IP地址
	else
		ip_present = 0; // 使用DHCP获得IP地址, 且还没有获取到IP地址

	// 显示IPv4地址
	if (ip_present)
	{
		if (ip_displayed == 0)
		{
			ip_displayed = 1;

			if (ip_present == 2)
				printf("DHCP supplied address!\r\n");
			printf("IP address: %s\r\n", ipaddr_ntoa(&netif_rtl8201cp.ip_addr));
			printf("Subnet mask: %s\r\n", ipaddr_ntoa(&netif_rtl8201cp.netmask));
			printf("Default gateway: %s\r\n", ipaddr_ntoa(&netif_rtl8201cp.gw));
			dns = 1;
		}
	}
	else
		ip_displayed = 0;

	// 显示IPv6地址
	for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; i++) // 0号地址是本地链路地址, 不需要显示
	{
		if (ip6_addr_isvalid(netif_ip6_addr_state(&netif_rtl8201cp, i)))
		{
			if ((ip6_displayed & _BV(i)) == 0)
			{
				ip6_displayed |= _BV(i);
				printf("IPv6 address %d: %s\r\n", i, ipaddr_ntoa(netif_ip_addr6(&netif_rtl8201cp, i)));
				dns = 1;
			}
		}
		else
			ip6_displayed &= ~_BV(i);
	}

	// 显示DNS服务器地址
	// 在lwip中, IPv4 DHCP和IPv6 SLAAC获取到的DNS地址会互相覆盖
	if (dns)
	{
		addr = dns_getserver(0);
		if (ip_addr_isany(addr))
			return;
		printf("DNS Server: %s", ipaddr_ntoa(addr));

		addr = dns_getserver(1);
		if (!ip_addr_isany(addr))
			printf(" %s", ipaddr_ntoa(addr));

		printf("\r\n");
	}
}

static void net_config(int use_dhcp)
{
	ip4_addr_t ipaddr, netmask, gw;

	if (use_dhcp)
		netif_add_noaddr(&netif_rtl8201cp, NULL, ethernetif_init, netif_input);
	else
	{
		IP4_ADDR(&ipaddr, 192, 168, 0, 19);
		IP4_ADDR(&netmask, 255, 255, 255, 0);
		IP4_ADDR(&gw, 192, 168, 0, 1);
		netif_add(&netif_rtl8201cp, &ipaddr, &netmask, &gw, NULL, ethernetif_init, netif_input);
	}
	netif_set_default(&netif_rtl8201cp);
	netif_set_up(&netif_rtl8201cp);

	if (use_dhcp)
		dhcp_start(&netif_rtl8201cp);

	netif_create_ip6_linklocal_address(&netif_rtl8201cp, 1);
	printf("IPv6 link-local address: %s\r\n", ipaddr_ntoa(netif_ip_addr6(&netif_rtl8201cp, 0)));
	netif_set_ip6_autoconfig_enabled(&netif_rtl8201cp, 1);
}

int main(void)
{
	printf("Hello from Nios II!\r\n");

	lwip_init();
	net_config(1);

	httpd_init();
	netbiosns_init();
	netbiosns_set_name("EP4CE10F17C8");

	while (1)
	{
		ethernetif_check_link(&netif_rtl8201cp);
		display_ip();

		ethernetif_input(&netif_rtl8201cp);
		sys_check_timeouts();
	}
}

ethernetif.c(网口驱动):
备注:官网lwip2.1版本的压缩包(lwip-2.1.0.zip)中的src/netif文件夹下没有ethernetif.c了,那个文件是被移动到contrib-2.1.0.zip的examples/ethernetif文件夹下去了。

/**
 * @file
 * Ethernet Interface Skeleton
 *
 */

/*
 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

/*
 * This file is a skeleton for developing Ethernet network interface
 * drivers for lwIP. Add code to the low_level functions and do a
 * search-and-replace for the word "ethernetif" to replace it with
 * something that better describes your network interface.
 */

#include "lwip/opt.h"

#if 1 /* don't build, this is only a skeleton, see previous comment */

#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/pbuf.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"
#include "lwip/ethip6.h"
#include "lwip/etharp.h"
#include "netif/ppp/pppoe.h"

#include <altera_avalon_sgdma.h>
#include <altera_avalon_sgdma_regs.h>
#include <altera_avalon_tse.h>
#include <netif/ethernetif.h>
#include <string.h>
#include <sys/alt_cache.h>
#include <system.h>

/* Define those to better describe your network interface. */
#define IFNAME0 'e'
#define IFNAME1 'n'

/**
 * Helper struct to hold private data used to operate your ethernet interface.
 * Keeping the ethernet address of the MAC in this struct is not necessary
 * as it is already kept in the struct netif.
 * But this is only an example, anyway...
 */
struct ethernetif {
  struct eth_addr *ethaddr;
  /* Add whatever per-interface state that is needed here. */
  np_tse_mac *tse_mac;
  alt_sgdma_dev *sgdma_rx;
  alt_sgdma_dev *sgdma_tx;
};

/* Forward declarations. */
//static void  ethernetif_input(struct netif *netif);

// 收发描述符和缓冲区
static alt_sgdma_descriptor sgdma_rx_desc[2];
static alt_sgdma_descriptor sgdma_tx_desc[2];
static alt_u32 sgdma_rx_buf[400];
static alt_u32 sgdma_tx_buf[400];

/**
 * In this function, the hardware should be initialized.
 * Called from ethernetif_init().
 *
 * @param netif the already initialized lwip network interface structure
 *        for this ethernetif
 */
static void
low_level_init(struct netif *netif)
{
  struct ethernetif *ethernetif = netif->state;

  /* set MAC hardware address length */
  netif->hwaddr_len = ETHARP_HWADDR_LEN;

  /* set MAC hardware address */
  // 设置MAC地址
  netif->hwaddr[0] = 0x00;
  netif->hwaddr[1] = 0x1c;
  netif->hwaddr[2] = 0x23;
  netif->hwaddr[3] = 0x17;
  netif->hwaddr[4] = 0x4a;
  netif->hwaddr[5] = 0xcb;
  printf("MAC address: %02X:%02X:%02X:%02X:%02X:%02X\r\n", netif->hwaddr[0], netif->hwaddr[1], netif->hwaddr[2], netif->hwaddr[3], netif->hwaddr[4], netif->hwaddr[5]);

  /* maximum transfer unit */
  netif->mtu = 1500;

  /* device capabilities */
  /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */
  netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP/* | NETIF_FLAG_LINK_UP*/; // 初始状态下认为网线还没有插
  netif->flags |= NETIF_FLAG_MLD6; // 启用IPv6多播

#if LWIP_IPV6 && LWIP_IPV6_MLD
  /*
   * For hardware/netifs that implement MAC filtering.
   * All-nodes link-local is handled by default, so we must let the hardware know
   * to allow multicast packets in.
   * Should set mld_mac_filter previously. */
  if (netif->mld_mac_filter != NULL) {
    ip6_addr_t ip6_allnodes_ll;
    ip6_addr_set_allnodes_linklocal(&ip6_allnodes_ll);
    netif->mld_mac_filter(netif, &ip6_allnodes_ll, NETIF_ADD_MAC_FILTER);
  }
#endif /* LWIP_IPV6 && LWIP_IPV6_MLD */

  /* Do whatever else is needed to initialize interface. */
  // IP核复位
  IOWR_ALTERA_TSEMAC_CMD_CONFIG(ETH_TSE_0_BASE, ALTERA_TSEMAC_CMD_SW_RESET_MSK);
  IOWR_ALTERA_TSEMAC_CMD_CONFIG(ETH_TSE_0_BASE, 0);
  IOWR_ALTERA_AVALON_SGDMA_CONTROL(SGDMA_0_BASE, ALTERA_AVALON_SGDMA_CONTROL_SOFTWARERESET_MSK);
  IOWR_ALTERA_AVALON_SGDMA_CONTROL(SGDMA_0_BASE, 0);
  IOWR_ALTERA_AVALON_SGDMA_CONTROL(SGDMA_1_BASE, ALTERA_AVALON_SGDMA_CONTROL_SOFTWARERESET_MSK);
  IOWR_ALTERA_AVALON_SGDMA_CONTROL(SGDMA_1_BASE, 0);

  // 配置IP核的MAC地址
  ethernetif->tse_mac = alt_remap_uncached((void *)ETH_TSE_0_BASE, sizeof(np_tse_mac));
  ethernetif->tse_mac->MAC_0 = (netif->hwaddr[3] << 24) | (netif->hwaddr[2] << 16) | (netif->hwaddr[1] << 8) | netif->hwaddr[0];
  ethernetif->tse_mac->MAC_1 = (netif->hwaddr[5] << 8) | netif->hwaddr[4];

  // 打开DMA
  ethernetif->sgdma_tx = alt_avalon_sgdma_open(SGDMA_0_NAME);
  ethernetif->sgdma_rx = alt_avalon_sgdma_open(SGDMA_1_NAME);

  printf("SGDMA Rx descriptor: %p\r\n", sgdma_rx_desc);
  printf("SGDMA Tx descriptor: %p\r\n", sgdma_tx_desc);
  printf("SGDMA Rx buffer: %p\r\n", sgdma_rx_buf);
  printf("SGDMA Tx buffer: %p\r\n", sgdma_tx_buf);
}

/**
 * This function should do the actual transmission of the packet. The packet is
 * contained in the pbuf that is passed to the function. This pbuf
 * might be chained.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type)
 * @return ERR_OK if the packet could be sent
 *         an err_t value if the packet couldn't be sent
 *
 * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to
 *       strange results. You might consider waiting for space in the DMA queue
 *       to become available since the stack doesn't retry to send a packet
 *       dropped because of memory failure (except for the TCP timers).
 */

static err_t
low_level_output(struct netif *netif, struct pbuf *p)
{
  struct ethernetif *ethernetif = netif->state;
  struct pbuf *q;
  alt_u8 *data = (alt_u8 *)sgdma_tx_buf + 2;
  alt_u8 status = 0;

  //initiate transfer();
  LWIP_ASSERT("tx packet too big", p->tot_len + 2 <= sizeof(sgdma_tx_buf));

#if ETH_PAD_SIZE
  pbuf_remove_header(p, ETH_PAD_SIZE); /* drop the padding word */
#endif

  for (q = p; q != NULL; q = q->next) {
    /* Send the data from the pbuf to the interface, one pbuf at a
       time. The size of the data in each pbuf is kept in the ->len
       variable. */
    //send data from(q->payload, q->len);
    memcpy(data, q->payload, q->len);
    data += q->len;
  }
  alt_dcache_flush(sgdma_tx_buf, sizeof(sgdma_tx_buf)); // 写完数据, 交给DMA之前必须清除一下缓存

  //signal that packet should be sent();
  if (netif_is_link_up(netif))
  {
    alt_avalon_sgdma_construct_mem_to_stream_desc(&sgdma_tx_desc[0], &sgdma_tx_desc[1], sgdma_tx_buf, p->tot_len + 2, 0, 1, 1, 0);
    status = alt_avalon_sgdma_do_sync_transfer(ethernetif->sgdma_tx, &sgdma_tx_desc[0]);
  }
  if (status == 0x0c)
    printf("[Send] len=%d\r\n", p->tot_len);
  else
    printf("[Send] len=%d (failed)\r\n", p->tot_len);

  MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p->tot_len);
  if (((u8_t *)p->payload)[0] & 1) {
    /* broadcast or multicast packet*/
    MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts);
  } else {
    /* unicast packet */
    MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
  }
  /* increase ifoutdiscards or ifouterrors on error */

#if ETH_PAD_SIZE
  pbuf_add_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif

  LINK_STATS_INC(link.xmit);

  return ERR_OK;
}

/**
 * Should allocate a pbuf and transfer the bytes of the incoming
 * packet from the interface into the pbuf.
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return a pbuf filled with the received packet (including MAC header)
 *         NULL on memory error
 */
static struct pbuf *
low_level_input(struct netif *netif)
{
  struct ethernetif *ethernetif = netif->state;
  struct pbuf *p = NULL, *q; // 这里p一定不要忘了赋初值
  alt_u8 *data = (alt_u8 *)sgdma_rx_buf + 2;
  int ret;
  u16_t len;

  /* Obtain the size of the packet and put it into the "len"
     variable. */
  ret = alt_avalon_sgdma_check_descriptor_status(&sgdma_rx_desc[0]);
  if (ret == -EINPROGRESS)
    return NULL; // 未收到数据包, 退出
  else if (ret == -EIO)
  {
    // 出错时清除错误标志, 否则将无法启动新的DMA传输
    IOWR_ALTERA_AVALON_SGDMA_STATUS(ethernetif->sgdma_rx->base, ALTERA_AVALON_SGDMA_STATUS_ERROR_MSK);
    alt_avalon_sgdma_stop(ethernetif->sgdma_rx);
  }

  // 计算收到的数据包的大小
  len = sgdma_rx_desc[0].actual_bytes_transferred;
  LWIP_ASSERT("rx packet too big", len <= sizeof(sgdma_rx_buf));
  if (len <= 2)
    goto end;
  len -= 2;
  if (sgdma_rx_desc[0].status == 0x80)
    printf("[Recv] len=%u\r\n", len);
  else
  {
    printf("[Recv] len=%u, err=0x%02x\r\n", len, sgdma_rx_desc[0].status);
    // err=0x85表示CRC错误, 0x89表示数据包因为FIFO满了被截断
    goto end;
  }

#if ETH_PAD_SIZE
  len += ETH_PAD_SIZE; /* allow room for Ethernet padding */
#endif

  /* We allocate a pbuf chain of pbufs from the pool. */
  p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);

  if (p != NULL) {

#if ETH_PAD_SIZE
    pbuf_remove_header(p, ETH_PAD_SIZE); /* drop the padding word */
#endif

    /* We iterate over the pbuf chain until we have read the entire
     * packet into the pbuf. */
    alt_dcache_flush(sgdma_rx_buf, sizeof(sgdma_rx_buf)); // 读数据前必须清除一下缓存
    for (q = p; q != NULL; q = q->next) {
      /* Read enough bytes to fill this pbuf in the chain. The
       * available data in the pbuf is given by the q->len
       * variable.
       * This does not necessarily have to be a memcpy, you can also preallocate
       * pbufs for a DMA-enabled MAC and after receiving truncate it to the
       * actually received size. In this case, ensure the tot_len member of the
       * pbuf is the sum of the chained pbuf len members.
       */
      //read data into(q->payload, q->len);
      memcpy(q->payload, data, q->len);
      data += q->len;
    }
    //acknowledge that packet has been read();

    MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len);
    if (((u8_t *)p->payload)[0] & 1) {
      /* broadcast or multicast packet*/
      MIB2_STATS_NETIF_INC(netif, ifinnucastpkts);
    } else {
      /* unicast packet*/
      MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
    }
#if ETH_PAD_SIZE
    pbuf_add_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif

    LINK_STATS_INC(link.recv);
  } else {
    //drop packet();
    LINK_STATS_INC(link.memerr);
    LINK_STATS_INC(link.drop);
    MIB2_STATS_NETIF_INC(netif, ifindiscards);
  }

end:
  // 继续接收后续数据包
  alt_avalon_sgdma_construct_stream_to_mem_desc(&sgdma_rx_desc[0], &sgdma_rx_desc[1], sgdma_rx_buf, 0, 0);
  ret = alt_avalon_sgdma_do_async_transfer(ethernetif->sgdma_rx, &sgdma_rx_desc[0]);
  if (ret != 0)
    printf("Failed to start reception!\r\n");

  return p;
}

/**
 * This function should be called when a packet is ready to be read
 * from the interface. It uses the function low_level_input() that
 * should handle the actual reception of bytes from the network
 * interface. Then the type of the received packet is determined and
 * the appropriate input function is called.
 *
 * @param netif the lwip network interface structure for this ethernetif
 */
void
ethernetif_input(struct netif *netif)
{
  struct ethernetif *ethernetif;
  //struct eth_hdr *ethhdr;
  struct pbuf *p;

  ethernetif = netif->state;

  /* move received packet into a new pbuf */
  p = low_level_input(netif);
  /* if no packet could be read, silently ignore this */
  if (p != NULL) {
    /* pass all packets to ethernet_input, which decides what packets it supports */
    if (netif->input(p, netif) != ERR_OK) {
      LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
      pbuf_free(p);
      p = NULL;
    }
  }
}

/**
 * Should be called at the beginning of the program to set up the
 * network interface. It calls the function low_level_init() to do the
 * actual setup of the hardware.
 *
 * This function should be passed as a parameter to netif_add().
 *
 * @param netif the lwip network interface structure for this ethernetif
 * @return ERR_OK if the loopif is initialized
 *         ERR_MEM if private data couldn't be allocated
 *         any other err_t on error
 */
err_t
ethernetif_init(struct netif *netif)
{
  struct ethernetif *ethernetif;

  LWIP_ASSERT("netif != NULL", (netif != NULL));

  ethernetif = mem_malloc(sizeof(struct ethernetif));
  if (ethernetif == NULL) {
    LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_init: out of memory\n"));
    return ERR_MEM;
  }

#if LWIP_NETIF_HOSTNAME
  /* Initialize interface hostname */
  netif->hostname = "EP4CE10F17C8_TSE"; // 路由器里面看到的设备名称
#endif /* LWIP_NETIF_HOSTNAME */

  /*
   * Initialize the snmp variables and counters inside the struct netif.
   * The last argument should be replaced with your link speed, in units
   * of bits per second.
   */
  MIB2_INIT_NETIF(netif, snmp_ifType_ethernet_csmacd, LINK_SPEED_OF_YOUR_NETIF_IN_BPS);

  netif->state = ethernetif;
  netif->name[0] = IFNAME0;
  netif->name[1] = IFNAME1;
  /* We directly use etharp_output() here to save a function call.
   * You can instead declare your own function an call etharp_output()
   * from it if you have to do some checks before sending (e.g. if link
   * is available...) */
#if LWIP_IPV4
  netif->output = etharp_output;
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
  netif->output_ip6 = ethip6_output;
#endif /* LWIP_IPV6 */
  netif->linkoutput = low_level_output;

  ethernetif->ethaddr = (struct eth_addr *) & (netif->hwaddr[0]);

  /* initialize the hardware */
  low_level_init(netif);

  return ERR_OK;
}

/* 网线插拔检测 */
void ethernetif_check_link(struct netif *netif)
{
	struct ethernetif *ethernetif = netif->state;

	if (ethernetif->tse_mac->mdio1.STATUS & PHY_LINKED_STATUS)
	{
		/* 已插入网线 */
		if (!netif_is_link_up(netif))
		{
			if (ethernetif->tse_mac->mdio1.STATUS & PHY_AUTONEGO_COMPLETE) // 自动协商完毕
			{
				// 配置速率和双工模式
				printf("Link is up!\r\n");
				if (ethernetif->tse_mac->mdio1.CONTROL & PHY_SPEED_STATUS)
				{
					printf("Speed: 100Mbps\r\n");
					ethernetif->tse_mac->COMMAND_CONFIG &= ~ALTERA_TSEMAC_CMD_ENA_10_MSK;
				}
				else
				{
					printf("Speed: 10Mbps\r\n");
					ethernetif->tse_mac->COMMAND_CONFIG |= ALTERA_TSEMAC_CMD_ENA_10_MSK;
				}
				if (ethernetif->tse_mac->mdio1.CONTROL & PHY_DUPLEX_STATUS)
				{
					printf("Duplex: full\r\n");
					ethernetif->tse_mac->COMMAND_CONFIG &= ~ALTERA_TSEMAC_CMD_HD_ENA_MSK;
				}
				else
				{
					printf("Duplex: half\r\n");
					ethernetif->tse_mac->COMMAND_CONFIG |= ALTERA_TSEMAC_CMD_HD_ENA_MSK;
				}

				ethernetif->tse_mac->COMMAND_CONFIG |= ALTERA_TSEMAC_CMD_TX_ENA_MSK | ALTERA_TSEMAC_CMD_RX_ENA_MSK; // 打开收发
				netif_set_link_up(netif);
			}
		}
	}
	else
	{
		/* 已拔出网线 */
		if (netif_is_link_up(netif))
		{
			printf("Link is down!\r\n");
			ethernetif->tse_mac->COMMAND_CONFIG &= ~(ALTERA_TSEMAC_CMD_TX_ENA_MSK | ALTERA_TSEMAC_CMD_RX_ENA_MSK); // 关闭收发
			netif_set_link_down(netif);
		}
	}
}

#endif /* 0 */

arch/cc.h:

#ifndef LWIP_ARCH_CC_H
#define LWIP_ARCH_CC_H

#define LWIP_RAND() ((u32_t)rand())
#define PACK_STRUCT_BEGIN __attribute__((packed, aligned(1)))

#endif

lwipopts.h:

#ifndef LWIP_LWIPOPTS_H
#define LWIP_LWIPOPTS_H

#define NO_SYS 1 // 无操作系统
#define SYS_LIGHTWEIGHT_PROT 0 // 不进行临界区保护

#define LWIP_NETCONN 0
#define LWIP_SOCKET 0

#define MEM_ALIGNMENT 4 // 4字节对齐方式
#define MEM_SIZE (64 * 1024) // lwip的mem_malloc函数使用的堆内存的大小
#define MEM_OVERFLOW_CHECK 1
#define MEM_SANITY_CHECK 1

// 配置TCP
#define TCP_MSS 1500
#define LWIP_TCP_SACK_OUT 1 // 允许批量确认

// 配置DHCP
#define LWIP_DHCP 1
#define LWIP_NETIF_HOSTNAME 1

// 配置DNS
#define LWIP_DNS 1

// 配置HTTP服务器
#define HTTPD_FSDATA_FILE "fsdata_custom.h"

// 广播包过滤器
#define IP_SOF_BROADCAST 1
#define IP_SOF_BROADCAST_RECV 1

// 配置IPv6
#define LWIP_IPV6 1
#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS LWIP_DNS // 允许SLAAC获取DNS服务器的地址

#endif

【程序运行结果】

Hello from Nios II!
MAC address: 00:1C:23:17:4A:CB
SGDMA Rx descriptor: 0x204d904
SGDMA Tx descriptor: 0x204d944
SGDMA Rx buffer: 0x204d984
SGDMA Tx buffer: 0x204dfc4
IPv6 link-local address: FE80::21C:23FF:FE17:4ACB
Link is up!
Speed: 100Mbps
Duplex: full
[Send] len=350
[Send] len=86
[Send] len=78
[Send] len=62
[Send] len=86
Link is down!
[Send] len=350 (failed)
Link is up!
Speed: 100Mbps
Duplex: full
[Send] len=350
[Send] len=86
[Recv] len=60
[Send] len=70
[Send] len=350
[Recv] len=60
[Recv] len=60
[Send] len=70
[Recv] len=142
[Send] len=86
[Recv] len=86
[Send] len=350
[Recv] len=60
[Send] len=78
[Recv] len=208
[Recv] len=60
[Recv] len=60
IPv6 address 1: 2409:8A62:369:3410:21C:23FF:FE17:4ACB
DNS Server: FE80::1
[Send] len=86
[Recv] len=86
[Recv] len=590
[Send] len=350
[Recv] len=590
[Send] len=42
[Send] len=42
[Send] len=42
[Recv] len=86
[Send] len=42
DHCP supplied address!
IP address: 192.168.1.7
Subnet mask: 255.255.255.0
Default gateway: 192.168.1.1
DNS Server: 192.168.1.1
[Recv] len=60
[Send] len=42
[Recv] len=86
[Send] len=42
[Recv] len=86
[Send] len=86
[Recv] len=208
[Recv] len=60
[Send] len=42
[Recv] len=60
[Recv] len=60
[Recv] len=208

【程序固化方法】

在外部SDRAM中运行的NIOS II程序的固化方法_ZLK1214的专栏-CSDN博客

ethernetif.c中有这样一行代码:ethernetif->tse_mac = alt_remap_uncached((void *)ETH_TSE_0_BASE, sizeof(np_tse_mac));
本来这行代码是:ethernetif->tse_mac = (np_tse_mac *)ETH_TSE_0_BASE;
之所以要加上alt_remap_uncached,是为了在这段内存上禁用dcache缓冲,避免程序固化后运行,ethernetif_check_link函数无法正常检测网线插拔,导致程序卡死。
alt_remap_uncached函数的原理:
NIOS C语言指针的最高位(第31位)具有特殊含义。若最高位为1,则是强制读写原始内存单元,不经过dcache。
比如a变量的地址是0x1234,若读取0x80001234这个地址,则是不经过dcache直接读a变量的值。
若读取0x1234这个地址,则有可能从dcache里面去取a变量的缓存值。
alt_remap_uncached的实现方式是将第一个参数的最高位置1,然后作为返回值返回

【lwip自带httpd服务器的简单应用】

小梅哥AC620开发板NIOS II LWIP实现HTTP网页控制数码管的显示内容

【扩展阅读】

 开拓者Nios II开发指南_V1.3
下载链接:百度网盘 请输入提取码(提取码:qnis)

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨大八爪鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值