Skip to content
systemcoding.dev
Kernels

Allocate an Ethernet net_device with alloc_etherdev

alloc_etherdev() allocates a net_device with Ethernet defaults and your private struct behind it; fetch that struct with netdev_priv() (Linux 6.12).

1 min read
Summarize in AI

A network driver starts by allocating a struct net_device. alloc_etherdev() does that and fills in the Ethernet defaults, such as the 1500 byte MTU and ether_setup() values, and it appends room for your private data in the same allocation. The sample is for Linux 6.12.

c
struct demo_priv {
	void __iomem *base;
	struct napi_struct napi;
};

static int demo_probe(struct platform_device *pdev)
{
	struct net_device *ndev;
	struct demo_priv *priv;

	ndev = alloc_etherdev(sizeof(*priv));
	if (!ndev)
		return -ENOMEM;

	SET_NETDEV_DEV(ndev, &pdev->dev);
	priv = netdev_priv(ndev);
	platform_set_drvdata(pdev, ndev);
	return 0;
}

netdev_priv() returns the memory right behind the net_device, so there is no second allocation and no pointer to keep. The memory is zeroed and freed with the device by free_netdev().

SET_NETDEV_DEV() links the network interface to the parent device, which gives sysfs the right path and lets the core use the parent for DMA and power management. On an error path after this point you must call free_netdev(), since the managed devm_alloc_etherdev() is the alternative that frees it for you on unbind. The allocation does not make the interface visible: for that you need register_netdev(). See the network device API.

Also inNetworking
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.