Linux Regulator Drivers: PMIC, Constraints and Consumers

Linux Regulator Drivers: PMIC, Constraints and Consumers

Share this post on:

The PMIC driver is one of the first we write when we bring up a board, because no device that takes a supply from its outputs can probe until it registers them. The boot firmware has already set the rails it needed, as described in our article on the boot flow, and Linux takes them over through the regulator framework.

This tutorial covers that framework from both sides, the driver of the PMIC and the drivers that use its outputs, with a fictional chip, the demo PMIC. Its seven outputs cover the common ways the framework describes an output, from a fixed voltage and linear steps to several linear ranges, a voltage table, a current regulator and a bypass mode. The registers of the chip are simulated in RAM behind regmap, so the two drivers build as out-of-tree modules and run on any Linux system. We tested them on Linux 6.19 in QEMU, with the procedure of the testing section; the complete sources are at the end of the article.

Contents
  1. How the Framework Is Organised
  2. The Demo PMIC
  3. Describing the Outputs: regulator_desc
  4. Operations and the regmap Helpers
  5. Probe: regmap and Registration
  6. Device Tree and Constraints
  7. Interrupts and Notifiers
  8. The Consumer Side
  9. Building and Testing in QEMU
  10. Inspecting Regulators at Run Time
  11. The Complete Sources
  12. Summing Up

How the Framework Is Organised

The regulator framework sits between two kinds of drivers. Producers register outputs, consumers request them, and the core in between decides what reaches the hardware.

Linux regulator framework: PMIC drivers and fixed regulators register outputs, the core applies constraints and reference counts, consumers request supplies
Figure 1. The regulator framework: producers register outputs, consumers request them, the core arbitrates.

The core holds the logic that no single driver can own:

  • Constraints, from the device tree: the voltage or current window an output may take, and the operations consumers may perform. A consumer bug cannot drive a rail outside the window that the board allows.
  • Reference counts: a rail shared by several devices stays on while at least one of them has it enabled.
  • Supply chains: the core enables the supply of an output before the output itself and, when the output declares a minimum dropout, raises the supply voltage to keep that headroom. needs more headroom.
  • Voltage arbitration: on a shared rail, the core picks a value that suits every consumer.
  • Notifiers: events such as an over-current or a voltage change reach every consumer that registered a notifier on the output.

Board rails that are always on, switched by a GPIO, or set to one of a few voltages by GPIOs need no driver of their own, since the generic regulator-fixed and regulator-gpio drivers take them from the device tree, and pwm-regulator does the same for a rail whose voltage follows a PWM output, as described in our article on PWM drivers. A PMIC with registers needs a driver, which is what the rest of this article builds.

The Demo PMIC

The demo PMIC has three switching regulators fed by a 5 V input, three LDOs fed by one of the bucks, and a current sink for an LED. Its registers are 8 bits wide.

The demo PMIC: a 5 V fixed rail feeds BUCK1, BUCK2 and BOOST; BUCK2 feeds LDO1, LDO2 and LDO3; ISINK is a current sink
Figure 2. The demo PMIC: seven outputs, fed by a 5 V board rail or by BUCK2.
OutputKindDescription in the driverRegister
BUCK1step-downtwo linear ranges, ramp rate, operating modes0x10 control, 0x11 voltage
BUCK2step-downone linear range, active discharge0x18 control, 0x19 voltage
BOOSTstep-upvoltage table: 5, 5.5, 9 and 12 V0x20
LDO1linearvoltage table from 1.2 to 3.3 V, 200 mV dropout0x28
LDO2linearfixed 3.0 V, 500 us start-up time0x29
LDO3linearfixed 1.8 V, bypass mode0x2a
ISINKcurrent sinkcurrent table from 5 to 30 mA0x30

Register 0x00 holds the chip ID, 0x93, and register 0x01 an interrupt status, one bit per output for over-current plus bit 7 for a temperature warning, cleared by writing 1. The topology of an output, buck, boost or LDO, does not matter to the framework. What matters is how its voltage or current is encoded in the registers, and that is what the next section describes.

Describing the Outputs: regulator_desc

Each output is described by a struct regulator_desc, constant, written once in the driver. Its fields give the name, the device tree node to match, the input supply, how the selector in the register maps to a voltage or a current, and where the enable bit sits. The fields shared by all outputs of the demo PMIC go in a macro:

#define DEMO_COMMON(_id, _name, _match, _supply, _ops)	
	.name		 = _name,				
	.of_match	 = _match,		
	.regulators_node = "regulators",		
	.supply_name	 = _supply,				
	.id		 = _id,					
	.ops		 = _ops,				
	.owner		 = THIS_MODULE

of_match and regulators_node let the core find the device tree node of each output by itself, as the device tree section shows. supply_name names the input of the output; the core looks in the PMIC node for that name followed by -supply, vin-buck1-supply for BUCK1, and builds the supply chain from it.

Fixed voltage

An output with a single voltage only needs fixed_uV and n_voltages = 1. LDO2 also declares how long it takes to settle, which the core waits after enabling it:

	[DEMO_LDO2] = {
		DEMO_COMMON(DEMO_LDO2, "LDO2", "ldo2", "vin-ldo2", &demo_fixed_ops),
		.type			= REGULATOR_VOLTAGE,
		.fixed_uV		= 3000000,
		.n_voltages		= 1,
		.enable_reg		= DEMO_LDO2_CTRL,
		.enable_mask		= DEMO_LDO_EN,
		.enable_time		= 500,	/* us before the output is usable */

Without fixed_uV, the core cannot know the voltage of an output that has no voltage callback, and regulator_get_voltage() would return the voltage of its supply, or an error when it has none.

Linear steps

When each selector adds the same step, min_uV and uV_step describe the whole output. BUCK2 goes from 1.8 V in 50 mV steps over 64 selectors, so up to 4.95 V:

	[DEMO_BUCK2] = {
		DEMO_COMMON(DEMO_BUCK2, "BUCK2", "buck2", "vin-buck2", &demo_buck2_ops),
		.type			= REGULATOR_VOLTAGE,
		.min_uV			= 1800000,
		.uV_step		= 50000,
		.n_voltages		= 64,
		.vsel_reg		= DEMO_BUCK2_VSEL,
		.vsel_mask		= DEMO_BUCK2_VSEL_MASK,

vsel_reg and vsel_mask tell the regmap helpers where the selector lives; the helpers shift the value by the position of the mask, so the selector can sit anywhere in the register.

Several linear ranges

Many PMICs use a fine step at low voltage and a coarser one above. BUCK1 does that, as figure 3 shows, and describes it with two linear_range entries:

BUCK1 voltage against selector: 12.5 mV steps from 0.6 V for selectors 0x00 to 0x3f, then 50 mV steps from 1.4 V up to 0x5f
Figure 3. BUCK1: fine steps up to 1.3875 V, coarser steps above 1.4 V.
/* BUCK1: 0.6 V to 1.3875 V in 12.5 mV steps, then 1.4 V to 2.95 V in 50 mV steps */
static const struct linear_range demo_buck1_ranges[] = {
	REGULATOR_LINEAR_RANGE(600000, 0x00, 0x3f, 12500),
	REGULATOR_LINEAR_RANGE(1400000, 0x40, 0x5f, 50000),
};

REGULATOR_LINEAR_RANGE() takes the voltage of the first selector, the first and last selectors, and the step. The descriptor sets n_voltages to 0x60, the total number of selectors, and points linear_ranges to the table.

Voltage table

When the values follow no rule, a table lists them by selector. LDO1 and BOOST use one:

static const unsigned int demo_ldo1_volt_table[] = {
	1200000, 1500000, 1800000, 2500000, 2800000, 3000000, 3300000,
};

LDO1 also sets min_dropout_uV to 200 mV, because it needs its input 200 mV above its output. When a consumer raises LDO1, the core raises BUCK2 to keep it at least 200 mV above LDO1, within the constraints of BUCK2; the test checks this.

Current regulators

A current regulator, such as the LED sink, uses REGULATOR_CURRENT as its type and a current table with its selector field:

	[DEMO_ISINK] = {
		DEMO_COMMON(DEMO_ISINK, "ISINK", "isink", NULL, &demo_isink_ops),
		.type			= REGULATOR_CURRENT,
		.curr_table		= demo_isink_curr_table,
		.n_current_limits	= ARRAY_SIZE(demo_isink_curr_table),
		.csel_reg		= DEMO_ISINK_CTRL,
		.csel_mask		= DEMO_ISINK_CSEL_MASK,
		.enable_reg		= DEMO_ISINK_CTRL,
		.enable_mask		= DEMO_ISINK_EN,

Its operations set and read a current limit instead of a voltage, and its constraints, in the device tree, are in microamps.

Bypass, ramp rate and active discharge

Three more features have their own fields. LDO3 can be bypassed, connecting its input straight to its output; bypass_reg and bypass_mask locate the switch. BUCK1 has a programmable ramp rate, given as a table in microvolts per microsecond:

/* BUCK1 ramp rates in uV/us, indexed by DEMO_BUCK1_RAMP_MASK */
static const unsigned int demo_buck1_ramp_table[] = { 25000, 12500, 6250, 3125 };

With ramp_reg, ramp_mask and that table, regulator_set_ramp_delay_regmap() programs the closest rate at or above the one requested in the device tree, and the core waits for the ramp after each voltage change. BUCK2, finally, can discharge its output through a resistor when it is turned off, described by the active_discharge_* fields.

Operations and the regmap Helpers

struct regulator_ops lists what an output can do. When the descriptor locates every field, the regmap helpers of the core do all the register work, and the operations of BUCK1 hold only the two mode functions written for this chip:

static const struct regulator_ops demo_buck1_ops = {
	.list_voltage		= regulator_list_voltage_linear_range,
	.map_voltage		= regulator_map_voltage_linear_range,
	.get_voltage_sel	= regulator_get_voltage_sel_regmap,
	.set_voltage_sel	= regulator_set_voltage_sel_regmap,
	.set_voltage_time_sel	= regulator_set_voltage_time_sel,
	.set_ramp_delay		= regulator_set_ramp_delay_regmap,
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
	.set_mode		= demo_buck1_set_mode,
	.get_mode		= demo_buck1_get_mode,
};

Each kind of description has its pair of helpers to list and map voltages, _linear for steps, _linear_range for ranges, _table with regulator_map_voltage_ascend() for sorted tables. regulator_set_voltage_time_sel() computes the settling time from the ramp rate. The current sink uses regulator_set_current_limit_regmap() and its getter, and LDO3 the bypass helpers.

Operating modes are the part that has no helper, because PMICs encode them in their own way. BUCK1 can run in automatic mode or in forced PWM, which gives lower ripple at light load:

static int demo_buck1_set_mode(struct regulator_dev *rdev, unsigned int mode)
{
	unsigned int val;

	switch (mode) {
	case REGULATOR_MODE_FAST:
		val = DEMO_BUCK1_FPWM;
		break;
	case REGULATOR_MODE_NORMAL:
		val = 0;
		break;
	default:
		return -EINVAL;
	}

	return regmap_update_bits(rdev_get_regmap(rdev), DEMO_BUCK1_CTRL,
				  DEMO_BUCK1_FPWM, val);
}

REGULATOR_MODE_FAST and REGULATOR_MODE_NORMAL are the generic modes of the framework. The device tree uses numbers of the chip instead, and of_map_mode in the descriptor translates them:

static unsigned int demo_buck1_of_map_mode(unsigned int dt_mode)
{
	switch (dt_mode) {
	case DEMO_DT_MODE_AUTO:
		return REGULATOR_MODE_NORMAL;
	case DEMO_DT_MODE_FPWM:
		return REGULATOR_MODE_FAST;
	default:
		return REGULATOR_MODE_INVALID;
	}
}

A real PMIC binding puts these numbers in a header under include/dt-bindings/regulator/, shared by the driver and the device tree.

Probe: regmap and Registration

Probe creates the regmap, checks the chip ID and registers the seven outputs. On the demo PMIC, the regmap reads and writes an array instead of a bus:

static const struct regmap_config demo_regmap_config = {
	.reg_bits = 8,
	.val_bits = 8,
	.max_register = DEMO_MAX_REG,
	.reg_read = demo_hw_read,
	.reg_write = demo_hw_write,
};

The two callbacks, demo_hw_read() and demo_hw_write(), are the simulated chip; the write callback implements the write-1-to-clear behaviour of the interrupt status. Registration then takes one regulator_config for all outputs:

	config.dev = dev;
	config.regmap = pmic->regmap;
	config.driver_data = pmic;

	for (i = 0; i < DEMO_NUM_REGULATORS; i++) {
		pmic->rdev[i] = devm_regulator_register(dev, &demo_regulators[i], &config);
		if (IS_ERR(pmic->rdev[i]))
			return dev_err_probe(dev, PTR_ERR(pmic->rdev[i]),
					     "failed to register %sn",
					     demo_regulators[i].name);
	}

config.dev gives the core the device whose node contains regulators. config.init_data stays empty, so the core reads the constraints from the device tree. config.ena_gpiod, unused here, would hand the core a GPIO that enables an output, for chips with enable pins.

For a real I2C PMIC, the driver becomes an i2c_driver, and apart from the probe prototype and the interrupt number, taken from i2c->irq, only the regmap changes. The simulation callbacks go, and the bus provides the accesses:

-static int demo_pmic_probe(struct platform_device *pdev)
+static int demo_pmic_probe(struct i2c_client *i2c)
 {
-	struct device *dev = &pdev->dev;
+	struct device *dev = &i2c->dev;
 [...]
-	pmic->regmap = devm_regmap_init(dev, NULL, pmic, &demo_regmap_config);
+	pmic->regmap = devm_regmap_init_i2c(i2c, &demo_regmap_config);

The regmap_config then drops reg_read and reg_write, and usually gains a cache, REGCACHE_MAPLE, with a volatile_reg callback for the interrupt status, so that reads of the other registers do not go to the bus.

Device Tree and Constraints

The PMIC node holds the input supplies of its outputs and a regulators node with one child per output, named as in of_match. The 5 V input is a regulator-fixed node:

	vin_5v: regulator-vin {
		compatible = "regulator-fixed";
		regulator-name = "vin-5v";
		regulator-min-microvolt = <5000000>;
		regulator-max-microvolt = <5000000>;
		regulator-always-on;
	};

	pmic {
		compatible = "labcsmart,demo-pmic";

		/* Inputs of the outputs: the 5 V rail, or BUCK2 for the LDOs */
		vin-buck1-supply = <&vin_5v>;
		vin-buck2-supply = <&vin_5v>;
		vin-boost-supply = <&vin_5v>;
		vin-ldo1-supply = <&buck2>;
		vin-ldo2-supply = <&buck2>;
		vin-ldo3-supply = <&buck2>;

		regulators {
			buck1: buck1 {
				regulator-name = "vdd-core";
				regulator-min-microvolt = <800000>;
				regulator-max-microvolt = <1100000>;
				regulator-ramp-delay = <12500>;
				regulator-initial-mode = <0>;		/* auto */
				regulator-allowed-modes = <0 1>;	/* auto, forced PWM */
			};

			buck2: buck2 {
				regulator-name = "vdd-3v3";
				regulator-min-microvolt = <3300000>;
				regulator-max-microvolt = <3600000>;
				regulator-always-on;
				regulator-active-discharge = <1>;
			};

			boost {
				regulator-name = "vbus-5v";
				regulator-min-microvolt = <5000000>;
				regulator-max-microvolt = <5000000>;
			};

			ldo1: ldo1 {
				regulator-name = "vdd-io";
				regulator-min-microvolt = <1800000>;
				regulator-max-microvolt = <3300000>;
			};

			ldo2: ldo2 {
				regulator-name = "vref-3v0";
			};

			ldo3: ldo3 {
				regulator-name = "vdd-bias";
				regulator-allow-bypass;
			};
			[...]

The core turns these properties into the struct regulation_constraints of each output. Some of the rules are implicit:

  • Different regulator-min-microvolt and regulator-max-microvolt allow consumers to change the voltage. Equal values fix it, and the core sets it at registration.
  • Every output may be switched on and off by its consumers unless it has regulator-always-on.
  • regulator-allow-bypass, regulator-allowed-modes and different regulator-min-microamp and regulator-max-microamp values each allow the matching operation.
  • At registration, a voltage outside the window is brought into it. BUCK1 starts at 1.2 V after power-on, above its 1.1 V limit, and the core logs vdd-core: Bringing 1200000uV into 1100000-1100000uV as it lowers it.

The LDOs are fed by BUCK2, an output of the same PMIC, so the PMIC node points to one of its own children. fw_devlink detects that cycle and logs Fixed dependency cycle(s); the message is harmless, and many in-tree PMIC device trees produce it.

Interrupts and Notifiers

A PMIC reports faults through an interrupt line. The driver reads the status, forwards each fault to the consumers of the output concerned with regulator_notifier_call_chain(), and clears the bits it handled:

static irqreturn_t demo_pmic_irq(int irq, void *data)
{
	struct demo_pmic *pmic = data;
	unsigned int status;
	int i;

	if (regmap_read(pmic->regmap, DEMO_INT_STATUS, &status) || !status)
		return IRQ_NONE;

	for (i = 0; i < DEMO_NUM_REGULATORS; i++) {
		if (status & BIT(i))
			regulator_notifier_call_chain(pmic->rdev[i],
						      REGULATOR_EVENT_OVER_CURRENT,
						      NULL);
		if (status & DEMO_INT_TEMP_WARN)
			regulator_notifier_call_chain(pmic->rdev[i],
						      REGULATOR_EVENT_OVER_TEMP_WARN,
						      NULL);
	}

	regmap_write(pmic->regmap, DEMO_INT_STATUS, status);
	return IRQ_HANDLED;
}

On real hardware, probe requests the line with devm_request_threaded_irq(). The handler reads the status over I2C or SPI, and those accesses may sleep, which is not allowed in hard interrupt context. The demo PMIC has no line, so a debugfs file, /sys/kernel/debug/pmic/inject_irq, sets status bits and calls the same handler. For chips with many fault types, devm_regulator_irq_helper() provides the notification and the disabling and re-enabling of the interrupt in a generic way, while the driver supplies a callback that reads the status and maps it to events.

The Consumer Side

The demo consumer is a platform driver that takes the supplies listed in its node and exposes them in sysfs for the tests. Two instances share BUCK1; the first also uses four other outputs:

	consumer-a {
		compatible = "labcsmart,demo-consumer";
		vcore-supply = <&buck1>;
		vio-supply = <&ldo1>;
		vref-supply = <&ldo2>;
		vbias-supply = <&ldo3>;
		led-supply = <&isink>;
	};

	consumer-b {
		compatible = "labcsmart,demo-consumer";
		vcore-supply = <&buck1>;
	};

Figure 4 shows how the core resolves a supply name into an output.

A consumer asking for vio follows the vio-supply phandle to the ldo1 node and its registered regulator, or gets a dummy or a probe deferral
Figure 4. From a supply name in the consumer driver to the regulator registered by the PMIC driver.

Getting a supply

devm_regulator_get() appends -supply to the name and follows the phandle. When the property is missing, it returns a dummy regulator, on which enable and disable succeed but voltage calls fail, so that drivers keep working on boards that do not describe the supply. A supply that may truly be absent is requested with devm_regulator_get_optional(), which returns -ENODEV instead:

/* Optional supply: NULL when absent, error pointer on a real error */
static struct regulator *demo_get_optional(struct device *dev, const char *id)
{
	struct regulator *r = devm_regulator_get_optional(dev, id);

	if (IS_ERR(r) && PTR_ERR(r) == -ENODEV) {
		dev_info(dev, "no %s supplyn", id);
		return NULL;
	}
	return r;
}

When the supply is described in the device tree but its regulator is not registered yet, devm_regulator_get() returns -EPROBE_DEFER, and the driver core retries the probe later. The consumer passes it up through dev_err_probe(), which keeps the deferral silent.

Enabling and reference counting

regulator_enable() and regulator_disable() must stay balanced for each handle. The core counts enables per handle and per output, and switches the output off only when no consumer keeps it on. For a supply enabled for the whole life of the device, two helpers save the bookkeeping: devm_regulator_get_enable(), and devm_regulator_get_enable_read_voltage(), which also returns the voltage, the usual case of a reference for an ADC:

	ret = devm_regulator_get_enable_read_voltage(dev, "vref");
	if (ret >= 0)
		c->vref_uV = ret;
	else if (ret == -ENODEV)
		dev_info(dev, "no vref supplyn");
	else
		return dev_err_probe(dev, ret, "cannot read vrefn");

For several supplies at once, devm_regulator_bulk_get_enable() does the same on an array of names.

Setting a voltage on a shared rail

regulator_set_voltage() takes a window of acceptable voltages. On a shared rail, the core keeps the window of each consumer and programs the lowest voltage that fits in all of them and in the constraints.

Voltage windows of the constraints and of two consumers on BUCK1; the core programs 900 mV, the only value they all accept
Figure 5. Two consumers and the constraints of BUCK1: the core programs the only voltage they all accept.

A request outside the constraints fails with -EINVAL and leaves the rail as it was. Before asking for a voltage that the output may not provide, such as a value missing from a table, a consumer can check it with regulator_is_supported_voltage():

	if (!regulator_is_supported_voltage(c->vio, uV, uV))
		return -EINVAL;

	ret = regulator_set_voltage(c->vio, uV, uV);

The MMC core does exactly this when it switches the I/O voltage of an SD card from 3.3 V to 1.8 V.

Current, bypass and notifications

A current regulator takes a window too, through regulator_set_current_limit(); the regmap helper picks the highest value of the table inside it. regulator_allow_bypass() only expresses consent, and the core puts the output in bypass once every consumer of it has allowed it. Notifications arrive through a notifier block:

static int demo_vcore_event(struct notifier_block *nb, unsigned long event,
			    void *data)
{
	struct demo_consumer *c = container_of(nb, struct demo_consumer, nb);

	if (event & REGULATOR_EVENT_OVER_CURRENT)
		dev_warn(c->dev, "vcore: over-currentn");
	if (event & REGULATOR_EVENT_OVER_TEMP_WARN)
		dev_warn(c->dev, "vcore: PMIC temperature warningn");
	if (event & REGULATOR_EVENT_PRE_VOLTAGE_CHANGE) {
		struct pre_voltage_change_data *v = data;

		dev_info(c->dev, "vcore: changing from %lu uV to %lu-%lu uVn",
			 v->old_uV, v->min_uV, v->max_uV);
	}
	if (event & REGULATOR_EVENT_DISABLE)
		dev_info(c->dev, "vcore: disabledn");

	return NOTIFY_OK;
}

devm_regulator_register_notifier() attaches it to the handle. The callback runs in the context of whoever sent the event, which is the interrupt thread of the PMIC for a fault and the caller of regulator_set_voltage() for a voltage change.

Building and Testing in QEMU

Both modules build against any kernel tree prepared for modules, with this Makefile:

# Out-of-tree build: make KDIR=/path/to/kernel/build
obj-m := demo-pmic.o demo-consumer.o

KDIR ?= /lib/modules/$(shell uname -r)/build

all:
	$(MAKE) -C $(KDIR) M=$(CURDIR) modules

clean:
	$(MAKE) -C $(KDIR) M=$(CURDIR) clean

We tested them on Linux 6.19 with QEMU’s arm64 virt machine, whose device tree we extended with the nodes above. The procedure, on a host with an aarch64 cross-compiler, QEMU and a static arm64 BusyBox:

# 1. Kernel: arm64 defconfig, with regulators and debugfs
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- O=build defconfig
./scripts/config --file build/.config -e REGULATOR -e REGULATOR_FIXED_VOLTAGE -e DEBUG_FS
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- O=build olddefconfig
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- O=build -j$(nproc) Image modules

# 2. The two modules
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- KDIR=$PWD/build -C demo

# 3. Device tree: the virt machine's own, plus the demo nodes
qemu-system-aarch64 -M virt,dumpdtb=virt.dtb -cpu cortex-a57 -m 512 -nographic
dtc -I dtb -O dts -o virt.dts virt.dtb
cat virt.dts demo/demo-pmic.dtsi > demo.dts
dtc -I dts -O dtb -o demo.dtb demo.dts

# 4. initramfs: BusyBox, the modules, test.sh, and an init that runs it
mkdir -p rootfs/bin rootfs/proc rootfs/sys rootfs/dev rootfs/lib/modules
cp busybox rootfs/bin/
cp demo/*.ko rootfs/lib/modules/
cp demo/test.sh rootfs/
cat > rootfs/init << 'EOF'
#!/bin/busybox sh
/bin/busybox --install -s /bin
mount -t proc proc /proc
mount -t sysfs sys /sys
mount -t devtmpfs dev /dev
mount -t debugfs none /sys/kernel/debug
sh /test.sh
poweroff -f
EOF
chmod +x rootfs/init
(cd rootfs && find . | cpio -o -H newc | gzip) > initramfs.cpio.gz

# 5. Boot
qemu-system-aarch64 -M virt -cpu cortex-a57 -m 512 -nographic -no-reboot 
    -kernel build/arch/arm64/boot/Image -dtb demo.dtb -initrd initramfs.cpio.gz 
    -append "console=ttyAMA0 rdinit=/init quiet"

On a real board, the modules load the same way, with the nodes added to its device tree or loaded as an overlay. The test script loads both modules, then checks each behaviour through the sysfs files of the consumers and of the regulators. Its output on 6.19:

PASS vref seen by consumer-a: 3000000
PASS vdd-core users: 2
PASS vdd-core in the common window: 1000000
PASS vdd-core, windows touching at 0.9 V: 900000
[    2.565335] vdd-core: unsupportable voltage range: 1150000-1100000uV
PASS request above the 1.1 V constraint: refused
PASS ramp rate bits (12.5 mV/us) and enable in BUCK1_CTRL: 81
PASS vdd-core mode from regulator-initial-mode: normal
PASS vdd-io at 1.8 V: 1800000
PASS vdd-io at 3.3 V: 3300000
PASS vdd-3v3 raised for the 200 mV dropout: 3500000
PASS 2.0 V, not in the table: refused
PASS vdd-bias bypass before: disabled
PASS vdd-bias bypass allowed by its only consumer: enabled
PASS led-sink at 15 mA: 15000
PASS led-sink capped by the 20 mA constraint: 20000
PASS over-current on BUCK1 reaches both consumers: 2
PASS INT_STATUS cleared by the handler: 00
PASS vdd-core still on, consumer-b holds it: enabled
PASS vdd-core off once both released: disabled
ALL TESTS PASSED

The ramp check reads the PMIC register directly, through the debugfs files that regmap creates for every map under /sys/kernel/debug/regmap/, which, for a map without a cache like this one, is also the quickest way to compare what the core believes with what the chip holds.

Inspecting Regulators at Run Time

Each output appears in /sys/class/regulator/regulator.N/, with read-only attributes: name, type, state, microvolts or microamps, num_users, the constraint window, opmode, bypass and the suspend settings. The whole tree is in /sys/kernel/debug/regulator/regulator_summary, here at the end of the test:

 regulator                      use open bypass  opmode voltage current     min     max
---------------------------------------------------------------------------------------
 regulator-dummy                  1    0      0 unknown     0mV     0mA     0mV     0mV
 vin-5v                           2    3      0 unknown  5000mV     0mA  5000mV  5000mV
    vdd-core                      0    2      0  normal   900mV     0mA   800mV  1100mV
       consumer-b-vcore           0                                 0mA   800mV   900mV
       consumer-a-vcore           0                                 0mA   900mV  1100mV
    vdd-3v3                       4    3      0 unknown  3500mV     0mA  3300mV  3600mV
       vdd-io                     1    1      0 unknown  3300mV     0mA  1800mV  3300mV
          consumer-a-vio          1                                 0mA  3300mV  3300mV
       vref-3v0                   1    1      0 unknown  3000mV     0mA     0mV     0mV
          consumer-a-vref         1                                 0mA     0mV     0mV
       vdd-bias                   1    1      1 unknown  3500mV     0mA     0mV     0mV
          consumer-a-vbias        1                                 0mA     0mV     0mV
    vbus-5v                       0    0      0 unknown  5000mV     0mA  5000mV  5000mV
 led-sink                         1    1      0 unknown     0mV    20mA     5mA    20mA

The summary shows the supply tree, and under each output the window that each consumer asked for. Two details stand out. vdd-bias, in bypass, reports 3500 mV, the voltage of its supply, and vdd-core reports its last voltage while disabled. A use count higher than expected is the usual sign of an unbalanced regulator_enable(), and a consumer missing from that list never got the supply, or got the dummy regulator.

The Complete Sources

The two drivers, the device tree nodes and the test script, as tested; checkpatch reports nothing on the drivers, and they build without warnings at W=1.

demo-pmic.c
// SPDX-License-Identifier: GPL-2.0
/*
 * Regulator driver for a fictional PMIC, the "demo PMIC".
 *
 * The chip has seven outputs that cover the ways the regulator framework
 * describes an output:
 *
 *   BUCK1  step-down, two linear voltage ranges, ramp rate, operating modes
 *   BUCK2  step-down, one linear range, active discharge
 *   BOOST  step-up, voltage table
 *   LDO1   linear regulator, voltage table, fed by BUCK2 with a dropout
 *   LDO2   linear regulator, fixed voltage, start-up time
 *   LDO3   linear regulator, fixed voltage, bypass mode
 *   ISINK  current sink, current table
 *
 * The registers of the chip are simulated in RAM, behind regmap, so that
 * the driver runs on any Linux system. On real hardware, the regmap comes
 * from the bus instead (devm_regmap_init_i2c() for an I2C PMIC) and the
 * rest of the driver stays the same.
 */

#include <linux/bits.h>
#include <linux/debugfs.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>

/* Register map */
#define DEMO_CHIP_ID		0x00
#define DEMO_INT_STATUS		0x01	/* write 1 to clear */
#define DEMO_INT_MASK		0x02
#define DEMO_BUCK1_CTRL		0x10
#define DEMO_BUCK1_VSEL		0x11
#define DEMO_BUCK2_CTRL		0x18
#define DEMO_BUCK2_VSEL		0x19
#define DEMO_BOOST_CTRL		0x20
#define DEMO_LDO1_CTRL		0x28
#define DEMO_LDO2_CTRL		0x29
#define DEMO_LDO3_CTRL		0x2a
#define DEMO_ISINK_CTRL		0x30
#define DEMO_MAX_REG		0x3f

#define DEMO_CHIP_ID_VALUE	0x93

#define DEMO_BUCK_EN		BIT(7)
#define DEMO_BUCK1_FPWM		BIT(6)
#define DEMO_BUCK1_RAMP_MASK	GENMASK(1, 0)
#define DEMO_BUCK1_VSEL_MASK	GENMASK(6, 0)
#define DEMO_BUCK2_DISCHARGE	BIT(4)
#define DEMO_BUCK2_VSEL_MASK	GENMASK(5, 0)
#define DEMO_BOOST_VSEL_MASK	GENMASK(1, 0)
#define DEMO_LDO_EN		BIT(0)
#define DEMO_LDO1_VSEL_MASK	GENMASK(3, 1)
#define DEMO_LDO3_BYPASS	BIT(1)
#define DEMO_ISINK_EN		BIT(0)
#define DEMO_ISINK_CSEL_MASK	GENMASK(6, 4)

/* Interrupt status bits, one per output plus a thermal warning */
#define DEMO_INT_TEMP_WARN	BIT(7)

/* Values of regulator-initial-mode and regulator-allowed-modes in DT */
#define DEMO_DT_MODE_AUTO	0
#define DEMO_DT_MODE_FPWM	1

enum demo_id {
	DEMO_BUCK1, DEMO_BUCK2, DEMO_BOOST, DEMO_LDO1, DEMO_LDO2, DEMO_LDO3,
	DEMO_ISINK, DEMO_NUM_REGULATORS,
};

struct demo_pmic {
	struct device *dev;
	struct regmap *regmap;
	struct regulator_dev *rdev[DEMO_NUM_REGULATORS];
	u8 regs[DEMO_MAX_REG + 1];	/* the simulated chip */
};

/* ------------------------------------------------------------------ */
/* Simulated hardware: regmap callbacks on a register file in RAM      */
/* ------------------------------------------------------------------ */

static int demo_hw_read(void *context, unsigned int reg, unsigned int *val)
{
	struct demo_pmic *pmic = context;

	*val = pmic->regs[reg];
	return 0;
}

static int demo_hw_write(void *context, unsigned int reg, unsigned int val)
{
	struct demo_pmic *pmic = context;

	if (reg == DEMO_CHIP_ID)
		return -EIO;			/* read-only */
	if (reg == DEMO_INT_STATUS)
		pmic->regs[reg] &= ~val;	/* write 1 to clear */
	else
		pmic->regs[reg] = val;
	return 0;
}

static const struct regmap_config demo_regmap_config = {
	.reg_bits = 8,
	.val_bits = 8,
	.max_register = DEMO_MAX_REG,
	.reg_read = demo_hw_read,
	.reg_write = demo_hw_write,
};

/* ------------------------------------------------------------------ */
/* Voltage and current descriptions                                    */
/* ------------------------------------------------------------------ */

/* BUCK1: 0.6 V to 1.3875 V in 12.5 mV steps, then 1.4 V to 2.95 V in 50 mV steps */
static const struct linear_range demo_buck1_ranges[] = {
	REGULATOR_LINEAR_RANGE(600000, 0x00, 0x3f, 12500),
	REGULATOR_LINEAR_RANGE(1400000, 0x40, 0x5f, 50000),
};

/* BUCK1 ramp rates in uV/us, indexed by DEMO_BUCK1_RAMP_MASK */
static const unsigned int demo_buck1_ramp_table[] = { 25000, 12500, 6250, 3125 };

static const unsigned int demo_boost_volt_table[] = {
	5000000, 5500000, 9000000, 12000000,
};

static const unsigned int demo_ldo1_volt_table[] = {
	1200000, 1500000, 1800000, 2500000, 2800000, 3000000, 3300000,
};

/* ISINK current limits in uA, indexed by DEMO_ISINK_CSEL_MASK */
static const unsigned int demo_isink_curr_table[] = {
	5000, 10000, 15000, 20000, 25000, 30000,
};

/* ------------------------------------------------------------------ */
/* Operations                                                          */
/* ------------------------------------------------------------------ */

static unsigned int demo_buck1_of_map_mode(unsigned int dt_mode)
{
	switch (dt_mode) {
	case DEMO_DT_MODE_AUTO:
		return REGULATOR_MODE_NORMAL;
	case DEMO_DT_MODE_FPWM:
		return REGULATOR_MODE_FAST;
	default:
		return REGULATOR_MODE_INVALID;
	}
}

static int demo_buck1_set_mode(struct regulator_dev *rdev, unsigned int mode)
{
	unsigned int val;

	switch (mode) {
	case REGULATOR_MODE_FAST:
		val = DEMO_BUCK1_FPWM;
		break;
	case REGULATOR_MODE_NORMAL:
		val = 0;
		break;
	default:
		return -EINVAL;
	}

	return regmap_update_bits(rdev_get_regmap(rdev), DEMO_BUCK1_CTRL,
				  DEMO_BUCK1_FPWM, val);
}

static unsigned int demo_buck1_get_mode(struct regulator_dev *rdev)
{
	unsigned int val;
	int ret;

	ret = regmap_read(rdev_get_regmap(rdev), DEMO_BUCK1_CTRL, &val);
	if (ret)
		return REGULATOR_MODE_INVALID;

	return (val & DEMO_BUCK1_FPWM) ? REGULATOR_MODE_FAST : REGULATOR_MODE_NORMAL;
}

static const struct regulator_ops demo_buck1_ops = {
	.list_voltage		= regulator_list_voltage_linear_range,
	.map_voltage		= regulator_map_voltage_linear_range,
	.get_voltage_sel	= regulator_get_voltage_sel_regmap,
	.set_voltage_sel	= regulator_set_voltage_sel_regmap,
	.set_voltage_time_sel	= regulator_set_voltage_time_sel,
	.set_ramp_delay		= regulator_set_ramp_delay_regmap,
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
	.set_mode		= demo_buck1_set_mode,
	.get_mode		= demo_buck1_get_mode,
};

static const struct regulator_ops demo_buck2_ops = {
	.list_voltage		= regulator_list_voltage_linear,
	.map_voltage		= regulator_map_voltage_linear,
	.get_voltage_sel	= regulator_get_voltage_sel_regmap,
	.set_voltage_sel	= regulator_set_voltage_sel_regmap,
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
	.set_active_discharge	= regulator_set_active_discharge_regmap,
};

static const struct regulator_ops demo_table_ops = {
	.list_voltage		= regulator_list_voltage_table,
	.map_voltage		= regulator_map_voltage_ascend,
	.get_voltage_sel	= regulator_get_voltage_sel_regmap,
	.set_voltage_sel	= regulator_set_voltage_sel_regmap,
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
};

static const struct regulator_ops demo_fixed_ops = {
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
};

static const struct regulator_ops demo_bypass_ops = {
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
	.set_bypass		= regulator_set_bypass_regmap,
	.get_bypass		= regulator_get_bypass_regmap,
};

static const struct regulator_ops demo_isink_ops = {
	.enable			= regulator_enable_regmap,
	.disable		= regulator_disable_regmap,
	.is_enabled		= regulator_is_enabled_regmap,
	.set_current_limit	= regulator_set_current_limit_regmap,
	.get_current_limit	= regulator_get_current_limit_regmap,
};

/* ------------------------------------------------------------------ */
/* Descriptions of the seven outputs                                   */
/* ------------------------------------------------------------------ */

#define DEMO_COMMON(_id, _name, _match, _supply, _ops)	
	.name		 = _name,				
	.of_match	 = _match,		
	.regulators_node = "regulators",		
	.supply_name	 = _supply,				
	.id		 = _id,					
	.ops		 = _ops,				
	.owner		 = THIS_MODULE

static const struct regulator_desc demo_regulators[DEMO_NUM_REGULATORS] = {
	[DEMO_BUCK1] = {
		DEMO_COMMON(DEMO_BUCK1, "BUCK1", "buck1", "vin-buck1", &demo_buck1_ops),
		.type			= REGULATOR_VOLTAGE,
		.linear_ranges		= demo_buck1_ranges,
		.n_linear_ranges	= ARRAY_SIZE(demo_buck1_ranges),
		.n_voltages		= 0x60,
		.vsel_reg		= DEMO_BUCK1_VSEL,
		.vsel_mask		= DEMO_BUCK1_VSEL_MASK,
		.enable_reg		= DEMO_BUCK1_CTRL,
		.enable_mask		= DEMO_BUCK_EN,
		.ramp_reg		= DEMO_BUCK1_CTRL,
		.ramp_mask		= DEMO_BUCK1_RAMP_MASK,
		.ramp_delay_table	= demo_buck1_ramp_table,
		.n_ramp_values		= ARRAY_SIZE(demo_buck1_ramp_table),
		.of_map_mode		= demo_buck1_of_map_mode,
	},
	[DEMO_BUCK2] = {
		DEMO_COMMON(DEMO_BUCK2, "BUCK2", "buck2", "vin-buck2", &demo_buck2_ops),
		.type			= REGULATOR_VOLTAGE,
		.min_uV			= 1800000,
		.uV_step		= 50000,
		.n_voltages		= 64,
		.vsel_reg		= DEMO_BUCK2_VSEL,
		.vsel_mask		= DEMO_BUCK2_VSEL_MASK,
		.enable_reg		= DEMO_BUCK2_CTRL,
		.enable_mask		= DEMO_BUCK_EN,
		.active_discharge_reg	= DEMO_BUCK2_CTRL,
		.active_discharge_mask	= DEMO_BUCK2_DISCHARGE,
		.active_discharge_on	= DEMO_BUCK2_DISCHARGE,
		.active_discharge_off	= 0,
	},
	[DEMO_BOOST] = {
		DEMO_COMMON(DEMO_BOOST, "BOOST", "boost", "vin-boost", &demo_table_ops),
		.type			= REGULATOR_VOLTAGE,
		.volt_table		= demo_boost_volt_table,
		.n_voltages		= ARRAY_SIZE(demo_boost_volt_table),
		.vsel_reg		= DEMO_BOOST_CTRL,
		.vsel_mask		= DEMO_BOOST_VSEL_MASK,
		.enable_reg		= DEMO_BOOST_CTRL,
		.enable_mask		= DEMO_BUCK_EN,
	},
	[DEMO_LDO1] = {
		DEMO_COMMON(DEMO_LDO1, "LDO1", "ldo1", "vin-ldo1", &demo_table_ops),
		.type			= REGULATOR_VOLTAGE,
		.volt_table		= demo_ldo1_volt_table,
		.n_voltages		= ARRAY_SIZE(demo_ldo1_volt_table),
		.vsel_reg		= DEMO_LDO1_CTRL,
		.vsel_mask		= DEMO_LDO1_VSEL_MASK,
		.enable_reg		= DEMO_LDO1_CTRL,
		.enable_mask		= DEMO_LDO_EN,
		.min_dropout_uV		= 200000,
	},
	[DEMO_LDO2] = {
		DEMO_COMMON(DEMO_LDO2, "LDO2", "ldo2", "vin-ldo2", &demo_fixed_ops),
		.type			= REGULATOR_VOLTAGE,
		.fixed_uV		= 3000000,
		.n_voltages		= 1,
		.enable_reg		= DEMO_LDO2_CTRL,
		.enable_mask		= DEMO_LDO_EN,
		.enable_time		= 500,	/* us before the output is usable */
	},
	[DEMO_LDO3] = {
		DEMO_COMMON(DEMO_LDO3, "LDO3", "ldo3", "vin-ldo3", &demo_bypass_ops),
		.type			= REGULATOR_VOLTAGE,
		.fixed_uV		= 1800000,
		.n_voltages		= 1,
		.enable_reg		= DEMO_LDO3_CTRL,
		.enable_mask		= DEMO_LDO_EN,
		.bypass_reg		= DEMO_LDO3_CTRL,
		.bypass_mask		= DEMO_LDO3_BYPASS,
		.bypass_val_on		= DEMO_LDO3_BYPASS,
		.bypass_val_off		= 0,
	},
	[DEMO_ISINK] = {
		DEMO_COMMON(DEMO_ISINK, "ISINK", "isink", NULL, &demo_isink_ops),
		.type			= REGULATOR_CURRENT,
		.curr_table		= demo_isink_curr_table,
		.n_current_limits	= ARRAY_SIZE(demo_isink_curr_table),
		.csel_reg		= DEMO_ISINK_CTRL,
		.csel_mask		= DEMO_ISINK_CSEL_MASK,
		.enable_reg		= DEMO_ISINK_CTRL,
		.enable_mask		= DEMO_ISINK_EN,
	},
};

/* ------------------------------------------------------------------ */
/* Interrupts: over-current per output, thermal warning for all        */
/* ------------------------------------------------------------------ */

static irqreturn_t demo_pmic_irq(int irq, void *data)
{
	struct demo_pmic *pmic = data;
	unsigned int status;
	int i;

	if (regmap_read(pmic->regmap, DEMO_INT_STATUS, &status) || !status)
		return IRQ_NONE;

	for (i = 0; i < DEMO_NUM_REGULATORS; i++) {
		if (status & BIT(i))
			regulator_notifier_call_chain(pmic->rdev[i],
						      REGULATOR_EVENT_OVER_CURRENT,
						      NULL);
		if (status & DEMO_INT_TEMP_WARN)
			regulator_notifier_call_chain(pmic->rdev[i],
						      REGULATOR_EVENT_OVER_TEMP_WARN,
						      NULL);
	}

	regmap_write(pmic->regmap, DEMO_INT_STATUS, status);
	return IRQ_HANDLED;
}

/*
 * Simulation only: writing a status value to debugfs raises the interrupt,
 * as the chip would on its IRQ line.
 */
static int demo_inject_set(void *data, u64 val)
{
	struct demo_pmic *pmic = data;

	pmic->regs[DEMO_INT_STATUS] |= val & 0xff;
	demo_pmic_irq(0, pmic);
	return 0;
}
DEFINE_DEBUGFS_ATTRIBUTE(demo_inject_fops, NULL, demo_inject_set, "%llun");

static void demo_pmic_debugfs_remove(void *data)
{
	debugfs_remove_recursive(data);
}

/* ------------------------------------------------------------------ */
/* Probe                                                               */
/* ------------------------------------------------------------------ */

static void demo_pmic_power_on_defaults(struct demo_pmic *pmic)
{
	/* What the simulated chip holds after power-on */
	pmic->regs[DEMO_CHIP_ID] = DEMO_CHIP_ID_VALUE;
	pmic->regs[DEMO_INT_MASK] = 0xff;
	pmic->regs[DEMO_BUCK1_VSEL] = 0x30;			/* 1.2 V */
	pmic->regs[DEMO_BUCK2_CTRL] = DEMO_BUCK_EN;		/* on */
	pmic->regs[DEMO_BUCK2_VSEL] = 0x1e;			/* 3.3 V */
	pmic->regs[DEMO_LDO1_CTRL] = 6 << 1;			/* 3.3 V */
}

static int demo_pmic_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct regulator_config config = { };
	struct demo_pmic *pmic;
	struct dentry *dir;
	unsigned int id;
	int i, irq, ret;

	pmic = devm_kzalloc(dev, sizeof(*pmic), GFP_KERNEL);
	if (!pmic)
		return -ENOMEM;
	pmic->dev = dev;
	demo_pmic_power_on_defaults(pmic);

	pmic->regmap = devm_regmap_init(dev, NULL, pmic, &demo_regmap_config);
	if (IS_ERR(pmic->regmap))
		return dev_err_probe(dev, PTR_ERR(pmic->regmap), "regmap init failedn");

	ret = regmap_read(pmic->regmap, DEMO_CHIP_ID, &id);
	if (ret)
		return dev_err_probe(dev, ret, "cannot read chip IDn");
	if (id != DEMO_CHIP_ID_VALUE)
		return dev_err_probe(dev, -ENODEV, "unexpected chip ID 0x%02xn", id);

	config.dev = dev;
	config.regmap = pmic->regmap;
	config.driver_data = pmic;

	for (i = 0; i < DEMO_NUM_REGULATORS; i++) {
		pmic->rdev[i] = devm_regulator_register(dev, &demo_regulators[i], &config);
		if (IS_ERR(pmic->rdev[i]))
			return dev_err_probe(dev, PTR_ERR(pmic->rdev[i]),
					     "failed to register %sn",
					     demo_regulators[i].name);
	}

	/* Unmask the interrupts of the outputs and the thermal warning */
	regmap_write(pmic->regmap, DEMO_INT_MASK, 0);

	irq = platform_get_irq_optional(pdev, 0);
	if (irq > 0) {
		ret = devm_request_threaded_irq(dev, irq, NULL, demo_pmic_irq,
						IRQF_ONESHOT, dev_name(dev), pmic);
		if (ret)
			return dev_err_probe(dev, ret, "cannot request IRQn");
	}

	dir = debugfs_create_dir(dev_name(dev), NULL);
	debugfs_create_file_unsafe("inject_irq", 0200, dir, pmic, &demo_inject_fops);
	ret = devm_add_action_or_reset(dev, demo_pmic_debugfs_remove, dir);
	if (ret)
		return ret;

	dev_info(dev, "demo PMIC, %d regulatorsn", DEMO_NUM_REGULATORS);
	return 0;
}

static const struct of_device_id demo_pmic_of_match[] = {
	{ .compatible = "labcsmart,demo-pmic" },
	{ }
};
MODULE_DEVICE_TABLE(of, demo_pmic_of_match);

static struct platform_driver demo_pmic_driver = {
	.driver = {
		.name = "demo-pmic",
		.of_match_table = demo_pmic_of_match,
		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
	},
	.probe = demo_pmic_probe,
};
module_platform_driver(demo_pmic_driver);

MODULE_DESCRIPTION("Regulator driver for a simulated demo PMIC");
MODULE_LICENSE("GPL");
demo-consumer.c
// SPDX-License-Identifier: GPL-2.0
/*
 * A consumer of the demo PMIC, to exercise the consumer side of the
 * regulator framework. Each instance takes the supplies listed in its
 * device tree node and exposes them through sysfs attributes:
 *
 *   vcore   required, voltage window set by the consumer, notifier
 *   vio     optional, voltage switched between two levels
 *   vref    optional, enabled at probe, voltage read once
 *   vbias   optional, the consumer allows bypass
 *   led     optional, current regulator
 *   vaux    optional, absent from the device tree on purpose
 */

#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/notifier.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>

struct demo_consumer {
	struct device *dev;
	struct regulator *vcore;
	struct regulator *vio;
	struct regulator *vbias;
	struct regulator *led;
	struct notifier_block nb;
	bool vcore_on;
	int vref_uV;
};

static int demo_vcore_event(struct notifier_block *nb, unsigned long event,
			    void *data)
{
	struct demo_consumer *c = container_of(nb, struct demo_consumer, nb);

	if (event & REGULATOR_EVENT_OVER_CURRENT)
		dev_warn(c->dev, "vcore: over-currentn");
	if (event & REGULATOR_EVENT_OVER_TEMP_WARN)
		dev_warn(c->dev, "vcore: PMIC temperature warningn");
	if (event & REGULATOR_EVENT_PRE_VOLTAGE_CHANGE) {
		struct pre_voltage_change_data *v = data;

		dev_info(c->dev, "vcore: changing from %lu uV to %lu-%lu uVn",
			 v->old_uV, v->min_uV, v->max_uV);
	}
	if (event & REGULATOR_EVENT_DISABLE)
		dev_info(c->dev, "vcore: disabledn");

	return NOTIFY_OK;
}

/* Optional supply: NULL when absent, error pointer on a real error */
static struct regulator *demo_get_optional(struct device *dev, const char *id)
{
	struct regulator *r = devm_regulator_get_optional(dev, id);

	if (IS_ERR(r) && PTR_ERR(r) == -ENODEV) {
		dev_info(dev, "no %s supplyn", id);
		return NULL;
	}
	return r;
}

/* ------------------------------------------------------------------ */
/* sysfs                                                               */
/* ------------------------------------------------------------------ */

static ssize_t vcore_enable_store(struct device *dev, struct device_attribute *attr,
				  const char *buf, size_t count)
{
	struct demo_consumer *c = dev_get_drvdata(dev);
	bool on;
	int ret;

	ret = kstrtobool(buf, &on);
	if (ret)
		return ret;
	if (on == c->vcore_on)
		return count;

	ret = on ? regulator_enable(c->vcore) : regulator_disable(c->vcore);
	if (ret)
		return ret;
	c->vcore_on = on;
	return count;
}

static ssize_t vcore_enable_show(struct device *dev, struct device_attribute *attr,
				 char *buf)
{
	struct demo_consumer *c = dev_get_drvdata(dev);

	return sysfs_emit(buf, "%dn", c->vcore_on);
}
static DEVICE_ATTR_RW(vcore_enable);

/* "min max" in microvolts: the window this consumer accepts on vcore */
static ssize_t vcore_range_store(struct device *dev, struct device_attribute *attr,
				 const char *buf, size_t count)
{
	struct demo_consumer *c = dev_get_drvdata(dev);
	int min_uV, max_uV, ret;

	if (sscanf(buf, "%d %d", &min_uV, &max_uV) != 2 || min_uV > max_uV)
		return -EINVAL;

	ret = regulator_set_voltage(c->vcore, min_uV, max_uV);
	return ret ? ret : count;
}

static ssize_t vcore_range_show(struct device *dev, struct device_attribute *attr,
				char *buf)
{
	struct demo_consumer *c = dev_get_drvdata(dev);

	return sysfs_emit(buf, "%dn", regulator_get_voltage(c->vcore));
}
static DEVICE_ATTR_RW(vcore_range);

static ssize_t vio_microvolt_store(struct device *dev, struct device_attribute *attr,
				   const char *buf, size_t count)
{
	struct demo_consumer *c = dev_get_drvdata(dev);
	int uV, ret;

	if (!c->vio)
		return -ENODEV;
	ret = kstrtoint(buf, 0, &uV);
	if (ret)
		return ret;
	if (!regulator_is_supported_voltage(c->vio, uV, uV))
		return -EINVAL;

	ret = regulator_set_voltage(c->vio, uV, uV);
	return ret ? ret : count;
}

static ssize_t vio_microvolt_show(struct device *dev, struct device_attribute *attr,
				  char *buf)
{
	struct demo_consumer *c = dev_get_drvdata(dev);

	if (!c->vio)
		return -ENODEV;
	return sysfs_emit(buf, "%dn", regulator_get_voltage(c->vio));
}
static DEVICE_ATTR_RW(vio_microvolt);

static ssize_t vref_microvolt_show(struct device *dev, struct device_attribute *attr,
				   char *buf)
{
	struct demo_consumer *c = dev_get_drvdata(dev);

	return sysfs_emit(buf, "%dn", c->vref_uV);
}
static DEVICE_ATTR_RO(vref_microvolt);

static ssize_t vbias_bypass_store(struct device *dev, struct device_attribute *attr,
				  const char *buf, size_t count)
{
	struct demo_consumer *c = dev_get_drvdata(dev);
	bool allow;
	int ret;

	if (!c->vbias)
		return -ENODEV;
	ret = kstrtobool(buf, &allow);
	if (ret)
		return ret;

	ret = regulator_allow_bypass(c->vbias, allow);
	return ret ? ret : count;
}
static DEVICE_ATTR_WO(vbias_bypass);

static ssize_t led_microamp_store(struct device *dev, struct device_attribute *attr,
				  const char *buf, size_t count)
{
	struct demo_consumer *c = dev_get_drvdata(dev);
	int uA, ret;

	if (!c->led)
		return -ENODEV;
	ret = kstrtoint(buf, 0, &uA);
	if (ret)
		return ret;

	/* Any limit up to the requested value will do */
	ret = regulator_set_current_limit(c->led, 0, uA);
	return ret ? ret : count;
}

static ssize_t led_microamp_show(struct device *dev, struct device_attribute *attr,
				 char *buf)
{
	struct demo_consumer *c = dev_get_drvdata(dev);

	if (!c->led)
		return -ENODEV;
	return sysfs_emit(buf, "%dn", regulator_get_current_limit(c->led));
}
static DEVICE_ATTR_RW(led_microamp);

static struct attribute *demo_consumer_attrs[] = {
	&dev_attr_vcore_enable.attr,
	&dev_attr_vcore_range.attr,
	&dev_attr_vio_microvolt.attr,
	&dev_attr_vref_microvolt.attr,
	&dev_attr_vbias_bypass.attr,
	&dev_attr_led_microamp.attr,
	NULL
};
ATTRIBUTE_GROUPS(demo_consumer);

/* ------------------------------------------------------------------ */
/* Probe                                                               */
/* ------------------------------------------------------------------ */

static void demo_regulator_disable(void *data)
{
	regulator_disable(data);
}

/* Enable a supply and disable it again when the device goes away */
static int demo_enable_managed(struct device *dev, struct regulator *r)
{
	int ret = regulator_enable(r);

	if (ret)
		return ret;
	return devm_add_action_or_reset(dev, demo_regulator_disable, r);
}

static void demo_vcore_off(void *data)
{
	struct demo_consumer *c = data;

	if (c->vcore_on)
		regulator_disable(c->vcore);
}

static int demo_consumer_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct demo_consumer *c;
	struct regulator *vaux;
	int ret;

	c = devm_kzalloc(dev, sizeof(*c), GFP_KERNEL);
	if (!c)
		return -ENOMEM;
	c->dev = dev;
	platform_set_drvdata(pdev, c);

	/* Required supply: a dummy regulator stands in if the DT lacks it */
	c->vcore = devm_regulator_get(dev, "vcore");
	if (IS_ERR(c->vcore))
		return dev_err_probe(dev, PTR_ERR(c->vcore), "no vcore supplyn");

	c->nb.notifier_call = demo_vcore_event;
	ret = devm_regulator_register_notifier(c->vcore, &c->nb);
	if (ret)
		return ret;

	ret = regulator_enable(c->vcore);
	if (ret)
		return ret;
	c->vcore_on = true;
	ret = devm_add_action_or_reset(dev, demo_vcore_off, c);
	if (ret)
		return ret;

	/* Optional supplies */
	c->vio = demo_get_optional(dev, "vio");
	if (IS_ERR(c->vio))
		return PTR_ERR(c->vio);
	if (c->vio) {
		ret = demo_enable_managed(dev, c->vio);
		if (ret)
			return ret;
	}

	ret = devm_regulator_get_enable_read_voltage(dev, "vref");
	if (ret >= 0)
		c->vref_uV = ret;
	else if (ret == -ENODEV)
		dev_info(dev, "no vref supplyn");
	else
		return dev_err_probe(dev, ret, "cannot read vrefn");

	c->vbias = demo_get_optional(dev, "vbias");
	if (IS_ERR(c->vbias))
		return PTR_ERR(c->vbias);
	if (c->vbias) {
		ret = demo_enable_managed(dev, c->vbias);
		if (ret)
			return ret;
	}

	c->led = demo_get_optional(dev, "led");
	if (IS_ERR(c->led))
		return PTR_ERR(c->led);
	if (c->led) {
		ret = demo_enable_managed(dev, c->led);
		if (ret)
			return ret;
	}

	vaux = demo_get_optional(dev, "vaux");
	if (IS_ERR(vaux))
		return PTR_ERR(vaux);

	dev_info(dev, "vcore at %d uV, vref at %d uVn",
		 regulator_get_voltage(c->vcore), c->vref_uV);
	return 0;
}

static const struct of_device_id demo_consumer_of_match[] = {
	{ .compatible = "labcsmart,demo-consumer" },
	{ }
};
MODULE_DEVICE_TABLE(of, demo_consumer_of_match);

static struct platform_driver demo_consumer_driver = {
	.driver = {
		.name = "demo-consumer",
		.of_match_table = demo_consumer_of_match,
		.dev_groups = demo_consumer_groups,
	},
	.probe = demo_consumer_probe,
};
module_platform_driver(demo_consumer_driver);

MODULE_DESCRIPTION("Consumer of the demo PMIC regulators");
MODULE_LICENSE("GPL");
demo-pmic.dtsi
// SPDX-License-Identifier: GPL-2.0
/*
 * The demo PMIC, its 5 V input rail and two consumers.
 * Added to the root node of a board device tree (here, QEMU's arm64 virt).
 */

/ {
	vin_5v: regulator-vin {
		compatible = "regulator-fixed";
		regulator-name = "vin-5v";
		regulator-min-microvolt = <5000000>;
		regulator-max-microvolt = <5000000>;
		regulator-always-on;
	};

	pmic {
		compatible = "labcsmart,demo-pmic";

		/* Inputs of the outputs: the 5 V rail, or BUCK2 for the LDOs */
		vin-buck1-supply = <&vin_5v>;
		vin-buck2-supply = <&vin_5v>;
		vin-boost-supply = <&vin_5v>;
		vin-ldo1-supply = <&buck2>;
		vin-ldo2-supply = <&buck2>;
		vin-ldo3-supply = <&buck2>;

		regulators {
			buck1: buck1 {
				regulator-name = "vdd-core";
				regulator-min-microvolt = <800000>;
				regulator-max-microvolt = <1100000>;
				regulator-ramp-delay = <12500>;
				regulator-initial-mode = <0>;		/* auto */
				regulator-allowed-modes = <0 1>;	/* auto, forced PWM */
			};

			buck2: buck2 {
				regulator-name = "vdd-3v3";
				regulator-min-microvolt = <3300000>;
				regulator-max-microvolt = <3600000>;
				regulator-always-on;
				regulator-active-discharge = <1>;
			};

			boost {
				regulator-name = "vbus-5v";
				regulator-min-microvolt = <5000000>;
				regulator-max-microvolt = <5000000>;
			};

			ldo1: ldo1 {
				regulator-name = "vdd-io";
				regulator-min-microvolt = <1800000>;
				regulator-max-microvolt = <3300000>;
			};

			ldo2: ldo2 {
				regulator-name = "vref-3v0";
			};

			ldo3: ldo3 {
				regulator-name = "vdd-bias";
				regulator-allow-bypass;
			};

			isink: isink {
				regulator-name = "led-sink";
				regulator-min-microamp = <5000>;
				regulator-max-microamp = <20000>;
			};
		};
	};

	consumer-a {
		compatible = "labcsmart,demo-consumer";
		vcore-supply = <&buck1>;
		vio-supply = <&ldo1>;
		vref-supply = <&ldo2>;
		vbias-supply = <&ldo3>;
		led-supply = <&isink>;
	};

	consumer-b {
		compatible = "labcsmart,demo-consumer";
		vcore-supply = <&buck1>;
	};
};
test.sh
#!/bin/sh
# Exercises the demo PMIC and its consumers; run as root on the target.
R=/sys/class/regulator
A=/sys/bus/platform/devices/consumer-a
B=/sys/bus/platform/devices/consumer-b
fail=0

check() {	# check <what> <expected> <actual>
	if [ "$2" = "$3" ]; then echo "PASS $1: $3"; else echo "FAIL $1: expected $2, got $3"; fail=1; fi
}

reg() {		# reg <regulator-name>: sysfs directory of that regulator
	for d in $R/regulator.*; do
		[ "$(cat $d/name)" = "$1" ] && { echo $d; return; }
	done
}

pmic_reg() {	# pmic_reg <address>: value of a PMIC register, from regmap debugfs
	grep "^$1:" /sys/kernel/debug/regmap/pmic/registers | cut -d' ' -f2
}

insmod /lib/modules/demo-pmic.ko
insmod /lib/modules/demo-consumer.ko
sleep 1

echo "== Regulators"
for d in $R/regulator.*; do
	printf "%-10s %-8s %-8s %-9s users=%sn" "$(cat $d/name)" "$(cat $d/type)" 
		"$(cat $d/state)" "$(cat $d/microvolts 2>/dev/null || cat $d/microamps)" "$(cat $d/num_users)"
done

CORE=$(reg vdd-core); V33=$(reg vdd-3v3); IO=$(reg vdd-io); BIAS=$(reg vdd-bias); LED=$(reg led-sink)

echo "== Fixed regulator, enabled and read at probe"
check "vref seen by consumer-a" 3000000 "$(cat $A/vref_microvolt)"

echo "== Shared rail: two consumers on vdd-core"
check "vdd-core users" 2 "$(cat $CORE/num_users)"
echo "900000 1100000" > $A/vcore_range
echo "1000000 1050000" > $B/vcore_range
check "vdd-core in the common window" 1000000 "$(cat $CORE/microvolts)"
echo "800000 900000" > $B/vcore_range
check "vdd-core, windows touching at 0.9 V" 900000 "$(cat $CORE/microvolts)"
echo "1150000 1200000" > $B/vcore_range 2>/dev/null && r=accepted || r=refused
check "request above the 1.1 V constraint" refused $r
check "ramp rate bits (12.5 mV/us) and enable in BUCK1_CTRL" 81 "$(pmic_reg 10)"
check "vdd-core mode from regulator-initial-mode" normal "$(cat $CORE/opmode)"

echo "== Voltage table and supply tracking: vdd-io fed by vdd-3v3"
echo 1800000 > $A/vio_microvolt
check "vdd-io at 1.8 V" 1800000 "$(cat $IO/microvolts)"
echo 3300000 > $A/vio_microvolt
check "vdd-io at 3.3 V" 3300000 "$(cat $IO/microvolts)"
check "vdd-3v3 raised for the 200 mV dropout" 3500000 "$(cat $V33/microvolts)"
echo 2000000 > $A/vio_microvolt 2>/dev/null && r=accepted || r=refused
check "2.0 V, not in the table" refused $r

echo "== Bypass"
check "vdd-bias bypass before" disabled "$(cat $BIAS/bypass)"
echo 1 > $A/vbias_bypass
check "vdd-bias bypass allowed by its only consumer" enabled "$(cat $BIAS/bypass)"

echo "== Current regulator"
echo 15000 > $A/led_microamp
check "led-sink at 15 mA" 15000 "$(cat $A/led_microamp)"
echo 30000 > $A/led_microamp
check "led-sink capped by the 20 mA constraint" 20000 "$(cat $A/led_microamp)"

echo "== Interrupts and notifiers"
dmesg -c > /dev/null
echo 1 > /sys/kernel/debug/pmic/inject_irq
check "over-current on BUCK1 reaches both consumers" 2 "$(dmesg | grep -c 'vcore: over-current')"
check "INT_STATUS cleared by the handler" 00 "$(pmic_reg 01)"

echo "== Reference counting"
echo 0 > $A/vcore_enable
check "vdd-core still on, consumer-b holds it" enabled "$(cat $CORE/state)"
echo 0 > $B/vcore_enable
check "vdd-core off once both released" disabled "$(cat $CORE/state)"

echo "== Summary"
cat /sys/kernel/debug/regulator/regulator_summary

[ $fail = 0 ] && echo "ALL TESTS PASSED" || echo "SOME TESTS FAILED"

The register file of the simulated chip starts with the values a real PMIC would hold after power-on, BUCK2 and LDO1 at 3.3 V, so that the core has something to bring into its constraints at registration.

Summing Up

A regulator driver is mostly description. It encodes each output in regulator_desc, uses the regmap helpers in regulator_ops, and needs code only for what the chip does in its own way, such as modes and interrupts. The device tree gives the board limits, and the core enforces them against every consumer request. On the consumer side, a driver names its supplies, keeps enables balanced, and asks for voltage windows.

LABCSMART writes PMIC and board support drivers for new boards as part of its engineering services.

Share this post on:

Leave a Reply

Your email address will not be published. Required fields are marked *