A driver feeds an accelerator by writing commands to a ring and ringing a doorbell. Ring it once per batch and the ring runs 5 times faster. Train the link at x4 and it slows.
Press 1, then 16 under “Commands per doorbell”. Watch the ring fill. Then narrow the link to x4. Then we build every piece: the link, the registers, the interrupts, the DMA maps, the IOMMU, the ring itself and how to measure it.
You need a little C and the idea that a bus is a set of wires two chips use to talk. We build the rest from zero. The model on this page is a model, not a measurement of real silicon.
Built from primary sources: the Linux kernel documentation (MSI HOWTO, DMA API HOWTO, VFIO, memory barriers), the PCI Express line-rate table, and a measured context-switch benchmark. The Field Guide lists every source. It follows Writing the Driver.
A model, not silicon. Link rates are the PCI Express table: Gen4 is 1.969 GB/s per lane per direction, Gen3 is 0.985. Payload efficiency 92.7% assumes 256-byte payloads and 20 bytes of packet overhead. Illustrative costs: 20 ns to write a descriptor, 150 ns to issue one doorbell write, 1 µs for a command to cross the device. Each command moves 512 bytes of payload plus a 64-byte descriptor. The ring is drawn with 32 slots and slowed so 4 million commands a second look like 1 a second.
Chapter 0
Learn why a card can sit in a fast slot and still run at a quarter of its speed, and how one command shows it
You bolt a new inference card into a server. The datasheet promises 28 GB/s of host transfers. Your benchmark prints 7. Nothing crashes. No log line complains. The driver loads, the model runs, and every number is simply too small.
The cause is almost never the driver. The cause is the road between the CPU and the card. That road is PCI Express (PCIe): the wires and the rules two chips use to move data. This chapter teaches you to read that road in one command, because every later chapter assumes the road is wide enough.
A lane is one pair of wires for each direction, like one lane of a two-way street. A link bundles 1, 2, 4, 8 or 16 lanes between two chips. Written x4 or x16, the number is the lane count. More lanes carry more cars at once.
Each lane runs at a fixed speed for its generation. Gen3 sends 8 billion bits a second on each wire. Gen4 sends 16 billion. Gen5 sends 32 billion. Those raw rates are in GT/s, giga-transfers per second. Not every transfer is your data: the line adds a little framing.
Gen3 and later use the 128b/130b line code. Every 130 bits on the wire carry 128 bits of real data and 2 bits of framing. The framing costs 2/130, about 1.5%. Now the arithmetic, step by step, for one Gen4 lane in one direction.
16 × 128/130 = 15.754 Gbit/s ÷ 8 = 1.969 GB/s per lane → × 16 = 31.5 GB/s → × 4 = 7.9 GB/s
These figures match the PCI Express table on Wikipedia: 1.969 GB/s per Gen4 lane and 31.508 GB/s for x16, per direction. Packet headers cost a further few percent, which Chapter 5 puts to work. So the 28 GB/s on the datasheet is a fair promise for Gen4 x16. The 7 GB/s you measured is exactly what Gen4 x4 delivers. The link is the suspect.
Nobody types the width into a setting. At power-up, each end of the link runs a small state machine called the LTSSM, the link training and status state machine. The two ends send test patterns, find which lanes work, and agree on the highest speed and the widest width that both ends and all the wires support. The result is the trained link.
That rule has a hard edge. If one lane is dirty, bent or badly routed, the ends do not fail. They fall back to a narrower width that still works, or to a lower speed. The link comes up, the OS boots, and the card works at a fraction of its speed. That is why the failure is silent.
Try it. The card below can do Gen4 x16. Choose how the slot is wired, pick the slot generation, then add dirty lanes and watch the trained link shrink.
The card can do Gen4 x16. Pick the slot wiring and generation, then drag dirty lanes. The terminal shows what lspci would print.
Model: trained width is the largest of 16, 8, 4, 2 or 1 that fits in the lanes that work; trained speed is the lower of the card and slot generations. Real training is subtler (lane reversal, per-lane equalisation), but the outcome rule is this one. Rates are the PCI Express table: 0.985 GB/s per Gen3 lane, 1.969 per Gen4 lane.
Three traps catch newcomers. The first is units. A datasheet may say “16 GT/s” or “16 Gb/s” or “31.5 GB/s”. A capital B means bytes and a small b means bits, so the last one is eight times bigger. The second is direction. Some data sheets add the two directions together, so a Gen4 x16 link is quoted at about 63 GB/s “total”. A single transfer from host to card can use only half of that. The third is generation against width. They trade off evenly: a Gen3 x8 link gives 8 × 0.985 = 7.88 GB/s, which matches a Gen4 x4 link at 4 × 1.969 = 7.88 GB/s.
That last equality has a use. If your Gen4 card trained at Gen3 speed, it has lost half its rate. Software cannot win that back, but a slot with twice the lanes can. Ask both questions every time: what speed, and what width?
One more fact belongs here. The link rate is a ceiling for the best case. Packet headers and acknowledgements take a further share, which Chapter 5 prices in. So when your measured number lands at 90 to 93% of the table value, the link is healthy. When it lands at 25% or 50%, look at the training first.
Symptom: a DMA benchmark reaches half, or a quarter, of the card's rated host bandwidth. The driver reports no errors. Measurement: compare two lines of lspci -vv for the card. LnkCap is what the link could do. LnkSta is what it trained to. When they differ, lspci adds the word (downgraded). Check both ends: the card, and the root port above it.
Fix: reseat the card, then try another slot. Read the board manual: a slot that is x16 in shape is often x8 or x4 in wiring. Clean the gold fingers. If the link still trains narrow, suspect signal integrity: a bad riser, a long trace or a worn connector. One more point: a downgrade report is not always a fault. A card may drop its link speed on purpose to save power when idle, so measure under load.
sudo lspci -vv -s <bus:dev.fn> and find LnkCap and LnkSta. On a Raspberry Pi 5 or a Jetson board with an M.2 slot, repeat it and write down the trained speed and width. Then change the slot or the cable and measure again.Chapter 1
Follow the boot-time census that finds your card, then map its registers so a C pointer can reach them
The machine powers on. Your accelerator has no name, no address and no driver yet. The CPU cannot read a register it has no address for. Before any of your code runs, the system must find the card, ask what it is, and give it a slice of the address map.
That job is called enumeration: a census of everything on the bus. The firmware, and later the kernel, walks every bus number, device number and function number. It asks each spot one question: is anyone there?
Every PCIe function (one logical device on the bus) carries a small block of read-only identity and setup registers. It is called configuration space. The standard header takes 256 bytes. PCI Express extends it to 4,096 bytes, where optional features such as error reporting live.
The first fields are the vendor ID and device ID. The kernel matches them against the table in your driver. When they match, the kernel calls your probe function. If nobody answers at an address, the read returns all ones. A vendor ID of 0xFFFF means “empty slot” and nothing else. Remember that value. It comes back in the failure section.
The card has registers and maybe on-board memory. The CPU reaches them by ordinary loads and stores to certain physical addresses. This is memory-mapped I/O, MMIO. But who picks the addresses? The card does not. It asks, through a base address register, a BAR in config space.
The ask works by a clever trick. Firmware writes all ones to the BAR and reads it back. The card hard-wires the low bits to zero, in proportion to the size it needs. The bits that stick as ones show the size. Sizes are always powers of two. The low 4 bits of a memory BAR are flags: memory or I/O, 32 or 64 bit, prefetchable or not.
readback 0xFFF00000 → clear low bits: 0xFFF00000 → invert: 0x000FFFFF → add 1: 0x100000 = 1 MiB
Firmware then writes a real address back into the BAR, chosen so every BAR in the machine fits without overlap and each is aligned to its own size. That is why the card’s registers now sit at an address like 0xF7000000. The kernel reads this assignment in pci_resource_start(). Try the whole dance below.
Pick the card’s BAR size. Press the steps in order: write all ones, assign an address, map it, read the ID register. Then pull the card out and read again.
Illustrative device: the ID register at offset 0x0 holds 0xACC10001, a made-up value. Addresses are examples. The readback rule is the standard PCI BAR sizing method.
Your driver runs in virtual memory. It cannot use the physical BAR address directly. pci_iomap() (or pcim_iomap(), which frees itself on unload) builds a virtual window over the BAR with caching turned off. You get a pointer. Then readl() and writel() read and write 32-bit registers through it. Use these helpers, not plain pointer dereferences. They make the compiler and the CPU keep the access in order and at the right width.
/* the first lines of every PCIe driver (Linux) */ static int acc_probe(struct pci_dev *pdev, const struct pci_device_id *id) { void __iomem *regs; int rc = pcim_enable_device(pdev); /* wake it, turn on memory decode */ if (rc) return rc; pci_set_master(pdev); /* allow the card to DMA */ regs = pcim_iomap(pdev, 0, 0); /* BAR0, whole length */ if (!regs) return -ENOMEM; if (readl(regs + REG_ID) == 0xFFFFFFFF) return -ENODEV; /* nobody home */ /* ... later: writel(val, regs + REG_DOORBELL); */ return 0; }
Look at the all-ones check. On many systems, a read to a card that has fallen off the bus ends with all ones. Some platforms raise an error instead. So a register that reads 0xFFFFFFFF is a strong hint, not a value.
Every function has a three-part address: bus, device, function. Linux writes it as 01:00.0. That is the number you pass to lspci -s. In the header, after the BARs, sits a pointer to a capability list. It is a chain of small blocks, each with an ID and a pointer to the next. One block describes MSI, one MSI-X, one the PCI Express link itself (the place LnkCap and LnkSta live), one power management. Chapters 0, 2 and 7 all read blocks from this one list.
Two bits in the command register matter before any I/O works. Memory space enable makes the card answer to its BARs. Bus master enable lets the card start its own transfers, which is what DMA is. The calls pcim_enable_device() and pci_set_master() set these two for you. Forget the second and your DMA engine stays silent, and no interrupt ever arrives.
A note on 64-bit BARs. A big card may need more than 4 GiB of space, for example to expose its on-board memory. Such a BAR uses two consecutive BAR slots. The first holds the low 32 bits, the second the high 32 bits. Sizing works the same way on the pair.
Finally, why readl() and not *ptr? Three reasons. The compiler must not cache or reorder a register access. The access must be exactly 32 bits wide. And registers are little-endian on the wire, so the helper converts on big-endian machines. Also note the cost: a read over PCIe must wait for the answer to come back, a full round trip, while a write is posted and does not wait. So avoid readl() in a hot loop. Read the host-memory copy of the status instead, as Chapter 6 does.
Symptom: the driver loaded fine yesterday. Now every readl() returns 0xFFFFFFFF and the status bits all look “set”. Measurement: read the vendor ID from config space with lspci -s <bus:dev.fn>. If the device is gone from the list, or lspci shows rev ff, the card left the bus. Fix: find out why. The usual causes are a card that lost power, a thermal shutdown, a link that went down under load, or a firmware crash. Add the all-ones check to your error paths so the driver stops cleanly instead of acting on garbage.
lspci -vv -s <bus:dev.fn> and find the Region 0: Memory at ... line: that is the BAR with its size in brackets. Then cat /sys/bus/pci/devices/<bus:dev.fn>/resource lists every BAR’s start, end and flags.Chapter 2
Give each command queue its own interrupt, and send that interrupt to the core that waits for the answer
Your accelerator finishes a batch of work. It must tell the CPU. The CPU is busy running other code and will not look at the card by itself. The card needs a way to tap the CPU on the shoulder. That tap is an interrupt: a signal that makes a core pause its work and run a handler.
On old PCI, a card pulled one shared wire. Many cards shared that wire, so the handler had to ask every card “was it you?”. PCI Express has no such wires. A PCIe card sends its interrupt as a message: a small memory write to an address the OS chose. No wire is shared, so no one is asked.
A vector is one interrupt number with its own handler. MSI, message-signalled interrupts, lets a card claim a block of vectors, up to 32, and the block must be a power of two. MSI-X raises the cap: a card can have any number from 1 up to 2,048. Each MSI-X vector has its own address and data word in a table, so each can point at a different CPU. The kernel documentation states both limits.
If the card has neither, the kernel falls back to one legacy interrupt line. One vector means one handler and one core for every queue the card owns. That is the slow road. A modern accelerator with several command queues wants MSI-X with one vector per queue.
Picture queue 2. A thread pinned on core 2 submits commands and waits for answers. The card finishes a command and sends vector 2. If vector 2 lands on core 2, the handler wakes the thread right there. The queue’s data is already warm in that core’s cache.
If vector 2 lands on core 0 instead, core 0 runs the handler, then must send a cross-core wake-up to core 2. That costs time, and the data goes cold in the wrong cache. Do this a hundred thousand times a second and you feel it. Now work the cost for one case. Suppose each interrupt costs about 2 µs of CPU time, an illustrative figure.
4 queues × 100,000 interrupts/s = 400,000/s → × 2 µs = 0.8 s of CPU per second = 80% of one core
Put all four vectors on one core and that core spends 80% of its time in interrupt handlers. Spread them, and each of four cores spends 100,000 × 2 µs = 20%. Same work, but now it fits. Try it. The device lets you choose where the vectors go.
Each queue’s consumer thread is pinned on the CPU with the same number. Choose where the interrupts land. Red lines are cross-core wake-ups.
Illustrative: 2 µs of CPU per interrupt and four queues with equal load. The cross-core cost is shown as a count, not a time, because it varies with the chip. The MSI and MSI-X vector limits (32 and 2,048) are from the Linux kernel MSI HOWTO.
One call asks for vectors. pci_alloc_irq_vectors() takes a minimum, a maximum and the types you accept. The kernel tries MSI-X first, then MSI, then the legacy line. Add the PCI_IRQ_AFFINITY flag and the kernel spreads the vectors across CPUs for you. Then pci_irq_vector() turns vector index i into the Linux IRQ number you pass to the request call.
/* one MSI-X vector per queue, spread over CPUs by the kernel */ nvec = pci_alloc_irq_vectors(pdev, 1, NQ, PCI_IRQ_MSIX | PCI_IRQ_MSI | PCI_IRQ_INTX | PCI_IRQ_AFFINITY); if (nvec < 0) return nvec; for (i = 0; i < nvec; i++) { int irq = pci_irq_vector(pdev, i); rc = request_threaded_irq(irq, acc_hardirq, acc_thread, 0, "acc-q%d", &q[i]); }
Notice request_threaded_irq(). The hard handler runs with interrupts masked and should do almost nothing: read one status register, then return IRQ_WAKE_THREAD. The threaded handler does the real work in a kernel thread, which the scheduler can preempt. This keeps a busy accelerator from freezing the rest of a robot’s real-time tasks. Real-Time Linux shows why.
The file /proc/interrupts is the best instrument you have. Each row is one vector. Each column is one CPU, and the number is how many interrupts that CPU has handled since boot. The device name sits at the end of the row. A healthy four-queue card shows four rows, acc-q0 to acc-q3, each with counts growing on a different column.
Read two snapshots one second apart and subtract. If row acc-q2 grew by 100,000 in column CPU2, the vector is aimed correctly, and the rate matches the 100,000 per second of our example. If it grew in column CPU0, the affinity is wrong. If it did not grow at all while commands finish, the message never arrived.
An MSI-X vector is a table entry in one of the card’s BARs. It holds a target address, a data word and a mask bit. To raise vector 2, the card does an ordinary memory write of the data word to the address. The chipset recognises the address as an interrupt and delivers it to the chosen core. The kernel fills in each entry for you. You never write the table by hand, but you can mask a vector in the card, which is what hybrid polling does in Chapter 6.
The split between the two handlers has a reason. A hard handler runs with its own vector masked and sometimes with others masked too. While it runs, the core cannot take a more urgent interrupt on that line. Keep it to a few register accesses. Defer everything else to the thread, where the scheduler can interleave it with your other tasks.
Symptom: you submit work and the driver waits forever, or spins on a status flag. Measurement: run cat /proc/interrupts and find your lines. The per-CPU counters are your instrument. If your vector’s counters stay at zero while the card says it finished, no message arrived. Check lspci -vv under the capability list: MSI-X: Enable+ means the OS turned it on. Fix: look for a failed pci_alloc_irq_vectors() that dropped to the legacy line, a masked vector in the MSI-X table, or a card that never wrote the message because bus mastering was off (pci_set_master).
watch -n1 'grep nvme /proc/interrupts' while you run fio on the drive. Each queue is one row; each column is one CPU. Then write a different mask to /proc/irq/<n>/smp_affinity_list and watch the counts move.Chapter 3
Pick the right Linux call for each buffer the card touches, and see what stale data looks like when you pick wrong
A camera frame is 2 MB. Your CPU could copy it to the card one 4-byte register write at a time. That would take half a million writes, and the CPU would do nothing else. Instead the card reads the frame straight out of host RAM, by itself. This is DMA, direct memory access: a device moving data to or from memory without the CPU copying each word.
For that to work, the card needs an address it can put on the link, and the data at that address must be the data you meant. The first part is a bus address, the address the device uses. It may equal the CPU’s physical address, or it may not, as Chapter 4 shows. The second part is about caches, and that is where drivers go wrong.
Your CPU keeps recent data in a fast cache. When you write a value, it may sit in the cache for a while before it reaches RAM. The card reads RAM. So the card may read the old value. The reverse also happens: the card writes new data into RAM, but your CPU still holds the old data in its cache and reads that. On x86 the hardware keeps the cache and DMA in step. On many Arm SoCs it does not, so the kernel must clean or invalidate the cache for you at the right moment. The DMA API exists to do the right thing on every platform.
The kernel offers two. A coherent mapping is memory that both sides see at the same moment, with no extra steps. dma_alloc_coherent() allocates it and returns two things: a virtual address for your code and a bus address for the card. Use it for things that live for the whole run and are touched by both sides all the time: command rings, completion rings, small status blocks.
A streaming mapping wraps an ordinary buffer you already have. You call dma_map_single() with a direction: DMA_TO_DEVICE (host memory to the card), DMA_FROM_DEVICE (card to host memory) or DMA_BIDIRECTIONAL. The direction tells the kernel which cache work to do: flush your writes before the card reads, or invalidate stale lines before you read what the card wrote. Use streaming maps for payloads: tensors, frames, packets. The kernel documentation says to check the result with dma_mapping_error(), because mapping can fail.
One rule for streaming buffers: between map and unmap, the buffer belongs to the card. If your CPU must touch it in between, call dma_sync_single_for_cpu() before and dma_sync_single_for_device() after. Try each buffer type below. Then switch on the mistake.
Choose a buffer. The panel names the right call. Then switch on Wrong direction and see what the reader gets.
The API names and the direction semantics are from the Linux DMA API how-to. The eight cells are a model of one cache line; the stale values are illustrative. On cache-coherent x86 a wrong direction often hides, which is why the bug appears only when you move the driver to an Arm board.
A 2 MB frame in user memory is rarely one block of physical RAM. It is hundreds of 4 KB pages scattered around. A scatter-gather list (struct scatterlist) names each piece. dma_map_sg() maps them all and returns how many entries it ended up with. With an IOMMU that number can be smaller than you passed in, because the IOMMU can glue neighbouring pieces into one device-visible range. Walk the list using the count it returns. Hand the original count to the unmap call.
Last, address masks. A card may have fewer address wires than the CPU. Call dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) first, and fall back to 32 if it fails. The documentation is firm: do not use DMA on a device until the mask call has returned success. When a buffer sits above what the card can address, the kernel copies the data through a low bounce buffer. It works, and it quietly costs a copy on every transfer.
/* a payload the card reads, then a result the card writes */ if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))) if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))) return -EIO; ring = dma_alloc_coherent(&pdev->dev, RING_BYTES, &ring_bus, GFP_KERNEL); in_bus = dma_map_single(&pdev->dev, in_buf, LEN, DMA_TO_DEVICE); if (dma_mapping_error(&pdev->dev, in_bus)) return -ENOMEM; /* ... put in_bus in a descriptor, ring the doorbell, wait ... */ dma_unmap_single(&pdev->dev, in_bus, LEN, DMA_TO_DEVICE); out_bus = dma_map_single(&pdev->dev, out_buf, LEN, DMA_FROM_DEVICE); /* ... card writes ... */ dma_sync_single_for_cpu(&pdev->dev, out_bus, LEN, DMA_FROM_DEVICE); /* now the CPU may read out_buf */
Take a 2 MiB frame in ordinary user memory. A page is 4 KiB, so the frame spans 2 MiB ÷ 4 KiB = 512 pages. The pages may sit anywhere in RAM. Without an IOMMU, dma_map_sg() returns up to 512 entries, and your descriptor format must carry 512 address and length pairs, or you must chain several descriptors. With an IOMMU, the mapper can assign one contiguous range of device addresses to all 512 pages and may return a single entry. A card with a single address and length per descriptor then works for this frame, which would be impossible without the IOMMU.
Compare the alternatives. Copying the frame into one contiguous buffer first costs time. At an illustrative 10 GB/s copy speed, 2 MiB takes about 210 µs, on every frame, plus the memory bandwidth. Mapping the pages in place costs no copy. At 30 frames per second the copy alone would use 30 × 210 µs = 6.3 ms of every second of one core. That is small, but the same pattern at 4K video rates or on a small SoC is not.
Bounce buffers hide the same cost. If the card can address only 32 bits and your buffer sits above 4 GiB, the kernel copies through a low buffer silently. Throughput falls and the profile shows memory copies in the DMA layer. Check the mask you asked for and the mask you got.
Symptom: results are correct on your x86 desktop and wrong on the target board, or wrong one run in a hundred. Values look like the previous frame. Measurement: build a debug kernel with CONFIG_DMA_API_DEBUG. It tracks every map and unmap and warns about a wrong direction, a missing unmap or a sync on an unmapped buffer. Fix: match each direction to who writes, sync before the CPU touches a mapped buffer, and unmap when done. Writing the Driver shows the same API in a smaller driver. The memory-system side of this, caches and page tables, is the planned lesson on virtual memory and DMA; this chapter gives the driver-side rules.
CONFIG_DMA_API_DEBUG=y on a Raspberry Pi 5 or another Linux board you own, load a driver that uses DMA, and read dmesg for DMA-API: warnings. Then, on purpose, change one direction and see the warning appear.Chapter 4
Put a fence around the card so a buggy DMA cannot reach other memory, then share one card between several users
Here is a frightening fact. A DMA engine writes to whatever address it is told. If a descriptor holds a wrong address, or the firmware on the card has a bug, the card can overwrite the kernel’s own memory. Nothing in Chapter 3 stops it. The CPU has a memory manager to stop a bad program. The card needs one too.
An IOMMU (input-output memory management unit) sits between the devices and RAM. On Intel it is called VT-d, and on Arm it is the SMMU. It does for a device what the CPU’s MMU does for a program. The device uses an I/O virtual address (IOVA). The IOMMU looks it up in a page table and gives the real physical address, or refuses.
The table is a tree, like the CPU’s. Count the bits: a 4 KB page needs a 12-bit offset. Each level of the tree uses 9 bits to pick one of 512 entries. Four levels give 4 × 9 + 12 = 48 bits of address. Five levels give 5 × 9 + 12 = 57 bits. Linux’s Intel IOMMU code supports 4 or 5 levels. The entry format is close to the CPU’s but not identical, so do not assume the two tables are the same objects.
4 levels × 9 bits + 12-bit page offset = 48 bits → 512 entries per level → a miss may need up to 4 table reads
A translation that is not in the cache costs table reads. The IOMMU keeps recent answers in an IOTLB, a small translation cache. Big, steady transfers hit the cache. Many small transfers to scattered pages miss it more. That is the price of the fence, and it is usually small next to the safety.
When a mapping is missing, the device’s access faults. The IOMMU blocks it and raises an interrupt. The kernel logs the address and the reason. This also gives Chapter 3’s scatter-gather a bonus: the IOMMU can present scattered pages as one contiguous IOVA range.
With a fence in place, you can safely give a card to a user program, or to a virtual machine. VFIO does that. Its documentation describes it as exposing direct device access to user space in a secure, IOMMU-protected environment. The unit is a group: devices the IOMMU cannot tell apart. A container, opened from /dev/vfio/vfio, holds one or more groups and their shared IOMMU mappings.
The program then asks for a mapping itself. The documentation’s example maps 1 MB of its own memory at I/O address 0, so the device sees it at 0x0:
/* user space, after opening the container and adding the group */ struct vfio_iommu_type1_dma_map dma_map = { .argsz = sizeof(dma_map) }; dma_map.vaddr = (uintptr_t)mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); dma_map.size = 1024 * 1024; dma_map.iova = 0; /* 1MB starting at 0x0 from device view */ dma_map.flags = VFIO_DMA_MAP_FLAG_READ | VFIO_DMA_MAP_FLAG_WRITE; ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map);
Frameworks that move packets or storage blocks without the kernel in the way use exactly this path. So do virtual machines that own a whole accelerator.
Sometimes you want to share one accelerator between four containers or VMs. SR-IOV (single-root I/O virtualisation) lets one card present itself as several. The real device is the physical function (PF). It is in charge: it creates and limits the others. Each virtual function (VF) looks like its own small PCIe device, with its own config space and registers. The kernel treats it like a hot-plugged device. You switch them on by writing a number to sriov_numvfs in sysfs, and a PF driver calls pci_enable_sriov(dev, nr_virtfn) to create them.
Each VF can go to a different VM through VFIO, and the IOMMU keeps their DMA apart. Try it. Slide the number of VFs, then let a VF reach into another VM’s memory with and without the IOMMU.
Each VM owns one VF and one slice of RAM. Press Rogue DMA: VF 0 tries to write into VM 1’s slice. Toggle the IOMMU and press again.
A model. The equal bandwidth split assumes every VF is busy and a Gen4 x16 link of 31.5 GB/s; real cards enforce shares in firmware and may allow bursts. The fault line imitates the shape of an Intel DMAR message and is illustrative. The tree arithmetic (4 × 9 + 12 = 48) is exact.
Follow the device address 0x00007F123456789A. Split it. The low 12 bits, 0x89A, are the offset inside the page. The next four groups of 9 bits are the table indices: 254 at the top level, then 72, then 418, then 359. The IOMMU reads entry 254 of the top table to find the next table, entry 72 there, entry 418 in the next, and entry 359 in the last. That last entry holds the physical page address and the permission bits: may the device read, may it write. The physical address is that page plus 0x89A. Four reads in the worst case, none at all if the IOTLB already knows this page.
Permissions make the fence precise. A buffer mapped for DMA_TO_DEVICE can be read by the card but not written. A card that tries to write it gets a fault, not a silent overwrite. That is how the “PTE Write access is not set” message in the Linux kernel’s own example comes about.
Some systems run the IOMMU in a pass-through mode, with iommu=pt on the kernel command line, using a one-to-one mapping so that trusted devices skip translation. That removes the fence. Use it only when you have measured that translation costs too much and you trust the device and its firmware.
Symptom: the job dies, the card reports a DMA error and dmesg prints a fault line from DMAR (Intel) or the SMMU (Arm), with the device address and a reason such as “write access is not set”. Measurement: match the faulting address against the IOVAs your driver mapped. A fault at an address just past a buffer means the card ran off the end. A fault at an address you freed means you unmapped too early. Fix: map before you ring the doorbell, unmap only after the completion, and never reuse a bus address while a command that holds it is in flight. Keep the IOMMU on in production: it turns a silent memory corruption into a loud log line.
echo 2 | sudo tee /sys/class/net/<if>/device/sriov_numvfs and then lspci | grep -i virtual. Two new functions appear. Read /sys/kernel/iommu_groups/ to see which devices share a group.Chapter 5
Take apart the hero: how a driver hands work to a card through shared memory, and why ringing the bell less often is faster
Picture a sushi restaurant with a conveyor belt. The chef puts plates on the belt. The guests take them off. Nobody hands a plate to anyone. The belt is a loop, so it never runs out, and the chef and the guests work at their own speed. Only two things need agreeing: where the chef last put a plate, and where the guests last took one.
A ring buffer is that belt, made of memory. It is an array of fixed-size slots used in a circle. After the last slot comes the first again. Here each slot holds one command descriptor: a small record that says what the card should do, for example “move this input buffer to that output buffer, 4,096 bytes, then tell me.”
Only two numbers are shared. The producer index says how many commands the host has written. The consumer index says how many the card has finished. Each number has exactly one writer, so no locks are needed. The ring is full when producer minus consumer equals the depth. It is empty when they are equal. With a depth that is a power of two, the slot for a count is just count & (depth - 1).
Where do the numbers live? The host keeps the ring in host memory, mapped coherent as Chapter 3 taught. The card reads descriptors by DMA. The card writes its consumer index back into host memory by DMA, so the host can read it cheaply. But the card cannot watch host memory for changes. It needs to be told. So the producer index goes the other way, into a doorbell: one register in the card’s BAR.
Writing a register through the BAR (Chapter 1) is an MMIO store. On the link it becomes a small packet, a TLP (transaction layer packet), with a header of 12 to 16 bytes plus framing; one application note counts 20 bytes of overhead per packet, for 4 bytes of data. It is a posted write: the CPU sends it and does not wait for a reply. That sounds free. It is not. The store goes to uncached space, so the CPU cannot merge it with others or reorder it freely, and the packet takes up room on the link.
The hero uses an illustrative cost: 20 ns to write a descriptor into the ring and 150 ns to issue one doorbell. If you ring after every command, each command costs both. If you ring once per b commands, the doorbell cost is shared.
b = 1: 1 ÷ (20 + 150) ns = 5.9 M/s → b = 16: 1 ÷ (20 + 9.4) ns = 34.0 M/s → 5.8 times faster
In the hero the ring itself holds 32 commands, which limits the card to 32 M/s, so you see about 5.4 times. The price of batching is waiting: the first command of a batch sits unrung until the last is written. At b = 16 the average wait is 7.5 gaps of 29.4 ns, about 0.22 µs. Pick b from your latency budget, not from your taste.
Now the dangerous part. The host writes the descriptor fields. Then it sets a flag that says “this slot is yours.” Modern CPUs and the link may make those two writes visible to the card in a different order. If the card sees the flag first, it fetches a half-written command. The cure is dma_wmb(), a barrier that forces the descriptor data to be visible before what follows. The kernel’s memory-barrier documentation shows exactly this pattern: write the data, dma_wmb(), set the ownership status, then writel() to the doorbell. It also warns that the dma_* barriers do not order MMIO accesses.
struct acc_desc { /* 64 bytes: one slot */ __le64 src_bus, dst_bus; /* bus addresses from dma_map_*() */ __le32 len; __le16 op; __le16 flags; /* flags carries OWN_DEVICE */ __le64 cookie; /* echoed back in the completion */ u8 rsvd[32]; }; static int acc_submit(struct acc_q *q, const struct acc_cmd *c, bool ring) { if (q->prod - READ_ONCE(*q->cons_shadow) == q->depth) return -EBUSY; struct acc_desc *d = &q->ring[q->prod & (q->depth - 1)]; d->src_bus = cpu_to_le64(c->src); d->dst_bus = cpu_to_le64(c->dst); d->len = cpu_to_le32(c->len); d->cookie = c->cookie; dma_wmb(); /* fields first ... */ d->flags = cpu_to_le16(OWN_DEVICE | c->op); /* ... then ownership */ q->prod++; if (ring) writel(q->prod & 0xFFFF, q->db); /* the doorbell */ return 0; }
Step through it. Submit some commands, ring the bell, let the card fetch. Then take the barrier out and watch for a torn command.
Submit writes a command into the next slot. Ring publishes the producer index. Fetch lets the card take the oldest rung command. With the barrier off, a fetch right after a submit can see the flag but not the data.
A model of visibility order, not of a real CPU. Without the barrier, a submitted command’s ownership flag becomes visible first and its data two steps later. Any fetch inside that window is torn. Real hardware tears rarely, which is why the bug survives testing.
Let the depth be 4. Start with producer 0 and consumer 0. The host submits commands A, B and C: producer is 3, and they sit in slots 0, 1 and 2. It rings once, with 3 as the value. The card fetches A and B and writes consumer 2. Now fill is 3 − 2 = 1. The host submits D and E: D goes to slot 3, E wraps to slot 0, because 4 & 3 = 0 and slot 0 is free again. Producer is 5, fill is 5 − 2 = 3, and the ring is not full. One more command would make fill 4, equal to the depth, and the host must wait.
Count the cost. Five commands, two doorbells: one for A, B and C, one for D and E. Without batching it would be five. With batching, the host paid 2 × 150 ns = 300 ns instead of 750 ns for the bells, which saves 450 ns for five commands, 90 ns each. That is the same effect as the hero, in numbers you can check by hand.
Symptom: one command in a million does the wrong thing: a wrong length, a wrong address, an IOMMU fault from Chapter 4 with an address nobody mapped. It never repeats on the same input. Measurement: add a per-command checksum or the cookie echo to the completion and count mismatches; run a stress test with many threads and a tiny ring. Fix: put dma_wmb() between the fields and the ownership flag, and the doorbell write after both. The lesson on rings, queues and drops, planned for the real-time track, covers the same producer and consumer rules for software queues.
fio --ioengine=io_uring --iodepth=1 and then --iodepth=32 against the same drive, and write down the commands per second for each. The depth is your ring depth.Chapter 6
Choose how the host learns that a command is done, and find the rate where the cheap choice becomes the costly one
You posted a pizza order and now you wait. You can sit by the door and stare at the street. Or you can go back to work and let the doorbell tell you. Staring is quick when the pizza arrives, but you do nothing else. The doorbell frees your hands, but you pay a little each time you get up. A driver faces this exact choice for every finished command.
The card writes a completion entry into a second ring in host memory: the cookie of the finished command, a status, and a phase bit that flips each time the ring wraps, so the host can tell a fresh entry from an old one without reading any card register. Reading host memory is cheap. Reading a card register is a full round trip over the link.
The host can learn that a new entry exists in two ways. In polling, a thread loops and checks the phase bit. In interrupt mode, the card sends the MSI-X message from Chapter 2, the CPU runs the handler, and the handler wakes the waiting thread.
Polling has a nearly fixed cost: it burns one core all the time, busy or idle. Its delay is tiny, about half the gap between two checks.
An interrupt has a cost per completion. The hardware enters the handler. The handler wakes a thread. The scheduler switches to that thread. That last step is measurable. Eli Bendersky timed two threads passing a message back and forth on a Haswell Intel i7-4771. Pinned to one core, a thread context switch took between 1.2 and 1.5 µs. Unpinned, about 2.2 µs. The author notes the pinned figure is a lower bound, since it leaves out the cache effects that follow.
Take the lower figure and add 2 µs for interrupt delivery and the handler, an illustrative number. Each completion then costs about 3.5 µs of CPU time and adds about 3.5 µs of delay. Now the key calculation: at what rate does one core spent on interrupts equal one core spent polling?
1 core = 1,000,000 µs per second ÷ 3.5 µs per completion = 285,714 completions per second
Below about 286,000 completions a second, interrupts use less CPU. Above it, polling is cheaper, because the interrupt path would need more than a whole core. The unpinned figure of 2.2 µs moves the crossover down to 1,000,000 ÷ 4.2 = 238,095 per second. Your robot rarely knows its load in advance, so there is a third way.
A hybrid scheme takes the interrupt, then masks it and polls until the ring is empty, then unmasks and goes back to sleep. Linux networking calls this NAPI. Light load behaves like interrupts and costs little CPU. Heavy load behaves like polling and costs almost no per-completion overhead. Drag the rate and compare.
Drag the completion rate. The lines show CPU use of each mode, in percent of one core. The vertical marker is your rate.
Context-switch times are measured: 1.2 to 1.5 µs pinned (1.5 used here) and about 2.2 µs unpinned, on an Intel i7-4771, in Eli Bendersky’s 2018 benchmark. The 2 µs for delivery and the handler, and 0.2 µs of polling delay, are illustrative. Your chip will differ; measure it.
There is a fourth option. The card can hold back its interrupt until several completions are ready, or until a short timer expires. This is interrupt coalescing. Suppose 400,000 completions arrive each second, one every 2.5 µs. Without coalescing, interrupts cost 400,000 × 3.5 µs = 1.4 s of CPU per second, which is 140% of a core: impossible. Coalesce 8 completions per interrupt and you take 50,000 interrupts a second: 50,000 × 3.5 µs = 0.175 s, which is 17.5% of a core. The price is delay. The first completion in a group waits for seven more, up to 7 × 2.5 = 17.5 µs.
So there are two knobs, as with the doorbell: a count and a timer. The count saves CPU under load. The timer bounds the delay when the load is light. For a robot arm that needs an answer within 100 µs, a 17.5 µs delay is fine. For a loop that needs 10 µs, it is not. Always decide from the deadline.
The phase bit from the start of this chapter makes all of this safe. The host never reads a card register to find out how many entries are ready. It reads the next slot of the completion ring and compares one bit. Several completions can arrive for one interrupt, and the handler loops until the bit says the slot is stale.
Symptom: the accelerator is fast, but a motor-control task on the same machine now misses deadlines every few seconds. Measurement: run cyclictest and watch the worst-case latency, and look at top for a thread at 100% on a core that real-time tasks share. A real-time polling thread can also hit Linux’s real-time throttling, which forces it to pause and shows up as jitter. Fix: give the polling thread its own isolated core, or switch to hybrid so it sleeps when the ring is quiet. Real-Time Linux covers isolation in depth, and Robot Real-Time Performance shows the cost of missed deadlines.
taskset -c 0, and time a million round trips. Run it again unpinned. Compare with 1.2 to 1.5 µs and 2.2 µs.Chapter 7
Let an idle accelerator sleep, and wake it before you ring a doorbell that nobody would hear
A delivery robot drives all night. For most of that night its vision accelerator has nothing to do. If the card sits fully awake it burns watts for nothing, and the battery pays. A good driver lets the card sleep between jobs. A bad driver lets it sleep through a job.
PCI defines device power states, named D0 to D3. D0 is fully on. D1 and D2 are intermediate states, and the kernel documentation says support for them is optional, so many devices skip them. D3hot is a deep sleep the software can enter: the device still has power, and its configuration registers still answer. D3cold means the supply voltage is gone. Software cannot program a device into D3cold; the platform cuts the power.
The important rule sits in the middle. In D1 through D3hot, the standard configuration registers must still be reachable. But the device’s memory and I/O spaces are switched off. Your BAR from Chapter 1 stops answering. Config space is how software brings the card back to D0.
Linux calls the scheme runtime PM. When no one has used the device for a set time, the PM core calls your runtime_suspend callback. You quiesce the card: stop its engines, wait for the queues to drain. The PCI core then does the PCI-specific work, saving config registers and arming wake-up. When someone needs the card again, the PCI core restores full power and calls your runtime_resume. You restore your own state: rewrite the ring base addresses, re-enable interrupts and the queues.
The driver’s duty is a reference count. Before any work that touches the card, take a reference with pm_runtime_get_sync(). That call wakes the card if needed, and returns when it is ready. When the work is done, drop it with pm_runtime_put_autosuspend(). The count keeps the card awake for as long as any command is in flight.
Waking is not instant. Deeper sleep saves more power and wakes more slowly. Here is the shape, with a made-up card. D0 idle: 10 W, wake time 0. D3hot: 2 W, wake time 5 ms. D3cold: 0 W, wake time 80 ms. Now a worked trade. A job arrives every 10 minutes. Staying in D0 costs 10 W × 600 s = 6,000 J per gap. Sleeping in D3cold costs 0 J while asleep, plus the wake cost. Suppose waking draws 20 W for 80 ms: 1.6 J. Sleep wins by a factor of nearly 4,000. If a job arrives every 100 ms instead, the card never gets to sleep, and the wake delay would add 80 ms to every job. Pick the timeout from the arrival pattern.
Press Idle to let the card sleep one step deeper. Then press Submit. Turn the PM reference off and submit to a sleeping card.
The state names and the rule that config space stays reachable in D1 to D3hot are from the Linux PCI power documentation. The watts and wake times are for a made-up card: your card’s datasheet has the real ones. D1 and D2 are optional and shown greyed because many devices do not implement them.
static int acc_run(struct acc_dev *a, const struct acc_cmd *c) { int rc = pm_runtime_get_sync(a->dev); /* wake it, wait until ready */ if (rc < 0) { pm_runtime_put_noidle(a->dev); return rc; } rc = acc_submit(&a->q, c, true); /* now the doorbell is heard */ /* ... wait for the completion ... */ pm_runtime_mark_last_busy(a->dev); pm_runtime_put_autosuspend(a->dev); /* sleep after the delay */ return rc; }
Sleeping costs energy to wake. The break-even idle time is the wake energy divided by the power you save. With the made-up card: waking from D3cold draws 20 W for 80 ms, which is 1.6 J. Staying in D0 draws 10 W, and D3cold draws 0 W, so the saving is 10 W. Break-even is 1.6 J ÷ 10 W = 0.16 s. If the card will idle for more than 0.16 s, sleeping saves energy. For D3hot: wake 20 W for 5 ms is 0.1 J, and the saving is 10 W − 2 W = 8 W. Break-even is 0.1 ÷ 8 = 12.5 ms.
Set the autosuspend delay near or above the break-even time, and above the typical gap between bursts of work. A delay of 5 ms on a camera that sends a frame every 33 ms would put the card to sleep and wake it 30 times a second. Each wake adds latency to the frame. A delay of 100 ms would keep it awake through the stream and still sleep soon after the stream ends.
Two more layers hide here. System suspend (closing the laptop lid, or a robot entering standby) is a separate path with its own callbacks. And the link itself has low-power states that the hardware enters when no traffic flows, which add a further small wake delay on the first packet. Measure the first-command latency after idle: it shows all of these together.
Symptom: the first command after a quiet period hangs, or the driver logs a timeout, but only after the system sat idle. Measurement: read /sys/bus/pci/devices/<bus:dev.fn>/power/runtime_status. It says suspended or active. If it says suspended at the moment of the hang, your code rang a doorbell on a card whose memory space was off. The write went nowhere. Fix: hold a PM reference from before the first register write until the last completion. Also check that your runtime_resume restores the ring addresses, since the card may have lost them.
cat /sys/bus/pci/devices/<bus:dev.fn>/power/runtime_status while idle and then while copying a large file. Write down which one prints suspended. On a board with a PCIe NPU, repeat and time the first command after 30 s of idle.Chapter 8
Line up the host’s clock with the card’s, find where a command’s time goes, and fix the small-transfer trap
The ring runs at half the speed you computed. You have three suspects: the host code, the link and the card. Guessing wastes a week. Measuring takes an afternoon, if you can see all three on one clock. This chapter is about seeing.
First, the host trace. Linux can timestamp events in the kernel with ftrace and perf: when the driver wrote the descriptor, when it rang the doorbell, when the interrupt fired, when the waiting thread woke. Put your own trace points around acc_submit() and the completion handler.
Second, the device counters. A good accelerator has hardware performance counters that you read through a BAR register: commands fetched, cycles busy, cycles stalled on memory, bytes moved. Many cards also keep a small trace buffer with its own timestamps. These tell you what the card did, and when, by its own clock.
Third, the PCIe analyser. This is a probe on the link itself. It records every packet, with a timestamp, the type and the address, and it never lies about the link. It is expensive, so use it last, but it ends arguments about who sent what.
The host and the card each keep time with their own oscillator. Their zero points differ. A card timestamp of 17.5 µs and a host timestamp of 17.5 µs are not the same moment. To read the story you must correlate: find the shift that lines the two traces up.
Causality gives a bound. A card cannot fetch a command before the host rang the doorbell. The host cannot see the completion before the card wrote it. In the made-up trace below, the host rings at 1.0 µs and takes its interrupt at 18.5 µs. The card’s own trace shows a fetch at 12.2, the engine busy from 12.4 to 25.0, and a completion write at 25.4. Its clock runs 9 µs ahead of the host’s, but you do not know that yet. Slide the card’s trace left until it fits between the two host marks.
Drag the shift. Purple is the card’s trace by its own clock. When the fetch comes after the doorbell and the completion before the interrupt, the bar turns green.
A made-up trace in microseconds. Causality allows a window of shifts, 4.3 µs wide, not a single value: the doorbell-to-fetch latency is only known to within that window. Real systems narrow it with a shared hardware clock or a timestamp message sent over the link.
The window is the honest answer. A single shift cannot be proven right from two traces alone. If you need exact numbers, give the card and the host one shared time source, or ask the card to write its own counter into a host buffer at a known doorbell. The lesson on custom instruction sets and kernel generation uses the same idea when it compares generated code on a simulator and on silicon.
With aligned traces, split one command into slices: host submit, doorbell to fetch, fetch to start, execute, completion write, interrupt to wake. The biggest slice is your target. One slice shows up again and again in small transfers: the DMA read round trip. A card that reads a descriptor, or a small buffer, must send a request and wait for the data to come back. The wait is the same for 64 bytes as for 4,096.
Model it. A transfer of n bytes costs a fixed latency L plus n divided by the usable link rate B. The effective rate is n / (L + n/B). It reaches half of B when n equals L × B.
L = 1 µs, B = 31.5 GB/s × 92.7% = 29.2 GB/s → half-rate size = 1 µs × 29.2 GB/s = 29.2 KB
So every transfer below about 29 KB runs under half the link’s speed, with these illustrative numbers. The cure is to coalesce: merge several small descriptors into one bigger transfer, so you pay L once. Try it.
Pick a small transfer size, then raise the number of descriptors merged into one transfer.
Model: effective rate = n ÷ (L + n ÷ B), with L = 1 µs of read round trip (illustrative) and B = 29.2 GB/s (Gen4 x16 at 92.7%, from the PCI Express table and a 256-byte-payload overhead figure). The shape is general; measure L on your own card.
Use the aligned trace from the first device. Time zero is the submit. The doorbell lands at 1.0 µs. The card fetches the descriptor 2.2 µs later, at 3.2. The engine starts 0.2 µs after that and runs until 16.0, which is 12.6 µs of work. The completion write lands at 16.4. The host takes its interrupt at 18.5, a further 2.1 µs later. Add the slices: 1.0 + 2.2 + 0.2 + 12.6 + 0.4 + 2.1 = 18.5 µs.
The engine is 12.6 of 18.5, or 68%. Doorbell-to-fetch and completion-to-interrupt together are 4.3 µs, or 23%. If you want this command to finish sooner, the card’s kernel is the place to look first. If you want 1,000 commands a second to share the card, overlap them in the ring so the 4.3 µs of waiting hides behind other commands’ work.
The counters then ask a sharper question: why did the engine take 12.6 µs? A counter of cycles stalled on memory, next to a counter of bytes moved, shows whether the engine waited for data or for arithmetic. This is how a performance engineer separates a memory-bound kernel from a compute-bound one without guessing. It is also how generated kernels are compared between a simulator and real silicon.
Symptom: the link is far from full, the CPU is idle, yet throughput is low. Measurement: the analyser or the device counters show many small reads with long gaps; the aligned trace shows time between fetch and start. Fix: batch and coalesce descriptors, as above, and use the doorbell batching from Chapter 5.
sudo trace-cmd record -e irq -e sched_wakeup sleep 5 while a driver runs, and open it with trace-cmd report. Find the gap from interrupt to wake-up. If your card exposes a timestamp register, read it twice around a known event to estimate the offset.Chapter 9
Keep the numbers, the checklist and the core code in one place, and see where the field is heading
One link, one ring, one doorbell. That is the whole lesson in a line. The link sets how many bytes can move: lanes times a per-lane rate. The ring sets how many commands wait: a depth. The doorbell sets how often the host pays to announce them: once per batch. Everything else keeps those three honest: BARs reach the registers, MSI-X aims the wake-ups, the DMA API keeps the bytes true, the IOMMU keeps the card inside its fence, and power management keeps it asleep only when it should be.
| Quantity | Value | Source or status |
|---|---|---|
| Gen4 lane | 16 GT/s, 128b/130b, 1.969 GB/s each way | PCI Express table (Wikipedia) |
| Gen4 x16 and x4 | 31.5 GB/s and 7.9 GB/s each way | Table value and 4 × 1.969 |
| Gen3 and Gen5 lane | 0.985 and 3.938 GB/s each way | PCI Express table (Wikipedia) |
| 128b/130b framing cost | 2/130, about 1.54% | PCI Express article |
| Packet overhead | 20 bytes per packet, 92.7% at 256-byte payload | Freescale AN3935 figure; the percentage is our arithmetic |
| MSI and MSI-X vectors | up to 32 (power of two); 1 to 2,048 | Linux kernel MSI HOWTO |
| IOMMU page-table reach | 4 levels = 48 bits; 5 levels = 57 bits | 9 bits per level + 12-bit offset; Linux VT-d code supports 4 or 5 levels |
| Thread context switch | 1.2 to 1.5 µs pinned, about 2.2 µs unpinned | Bendersky 2018, Intel i7-4771 |
| Interrupt versus polling crossover | about 286,000 completions/s | Derived from 3.5 µs per completion: illustrative |
| Doorbell batching | 5.9 M/s at b = 1; 34.0 M/s at b = 16 | Derived from 20 ns and 150 ns: illustrative |
| NVMe queue limits | 65,535 queues; 65,536 commands each; 64-byte command | Wikipedia NVMe comparison table |
| PCIe 7.0 | 128 GT/s per lane, released 11 June 2025 | PCI Express article (Wikipedia) |
| CXL 4.0 | 128 GT/s on a PCIe 7.0 physical layer, November 2025 | CXL Consortium release notes as reported |
| Accelerator subsystem | drivers/accel, devices at /dev/accel/accel*, major 261; NPU drivers such as amdxdna, qaic and rocket | Linux kernel accel documentation |
LnkSta with LnkCap on the card and its upstream port. Fix width and speed before any code.pcim_enable_device, pci_set_master, pcim_iomap. Treat all ones as a dead card.pci_alloc_irq_vectors with MSI-X first. One vector per queue. Check /proc/interrupts.CONFIG_DMA_API_DEBUG.dma_wmb(), ownership flag, then the doorbell. Batch the bell.Three pieces carry the design. The first you saw in Chapter 5. The second reads completions with a phase bit and the matching read barrier, so the status is read before the rest of the entry. The third checks the card’s version at probe, which prevents the version skew that bites when the driver and the firmware drift apart.
/* completion side: poll with a phase bit (Chapter 6) */ static int acc_poll(struct acc_q *q, int budget) { int n = 0; while (n < budget) { struct acc_cpl *e = &q->cpl[q->head & (q->depth - 1)]; u16 st = le16_to_cpu(READ_ONCE(e->status)); if ((st & PHASE) != q->phase) break; /* not fresh yet */ dma_rmb(); /* status before the rest */ acc_complete(q, e->cookie, st); if ((++q->head & (q->depth - 1)) == 0) q->phase ^= PHASE; n++; } return n; } /* probe side: negotiate capabilities (Chapter 9) */ u32 ver = readl(regs + REG_ABI_VERSION); u32 caps = readl(regs + REG_CAPS); if (ver < ABI_MIN || ver > ABI_MAX) return -ENODEV; /* refuse skew */ q->batch_ok = !!(caps & CAP_DOORBELL_BATCH); /* use only what exists */
Accelerators are no longer exotic. The kernel now has a subsystem for them, drivers/accel, with its own device nodes and drivers for NPUs from several vendors. The link is getting faster too: PCIe 7.0 doubles the lane rate to 128 GT/s, and CXL 4.0 builds on that physical layer. The ring and the doorbell are the same on each of them. Only the numbers move. A robot that carries a vision accelerator, a camera path and a network link meets all three of this lesson’s ideas every day.
The kernel numbers come from the kernel documentation, the benchmark from its author, and the packet overhead from a vendor application note (Freescale AN3935). The link-rate table is a reference summary of the PCI Express specification. Linux kernel documentation: MSI HOWTO, DMA API HOWTO, memory barriers, VFIO, SR-IOV, PCI power management, accel subsystem. Reference tables: PCI Express, PCI configuration space, NVM Express. Measurement: Bendersky, measuring context switching. Standards news: CXL 4.0. The model costs (20 ns, 150 ns, 1 µs, 2 µs, the power figures) are illustrative and marked wherever they appear. For depth, see MindShare’s PCI Express System Architecture and Linux Device Drivers, 3rd edition, chapters 12 and 15, whose APIs are old.
Open the hero again and drag it with new eyes: you now know what every slot, every pulse and every lane means. Then try Teach to explain the ring on a whiteboard, or Present to say it aloud.