当前位置: 首页 > 工具软件 > Netpoll > 使用案例 >

设备接口层NetPoll机制

虞展
2023-12-01


NetPoll是设备接口层基于NAPI模式提供的一种纯粹的轮询接收数据包机制,它只依赖网络设备驱动,不依赖中断机制和协议栈,通过NetPoll,可以实现UDP报文的收发。设计它的目的是为了在中断异常或者协议栈异常的情况下,提供一种可以对外发送报文的机制,这样可以让系统告诉外界自身的状况。

drivers/net/netconsole.c就是基于NetPoll实现的一种将本机内核日志发送给远程主机的驱动,关于它的介绍参考内核文档Documentation/networking/netconsole.txt。

数据结构

NetPoll对象: netpoll

struct netpoll {
    // NetPool对象必须和一个网络设备对象绑定,调用者指定网络设备名字,
    // 由NetPool来关联dev指针
	struct net_device *dev;
	char dev_name[IFNAMSIZ];
	const char *name; // 使用NetPoll的模块名称
	// 如果需要通过NetPool接收,则指定接收回调
	void (*rx_hook)(struct netpoll *, int, char *, int);
    // 本地和远端IP、端口、远端mac地址
	u32 local_ip, remote_ip;
	u16 local_port, remote_port;
	u8 remote_mac[ETH_ALEN];
};

NetPoll信息: netpoll_info

struct netpoll_info {
	atomic_t refcnt; // 引用计数
	int rx_flags; // 使能NETPOLL_RX_ENABLED表示要接收数据
	spinlock_t rx_lock;
	struct netpoll *rx_np; /* netpoll that registered an rx_hook 只可以有一个接收对象 */
	struct sk_buff_head arp_tx; /* list of arp requests to reply to */
	// 待发送skb
	struct sk_buff_head txq;
	// 延时发送任务,处理函数为queue_process()
	struct delayed_work tx_work;
};

NetPoll提供了接口netpoll_parse_options()可以让调用者指定一个字符串配置来初始化netpoll对象中的ip端口等地址信息。

模块初始化: netpoll_init()

系统初始化时只初始化一个skb队列。

static struct sk_buff_head skb_pool;

static int __init netpoll_init(void)
{
	skb_queue_head_init(&skb_pool);
	return 0;
}
core_initcall(netpoll_init);

注册NetPoll对象: netpoll_setup()

int netpoll_setup(struct netpoll *np)
{
	struct net_device *ndev = NULL;
	struct in_device *in_dev;
	struct netpoll_info *npinfo;
	unsigned long flags;
	int err;

    // 根据网络设备名称查找网络设备对象,必须指定
	if (np->dev_name)
		ndev = dev_get_by_name(&init_net, np->dev_name);
	if (!ndev) {
		printk(KERN_ERR "%s: %s doesn't exist, aborting.\n",
		       np->name, np->dev_name);
		return -ENODEV;
	}
	np->dev = ndev;
	
	// 如果该网络设备对象还没有关联netpool_info对象,则为其新建一个;已有则增加引用计数
	if (!ndev->npinfo) {
		npinfo = kmalloc(sizeof(*npinfo), GFP_KERNEL);
		if (!npinfo) {
			err = -ENOMEM;
			goto release;
		}
        // 初始化netpoll_info对象
		npinfo->rx_flags = 0;
		npinfo->rx_np = NULL;
		spin_lock_init(&npinfo->rx_lock);
		skb_queue_head_init(&npinfo->arp_tx);
		skb_queue_head_init(&npinfo->txq);
		INIT_DELAYED_WORK(&npinfo->tx_work, queue_process);
        // 引用计数为1
		atomic_set(&npinfo->refcnt, 1);
	} else {
		npinfo = ndev->npinfo;
		atomic_inc(&npinfo->refcnt);
	}

    // 网络设备对象要支持NetPool就必须要提供ndo_poll_controller()回调
	if (!ndev->netdev_ops->ndo_poll_controller) {
		printk(KERN_ERR "%s: %s doesn't support polling, aborting.\n",
		       np->name, np->dev_name);
		err = -ENOTSUPP;
		goto release;
	}
    // 如果网络设备没有打开,则尝试打开它
	if (!netif_running(ndev)) {
		unsigned long atmost, atleast;

		printk(KERN_INFO "%s: device %s not up yet, forcing it\n",
		       np->name, np->dev_name);

		rtnl_lock();
		err = dev_open(ndev); // 打开网络设备
		rtnl_unlock();
		if (err) {
			printk(KERN_ERR "%s: failed to open %s\n", np->name, ndev->name);
			goto release;
		}
        // 等待网络设备ok
		atleast = jiffies + HZ/10;
		atmost = jiffies + 4*HZ;
		while (!netif_carrier_ok(ndev)) {
			if (time_after(jiffies, atmost)) {
				printk(KERN_NOTICE "%s: timeout waiting for carrier\n", np->name);
				break;
			}
			cond_resched();
		}
		/* If carrier appears to come up instantly, we don't
		 * trust it and pause so that we don't pump all our
		 * queued console messages into the bitbucket.
		 */
        // carrier就绪后,可能并不是立刻就可以发送数据,稍微等一会儿
		if (time_before(jiffies, atleast)) {
			printk(KERN_NOTICE "%s: carrier detect appears"
			       " untrustworthy, waiting 4 seconds\n",
			       np->name);
			msleep(4000);
		}
	}
    // 如果没有指定本机IP,则尝试从网络设备中读取一个
	if (!np->local_ip) {
		rcu_read_lock();
		in_dev = __in_dev_get_rcu(ndev);

		if (!in_dev || !in_dev->ifa_list) {
			rcu_read_unlock();
			printk(KERN_ERR "%s: no IP address for %s, aborting\n",
			       np->name, np->dev_name);
			err = -EDESTADDRREQ;
			goto release;
		}

		np->local_ip = ntohl(in_dev->ifa_list->ifa_local);
		rcu_read_unlock();
		printk(KERN_INFO "%s: local IP %d.%d.%d.%d\n",
		       np->name, HIPQUAD(np->local_ip));
	}
    // 如果要接收数据,则使能NETPOLL_RX_ENABLED标记,并且将netpool对象记录到netpoll_info对象中
	if (np->rx_hook) {
		spin_lock_irqsave(&npinfo->rx_lock, flags);
		npinfo->rx_flags |= NETPOLL_RX_ENABLED;
		npinfo->rx_np = np;
		spin_unlock_irqrestore(&npinfo->rx_lock, flags);
	}
	// 提前分配一定数量的skb,存入全局skb_poll队列中
	refill_skbs();
	// 将netpoll_info对象存入网络设备对象中
	ndev->npinfo = npinfo;

	/* avoid racing with NAPI reading npinfo */
	synchronize_rcu();
	return 0;

 release:
	if (!ndev->npinfo)
		kfree(npinfo);
	np->dev = NULL;
	dev_put(ndev);
	return err;
}

发送数据: netpoll_send_udp()

NetPoll只能发送和接收UDP报文。

void netpoll_send_udp(struct netpoll *np, const char *msg, int len)
{
	int total_len, eth_len, ip_len, udp_len;
	struct sk_buff *skb;
	struct udphdr *udph;
	struct iphdr *iph;
	struct ethhdr *eth;

    // 计算udp、ip和mac各层报文总长度
	udp_len = len + sizeof(*udph);
	ip_len = eth_len = udp_len + sizeof(*iph);
	total_len = eth_len + ETH_HLEN + NET_IP_ALIGN;
    // 找一个skb
	skb = find_skb(np, total_len, total_len - len);
	if (!skb)
		return;
    // 将待发送数据拷贝到skb中
	skb_copy_to_linear_data(skb, msg, len);
	skb->len += len;

    // 构造UDP报文首部
	skb_push(skb, sizeof(*udph));
	skb_reset_transport_header(skb);
	udph = udp_hdr(skb);
	udph->source = htons(np->local_port);
	udph->dest = htons(np->remote_port);
	udph->len = htons(udp_len);
	udph->check = 0;
	udph->check = csum_tcpudp_magic(htonl(np->local_ip),
					htonl(np->remote_ip),
					udp_len, IPPROTO_UDP,
					csum_partial(udph, udp_len, 0));
	if (udph->check == 0)
		udph->check = CSUM_MANGLED_0;

    // 构造IP报文首部
	skb_push(skb, sizeof(*iph));
	skb_reset_network_header(skb);
	iph = ip_hdr(skb);

	/* iph->version = 4; iph->ihl = 5; */
	put_unaligned(0x45, (unsigned char *)iph);
	iph->tos      = 0;
	put_unaligned(htons(ip_len), &(iph->tot_len));
	iph->id       = 0;
	iph->frag_off = 0;
	iph->ttl      = 64;
	iph->protocol = IPPROTO_UDP;
	iph->check    = 0;
	put_unaligned(htonl(np->local_ip), &(iph->saddr));
	put_unaligned(htonl(np->remote_ip), &(iph->daddr));
	iph->check    = ip_fast_csum((unsigned char *)iph, iph->ihl);

    // 构造以太网帧首部
	eth = (struct ethhdr *) skb_push(skb, ETH_HLEN);
	skb_reset_mac_header(skb);
	skb->protocol = eth->h_proto = htons(ETH_P_IP);
	memcpy(eth->h_source, np->dev->dev_addr, ETH_ALEN);
	memcpy(eth->h_dest, np->remote_mac, ETH_ALEN);
    // 指定出口网络设备
	skb->dev = np->dev;
    // 发送数据包
	netpoll_send_skb(np, skb);
}

netpoll_send_skb()

static void netpoll_send_skb(struct netpoll *np, struct sk_buff *skb)
{
	int status = NETDEV_TX_BUSY;
	unsigned long tries;
	struct net_device *dev = np->dev;
	const struct net_device_ops *ops = dev->netdev_ops;
	struct netpoll_info *npinfo = np->dev->npinfo;

    // 网络设备当前无法工作,丢弃发送报文
	if (!npinfo || !netif_running(dev) || !netif_device_present(dev)) {
		__kfree_skb(skb);
		return;
	}

	// 首次发送
	if (skb_queue_len(&npinfo->txq) == 0 && !netpoll_owner_active(dev)) {
		struct netdev_queue *txq;
		unsigned long flags;

		txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));

		local_irq_save(flags);
		// 如果发送失败,这里尝试发送多次
		for (tries = jiffies_to_usecs(1)/USEC_PER_POLL;tries > 0; --tries) {
			if (__netif_tx_trylock(txq)) {
			    // 发送给网络设备驱动
				if (!netif_tx_queue_stopped(txq))
					status = ops->ndo_start_xmit(skb, dev);
				__netif_tx_unlock(txq);
                // 发送成功
				if (status == NETDEV_TX_OK)
					break;

			}
			// 每个寻魂都尝试去轮询一次设备,检查是否有数据可接收
			netpoll_poll(np);
			udelay(USEC_PER_POLL);
		}
		local_irq_restore(flags);
	}
    // 本轮发送没有成功,将skb放入发送队列
	if (status != NETDEV_TX_OK) {
		skb_queue_tail(&npinfo->txq, skb);
		schedule_delayed_work(&npinfo->tx_work,0);
	}
}

延时发送任务: queue_process()

static void queue_process(struct work_struct *work)
{
	struct netpoll_info *npinfo = container_of(work, struct netpoll_info, tx_work.work);
	struct sk_buff *skb;
	unsigned long flags;

    // 遍历发送待发送队列
	while ((skb = skb_dequeue(&npinfo->txq))) {
		struct net_device *dev = skb->dev;
		const struct net_device_ops *ops = dev->netdev_ops;
		struct netdev_queue *txq;
        // 网络设备对象不再工作状态
		if (!netif_device_present(dev) || !netif_running(dev)) {
			__kfree_skb(skb);
			continue;
		}

		txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
		local_irq_save(flags);
		__netif_tx_lock(txq, smp_processor_id());
		// 发送数据包
		if (netif_tx_queue_stopped(txq) ||
		    netif_tx_queue_frozen(txq) ||
		    ops->ndo_start_xmit(skb, dev) != NETDEV_TX_OK) {
		    // 发送失败把skb再放回发送队列首部
			skb_queue_head(&npinfo->txq, skb);
			__netif_tx_unlock(txq);
			local_irq_restore(flags);
            // 再次调度
			schedule_delayed_work(&npinfo->tx_work, HZ/10);
			return;
		}
		__netif_tx_unlock(txq);
		local_irq_restore(flags);
	}
}

接收数据

在NetPoll发送数据的过程中,会在某些时机通过netpoll_poll()尝试轮询设备,看网络设备当前是否有数据要接收。

netpoll_poll()

void netpoll_poll(struct netpoll *np)
{
	struct net_device *dev = np->dev;
	const struct net_device_ops *ops = dev->netdev_ops;

	if (!dev || !netif_running(dev) || !ops->ndo_poll_controller)
		return;
	// 调用驱动程序ndo_poll_controller()回调
	ops->ndo_poll_controller(dev);

    // 调用驱动程序的poll()回调轮询设备,驱动程序可以在poll()中完成NAPI接收
	poll_napi(dev);
    // 处理ARP相应
	service_arp_queue(dev->npinfo);
    // 清理
	zap_completion_queue();
}

poll_napi()

/*
 * Check whether delayed processing was scheduled for our NIC. If so,
 * we attempt to grab the poll lock and use ->poll() to pump the card.
 * If this fails, either we've recursed in ->poll() or it's already
 * running on another CPU.
 *
 * Note: we don't mask interrupts with this lock because we're using
 * trylock here and interrupts are already disabled in the softirq
 * case. Further, we test the poll_owner to avoid recursion on UP
 * systems where the lock doesn't exist.
 *
 * In cases where there is bi-directional communications, reading only
 * one message at a time can lead to packets being dropped by the
 * network adapter, forcing superfluous retries and possibly timeouts.
 * Thus, we set our budget to greater than 1.
 */
static int poll_one_napi(struct netpoll_info *npinfo,
			 struct napi_struct *napi, int budget)
{
	int work;

	/* net_rx_action's ->poll() invocations and our's are
	 * synchronized by this test which is only made while
	 * holding the napi->poll_lock.
	 */
	// 接收软中断函数正在调度该napi对象
	if (!test_bit(NAPI_STATE_SCHED, &napi->state))
		return budget;
    // 调度一次poll()回调
	npinfo->rx_flags |= NETPOLL_RX_DROP;
	atomic_inc(&trapped);
	set_bit(NAPI_STATE_NPSVC, &napi->state);
	work = napi->poll(napi, budget);
	clear_bit(NAPI_STATE_NPSVC, &napi->state);
	atomic_dec(&trapped);
	npinfo->rx_flags &= ~NETPOLL_RX_DROP;

	return budget - work;
}

static void poll_napi(struct net_device *dev)
{
	struct napi_struct *napi;
	int budget = 16;

	list_for_each_entry(napi, &dev->napi_list, dev_list) {
		if (napi->poll_owner != smp_processor_id() &&
		    spin_trylock(&napi->poll_lock)) {
			budget = poll_one_napi(dev->npinfo, napi, budget);
			spin_unlock(&napi->poll_lock);
            // 配额已用尽
			if (!budget)
				break;
		}
	}
}

netpoll_rx()

在数据包的接收路径上,会优先通过调用netpoll_receive_skb()或者netpoll_rx()让NetPoll有机会处理数据包,如果NetPoll返回数据包已被处理的结果,那么整个数据包接收路径也会终止。

static inline int netpoll_rx(struct sk_buff *skb)
{
	struct netpoll_info *npinfo = skb->dev->npinfo;
	unsigned long flags;
	int ret = 0;

    // 如果接收模式没有开启,返回0让数据包继续正常的接收路径
	if (!npinfo || (!npinfo->rx_np && !npinfo->rx_flags))
		return 0;

	spin_lock_irqsave(&npinfo->rx_lock, flags);
	/* check rx_flags again with the lock held */
	if (npinfo->rx_flags && __netpoll_rx(skb))
		ret = 1;
	spin_unlock_irqrestore(&npinfo->rx_lock, flags);
	return ret;
}

__netpoll_rx()

// 接收ARP报文开关,以及打开它后可以将所有的输入报文丢弃
static atomic_t trapped;

int __netpoll_rx(struct sk_buff *skb)
{
	int proto, len, ulen;
	struct iphdr *iph;
	struct udphdr *uh;
	struct netpoll_info *npi = skb->dev->npinfo;
	struct netpoll *np = npi->rx_np;

	if (!np)
		goto out;
	// 必须是以太类型帧
	if (skb->dev->type != ARPHRD_ETHER)
		goto out;

	// 如果需要响应ARP报文,则将skb放入apr_rx队列中,返回1表示skb已经被处理
	if (skb->protocol == htons(ETH_P_ARP) && atomic_read(&trapped)) {
		skb_queue_tail(&npi->arp_tx, skb);
		return 1;
	}

    // 必须是IP报文,并且必须是发给本机的
	proto = ntohs(eth_hdr(skb)->h_proto);
	if (proto != ETH_P_IP)
		goto out;
	if (skb->pkt_type == PACKET_OTHERHOST)
		goto out;
	if (skb_shared(skb))
		goto out;

    // IP报文基本判断&&校验和检查
	iph = (struct iphdr *)skb->data;
	if (!pskb_may_pull(skb, sizeof(struct iphdr)))
		goto out;
	if (iph->ihl < 5 || iph->version != 4)
		goto out;
	if (!pskb_may_pull(skb, iph->ihl*4))
		goto out;
	if (ip_fast_csum((u8 *)iph, iph->ihl) != 0)
		goto out;

	len = ntohs(iph->tot_len);
	if (skb->len < len || len < iph->ihl*4)
		goto out;

	/*
	 * Our transport medium may have padded the buffer out.
	 * Now We trim to the true length of the frame.
	 */
	if (pskb_trim_rcsum(skb, len))
		goto out;
    // 必须是UDP报文
	if (iph->protocol != IPPROTO_UDP)
		goto out;

	len -= iph->ihl*4;
	uh = (struct udphdr *)(((char *)iph) + iph->ihl*4);
	ulen = ntohs(uh->len);
    // 检验udp报文信息
	if (ulen != len)
		goto out;
	if (checksum_udp(skb, uh, ulen, iph->saddr, iph->daddr))
		goto out;
	if (np->local_ip && np->local_ip != ntohl(iph->daddr))
		goto out;
	if (np->remote_ip && np->remote_ip != ntohl(iph->saddr))
		goto out;
	if (np->local_port && np->local_port != ntohs(uh->dest))
		goto out;
    // 将报文传递给接收者,已经剥掉了UDP首部
	np->rx_hook(np, ntohs(uh->source), (char *)(uh+1), ulen - sizeof(struct udphdr));
    // 释放skb,返回1表示报文已经被接收
	kfree_skb(skb);
	return 1;

out:
	if (atomic_read(&trapped)) {
		kfree_skb(skb);
		return 1;
	}
	return 0;
}
 类似资料: