1/21/2012

lwIP網路卡驅動程式撰寫

lwIP網路卡驅動程式主要以輪詢模式(polling mode)運作。使用者將網路卡介面(network interface)透過netif_add()添加至lwIP後,其生命週期便由lwIP接管,之後只要在主程式迴圈(main program loop)中,按時輪詢網路卡驅動程式,將接收到的封包派送至通訊協定堆疊即可。驅動程式撰寫者,只需要專注於提供與lwIP相容之驅動程式介面即可。
精簡的介面
在lwIP架構下,網路卡驅動程式撰寫者需實作三個介面:初始化、傳送封包、接收封包。亦即,err_t (*init)(struct netif *netif)、err_t (*input)(struct pbuf *p, struct netif *netif)、err_t linkoutput(struct netif *netif, struct pbuf *p)。 初始化
網路卡驅動程式的初始化需透過函式err_t (* init)(struct netif *netif)。此函式將在註冊驅動程式之時,經由netif_add()傳遞至lwIP。

接收封包
網路卡接收到封包後, 可透過下列四個lwIP提供函式其中之一:ethernet_input()、ip_input()、tcpip_ethinput()、tcpip_input()將封包分派至通謝協定堆疊進行處理。上述四個函式各有不同的使用情境,於單執行緒並提供ARP功能之平台,如uboot,接收到的封包可直接搭配lwIP內建之ethernet_input()運作。為了確保對未來版本之lwIP的相容性,接收函式建議於netif_add()中指定,並透過netif內名為input之函式指標呼叫。

傳送封包
要能傳送封包,驅動程式需實作兩個介面linkoutput()與output(),這兩個介面以函式指標的方式存在於資料結構netif中。output()函式作用於幫IP封包添加link layer的header;在大多數情況下,output()可直接選用lwIP內建之etharp_output()。最終,output()函式結束時,網路封包將透過linkoutput()經由網路卡傳輸。總結來說,lwIP中網路封包之傳輸順序如下:IP堆疊->output()->linkoutput()->網路卡硬體。
output函式之原型:
err_t output(struct netif *netif, struct pbuf *p);
linkoutput函式之宣告:
err_t linkoutput(struct netif *netif, struct pbuf *p);

驅動程式範例
驅動程式的範例可參考lwip原始碼提供之ethernetif.c。ethernetif.c是一個範例,也是一個lwip網路驅動程式之框架(skeleton)。任何想要撰寫lwip網路卡驅動程式者,都應當詳細閱讀該原始檔。在lwip官網上也有其它的驅動程式實作可供下載。
/* 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. */
};

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

/**
 * 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 */
  netif->hwaddr[0] = ;
  ...
  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;
 
  /* Do whatever else is needed to initialize interface. */  
}

/**
 * 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 availale 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;

  initiate transfer();
  
#if ETH_PAD_SIZE
  pbuf_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);
  }

  signal that packet should be sent();

#if ETH_PAD_SIZE
  pbuf_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, *q;
  u16_t len;

  /* Obtain the size of the packet and put it into the "len"
     variable. */
  len = ;

#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_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. */
    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);
    }
    acknowledge that packet has been read();

#if ETH_PAD_SIZE
    pbuf_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);
  }

  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
 */
static 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);
  /* no packet could be read, silently ignore this */
  if (p == NULL) return;
  /* points to packet payload, which starts with an Ethernet header */
  ethhdr = p->payload;

  switch (htons(ethhdr->type)) {
  /* IP or ARP packet? */
  case ETHTYPE_IP:
  case ETHTYPE_ARP:
#if PPPOE_SUPPORT
  /* PPPoE packet? */
  case ETHTYPE_PPPOEDISC:
  case ETHTYPE_PPPOE:
#endif /* PPPOE_SUPPORT */
    /* full packet send to tcpip_thread to process */
    if (netif->input(p, netif)!=ERR_OK)
     { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n"));
       pbuf_free(p);
       p = NULL;
     }
    break;

  default:
    pbuf_free(p);
    p = NULL;
    break;
  }
}

/**
 * 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 = "lwip";
#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.
   */
  NETIF_INIT_SNMP(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...) */
  netif->output = etharp_output;
  netif->linkoutput = low_level_output;
  
  ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]);
  
  /* initialize the hardware */
  low_level_init(netif);

  return ERR_OK;
}

使用範例
驅動程式完成後,應用程式撰寫方式很簡單,首先把驅動程式加入lwip,接著在主迴圈對網路卡不斷進行輪詢即可。
static void ethernet_timer_init(void)
{
    ... ... ...
}

int ethernet_init(void)
{
    ... ... ...

    // Initialize LWIP
    lwip_init();

    // Add our netif to LWIP
    if (netif_add(ðernetif, &myip_addr, &netmask, &gw_addr, NULL,
                ethernetif_init, ethernet_input) == NULL)
    {
        return -1;
    }

    netif_set_default(ðernetif);
    netif_set_up(ðernetif);

    ... ... ...

    return 0;
}

void ethernet_poll(void)
{
    ... ... ...

    // Invokes network interface driver to process incoming packets
    ethernetif_input(ðernetif);

    // Process lwip network-related timers.
    ... ... ...
}

int main(void)
{
    ... ... ...

    ethernet_timer_init(); // Initialize timer for lwip and network interface
    ethernet_init();
    while (1) {
        ethernet_poll();             // Poll network stack

        ... ... ...
    }
}

No comments:

Post a Comment