MIT-6.S081-2021 Lab7: networking
1. 要求
lab 要求简单来说就是实现网卡驱动的 transmit
和 recv
功能。其实只要跟着 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 数组,其结构图大致如下:
分类:
MIT-6.S081
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了