1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *	watchdog_core.c
4  *
5  *	(c) Copyright 2008-2011 Alan Cox <alan@lxorguk.ukuu.org.uk>,
6  *						All Rights Reserved.
7  *
8  *	(c) Copyright 2008-2011 Wim Van Sebroeck <wim@iguana.be>.
9  *
10  *	This source code is part of the generic code that can be used
11  *	by all the watchdog timer drivers.
12  *
13  *	Based on source code of the following authors:
14  *	  Matt Domsch <Matt_Domsch@dell.com>,
15  *	  Rob Radez <rob@osinvestor.com>,
16  *	  Rusty Lynch <rusty@linux.co.intel.com>
17  *	  Satyam Sharma <satyam@infradead.org>
18  *	  Randy Dunlap <randy.dunlap@oracle.com>
19  *
20  *	Neither Alan Cox, CymruNet Ltd., Wim Van Sebroeck nor Iguana vzw.
21  *	admit liability nor provide warranty for any of this software.
22  *	This material is provided "AS-IS" and at no charge.
23  */
24 
25 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
26 
27 #include <linux/module.h>	/* For EXPORT_SYMBOL/module stuff/... */
28 #include <linux/types.h>	/* For standard types */
29 #include <linux/errno.h>	/* For the -ENODEV/... values */
30 #include <linux/kernel.h>	/* For printk/panic/... */
31 #include <linux/reboot.h>	/* For restart handler */
32 #include <linux/watchdog.h>	/* For watchdog specific items */
33 #include <linux/init.h>		/* For __init/__exit/... */
34 #include <linux/idr.h>		/* For ida_* macros */
35 #include <linux/err.h>		/* For IS_ERR macros */
36 #include <linux/of.h>		/* For of_get_timeout_sec */
37 
38 #include "watchdog_core.h"	/* For watchdog_dev_register/... */
39 
40 static DEFINE_IDA(watchdog_ida);
41 
42 /*
43  * Deferred Registration infrastructure.
44  *
45  * Sometimes watchdog drivers needs to be loaded as soon as possible,
46  * for example when it's impossible to disable it. To do so,
47  * raising the initcall level of the watchdog driver is a solution.
48  * But in such case, the miscdev is maybe not ready (subsys_initcall), and
49  * watchdog_core need miscdev to register the watchdog as a char device.
50  *
51  * The deferred registration infrastructure offer a way for the watchdog
52  * subsystem to register a watchdog properly, even before miscdev is ready.
53  */
54 
55 static DEFINE_MUTEX(wtd_deferred_reg_mutex);
56 static LIST_HEAD(wtd_deferred_reg_list);
57 static bool wtd_deferred_reg_done;
58 
59 static void watchdog_deferred_registration_add(struct watchdog_device *wdd)
60 {
61 	list_add_tail(&wdd->deferred,
62 		      &wtd_deferred_reg_list);
63 }
64 
65 static void watchdog_deferred_registration_del(struct watchdog_device *wdd)
66 {
67 	struct list_head *p, *n;
68 	struct watchdog_device *wdd_tmp;
69 
70 	list_for_each_safe(p, n, &wtd_deferred_reg_list) {
71 		wdd_tmp = list_entry(p, struct watchdog_device,
72 				     deferred);
73 		if (wdd_tmp == wdd) {
74 			list_del(&wdd_tmp->deferred);
75 			break;
76 		}
77 	}
78 }
79 
80 static void watchdog_check_min_max_timeout(struct watchdog_device *wdd)
81 {
82 	/*
83 	 * Check that we have valid min and max timeout values, if
84 	 * not reset them both to 0 (=not used or unknown)
85 	 */
86 	if (!wdd->max_hw_heartbeat_ms && wdd->min_timeout > wdd->max_timeout) {
87 		pr_info("Invalid min and max timeout values, resetting to 0!\n");
88 		wdd->min_timeout = 0;
89 		wdd->max_timeout = 0;
90 	}
91 }
92 
93 /**
94  * watchdog_init_timeout() - initialize the timeout field
95  * @wdd: watchdog device
96  * @timeout_parm: timeout module parameter
97  * @dev: Device that stores the timeout-sec property
98  *
99  * Initialize the timeout field of the watchdog_device struct with either the
100  * timeout module parameter (if it is valid value) or the timeout-sec property
101  * (only if it is a valid value and the timeout_parm is out of bounds).
102  * If none of them are valid then we keep the old value (which should normally
103  * be the default timeout value). Note that for the module parameter, '0' means
104  * 'use default' while it is an invalid value for the timeout-sec property.
105  * It should simply be dropped if you want to use the default value then.
106  *
107  * A zero is returned on success or -EINVAL if all provided values are out of
108  * bounds.
109  */
110 int watchdog_init_timeout(struct watchdog_device *wdd,
111 				unsigned int timeout_parm, struct device *dev)
112 {
113 	const char *dev_str = wdd->parent ? dev_name(wdd->parent) :
114 			      (const char *)wdd->info->identity;
115 	unsigned int t = 0;
116 	int ret = 0;
117 
118 	watchdog_check_min_max_timeout(wdd);
119 
120 	/* check the driver supplied value (likely a module parameter) first */
121 	if (timeout_parm) {
122 		if (!watchdog_timeout_invalid(wdd, timeout_parm)) {
123 			wdd->timeout = timeout_parm;
124 			return 0;
125 		}
126 		pr_err("%s: driver supplied timeout (%u) out of range\n",
127 			dev_str, timeout_parm);
128 		ret = -EINVAL;
129 	}
130 
131 	/* try to get the timeout_sec property */
132 	if (dev && dev->of_node &&
133 	    of_property_read_u32(dev->of_node, "timeout-sec", &t) == 0) {
134 		if (t && !watchdog_timeout_invalid(wdd, t)) {
135 			wdd->timeout = t;
136 			return 0;
137 		}
138 		pr_err("%s: DT supplied timeout (%u) out of range\n", dev_str, t);
139 		ret = -EINVAL;
140 	}
141 
142 	if (ret < 0 && wdd->timeout)
143 		pr_warn("%s: falling back to default timeout (%u)\n", dev_str,
144 			wdd->timeout);
145 
146 	return ret;
147 }
148 EXPORT_SYMBOL_GPL(watchdog_init_timeout);
149 
150 static int watchdog_reboot_notifier(struct notifier_block *nb,
151 				    unsigned long code, void *data)
152 {
153 	struct watchdog_device *wdd;
154 
155 	wdd = container_of(nb, struct watchdog_device, reboot_nb);
156 	if (code == SYS_DOWN || code == SYS_HALT) {
157 		if (watchdog_active(wdd)) {
158 			int ret;
159 
160 			ret = wdd->ops->stop(wdd);
161 			if (ret)
162 				return NOTIFY_BAD;
163 		}
164 	}
165 
166 	return NOTIFY_DONE;
167 }
168 
169 static int watchdog_restart_notifier(struct notifier_block *nb,
170 				     unsigned long action, void *data)
171 {
172 	struct watchdog_device *wdd = container_of(nb, struct watchdog_device,
173 						   restart_nb);
174 
175 	int ret;
176 
177 	ret = wdd->ops->restart(wdd, action, data);
178 	if (ret)
179 		return NOTIFY_BAD;
180 
181 	return NOTIFY_DONE;
182 }
183 
184 /**
185  * watchdog_set_restart_priority - Change priority of restart handler
186  * @wdd: watchdog device
187  * @priority: priority of the restart handler, should follow these guidelines:
188  *   0:   use watchdog's restart function as last resort, has limited restart
189  *        capabilies
190  *   128: default restart handler, use if no other handler is expected to be
191  *        available and/or if restart is sufficient to restart the entire system
192  *   255: preempt all other handlers
193  *
194  * If a wdd->ops->restart function is provided when watchdog_register_device is
195  * called, it will be registered as a restart handler with the priority given
196  * here.
197  */
198 void watchdog_set_restart_priority(struct watchdog_device *wdd, int priority)
199 {
200 	wdd->restart_nb.priority = priority;
201 }
202 EXPORT_SYMBOL_GPL(watchdog_set_restart_priority);
203 
204 static int __watchdog_register_device(struct watchdog_device *wdd)
205 {
206 	int ret, id = -1;
207 
208 	if (wdd == NULL || wdd->info == NULL || wdd->ops == NULL)
209 		return -EINVAL;
210 
211 	/* Mandatory operations need to be supported */
212 	if (!wdd->ops->start || (!wdd->ops->stop && !wdd->max_hw_heartbeat_ms))
213 		return -EINVAL;
214 
215 	watchdog_check_min_max_timeout(wdd);
216 
217 	/*
218 	 * Note: now that all watchdog_device data has been verified, we
219 	 * will not check this anymore in other functions. If data gets
220 	 * corrupted in a later stage then we expect a kernel panic!
221 	 */
222 
223 	/* Use alias for watchdog id if possible */
224 	if (wdd->parent) {
225 		ret = of_alias_get_id(wdd->parent->of_node, "watchdog");
226 		if (ret >= 0)
227 			id = ida_simple_get(&watchdog_ida, ret,
228 					    ret + 1, GFP_KERNEL);
229 	}
230 
231 	if (id < 0)
232 		id = ida_simple_get(&watchdog_ida, 0, MAX_DOGS, GFP_KERNEL);
233 
234 	if (id < 0)
235 		return id;
236 	wdd->id = id;
237 
238 	ret = watchdog_dev_register(wdd);
239 	if (ret) {
240 		ida_simple_remove(&watchdog_ida, id);
241 		if (!(id == 0 && ret == -EBUSY))
242 			return ret;
243 
244 		/* Retry in case a legacy watchdog module exists */
245 		id = ida_simple_get(&watchdog_ida, 1, MAX_DOGS, GFP_KERNEL);
246 		if (id < 0)
247 			return id;
248 		wdd->id = id;
249 
250 		ret = watchdog_dev_register(wdd);
251 		if (ret) {
252 			ida_simple_remove(&watchdog_ida, id);
253 			return ret;
254 		}
255 	}
256 
257 	if (test_bit(WDOG_STOP_ON_REBOOT, &wdd->status)) {
258 		wdd->reboot_nb.notifier_call = watchdog_reboot_notifier;
259 
260 		ret = register_reboot_notifier(&wdd->reboot_nb);
261 		if (ret) {
262 			pr_err("watchdog%d: Cannot register reboot notifier (%d)\n",
263 			       wdd->id, ret);
264 			watchdog_dev_unregister(wdd);
265 			ida_simple_remove(&watchdog_ida, id);
266 			return ret;
267 		}
268 	}
269 
270 	if (wdd->ops->restart) {
271 		wdd->restart_nb.notifier_call = watchdog_restart_notifier;
272 
273 		ret = register_restart_handler(&wdd->restart_nb);
274 		if (ret)
275 			pr_warn("watchdog%d: Cannot register restart handler (%d)\n",
276 				wdd->id, ret);
277 	}
278 
279 	return 0;
280 }
281 
282 /**
283  * watchdog_register_device() - register a watchdog device
284  * @wdd: watchdog device
285  *
286  * Register a watchdog device with the kernel so that the
287  * watchdog timer can be accessed from userspace.
288  *
289  * A zero is returned on success and a negative errno code for
290  * failure.
291  */
292 
293 int watchdog_register_device(struct watchdog_device *wdd)
294 {
295 	const char *dev_str;
296 	int ret = 0;
297 
298 	mutex_lock(&wtd_deferred_reg_mutex);
299 	if (wtd_deferred_reg_done)
300 		ret = __watchdog_register_device(wdd);
301 	else
302 		watchdog_deferred_registration_add(wdd);
303 	mutex_unlock(&wtd_deferred_reg_mutex);
304 
305 	if (ret) {
306 		dev_str = wdd->parent ? dev_name(wdd->parent) :
307 			  (const char *)wdd->info->identity;
308 		pr_err("%s: failed to register watchdog device (err = %d)\n",
309 			dev_str, ret);
310 	}
311 
312 	return ret;
313 }
314 EXPORT_SYMBOL_GPL(watchdog_register_device);
315 
316 static void __watchdog_unregister_device(struct watchdog_device *wdd)
317 {
318 	if (wdd == NULL)
319 		return;
320 
321 	if (wdd->ops->restart)
322 		unregister_restart_handler(&wdd->restart_nb);
323 
324 	if (test_bit(WDOG_STOP_ON_REBOOT, &wdd->status))
325 		unregister_reboot_notifier(&wdd->reboot_nb);
326 
327 	watchdog_dev_unregister(wdd);
328 	ida_simple_remove(&watchdog_ida, wdd->id);
329 }
330 
331 /**
332  * watchdog_unregister_device() - unregister a watchdog device
333  * @wdd: watchdog device to unregister
334  *
335  * Unregister a watchdog device that was previously successfully
336  * registered with watchdog_register_device().
337  */
338 
339 void watchdog_unregister_device(struct watchdog_device *wdd)
340 {
341 	mutex_lock(&wtd_deferred_reg_mutex);
342 	if (wtd_deferred_reg_done)
343 		__watchdog_unregister_device(wdd);
344 	else
345 		watchdog_deferred_registration_del(wdd);
346 	mutex_unlock(&wtd_deferred_reg_mutex);
347 }
348 
349 EXPORT_SYMBOL_GPL(watchdog_unregister_device);
350 
351 static void devm_watchdog_unregister_device(struct device *dev, void *res)
352 {
353 	watchdog_unregister_device(*(struct watchdog_device **)res);
354 }
355 
356 /**
357  * devm_watchdog_register_device() - resource managed watchdog_register_device()
358  * @dev: device that is registering this watchdog device
359  * @wdd: watchdog device
360  *
361  * Managed watchdog_register_device(). For watchdog device registered by this
362  * function,  watchdog_unregister_device() is automatically called on driver
363  * detach. See watchdog_register_device() for more information.
364  */
365 int devm_watchdog_register_device(struct device *dev,
366 				struct watchdog_device *wdd)
367 {
368 	struct watchdog_device **rcwdd;
369 	int ret;
370 
371 	rcwdd = devres_alloc(devm_watchdog_unregister_device, sizeof(*rcwdd),
372 			     GFP_KERNEL);
373 	if (!rcwdd)
374 		return -ENOMEM;
375 
376 	ret = watchdog_register_device(wdd);
377 	if (!ret) {
378 		*rcwdd = wdd;
379 		devres_add(dev, rcwdd);
380 	} else {
381 		devres_free(rcwdd);
382 	}
383 
384 	return ret;
385 }
386 EXPORT_SYMBOL_GPL(devm_watchdog_register_device);
387 
388 static int __init watchdog_deferred_registration(void)
389 {
390 	mutex_lock(&wtd_deferred_reg_mutex);
391 	wtd_deferred_reg_done = true;
392 	while (!list_empty(&wtd_deferred_reg_list)) {
393 		struct watchdog_device *wdd;
394 
395 		wdd = list_first_entry(&wtd_deferred_reg_list,
396 				       struct watchdog_device, deferred);
397 		list_del(&wdd->deferred);
398 		__watchdog_register_device(wdd);
399 	}
400 	mutex_unlock(&wtd_deferred_reg_mutex);
401 	return 0;
402 }
403 
404 static int __init watchdog_init(void)
405 {
406 	int err;
407 
408 	err = watchdog_dev_init();
409 	if (err < 0)
410 		return err;
411 
412 	watchdog_deferred_registration();
413 	return 0;
414 }
415 
416 static void __exit watchdog_exit(void)
417 {
418 	watchdog_dev_exit();
419 	ida_destroy(&watchdog_ida);
420 }
421 
422 subsys_initcall_sync(watchdog_init);
423 module_exit(watchdog_exit);
424 
425 MODULE_AUTHOR("Alan Cox <alan@lxorguk.ukuu.org.uk>");
426 MODULE_AUTHOR("Wim Van Sebroeck <wim@iguana.be>");
427 MODULE_DESCRIPTION("WatchDog Timer Driver Core");
428 MODULE_LICENSE("GPL");
429