各种网络设备分配创建net_device{}流程

接下来分析alloc_netdev_mq()

 /*
@sizeof_priv 私有数据大小,驱动可以使用netdev_priv()得到该私有数据
@name:网络接口的名字
@setup:驱动程序负责实现此函数,实现的此函数用于初始化net_device中的一些成员
@queue_count:网络设备的发送队列
net_device数据结构的内存空间+私有数据内存空间+设备发送队列的内存空间+对齐字节
*/
struct net_device *alloc_netdev_mq(int sizeof_priv, 
                                            const char *name,
		                                    void (*setup)(struct net_device *), 
		                                    unsigned int queue_count)
{
	struct netdev_queue *tx;
	struct net_device *dev;
	size_t alloc_size;
	struct net_device *p;

	//设置的网络接口名字不能太长
	BUG_ON(strlen(name) >= sizeof(dev->name));

	 /* 计算net_device结构大小 */
	alloc_size = sizeof(struct net_device);

	 /* 加上私有数据大小 */
	if (sizeof_priv) 
	{
		/* ensure 32-byte alignment of private area */
		alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
		alloc_size += sizeof_priv;
	}

	/* ensure 32-byte alignment of whole construct */
	/* 整个空间做对齐后的大小 */
	alloc_size += NETDEV_ALIGN - 1;

	p = kzalloc(alloc_size, GFP_KERNEL);
	if (!p) {
		printk(KERN_ERR "alloc_netdev: Unable to allocate device.\n");
		return NULL;
	}

	//发送队列空间 在alloc_netdev()中queue_count为1
	tx = kcalloc(queue_count, sizeof(struct netdev_queue), GFP_KERNEL);
	if (!tx) 
	{
		printk(KERN_ERR "alloc_netdev: Unable to allocate tx qdiscs.\n");
		goto free_p;
	}

	/* 计算对齐的填充 */
	dev = PTR_ALIGN(p, NETDEV_ALIGN);

	//计算为了填充多增加了几个字节
	dev->padded = (char *)dev - (char *)p;

	/* 地址列表初始化 */
	if (dev_addr_init(dev))
		goto free_tx;

	//初始化单播地址列表
	dev_unicast_init(dev);
	
	/* 设置网络命名空间net */
	dev_net_set(dev, &init_net);

	/* 设置发送队列数 */
	dev->_tx = tx;//关联发送队列
	dev->num_tx_queues = queue_count;//发送队列数
	dev->real_num_tx_queues = queue_count;//活动的发送队列数

	dev->gso_max_size = GSO_MAX_SIZE;
    //初始化接收队列
	netdev_init_queues(dev);
    
	INIT_LIST_HEAD(&dev->napi_list);
	
	dev->priv_flags = IFF_XMIT_DST_RELEASE;

	/* 给驱动程序一个机会来设置当前函数中未设置的net_dev对象成员 */
	setup(dev);
	
	//设置接口名
	strcpy(dev->name, name);
	return dev;

free_tx:
	kfree(tx);

free_p:
	kfree(p);
	return NULL;
}

猜你喜欢

转载自blog.csdn.net/yldfree/article/details/84344791