Skip to content
systemcoding.dev
Kernels

Write a Minimal Linux Network Driver With net_device_ops

Write a minimal Linux 6.12 network driver with alloc_etherdev, net_device_ops, ndo_start_xmit and netif_rx, then read its counters with ip and ethtool.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and GNU logos.

A network driver looks intimidating because real ones, with their rings and offloads and firmware, run to tens of thousands of lines. The skeleton underneath is small. A driver allocates a net_device, fills in a table of operations, and registers it; after that the network stack hands it packets to send and the driver hands it packets it received. This post writes a complete virtual driver of about a hundred lines for Linux 6.12, with no hardware: whatever the stack transmits on it comes back as received traffic, like a loopback device that can be configured as an ordinary interface. It is enough to see every part of the contract, and it prepares the ground for the full guide to network drivers. Packets travel in the structure from the sk_buff post.

The reference is the kernel's net_device documentation and the definitions in include/linux/netdevice.h.

What a driver must provide

The network core asks very little of a driver to get started. For a working interface it needs:

PieceWhat it does
A struct net_deviceThe interface itself, allocated with alloc_etherdev()
ndo_openCalled when the interface is brought up
ndo_stopCalled when it is brought down
ndo_start_xmitCalled for every packet the stack wants to send
A MAC addressSet in dev->dev_addr
Registrationregister_netdev() makes the interface visible

Everything else, the receive path, statistics, the ethtool interface and multicast filtering, is optional or comes from helpers. Per-driver private data lives at the end of the same allocation and is reached with netdev_priv().

The driver

sample_net.cc
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/module.h>
#include <linux/netdevice.h>

#define DRV_NAME "sample_net"

struct sample_priv {
	struct net_device *dev;
};

static int sample_open(struct net_device *dev)
{
	netif_start_queue(dev);
	return 0;
}

static int sample_stop(struct net_device *dev)
{
	netif_stop_queue(dev);
	return 0;
}

static netdev_tx_t sample_xmit(struct sk_buff *skb, struct net_device *dev)
{
	unsigned int len = skb->len;

	skb_tx_timestamp(skb);

	/* Loop the frame back as if it had arrived on this interface. */
	skb->protocol = eth_type_trans(skb, dev);
	skb->ip_summed = CHECKSUM_UNNECESSARY;

	dev->stats.tx_packets++;
	dev->stats.tx_bytes += len;
	dev->stats.rx_packets++;
	dev->stats.rx_bytes += len;

	netif_rx(skb);
	return NETDEV_TX_OK;
}

static void sample_get_drvinfo(struct net_device *dev,
			       struct ethtool_drvinfo *info)
{
	strscpy(info->driver, DRV_NAME, sizeof(info->driver));
	strscpy(info->version, "1.0", sizeof(info->version));
}

static const struct ethtool_ops sample_ethtool_ops = {
	.get_drvinfo	= sample_get_drvinfo,
	.get_link	= ethtool_op_get_link,
};

static const struct net_device_ops sample_netdev_ops = {
	.ndo_open		= sample_open,
	.ndo_stop		= sample_stop,
	.ndo_start_xmit		= sample_xmit,
	.ndo_set_mac_address	= eth_mac_addr,
	.ndo_validate_addr	= eth_validate_addr,
};

static struct net_device *sample_dev;

static int __init sample_init(void)
{
	struct sample_priv *priv;
	int ret;

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

	priv = netdev_priv(sample_dev);
	priv->dev = sample_dev;

	strscpy(sample_dev->name, "sample%d", IFNAMSIZ);
	sample_dev->netdev_ops = &sample_netdev_ops;
	sample_dev->ethtool_ops = &sample_ethtool_ops;
	sample_dev->flags |= IFF_NOARP;
	sample_dev->features |= NETIF_F_HW_CSUM;
	eth_hw_addr_random(sample_dev);

	ret = register_netdev(sample_dev);
	if (ret) {
		free_netdev(sample_dev);
		return ret;
	}

	pr_info(DRV_NAME ": registered %s\n", sample_dev->name);
	return 0;
}

static void __exit sample_exit(void)
{
	unregister_netdev(sample_dev);
	free_netdev(sample_dev);
}

module_init(sample_init);
module_exit(sample_exit);

MODULE_DESCRIPTION("Minimal loopback network driver");
MODULE_LICENSE("GPL");

After insmod, the log reports the interface name the kernel assigned:

Text
sample_net: registered sample0

Walking through it

alloc_etherdev(sizeof(*priv)) allocates the net_device and the private area together, and calls ether_setup(), which sets Ethernet defaults: type, header length 14, a 1500-byte MTU, broadcast address and the usual flags. The %d in the name is replaced by the first free number when the device is registered, which is why the first one is sample0.

eth_hw_addr_random() sets a random locally administered MAC address and marks it as random. A real driver reads the address from the hardware or the device tree. The ndo_set_mac_address entry uses the generic eth_mac_addr(), so ip link set dev sample0 address ... works, and eth_validate_addr() rejects a zero or multicast address when the interface comes up.

netif_start_queue() in open tells the stack the driver can accept packets, and netif_stop_queue() in stop tells it to stop. A real driver also calls netif_stop_queue() from the transmit path when its hardware ring is full and netif_wake_queue() when space returns, which is how flow control works at this layer. The stack never calls ndo_start_xmit on a stopped queue.

ndo_start_xmit is the heart. The stack gives the driver an sk_buff that holds a complete Ethernet frame, and the driver owns it from that moment. It must either transmit it and free it or hand it on, and it returns NETDEV_TX_OK to say the packet was dealt with, even if it was dropped. Returning NETDEV_TX_BUSY asks the stack to retry later, and the driver must not have freed the skb in that case.

This driver sends the frame no further than the stack. eth_type_trans() does three jobs for a received frame: it sets skb->dev, pulls the 14-byte Ethernet header so data points at the IP header, and returns the EtherType, which goes into skb->protocol. Setting ip_summed to CHECKSUM_UNNECESSARY tells the stack the checksum is already verified, which is true for a looped-back packet and avoids a pointless check. netif_rx() queues the skb on the per-CPU backlog for the receive softirq, as described in the path from NIC to socket, and after the call the driver must not touch the skb.

The IFF_NOARP flag stops the stack from sending ARP on this interface. A looped-back ARP request would never get an answer, and every address on the link would stay unresolved. With the flag, the stack addresses frames without resolving.

Counters

The statistics fields in dev->stats feed ip -s link and the files under /sys/class/net/sample0/statistics/. A driver with no ndo_get_stats64 function gets them reported directly from this structure. Updating plain unsigned long counters from several CPUs without a lock can lose increments, so a production driver uses per-CPU counters or u64_stats_sync. For this teaching driver the simple form is acceptable.

Bring the interface up, give it an address and send a few packets:

Shell
sudo sysctl -w net.ipv6.conf.sample0.disable_ipv6=1
sudo ip link set sample0 up
sudo ip addr add 192.168.50.1/24 dev sample0
ping -c 3 -I sample0 192.168.50.9
ip -s link show sample0
Text
3: sample0: <BROADCAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/ether 3a:1c:55:9e:02:7b brd ff:ff:ff:ff:ff:ff
    RX:  bytes packets errors dropped  missed   mcast
           294       3      0       0       0       0
    TX:  bytes packets errors dropped carrier collsns
           294       3      0       0       0       0

The ping reports 100 percent loss, since nothing answers, which is expected. Each echo request is 98 bytes on the wire: 14 for Ethernet, 20 for IP and 64 for ICMP including its payload, so three of them make 294. The IPv6 sysctl is set first because an interface that comes up with IPv6 enabled sends router solicitations and neighbor discovery messages by itself, which would add packets and change the counts. The MAC address in the output is random and will differ.

The driver information comes from the ethtool operations:

Shell
ethtool -i sample0
Text
driver: sample_net
version: 1.0
firmware-version: 
expansion-rom-version: 
bus-info: 
supports-statistics: no
supports-test: no
supports-eeprom-access: no
supports-register-dump: no
supports-priv-flags: no

That is the output format covered in the post on listing interfaces and drivers, and a real driver fills in the firmware and bus fields.

What a real driver adds

The gap between this skeleton and a driver for hardware is mostly the hardware. The transmit function maps the skb for DMA and writes a descriptor into a ring instead of looping it back, and it stops the queue when the ring fills. A completion interrupt frees the skb with consume_skb() and wakes the queue. The receive side allocates buffers for a ring, and its NAPI poll function builds skbs and passes them up, as covered in the guide. The probe function comes from a bus: the PCI skeleton from the PCI post creates the net_device with SET_NETDEV_DEV(dev, &pdev->dev), so sysfs links the interface to its device.

Several optional features sit on top: checksum and segmentation offload through the features flags, multicast filtering with ndo_set_rx_mode, a watchdog with ndo_tx_timeout that resets a stuck transmitter, and extensive statistics through ethtool. None of them changes the basic shape that this driver shows.

Also inNetworking
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.