Skip to content
systemcoding.dev
Kernels

Write a Watchdog Driver With the Watchdog Core

Write a Linux 6.12 watchdog driver with watchdog_device and watchdog_ops, handle the timeout and nowayout options, and see it through /dev/watchdog and wdctl.

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

A watchdog is a hardware timer that resets the machine if software stops feeding it. It is the last line of defense for an unattended device: when the kernel hangs or a critical service dies, the timer expires and the board reboots by itself. Linux has a watchdog core that does most of the work of a driver. It creates /dev/watchdog0, handles the user-space protocol, and can even keep feeding the hardware while the system boots, leaving the driver to implement only the register operations. This post writes a driver for a memory-mapped watchdog on Linux 6.12, explains each callback, and shows how systemd and wdctl use it. It builds on the driver introduction.

The core is documented in the kernel's watchdog kernel API.

What the core provides

The driver describes the hardware in two structures, struct watchdog_info and struct watchdog_ops, and a struct watchdog_device that ties them to the instance. The core then supplies:

  • the character device /dev/watchdogN, with open, write, ioctl and release

  • the user-space protocol: opening starts the watchdog, writing any data pings it, and the "magic close" character V allows a clean stop

  • the WDIOC_* ioctls that tools use to set the timeout and read status

  • a kernel worker that pings the hardware by itself between the moment the driver registers and the moment user space opens the device, when the hardware is already running

The driver only has to start, stop and ping the hardware, and optionally set the timeout.

The driver

This watchdog has three registers: a control register where bit 0 enables the timer, a load register that holds the timeout in seconds, and a refresh register that reloads the counter when written:

sample_wdt.cc
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>

#define REG_CTRL	0x00
#define REG_LOAD	0x04
#define REG_REFRESH	0x08
#define CTRL_ENABLE	BIT(0)
#define REFRESH_KEY	0xa5a5a5a5

struct sample_wdt {
	struct watchdog_device	wdd;
	void __iomem		*regs;
};

static int sample_wdt_start(struct watchdog_device *wdd)
{
	struct sample_wdt *w = watchdog_get_drvdata(wdd);

	iowrite32(wdd->timeout, w->regs + REG_LOAD);
	iowrite32(CTRL_ENABLE, w->regs + REG_CTRL);
	return 0;
}

static int sample_wdt_stop(struct watchdog_device *wdd)
{
	struct sample_wdt *w = watchdog_get_drvdata(wdd);

	iowrite32(0, w->regs + REG_CTRL);
	return 0;
}

static int sample_wdt_ping(struct watchdog_device *wdd)
{
	struct sample_wdt *w = watchdog_get_drvdata(wdd);

	iowrite32(REFRESH_KEY, w->regs + REG_REFRESH);
	return 0;
}

static int sample_wdt_set_timeout(struct watchdog_device *wdd,
				  unsigned int timeout)
{
	struct sample_wdt *w = watchdog_get_drvdata(wdd);

	wdd->timeout = timeout;
	iowrite32(timeout, w->regs + REG_LOAD);
	return 0;
}

static const struct watchdog_info sample_wdt_info = {
	.options	= WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING |
			  WDIOF_MAGICCLOSE,
	.identity	= "Sample watchdog",
};

static const struct watchdog_ops sample_wdt_ops = {
	.owner		= THIS_MODULE,
	.start		= sample_wdt_start,
	.stop		= sample_wdt_stop,
	.ping		= sample_wdt_ping,
	.set_timeout	= sample_wdt_set_timeout,
};

static unsigned int timeout;
module_param(timeout, uint, 0444);
MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds (default 30)");

static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0444);
MODULE_PARM_DESC(nowayout, "Do not stop the watchdog once started");

static int sample_wdt_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct sample_wdt *w;

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

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

	w->wdd.info = &sample_wdt_info;
	w->wdd.ops = &sample_wdt_ops;
	w->wdd.min_timeout = 1;
	w->wdd.max_timeout = 600;
	w->wdd.timeout = 30;
	w->wdd.parent = dev;

	watchdog_init_timeout(&w->wdd, timeout, dev);
	watchdog_set_nowayout(&w->wdd, nowayout);
	watchdog_set_drvdata(&w->wdd, w);

	return devm_watchdog_register_device(dev, &w->wdd);
}

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

static struct platform_driver sample_wdt_driver = {
	.probe	= sample_wdt_probe,
	.driver	= {
		.name		= "sample-wdt",
		.of_match_table	= sample_wdt_of_match,
	},
};
module_platform_driver(sample_wdt_driver);

MODULE_DESCRIPTION("Sample watchdog driver");
MODULE_LICENSE("GPL");

Walking through it

watchdog_info.options advertises what the device can do to user space. WDIOF_SETTIMEOUT says the timeout can be changed, WDIOF_KEEPALIVEPING says a ping is supported, and WDIOF_MAGICCLOSE says writing V before closing disables the watchdog, so a controlled shutdown does not reset the machine. Advertise only what the driver implements, because tools read these flags.

watchdog_ops holds the callbacks. start and stop are mandatory, and ping is needed if the hardware supports it. If ping is missing, the core calls start again to refresh the timer, which suits hardware where starting reloads the counter. set_timeout is needed when WDIOF_SETTIMEOUT is advertised. The callback must save the new value in wdd->timeout, since the core reads it back.

The three timeout fields set the limits. min_timeout and max_timeout bound what a user can request, and timeout is the default. watchdog_init_timeout() picks the initial value from the module parameter first, then from a timeout-sec property in the device tree, then keeps the default. It validates the choice against the limits and falls back with a warning if the request is out of range.

watchdog_set_nowayout() controls what happens when user space closes the device. With nowayout true, the watchdog cannot be stopped once started, even by the magic close, so a crashed daemon cannot disarm the safety. The default comes from the kernel's CONFIG_WATCHDOG_NOWAYOUT option. For a production device the safe choice is on, and for development you want it off, so a debug session does not end in a reboot.

devm_watchdog_register_device() registers the device and arranges removal on unbind. The core calls stop when it unregisters if the watchdog is running, unless nowayout prevents it.

Using it

Registration creates the device node and a sysfs entry. The wdctl tool from util-linux reads the state:

Shell
sudo wdctl /dev/watchdog0
Text
Device:        /dev/watchdog0
Identity:      Sample watchdog [version 0]
Timeout:       30 seconds
Pre-timeout:    0 seconds
FLAG           DESCRIPTION               STATUS BOOT-STATUS
KEEPALIVEPING  Keep alive ping reply          0           0
MAGICCLOSE     Supports magic close char      0           0
SETTIMEOUT     Set timeout (in seconds)       0           0

Opening the device starts the watchdog, and from then on something must write to it more often than the timeout. A shell test shows the whole protocol, and it reboots the machine on purpose if you stop writing, so run it only on a board where that is acceptable:

Shell
sudo sh -c 'exec 3>/dev/watchdog0; while true; do echo . >&3; sleep 10; done'

Each write is a ping. Kill the loop without writing V and, with nowayout set, the board resets after 30 seconds. The reliable consumer in a real system is systemd, which pings the watchdog by itself when configured:

Text
[Manager]
RuntimeWatchdogSec=20

in /etc/systemd/system.conf. systemd opens /dev/watchdog0, sets the timeout to the requested value, and pings at half that interval, so a hung manager stops the pings and the hardware reboots the system.

Pre-timeout and other features

Hardware that can warn before it resets exposes a pre-timeout: an interrupt that fires some seconds before the reset, where the kernel can log or dump state. A driver sets info.options |= WDIOF_PRETIMEOUT and provides set_pretimeout, and the core connects it to a governor that decides the response (panic or noop). It is optional and helpful for diagnosing hangs, since the panic output tells you where the system was stuck.

A watchdog that was started by the bootloader is a related case. If the hardware is already running when the driver probes, the driver sets WDOG_HW_RUNNING in wdd.status and the core keeps pinging until user space takes over, avoiding a reset in the gap. Skipping that flag when the hardware is already counting down causes a reboot loop that looks like a boot failure.

Pitfalls

A timeout longer than the hardware's maximum counter value is a real problem. If the register holds only 16 bits of 1 ms ticks, the hardware cannot count 90 seconds, and the driver must either set max_hw_heartbeat_ms so the core pings more often than the user's timeout, or clamp max_timeout. The core's heartbeat worker handles the translation when you set the hardware limit, which is the recommended approach.

A stop that does not actually stop the hardware turns a clean shutdown into a reset. Test the stop path and the magic close character explicitly.

Choosing a timeout

The timeout is a trade between recovery speed and false resets. A short value recovers quickly from a hang, but a busy system that stalls for a moment, for example during a long filesystem sync or a heavy swap storm, may miss a ping and reboot without being broken. A long value tolerates stalls and leaves a hung device unavailable for that long. Pick a value several times larger than the longest legitimate pause in the pinging process, then test it by suspending that process on purpose. Also decide who pings: a dedicated high-priority daemon, or systemd, is better than a shell loop, because the pinger itself must keep running when the rest of the system is under load.

Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.