和实验: 非NAPI模式数据包接收类似,这篇笔记使用vcard虚拟网卡来演示NAPI模式如何和协议栈配合完成数据包的接收,以便加深对这种接收模式的理解。
网络设备的定义需要包含struct napi_struct,所以不能再是简单的struct net_device了,定义如下:
// 网卡设备,NAPI模式必须提供一个napi_struct struct vcard_net_device { struct net_device *dev; struct napi_struct napi; }; struct vcard_net_device *vcard_dev = NULL;在网络设备注册过程中,对napi结构进行初始化:
static int install_net_device(void) { int ret; struct net_device *dev; // 分配网卡对象 dev = alloc_netdev(sizeof(struct vcard_net_device), DEV_NAME, vcard_setup); if (!dev) { printk(TAG "alloc_netdev failed\n"); return -ENOMEM; } vcard_dev = netdev_priv(dev); vcard_dev->dev = dev; // 调用系统api对napi进行初始化,这里指定poll()回调为vcard_poll(),配额为5个数据包 netif_napi_add(dev, &vcard_dev->napi, vcard_poll, 5); // 将网卡注册到系统中 ret = register_netdev(dev); if (ret) { printk(TAG "register_netdev failed\n"); goto free; } return 0; free: free_netdev(dev); vcard_dev = NULL; return ret; } /** * netif_napi_add - initialize a napi context * @dev: network device * @napi: napi context * @poll: polling function * @weight: default weight * * netif_napi_add() must be used to initialize a napi context prior to calling * *any* of the other napi related functions. */ static inline void netif_napi_add(struct net_device *dev, struct napi_struct *napi, int (*poll)(struct napi_struct *, int), int weight) { INIT_LIST_HEAD(&napi->poll_list); napi->poll = poll; napi->weight = weight; // 这里设置了已调度标记,会影响后面的软终端激活过程 set_bit(NAPI_STATE_SCHED, &napi->state); }初始化回调实现如下:
static int vcard_init(struct net_device *dev) { struct vcard_net_device *vdev = netdev_priv(dev); // 因为在netif_napi_add()会设置NAPI_STATE_SCHED标记, // 所以这里必须将该标记清除,否则napi_schedule_prep() // 会返回false,将无法启动接收软中断 clear_bit(NAPI_STATE_SCHED, &vdev->napi.state); return 0; }和之前的实验类似,我们使用一个定时器来激活软中断:
static void resume_napi(unsigned long data) { // 由于是虚拟设备,也不涉及关中断(定时器自己只启动一次), // 直接尝试激活软中断即可 if (likely(napi_schedule_prep(&vcard_dev->napi))) { __napi_schedule(&vcard_dev->napi); } }vcard_poll()将会被net_rx_action()回调,在其中完成数据包的接收,实现如下:
int vcard_poll(struct napi_struct *napi, int budget) { struct vcard_net_device *vdev = container_of(napi, struct vcard_net_device, napi); struct sk_buff *skb; int rcv = 0; while (rcv < budget && (skb = populate_pkt()) != NULL) { ++rcv; netif_receive_skb(skb); } // 如果数据已经全部接收完毕,那么驱动需要负责将调度停止, // 这里要特别注意,必须是小于,不能是小于等于,因为等于 // 表示刚好接收了指定配额个数据包,这个返回值对于NAPI接收 // 框架是有特殊意义的 if (rcv < budget) napi_complete(&vdev->napi); // 返回实际读取的数据包个数 printk(TAG "vcard_poll ret=%d\n", rcv); return rcv; }内核驱动的输出如下图所示: 26个字母,每次接收5个,所以分六次,前5次都是收到5包(配额就是5)然后结束进行下一次轮询,最后一次接收了1个数据包后,发现接收完毕,停止软中断调度。
用户态输出如下: 用户态可以准确的输出“AAAAA”~“ZZZZZ”的内容。
注意:
要先将vcard插入内核中;执行"ip link set dev vcard up"打开设备,否则用户态无法bind到该设备;用户态程序一定要以root权限执行;完整的实验代码在这里。
