</>EmbeddedInterview

How does a driver access device registers?

MediumLinux Kernel & Device Drivers

Short answer: Map the physical register range into kernel virtual address space (devm_platform_ioremap_resource() or devm_ioremap()), which returns an void __iomem *, then access registers only through the I/O accessors readl/writel (and readb/w/q, writeb/w/q), never through plain pointer dereferences. The accessors use the right instruction width, include the barriers needed to order MMIO against DMA and normal memory, and handle endianness. For complex register maps, many drivers use regmap.

void __iomem *base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(base)) return PTR_ERR(base);

u32 v = readl(base + CTRL);
writel(v | CTRL_EN, base + CTRL);

/* poll a status bit with timeout (sleeps between reads) */
ret = readl_poll_timeout(base + STATUS, v, v & STATUS_READY, 10, 1000);   /* 10 µs, 1 ms */
if (ret) return dev_err_probe(dev, ret, "device not ready\n");

Accessor variants

Accessor Ordering
readl / writel ordered against other MMIO and DMA buffers: writel comes after earlier normal memory writes (so a descriptor written before the doorbell is visible to the device)
readl_relaxed / writel_relaxed no barriers against normal memory; faster for register-only sequences
ioread32 / iowrite32 work for both MMIO and port I/O (PCI)
ioread32be, readl_be (via __raw + swab) big-endian device registers
readl_poll_timeout(_atomic) polling with a timeout

Why not a plain pointer: the compiler may reorder, merge or cache accesses (volatile only partly helps), the architecture may need specific instructions or barriers (Arm device memory, dsb/dmb), and sparse checks __iomem annotations to catch mistakes.

Bit helpers: FIELD_PREP(GENMASK(7, 4), val) and FIELD_GET from <linux/bitfield.h> make field updates clear.

Debugging from user space: devmem2 or busybox devmem 0x40010000 32 (needs /dev/mem access, often restricted with CONFIG_STRICT_DEVMEM).