MIT-6.S081-2021 Lab7: networking

https://pdos.csail.mit.edu/6.S081/2021/labs/net.html

1. 要求

lab 要求简单来说就是实现网卡驱动的 transmitrecv 功能。其实只要跟着 lab 的 hints 做就可以了,难度较低。

2. 实现

首先是 transmit 功能,这里比较麻烦的是确定 tx_desc.cmd 的值,查阅下文档即可。文档中标注:

VLE, IFCS, and IC are qualified by EOP. That is, hardware interprets these bits ONLY when
EOP is set.
Hardware only sets the DD bit for descriptors with RS set.

因此设置 DD bit 和 EOP bit 即可。其实头文件中关于 cmd 也只定义了这 2 个 bit。

int e1000_transmit(struct mbuf *m)
{
  //
  // Your code here.
  //
  // the mbuf contains an ethernet frame; program it into
  // the TX descriptor ring so that the e1000 sends it. Stash
  // a pointer so that it can be freed after sending.
  //
  acquire(&e1000_lock);
  uint32 tail = regs[E1000_TDT];
  struct tx_desc* txdesc = &tx_ring[tail];
  if ((txdesc->status & E1000_TXD_STAT_DD) == 0){
    release(&e1000_lock);
    return -1;    // the E1000 hasn't finished the corresponding previous transmission request, so return an error.
  }
  
  if (tx_mbufs[tail])
    mbuffree(tx_mbufs[tail]);

  tx_mbufs[tail] = m;
  txdesc->addr = (uint64)m->head;
  txdesc->length = m->len;
  // VLE, IFCS, and IC are qualified by EOP. That is, hardware interprets these bits ONLY when
  // EOP is set.
  // Hardware only sets the DD bit for descriptors with RS set.
  txdesc->cmd = (E1000_TXD_CMD_EOP | E1000_TXD_CMD_RS);
  regs[E1000_TDT] = (tail + 1) % TX_RING_SIZE;
  release(&e1000_lock);
  return 0;
}

接着实现 recv 功能,这里需要注意的是,recv 在一次中断可能收到多个 packet。因此我们需要从 tail 处开始,依次遍历,检查 DD bit 是否为 1,为 1 表示该描述符可以进行 net_rx 操作。
其次需要注意要在 net_rx 前释放锁,否则会引起 panic。

static void
e1000_recv(void)
{
  //
  // Your code here.
  //
  // Check for packets that have arrived from the e1000
  // Create and deliver an mbuf for each packet (using net_rx()).
  //
  uint32 tail = (regs[E1000_RDT] + 1) % RX_RING_SIZE;
  struct rx_desc* rxdesc = &rx_ring[tail];

  while(rxdesc->status & E1000_RXD_STAT_DD){
    acquire(&e1000_lock);

    struct mbuf* buf = rx_mbufs[tail];
    mbufput(buf, rxdesc->length);

    struct mbuf* m = mbufalloc(0);
    rxdesc->addr = (uint64)m->head; 
    rxdesc->status = 0;
    rx_mbufs[tail] = m;
    regs[E1000_RDT] = tail;
    release(&e1000_lock);

    net_rx(buf);
    tail = (tail + 1) % RX_RING_SIZE;
    rxdesc = &rx_ring[tail];
  }
}

3. 小结

该 lab 实现的思路都在 hint 中,关于 recv 和 transmit 的 ring 数组,其结构图大致如下:

posted @ 2022-04-05 09:53  lawliet9  阅读(85)  评论(0编辑  收藏  举报