Handle PCIe Hotplug and Surprise Removal in Drivers
Make a Linux 6.12 PCIe driver survive hot removal: detect all-ones reads, use pci_device_is_present, stop DMA and work, and get remove to finish cleanly.

A PCIe device can leave a running system in two ways. In orderly removal, an operator presses a button or runs a command, the kernel tells the driver, and the driver shuts down while the device is still there. In surprise removal, the card or cable is gone: the link drops, every register read returns all ones, and the driver finds out only because something stopped working. NVMe drives, Thunderbolt enclosures, GPUs in external boxes and cards in hot-swap servers all take the second path, and a driver written for the first path hangs or crashes on it. This post covers how Linux 6.12 handles hotplug, how a driver detects that its device vanished, and how to write the I/O and remove paths so they finish. It builds on the PCI error handling post and on USB disconnect handling, whose patterns apply.
The kernel side is in the PCI hotplug documentation and in drivers/pci/hotplug/.
How the kernel learns about removal
PCIe hotplug is a slot feature. A slot with a hot-plug controller has a presence detect pin and, usually, an attention button and power control. The pciehp driver, the native PCI Express hotplug service, watches the slot's status through the downstream port's registers and handles two events:
Presence detect changed: a card was inserted or removed. On removal,
pciehpremoves the device from the system, which calls its driver'sremovecallback.Data link layer state changed: the link went down. This is how a surprise removal appears when the presence pin is not wired.
Either way, the kernel's reaction is to tear the device down by calling remove, and that call happens after the hardware is already gone. The driver cannot ask the device to quiesce. Every register access in remove fails, so remove must work with a dead device.
Check how the slot is set up:
ls /sys/bus/pci/slots
cat /sys/bus/pci/slots/3/address
cat /sys/bus/pci/slots/3/power3
0000:02:00
1A slot directory exists when a hot-plug controller manages it. power reads 1 when the slot is powered. Writing 0 to power is the orderly removal: the kernel removes the device first, then powers the slot down, so an operator can pull the card safely. The same write with 1 powers the slot and enumerates the new device.
What a gone device looks like
When the link is down, the root port completes every read to the device with an error, and the CPU sees 0xffffffff for a 32-bit read (and all ones for other widths). Writes are discarded. On some platforms the error is reported as a machine check, which the platform firmware may convert into a recoverable event. Linux's AER handling covers the case where the error is reported rather than silently completed.
The practical detection tools are these:
static bool sample_device_gone(struct sample *s)
{
if (pci_channel_offline(s->pdev))
return true;
return ioread32(s->regs + REG_ID) == 0xffffffff;
}pci_channel_offline() returns true when the PCI error recovery core has already marked the channel as frozen or permanently failed. It is cheap and involves no hardware access. The all-ones read is the fallback for a device that vanished before anyone told the kernel. Pick a register that can never legitimately read all ones, such as an ID or version register, and check it only on error paths and slow paths, not in the fast path of every operation.
A related helper, pci_device_is_present(), reads the vendor ID register from configuration space and returns false if it comes back as all ones. It is the reliable test, because the vendor ID of a real device is never 0xffff. It costs a configuration read, so call it where you already suspect a problem.
Loops that never finish
The classic surprise-removal bug is a polling loop that waits for a status bit:
while (!(ioread32(s->regs + REG_STATUS) & STATUS_DONE))
cpu_relax();With the device gone, the read returns 0xffffffff, the STATUS_DONE bit looks set in all-ones, and the loop exits immediately, treating garbage as a result. Reverse the condition, wait for a bit to clear, and the loop spins forever, since all ones never clears. Both are wrong. The repair is to bound every wait and to check for the dead device inside it:
static int sample_wait_idle(struct sample *s)
{
unsigned long end = jiffies + msecs_to_jiffies(1000);
u32 status;
do {
status = ioread32(s->regs + REG_STATUS);
if (status == 0xffffffff)
return -ENODEV;
if (!(status & STATUS_BUSY))
return 0;
usleep_range(100, 200);
} while (time_before(jiffies, end));
return -ETIMEDOUT;
}This treats all ones as a distinct, fatal result, gives every wait a deadline, and sleeps instead of spinning. The helpers readl_poll_timeout() and its relatives implement the timeout part, and you add the all-ones test in the condition.
The same discipline applies to values read from the device and used as sizes or indexes. A length register that reads 0xffffffff and then drives a memcpy() is a memory corruption. Validate device-provided values before using them, and treat an implausible value as a reason to check whether the device is still there.
Writing remove for a dead device
By the time remove runs, the registers do not work. The function has three jobs: stop everything that could touch the device, release what the driver holds, and avoid waiting on hardware.
static void sample_remove(struct pci_dev *pdev)
{
struct sample *s = pci_get_drvdata(pdev);
sample_set_dead(s); /* flag checked by all I/O paths */
sample_stop_io(s); /* no new work, flush queues */
cancel_work_sync(&s->reset_work);
free_irq(pci_irq_vector(pdev, 0), s);
pci_free_irq_vectors(pdev);
if (!pci_device_is_present(pdev))
sample_abort_pending(s); /* complete requests with -ENODEV */
else
sample_quiesce_hw(s); /* orderly path: talk to the device */
pci_iounmap(pdev, s->regs);
pci_release_regions(pdev);
pci_disable_device(pdev);
}The branch on pci_device_is_present() is the key. If the device is there, remove can do the orderly shutdown, such as telling the hardware to stop DMA. If it is not, the only correct action is to complete every request that was in flight with an error and release resources, because nothing will ever complete them otherwise. Skipping that step leaves callers sleeping on a request that the hardware can no longer finish, and they block forever.
Several rules follow from this. Do not call pci_disable_device() expecting it to reach the hardware, since it only updates software state when the device is gone. Do not hold a lock in remove that an I/O path also needs while that I/O path is waiting on the hardware. And keep the order that the USB post argues for: mark the device dead under a lock first, so a racing new request is refused, then stop and flush what is running.
Memory the device was using for DMA must outlive its last access, but with the device gone there is no access, so freeing it in remove is safe, unlike on a live device where you must first stop the DMA. Even so, free it after the completions have been run. A completion handler that dereferences the freed ring is a use after free.
Unbinding without removal
Not every removal is a hotplug. The unbind file in sysfs calls the same remove on a present device. A driver that is correct for surprise removal is correct for this too, and the two are worth testing together: unbind while I/O runs exercises the orderly path, and the same write to the slot's power file exercises hot removal on slot hardware. On a virtual machine, the hypervisor's device-removal command is the surprise case, and it makes a good test where no hot-plug slot exists.


