Skip to content

GPU drivers lessons from amdgpu

ebenali edited this page Dec 4, 2026 · 3 revisions

GPU drivers: lessons from amdgpu

amdgpu, AMD's Linux driver for its GPUs since 2015, is about 935 C files: a fifth of a whole BSD kernel. Most of it is not graphics. This chapter reads it for the ideas that hold for systems programming in general, and points to where each one shows up in aiBSD. Two small drivers serve as counterpoints: bochs (drm/tiny/bochs.c, 836 lines) shows what every display driver must do, and virtio-gpu (drm/virtio/, about 7000 lines) shows a GPU reduced to a message protocol. Paths are relative to sys/external/bsd/drm2/dist/drm/amd/ for amdgpu and to sys/external/bsd/drm2/dist/ otherwise.

A GPU is many processors

A modern GPU is not one processor but a set of independent engines, each with its own microcontroller running firmware:

Engine Job amdgpu
GFX / compute shaders: drawing and general computation gfx_v*.c
SDMA copying and filling memory sdma_v*.c
VCN, JPEG video encode and decode vcn_v*.c, jpeg_v*.c
DCN display: scanning images out to monitors display/ (DC)
SMU power, clocks, fans, temperatures pm/swsmu/
PSP security processor: loads the others' firmware amdgpu_psp.c
MES schedules work queues in hardware mes_v*.c

Each engine type comes in versions, and a GPU combines particular versions of each. Newer GPUs describe their combination in a table in VRAM, which amdgpu_discovery.c reads to pick the matching code (about 85 calls to amdgpu_device_ip_block_add). The driver is then a list of IP blocks with common hooks (early_init, sw_init, hw_init, suspend, resume, ...), run in order.

The lesson: large hardware is a network of cooperating agents, and the driver mostly coordinates them -- boots them in the right order (the PSP before the other firmware-running engines, because it authenticates everyone else's firmware), hands them work, and recovers them when one fails. The 98 per-generation files in amdgpu/ show how a vendor versions hardware interfaces without dropping old chips.

Discovery and the order of IP blocks

On current GPUs the combination of engine versions is not in a table in the driver but in an IP discovery binary the GPU's firmware leaves behind: at a fixed distance below the top of VRAM on a discrete GPU (read through amdgpu_device_vram_access, before VRAM is mapped), or in reserved system memory on an APU, whose VRAM size register reads 0 (memremap of the reserved range). A file, amdgpu/ip_discovery.bin, can stand in for it. amdgpu_discovery_set_ip_blocks turns the table into the IP block list, in an order that encodes the dependencies:

Order Block Why there
1 common (nv_common, soc21_common, ...) registers every other block uses
2 GMC (gmc_v*) memory controller: nothing else has addresses before it
3 IH (*_ih) interrupt ring, so later blocks can be told when work is done
4 PSP security processor: loads and authenticates the rest's firmware
5 SMU power and clocks, its firmware loaded by the PSP
6 DCN (dm) display
7 GFX, SDMA the compute and copy engines
8 VCN, JPEG, MES, ... media and scheduling

hw_init runs in this order and teardown in reverse, so a block may rely on everything above it in the table. (In an SR-IOV guest the PSP moves ahead of IH.)

The security processor: a mailbox, then a ring

The PSP (Platform Security Processor) is an ARM core that holds the keys: it checks the signature of every other engine's firmware before that engine may run it, and it owns the Trusted Memory Region, a range of graphics memory the other engines' firmware lives in and the CPU may not touch. The driver talks to it in two stages, both visible in amdgpu_psp.c and the per-version psp_v*_0.c.

Mailbox registers. The PSP's MP0 block exposes a set of 32-bit message registers, C2PMSG_n ("CPU to PSP message"), that both sides read and write. Each version file says which register means what; for psp_v13_0.c:

Register Use
C2PMSG_35 bootloader command; bit 31 set when the bootloader is ready
C2PMSG_36 bootloader argument: address of the image to load, in MiB
C2PMSG_81 non-zero once the secure OS (sOS) is running
C2PMSG_64 ring command; the sOS sets bit 31 (response) when done, with a status in the low bits
C2PMSG_69, 70 ring address, low and high 32 bits (an MC address)
C2PMSG_71 ring size
C2PMSG_67 ring write pointer, in dwords

Every exchange is a register write followed by psp_wait_for, which polls a register until (value & mask) == expected or about usec_timeout microseconds pass, and returns -ETIME.

Booting the PSP (psp_hw_start). On a discrete GPU the PSP starts with only its boot ROM and bootloader. The driver copies each image into a private buffer (psp_copy_fw), writes its address to C2PMSG_36 and a load command to C2PMSG_35, and waits for bit 31: the key database (kdb), the SPL table, the system driver, then the secure OS itself, plus whatever optional drivers the firmware file carries. An APU's PSP is part of the CPU's own security processor and its secure OS is already running when the operating system starts; C2PMSG_81 reads non-zero, every bootloader step returns at once, and the firmware file holds only a table of contents (TOC) and the trusted applications (psp_v13_0_init_microcode picks toc rather than sos for APU versions).

The ring. With the sOS up, the driver waits for C2PMSG_64 to show it ready, writes the ring's address and size to C2PMSG_69..71 and the "initialise ring" command to C2PMSG_64, and waits for the response bit. From then on commands go through the KM ring (psp->km_ring, once called GPCOM), a buffer in graphics memory of 64-byte frames (struct psp_gfx_rb_frame). psp_cmd_submit_buf:

  1. copies the command (struct psp_gfx_cmd_resp) into the shared command buffer;
  2. takes the next fence value and writes a frame holding the command buffer's MC address, the fence buffer's MC address and that value (psp_ring_cmd_submit);
  3. flushes HDP and advances the write pointer in C2PMSG_67 by one frame;
  4. polls the fence buffer (invalidating HDP before each read) until the PSP has written the fence value there, or psp_timeout polls pass;
  5. reads the response, whose status field the PSP fills in.

All three buffers are addressed by MC address, so the PSP reaches them through the memory controller while the CPU uses its own mapping of the same bytes (three addresses).

Two kinds of failure. A response with a non-zero status means the PSP read the command and refused it. A timeout with the status still 0 means the PSP never wrote back: it never saw the frame, or its writes did not land where the CPU looks. The first is a question about the command and the firmware; the second is a question about the path: the ring and fence addresses, the memory they are in, and the order in which the CPU's writes become visible.

The TMR. The first command on the ring decides the trusted memory region. Where the firmware has a TOC, the driver sends LOAD_TOC with it, and the PSP answers with the TMR size the listed firmware needs (psp_load_toc inside psp_tmr_init). The driver allocates a buffer of that size, naturally aligned, and hands it over with SETUP_TMR (psp_tmr_load), giving both its MC and physical address. After that every engine's firmware is loaded with LOAD_IP_FW commands, each placed by the PSP inside the TMR.

Work is asynchronous: rings, doorbells, fences

The CPU never draws. It writes commands into a ring buffer, a circular array in memory both sides can reach, and tells the engine how far it has written:

  1. the driver appends packets at the write pointer (wptr);
  2. pads to the engine's fetch size and issues a memory barrier (amdgpu_ring_commit: mb() before amdgpu_ring_set_wptr), so that the commands are in memory before the engine can see the new pointer;
  3. writes the new pointer to a doorbell, a register in a BAR set aside for it, which wakes the engine;
  4. the engine reads packets up to wptr and advances its read pointer (rptr).

That is the producer/consumer queue of every operating system course, with the hardware as the consumer and the ordering made explicit. The same structure runs backwards for interrupts: the GPU writes events into an interrupt ring (amdgpu_ih.c) and the driver consumes them.

The CPU learns that work is done through a fence: the driver ends a job with a packet that makes the engine write a sequence number to memory and raise an interrupt (amdgpu_ring_emit_fence). amdgpu_fence_process reads the last number written and signals every fence up to it. Fences are the currency of the whole graphics stack:

  • dma_fence (linux_dma_fence.c in the compat layer) is the common type, shared between drivers and with user space (sync files);
  • the GPU scheduler (drmkms_sched) queues jobs per ring and starts each once the fences it depends on have signalled;
  • reservation objects (dma_resv, locked with ww_mutex) record which fences each buffer is busy with.

The lesson: asynchronous systems stand on two skills -- ordering (barriers, and which side may see what when) and knowing when something has finished. Most GPU driver bugs are lifetime bugs: memory freed or reused while an engine still reads it.

Memory is the hard part

GPUs compute easily; feeding them memory is what is hard.

Memory domains. A discrete GPU has its own memory, VRAM, which the CPU reaches only through a PCI BAR -- often a 256 MiB window onto many gigabytes (visible_vram_size against real_vram_size; see PCI on resizable BARs). The GPU also reaches system RAM through its own page table, the GTT. A buffer lives in one domain at a time and moves under pressure: VRAM to GTT when VRAM is full, back when it is used again. That is TTM's job (drmkms_ttm), and it is why mappings must be revocable: a process that mapped a buffer must not keep reaching the old copy after a move (Memory and DMA).

Three addresses for one byte. A byte of VRAM has an address in the GPU's memory controller (an MC address, between gmc.vram_start and gmc.vram_end, what the GPU's own engines and page tables use), a physical address on the CPU's side, and, once mapped, a kernel virtual address. gmc.aper_base is the physical address of the start of VRAM as the CPU sees it, so for VRAM the CPU can reach

CPU physical = gmc.aper_base + (MC address - gmc.vram_start)

What aper_base is depends on the kind of GPU (gmc_v*_mc_init):

  • A discrete GPU: VRAM sits behind BAR 0, so aper_base is the BAR's address and visible_vram_size its length. The driver tries to resize the BAR to cover all VRAM first (amdgpu_device_resize_fb_bar); where that fails, only the first visible_vram_size bytes are reachable by the CPU, and buffers the CPU must touch are placed there.
  • An APU (x86, not passed through to a guest): "VRAM" is a carve-out of system RAM that the firmware reserves at boot, and the memory controller registers say where (get_mc_fb_offset, the GCMC_VM_FB_OFFSET register). aper_base becomes that physical address and the aperture is the whole carve-out; BAR 0 is not used to reach it. The carve-out is not RAM to the kernel: it is not in mem_clusters, so the direct map leaves it out and no write-back alias exists. That is also why ioremap may map it: the compat ioremap* refuse ranges that are RAM in the direct map (linux_range_is_ram in linux_page.c).

amdgpu_ttm_init maps the aperture once, write-combining (ioremap_wc → pmap_kenter_pa(..., PMAP_WRITE_COMBINE) → PGC_WC, see memory types), into mman.aper_base_kaddr. TTM's io_mem_reserve hook then gives a VRAM buffer its CPU address: the bus offset is always aper_base + offset, and the kernel pointer aper_base_kaddr + offset is filled in only for buffers placed with TTM_PL_FLAG_CONTIGUOUS, since only a contiguous buffer is one straight run of the aperture. Kernel-internal buffers (amdgpu_bo_create_reserved, used for rings, fences, firmware) are always created contiguous; others are mapped page by page through TTM.

Write-combining and ordering. WC writes go into the CPU's write-combining buffers and reach memory in bursts, in no promised order and not at once. Before the GPU may read what the CPU wrote (a command, a ring's write pointer, a fence value it is told to compare), the CPU must drain those buffers: a store fence (wmb(), sfence on x86) or an uncached access such as a register write, which on x86 drains them too. The reverse direction matters as much: a WC mapping is not cached for reads, so the CPU sees the GPU's writes to VRAM without a cache flush, but only once the GPU has pushed them out of its own caches.

HDP. On a discrete GPU, CPU accesses through the BAR pass through the GPU's Host Data Path, which has a small cache and write queue of its own. The driver flushes it after the CPU writes data the GPU is about to use (amdgpu_device_flush_hdp, or a ring packet emitted before the work, emit_hdp_flush), and invalidates it before the CPU reads results. On an x86 APU the CPU reaches the carve-out directly as RAM, not through the BAR, so there is no HDP in the path and amdgpu_device_flush_hdp returns at once; the same holds for a GPU connected to the CPU over a coherent fabric (xgmi.connected_to_cpu, mapped cached with ioremap_cache).

Memory types. Whether the CPU caches a page is decided per mapping, and must agree between mappings: the GPU reads RAM without snooping the CPU's caches for some buffers, so those must be write-combining or uncached everywhere (Page tables, TLBs, memory types). A conflicting cached alias is not a slowdown but undefined behaviour.

A second MMU. The GPU translates addresses with page tables of its own, one set per process (amdgpu_vm.c, amdgpu_vm_pt.c), updated by the CPU or by SDMA jobs, with TLB flushes the driver must order with the work that uses them. A GPU driver contains a small virtual memory system next to the kernel's.

The lesson: a GPU driver teaches virtual memory, caching and coherence more concretely than most textbooks, because it must manage all three for a device with different rules from the CPU.

The fast path is short; the slow paths are the driver

Submitting work is a few writes. The bulk of amdgpu handles what goes wrong or changes:

  • Initialisation: firmware loading through the PSP, discovery, bringing up each IP block, reserving memory regions the firmware uses.
  • Power: the SMU changes clocks and voltages, engines power down when idle, the whole GPU suspends with the system (Power management).
  • Hangs and reset: when a job runs too long the scheduler calls amdgpu_job_timedout, which tries to reset the engine and, failing that, the GPU (amdgpu_device_gpu_recover, amdgpu_reset.c), then replays or fails the jobs in flight.
  • Errors: RAS reports corrected and uncorrected memory errors and retires bad pages (ras/).
  • Removal: a GPU can disappear (an external enclosure, a fatal error), and every user -- open files, mappings, fences other drivers wait on -- must fail cleanly (Devices and drivers).

The lesson: robust systems code is mostly failure handling, and it must be designed in: a reset has to be possible at any point the hardware can hang, which shapes every data structure.

The smallest display driver

Strip a display driver to what every one must do, and bochs is left -- the driver for QEMU's standard VGA, which has no engines at all:

  • Describe the display pipeline to DRM: a plane (an image in memory), a CRTC (the timing generator that scans a plane out), an encoder and a connector (where the monitor is). User space builds a configuration from these objects and DRM checks and applies it as one atomic commit (bochs_kms_init, drm_atomic_helper_*).
  • Program a mode: resolution, depth and the scanout address go into a handful of registers -- for bochs the "dispi" interface, an index port and a data port (bochs_dispi_write, I/O ports 0x1ce/0x1cf).
  • Provide buffers: dumb buffers user space can map and draw into, here shmem GEM objects (pages of system RAM, drm_gem_shmem_helper.c), copied into the card's VRAM when the plane is updated.
  • Signal vertical blanks: the moment between frames when a new image may be shown without tearing. Hardware raises an interrupt; bochs has none, so DRM runs a timer that fires once per frame period instead (drm_crtc_vblank_start_timer, an hrtimer that forwards itself and restarts). If the timer is wrong, every commit waits a full timeout for a vblank that never comes.

The lesson: the kernel side of displaying an image is small: a model of the pipeline, a few registers, a buffer and a clock. Everything amdgpu adds is acceleration, power, memory management and recovery around this core.

A GPU as a message protocol: virtio-gpu

A virtual machine's GPU need not pretend to be hardware. virtio-gpu is a paravirtual device: the guest driver talks to the host through queues of request and response buffers (virtqueues, the same mechanism as virtio disks and network cards), and every operation is a message:

Command Number Meaning
RESOURCE_CREATE_2D 0x101 the host allocates an image of a given size and format
RESOURCE_ATTACH_BACKING 0x106 the guest gives the host a list of its own pages holding the image
TRANSFER_TO_HOST_2D 0x105 the host copies a rectangle from those pages into its image
SET_SCANOUT 0x103 the image becomes what a display shows
RESOURCE_FLUSH 0x104 a rectangle changed: show it

(include/uapi/linux/virtio_gpu.h.) A plane update in the driver is therefore transfer, then flush (virtio_gpu_primary_plane_update in drm/virtio/virtgpu_plane.c); a mode change adds a SET_SCANOUT. Completion comes back as responses on the queue, matched to fences as with amdgpu's rings, and 3D is the same idea with command buffers for a host-side renderer (virgl, venus) as message payloads.

The design shows what a GPU interface reduces to once the hardware is taken away: name some memory, say how it is laid out, say when it changed, and wait for an answer. It also explains why the guest's memory must be described exactly: the host reads the guest's pages through the list ATTACH_BACKING sent (struct virtio_gpu_mem_entry, address and length per entry), so a wrong list does not crash -- the host just refuses later commands on that image.

The lesson: an interface between two systems is easiest to reason about as messages with explicit ownership of memory; paravirtual devices are the cleanest examples, and reading one is a good way to see what a real device's registers are doing underneath.

Handing the screen over

Before any GPU driver runs, the firmware has already lit the screen: UEFI's GOP leaves a framebuffer -- an address, a size, a pixel format -- and the kernel's first console draws into it (NetBSD's genfb, Linux's efifb or simpledrm). When the GPU driver arrives, three things must happen in order:

  1. Evict the firmware framebuffer's users before the driver reprograms the display or reuses the memory: the console still drawing there would scribble over buffers the GPU now owns. Linux calls it aperture removal (aperture_remove_conflicting_pci_devices, first thing in a probe); aiBSD detaches genfb and stops the early console (DRM integration).
  2. Bring up the driver's own framebuffer: DRM's fbdev emulation allocates a buffer, sets a mode, and registers it as a framebuffer device (drm_fbdev_*.c, register_framebuffer).
  3. Move the console onto it: Linux's fbcon binds to the new fbdev; aiBSD attaches a wsdisplay to it (drmfb) and makes it the console.

Two properties make this harder than it looks. The emulated framebuffer is usually a shadow in system memory, not what the hardware scans out, so whatever draws the console must say which pixels changed (damage), and a worker copies them to the real buffer (drm_fb_helper_damage_area). And the handover has a window in which nobody owns the screen: if the driver fails after step 1, the console is gone unless something gives the firmware framebuffer back -- and the GPU may already have reprogrammed it.

The lesson: handing a resource between two owners needs an explicit protocol -- who releases, who acquires, what happens if the new owner fails -- and the failure path decides whether the machine stays usable.

What a device can read: memory as pages

A device reaches memory by physical address, but kernel code sees virtual addresses, and the two disagree in ways that matter:

  • Contiguity. Memory that is contiguous in kernel virtual space may be scattered physically. Linux's kmalloc memory is physically contiguous; vmalloc memory is not, and a driver that hands it to a device must describe it page by page (virtio-gpu's vmalloc_to_sgt in drm/virtio/virtgpu_vq.c builds one entry per page, which is why it insists the buffer be page-aligned). A scatterlist is that description: a list of physical runs, merged where pages happen to be adjacent, split at a maximum segment size the device can take.
  • Reach. A device may address only part of physical memory -- 32 bits for many PCI devices by default. The DMA mask says how much; memory beyond it must be bounced through a buffer the device can reach, or the mapping fails. A virtual device can address everything and says so with a 64-bit mask, as Linux's virtio PCI driver does.
  • Translation. With an IOMMU, the addresses a device uses are translated again, and the device sees only what was mapped for it; without one -- the common case in virtual machines -- it sees physical memory directly.

The lesson: "a pointer to the buffer" is not a description a device can use. Device memory interfaces are about producing exact lists of physical pages, within the device's reach, for exactly as long as the device may touch them.

Code shared across operating systems

The display code, DC (display/dc/), is a library AMD shares between Linux and Windows. It talks to the operating system only through a thin layer, amdgpu_dm and dm_helpers (display manager). Its types are its own: dm_helpers_allocate_gpu_mem takes a long long * where callers pass uint64_t *, which only compiles where those are the same type -- one reason aiBSD compiles DRM with Linux's integer model (DRM integration).

Part of DC, DML (92 files), computes display bandwidth and timing in floating point. Kernels normally avoid the FPU: user processes' FPU state must be saved before the kernel may touch it, and the kernel must not be preempted while it holds the FPU. DC brackets its floating-point code with DC_FP_START/DC_FP_END (dc_fpu.c), on Linux's kernel_fpu_begin/end -- NetBSD's fpu_kern_enter/leave (<linux/fpu.h>) -- and those files alone are compiled with FPU instructions enabled.

The lesson: sharing code across operating systems works through a narrow, explicit boundary; whatever leaks across it (types, build assumptions) is what a port must reproduce.

What porting it teaches

Moving amdgpu to NetBSD shows how much of a program's meaning lives outside its source text:

  • the build: Kbuild's configuration (off means undefined), its warning set, its per-file flags -- reproduced so that the code means the same thing (DRM integration);
  • the compiler's model: what int64_t is, what __always_inline expands to;
  • the loader: how link sets reach a module, which symbols a module linker accepts (The compat layer);
  • the kernel interfaces it was written against -- struct page, vm_ops->fault, pci_driver -- which a compat layer can provide on a different VM and driver model because they are interfaces, not implementations;
  • the promises behind small functions: a stand-in must keep the contract, not only the signature. An is_vmalloc_addr that answers "yes" for every address compiles and runs, until a driver relies on what the answer implies (page alignment, page-by-page description) and hands a device a wrong page list. Stand-ins that cannot keep the contract should fail loudly (Backlog).

Skills it builds

  • Reading register specifications; safe MMIO, with posted writes flushed by a read before relying on them (PCI).
  • Interrupts at scale: MSI-X vectors per engine, interrupt rings.
  • Firmware loading and authenticated boot chains (Firmware).
  • Debugging without a debugger: register state, ring contents, fence sequence numbers, device core dumps after a hang.
  • Concurrency with external agents: the "other thread" is hardware that ignores your locks.
  • Finding where an error comes from: tracing which function first returns the error code (DTrace's function-boundary probes on return, filtered on the value), instead of guessing from the message that finally reports it.
  • Watching the other side: a virtual device's host can log every command it receives (QEMU's trace events), which turns "the screen stays black" into a list of what the guest actually sent.

Reading order

  1. A small KMS driver -- DRM's vkms, or drm/tiny/bochs.c for one that drives a (virtual) device: the display model -- CRTCs, planes, connectors -- and atomic commits.
  2. drm/virtio/: a whole GPU driver as a message protocol; virtgpu_vq.c for the queues, virtgpu_plane.c for display updates.
  3. amdgpu/amdgpu_ring.c and amdgpu/amdgpu_fence.c: submission and completion end to end.
  4. TTM (drm/ttm/ttm_bo.c, ttm_tt.c): placement and eviction.
  5. amdgpu/amdgpu_vm.c: the GPU's own virtual memory.
  6. The other half: user space. Mesa's drivers (RadeonSI for OpenGL, RADV for Vulkan) build the command streams the kernel submits; a small Vulkan program traced down to its ioctls shows the whole path.
  7. On Linux, AMD's umr reads registers, rings and wave state live.

Further reading

  • AMD's register and ISA documentation: the GPUOpen documentation site publishes instruction-set manuals for each GCN and RDNA generation.
  • The Linux kernel's GPU documentation (Documentation/gpu/ in the kernel tree): DRM memory management, the scheduler, dma-buf, and an amdgpu section with a glossary.
  • The OASIS Virtual I/O Device (VIRTIO) specification: virtqueues, device initialization, and the GPU device's commands, in a few dozen readable pages.

Clone this wiki locally