Skip to content
systemcoding.dev
Kernels

Write a GPIO Controller Driver With struct gpio_chip

Write a Linux 6.12 GPIO controller driver with struct gpio_chip: direction, get and set callbacks, locking, registration and the generic MMIO helper.

8 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and FreeBSD logos.

The consumer drivers in this cluster, the buttons and resets and enables, all depend on somebody providing the lines. That somebody is a GPIO controller driver: it owns a bank of pins and registers a struct gpio_chip that tells the GPIO core how to read, write and configure each one. Once it is registered, the lines appear to every consumer through gpiod_get(), to user space as /dev/gpiochipN, and to the device tree as a node you can point at with <&gpio 4 0>. This post writes a controller for a memory-mapped bank of 16 pins on Linux 6.12, explains each callback, covers the locking that read-modify-write needs, and shows the generic helper that makes most of this code unnecessary. The consumer side is in the GPIO descriptor post.

The provider interface is documented in the kernel's GPIO driver guide.

The hardware

The controller has two 32-bit registers. The data register holds the pin levels, where reading returns the current input state and writing sets the outputs. The direction register has one bit per pin, set for output and clear for input. Only the low 16 bits are connected:

c
#define REG_DATA	0x00
#define REG_DIR		0x04
#define NGPIO		16

Pins on controllers like this one are almost always shared by many consumers, so several callers can change different bits of the same register at once. That is why the driver needs a lock, and it is the main source of subtle bugs in GPIO drivers.

The callbacks

A gpio_chip has callbacks for each operation. The ones this driver implements:

CallbackPurpose
get_directionReport whether a line is input or output
direction_inputMake a line an input
direction_outputMake a line an output at a given value
getRead a line's level
setWrite a line's level

All take the chip and the line offset, which is the pin number within this controller, from 0 to ngpio - 1. The offsets are the numbers a device tree uses in the first cell after the controller reference.

The driver

sample_gpio_chip.cc
#include <linux/bits.h>
#include <linux/gpio/driver.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>

#define REG_DATA	0x00
#define REG_DIR		0x04
#define NGPIO		16

struct sample_gpio {
	struct gpio_chip	chip;
	void __iomem		*regs;
	raw_spinlock_t		lock;
};

static int sample_gpio_get_direction(struct gpio_chip *gc, unsigned int off)
{
	struct sample_gpio *g = gpiochip_get_data(gc);
	u32 dir = ioread32(g->regs + REG_DIR);

	return (dir & BIT(off)) ? GPIO_LINE_DIRECTION_OUT :
				  GPIO_LINE_DIRECTION_IN;
}

static int sample_gpio_direction_input(struct gpio_chip *gc, unsigned int off)
{
	struct sample_gpio *g = gpiochip_get_data(gc);
	unsigned long flags;
	u32 dir;

	raw_spin_lock_irqsave(&g->lock, flags);
	dir = ioread32(g->regs + REG_DIR);
	iowrite32(dir & ~BIT(off), g->regs + REG_DIR);
	raw_spin_unlock_irqrestore(&g->lock, flags);
	return 0;
}

static void sample_gpio_set(struct gpio_chip *gc, unsigned int off, int val)
{
	struct sample_gpio *g = gpiochip_get_data(gc);
	unsigned long flags;
	u32 data;

	raw_spin_lock_irqsave(&g->lock, flags);
	data = ioread32(g->regs + REG_DATA);
	data = val ? (data | BIT(off)) : (data & ~BIT(off));
	iowrite32(data, g->regs + REG_DATA);
	raw_spin_unlock_irqrestore(&g->lock, flags);
}

static int sample_gpio_direction_output(struct gpio_chip *gc,
					unsigned int off, int val)
{
	struct sample_gpio *g = gpiochip_get_data(gc);
	unsigned long flags;
	u32 dir;

	sample_gpio_set(gc, off, val);	/* set the level before driving it */

	raw_spin_lock_irqsave(&g->lock, flags);
	dir = ioread32(g->regs + REG_DIR);
	iowrite32(dir | BIT(off), g->regs + REG_DIR);
	raw_spin_unlock_irqrestore(&g->lock, flags);
	return 0;
}

static int sample_gpio_get(struct gpio_chip *gc, unsigned int off)
{
	struct sample_gpio *g = gpiochip_get_data(gc);

	return !!(ioread32(g->regs + REG_DATA) & BIT(off));
}

static int sample_gpio_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct sample_gpio *g;

	g = devm_kzalloc(dev, sizeof(*g), GFP_KERNEL);
	if (!g)
		return -ENOMEM;

	g->regs = devm_platform_ioremap_resource(pdev, 0);
	if (IS_ERR(g->regs))
		return PTR_ERR(g->regs);

	raw_spin_lock_init(&g->lock);

	g->chip.label		= "sample-gpio";
	g->chip.parent		= dev;
	g->chip.owner		= THIS_MODULE;
	g->chip.base		= -1;
	g->chip.ngpio		= NGPIO;
	g->chip.can_sleep	= false;
	g->chip.get_direction	= sample_gpio_get_direction;
	g->chip.direction_input	= sample_gpio_direction_input;
	g->chip.direction_output = sample_gpio_direction_output;
	g->chip.get		= sample_gpio_get;
	g->chip.set		= sample_gpio_set;

	return devm_gpiochip_add_data(dev, &g->chip, g);
}

static const struct of_device_id sample_gpio_of_match[] = {
	{ .compatible = "example,sample-gpio" },
	{ }
};
MODULE_DEVICE_TABLE(of, sample_gpio_of_match);

static struct platform_driver sample_gpio_driver = {
	.probe	= sample_gpio_probe,
	.driver	= {
		.name		= "sample-gpio-chip",
		.of_match_table	= sample_gpio_of_match,
	},
};
module_platform_driver(sample_gpio_driver);

MODULE_DESCRIPTION("Memory-mapped GPIO controller");
MODULE_LICENSE("GPL");

The 6.12 signature of set returns nothing. A later kernel changes it to return an error code, so a driver written for a newer tree looks slightly different, and you should match the signature of the tree you build against.

The pieces that are easy to get wrong

**base = -1.** This lets the core assign a base number dynamically. A fixed base was how drivers claimed global numbers in the old interface, and it collides with other controllers. Use -1 always. Nothing in modern consumers needs the number.

**can_sleep.** It says whether the callbacks can sleep. A memory-mapped bank is accessed with plain register operations that never sleep, so it is false, and consumers may then use the non-cansleep calls inside interrupt context. For a controller behind I2C or SPI it must be true, and the driver can take a mutex. Getting this wrong in either direction is a bug: claiming false while sleeping in a callback produces warnings and deadlocks.

The lock. set and the direction functions each read a register, change a bit and write it back. Two threads changing different pins, with no lock, can lose an update: both read the same value, each sets its own bit, and the second write erases the first. A raw spinlock with interrupts saved protects the sequence and is valid in any context, because can_sleep is false and the callbacks may run from an interrupt handler. It is a raw spinlock because the sections are tiny and must not sleep even on kernels that make ordinary spinlocks sleepable.

**Order in direction_output.** The driver sets the level before turning the pin into an output. The other order briefly drives whatever stale level the data register held, which can glitch a reset line or fire a relay. The GPIO core passes the intended value to this callback for exactly that reason.

Checking it from user space

When the driver binds, the controller appears as a new chip:

Shell
gpiodetect
gpioinfo -c gpiochip1 | head -n 3
Text
gpiochip0 [pinctrl-bcm2711] (58 lines)
gpiochip1 [sample-gpio] (16 lines)
gpiochip1 - 16 lines:
	line   0:	unnamed         	input
	line   1:	unnamed         	input

Each of the 16 lines is available to the tools from the sysfs versus libgpiod post, and a consumer node in the device tree refers to a line as <&gpio_bank 4 GPIO_ACTIVE_HIGH> by controller, offset and flags. For that to work the controller's node needs gpio-controller; and #gpio-cells = <2>;, which tell the core how to parse the cells.

The generic helper that replaces most of this

Most simple memory-mapped GPIO banks need exactly the code above, and the kernel has a library for it: gpio-mmio, reached with bgpio_init(). You describe the registers and it fills in every callback, with locking, for any width and endianness:

c
ret = bgpio_init(&g->chip, dev, 4, regs + REG_DATA, NULL, NULL,
		 regs + REG_DIR, NULL, 0);
if (ret)
	return ret;

g->chip.ngpio = NGPIO;
return devm_gpiochip_add_data(dev, &g->chip, g);

The arguments are the register width in bytes and the addresses of the data-in, set, clear, direction-out and direction-in registers, with NULL for the ones the hardware lacks. For this hardware, with a single data register and an output-direction register, that is the call above. A new driver should check whether bgpio_init() fits before writing callbacks by hand. The hand-written form earns its place when the hardware has quirks the helper cannot model, such as write-enable bits or lines with different electrical options.

Interrupts

A controller that raises interrupts on pin changes registers an irq chip with the gpio_irq_chip member of the gpio_chip, so that consumers can call gpiod_to_irq(). That adds a mask, unmask and type-setting set of callbacks, and an interrupt handler that reads the status register and calls generic_handle_domain_irq() for each pending line. It is a larger piece of work than the basic provider, and most hardware drivers add it after the base functionality works.

A device tree node for the controller

The controller needs a node in the device tree that gives its registers and declares it a GPIO provider. Consumers refer to it by label:

dts
gpio_bank: gpio@10001000 {
	compatible = "example,sample-gpio";
	reg = <0x10001000 0x8>;
	gpio-controller;
	#gpio-cells = <2>;
};

button {
	compatible = "gpio-keys";
	key-enter {
		label = "Enter";
		linux,code = <28>;
		gpios = <&gpio_bank 4 GPIO_ACTIVE_LOW>;
	};
};

The #gpio-cells = <2> line says consumers write two numbers after the controller reference: the line offset and the flags. Line 4 of this bank is then what the button driver requests. Because the offsets are the hardware's own, the board file stays valid when another controller loads first and the global numbering changes, which is the whole reason for the descriptor interface.

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.