Internet实现了全球范围内计算机网络的互连,不同主机之间必须遵循相同的网络协议才能彼此通信。TCP/IP协议作为一种网络互联协议,在Internet中得到了最广泛的支持以及应用。笔者此处就轻量级TCP/IP协议Lwip的移植作一个简单的介绍。
1. TCP/IP协议概述
TCP/IP协议是Internet上使用最广泛的通信协议,其实际上是一个协议簇,其中TCP协议和IP协议是其中两个最重要的协议。
TCP/IP协议采用4层层级结构:应用层、运输层、网络层、链路层。相应的层级除了能够向上一层提供服务,还需要使用下一层所提供的服务。
1.1. 链路层
数据链路层将网络层交下来的IP数据报组装成帧,在两个相邻结点间的链路上透明传送以帧为单位的数据,另一结点若收到无差错的帧,则从收到的帧中提取出IP数据报上交上一层,否则丢弃此包。这一层级帧格式通常采用Ethernet V2,有效的MAC帧长度为64~1518字节,通常由网络适配器实现这一层级。
1.2. 网络层
网络层把运输层产生的报文段或用户数据报封装成分组或包进行传送,由于网络层使用无连接的网际协议IP,因此,分组也称为IP数据报,并且是不可靠的。除了IP协议,网络层还需配套使用以下几个协议:地址解析协议ARP、逆地址解析协议RARP、因特网控制报文协议ICMP、因特网组管理协议IGMP。
1.3. 运输层
运输层向上面的应用层提供通信服务,具有复用和分用的功能。复用就是多个应用层进程可同时使用运输层的服务,分用则为运输层可以把收到的数据分别交付上面应用层中相应的进程。这一层级有两个不同的协议:传输控制协议TCP和用户数据报协议UDP。TCP提供面向连接的服务,数据传输单位为报文段,能够保证提供可靠的交付。其传输数据前必须先建立连接,结束传输后要释放连接,不提供广播或多播服务。UDP传输数据前不需要建立连接,数据传输单位为用户数据报,不保证提供可靠的交付。运输层接收到UDP报文后,不需要给出任何确认,可以实现广播或多播服务。
1.4. 应用层
应用层根据运输层提供的服务,实现不同主机中多个应用进程之间的通信和协同工作,由实际的应用规划应用进程在通信时所遵循的协议。在Internet中有很多标准的应用层协议如:域名系统DNS、文件传输协议FTP、超文本传输协议HTTP、远程终端协议TELNET、动态主机配置协议DHCP、简单网络管理协议SNMP等等。
2. Lwip概述
Lwip是瑞典计算机科学院(SICS)的Adam Dunkels开发的一个小型开源TCP/IP协议栈。作为轻量级TCP/IP协议,Lwip支持有操作系统以及无操作系统运行,其在保持TCP/IP协议主要功能的基础上,减少对RAM、ROM的占用,非常适合于嵌入式系统使用。
3. Lwip移植
对于一个可移植的开源协议栈,移植部分往往分成体系结构相关、操作系统相关、驱动接口相关这几个部分。此处以Lwip-1.4.1版本为例说明移植的相关代码文件。
3.1. 体系结构相关
3.1.1. cc.h
在cc.h中需实现cpu以及编译器相关的定义,Lwip为了可移植,使用了自身的数据类型,需根据使用的cpu以及编译器进行定义。网络字节序使用大端格式,并且其数据结构需严格按照字节对齐,此处定义cpu的字节序以及编译器字节对齐宏等。
#ifndef __ARCH_CC_H__#define __ARCH_CC_H__#include <stdio.h> /* printf, fflush, FILE */#include <stdlib.h> /* abort */#define LWIP_PROVIDE_ERRNO/* Define platform endianness (might already bedefined) */#define BYTE_ORDER LITTLE_ENDIAN/* Define generic types used in lwIP */typedef unsigned char u8_t;typedef signed char s8_t;typedef unsigned short u16_t;typedef signed short s16_t;typedef unsigned long u32_t;typedef signed long s32_t;typedef u32_t mem_ptr_t;typedef u32_t sys_prot_t;/* Define (sn)printf formatters for these lwIP types*/#define U16_F "hu"#define S16_F "hd"#define X16_F "hx"#define U32_F "lu"#define S32_F "ld"#define X32_F "lx"/* Compiler hints for packing structures */#define PACK_STRUCT_BEGIN#define PACK_STRUCT_STRUCT __attribute__((__packed__))#define PACK_STRUCT_END#define PACK_STRUCT_FIELD(x) x/* Plaform specific diagnostic output */#define LWIP_PLATFORM_DIAG(x) do { printf x; } while(0)#define LWIP_PLATFORM_ASSERT(x) do {printf("Assertion \"%s\" failed at line%d in %s\n", \x, __LINE__, __FILE__); fflush(NULL); abort(); }while(0)#endif /* __ARCH_CC_H__ */
3.1.2. perf.h
perf.h用于实现系统统计和测量相关头文件,在平时可以不用。
#ifndef __PERF_H__#define __PERF_H__#define PERF_START /* null definition */#define PERF_STOP(x) /* null definition */#endif /* __PERF_H__ */
3.2. 操作系统相关
3.2.1. sys_arch.h/sys_arch.c
在sys_arch.h/sys_arch.c中需实现操作系统相关的接口,主要是提供信号量、邮箱、临界区保护的接口实现,为了支持Lwip的完整功能,还需实现多线程接口,除此之外,Lwip还需使用系统时钟来确定一些模块(如ARP、TCP等)的超时处理。所有需在sys_arch.h/sys_arch.c中实现的接口函数均在sys.h中给出了原型,此处不使用操作系统,只需实现Lwip的系统时钟即可。
extern volatile uint32_t SystemTick;uint32_t sys_now(void){returnSystemTick;}
3.3. 驱动接口相关
3.3.1. ethernetif.c
Lwip最底层需要实现读写网卡,其中在源码包中ethernetif.c,已经给出了底层驱动接口模板的实现,因此只需要在模板中加入网卡驱动接口函数即可,主要是网卡初始化、网卡接收、网卡发送这三个函数。笔者使用的是DM9000A,驱动的实现在前面章节有详细的介绍,此处不再细述。
/* Define those to better describe your networkinterface. */#define IFNAME0 'e'#define IFNAME1 'n'struct ethernetif {structeth_addr *ethaddr;/* Addwhatever per-interface state that is needed here. */};struct netif DM9000_netif;static void low_level_init(struct netif *netif){/* set MAC hardware address length */netif->hwaddr_len = ETHARP_HWADDR_LEN;/* set MAC hardware address */netif->hwaddr[0] = default_enetaddr[0];netif->hwaddr[1] = default_enetaddr[1];netif->hwaddr[2] = default_enetaddr[2];netif->hwaddr[3] = default_enetaddr[3];netif->hwaddr[4] = default_enetaddr[4];netif->hwaddr[5] = default_enetaddr[5];/* maximum transfer unit */netif->mtu = 1500;/* device capabilities *//* don't set NETIF_FLAG_ETHARP if this device is notan ethernet one */netif->flags = NETIF_FLAG_BROADCAST |NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP;/* Do whatever else is needed to initialize interface.*/DM9000_Init();}static err_t low_level_output(struct netif *netif,struct pbuf *p){struct pbuf*q;uint16_tBuffer[1514/2];uint8_t*pBuffer;#if ETH_PAD_SIZEpbuf_header(p,-ETH_PAD_SIZE); /* drop the padding word */#endifpBuffer =(uint8_t *)Buffer;for(q = p; q!= NULL; q = q->next) {memcpy(pBuffer, q->payload, q->len);pBuffer +=q->len;}// signal thatpacket should be sent();DM9000_SendPacket(Buffer, p->tot_len);#if ETH_PAD_SIZEpbuf_header(p,ETH_PAD_SIZE); /* reclaim the padding word */#endifLINK_STATS_INC(link.xmit);return ERR_OK;}static struct pbuf * low_level_input(struct netif*netif){struct pbuf*p, *q;uint16_tBuffer[1514/2];uint8_t*pBuffer;int16_t len;/* Obtain thesize of the packet and put it into the "len" variable. */len =DM90000_ReceivePacket(Buffer);if (len <=0) {return NULL;}#if ETH_PAD_SIZElen +=ETH_PAD_SIZE; /* allow room for Ethernet padding */#endif/* We allocatea pbuf chain of pbufs from the pool. */p =pbuf_alloc(PBUF_RAW, len, PBUF_POOL);if (p != NULL){#if ETH_PAD_SIZEpbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */#endifpBuffer =(uint8_t *)Buffer;for(q = p; q!= NULL; q = q->next) {memcpy(q->payload, pBuffer, q->len);pBuffer+= q->len;}#if ETH_PAD_SIZEpbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */#endifLINK_STATS_INC(link.recv);} else {LINK_STATS_INC(link.memerr);LINK_STATS_INC(link.drop);}return p;}void ethernetif_input(struct netif *netif){struct eth_hdr*ethhdr;struct pbuf*p;/* movereceived packet into a new pbuf */p =low_level_input(netif);/* no packetcould be read, silently ignore this */if (p == NULL)return;/* points topacket payload, which starts with an Ethernet header */ethhdr =p->payload;switch(htons(ethhdr->type)) {/* IP or ARPpacket? */caseETHTYPE_IP:caseETHTYPE_ARP:#if PPPOE_SUPPORT/* PPPoEpacket? */caseETHTYPE_PPPOEDISC:caseETHTYPE_PPPOE:#endif /* PPPOE_SUPPORT */if(netif->input(p, netif)!=ERR_OK) {LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IPinput error\n"));pbuf_free(p);p = NULL;}break;default:pbuf_free(p);p = NULL;break;}}err_t ethernetif_init(struct netif *netif){structethernetif *ethernetif;LWIP_ASSERT("netif != NULL", (netif != NULL));ethernetif =mem_malloc(sizeof(struct ethernetif));if (ethernetif== NULL) {LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_init: out ofmemory\n"));returnERR_MEM;}#if LWIP_NETIF_HOSTNAME/* Initializeinterface hostname */netif->hostname = "lwip";#endif /* LWIP_NETIF_HOSTNAME */netif->state= ethernetif;netif->name[0] = IFNAME0;netif->name[1] = IFNAME1;netif->output = etharp_output;netif->linkoutput = low_level_output;ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]);/* initializethe hardware */low_level_init(netif);return ERR_OK;}void ethernetif_config(void){struct ip_addripaddr;struct ip_addrnetmask;struct ip_addrgw;/* IP addressdefault setting */IP4_ADDR(&ipaddr, 192, 168, 0, 20);IP4_ADDR(&netmask,255, 255 , 255, 0);IP4_ADDR(&gw, 192, 168, 0, 1);/* add thenetwork interface */netif_add(&DM9000_netif, &ipaddr, &netmask, &gw, NULL,ðernetif_init, ðernet_input);/* Registers the default network interface */netif_set_default(&DM9000_netif);netif_set_up(&DM9000_netif);}
3.4. Lwip配置
Lwip是可裁剪、可配置的TCP/IP协议栈,可根据具体的应用进行模块裁剪、资源分配等。Lwip所有的可配置项在源码中opt.h中默认给出配置,在lwipopts.h中进行具体应用特定的配置,可只针对所关心的选项进行配置,其它非关键选项可以直接由opt.h中默认配置。
#ifndef __LWIPOPTS_H__#define __LWIPOPTS_H__/*** NO_SYS==1:Provides VERY minimal functionality. Otherwise,* use lwIPfacilities.*/#define NO_SYS 1/***NO_SYS_NO_TIMERS==1: Drop support for sys_timeout when NO_SYS==1* Mainly forcompatibility to old versions.*/#define NO_SYS_NO_TIMERS 0/***MEM_ALIGNMENT: should be set to the alignment of the CPU*/#define MEM_ALIGNMENT 4/*** MEM_SIZE: thesize of the heap memory. If the application will send* a lot of datathat needs to be copied, this should be set high.*/#define MEM_SIZE (32*1024)/*** 在以太网帧头填充两字节,上层去掉帧头后使得IP数据报以字对齐,armv6架构以上* CPU支持非对齐访问,但效率低下,对于32位CPU,填充2字节*/#define ETH_PAD_SIZE 2/*** LWIP_ARP==1:Enable ARP functionality.*/#define LWIP_ARP 1/*** LWIP_DHCP==1:Enable DHCP module.*/#define LWIP_DHCP 0/*** LWIP_ICMP==1:Enable ICMP module inside the IP stack.* Be careful,disable that make your product non-compliant to RFC1122*/#define LWIP_ICMP 1/*** LWIP_TCP==1:Turn on TCP.*/#define LWIP_TCP 1/*** TCP_MSS: TCPMaximum segment size. (default is 536, a conservative default,* you mightwant to increase this.)* For thereceive side, this MSS is advertised to the remote side* when openinga connection. For the transmit size, this MSS sets* an upperlimit on the MSS advertised by the remote host.*/#define TCP_MSS (1500 - 40)/*** LWIP_UDP==1:Turn on UDP.*/#define LWIP_UDP 1/*** LWIP_SNMP==1:Turn on SNMP module. UDP must be available for SNMP* transport.*/#define LWIP_SNMP 0/*** LWIP_IGMP==1:Turn on IGMP module.*/#define LWIP_IGMP 0/*** LWIP_DNS==1:Turn on DNS module. UDP must be available for DNS* transport.*/#define LWIP_DNS 0/***LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c*/#define LWIP_HAVE_LOOPIF 0/***LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c*/#define LWIP_HAVE_SLIPIF 0/***PPP_SUPPORT==1: Enable PPP.*/#define PPP_SUPPORT 0/***LWIP_STATS==1: Enable statistics collection in lwip_stats.*/#define LWIP_STATS 0/*** LWIP_RAW==1:Enable application layer to hook into the IP layer itself.*/#define LWIP_RAW 1/***LWIP_SOCKET==1: Enable Socket API (require to use sockets.c)*/#define LWIP_SOCKET 0/***LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c)*/#define LWIP_NETCONN 0/*** #define LWIP_DEBUG: Enable LWIP Debug*///#define LWIP_DEBUG#define ETHARP_DEBUG LWIP_DBG_ON#define IP_DEBUG LWIP_DBG_ON#define TCP_OUTPUT_DEBUG LWIP_DBG_ON#define TCP_DEBUG LWIP_DBG_ON#endif /* __LWIPOPTS_H__ */
4. 应用编程
Lwip提供三种应用编程接口(API):底层的基于回调函数API(raw API)、高层的连续API(sequential API)、BSD API。
raw API把应用程序通过回调函数的方式驻留在TCP/IP代码中,具有最快的代码执行效率以及最少的硬件资源需求,但这样的应用程序不便于理解以及维护。
sequential API提供了一种通用的应用编程方法,与BSD标准的socket API非常类似,应用程序的执行是基于” open-read-write-close”模式。TCP/IP协议通信过程本质是事件驱动的,因此这种编程方式要求TCP/IP代码与应用程序在不同的线程运行。
BSD API进一步封装了sequential API,兼容于目前存在的socketAPI应用程序,非常便于与其它平台(unix、windows等)socket API应用程序相互之间的移植。但相对效率比较低,占用资源多。
Lwip在使用前必须先初始化整个协议栈,配置网卡参数后并启动。由于此处未采用操作系统,通过在中断中获取包接收事件,在主循环中处理该事件,把包上传给上层,同时也在主循环中处理Lwip的超时事件。此处以HTTP服务器为例说明Lwip raw API的编程。
volatile uint32_t SystemTick;static void Timer4_Callback(void){SystemTick++;// 1ms计数}void main(void){Uart_Init();printf("CPU: S3C2416@%dMHz\n",get_ARMCLK()/1000000);printf(" Fclk = %dMHz, Hclk = %dMHz, Pclk =%dMHz\n",get_FCLK()/1000000,get_HCLK()/1000000, get_PCLK()/1000000);// Initilaizethe LwIP stacklwip_init();// ip address192, 168, 0, 20ethernetif_config();Timer4_Init(1000,Timer4_Callback); // 1ms/tickTimer4_Start();// Httpwebserver Inithttpd_init();while (1) {if(DM9000_GetReceiveStatus()) {ethernetif_input(&DM9000_netif);}// Handletimeoutssys_check_timeouts();}}


5. 附录
S3C2416_MDK_Lwip.rar,包含Lwip完整移植工程。
