PWM outputs drive fans, LED and backlight brightness, buzzers, motors and the control loops of some power supplies. On most SoCs, the PWM controller is a small block with a counter per channel, and its Linux driver is short; the work lies in rounding requests to what the counter can do, and in keeping consumers, sysfs and device tree in agreement.
This tutorial covers the framework from both sides with a fictional controller, the demo PWM, in the same way as our article on regulator drivers. Its registers are simulated in RAM behind regmap, so the drivers build as out-of-tree modules and run on any Linux system. It uses the current API, which changed a lot over the last releases, and we tested everything on Linux 6.19 in QEMU, with the procedure of the testing section; the complete sources are at the end of the article.
Contents
- Describing a PWM Signal
- The PWM Framework Today
- The Demo PWM Controller
- Rounding: round_waveform_tohw and fromhw
- Writing and Reading the Hardware
- Input Capture
- Probe: Chip, Clock and Registration
- Device Tree Bindings
- The Consumer Side
- User Space: sysfs and the Character Device
- Building and Testing in QEMU
- The Complete Sources
- Summing Up
Describing a PWM Signal
A PWM output repeats the same pattern every period, high for part of it and low for the rest. Linux describes that pattern in two ways, shown in figure 1.
The older description, struct pwm_state, has a period, a duty cycle, a polarity and an enable flag; with normal polarity, the output starts each period high, and with inversed polarity, it starts low. The newer one, struct pwm_waveform, has a period length, a duty length and a duty offset, the delay between the start of the period and the start of the active part:
struct pwm_waveform {
u64 period_length_ns; /* 0: output disabled */
u64 duty_length_ns;
u64 duty_offset_ns;
};
An inversed state with duty cycle d is a waveform with duty length period minus d and offset d, so the waveform covers everything the state described, and also signals that the state cannot express, such as two outputs with the same period whose active parts do not start together. All times are in nanoseconds in both descriptions.
The PWM Framework Today
Controller drivers implement struct pwm_ops; the core turns requests from kernel drivers, sysfs and the character device into calls to it.
The API has changed several times since 2022, and code written for older kernels needs these updates:
| Release | Change |
|---|---|
| 6.8 | pwm_apply_state() becomes pwm_apply_might_sleep(), and pwm_apply_atomic() is added for atomic contexts |
| 6.9 | controllers allocate their chip with devm_pwmchip_alloc(), which also holds the private data |
| 6.13 | waveform callbacks for controllers, pwm_set_waveform_might_sleep() and friends for consumers |
| 6.17 | the /dev/pwmchipN character device, with ioctls on waveforms |
A controller driver implements either the waveform callbacks or the older apply and get_state. Consumers can use the state API with any controller; the waveform API, and with it the character device, needs a controller with the waveform callbacks. The demo PWM implements the waveform callbacks, the recommended choice for a new driver.
The Demo PWM Controller
The demo PWM has five channels, clocked at 10 MHz, which gives a resolution of 100 ns. Channels 0 to 3 are outputs; channel 4 is an input capture unit, wired on the board to the output of channel 0. Each output has four 32-bit registers:
| Register | Offset | Content |
|---|---|---|
| CTRL | 0x10 + 0x10 × n | bit 0: enable |
| PERIOD | 0x14 + 0x10 × n | period, in clock cycles |
| DUTY | 0x18 + 0x10 × n | active time, in clock cycles |
| OFFSET | 0x1c + 0x10 × n | start of the active time, in clock cycles |
Register 0x00 holds a version number. The driver keeps what it writes for one channel in a small structure, which the core handles as an opaque buffer:
/* What the driver writes to the hardware for one channel */
struct demo_pwm_wfhw {
u32 period_cnt; /* 0: channel disabled */
u32 duty_cnt;
u32 offset_cnt;
};
.sizeof_wfhw in pwm_ops tells the core how large it is.
Rounding: round_waveform_tohw and fromhw
Two callbacks convert between nanoseconds and the hardware representation. round_waveform_tohw() picks the register values for a requested waveform. The framework’s rule is that each value is rounded down to the nearest value the hardware can produce, and the callback returns 1 only when it had to round up, because the request was below the minimum:
static u32 demo_pwm_ns_to_cnt(struct demo_pwm *priv, u64 ns)
{
/* Round down; the clock is below 1 GHz, so this cannot overflow */
return min_t(u64, mul_u64_u32_div(ns, priv->clk_rate_hz, NSEC_PER_SEC), U32_MAX);
}
static int demo_pwm_round_waveform_tohw(struct pwm_chip *chip, struct pwm_device *pwm,
const struct pwm_waveform *wf, void *_wfhw)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
struct demo_pwm_wfhw *wfhw = _wfhw;
if (pwm->hwpwm == DEMO_PWM_CAPTURE_CH)
return wf->period_length_ns ? -EINVAL : 0;
if (!wf->period_length_ns) {
*wfhw = (struct demo_pwm_wfhw){ };
return 0;
}
wfhw->period_cnt = demo_pwm_ns_to_cnt(priv, wf->period_length_ns);
if (!wfhw->period_cnt) {
/* Shorter than one clock cycle: round up to the shortest period */
*wfhw = (struct demo_pwm_wfhw){ .period_cnt = 1 };
return 1;
}
wfhw->duty_cnt = demo_pwm_ns_to_cnt(priv, wf->duty_length_ns);
wfhw->offset_cnt = demo_pwm_ns_to_cnt(priv, wf->duty_offset_ns);
/* The offset must stay inside the rounded period */
if (wfhw->offset_cnt >= wfhw->period_cnt)
wfhw->offset_cnt = wfhw->period_cnt - 1;
return 0;
}
A period of 0 means a disabled output. The offset gets one more check, since the framework requires it to stay below the rounded period. round_waveform_fromhw() does the reverse, rounding up so that converting back and forth is stable:
static u64 demo_pwm_cnt_to_ns(struct demo_pwm *priv, u32 cnt)
{
return DIV64_U64_ROUND_UP((u64)cnt * NSEC_PER_SEC, priv->clk_rate_hz);
}
static int demo_pwm_round_waveform_fromhw(struct pwm_chip *chip, struct pwm_device *pwm,
const void *_wfhw, struct pwm_waveform *wf)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
const struct demo_pwm_wfhw *wfhw = _wfhw;
wf->period_length_ns = demo_pwm_cnt_to_ns(priv, wfhw->period_cnt);
wf->duty_length_ns = demo_pwm_cnt_to_ns(priv, wfhw->duty_cnt);
wf->duty_offset_ns = demo_pwm_cnt_to_ns(priv, wfhw->offset_cnt);
return 0;
}
With CONFIG_PWM_DEBUG, the core checks these rules on every request and logs Wrong rounding when a driver breaks them. We built the test kernel with it, and the test checks that the message never appears.
Writing and Reading the Hardware
write_waveform() programs a channel from the buffer that round_waveform_tohw() filled, and read_waveform() fills a buffer from the registers. The core calls the reader when a channel is requested, to know what the boot firmware left running, and in pwm_get_waveform_might_sleep():
static int demo_pwm_write_waveform(struct pwm_chip *chip, struct pwm_device *pwm,
const void *_wfhw)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
const struct demo_pwm_wfhw *wfhw = _wfhw;
unsigned int ch = pwm->hwpwm;
int ret;
if (ch == DEMO_PWM_CAPTURE_CH)
return 0;
if (!wfhw->period_cnt)
return regmap_write(priv->regmap, DEMO_PWM_CTRL(ch), 0);
ret = regmap_write(priv->regmap, DEMO_PWM_PERIOD(ch), wfhw->period_cnt);
if (ret)
return ret;
ret = regmap_write(priv->regmap, DEMO_PWM_DUTY(ch), wfhw->duty_cnt);
if (ret)
return ret;
ret = regmap_write(priv->regmap, DEMO_PWM_OFFSET(ch), wfhw->offset_cnt);
if (ret)
return ret;
return regmap_write(priv->regmap, DEMO_PWM_CTRL(ch), DEMO_PWM_CTRL_EN);
}
Two details of real hardware matter here. Many controllers latch new values only at the end of the current period, or need a load bit, so that a period and a duty from different requests never mix in one cycle; and many cannot apply a new period without a glitch. A driver for such hardware documents these limits at the top of its file, as in-tree drivers do in a Limitations: comment.
Input Capture
Some controllers also measure an incoming signal. The capture callback returns the period and duty cycle of the incoming signal, and sysfs exposes it as a capture attribute. On the demo PWM, channel 4 measures channel 0:
static int demo_pwm_capture(struct pwm_chip *chip, struct pwm_device *pwm,
struct pwm_capture *result, unsigned long timeout)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
struct pwm_device *src = &chip->pwms[0];
struct demo_pwm_wfhw wfhw;
int ret;
if (pwm->hwpwm != DEMO_PWM_CAPTURE_CH)
return -EOPNOTSUPP;
/* The simulated capture unit measures the signal of channel 0 */
ret = demo_pwm_read_waveform(chip, src, &wfhw);
if (ret)
return ret;
if (!wfhw.period_cnt)
return -ETIMEDOUT; /* no edge before the timeout */
result->period = demo_pwm_cnt_to_ns(priv, wfhw.period_cnt);
result->duty_cycle = demo_pwm_cnt_to_ns(priv, wfhw.duty_cnt);
return 0;
}
A real capture unit waits for edges up to the timeout given by the caller and returns -ETIMEDOUT when none arrives, which the simulation reproduces when channel 0 is off.
Probe: Chip, Clock and Registration
Probe allocates the chip with its private data, gets the clock and registers the chip:
chip = devm_pwmchip_alloc(dev, DEMO_PWM_NUM_CHANNELS, sizeof(*priv)); if (IS_ERR(chip)) return PTR_ERR(chip); priv = pwmchip_get_drvdata(chip); [...] clk = devm_clk_get_enabled(dev, NULL); if (IS_ERR(clk)) return dev_err_probe(dev, PTR_ERR(clk), "cannot get the clock\n"); /* The rate must not change while channels run */ ret = devm_clk_rate_exclusive_get(dev, clk); if (ret) return dev_err_probe(dev, ret, "cannot lock the clock rate\n"); priv->clk_rate_hz = clk_get_rate(clk); if (!priv->clk_rate_hz || priv->clk_rate_hz > NSEC_PER_SEC) return dev_err_probe(dev, -EINVAL, "unsupported clock rate %lu Hz\n", priv->clk_rate_hz); chip->ops = &demo_pwm_ops; chip->atomic = true; /* the callbacks never sleep */ ret = devm_pwmchip_add(dev, chip); if (ret) return dev_err_probe(dev, ret, "cannot add the PWM chip\n");
Since 6.9, devm_pwmchip_alloc() allocates the chip and the private data in one block; pwmchip_get_drvdata() returns the latter. devm_clk_rate_exclusive_get() keeps other drivers from changing the clock rate under running channels, since every count depends on it. chip->atomic declares that the callbacks never sleep, which allows consumers to call pwm_apply_atomic() from atomic context; the regmap sets fast_io for that reason, so that it locks with a spinlock instead of a mutex. A controller behind I2C, such as a PCA9685, leaves it false.
For a memory-mapped controller, only the regmap line changes, with the register area from the device tree:
- priv->regmap = devm_regmap_init(dev, NULL, priv, &demo_pwm_regmap_config); + base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(base)) + return PTR_ERR(base); + priv->regmap = devm_regmap_init_mmio(dev, base, &demo_pwm_regmap_config);
The regmap_config then loses its reg_read and reg_write callbacks, and the device tree node gains a reg property.
Device Tree Bindings
The controller node declares the number of cells in a PWM specifier; consumers point to a channel with a phandle and those cells. Figure 3 shows the wiring of the test, with the generic LED driver on channel 1 and our consumer on channels 0 and 2.
// SPDX-License-Identifier: GPL-2.0
/*
* The demo PWM controller, its clock and its consumers.
* Added to the root node of a board device tree (here, QEMU's arm64 virt).
*/
/ {
pwm_clk: pwm-clock {
compatible = "fixed-clock";
#clock-cells = <0>;
clock-frequency = <10000000>; /* 10 MHz: 100 ns resolution */
};
pwm: pwm {
compatible = "labcsmart,demo-pwm";
clocks = <&pwm_clk>;
#pwm-cells = <3>; /* channel, period in ns, flags */
};
/* An in-tree consumer: the generic PWM LED driver, on channel 1 */
leds {
compatible = "pwm-leds";
led-status {
label = "status";
pwms = <&pwm 1 1000000 0>; /* 1 kHz */
max-brightness = <255>;
};
};
/* Our consumer: two phases at 20 kHz, on channels 0 and 2 */
interleaved {
compatible = "labcsmart,demo-pwm-consumer";
pwms = <&pwm 0 50000 0>, <&pwm 2 50000 0>;
pwm-names = "phase-a", "phase-b";
};
};
With #pwm-cells = <3>, the cells are the channel, the period in nanoseconds and flags, where PWM_POLARITY_INVERTED from <dt-bindings/pwm/pwm.h> requests the inversed polarity. Since a demo driver leaves of_xlate unset, the core uses its default, of_pwm_xlate_with_flags(), which handles both two and three cells. The clock is a fixed-clock, so that the rate the driver reads is the one in the device tree.
The Consumer Side
The demo consumer drives two outputs like the two phases of an interleaved converter, with the same period and duty cycle and the second phase delayed by half a period, so that the input current is spread over the period.
Getting the outputs
devm_pwm_get() looks up the name it is given in pwm-names; with a single output, the name can be NULL. As for regulators, devm_pwm_get() returns -EPROBE_DEFER when the controller has not probed yet, which dev_err_probe() passes on quietly:
c->phase_a = devm_pwm_get(dev, "phase-a"); if (IS_ERR(c->phase_a)) return dev_err_probe(dev, PTR_ERR(c->phase_a), "no phase-a PWM\n"); c->phase_b = devm_pwm_get(dev, "phase-b"); if (IS_ERR(c->phase_b)) return dev_err_probe(dev, PTR_ERR(c->phase_b), "no phase-b PWM\n");
A channel serves one user at a time. Once the consumer holds channel 0, exporting it from sysfs fails with -EBUSY, as the test checks.
The state API
Phase A uses the state API. pwm_init_state() starts from the period and polarity of the device tree, pwm_set_relative_duty_cycle() computes a duty cycle from a ratio, and pwm_apply_might_sleep() programs it:
/* Phase A: period and polarity from the device tree, relative duty */ pwm_init_state(c->phase_a, &state); pwm_set_relative_duty_cycle(&state, c->duty_percent, 100); state.enabled = c->enabled; ret = pwm_apply_might_sleep(c->phase_a, &state); if (ret) return ret;
The state is applied as a whole, with no separate call for the period, the duty cycle or the enable bit, so the driver always receives a consistent set of values to program.
The waveform API
Phase B needs an offset, so it goes through the waveform API:
/* Phase B: same waveform, delayed by half a period */
if (c->enabled)
wf = (struct pwm_waveform){
.period_length_ns = state.period,
.duty_length_ns = state.duty_cycle,
.duty_offset_ns = state.period / 2,
};
else
wf = (struct pwm_waveform){ .period_length_ns = 0 };
return pwm_set_waveform_might_sleep(c->phase_b, &wf, false);
The last argument, exact, chooses between accepting the rounding of the hardware and failing with -EDOM when the waveform cannot be produced exactly. pwm_round_waveform_might_sleep() shows the result of the rounding without applying it, and pwm_get_waveform_might_sleep() reads what the channel produces:
ret = pwm_round_waveform_might_sleep(c->phase_a, &wf); if (ret < 0) return ret; return sysfs_emit(buf, "%llu %llu %llu%s\n", wf.period_length_ns, wf.duty_length_ns, wf.duty_offset_ns, ret ? " (rounded up)" : "");
With one clock cycle of 100 ns, a request of 12345 ns becomes 12300 ns, and 50 ns, below one cycle, becomes 100 ns with the return value set to 1.
In-tree consumers
Most boards need no consumer code at all, since leds-pwm, pwm-backlight, pwm-fan, pwm-beeper and pwm-regulator take their output from the device tree. In the test, the LED on channel 1 at brightness 128 out of 255 asks for a duty cycle of 501960 ns, which the controller rounds down to 501900 ns. The debugfs file of the core shows both values, requested and actual, as the end of the test shows.
User Space: sysfs and the Character Device
A channel can be driven from user space through sysfs, one file per parameter. It is the quickest way to try an output by hand, a procedure that works on any board:
cd /sys/class/pwm/pwmchip0 echo 3 > export # creates pwm3/ echo 1000000 > pwm3/period # 1 ms echo 250000 > pwm3/duty_cycle # 25 % echo 1 > pwm3/enable echo 0 > pwm3/enable echo inversed > pwm3/polarity echo 1 > pwm3/enable echo 3 > unexport
Each write applies a full state, so the order matters while the channel is enabled. A duty cycle larger than the current period is refused, and when shortening the period, the duty cycle has to go down first.
Since 6.17, each chip whose driver implements the waveform callbacks also has a character device, /dev/pwmchipN, with ioctls that take a whole waveform at once, offset included. A process requests a channel, which stays reserved until the process closes the file, and the output keeps its last waveform once the file is closed. The small tool we used in the test:
/* Exclusive use of the channel until the file is closed */
if (ioctl(fd, PWM_IOCTL_REQUEST, wf.hwpwm) < 0) {
perror("PWM_IOCTL_REQUEST");
return 1;
}
ret = ioctl(fd, cmd, &wf);
if (ret < 0) {
printf("%s: %s\n", argv[3], strerror(errno));
return 1;
}
if (cmd == PWM_IOCTL_ROUNDWF) {
print_wf("rounded", &wf);
return 0;
}
if (ioctl(fd, PWM_IOCTL_GETWF, &wf) < 0) {
perror("PWM_IOCTL_GETWF");
return 1;
}
print_wf("programmed", &wf);
PWM_IOCTL_SETROUNDEDWF accepts the rounding, PWM_IOCTL_SETEXACTWF refuses it with EDOM, and PWM_IOCTL_ROUNDWF only reports it.
Building and Testing in QEMU
The two modules build against any kernel tree prepared for modules:
# Out-of-tree build: make KDIR=/path/to/kernel/build obj-m := demo-pwm.o demo-pwm-consumer.o KDIR ?= /lib/modules/$(shell uname -r)/build all: $(MAKE) -C $(KDIR) M=$(CURDIR) modules clean: $(MAKE) -C $(KDIR) M=$(CURDIR) clean
The procedure is the one of the regulator article: an arm64 kernel, QEMU’s virt machine with its device tree extended by the nodes above, and an initramfs with BusyBox, the modules, the character device tool and the test script. The kernel adds CONFIG_PWM_DEBUG; CONFIG_PWM and CONFIG_LEDS_PWM are already in the arm64 defconfig. The tool is built statically against the kernel headers:
make ARCH=arm64 O=build headers_install INSTALL_HDR_PATH=$PWD/hdr aarch64-linux-gnu-gcc -static -O2 -Wall -I hdr/include -o pwmchip-wf pwmchip-wf.c
The output of the test script on 6.19:
== Consumer at probe: 25 % on two phases, the second delayed by half a period PASS phase A: 50000 12500 0 PASS phase B: 50000 12500 25000 PASS atomic controller: 0 == Changing the duty cycle PASS phase A at 30 %: 50000 15000 0 PASS phase B at 30 %: 50000 15000 25000 == Rounding to the 100 ns clock PASS rounded down: 12300 5500 0 PASS below one cycle, rounded up: 100 0 0 (rounded up) == In-tree consumer: pwm-leds on channel 1 PASS LED at 128/255 of 1 ms: enabled, 501900/1000000 ns, normal polarity == sysfs interface on channel 3 PASS channel 0, held by the consumer: busy PASS channel 3 at 25 % of 1 ms: enabled, 250000/1000000 ns, normal polarity PASS channel 3 inversed: enabled, 250000/1000000 ns, inverse polarity == Input capture on channel 4, wired to channel 0 PASS captured period and duty: 50000 15000 == Character device on channel 3 PASS set, rounded: programmed: period 33300 ns, duty 11100 ns, offset 0 ns PASS exact, not possible: exact: Numerical argument out of domain PASS exact, possible: programmed: period 40000 ns, duty 10000 ns, offset 5000 ns == Consumer disabled PASS phase A off: 0 0 0 PASS capture without a signal: timed out PASS no rounding error reported by PWM_DEBUG: 0 ALL TESTS PASSED
The end of the run prints the debugfs view of the chip, with the requested and the actual configuration of each channel:
== debugfs 0: platform/pwm, npwm: 5 pwm-0 (phase-a ): requested requested configuration: disabled, 15000/50000 ns, normal polarity actual configuration: disabled, 0/0 ns, normal polarity pwm-1 (led-status ): requested requested configuration: enabled, 501960/1000000 ns, normal polarity actual configuration: enabled, 501900/1000000 ns, normal polarity pwm-2 (phase-b ): requested requested configuration: disabled, 0/0 ns, normal polarity actual configuration: disabled, 0/0 ns, normal polarity pwm-3 ((null) ): requested configuration: enabled, 10000/40000 ns, normal polarity actual configuration: enabled, 10000/40000 ns, normal polarity pwm-4 ((null) ): requested configuration: disabled, 0/0 ns, normal polarity actual configuration: disabled, 0/0 ns, normal polarity
Channel 3, last set through the character device with a 5 us offset, appears there as a plain 10/40 us signal, because debugfs prints the state description, which has no offset.
The Complete Sources
The two drivers, the device tree nodes, the character device tool and the test script, as tested; checkpatch reports nothing, and they build without warnings at W=1.
demo-pwm.c
// SPDX-License-Identifier: GPL-2.0
/*
* PWM driver for a fictional controller, the "demo PWM".
*
* The controller has five channels clocked by one input clock:
*
* channels 0 to 3 outputs, with programmable period, duty length and
* duty offset (the delay of the active phase from the
* start of the period), counted in clock cycles
* channel 4 input capture, wired on the board to the output of
* channel 0
*
* Each output channel has four 32-bit registers:
*
* CTRL bit 0: enable
* PERIOD period, in clock cycles
* DUTY active time, in clock cycles
* OFFSET start of the active time within the period, in clock cycles
*
* The registers are simulated in RAM behind regmap, so the driver runs on
* any Linux system. A real memory-mapped controller would use
* devm_regmap_init_mmio() instead, or readl()/writel() directly.
*/
#include <linux/bits.h>
#include <linux/clk.h>
#include <linux/kernel.h>
#include <linux/math64.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/platform_device.h>
#include <linux/pwm.h>
#include <linux/regmap.h>
#define DEMO_PWM_VERSION 0x00
#define DEMO_PWM_CH_BASE(ch) (0x10 + (ch) * 0x10)
#define DEMO_PWM_CTRL(ch) (DEMO_PWM_CH_BASE(ch) + 0x0)
#define DEMO_PWM_PERIOD(ch) (DEMO_PWM_CH_BASE(ch) + 0x4)
#define DEMO_PWM_DUTY(ch) (DEMO_PWM_CH_BASE(ch) + 0x8)
#define DEMO_PWM_OFFSET(ch) (DEMO_PWM_CH_BASE(ch) + 0xc)
#define DEMO_PWM_MAX_REG 0x5c
#define DEMO_PWM_CTRL_EN BIT(0)
#define DEMO_PWM_VERSION_VALUE 0x00010000
#define DEMO_PWM_NUM_OUTPUTS 4
#define DEMO_PWM_CAPTURE_CH 4 /* sees the output of channel 0 */
#define DEMO_PWM_NUM_CHANNELS 5
struct demo_pwm {
struct regmap *regmap;
unsigned long clk_rate_hz;
u32 regs[DEMO_PWM_MAX_REG / 4 + 1]; /* the simulated controller */
};
/* What the driver writes to the hardware for one channel */
struct demo_pwm_wfhw {
u32 period_cnt; /* 0: channel disabled */
u32 duty_cnt;
u32 offset_cnt;
};
/* ------------------------------------------------------------------ */
/* Simulated hardware */
/* ------------------------------------------------------------------ */
static int demo_pwm_hw_read(void *context, unsigned int reg, unsigned int *val)
{
struct demo_pwm *priv = context;
*val = priv->regs[reg / 4];
return 0;
}
static int demo_pwm_hw_write(void *context, unsigned int reg, unsigned int val)
{
struct demo_pwm *priv = context;
if (reg == DEMO_PWM_VERSION)
return -EIO;
priv->regs[reg / 4] = val;
return 0;
}
static const struct regmap_config demo_pwm_regmap_config = {
.reg_bits = 32,
.val_bits = 32,
.reg_stride = 4,
.max_register = DEMO_PWM_MAX_REG,
.reg_read = demo_pwm_hw_read,
.reg_write = demo_pwm_hw_write,
.fast_io = true, /* spinlock: the callbacks never sleep */
};
/* ------------------------------------------------------------------ */
/* Waveform callbacks */
/* ------------------------------------------------------------------ */
static u32 demo_pwm_ns_to_cnt(struct demo_pwm *priv, u64 ns)
{
/* Round down; the clock is below 1 GHz, so this cannot overflow */
return min_t(u64, mul_u64_u32_div(ns, priv->clk_rate_hz, NSEC_PER_SEC), U32_MAX);
}
static u64 demo_pwm_cnt_to_ns(struct demo_pwm *priv, u32 cnt)
{
return DIV64_U64_ROUND_UP((u64)cnt * NSEC_PER_SEC, priv->clk_rate_hz);
}
static int demo_pwm_round_waveform_tohw(struct pwm_chip *chip, struct pwm_device *pwm,
const struct pwm_waveform *wf, void *_wfhw)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
struct demo_pwm_wfhw *wfhw = _wfhw;
if (pwm->hwpwm == DEMO_PWM_CAPTURE_CH)
return wf->period_length_ns ? -EINVAL : 0;
if (!wf->period_length_ns) {
*wfhw = (struct demo_pwm_wfhw){ };
return 0;
}
wfhw->period_cnt = demo_pwm_ns_to_cnt(priv, wf->period_length_ns);
if (!wfhw->period_cnt) {
/* Shorter than one clock cycle: round up to the shortest period */
*wfhw = (struct demo_pwm_wfhw){ .period_cnt = 1 };
return 1;
}
wfhw->duty_cnt = demo_pwm_ns_to_cnt(priv, wf->duty_length_ns);
wfhw->offset_cnt = demo_pwm_ns_to_cnt(priv, wf->duty_offset_ns);
/* The offset must stay inside the rounded period */
if (wfhw->offset_cnt >= wfhw->period_cnt)
wfhw->offset_cnt = wfhw->period_cnt - 1;
return 0;
}
static int demo_pwm_round_waveform_fromhw(struct pwm_chip *chip, struct pwm_device *pwm,
const void *_wfhw, struct pwm_waveform *wf)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
const struct demo_pwm_wfhw *wfhw = _wfhw;
wf->period_length_ns = demo_pwm_cnt_to_ns(priv, wfhw->period_cnt);
wf->duty_length_ns = demo_pwm_cnt_to_ns(priv, wfhw->duty_cnt);
wf->duty_offset_ns = demo_pwm_cnt_to_ns(priv, wfhw->offset_cnt);
return 0;
}
static int demo_pwm_write_waveform(struct pwm_chip *chip, struct pwm_device *pwm,
const void *_wfhw)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
const struct demo_pwm_wfhw *wfhw = _wfhw;
unsigned int ch = pwm->hwpwm;
int ret;
if (ch == DEMO_PWM_CAPTURE_CH)
return 0;
if (!wfhw->period_cnt)
return regmap_write(priv->regmap, DEMO_PWM_CTRL(ch), 0);
ret = regmap_write(priv->regmap, DEMO_PWM_PERIOD(ch), wfhw->period_cnt);
if (ret)
return ret;
ret = regmap_write(priv->regmap, DEMO_PWM_DUTY(ch), wfhw->duty_cnt);
if (ret)
return ret;
ret = regmap_write(priv->regmap, DEMO_PWM_OFFSET(ch), wfhw->offset_cnt);
if (ret)
return ret;
return regmap_write(priv->regmap, DEMO_PWM_CTRL(ch), DEMO_PWM_CTRL_EN);
}
static int demo_pwm_read_waveform(struct pwm_chip *chip, struct pwm_device *pwm,
void *_wfhw)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
struct demo_pwm_wfhw *wfhw = _wfhw;
unsigned int ch = pwm->hwpwm, ctrl;
int ret;
*wfhw = (struct demo_pwm_wfhw){ };
if (ch == DEMO_PWM_CAPTURE_CH)
return 0;
ret = regmap_read(priv->regmap, DEMO_PWM_CTRL(ch), &ctrl);
if (ret || !(ctrl & DEMO_PWM_CTRL_EN))
return ret;
ret = regmap_read(priv->regmap, DEMO_PWM_PERIOD(ch), &wfhw->period_cnt);
if (ret)
return ret;
ret = regmap_read(priv->regmap, DEMO_PWM_DUTY(ch), &wfhw->duty_cnt);
if (ret)
return ret;
return regmap_read(priv->regmap, DEMO_PWM_OFFSET(ch), &wfhw->offset_cnt);
}
/* ------------------------------------------------------------------ */
/* Input capture */
/* ------------------------------------------------------------------ */
static int demo_pwm_capture(struct pwm_chip *chip, struct pwm_device *pwm,
struct pwm_capture *result, unsigned long timeout)
{
struct demo_pwm *priv = pwmchip_get_drvdata(chip);
struct pwm_device *src = &chip->pwms[0];
struct demo_pwm_wfhw wfhw;
int ret;
if (pwm->hwpwm != DEMO_PWM_CAPTURE_CH)
return -EOPNOTSUPP;
/* The simulated capture unit measures the signal of channel 0 */
ret = demo_pwm_read_waveform(chip, src, &wfhw);
if (ret)
return ret;
if (!wfhw.period_cnt)
return -ETIMEDOUT; /* no edge before the timeout */
result->period = demo_pwm_cnt_to_ns(priv, wfhw.period_cnt);
result->duty_cycle = demo_pwm_cnt_to_ns(priv, wfhw.duty_cnt);
return 0;
}
static const struct pwm_ops demo_pwm_ops = {
.sizeof_wfhw = sizeof(struct demo_pwm_wfhw),
.round_waveform_tohw = demo_pwm_round_waveform_tohw,
.round_waveform_fromhw = demo_pwm_round_waveform_fromhw,
.read_waveform = demo_pwm_read_waveform,
.write_waveform = demo_pwm_write_waveform,
.capture = demo_pwm_capture,
};
/* ------------------------------------------------------------------ */
/* Probe */
/* ------------------------------------------------------------------ */
static int demo_pwm_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct pwm_chip *chip;
struct demo_pwm *priv;
unsigned int version;
struct clk *clk;
int ret;
chip = devm_pwmchip_alloc(dev, DEMO_PWM_NUM_CHANNELS, sizeof(*priv));
if (IS_ERR(chip))
return PTR_ERR(chip);
priv = pwmchip_get_drvdata(chip);
priv->regs[DEMO_PWM_VERSION / 4] = DEMO_PWM_VERSION_VALUE;
priv->regmap = devm_regmap_init(dev, NULL, priv, &demo_pwm_regmap_config);
if (IS_ERR(priv->regmap))
return dev_err_probe(dev, PTR_ERR(priv->regmap), "regmap init failed\n");
ret = regmap_read(priv->regmap, DEMO_PWM_VERSION, &version);
if (ret)
return ret;
clk = devm_clk_get_enabled(dev, NULL);
if (IS_ERR(clk))
return dev_err_probe(dev, PTR_ERR(clk), "cannot get the clock\n");
/* The rate must not change while channels run */
ret = devm_clk_rate_exclusive_get(dev, clk);
if (ret)
return dev_err_probe(dev, ret, "cannot lock the clock rate\n");
priv->clk_rate_hz = clk_get_rate(clk);
if (!priv->clk_rate_hz || priv->clk_rate_hz > NSEC_PER_SEC)
return dev_err_probe(dev, -EINVAL, "unsupported clock rate %lu Hz\n",
priv->clk_rate_hz);
chip->ops = &demo_pwm_ops;
chip->atomic = true; /* the callbacks never sleep */
ret = devm_pwmchip_add(dev, chip);
if (ret)
return dev_err_probe(dev, ret, "cannot add the PWM chip\n");
dev_info(dev, "demo PWM v%u.%u, %u channels at %lu Hz\n", version >> 16,
version & 0xffff, DEMO_PWM_NUM_CHANNELS, priv->clk_rate_hz);
return 0;
}
static const struct of_device_id demo_pwm_of_match[] = {
{ .compatible = "labcsmart,demo-pwm" },
{ }
};
MODULE_DEVICE_TABLE(of, demo_pwm_of_match);
static struct platform_driver demo_pwm_driver = {
.driver = {
.name = "demo-pwm",
.of_match_table = demo_pwm_of_match,
},
.probe = demo_pwm_probe,
};
module_platform_driver(demo_pwm_driver);
MODULE_DESCRIPTION("PWM driver for a simulated demo PWM controller");
MODULE_LICENSE("GPL");
demo-pwm-consumer.c
// SPDX-License-Identifier: GPL-2.0
/*
* A consumer of two PWM channels, driven like the two phases of an
* interleaved converter: same period and duty cycle, the second phase
* delayed by half a period.
*
* Phase A goes through the state API (pwm_apply_might_sleep()), phase B
* through the waveform API (pwm_set_waveform_might_sleep()), which can
* express the delay. sysfs attributes expose both for testing:
*
* duty_percent duty cycle of both phases
* enable 0 or 1, both phases
* waveform_a/b period, duty length and offset in ns, as programmed
* round write "period duty offset", read what phase A would get
* might_sleep whether the controller callbacks may sleep
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/pwm.h>
struct demo_pwm_consumer {
struct device *dev;
struct pwm_device *phase_a;
struct pwm_device *phase_b;
struct mutex lock; /* serialises the sysfs writers */
unsigned int duty_percent;
bool enabled;
struct pwm_waveform round_req;
};
/* Program both phases from the current settings */
static int demo_update(struct demo_pwm_consumer *c)
{
struct pwm_waveform wf;
struct pwm_state state;
int ret;
/* Phase A: period and polarity from the device tree, relative duty */
pwm_init_state(c->phase_a, &state);
pwm_set_relative_duty_cycle(&state, c->duty_percent, 100);
state.enabled = c->enabled;
ret = pwm_apply_might_sleep(c->phase_a, &state);
if (ret)
return ret;
/* Phase B: same waveform, delayed by half a period */
if (c->enabled)
wf = (struct pwm_waveform){
.period_length_ns = state.period,
.duty_length_ns = state.duty_cycle,
.duty_offset_ns = state.period / 2,
};
else
wf = (struct pwm_waveform){ .period_length_ns = 0 };
return pwm_set_waveform_might_sleep(c->phase_b, &wf, false);
}
static ssize_t duty_percent_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
unsigned int pct;
int ret;
ret = kstrtouint(buf, 0, &pct);
if (ret)
return ret;
if (pct > 100)
return -EINVAL;
mutex_lock(&c->lock);
c->duty_percent = pct;
ret = demo_update(c);
mutex_unlock(&c->lock);
return ret ? ret : count;
}
static ssize_t duty_percent_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
return sysfs_emit(buf, "%u\n", c->duty_percent);
}
static DEVICE_ATTR_RW(duty_percent);
static ssize_t enable_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
bool on;
int ret;
ret = kstrtobool(buf, &on);
if (ret)
return ret;
mutex_lock(&c->lock);
c->enabled = on;
ret = demo_update(c);
mutex_unlock(&c->lock);
return ret ? ret : count;
}
static ssize_t enable_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
return sysfs_emit(buf, "%d\n", c->enabled);
}
static DEVICE_ATTR_RW(enable);
static ssize_t demo_show_waveform(struct pwm_device *pwm, char *buf)
{
struct pwm_waveform wf;
int ret;
ret = pwm_get_waveform_might_sleep(pwm, &wf);
if (ret)
return ret;
return sysfs_emit(buf, "%llu %llu %llu\n", wf.period_length_ns,
wf.duty_length_ns, wf.duty_offset_ns);
}
static ssize_t waveform_a_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
return demo_show_waveform(c->phase_a, buf);
}
static DEVICE_ATTR_RO(waveform_a);
static ssize_t waveform_b_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
return demo_show_waveform(c->phase_b, buf);
}
static DEVICE_ATTR_RO(waveform_b);
static ssize_t round_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
struct pwm_waveform wf;
if (sscanf(buf, "%llu %llu %llu", &wf.period_length_ns, &wf.duty_length_ns,
&wf.duty_offset_ns) != 3)
return -EINVAL;
mutex_lock(&c->lock);
c->round_req = wf;
mutex_unlock(&c->lock);
return count;
}
/* What phase A would get for the last requested waveform, without applying it */
static ssize_t round_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
struct pwm_waveform wf;
int ret;
mutex_lock(&c->lock);
wf = c->round_req;
mutex_unlock(&c->lock);
ret = pwm_round_waveform_might_sleep(c->phase_a, &wf);
if (ret < 0)
return ret;
return sysfs_emit(buf, "%llu %llu %llu%s\n", wf.period_length_ns, wf.duty_length_ns,
wf.duty_offset_ns, ret ? " (rounded up)" : "");
}
static DEVICE_ATTR_RW(round);
static ssize_t might_sleep_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct demo_pwm_consumer *c = dev_get_drvdata(dev);
return sysfs_emit(buf, "%d\n", pwm_might_sleep(c->phase_a));
}
static DEVICE_ATTR_RO(might_sleep);
static struct attribute *demo_pwm_consumer_attrs[] = {
&dev_attr_duty_percent.attr,
&dev_attr_enable.attr,
&dev_attr_waveform_a.attr,
&dev_attr_waveform_b.attr,
&dev_attr_round.attr,
&dev_attr_might_sleep.attr,
NULL
};
ATTRIBUTE_GROUPS(demo_pwm_consumer);
static void demo_pwm_consumer_stop(void *data)
{
struct demo_pwm_consumer *c = data;
c->enabled = false;
demo_update(c);
}
static int demo_pwm_consumer_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct demo_pwm_consumer *c;
int ret;
c = devm_kzalloc(dev, sizeof(*c), GFP_KERNEL);
if (!c)
return -ENOMEM;
c->dev = dev;
ret = devm_mutex_init(dev, &c->lock);
if (ret)
return ret;
platform_set_drvdata(pdev, c);
c->phase_a = devm_pwm_get(dev, "phase-a");
if (IS_ERR(c->phase_a))
return dev_err_probe(dev, PTR_ERR(c->phase_a), "no phase-a PWM\n");
c->phase_b = devm_pwm_get(dev, "phase-b");
if (IS_ERR(c->phase_b))
return dev_err_probe(dev, PTR_ERR(c->phase_b), "no phase-b PWM\n");
c->duty_percent = 25;
c->enabled = true;
ret = demo_update(c);
if (ret)
return dev_err_probe(dev, ret, "cannot start the PWMs\n");
ret = devm_add_action_or_reset(dev, demo_pwm_consumer_stop, c);
if (ret)
return ret;
dev_info(dev, "two phases at %llu ns, %u%% duty\n",
pwm_get_period(c->phase_a), c->duty_percent);
return 0;
}
static const struct of_device_id demo_pwm_consumer_of_match[] = {
{ .compatible = "labcsmart,demo-pwm-consumer" },
{ }
};
MODULE_DEVICE_TABLE(of, demo_pwm_consumer_of_match);
static struct platform_driver demo_pwm_consumer_driver = {
.driver = {
.name = "demo-pwm-consumer",
.of_match_table = demo_pwm_consumer_of_match,
.dev_groups = demo_pwm_consumer_groups,
},
.probe = demo_pwm_consumer_probe,
};
module_platform_driver(demo_pwm_consumer_driver);
MODULE_DESCRIPTION("Two-phase consumer of the demo PWM controller");
MODULE_LICENSE("GPL");
pwmchip-wf.c
// SPDX-License-Identifier: GPL-2.0
/*
* Drives one PWM channel through the PWM character device (Linux 6.17+).
*
* pwmchip-wf /dev/pwmchip0 <channel> round|set|exact <period> <duty> <offset>
*
* "round" prints what the hardware would do, "set" programs the rounded
* waveform, "exact" programs it only if no rounding is needed. All three
* then print the waveform read back from the channel.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <linux/pwm.h>
static void print_wf(const char *what, const struct pwmchip_waveform *wf)
{
printf("%s: period %llu ns, duty %llu ns, offset %llu ns\n", what,
(unsigned long long)wf->period_length_ns,
(unsigned long long)wf->duty_length_ns,
(unsigned long long)wf->duty_offset_ns);
}
int main(int argc, char **argv)
{
struct pwmchip_waveform wf = { 0 };
unsigned long cmd;
int fd, ret;
if (argc != 7) {
fprintf(stderr, "usage: %s /dev/pwmchipN channel round|set|exact period duty offset\n",
argv[0]);
return 2;
}
fd = open(argv[1], O_RDWR);
if (fd < 0) {
perror(argv[1]);
return 1;
}
wf.hwpwm = strtoul(argv[2], NULL, 0);
wf.period_length_ns = strtoull(argv[4], NULL, 0);
wf.duty_length_ns = strtoull(argv[5], NULL, 0);
wf.duty_offset_ns = strtoull(argv[6], NULL, 0);
if (!strcmp(argv[3], "round"))
cmd = PWM_IOCTL_ROUNDWF;
else if (!strcmp(argv[3], "set"))
cmd = PWM_IOCTL_SETROUNDEDWF;
else if (!strcmp(argv[3], "exact"))
cmd = PWM_IOCTL_SETEXACTWF;
else
return 2;
/* Exclusive use of the channel until the file is closed */
if (ioctl(fd, PWM_IOCTL_REQUEST, wf.hwpwm) < 0) {
perror("PWM_IOCTL_REQUEST");
return 1;
}
ret = ioctl(fd, cmd, &wf);
if (ret < 0) {
printf("%s: %s\n", argv[3], strerror(errno));
return 1;
}
if (cmd == PWM_IOCTL_ROUNDWF) {
print_wf("rounded", &wf);
return 0;
}
if (ioctl(fd, PWM_IOCTL_GETWF, &wf) < 0) {
perror("PWM_IOCTL_GETWF");
return 1;
}
print_wf("programmed", &wf);
/* Closing the file frees the channel; the output keeps running */
close(fd);
return 0;
}
test.sh
#!/bin/sh
# Exercises the demo PWM controller and its consumers; run as root on the target.
C=/sys/bus/platform/devices/interleaved
P=/sys/class/pwm/pwmchip0
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
}
dbg() { # dbg <channel>: actual configuration of that channel, from debugfs
grep -A2 "pwm-$1 " /sys/kernel/debug/pwm | grep actual | sed 's/.*actual configuration: *//'
}
insmod /lib/modules/demo-pwm.ko
insmod /lib/modules/demo-pwm-consumer.ko
sleep 1
echo "== Consumer at probe: 25 % on two phases, the second delayed by half a period"
check "phase A" "50000 12500 0" "$(cat $C/waveform_a)"
check "phase B" "50000 12500 25000" "$(cat $C/waveform_b)"
check "atomic controller" 0 "$(cat $C/might_sleep)"
echo "== Changing the duty cycle"
echo 30 > $C/duty_percent
check "phase A at 30 %" "50000 15000 0" "$(cat $C/waveform_a)"
check "phase B at 30 %" "50000 15000 25000" "$(cat $C/waveform_b)"
echo "== Rounding to the 100 ns clock"
echo "12345 5555 0" > $C/round
check "rounded down" "12300 5500 0" "$(cat $C/round)"
echo "50 20 0" > $C/round
check "below one cycle, rounded up" "100 0 0 (rounded up)" "$(cat $C/round)"
echo "== In-tree consumer: pwm-leds on channel 1"
echo 128 > /sys/class/leds/status/brightness
check "LED at 128/255 of 1 ms" "enabled, 501900/1000000 ns, normal polarity" "$(dbg 1)"
echo "== sysfs interface on channel 3"
echo 0 > $P/export 2>/dev/null && r=exported || r=busy
check "channel 0, held by the consumer" busy $r
echo 3 > $P/export
echo 1000000 > $P/pwm3/period
echo 250000 > $P/pwm3/duty_cycle
echo 1 > $P/pwm3/enable
check "channel 3 at 25 % of 1 ms" "enabled, 250000/1000000 ns, normal polarity" "$(dbg 3)"
echo 0 > $P/pwm3/enable
echo inversed > $P/pwm3/polarity
echo 1 > $P/pwm3/enable
check "channel 3 inversed" "enabled, 250000/1000000 ns, inverse polarity" "$(dbg 3)"
echo 3 > $P/unexport
echo "== Input capture on channel 4, wired to channel 0"
echo 4 > $P/export
check "captured period and duty" "50000 15000" "$(cat $P/pwm4/capture)"
echo "== Character device on channel 3"
check "set, rounded" "programmed: period 33300 ns, duty 11100 ns, offset 0 ns" \
"$(pwmchip-wf /dev/pwmchip0 3 set 33333 11111 0)"
check "exact, not possible" "exact: Numerical argument out of domain" \
"$(pwmchip-wf /dev/pwmchip0 3 exact 33333 11111 0)"
check "exact, possible" "programmed: period 40000 ns, duty 10000 ns, offset 5000 ns" \
"$(pwmchip-wf /dev/pwmchip0 3 exact 40000 10000 5000)"
echo "== Consumer disabled"
echo 0 > $C/enable
check "phase A off" "0 0 0" "$(cat $C/waveform_a)"
cat $P/pwm4/capture > /dev/null 2>&1 && r=measured || r="timed out"
check "capture without a signal" "timed out" "$r"
echo 4 > $P/unexport
check "no rounding error reported by PWM_DEBUG" 0 "$(dmesg | grep -c 'Wrong rounding')"
echo "== debugfs"
cat /sys/kernel/debug/pwm
[ $fail = 0 ] && echo "ALL TESTS PASSED" || echo "SOME TESTS FAILED"
The device tree nodes are listed in full in the device tree section above.
Summing Up
A PWM controller driver today is mostly arithmetic. It converts nanoseconds to counts, rounding down, converts them back, rounding up, and writes and reads the registers. The waveform callbacks give consumers the duty offset and give user space the character device; CONFIG_PWM_DEBUG checks the rounding. On the consumer side, a driver applies complete states or waveforms, never single parameters, and lets the device tree carry the period and polarity.
LABCSMART writes and upstreams drivers for SoC peripherals as part of its engineering services.


