Repository navigation
PCI
Part III of the system development guide.
Nearly every GPU is a PCI (Express) device. This chapter explains how
PCI Express works, then shows how a
PCI device is found, configured and talked to on NetBSD and on Linux,
and how a Linux driver's struct pci_dev is built on NetBSD. Read
devices and drivers first.
Whatever the OS, a PCI function has:
- a configuration space: 256 bytes (4 KiB on PCI Express) of registers with its vendor and device IDs, class, command and status bits, the BARs (base address registers) saying where its memory and I/O windows are, its interrupt pin, and a linked list of capabilities (power management, MSI, MSI-X, PCI Express);
- memory windows (BARs of memory type) — for a GPU, the register block (MMIO) and the visible part of video memory (the "aperture");
- possibly I/O port windows (rare on modern hardware);
- interrupts: a legacy pin (INTx, shared, level-triggered) or message-signalled interrupts (MSI, MSI-X: writes to a special address, one or many vectors, never shared);
- bus mastering: the device reads and writes system memory by itself (DMA), which must be enabled in the command register.
PCI was a shared parallel bus; PCI Express replaced the wires with serial point-to-point links but kept PCI's software model, so an operating system still sees buses, bridges and functions.
Topology. The root complex connects the CPU and memory to the PCI world. Its root ports each lead a link to one device: an endpoint (a GPU, an NVMe drive) or a switch, which fans one link out to several. To software, every port is a PCI-to-PCI bridge with a bus behind it:
CPU, memory -- root complex
|-- root port (bridge) -- bus 1 -- GPU 01:00.0 (+ 01:00.1 audio)
|-- root port (bridge) -- bus 2 -- switch upstream port (bridge)
|-- downstream port -- bus 4 -- NVMe 04:00.0
|-- downstream port -- bus 5 -- NIC 05:00.0
A function is named bus:device.function: up to 256 buses, 32 devices per bus, 8 functions per device. A GPU is typically function 0, and its HDMI/DisplayPort audio controller function 1 of the same device.
Configuration space is how software identifies and sets up a function. Two ways to reach it:
- the legacy mechanism #1: write the bus/device/function/register to
I/O port
0xCF8, then read or write the data at0xCFC-- 256 bytes per function, one access at a time, through a global pair of ports; -
ECAM (enhanced configuration access, "MMCONFIG"): all of it
mapped as memory, 4 KiB per function, at
base + (bus << 20 | device << 15 | function << 12 | register), with the base from the ACPI MCFG table. It is needed for the extended space above 256 bytes, where PCI Express keeps its extended capabilities (AER error reporting, resizable BARs, SR-IOV).
NetBSD's x86 code uses mechanism #1 (arch/x86/pci/pci_machdep.c)
and ECAM when ACPI provides MCFG (dev/acpi/acpi_mcfg.c).
Enumeration. To find what is there, software reads the vendor ID
of every possible device on bus 0 (0xFFFF means nothing), and for
each bridge assigns its secondary and subordinate bus numbers and
scans the bus behind it, recursively. The firmware usually has done
this already; the OS walks what it finds.
BARs and address assignment. A function's base address registers say how big each of its windows is and where it is. The size is found by writing all ones to a BAR and reading it back: the bits that stay zero are the size (a 256 MiB BAR reads back with its low 28 address bits clear). Low bits of the BAR describe the window: I/O or memory, 32- or 64-bit (a 64-bit BAR uses two registers), prefetchable (reads have no side effects, so the CPU may combine and prefetch -- true for video memory, false for registers). Someone then writes an address into each BAR, and every bridge on the path gets a window (I/O, memory, prefetchable memory) that contains its children's BARs. Firmware does this at boot; operating systems may redo it. Large windows only fit above 4 GiB, which firmware does only with "above 4G decoding" enabled.
Transactions. Links carry transaction layer packets (TLPs): memory reads and writes, configuration accesses, completions, messages. Two rules matter to drivers:
- Writes are posted: the writer does not wait for them to arrive. A register write may sit in a buffer in a switch or the root complex while the CPU moves on.
- Reads do not pass earlier writes in the same direction, and a read needs a completion. So reading any register of a device after writing others guarantees the writes have reached it. That is why drivers "flush" with a dummy read before relying on a write -- e.g. before waiting for an interrupt the write was to trigger.
A device that does DMA sends memory TLPs of its own; the bus master bit in its command register allows it to.
Interrupts as messages. The legacy INTx interrupt is a virtual
wire (sent as messages on PCIe), shared and level-triggered. MSI
and MSI-X are plain memory writes: the OS gives the function an
address and a data value, and the function writes that value to that
address to interrupt. On x86 the address lies in the local APIC's
range (0xFEExxxxx) and selects a CPU; the data selects the vector.
MSI-X keeps a table of address/data pairs, one per vector, in one of
the function's BARs, so a device can have many independent
interrupts (a GPU: one per engine or ring), never shared.
Resizable BAR. A GPU's video memory is reached through a BAR, but
the BAR a GPU shows by default is small (256 MiB, a compatibility
choice), so the CPU sees only a window of its many gigabytes. The
Resizable BAR extended capability lets software pick a larger size
-- up to all of VRAM -- if the bridge windows above it can hold it;
drivers then reach any buffer directly instead of moving it into the
window ("Smart Access Memory" is AMD's name). amdgpu asks for it
(amdgpu_device_resize_fb_bar calls pci_resize_resource). NetBSD
defines the registers (PCI_EXTCAP_RESIZBAR) but cannot resize a BAR,
so on aiBSD a GPU keeps the size its firmware gave it -- which is
already all of VRAM when the firmware has "resizable BAR" enabled.
Links. A link has a generation (2.5 GT/s per lane for PCIe 1, up to 64 GT/s for PCIe 6) and a width (x1 to x16). Both are negotiated at reset and can be lowered to save power; GPU drivers read them from the PCI Express capability to report bandwidth and manage power.
pci(4) attaches to a host bridge (or to a PCI–PCI bridge, ppb(4)),
scans every bus/device/function and, for each function present, calls
config_found() with a struct pci_attach_args (dev/pci/pcivar.h):
| Field | Meaning |
|---|---|
pa_iot, pa_memt
|
bus space tags for I/O and memory windows |
pa_dmat, pa_dmat64
|
bus DMA tags (32- and 64-bit capable) |
pa_pc, pa_tag
|
chipset tag and the function's tag, for config access |
pa_bus, pa_device, pa_function
|
its address |
pa_id, pa_class
|
the ID and class registers (PCI_VENDOR(), PCI_PRODUCT(), PCI_CLASS(), PCI_REVISION() take them apart) |
pa_intrpin, pa_intrline, ... |
legacy interrupt routing |
A driver's match looks at pa_id/pa_class and returns a score.
pci_conf_read(pc, tag, reg) and pci_conf_write(pc, tag, reg, v)
access 32-bit registers. pci_get_capability(pc, tag, PCI_CAP_*, &offset, &value) finds a capability. pci_get_powerstate() and
pci_set_powerstate() move between D0 and D3.
pcireg_t type = pci_mapreg_type(pa->pa_pc, pa->pa_tag, PCI_BAR(0));
error = pci_mapreg_map(pa, PCI_BAR(0), type, 0,
&sc->sc_bst, &sc->sc_bsh, &addr, &size);
...
v = bus_space_read_4(sc->sc_bst, sc->sc_bsh, REG);pci_mapreg_info() reads a BAR's address and size without mapping it.
Mapping goes through bus_space(9): a tag (which space) and a
handle (which window), with read/write functions that work on any
architecture. BUS_SPACE_MAP_LINEAR asks for a window addressable
directly (then bus_space_vaddr() gives its kernel address);
BUS_SPACE_MAP_PREFETCHABLE allows write-combining, which matters for
framebuffers.
pci_intr_handle_t *ihps;
int counts[PCI_INTR_TYPE_SIZE] = { [PCI_INTR_TYPE_MSI] = 1, ... };
error = pci_intr_alloc(pa, &ihps, counts, PCI_INTR_TYPE_MSI);
sc->sc_ih = pci_intr_establish_xname(pa->pa_pc, ihps[0], IPL_VM,
handler, sc, device_xname(self));
...
pci_intr_disestablish(pa->pa_pc, sc->sc_ih);
pci_intr_release(pa->pa_pc, ihps, 1);pci_intr_alloc() picks MSI-X, MSI or INTx, best first, up to the
type given (pci_msi(9)). The handler runs in hard interrupt context
at the given IPL (see kernel basics).
The attach args' DMA tags are what the driver passes to bus_dma(9); see memory and DMA.
The PCI core creates a struct pci_dev for every function, whether a
driver wants it or not, and registers its embedded struct device
(pdev->dev). Drivers read its fields directly: vendor, device,
subsystem_vendor, subsystem_device, revision, class, devfn,
bus, and the resource table.
A driver is a struct pci_driver: a name, a table of
struct pci_device_id (vendor/device/class patterns with
driver-private data), probe(pdev, id), remove(pdev), shutdown,
and power-management ops; module_pci_driver() registers it. In
probe, a driver typically:
- enables the device (
pci_enable_device(), orpcim_enable_device()to have it undone automatically); - claims and maps its BARs (
pci_request_regions(),pci_iomap()orpcim_iomap_regions();pci_resource_start/len/flags()describe them;ioremap_wc()for write-combined mappings); - turns on bus mastering (
pci_set_master()) and sets its DMA mask (dma_set_mask_and_coherent()); - allocates interrupt vectors (
pci_alloc_irq_vectors()), gets their numbers (pci_irq_vector()) and installs handlers (request_irq()); - stores its state with
pci_set_drvdata(pdev, priv).
Generic code that only has a struct device gets back to the PCI
device with to_pci_dev(dev) after checking dev_is_pci(dev).
The compat struct pci_dev (<linux/pci.h>) holds both worlds:
-
NetBSD state: a copy of the attach args (
pd_pa), the NetBSD device (pd_dev), the BARs found at attach (pd_resources[]: address, size, flags frompci_mapreg_info(), and the bus space mapping once mapped), saved config state, interrupt handles; -
Linux fields (
vendor,device,subsystem_*,revision,class,devfn,bus), filled from the attach args; -
a Linux
struct device devwhosebsddevispd_dev.
Its life:
- The driver's NetBSD attachment (
<driver>_pci.c) callslinux_pci_dev_init(pdev, self, parent, pa, kludges), which fills all of the above and registers the Linux device (named after the NetBSD one), as the Linux PCI core would have. - Linux code then uses the usual API on it: config access maps to
pci_conf_read/write;pci_resource_*readspd_resources;pci_iomap()/pci_iomap_range()map a memory BAR withbus_space_map(BUS_SPACE_MAP_LINEAR | flags)and returnbus_space_vaddr(); drvdata lives in the Linux device, sopci_get_drvdata(pdev)anddev_get_drvdata(&pdev->dev)agree;to_pci_dev()iscontainer_of;dev_is_pci()checks the device's bus type. I/O-port BARs. On x86, port space is reached only within/outinstructions, so there is no address to hand back. Linux's answer (lib/iomap.c) is a cookie: a small number no kernel address can be, whichioread8()/iowrite8()and friends recognize and turn into port accesses; anything else they treat as memory. aiBSD does the same: an I/O BAR is mapped withbus_space_map()on the I/O tag, recorded in a slot, and returned asLINUX_PIO_BASE + slot * LINUX_PIO_SPAN(below 1 MiB);linux_pio_read/_writeturn the cookie back into a tag, handle and offset. Every mapping is kept on the device (pd_iomaps), sopci_iounmap()and teardown unmap exactly what was mapped.pcim_iomap_region()is the managed variant (unmapped at detach). - The detach routine calls
linux_pci_dev_destroy(pdev): managed resources are released (newest first) and the Linux device unregistered, then mappings undone.
Where it differs from Linux:
-
Interrupts are not installed by Linux code: there is no
request_irq(). NetBSD glue (drm2/pci/drm_pci.c) allocates and establishes them withpci_intr_alloc()/pci_intr_establish_xname()atIPL_DRM(=IPL_VM) and calls the driver's Linux handler. -
Bridges: Linux code walks up to the upstream bridge (link speed,
ASPM).
pci_get_domain_bus_and_slot()and parent devices are faked frompci(4)/ppb(4)softcs ("grovels pci(4) and ppb(4) internals"), enough for config-space reads. -
Devices met by a search have no NetBSD device. Linux code
looks for other PCI functions with
pci_get_class(),pci_get_device()and the like (amdgpu looks for other display devices before deciding how to use ACPI). Each match is a transientpci_devbuilt frompci(4)'s view of the function, with no autoconfdevice_t(pd_devis NULL), because nothing attached it. Such apci_devis not registered as a Linux device, messages about it name its bus location instead of a device, andpci_dev_put()frees it without unregistering. Code that takes apci_devmust not assume adevice_tbehind it. -
No driver core: the ID table is used by the NetBSD
matchroutine;probeis called (or its pieces are) by the attachment.
-
pcictl pci0 list -nlists functions and IDs;pcictl pci0 dump -b B -d D -f Fshows config space. - In a driver's
_pci.c, followlinux_pci_dev_init()intolinux_pci.cand find where each Linux field comes from.
pci(4), ppb(4), pcictl(8), pci(9), pci_intr(9), pci_msi(9),
bus_space(9); sys/dev/pci/pcivar.h, pci_map.c, pci.c;
sys/external/bsd/drm2/linux/linux_pci.c, drm2/pci/drm_pci.c.
aiBSD system development guide
Tutorial
II — Building
III — The kernel
- Kernel basics
- Booting and kernel modules
- Threads, processes, tasks
- Devices and drivers
- Files, descriptors, device nodes
- PCI
- Virtual memory
- Memory and DMA
- Page tables, TLBs, memory types
- Firmware
- State and events
- The console
- Power management
IV — Linux compat layer
V — DRM
VI — Testing
VII — Upstreams
Appendices