The Complete Guide to Linux PCI Device Drivers
Write a complete Linux 6.12 PCI driver: probe, BAR mapping, MSI interrupts, DMA with a restricted mask, a user-space interface, error recovery and testing.

A PCI driver is the place where nearly every part of the kernel's hardware model meets: bus enumeration, memory-mapped registers, interrupts, DMA, power management, error recovery and a user-space interface. Each of those is a separate topic with its own rules, and a driver for real hardware needs all of them to work together. This guide builds one complete driver for Linux 6.12, one subsystem at a time, so that each addition is small enough to understand and the whole is complete enough to use as a template. The target is QEMU's educational edu device, a virtual PCI device with a documented register map, an interrupt-raising factorial engine and a DMA engine, which makes every mechanism testable without risking real hardware. The same structure applies, register offsets aside, to a driver for a network card, a storage controller or an accelerator.
The short version: a PCI driver is a struct pci_driver with an ID table, a probe and a remove. In probe it enables the device, claims and maps its BARs, sets the DMA mask, allocates interrupt vectors and DMA memory, registers an interface for user space, and keeps a state structure. Everything it acquires is released in reverse order on failure and in remove. The rest of this guide is the detail and the reasoning behind each of those steps, plus the parts a first driver usually omits: locking, error recovery, hotplug and tests.
The authoritative references are the kernel's PCI documentation, the DMA API guide and the PCI Express Base Specification. The edu device is specified in the QEMU documentation.
What the bus has already done
By the time the kernel calls your probe, a good deal of work is finished, and knowing what saves you from redoing it. Firmware or the kernel has enumerated the bus, trained the link, read each function's configuration space and assigned address ranges to every BAR, as the post on how PCI Express works describes. The device is in a known state, and its resources are listed in the struct pci_dev that probe receives: vendor and device IDs, the resource array for the BARs, and the interrupt line.
What has not been done is anything that commits a resource to your driver. The device is not enabled, its regions are not reserved, no mapping exists, no interrupt is allocated and bus mastering is off. The driver's probe performs those steps, and each has a matching undo. That symmetry is the organizing idea of a PCI driver: every acquisition in probe has a release in remove, in the opposite order.
The device we drive
The edu device has vendor ID 0x1234 and device ID 0x11e8, one 1 MiB memory BAR (BAR 0), support for MSI and a small set of registers:
| Offset | Access | Meaning |
|---|---|---|
0x00 | read | Identification, 0xRRrr00ed for version RR.rr |
0x04 | read/write | Liveness check, reads back the inverse of the last write |
0x08 | read/write | Factorial input and result |
0x20 | read/write | Status: bit 0 busy, bit 7 raise interrupt when done |
0x24 | read | Interrupt status |
0x60 | write | Raise an interrupt with the given value |
0x64 | write | Acknowledge interrupt bits |
0x80 | read/write | DMA source address |
0x88 | read/write | DMA destination address |
0x90 | read/write | DMA transfer length |
0x98 | read/write | DMA command: bit 0 start, bit 1 direction, bit 2 raise interrupt |
0x40000 | memory | A 4 KiB buffer inside the device that DMA targets |
The device's DMA engine can address only 28 bits, so memory above 256 MiB is out of its reach. That is not an oddity of this device. Many real devices have address limits of 32 bits or less, and the DMA API is built for them, so edu is a good teacher exactly because it forces the mask logic to work.
Run the device by adding -device edu to a QEMU guest's command line. The guest then shows it:
lspci -nn | grep 123400:04.0 Unclassified device [00ff]: Red Hat, Inc. QEMU EDU device [1234:11e8] (rev 10)Everything in this guide runs inside that guest. A wrong register write cannot hurt anything real, which is the point.
Build setup and a first look
The module builds out of tree with the same Kbuild file as any other: obj-m += edu_driver.o and a Makefile that calls make -C /lib/modules/$(uname -r)/build M=$(PWD) modules. Load it with insmod, unload with rmmod, and keep dmesg -w open in a second terminal. The kernel log with the device name prefixed is the main output of a driver under development.
Two files in /proc and /sys help from the first run. /proc/iomem lists the address ranges and who has claimed them, and /sys/bus/pci/devices/0000:00:04.0/ has the resources and driver binding. Look at both before you write anything, to see what the device looks like from the system's side.
The ID table, the state structure and the registration
The skeleton is covered in the PCI skeleton post. In its final form for this driver it holds everything the later sections need:
// SPDX-License-Identifier: GPL-2.0
#include <linux/completion.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/io-64-nonatomic-lo-hi.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/pci.h>
#include <linux/uaccess.h>
#define DRV_NAME "edu_driver"
#define EDU_REG_ID 0x00
#define EDU_REG_LIVE 0x04
#define EDU_REG_FACT 0x08
#define EDU_REG_STATUS 0x20
#define EDU_REG_IRQ_STATUS 0x24
#define EDU_REG_IRQ_ACK 0x64
#define EDU_REG_DMA_SRC 0x80
#define EDU_REG_DMA_DST 0x88
#define EDU_REG_DMA_CNT 0x90
#define EDU_REG_DMA_CMD 0x98
#define EDU_DEV_BUF 0x40000
#define EDU_STATUS_BUSY BIT(0)
#define EDU_STATUS_IRQ_EN BIT(7)
#define EDU_IRQ_FACT 0x01
#define EDU_IRQ_DMA 0x100
#define EDU_DMA_START BIT(0)
#define EDU_DMA_FROM_DEV BIT(1)
#define EDU_DMA_IRQ BIT(2)
#define EDU_DMA_SIZE 4096
static const struct pci_device_id edu_ids[] = {
{ PCI_DEVICE(0x1234, 0x11e8) },
{ }
};
MODULE_DEVICE_TABLE(pci, edu_ids);
struct edu {
struct pci_dev *pdev;
void __iomem *regs;
struct mutex lock; /* one operation at a time */
struct completion done;
u32 irq_status;
void *dma_buf;
dma_addr_t dma_handle;
struct miscdevice misc;
};The mutex serializes operations because the device has one factorial engine and one DMA engine, and two callers using them at once would corrupt each other. The completion is how the interrupt handler tells the waiting caller the operation finished. The DMA buffer and handle are the coherent memory the device reads and writes. The miscdevice is the user-space interface, added later.
Enable the device, claim and map the BAR
probe begins with the steps that make the device usable. The order is fixed by dependency: enable before claiming, claim before mapping.
static int edu_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct edu *e;
int ret;
e = kzalloc(sizeof(*e), GFP_KERNEL);
if (!e)
return -ENOMEM;
e->pdev = pdev;
mutex_init(&e->lock);
init_completion(&e->done);
ret = pci_enable_device(pdev);
if (ret)
goto err_free;
ret = pci_request_regions(pdev, DRV_NAME);
if (ret)
goto err_disable;
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
ret = -ENODEV;
goto err_release;
}
e->regs = pci_iomap(pdev, 0, 0);
if (!e->regs) {
ret = -ENOMEM;
goto err_release;
}
dev_info(&pdev->dev, "edu id 0x%08x\n", ioread32(e->regs + EDU_REG_ID));
/* later sections add DMA, interrupts and the user interface here */
pci_set_drvdata(pdev, e);
return 0;
err_release:
pci_release_regions(pdev);
err_disable:
pci_disable_device(pdev);
err_free:
kfree(e);
return ret;
}pci_enable_device() powers up the device and turns on its memory decoding. pci_request_regions() reserves every BAR under the driver's name so that no other driver can map the same range. The flag check guards the assumption that BAR 0 is memory, since a device that exposes an I/O port BAR instead would break the mapping. pci_iomap() returns an __iomem pointer that only the ioread and iowrite families may dereference, as the BAR mapping post explains. The first register read proves the whole chain works:
edu_driver 0000:00:04.0: edu id 0x010000edIf that line shows 0xffffffff, the device is not responding, and the likely causes are a missing pci_enable_device(), memory decoding disabled in the command register or a failed link.
Register access and the posted-write rule
Every access to the device goes through ioread32() and iowrite32(), which produce the right instruction on any architecture and keep the compiler from merging or reordering accesses to the same device. Their one blind spot is that writes are posted. The CPU hands the write to the interconnect and moves on, so a later instruction can run before the device has seen the write.
For this device the consequence appears in the liveness test, which is the simplest register interaction. Writing a value and reading it back works, because the read cannot complete until the earlier write has reached the device:
static int edu_selftest(struct edu *e)
{
u32 val;
iowrite32(0x12345678, e->regs + EDU_REG_LIVE);
val = ioread32(e->regs + EDU_REG_LIVE);
if (val != ~0x12345678U) {
dev_err(&e->pdev->dev, "liveness check failed: 0x%08x\n", val);
return -EIO;
}
return 0;
}edu_driver 0000:00:04.0: liveness check passedThe same trick, a read from the same device, is how a driver flushes a write that must take effect before the next step, such as before a delay or before starting a transfer. It is worth making a habit, since the bugs it prevents appear only on slow buses.
Interrupts with MSI
A device that does work asynchronously needs to tell the driver when it is done. edu raises an interrupt when the factorial completes or a DMA transfer ends. The allocation call chooses the best mode, as the MSI post details:
static irqreturn_t edu_irq(int irq, void *data)
{
struct edu *e = data;
u32 status = ioread32(e->regs + EDU_REG_IRQ_STATUS);
if (!status)
return IRQ_NONE;
e->irq_status = status;
iowrite32(status, e->regs + EDU_REG_IRQ_ACK);
complete(&e->done);
return IRQ_HANDLED;
}
static int edu_setup_irq(struct edu *e)
{
struct pci_dev *pdev = e->pdev;
int nvec, ret;
nvec = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES);
if (nvec < 0)
return nvec;
ret = request_irq(pci_irq_vector(pdev, 0), edu_irq,
pdev->msi_enabled ? 0 : IRQF_SHARED, DRV_NAME, e);
if (ret)
pci_free_irq_vectors(pdev);
return ret;
}The handler reads the cause, returns IRQ_NONE if none of its bits are set (a requirement when the line is shared), saves the status, acknowledges the interrupt by writing the same bits back to the acknowledge register, and signals the completion. Acknowledging before returning is mandatory for a level-triggered interrupt, which would otherwise fire again immediately.
Add the call to probe after the mapping, with err_unmap and err_irq labels in the cleanup chain. In remove, disable the interrupt source first by clearing the enable bit in the status register, then free the interrupt and the vectors, in that order. A handler that runs after the structure is freed is a use after free, so the interrupt must be freed before anything it uses.
Afterwards, /proc/interrupts shows the vector and its count:
grep edu /proc/interrupts 24: 0 0 PCI-MSI-0000:00:04.0 0-edge edu_driverAn operation that waits for an interrupt
With interrupts working, the factorial can be computed without polling. The operation enables the completion interrupt, starts the work, and sleeps until the handler wakes it, with a timeout so a dead device cannot hang the caller:
static int edu_factorial(struct edu *e, u32 n, u32 *result)
{
int ret = 0;
mutex_lock(&e->lock);
reinit_completion(&e->done);
iowrite32(EDU_STATUS_IRQ_EN, e->regs + EDU_REG_STATUS);
iowrite32(n, e->regs + EDU_REG_FACT);
if (!wait_for_completion_timeout(&e->done, msecs_to_jiffies(500))) {
dev_err(&e->pdev->dev, "factorial timed out\n");
ret = -ETIMEDOUT;
goto out;
}
*result = ioread32(e->regs + EDU_REG_FACT);
out:
mutex_unlock(&e->lock);
return ret;
}reinit_completion() clears a completion that a previous operation used. The order of the two writes matters: the interrupt enable bit is set before the work starts, so that a very fast completion cannot be missed. The log for n equal to 10 reads:
edu_driver 0000:00:04.0: 10! = 3628800A timeout that fires is a clue, not a nuisance. It means the device never raised the interrupt, and the first suspects are the interrupt-enable write, an interrupt that was never delivered to the CPU (check /proc/interrupts for a stuck count) or a handler that returned IRQ_NONE because the status register read as zero.
The DMA mask and coherent memory
DMA starts with the mask. The edu engine can address 28 bits, so the driver tells the DMA layer, and the layer allocates memory the device can reach, as the DMA post explains:
static int edu_setup_dma(struct edu *e)
{
struct pci_dev *pdev = e->pdev;
int ret;
ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(28));
if (ret) {
dev_err(&pdev->dev, "no usable 28-bit DMA mask\n");
return ret;
}
pci_set_master(pdev);
e->dma_buf = dma_alloc_coherent(&pdev->dev, EDU_DMA_SIZE,
&e->dma_handle, GFP_KERNEL);
if (!e->dma_buf)
return -ENOMEM;
return 0;
}If the mask were wider than the device's real limit, the allocator could return memory at an address the device cannot drive, and the transfer would corrupt whatever the truncated address pointed at. Setting the honest mask is what makes the allocator pick low memory, or lets the IOMMU or a bounce buffer cover the gap. pci_set_master() is needed because the device initiates the transfers itself.
dma_alloc_coherent() returns two values: a kernel virtual address the CPU uses and a dma_addr_t the device uses. They are different numbers, and the register must get the second. Release the buffer in remove with dma_free_coherent(), using the same size and both values.
A DMA round trip
The device's internal buffer at offset 0x40000 is the target. A write copies bytes from RAM into it, and a read copies them back. Both directions use the same registers:
static int edu_dma(struct edu *e, bool from_device, u64 dev_addr,
dma_addr_t bus, size_t len)
{
u64 src = from_device ? dev_addr : bus;
u64 dst = from_device ? bus : dev_addr;
u32 cmd = EDU_DMA_START | EDU_DMA_IRQ |
(from_device ? EDU_DMA_FROM_DEV : 0);
reinit_completion(&e->done);
lo_hi_writeq(src, e->regs + EDU_REG_DMA_SRC);
lo_hi_writeq(dst, e->regs + EDU_REG_DMA_DST);
lo_hi_writeq(len, e->regs + EDU_REG_DMA_CNT);
iowrite32(cmd, e->regs + EDU_REG_DMA_CMD);
if (!wait_for_completion_timeout(&e->done, msecs_to_jiffies(500)))
return -ETIMEDOUT;
return 0;
}
static int edu_dma_roundtrip(struct edu *e)
{
size_t len = 64;
int ret;
memcpy(e->dma_buf, "round trip through the device buffer", 37);
mutex_lock(&e->lock);
ret = edu_dma(e, false, EDU_DEV_BUF, e->dma_handle, len);
if (!ret) {
memset(e->dma_buf, 0, len);
ret = edu_dma(e, true, EDU_DEV_BUF, e->dma_handle, len);
}
mutex_unlock(&e->lock);
if (!ret)
dev_info(&e->pdev->dev, "dma returned: %s\n",
(char *)e->dma_buf);
return ret;
}edu_driver 0000:00:04.0: dma returned: round trip through the device bufferThe test is built to be meaningful. The buffer is cleared between the two transfers, so the text that comes back must have gone to the device and returned, and a stale copy cannot pass. Because the memory is coherent, the CPU needs no cache maintenance between the write by the device and the read in the dev_info call. A driver using a streaming mapping would add dma_sync_single_for_cpu() there.
The command register is written last on purpose. Writing the start bit begins the transfer, so every other register must be valid before it. The lo_hi_writeq() helper writes a 64-bit register as two 32-bit stores, low half first, which is the safe form for a device that may not support 64-bit accesses.
A streaming alternative
Coherent memory fits a long-lived buffer. For a buffer that already exists, such as a user page or a packet, a streaming mapping avoids the copy. The same transfer with a mapping looks like this:
dma_addr_t bus = dma_map_single(&pdev->dev, buf, len, DMA_TO_DEVICE);
if (dma_mapping_error(&pdev->dev, bus))
return -ENOMEM;
ret = edu_dma(e, false, EDU_DEV_BUF, bus, len);
dma_unmap_single(&pdev->dev, bus, len, DMA_TO_DEVICE);Every streaming mapping is checked with dma_mapping_error() and ended with the matching unmap, since the unmap is what returns the buffer to the CPU and, on a system with an IOMMU, revokes the device's access. The direction names the side that writes, and choosing it narrowly lets the kernel skip cache operations it does not need. The same 28-bit mask applies, and the streaming layer enforces it with a bounce buffer if the buffer sits above 256 MiB, at the cost of an extra copy.
The user-space interface
Nothing so far lets a program use the device. A misc device is the lightest way to add a node: a single struct miscdevice registers a character device with a dynamic minor number, and the driver adds an ioctl for the factorial.
#define EDU_IOC_FACTORIAL _IOWR('e', 1, __u32)
static long edu_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct miscdevice *misc = file->private_data;
struct edu *e = container_of(misc, struct edu, misc);
u32 n, result;
int ret;
if (cmd != EDU_IOC_FACTORIAL)
return -ENOTTY;
if (get_user(n, (u32 __user *)arg))
return -EFAULT;
if (n > 12)
return -EINVAL;
ret = edu_factorial(e, n, &result);
if (ret)
return ret;
return put_user(result, (u32 __user *)arg);
}
static const struct file_operations edu_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = edu_ioctl,
.llseek = noop_llseek,
};In probe set e->misc.minor = MISC_DYNAMIC_MINOR, e->misc.name = "edu" and e->misc.fops = &edu_fops, then call misc_register(&e->misc). In remove call misc_deregister() first, before anything the file operations use is released. The input is validated before it reaches the hardware: factorials above 12 overflow a 32-bit result, and the range check turns a silent wrong answer into an error. A user program then calls the device with an ioctl, ioctl(fd, EDU_IOC_FACTORIAL, &n), and gets the factorial back in the same variable. The node appears as /dev/edu.
An open file can outlive the device, and removing the driver while a program holds the node needs the same lifetime care as the USB case in the disconnect post: deregister the node first, so no new opens arrive, and let a reference count or the misc layer's own handling keep the structure alive for existing ones. For a driver that must handle hot removal, the discipline in the hotplug post applies.
Locking and concurrency
The driver has several things that can run at the same time: user calls through the ioctl, the interrupt handler, the removal path and power callbacks. The rules for keeping them apart are short.
The mutex lock serializes operations on the engines, and it is a sleeping lock, so it is held only in process context. The interrupt handler never takes it. The handler communicates through the completion and the irq_status field, with a clear order: the handler writes the field, then completes, and the waiter reads the field after the wait returns. The completion supplies the memory ordering.
Data shared between the handler and process context that cannot use a completion needs a spinlock taken with spin_lock_irqsave() in process context and spin_lock() in the handler, so a handler cannot interrupt the holder and deadlock on it. Registers touched in both contexts, for example a shared mask register, follow the same rule. A common error is reading a register in process context while the handler modifies a related one, which leaves the two views inconsistent for an instant. The fix is to read the shared state under the spinlock.
The removal path stops the sources first: disable the device's interrupt enable, free the interrupt, deregister the node, then release memory. Running those in the wrong order is the way a driver ends with a handler that runs after its structure is freed.
Power management and reset
A driver that ignores power management still works until the machine suspends. The PCI core saves and restores configuration space for the device automatically in the common case, but the device's own registers are the driver's responsibility. A driver adds power management callbacks through struct dev_pm_ops in the driver member of the pci_driver:
static int edu_suspend(struct device *dev)
{
struct edu *e = dev_get_drvdata(dev);
mutex_lock(&e->lock);
iowrite32(0, e->regs + EDU_REG_STATUS); /* interrupts off */
return 0;
}
static int edu_resume(struct device *dev)
{
struct edu *e = dev_get_drvdata(dev);
mutex_unlock(&e->lock);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(edu_pm_ops, edu_suspend, edu_resume);Holding the lock across the sleep keeps new operations out until resume, and the .driver.pm = &edu_pm_ops entry hooks the table in. A device whose state is lost in sleep re-programs its registers in resume, which for edu means nothing, since its operations configure themselves for each call. A driver that cannot tolerate being suspended with an operation in flight waits for it, and the lock does that here.
Function-level reset is the second path. A device that hangs can be reset through the reset file in sysfs, and the PCI core calls the driver's reset_prepare and reset_done callbacks around it, in err_handler. They follow the same pattern as the USB reset callbacks: block new work in the first and restore the device state in the second.
Error recovery and hotplug
A link error or a surprise removal is the case that separates driver quality. The structure from the error recovery post supplies error_detected, slot_reset and resume callbacks, and the first one stops the operations before the device is reset:
static pci_ers_result_t edu_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct edu *e = pci_get_drvdata(pdev);
complete_all(&e->done); /* release any waiter */
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
return PCI_ERS_RESULT_NEED_RESET;
}Completing the completion wakes any thread blocked in wait_for_completion_timeout(), so it returns immediately and its caller sees a failure instead of waiting out the timeout. slot_reset re-enables the device, restores the saved configuration space, and a pci_save_state() at the end of probe is what makes that possible. A surprise removal reaches remove, which must not wait on the hardware: it checks pci_device_is_present() and, if the device is gone, skips the register writes that would have quiesced it.
Debugging a PCI driver
The tools are the same ones used earlier in the cluster. lspci -vv -s 00:04.0 shows the command register and the BAR assignments, and a Mem- or BusMaster- there says the device was not enabled or bus mastering was never turned on. /proc/iomem shows the reservation your driver made, and a missing line means pci_request_regions() did not run. /proc/interrupts shows whether the vector fired, and a count that never rises while the device was supposed to interrupt points at the enable bit, the vector allocation or the delivery path.
For code-level bugs, a development kernel with CONFIG_KASAN finds use-after-free in the interrupt and removal paths, CONFIG_DEBUG_ATOMIC_SLEEP finds a sleeping call in the handler, and CONFIG_DMA_API_DEBUG finds DMA mapping errors such as an unmap with the wrong size. Dynamic debug turns your dev_dbg() lines on at run time with echo 'module edu_driver +p' > /sys/kernel/debug/dynamic_debug/control, so verbose output costs nothing in a normal build.
For protocol questions, the device's own register map is the reference. The most useful debugging habit is to log the value of every status and interrupt register on every unexpected path, since the answer to "why did this fail" is nearly always in a register the driver already knows how to read.
Testing the driver
A test plan follows the same order as the driver's construction. Check probe: load the module and confirm the ID line and the liveness check. Check interrupts: run the factorial for several inputs and confirm the log and the /proc/interrupts count rise together. Check DMA: run the round trip, then repeat it with the buffer cleared to confirm the data really travels. Check the interface: write a small program that opens /dev/edu, calls the ioctl for 5 and prints 120, and one that calls it with 13 and gets EINVAL.
Then stress the lifecycle, which is where most bugs hide:
for i in $(seq 1 100); do
echo 0000:00:04.0 | sudo tee /sys/bus/pci/drivers/edu_driver/unbind > /dev/null
echo 0000:00:04.0 | sudo tee /sys/bus/pci/drivers/edu_driver/bind > /dev/null
done
sudo dmesg | tail -n 2edu_driver 0000:00:04.0: edu id 0x010000ed
edu_driver 0000:00:04.0: liveness check passedA hundred cycles of unbind and bind expose leaks in probe and remove: a leaked region makes the second probe fail with -EBUSY, a leaked vector exhausts the interrupt space, and a leaked DMA buffer shows up in /proc/meminfo over time. Repeat the same with a program running ioctls in a loop, and with a write to the device's reset file in sysfs. In a virtual machine, removing the device through the hypervisor's console exercises surprise removal. A driver that survives all of these has earned the label.
Alternatives to a kernel driver
Not every PCI device needs a driver in the kernel. When a single program uses the device and the isolation of user space is worth more than a standard interface, VFIO gives the program the device with the IOMMU confining its DMA, as the VFIO post shows. DPDK and SPDK use that to drive network cards and NVMe drives from user space, and virtual machines use it to pass a card to a guest. A virtualization-friendly device may also support SR-IOV, in which case the physical function driver adds the sriov_configure callback and the guests get virtual functions, covered in the SR-IOV post.
The choice mirrors the USB question in the libusb comparison: a kernel driver for a standard interface or early availability, and a user-space driver for isolation, portability and speed of development.
Several devices, one driver
Nothing in the driver may assume there is only one device. A machine can hold two edu devices, and probe runs once for each, with a different struct pci_dev and a fresh struct edu. The rules that follow are simple and easy to break. Keep all per-device state in the structure, and keep it out of global and static variables. Do not store a pointer to the first device in a global so that the ioctl can find it. The ioctl in this guide finds its device through the miscdevice embedded in the structure, so it works for any number of devices. The names must be unique too: a misc device name is a node name, so a second device needs edu0 and edu1, built with a counter or an IDA allocator, and a fixed "edu" would make the second registration fail.
The same holds for resources named with a string. The region name passed to pci_request_regions() need not be unique, since the range is what conflicts, but interrupt names and workqueue names show up in /proc/interrupts and in the process list, and distinct names are what make a two-device system debuggable.
Top halves, bottom halves and threaded handlers
The interrupt handler in this guide does very little, and that is the model. A hard interrupt handler runs with the CPU's interrupts masked for that line, in a context where it cannot sleep, and every microsecond spent there delays every other interrupt on that CPU. The usual structure splits the work in two. The top half reads the cause, acknowledges the device and records what happened. The bottom half does the real work later, in a context where sleeping and longer processing are allowed.
The kernel offers several bottom-half mechanisms. A workqueue item runs in process context and may sleep, so it is the right tool for anything that takes a mutex or talks to a slow bus. A threaded interrupt, requested with request_threaded_irq(), combines the two: the first function runs in the hard handler and returns IRQ_WAKE_THREAD, and the second runs in a dedicated kernel thread. A tasklet or a softirq runs in a restricted context that cannot sleep and is reserved for the very high rate paths such as networking, where its cost is justified. New drivers choose between the first two.
For edu, completions already serve as a bottom half in disguise: the handler wakes the waiter, and the waiter does the work in process context. A device with a stream of events, such as a network card, uses NAPI or a workqueue with a list protected by a spinlock. A rule of thumb for the split is to ask what must happen before the device can raise the next interrupt. That part, usually reading and acknowledging a status register, belongs in the top half. Everything else is deferrable.
What a PCI driver costs, and why
Performance advice in driver work is full of folklore, so it is worth stating where time actually goes, from the mechanism. A register read over PCI Express is expensive, because the CPU waits for a round trip across the link: a memory read request goes out as a packet and the completion comes back before the instruction finishes. A write is posted and does not wait. The consequence is that code that reads status registers in a loop, or reads several registers per operation, spends most of its time stalled, and the standard remedy is to keep state in memory that the device updates by DMA, so the driver reads host memory in the fast path and touches registers only to start work.
Interrupts cost a context switch and a trip through the interrupt controller each time, which is why high-rate devices coalesce them: the device raises one interrupt for a batch of events, within limits the driver programs. The trade is latency for CPU efficiency. DMA mappings cost time too, since each streaming map and unmap updates IOMMU tables and may flush a translation cache, so drivers that move many small buffers map once and reuse, with the sync calls at each handoff.
Locks matter as much as I/O. A lock taken on every packet, shared by all CPUs, serializes a path that the hardware could run in parallel. Devices with several queues give each queue its own lock, interrupt vector and CPU, as the MSI post shows with affinity. Measuring comes before changing any of it: perf shows where the CPU spends time, and the interrupt and softirq counters in /proc show the rates. None of these costs is a reason to complicate a first driver. They are what to look at when a working driver is too slow.
A review checklist
Before treating the driver as finished, read it against these questions. Each describes a class of bug that has shipped in real drivers.
| Area | Question |
|---|---|
| Probe | Is every acquisition undone in reverse order on every error path and in remove? |
| Enable | Is bus mastering enabled only if the device does DMA? |
| BARs | Are the BAR type and size checked before mapping, and every offset bounded? |
| Registers | Is every access through ioread and iowrite, with a read back where order matters? |
| DMA | Is the mask set to the device's true width, and every mapping checked and unmapped? |
| Interrupts | Does the handler return IRQ_NONE for foreign causes and acknowledge its own? |
| Context | Does nothing sleep in the handler, and does everything that sleeps run in process context? |
| Waits | Does every wait have a timeout, and does a timeout leave the device in a known state? |
| Locking | Are shared registers and state protected with the right kind of lock for each context? |
| Teardown | Are interrupt source, interrupt, node and memory released in that order? |
| Multiple devices | Is all state per device, with unique names? |
| Power | Do suspend and resume stop and restore the device's own state? |
| Errors | Are recovery callbacks provided, and is a missing device detected with pci_device_is_present()? |
| User input | Is every value from user space validated before it reaches a register? |
Failures and what they mean
The symptoms below account for most of the time spent on a new PCI driver, and each points back to one part of this guide. A read of all ones from a register means the device is not enabled, memory decoding is off or the link is down, which sends you to the enable step and to the command register in lspci -vv. A probe that fails with -EBUSY from pci_request_regions() means another driver already holds the BAR, and lspci -k names it. A timeout that never ends in an interrupt means the enable bit, the vector or the handler is wrong, and the /proc/interrupts count tells you which. A transfer whose data is wrong or partly stale means a mask or a mapping problem, or a read of coherent memory before the device finished.
A crash a moment after rmmod means a handler or a work item ran against freed memory, and the fix is in the teardown order. A system that locks up under load usually has a handler that does too much, a lock held across a sleep, or an interrupt that is never acknowledged and therefore fires forever, and the NMI watchdog output or perf identifies the loop. A warning about "sleeping function called from invalid context" names the function and shows the stack, and the cure is to move the call to a workqueue. A failure only after a suspend and resume cycle means the device lost state that the driver did not restore.
When none of these matches, narrow the layer. Confirm the device responds, then that interrupts arrive, then that DMA moves data, and only then suspect the logic above them. Each layer can be tested alone with the tools in this guide, and the bug lives in the first one that fails.
Inspecting the device from user space
A driver is not the only way to look at a PCI device, and during development the other ways are valuable. Every BAR is exposed as a file under the device's sysfs directory, named resource0, resource1 and so on, and a privileged program can map it with mmap() and read the registers without any driver loaded. That is how small tools read a device that nothing owns, and it is also how you check the registers of your own device from outside the driver while it is running, to see what the hardware thinks. The files resource and config in the same directory hold the address ranges and the raw configuration space, and they are the source of what lspci prints.
The convenience has a cost that matches its power. A program writing to resource0 bypasses every lock in the driver, so a write there while the driver runs can corrupt its state, and with the IOMMU off such a program can program a device to DMA anywhere. Use these files to read, and treat any write as a deliberate experiment on a test machine. Kernels with lockdown enabled, as many distributions use under Secure Boot, refuse access to these files entirely, which is the right default for production.
Where this guide does not apply
The driver here handles a conventional PCI Express endpoint with memory BARs, MSI and one DMA engine. It does not cover devices behind PCI bridges that need their own resources, which are handled by the core. It does not cover the many virtual and platform devices that look like PCI but live on a SoC bus, whose drivers use the platform interfaces. It does not cover GPUs, network and storage controllers in depth, whose subsystems add large frameworks on top of the PCI layer: DRM, the network stack and the block layer each have their own rules and their own guide. It does not cover peer-to-peer DMA between devices, large BAR resizing or the PCIe features used by accelerators, such as shared virtual addressing.
It also assumes a device that behaves. Real hardware has errata, and errata handling is where drivers become long: workarounds keyed on the revision ID, delays that the datasheet forgot to mention, registers that read back stale values. The structure here gives those workarounds a place to live, in a quirk table keyed on the ID and revision, and not in the main flow.


