Skip to content
systemcoding.dev
Kernels

Simplify I2C and SPI Register Access With regmap

Replace hand-written register accessors with regmap: one config for I2C or SPI, read and write, update_bits, caching and a debugfs register dump on Linux 6.12.

7 min read
Summarize in AI
Flat illustration of a hardware register drawn as bit fields with one field highlighted, with the Linux, Arm and C logos.

Most I2C and SPI chips are a bag of registers, and a driver spends much of its code reading, writing and masking them. Every driver used to write its own accessor functions for its bus, then repeat the work when the same chip appeared in an SPI variant. The kernel's regmap layer removes that duplication. You describe the register layout once in a struct regmap_config, create a regmap for I2C or SPI with one call, and the rest of the driver uses the same functions whichever bus is underneath. As a bonus you get register caching, locking, bit-field helpers and a debugfs dump for free. This post shows the pattern on a chip with I2C and SPI variants, using Linux 6.12, and follows the kernel's regmap documentation. Outputs are worked out from the code.

The problem regmap solves

Consider a driver for a chip with a 16-bit register at index 0x10 holding an enable bit and a mode field. Without a helper, enabling the bit means an I2C read, a mask, an I2C write, and for the SPI variant a separate pair of functions with a different message format. Multiply by every register access and every chip variant, and half the driver is plumbing. Regmap puts the bus differences behind one interface and keeps the chip logic in one place.

Describe the registers

A struct regmap_config states how registers look to the bus:

regmap_config.cc
#include <linux/bitfield.h>
#include <linux/bits.h>
#include <linux/regmap.h>

#define ACME_REG_ID      0x00
#define ACME_REG_CTRL    0x10
#define ACME_REG_STATUS  0x11
#define ACME_REG_DATA    0x20

#define ACME_CTRL_ENABLE BIT(0)
#define ACME_CTRL_MODE   GENMASK(3, 1)

static bool acme_volatile_reg(struct device *dev, unsigned int reg)
{
    return reg == ACME_REG_STATUS || reg == ACME_REG_DATA;
}

static const struct regmap_config acme_regmap_config = {
    .reg_bits         = 8,
    .val_bits         = 8,
    .max_register     = ACME_REG_DATA,
    .volatile_reg     = acme_volatile_reg,
    .cache_type       = REGCACHE_MAPLE,
};

The fields are few and each has a reason. reg_bits is the width of a register address on the wire, and val_bits is the width of one value. max_register bounds legal accesses, and the core rejects anything beyond it, which catches typos. volatile_reg lists registers that change by themselves, so the cache must never serve them: status flags and data registers. Everything else may be cached, so a repeated read of a control register costs no bus traffic. REGCACHE_MAPLE selects a cache based on the kernel's maple tree, suitable for sparse register maps and the current default recommendation; REGCACHE_RBTREE is the older equivalent and REGCACHE_NONE disables caching.

Create the map for I2C or SPI

The bus-specific part is one call, and managed versions exist for both. In an I2C driver:

regmap_i2c.cc
static int acme_i2c_probe(struct i2c_client *client)
{
    struct regmap *map;

    map = devm_regmap_init_i2c(client, &acme_regmap_config);
    if (IS_ERR(map))
        return dev_err_probe(&client->dev, PTR_ERR(map),
                             "regmap init failed\n");
    return acme_core_probe(&client->dev, map);
}

In the SPI variant, the config differs only in how the chip frames a transfer. Many SPI chips mark a read with the top bit of the first byte, which regmap handles through read_flag_mask and write_flag_mask:

regmap_spi.cc
static const struct regmap_config acme_spi_regmap_config = {
    .reg_bits        = 8,
    .val_bits        = 8,
    .read_flag_mask  = 0x80,
    .max_register    = ACME_REG_DATA,
    .volatile_reg    = acme_volatile_reg,
    .cache_type      = REGCACHE_MAPLE,
};

static int acme_spi_probe(struct spi_device *spi)
{
    struct regmap *map;

    map = devm_regmap_init_spi(spi, &acme_spi_regmap_config);
    if (IS_ERR(map))
        return dev_err_probe(&spi->dev, PTR_ERR(map),
                             "regmap init failed\n");
    return acme_core_probe(&spi->dev, map);
}

With read_flag_mask = 0x80, a read of register 0x10 goes out as the byte 0x90, and a write goes out as 0x10. That is the whole difference between the two buses. Both probes then call the same acme_core_probe, which contains the chip logic and knows nothing about the bus. This is how many real drivers are structured: a -core.c file, an -i2c.c file and a -spi.c file, with the core exported and shared.

Using the map

The core logic uses four calls most of the time:

regmap_use.cc
static int acme_core_probe(struct device *dev, struct regmap *map)
{
    unsigned int id;
    int ret;

    ret = regmap_read(map, ACME_REG_ID, &id);
    if (ret)
        return dev_err_probe(dev, ret, "cannot read id\n");
    dev_info(dev, "chip id 0x%02x\n", id);

    ret = regmap_write(map, ACME_REG_CTRL, 0);
    if (ret)
        return ret;

    ret = regmap_update_bits(map, ACME_REG_CTRL,
                             ACME_CTRL_ENABLE | ACME_CTRL_MODE,
                             ACME_CTRL_ENABLE | FIELD_PREP(ACME_CTRL_MODE, 2));
    if (ret)
        return ret;

    return 0;
}

regmap_read and regmap_write do what they say. regmap_update_bits(map, reg, mask, val) is the workhorse: it reads the register, clears the bits in mask, sets the bits from val and writes the result back, and it skips the write if nothing changed. It also takes the regmap's lock, so concurrent updates do not lose each other's changes, which hand-written read-modify-write code often gets wrong. The FIELD_PREP macro from <linux/bitfield.h> shifts a value into the position the mask names, so the code never counts bits. Here the mode field is the mask GENMASK(3, 1), and a value of 2 becomes 0x04, giving a final control value of 0x05.

If the chip printed 0xA1 for its ID, the log would show:

Text
acme-chip 1-0050: chip id 0xa1

For bulk data, regmap_bulk_read reads consecutive registers into a buffer in one bus transaction, and regmap_noinc_read reads repeatedly from a single FIFO-style register without incrementing the address. They exist because a sample buffer read one byte at a time would be slow and could tear.

The cache and when it bites

The cache holds register values the driver wrote or read, so regmap_read returns instantly for them, and regmap_update_bits avoids a read. It has two sharp edges. A register the hardware changes by itself must be volatile, or the driver sees stale data. And a chip that loses its settings in suspend needs the cache replayed on resume: call regcache_cache_only(map, true) and regcache_mark_dirty(map) when suspending, then regcache_cache_only(map, false) and regcache_sync(map) on resume, and the core rewrites every cached register that differs from the hardware default. That makes resume code three lines instead of a table of saved values.

Debugging with debugfs

Regmap publishes the register state through debugfs, one directory per device:

Shell
sudo cat /sys/kernel/debug/regmap/1-0050/registers
Text
00: a1
10: 05
11: 00
20: 00

Each line is a register and its value. Volatile registers are read from the chip, and the others come from the cache, so this view doubles as a register dump you did not have to write. The file range, name and access in the same directory describe the map. This is often the fastest way to see whether the driver configured the chip as intended.

Beyond the basics

The config has many more fields for awkward chips. reg_stride sets the spacing between register addresses, 4 for 32-bit registers on a memory-mapped device. reg_format_endian and val_format_endian handle big-endian chips. writeable_reg and readable_reg mark registers that must not be touched, and reg_defaults lists the power-on values so the cache starts valid. Memory-mapped registers use devm_regmap_init_mmio, which gives them the same interface and the same debugfs view, so one driver structure can serve an MMIO variant too. A regmap can also report fields through regmap_field, a handle for a bit range that you read and write by value, which removes the masks entirely for heavily used fields.

Boundaries

Regmap adds a layer, and for a driver with two registers that never change, a direct i2c_smbus_* call is simpler. It is also not a good fit for devices that need command streams or multi-step handshakes, where the register model does not apply. Locking is per map: if two maps share hardware state, you must serialize them yourself. And caching hides bus errors that a read would have exposed, so run the first bring-up with REGCACHE_NONE and enable the cache once the chip behaves.

Also inEmbedded
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.