Skip to content
systemcoding.dev
Kernels

Write a PCI Driver Skeleton With pci_driver and probe

Write a minimal Linux 6.12 PCI driver with a pci_device_id table, probe and remove, pci_enable_device, region claiming, bus mastering and the error unwinding.

6 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 Rust logos.

A PCI driver has the same shape as a USB driver: an ID table, a probe that runs when a matching device appears, a remove that undoes it, and one structure that registers them. The difference is what probe does. A PCI device arrives with its resources already assigned, and the driver must enable it, claim its address ranges, and decide whether it will do DMA. This post writes that skeleton for Linux 6.12, explains the order of the calls and the error unwinding, and shows the kernel messages it produces. The next posts add BAR mapping, interrupts and DMA to it.

The reference is the kernel's How To Write Linux PCI Drivers and include/linux/pci.h.

The ID table

The table lists the vendor and device pairs the driver supports, ended by an empty entry:

c
static const struct pci_device_id sample_ids[] = {
	{ PCI_DEVICE(0x1234, 0x11e8) },
	{ }
};
MODULE_DEVICE_TABLE(pci, sample_ids);

PCI_DEVICE(vendor, device) matches an exact pair and ignores the subsystem IDs. PCI_DEVICE_SUB() adds a subsystem match for boards that need different handling, and PCI_DEVICE_CLASS(class, mask) matches by class code for generic drivers. MODULE_DEVICE_TABLE(pci, ...) exports the table into the module's metadata, so udev can load the module when the hardware appears, as described in the lookup post.

The pair 0x1234:0x11e8 is not arbitrary. It is the ID of the educational edu device in QEMU, which a later post uses as a safe target for experiments, so the skeleton here is ready for it.

The full skeleton

sample_pci.cc
// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>

#define DRV_NAME "sample_pci"

static const struct pci_device_id sample_ids[] = {
	{ PCI_DEVICE(0x1234, 0x11e8) },
	{ }
};
MODULE_DEVICE_TABLE(pci, sample_ids);

struct sample {
	struct pci_dev	*pdev;
};

static int sample_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
	struct sample *s;
	int ret;

	s = kzalloc(sizeof(*s), GFP_KERNEL);
	if (!s)
		return -ENOMEM;
	s->pdev = pdev;

	ret = pci_enable_device(pdev);
	if (ret)
		goto err_free;

	ret = pci_request_regions(pdev, DRV_NAME);
	if (ret)
		goto err_disable;

	pci_set_master(pdev);
	pci_set_drvdata(pdev, s);

	dev_info(&pdev->dev, "bound to %04x:%04x, BAR0 %pR\n",
		 pdev->vendor, pdev->device, &pdev->resource[0]);
	return 0;

err_disable:
	pci_disable_device(pdev);
err_free:
	kfree(s);
	return ret;
}

static void sample_remove(struct pci_dev *pdev)
{
	struct sample *s = pci_get_drvdata(pdev);

	pci_release_regions(pdev);
	pci_disable_device(pdev);
	kfree(s);
	dev_info(&pdev->dev, "removed\n");
}

static struct pci_driver sample_driver = {
	.name		= DRV_NAME,
	.id_table	= sample_ids,
	.probe		= sample_probe,
	.remove		= sample_remove,
};
module_pci_driver(sample_driver);

MODULE_DESCRIPTION("Minimal PCI driver skeleton");
MODULE_LICENSE("GPL");

module_pci_driver() generates the init and exit functions that call pci_register_driver() and pci_unregister_driver().

What each call is for

**pci_enable_device()** wakes the device from a low-power state and enables its I/O and memory decoding, by setting bits in the command register. Without it, the device does not respond to accesses to its BARs and reads come back as all ones. It also assigns the interrupt line when the device needs a legacy one.

**pci_request_regions()** claims every BAR of the device for your driver under the name you give, and it fails with -EBUSY if another driver already holds one. The names appear in /proc/iomem and /proc/ioports, which makes it easy to see who owns what. Claiming regions is not a mapping. It is a reservation that prevents two drivers from using the same range.

**pci_set_master()** turns on bus mastering, which lets the device start DMA. Call it only if the device will do DMA, since it is an extra capability to grant. A device that only exposes registers has no need for it.

**pci_set_drvdata() and pci_get_drvdata()** attach your private structure to the pci_dev, the same way usb_set_intfdata() does for USB.

On a successful bind for the QEMU device at address 0000:00:04.0, the log shows:

Text
sample_pci 0000:00:04.0: bound to 1234:11e8, BAR0 [mem 0xfebf0000-0xfebfffff]

The %pR format prints a resource as its type and range, which is a quick way to confirm the BAR was assigned. When the module is removed with rmmod, or the device is unbound, remove prints the last line:

Text
sample_pci 0000:00:04.0: removed

The unwinding rule

Every successful step needs an undo, in the reverse order, on both the error path and the remove path. The labels above show the pattern: err_disable undoes pci_enable_device(), err_free undoes the allocation. A mistake in this order is a leak that appears only on the failing path, which is the path nobody tests. The discipline is to add the undo for each call at the moment you add the call, and to keep remove as the mirror image of probe.

The kernel also offers managed variants, whose names start with pcim_ and devm_, that release resources automatically when the driver detaches. pcim_enable_device() replaces pci_enable_device() and its undo, and devm_kzalloc() replaces kzalloc() and kfree(). They remove entire classes of leaks. They are the better choice in new drivers, with one caution for kernel 6.12: the managed behavior of the region and mapping calls has been changing across recent releases, so check the documentation for the exact version when you mix pcim_enable_device() with pci_request_regions() and pci_iomap(). The unmanaged calls used here behave the same on every version, which is why they are used for teaching.

Choosing what to return

probe returns zero to claim the device and a negative errno to refuse it. Return -ENODEV if, after looking at the device, you decide it is not one you can drive, for example because a revision register shows an unsupported chip. Return -ENOMEM for allocation failure and pass through whatever the helper returned for the rest. A non-zero return leaves the device without a driver, and the core may offer it to another one.

A check before the first real access

A common first bug is a driver that works on one machine and reads garbage on another. Before relying on a BAR, confirm it is the kind of resource you expect:

c
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
	dev_err(&pdev->dev, "BAR 0 is not a memory region\n");
	ret = -ENODEV;
	goto err_release;
}

A device that exposes its registers in I/O port space instead has a BAR with the IORESOURCE_IO flag, and mapping it as memory fails. The check is cheap and turns a mysterious crash into a clear message. It also documents the assumption your driver makes about the hardware, which is the point of a check at this level.

Building and loading

An out-of-tree PCI module uses the same Kbuild line as the USB one: obj-m += sample_pci.o, built with make -C /lib/modules/$(uname -r)/build M=$PWD modules. Load it with sudo insmod sample_pci.ko. If a device with the matching IDs is present and no other driver holds it, probe runs at once. If another driver has it, unbind that one first with the sysfs unbind file, then write the address to your driver's bind file.

Testing the unbind and rebind cycle

A skeleton is not finished until both directions work. After the first successful bind, write the device address to the driver's unbind file, confirm that remove ran and printed its message, and write the address to the bind file to run probe again. A second probe that fails with -EBUSY from pci_request_regions() shows that remove forgot pci_release_regions(), and one that fails inside pci_enable_device() shows that the enable count was not balanced. The two failures are the usual symptoms of an unwinding bug, and finding them now costs a minute, while finding them after the driver has grown several resources costs an afternoon.

Also inHardware
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.