Skip to content
systemcoding.dev
Kernels

The Complete Guide to Linux Network Device Drivers

Build a complete Linux 6.12 network driver for a ring-based PCIe NIC: rings, NAPI, DMA, statistics, ethtool, link state, offloads and recovery.

33 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 is the one kind of driver whose job is measured in packets per second, and nearly every design choice in it comes from that. The interrupt handler does almost nothing, because a card can raise tens of thousands of interrupts a second. Memory is mapped for DMA once and reused, because mapping per packet costs too much. Lock contention, cache misses and the number of times a function touches a register are all visible in the result. Yet the structure underneath is regular and small: a net_device with a table of operations, a transmit ring, a receive ring, and a NAPI poll function that connects them to the stack. This guide builds such a driver for Linux 6.12 around a hypothetical PCI Express NIC, one mechanism at a time, and explains at each step why the kernel's interface is shaped the way it is.

The short version: a network driver allocates a net_device with alloc_etherdev(), registers a net_device_ops table, and moves packets through two DMA rings. Transmit maps the packet, writes a descriptor and rings a doorbell, stopping the queue when the ring is full. Receive runs in a NAPI poll function that drains completed descriptors, builds sk_buffs and passes them to the stack with GRO. The hard interrupt handler only masks the device interrupt and schedules NAPI. Statistics, ethtool operations, link state and a transmit timeout handler make the driver observable and recoverable.

The authoritative references are the kernel's networking documentation, including net_device and NAPI, and the in-tree drivers under drivers/net/ethernet/, in particular the small ones such as 8139too and e100, which are readable end to end.

The pieces and how they fit

A network driver is the intersection of five mechanisms, each with its own post in this cluster.

The net_device is the interface as the stack sees it, built as in the minimal driver post. It carries the name, the MAC address, the MTU, the feature flags, the statistics and the table of operations the stack calls.

The packet is a struct sk_buff, covered in the sk_buff post. The driver builds one for each received frame and consumes one for each transmitted frame.

The rings are circular arrays of descriptors in coherent DMA memory, shared with the hardware. Each descriptor points to a buffer and says how long it is. The driver and the NIC take turns: the driver fills descriptors and tells the NIC how far it filled, and the NIC works through them and marks each one done.

NAPI is the interrupt mitigation scheme. The interrupt handler masks the card's interrupt and schedules a poll function, which processes packets in batches with a budget and re-enables the interrupt only when the ring is empty. The flow of a received packet through it is traced in the post on the path from NIC to socket.

The bus supplies the hardware: probe, BARs, interrupts and DMA, as in the PCI driver guide. A network driver for a PCI NIC is a PCI driver whose probe also creates a net_device.

The NIC we are writing for

The example NIC is small enough to hold in mind. It has one memory BAR and one transmit and one receive ring, each described by a base address and a size in descriptors. The registers:

OffsetMeaning
0x00Control: bit 0 enable, bit 1 reset
0x04Status: bit 0 link up
0x08Interrupt mask: bit 0 receive, bit 1 transmit, bit 2 link; write 1 to enable
0x0cInterrupt cause: read to see, write 1 to clear
0x10TX ring base address, 64 bits
0x18TX ring length in descriptors
0x1cTX tail doorbell: driver writes the next index to fill
0x20TX head: the NIC's current index, read-only
0x30RX ring base address, 64 bits
0x38RX ring length
0x3cRX tail doorbell
0x40MAC address low 32 bits, 0x44 high 16 bits

A descriptor is 16 bytes: a 64-bit buffer address, a 16-bit length, a 16-bit flags field and a 32-bit status. In a transmit descriptor the flags carry "end of packet" and "insert checksum", and the status gets a done bit when the NIC has sent the buffer. In a receive descriptor the driver sets the address of an empty buffer, and the NIC writes the received length and sets the done bit.

c
struct nic_desc {
	__le64	addr;
	__le16	len;
	__le16	flags;
	__le32	status;
};

#define DESC_EOP	BIT(0)
#define DESC_CSUM	BIT(1)
#define DESC_DONE	BIT(0)		/* in status */

This is a deliberately plain model of how real NICs work. Intel's e1000 family, Realtek's 8139 and many others use rings of this shape, with more flags, and the driver structure you see here is theirs.

State and ring structures

The driver's private data holds everything per device: the PCI handle, the mapped registers, one ring of each kind, the NAPI context and the statistics:

nic.cc
// SPDX-License-Identifier: GPL-2.0
#include <linux/dma-mapping.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/pci.h>
#include <linux/u64_stats_sync.h>

#define DRV_NAME	"sample_nic"
#define RING_SIZE	256
#define RX_BUF_LEN	2048

#define REG_CTRL	0x00
#define REG_STATUS	0x04
#define REG_IMASK	0x08
#define REG_ICAUSE	0x0c
#define REG_TX_BASE	0x10
#define REG_TX_LEN	0x18
#define REG_TX_TAIL	0x1c
#define REG_TX_HEAD	0x20
#define REG_RX_BASE	0x30
#define REG_RX_LEN	0x38
#define REG_RX_TAIL	0x3c
#define REG_MAC_LO	0x40
#define REG_MAC_HI	0x44

#define CTRL_ENABLE	BIT(0)
#define CTRL_RESET	BIT(1)
#define IRQ_RX		BIT(0)
#define IRQ_TX		BIT(1)
#define IRQ_LINK	BIT(2)

struct nic_buf {
	struct sk_buff	*skb;
	dma_addr_t	dma;
	unsigned int	len;
};

struct nic_ring {
	struct nic_desc	*desc;
	dma_addr_t	desc_dma;
	struct nic_buf	buf[RING_SIZE];
	unsigned int	next_to_use;	/* driver fills here */
	unsigned int	next_to_clean;	/* driver reclaims here */
};

struct nic {
	struct pci_dev		*pdev;
	struct net_device	*netdev;
	void __iomem		*regs;
	struct napi_struct	napi;
	struct nic_ring		tx;
	struct nic_ring		rx;

	struct u64_stats_sync	syncp;
	u64			rx_packets, rx_bytes;
	u64			tx_packets, tx_bytes;
	u64			rx_dropped;
};

Two indexes per ring carry the whole protocol. next_to_use is where the driver will put the next descriptor, and next_to_clean is the oldest descriptor the driver has not yet reclaimed. The number in use is their difference modulo the ring size. A ring of 256 entries keeps one slot empty, so that "full" and "empty" can be told apart, which means at most 255 descriptors are in flight.

A helper for the space left is used in several places:

c
static unsigned int ring_free(const struct nic_ring *r)
{
	return (r->next_to_clean - r->next_to_use - 1) & (RING_SIZE - 1);
}

The mask arithmetic works because RING_SIZE is a power of two, which is why rings always are.

Probe: from PCI device to net_device

probe is the PCI skeleton plus the creation of the interface. The order is: enable and map the device, set the DMA mask, allocate the net_device with room for the private data, set it up, and register last:

c
static int nic_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
	struct net_device *netdev;
	struct nic *n;
	u8 mac[ETH_ALEN];
	u32 lo, hi;
	int ret;

	ret = pcim_enable_device(pdev);
	if (ret)
		return ret;

	ret = pci_request_regions(pdev, DRV_NAME);
	if (ret)
		return ret;

	ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
	if (ret)
		ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
	if (ret)
		goto err_regions;

	pci_set_master(pdev);

	netdev = alloc_etherdev(sizeof(*n));
	if (!netdev) {
		ret = -ENOMEM;
		goto err_regions;
	}
	SET_NETDEV_DEV(netdev, &pdev->dev);

	n = netdev_priv(netdev);
	n->pdev = pdev;
	n->netdev = netdev;
	u64_stats_init(&n->syncp);

	n->regs = pci_iomap(pdev, 0, 0);
	if (!n->regs) {
		ret = -ENOMEM;
		goto err_netdev;
	}

	lo = ioread32(n->regs + REG_MAC_LO);
	hi = ioread32(n->regs + REG_MAC_HI);
	mac[0] = lo;       mac[1] = lo >> 8;
	mac[2] = lo >> 16; mac[3] = lo >> 24;
	mac[4] = hi;       mac[5] = hi >> 8;
	if (is_valid_ether_addr(mac))
		eth_hw_addr_set(netdev, mac);
	else
		eth_hw_addr_random(netdev);

	netdev->netdev_ops = &nic_netdev_ops;
	netdev->ethtool_ops = &nic_ethtool_ops;
	netdev->watchdog_timeo = 5 * HZ;
	netdev->min_mtu = ETH_MIN_MTU;
	netdev->max_mtu = RX_BUF_LEN - ETH_HLEN - ETH_FCS_LEN;
	netdev->features = NETIF_F_HW_CSUM | NETIF_F_SG;
	netdev->hw_features = netdev->features;

	netif_napi_add(netdev, &n->napi, nic_poll);
	pci_set_drvdata(pdev, n);

	ret = register_netdev(netdev);
	if (ret)
		goto err_unmap;

	dev_info(&pdev->dev, "registered %s, MAC %pM\n", netdev->name,
		 netdev->dev_addr);
	return 0;

err_unmap:
	netif_napi_del(&n->napi);
	pci_iounmap(pdev, n->regs);
err_netdev:
	free_netdev(netdev);
err_regions:
	pci_release_regions(pdev);
	return ret;
}
Text
sample_nic 0000:03:00.0: registered enp3s0, MAC a4:bb:6d:12:34:56

The interface is named by udev after registration, so the log shows the name the kernel gave at that instant, and then the system renames it. Several lines carry weight. SET_NETDEV_DEV() links the interface to its PCI device in sysfs, which is what lets ethtool -i report the driver and bus address. The MAC address comes from the hardware, and a random one is the fallback for a device whose address is unset, with eth_hw_addr_random() marking it as locally administered. watchdog_timeo arms the transmit timeout, covered below. max_mtu is bounded by the receive buffer length, because a frame larger than a buffer would need multi-buffer receive, which this driver does not implement. And register_netdev() comes last, because the moment it returns the interface is live and the stack may call ndo_open at once. Everything it needs must already be set.

Allocating the rings

The descriptor arrays are coherent DMA memory, since both the CPU and the NIC read and write them constantly. The buffers they point to are mapped separately, per packet or per receive buffer.

c
static int nic_alloc_ring(struct nic *n, struct nic_ring *r)
{
	size_t size = RING_SIZE * sizeof(struct nic_desc);

	r->desc = dma_alloc_coherent(&n->pdev->dev, size, &r->desc_dma,
				     GFP_KERNEL);
	if (!r->desc)
		return -ENOMEM;
	r->next_to_use = 0;
	r->next_to_clean = 0;
	return 0;
}

static void nic_free_ring(struct nic *n, struct nic_ring *r)
{
	dma_free_coherent(&n->pdev->dev, RING_SIZE * sizeof(struct nic_desc),
			  r->desc, r->desc_dma);
	r->desc = NULL;
}

The rings live as long as the interface is up. They are allocated in ndo_open and freed in ndo_stop, not in probe, so an interface that is down holds no DMA memory. The discipline matters on systems with many interfaces.

The receive ring also needs buffers. Each descriptor gets an empty sk_buff, mapped for the NIC to write into. Refill is done in the same function at open time and in the poll function afterwards:

c
static int nic_rx_refill(struct nic *n, unsigned int count)
{
	struct nic_ring *r = &n->rx;

	while (count--) {
		struct nic_buf *b = &r->buf[r->next_to_use];
		struct sk_buff *skb;
		dma_addr_t dma;

		skb = napi_alloc_skb(&n->napi, RX_BUF_LEN);
		if (!skb)
			break;

		dma = dma_map_single(&n->pdev->dev, skb->data, RX_BUF_LEN,
				     DMA_FROM_DEVICE);
		if (dma_mapping_error(&n->pdev->dev, dma)) {
			dev_kfree_skb_any(skb);
			break;
		}

		b->skb = skb;
		b->dma = dma;
		r->desc[r->next_to_use].addr = cpu_to_le64(dma);
		r->desc[r->next_to_use].status = 0;
		r->next_to_use = (r->next_to_use + 1) & (RING_SIZE - 1);
	}

	wmb();	/* descriptors visible before the doorbell */
	iowrite32(r->next_to_use, n->regs + REG_RX_TAIL);
	return 0;
}

The wmb() is the point where the driver's writes to the descriptors, which sit in coherent memory, must be visible to the NIC before the doorbell write tells it to look. Without it, a weakly ordered CPU may let the doorbell reach the device first, and the NIC would read a stale descriptor. The refill stops quietly when memory runs out, and the next poll tries again, which is how a receive path degrades under pressure and not by failing.

Open and stop

ndo_open brings the interface up: allocate the rings, program the NIC, request the interrupt, enable NAPI and start the queue. ndo_stop undoes it in the reverse order:

c
static int nic_open(struct net_device *netdev)
{
	struct nic *n = netdev_priv(netdev);
	int ret;

	ret = nic_alloc_ring(n, &n->tx);
	if (ret)
		return ret;
	ret = nic_alloc_ring(n, &n->rx);
	if (ret)
		goto err_tx;

	iowrite32(CTRL_RESET, n->regs + REG_CTRL);
	lo_hi_writeq(n->tx.desc_dma, n->regs + REG_TX_BASE);
	iowrite32(RING_SIZE, n->regs + REG_TX_LEN);
	lo_hi_writeq(n->rx.desc_dma, n->regs + REG_RX_BASE);
	iowrite32(RING_SIZE, n->regs + REG_RX_LEN);

	nic_rx_refill(n, RING_SIZE - 1);

	ret = request_irq(n->pdev->irq, nic_irq, IRQF_SHARED, netdev->name, n);
	if (ret)
		goto err_rx;

	napi_enable(&n->napi);
	iowrite32(CTRL_ENABLE, n->regs + REG_CTRL);
	iowrite32(IRQ_RX | IRQ_TX | IRQ_LINK, n->regs + REG_IMASK);

	netif_start_queue(netdev);
	return 0;

err_rx:
	nic_free_ring(n, &n->rx);
err_tx:
	nic_free_ring(n, &n->tx);
	return ret;
}

The sequence follows dependencies. The rings must exist and be programmed before the NIC is enabled. The interrupt handler must be registered before interrupts are unmasked, or an interrupt could arrive with no handler. NAPI must be enabled before the first interrupt so that napi_schedule() has something to schedule. And the queue starts last, since the moment netif_start_queue() runs the stack may call the transmit function.

ndo_stop is the mirror, and the order is again the point: stop the queue so no new transmit starts, disable the interrupt source at the NIC, free the interrupt, disable NAPI, which waits for any running poll to finish, and only then reclaim the packets and the rings. Reclaiming the buffers means unmapping and freeing every sk_buff that is still in a ring. A driver that leaks them leaks memory on every ip link set down and up cycle, and a loop of ten thousand cycles is a good test.

The transmit path

The stack calls ndo_start_xmit with a ready packet. The driver's job is to map it, describe it to the NIC, and tell the NIC. It also has to say when it can accept no more.

c
static netdev_tx_t nic_xmit(struct sk_buff *skb, struct net_device *netdev)
{
	struct nic *n = netdev_priv(netdev);
	struct nic_ring *r = &n->tx;
	struct nic_buf *b;
	struct nic_desc *d;
	dma_addr_t dma;

	if (skb_linearize(skb)) {
		dev_kfree_skb_any(skb);
		return NETDEV_TX_OK;
	}

	dma = dma_map_single(&n->pdev->dev, skb->data, skb->len, DMA_TO_DEVICE);
	if (dma_mapping_error(&n->pdev->dev, dma)) {
		dev_kfree_skb_any(skb);
		netdev->stats.tx_dropped++;
		return NETDEV_TX_OK;
	}

	b = &r->buf[r->next_to_use];
	b->skb = skb;
	b->dma = dma;
	b->len = skb->len;

	d = &r->desc[r->next_to_use];
	d->addr = cpu_to_le64(dma);
	d->len = cpu_to_le16(skb->len);
	d->flags = cpu_to_le16(DESC_EOP |
			       (skb->ip_summed == CHECKSUM_PARTIAL ? DESC_CSUM : 0));
	d->status = 0;

	skb_tx_timestamp(skb);
	r->next_to_use = (r->next_to_use + 1) & (RING_SIZE - 1);

	if (ring_free(r) < 2) {
		netif_stop_queue(netdev);
		smp_mb();	/* pairs with the reclaim path */
		if (ring_free(r) >= 2)
			netif_start_queue(netdev);
	}

	wmb();
	iowrite32(r->next_to_use, n->regs + REG_TX_TAIL);
	return NETDEV_TX_OK;
}

The function does several things that are worth reading closely. skb_linearize() makes the packet one contiguous run of bytes, since this NIC takes one buffer per descriptor, and a real driver with scatter-gather support maps each fragment instead. A packet that cannot be sent, because the mapping failed, is dropped and counted, and the function still returns NETDEV_TX_OK, because the skb has been consumed. Returning NETDEV_TX_BUSY is for the case where the packet could not be queued and the driver still owns it, and the stack will call again, so the skb must not have been freed.

The flow control is the delicate part. After using a slot, the driver checks whether the ring is nearly full, and if so stops the queue so the stack stops calling. But the reclaim path, running in NAPI on another CPU, may free slots at any moment, including between the check and the stop. If it woke the queue before it was stopped, the wake-up is lost and the queue stays stopped forever with an empty ring. The pattern in the code closes the gap: stop the queue, issue a full barrier, and check again, restarting the queue if space appeared. The reclaim path has a matching barrier before it tests the stopped state.

The wmb() before the doorbell has the same purpose as in the refill. The tail write tells the NIC to start sending, so the descriptor must be complete first. Hardware usually coalesces doorbells too: a driver handling a burst can write the descriptor for several packets and ring once, using netdev_xmit_more() to learn whether another packet follows.

Transmit completion

The NIC marks each descriptor done after sending it, and the driver must reclaim them: unmap the buffer, free the packet, and wake the queue if it was stopped.

c
static unsigned int nic_clean_tx(struct nic *n)
{
	struct nic_ring *r = &n->tx;
	unsigned int done = 0, bytes = 0;

	while (r->next_to_clean != r->next_to_use) {
		struct nic_desc *d = &r->desc[r->next_to_clean];
		struct nic_buf *b = &r->buf[r->next_to_clean];

		if (!(le32_to_cpu(d->status) & DESC_DONE))
			break;
		dma_rmb();	/* read the rest only after the done bit */

		dma_unmap_single(&n->pdev->dev, b->dma, b->len, DMA_TO_DEVICE);
		bytes += b->len;
		consume_skb(b->skb);
		b->skb = NULL;

		r->next_to_clean = (r->next_to_clean + 1) & (RING_SIZE - 1);
		done++;
	}

	if (done) {
		u64_stats_update_begin(&n->syncp);
		n->tx_packets += done;
		n->tx_bytes += bytes;
		u64_stats_update_end(&n->syncp);

		smp_mb();	/* pairs with the barrier in nic_xmit */
		if (netif_queue_stopped(n->netdev) && ring_free(r) >= 2)
			netif_wake_queue(n->netdev);
	}
	return done;
}

consume_skb() is the call for a packet that was handled, and kfree_skb() is for one that was dropped, so that drop monitors do not report every successful transmit. dma_rmb() makes sure the driver reads the descriptor fields after it has seen the done bit, which matters on weakly ordered CPUs where the NIC's writes could otherwise be observed out of order. The statistics are updated inside the u64_stats sequence, explained below.

The receive path and the poll function

Receive and transmit completion are both handled in the NAPI poll function, which the stack calls with a budget: the maximum number of received packets it may process in one go.

c
static int nic_poll(struct napi_struct *napi, int budget)
{
	struct nic *n = container_of(napi, struct nic, napi);
	struct nic_ring *r = &n->rx;
	int work = 0;

	nic_clean_tx(n);

	while (work < budget) {
		struct nic_desc *d = &r->desc[r->next_to_clean];
		struct nic_buf *b = &r->buf[r->next_to_clean];
		struct sk_buff *skb;
		unsigned int len;

		if (!(le32_to_cpu(d->status) & DESC_DONE))
			break;
		dma_rmb();

		len = le16_to_cpu(d->len);
		dma_unmap_single(&n->pdev->dev, b->dma, RX_BUF_LEN,
				 DMA_FROM_DEVICE);
		skb = b->skb;
		b->skb = NULL;

		skb_put(skb, len);
		skb->protocol = eth_type_trans(skb, n->netdev);
		skb_checksum_none_assert(skb);
		napi_gro_receive(napi, skb);

		u64_stats_update_begin(&n->syncp);
		n->rx_packets++;
		n->rx_bytes += len;
		u64_stats_update_end(&n->syncp);

		r->next_to_clean = (r->next_to_clean + 1) & (RING_SIZE - 1);
		work++;
	}

	if (work)
		nic_rx_refill(n, work);

	if (work < budget && napi_complete_done(napi, work))
		iowrite32(IRQ_RX | IRQ_TX | IRQ_LINK, n->regs + REG_IMASK);

	return work;
}

The structure of this function is the whole NAPI contract. It reclaims transmit descriptors first, since that is cheap and frees memory. It then loops over completed receive descriptors up to the budget. For each, it unmaps the buffer, sets the packet length with skb_put(), lets eth_type_trans() pull the Ethernet header and set the protocol, and passes the packet up with napi_gro_receive(), which attempts to merge it with its neighbors in the same flow. After the loop, the consumed buffers are replaced with new ones.

The ending decides how the driver behaves under load. If fewer packets arrived than the budget, the ring is drained, and the driver calls napi_complete_done() to leave polling mode and re-enables the card's interrupt. If the loop used the whole budget, there may be more work, and the function returns without completing, so the kernel calls it again without any interrupt. Under a flood, the card's interrupt stays masked and the CPU runs the poll function in a loop, which is the point of NAPI: interrupts per packet become polling per batch. The return value must be the work done, and it must never exceed the budget.

The interrupt handler

With NAPI doing the work, the interrupt handler is small:

c
static irqreturn_t nic_irq(int irq, void *data)
{
	struct nic *n = data;
	u32 cause = ioread32(n->regs + REG_ICAUSE);

	if (!cause)
		return IRQ_NONE;

	iowrite32(cause, n->regs + REG_ICAUSE);		/* acknowledge */

	if (cause & IRQ_LINK)
		nic_check_link(n);

	if (cause & (IRQ_RX | IRQ_TX)) {
		iowrite32(IRQ_LINK, n->regs + REG_IMASK);	/* mask rx, tx */
		napi_schedule(&n->napi);
	}
	return IRQ_HANDLED;
}

It reads the cause, returns IRQ_NONE if the interrupt is not this device's (required for a shared line), acknowledges what it saw, masks the receive and transmit interrupts, and schedules NAPI. It does not look at a single packet. The mask write is what prevents a second interrupt while NAPI runs, and the poll function is the one that unmasks it.

On a card with message-signaled interrupts, the same structure applies with one vector per queue, as in the MSI post, and each vector has its own NAPI context pinned to a CPU.

Statistics

The stack needs counters for ip -s link and the files in sysfs. The old way, writing netdev->stats directly, loses updates when several CPUs write the same field, and a 64-bit counter read on a 32-bit machine can tear. The correct tool is u64_stats_sync, a lightweight sequence lock that is free on 64-bit machines and consistent on 32-bit ones. Writers bracket their updates with u64_stats_update_begin() and u64_stats_update_end(), as in the functions above, and the reader retries until it sees a consistent snapshot:

c
static void nic_get_stats64(struct net_device *netdev,
			    struct rtnl_link_stats64 *stats)
{
	struct nic *n = netdev_priv(netdev);
	unsigned int start;

	do {
		start = u64_stats_fetch_begin(&n->syncp);
		stats->rx_packets = n->rx_packets;
		stats->rx_bytes = n->rx_bytes;
		stats->tx_packets = n->tx_packets;
		stats->tx_bytes = n->tx_bytes;
		stats->rx_dropped = n->rx_dropped;
	} while (u64_stats_fetch_retry(&n->syncp, start));
}

A busy multiqueue driver keeps one set of counters per queue and sums them here, so no CPU contends with another on the counters. The counters the driver has are mapped into the generic structure, and driver-specific ones, such as the number of ring refills that failed, go to ethtool -S.

The operations table and ethtool

The table collects every function above:

c
static const struct net_device_ops nic_netdev_ops = {
	.ndo_open		= nic_open,
	.ndo_stop		= nic_stop,
	.ndo_start_xmit		= nic_xmit,
	.ndo_get_stats64	= nic_get_stats64,
	.ndo_tx_timeout		= nic_tx_timeout,
	.ndo_set_mac_address	= eth_mac_addr,
	.ndo_validate_addr	= eth_validate_addr,
};

ethtool is the interface for the facts about the device that are not packets. A driver provides what it can, and the rest is absent:

c
static void nic_get_drvinfo(struct net_device *netdev,
			    struct ethtool_drvinfo *info)
{
	struct nic *n = netdev_priv(netdev);

	strscpy(info->driver, DRV_NAME, sizeof(info->driver));
	strscpy(info->bus_info, pci_name(n->pdev), sizeof(info->bus_info));
}

static void nic_get_ringparam(struct net_device *netdev,
			      struct ethtool_ringparam *ring,
			      struct kernel_ethtool_ringparam *kernel_ring,
			      struct netlink_ext_ack *extack)
{
	ring->rx_max_pending = RING_SIZE - 1;
	ring->tx_max_pending = RING_SIZE - 1;
	ring->rx_pending = RING_SIZE - 1;
	ring->tx_pending = RING_SIZE - 1;
}

static const struct ethtool_ops nic_ethtool_ops = {
	.get_drvinfo	= nic_get_drvinfo,
	.get_link	= ethtool_op_get_link,
	.get_ringparam	= nic_get_ringparam,
};

With these, the commands from the post on listing interfaces and drivers work for the new interface:

Shell
ethtool -i enp3s0
ethtool -g enp3s0
Text
driver: sample_nic
version: 
firmware-version: 
expansion-rom-version: 
bus-info: 0000:03:00.0
supports-statistics: no
supports-test: no
supports-eeprom-access: no
supports-register-dump: no
supports-priv-flags: no
Ring parameters for enp3s0:
Pre-set maximums:
RX:		255
RX Mini:	n/a
RX Jumbo:	n/a
TX:		255
Current hardware settings:
RX:		255
RX Mini:	n/a
RX Jumbo:	n/a
TX:		255

Adding get_ethtool_stats and get_strings exports driver-specific counters, and get_link_ksettings reports speed and duplex. The generic ethtool_op_get_link reads the carrier state, which is the next topic.

A network interface is up in two senses. It is administratively up when someone ran ip link set up, and it has carrier when the cable is connected and the link negotiated. The driver reports the second with netif_carrier_on() and netif_carrier_off(), and the stack uses it to stop sending when there is no link and to announce the change to user space:

c
static void nic_check_link(struct nic *n)
{
	bool up = ioread32(n->regs + REG_STATUS) & BIT(0);

	if (up && !netif_carrier_ok(n->netdev)) {
		netif_carrier_on(n->netdev);
		netdev_info(n->netdev, "link up\n");
	} else if (!up && netif_carrier_ok(n->netdev)) {
		netif_carrier_off(n->netdev);
		netdev_info(n->netdev, "link down\n");
	}
}

Call it at open and from the link interrupt. ip -br link then shows LOWER_UP or NO-CARRIER, as in the earlier post. For a NIC that uses an external PHY, which is the usual case on embedded boards, the driver does not read link status itself. It uses phylink or the older phylib, which talk to the PHY over MDIO, negotiate speed and duplex and call back into the driver to apply them. That is the largest piece this guide leaves out, and it is a well-defined layer: the MAC driver implements a small set of phylink_mac_ops and the framework runs the state machine.

Checksums, scatter-gather and segmentation

The feature flags set in probe tell the stack what the hardware can do, so that software work is skipped. NETIF_F_HW_CSUM says the NIC can compute transport checksums, and the transmit function honors it by setting the checksum flag in the descriptor for packets the stack marked CHECKSUM_PARTIAL. A real driver also tells the NIC where the checksum starts and where to store it, from skb->csum_start and skb->csum_offset. Without the flag the stack computes checksums in software, which works and costs CPU.

NETIF_F_SG means the NIC accepts a packet in several buffers, so the stack can pass a large packet as a header plus page fragments and avoid copying them together. The transmit function then loops over skb_shinfo(skb)->frags, mapping each with skb_frag_dma_map(), and writes one descriptor per piece, setting the end-of-packet flag on the last. NETIF_F_TSO goes further: the stack hands over a 64 KiB TCP segment and the NIC splits it into packets with correct headers. Offloads like these are the reason a modest CPU can saturate a fast link, and they are also the largest source of subtle driver bugs, because the NIC's idea of where headers sit must match the stack's exactly. Add them one at a time, test each with real traffic, and keep the software fallback working.

On receive, a NIC that verifies checksums tells the stack by setting skb->ip_summed to CHECKSUM_UNNECESSARY, and the stack skips its own check. The driver above sets none, which is the safe default.

Recovery from a stuck transmitter

A NIC can wedge: the transmit ring is full, the NIC stops advancing its head pointer, and the queue stays stopped. The stack has a watchdog for this. If the queue is stopped for longer than watchdog_timeo, it calls ndo_tx_timeout, and the driver must reset the hardware:

c
static void nic_tx_timeout(struct net_device *netdev, unsigned int txqueue)
{
	struct nic *n = netdev_priv(netdev);

	netdev_err(netdev, "transmit timeout, resetting\n");
	netif_stop_queue(netdev);
	napi_disable(&n->napi);

	iowrite32(CTRL_RESET, n->regs + REG_CTRL);
	nic_clean_all_tx(n);
	nic_reinit_rings(n);

	napi_enable(&n->napi);
	iowrite32(CTRL_ENABLE, n->regs + REG_CTRL);
	netif_wake_queue(netdev);
}

nic_clean_all_tx() and nic_reinit_rings() stand for reclaiming every packet in flight, with kfree_skb(), since they were never sent, and reprogramming the rings. In a real driver the reset is scheduled on a workqueue and not run in the timeout context, because the reset sleeps. The log line is what a field report looks like, and a timeout in the log of a healthy system is a bug worth chasing, since it means the hardware stopped, not that the network is busy.

MTU, multicast and the receive filter

The MTU decides how large a frame the driver must be ready to receive. With one buffer per frame, the receive buffer length bounds it, which is why max_mtu was computed from RX_BUF_LEN. Supporting larger frames means either bigger buffers or chained buffers, and a driver that allows a larger MTU than its buffers can hold truncates frames silently. Provide ndo_change_mtu only if the ring must be rebuilt for a new size, and let the stack's default handle the simple case.

Receive filtering follows the interface flags. A NIC normally accepts frames to its own address and broadcast, and the stack tells the driver about changes through ndo_set_rx_mode: promiscuous mode when a tool like tcpdump turns it on, and the list of multicast addresses a program joined. The driver writes the NIC's filter table, or falls back to accepting all multicast when the table is too small. A driver without this callback appears to work until the first program that needs multicast, such as IPv6 neighbor discovery, silently never receives its packets.

Multiple queues

A modern NIC has many ring pairs, one per CPU, and steers each flow to a ring by hashing its headers, so that packets of one connection are always handled by one CPU, in order, with no lock shared across CPUs. In the driver, this changes the structure from one ring pair to an array. Each queue has its own rings, its own NAPI context, and its own interrupt vector with CPU affinity. alloc_etherdev_mq() takes the number of queues, ndo_start_xmit picks the transmit ring from skb_get_queue_mapping(), and netif_stop_subqueue() and netif_wake_subqueue() replace the single-queue calls.

Receive-side scaling is configured through ethtool, ethtool -x for the hash table and -X to change it, and the driver implements the get_rxfh and set_rxfh operations. The cost is code: everything above is repeated per queue, and the statistics are summed. The benefit is that throughput scales with cores, which is the only way a single NIC reaches its rated speed.

An XDP program can be attached at the receive path, in the driver's poll function before any sk_buff is built, with ndo_bpf to attach it and a hook call that returns a verdict for each packet: pass, drop, transmit or redirect. XDP is how packet filters and load balancers reach tens of millions of packets per second per CPU, and it requires the driver to support it explicitly. It is worth planning for in a design, since adding it later means restructuring the receive buffer handling.

Debugging

The first tool is the counters. ip -s link shows drops and errors per direction, and ethtool -S shows the driver's own, which is where a driver should count each failure mode separately: refill failures, mapping failures, ring-full events and timeouts. A driver that counts only "errors" gives nobody a place to start.

kfree_skb() with a drop reason is visible to the tracing tools. The skb:kfree_skb tracepoint, available through perf and bpftrace, reports the location and reason of every dropped packet, which turns "packets disappear somewhere" into a specific line of code:

Shell
sudo perf trace -e skb:kfree_skb --max-events 3
Text
     0.000 skb:kfree_skb(skbaddr: 0xffff9a2b3c4d5e00, location: 0xffffffffb3e2a1c0, protocol: 2048, reason: NOT_SPECIFIED)

The location is an address that perf or addr2line turns into a function name. The kernel log shows the driver's messages, and /proc/interrupts and /proc/net/softnet_stat show whether interrupts arrive and whether the backlog drops. For a reproducible workload, the kernel's pktgen module generates packets at high rates from inside the kernel, which tests the transmit path far beyond what a user program can.

Testing the driver

A test plan follows the layers. Bring the interface up and down repeatedly, and confirm no memory is leaked, through ip link set in a loop and kmemleak or /proc/meminfo. Send single packets with ping to a neighbor, then a flood with ping -f, and read the counters on both ends. Check that the queue stops and wakes: send a burst larger than the ring and confirm there are no transmit timeouts. Test with large packets and with an MTU change, with checksum offload toggled through ethtool -K, and with the link unplugged and replugged, to see the carrier events. Run a bulk transfer in each direction with a tool such as iperf3, comparing against another NIC in the same machine, and watch for drops.

Finally, unload the module while traffic runs, and unbind the device through sysfs. The path that frees rings and unmaps buffers while the stack still holds packets is where use-after-free bugs live, and a kernel built with CONFIG_KASAN and CONFIG_DMA_API_DEBUG reports them at the line that caused them. A driver that survives those, plus a transmit timeout injected on purpose by stalling the device in a virtual machine, is ready for the real hardware.

Ordering and memory barriers in a ring driver

The ring protocol is a conversation between two agents that do not share a clock, the CPU and the NIC, and every bug in it is an ordering bug. It is worth seeing the rules in one place, since they recur in every function above.

The CPU writes descriptors into coherent memory and then writes a doorbell register. The NIC must not see the doorbell before the descriptors, so a write barrier sits between them: wmb() orders ordinary memory writes before a following write to the device. The NIC writes completion status and data into memory, then the CPU reads the status. The CPU must not read the payload fields before it has seen the done bit, and a read barrier, dma_rmb(), between the two reads enforces it. For plain coherent descriptors, the dma_wmb() and dma_rmb() forms are cheaper and sufficient; wmb() before an MMIO doorbell is the one place the stronger barrier is needed, because the doorbell is a device register write and not coherent memory.

The CPU-to-CPU conversation between the transmit function and the completion path has its own barrier pair. The queue-stopped flag is a shared variable, and the full barriers on both sides, smp_mb() after stopping and before checking for space, smp_mb() after freeing and before testing the stopped flag, guarantee that at least one side sees the other's update. Skipping them produces a bug that appears once a day on a loaded 64-core machine and never in testing, which is the definition of a barrier bug.

A check that catches most of these is to read each function aloud and, at each shared variable, say who writes it, who reads it and what ordering the reader needs. If the answer is "the reader needs to see this before that", there is a barrier there. If the answer is "it does not matter", there should be none, and a barrier added out of caution costs time in a path that runs millions of times a second.

Memory and buffer management

A receive ring is a standing commitment of memory: 256 buffers of 2 KiB each is half a megabyte per queue, held whether or not traffic flows. Drivers for fast NICs use rings of thousands of entries and several queues, so this is the largest memory cost of the driver. Three techniques keep it manageable.

The first is page-based receive buffers. Instead of allocating an sk_buff with its own data area per descriptor, the driver allocates pages, maps each page once, and carves buffers out of it, building the sk_buff around the buffer only when a packet arrives, with build_skb() or by attaching the page as a fragment. This avoids a per-packet allocation in the refill path and lets the driver reuse a page when the stack has finished with it. The kernel's page pool library, page_pool, packages that logic, including recycling and DMA mapping, and is the standard tool in new drivers.

The second is to defer the refill. Refilling after every received packet is a lot of small allocations, so drivers refill in batches, and when memory is tight they let the ring run partly empty rather than failing. A ring that runs completely empty drops packets in hardware, and the driver should count and log that case, since it signals memory pressure the administrator needs to see.

The third is to bound the transmit side. The queue limit, controlled by netdev_tx_sent_queue() and netdev_tx_completed_queue(), is byte queue limits: the stack measures how many bytes are in the hardware ring and holds back packets beyond what is needed to keep the NIC busy. It keeps latency low under load, because packets wait in the stack, where the queueing discipline can order them, and not in a deep hardware ring where nothing can. A driver opts in by calling the two functions at the points where it queues and where it completes bytes, and the rest is automatic.

Choosing between a hard-coded ring size and a configurable one

The ring size of 256 here is a constant, and it was chosen for clarity. A production driver makes it configurable through ethtool -G, with the set_ringparam operation tearing down the rings and rebuilding them at the new size, because the right size depends on the workload. A larger ring absorbs bursts and tolerates a delay in the poll function, and costs memory and latency, since a packet may wait behind more others. A smaller ring keeps latency down and uses less memory, and drops packets in a burst larger than it can hold.

There is no universal answer, and a number from another system's tuning guide should be treated as a starting point to test. The mechanism-based rule is to size the receive ring to cover the longest interval the poll function can be delayed, multiplied by the packet rate, and to size the transmit ring to cover the interrupt coalescing interval. Measure the drops that ethtool -S reports, change one parameter, and measure again.

A review checklist

Before treating the driver as done, review it against these points. Each describes a class of bug that has shipped in real drivers.

AreaQuestion
RegistrationIs register_netdev() last in probe, with everything the stack may call already working?
DMAIs every mapping checked with dma_mapping_error(), and every map matched by an unmap with the same length and direction?
BarriersIs there a write barrier before each doorbell and a read barrier after each done bit?
Flow controlDoes the transmit function stop the queue with the recheck pattern, and does completion wake it?
OwnershipIs an skb freed exactly once, with consume_skb() for success and kfree_skb() for a drop?
NAPIDoes the poll function return at most the budget, and call napi_complete_done() only when it did less?
InterruptsDoes the handler acknowledge its cause, mask the source, schedule NAPI and return IRQ_NONE for others?
TeardownDoes ndo_stop stop the queue, mask interrupts, free the IRQ, disable NAPI and then reclaim buffers?
StatisticsAre counters updated inside u64_stats sequences, and is each failure mode counted separately?
RecoveryDoes ndo_tx_timeout reset the hardware and restore the rings?
LinkIs carrier state reported on open and on every link change?
LimitsDo the MTU and the buffer length agree, with no silent truncation?
FiltersDoes ndo_set_rx_mode program promiscuous and multicast state?
LifecycleDo repeated up and down cycles and module unload under traffic leave no leaks or warnings?

Symptoms and causes

The failures of a network driver have recognizable signatures. An interface that comes up and never carries traffic usually has no carrier, no enabled interrupt or a ring base address the NIC cannot read: check ip link for NO-CARRIER, then /proc/interrupts for a count that never rises. A transmit that works for a few packets and then stops has a stopped queue that was never woken, which is the barrier bug above, or completions that are never reclaimed because the done bit is read wrongly.

A receive path that works at low rates and loses packets at high rates has a ring that is too small, a refill that fails and is not retried, or a poll function that does too much work per packet. Compare rx_missed style counters in ethtool -S with softnet_stat to tell hardware drops from software ones. A machine that freezes under a flood has a poll function that never returns, because it ignores the budget, or a handler that never masks the interrupt, which makes the CPU run nothing but interrupt handlers.

A crash in dma_unmap_single() or a warning from CONFIG_DMA_API_DEBUG means an unmap with the wrong size or direction, or a double unmap. Corrupted packet contents point at a missing dma_rmb(), or at a buffer reused while the NIC still owned it. A leak that grows by one packet per transmit timeout means the reset path did not free the in-flight buffers. And a driver that works alone but fails when two interfaces are present has global state that should have been per device.

When none of those fit, bisect by layer, as with every driver: confirm the NIC is enabled and responds, then that interrupts arrive, then that descriptors move, and then that packets reach the stack. The first layer that fails contains the bug.

Where this guide does not apply

This guide builds a driver for a simple PCI Express NIC with one ring pair and an on-chip link. It does not cover drivers that sit on a PHY through MDIO, which use phylink and are the norm on embedded boards. It does not cover wireless drivers, which use the mac80211 and cfg80211 frameworks, or virtual drivers such as veth, tun and virtio-net, which have no hardware rings, though virtio-net uses the same NAPI and ring ideas over shared memory. It does not cover switch drivers, which use switchdev and DSA and present several ports and an offloaded forwarding table.

It also stops short of the deepest layers of a production driver: device-specific firmware commands, hardware timestamping through the PTP interface, flow steering, SR-IOV virtual functions, as in the SR-IOV post, and the busy-polling and zero-copy receive features. Each is an addition to the structure shown, not a replacement.

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.