1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * ipmi_watchdog.c
4 *
5 * A watchdog timer based upon the IPMI interface.
6 *
7 * Author: MontaVista Software, Inc.
8 *         Corey Minyard <minyard@mvista.com>
9 *         source@mvista.com
10 *
11 * Copyright 2002 MontaVista Software Inc.
12 */
13
14#define pr_fmt(fmt) "IPMI Watchdog: " fmt
15
16#include <linux/module.h>
17#include <linux/moduleparam.h>
18#include <linux/ipmi.h>
19#include <linux/ipmi_smi.h>
20#include <linux/mutex.h>
21#include <linux/watchdog.h>
22#include <linux/miscdevice.h>
23#include <linux/init.h>
24#include <linux/completion.h>
25#include <linux/kdebug.h>
26#include <linux/rwsem.h>
27#include <linux/errno.h>
28#include <linux/uaccess.h>
29#include <linux/notifier.h>
30#include <linux/nmi.h>
31#include <linux/reboot.h>
32#include <linux/wait.h>
33#include <linux/poll.h>
34#include <linux/string.h>
35#include <linux/ctype.h>
36#include <linux/delay.h>
37#include <linux/atomic.h>
38#include <linux/sched/signal.h>
39
40#ifdef CONFIG_X86
41/*
42 * This is ugly, but I've determined that x86 is the only architecture
43 * that can reasonably support the IPMI NMI watchdog timeout at this
44 * time.  If another architecture adds this capability somehow, it
45 * will have to be a somewhat different mechanism and I have no idea
46 * how it will work.  So in the unlikely event that another
47 * architecture supports this, we can figure out a good generic
48 * mechanism for it at that time.
49 */
50#include <asm/kdebug.h>
51#include <asm/nmi.h>
52#define HAVE_DIE_NMI
53#endif
54
55/*
56 * The IPMI command/response information for the watchdog timer.
57 */
58
59/* values for byte 1 of the set command, byte 2 of the get response. */
60#define WDOG_DONT_LOG		(1 << 7)
61#define WDOG_DONT_STOP_ON_SET	(1 << 6)
62#define WDOG_SET_TIMER_USE(byte, use) \
63	byte = ((byte) & 0xf8) | ((use) & 0x7)
64#define WDOG_GET_TIMER_USE(byte) ((byte) & 0x7)
65#define WDOG_TIMER_USE_BIOS_FRB2	1
66#define WDOG_TIMER_USE_BIOS_POST	2
67#define WDOG_TIMER_USE_OS_LOAD		3
68#define WDOG_TIMER_USE_SMS_OS		4
69#define WDOG_TIMER_USE_OEM		5
70
71/* values for byte 2 of the set command, byte 3 of the get response. */
72#define WDOG_SET_PRETIMEOUT_ACT(byte, use) \
73	byte = ((byte) & 0x8f) | (((use) & 0x7) << 4)
74#define WDOG_GET_PRETIMEOUT_ACT(byte) (((byte) >> 4) & 0x7)
75#define WDOG_PRETIMEOUT_NONE		0
76#define WDOG_PRETIMEOUT_SMI		1
77#define WDOG_PRETIMEOUT_NMI		2
78#define WDOG_PRETIMEOUT_MSG_INT		3
79
80/* Operations that can be performed on a pretimout. */
81#define WDOG_PREOP_NONE		0
82#define WDOG_PREOP_PANIC	1
83/* Cause data to be available to read.  Doesn't work in NMI mode. */
84#define WDOG_PREOP_GIVE_DATA	2
85
86/* Actions to perform on a full timeout. */
87#define WDOG_SET_TIMEOUT_ACT(byte, use) \
88	byte = ((byte) & 0xf8) | ((use) & 0x7)
89#define WDOG_GET_TIMEOUT_ACT(byte) ((byte) & 0x7)
90#define WDOG_TIMEOUT_NONE		0
91#define WDOG_TIMEOUT_RESET		1
92#define WDOG_TIMEOUT_POWER_DOWN		2
93#define WDOG_TIMEOUT_POWER_CYCLE	3
94
95/*
96 * Byte 3 of the get command, byte 4 of the get response is the
97 * pre-timeout in seconds.
98 */
99
100/* Bits for setting byte 4 of the set command, byte 5 of the get response. */
101#define WDOG_EXPIRE_CLEAR_BIOS_FRB2	(1 << 1)
102#define WDOG_EXPIRE_CLEAR_BIOS_POST	(1 << 2)
103#define WDOG_EXPIRE_CLEAR_OS_LOAD	(1 << 3)
104#define WDOG_EXPIRE_CLEAR_SMS_OS	(1 << 4)
105#define WDOG_EXPIRE_CLEAR_OEM		(1 << 5)
106
107/*
108 * Setting/getting the watchdog timer value.  This is for bytes 5 and
109 * 6 (the timeout time) of the set command, and bytes 6 and 7 (the
110 * timeout time) and 8 and 9 (the current countdown value) of the
111 * response.  The timeout value is given in seconds (in the command it
112 * is 100ms intervals).
113 */
114#define WDOG_SET_TIMEOUT(byte1, byte2, val) \
115	(byte1) = (((val) * 10) & 0xff), (byte2) = (((val) * 10) >> 8)
116#define WDOG_GET_TIMEOUT(byte1, byte2) \
117	(((byte1) | ((byte2) << 8)) / 10)
118
119#define IPMI_WDOG_RESET_TIMER		0x22
120#define IPMI_WDOG_SET_TIMER		0x24
121#define IPMI_WDOG_GET_TIMER		0x25
122
123#define IPMI_WDOG_TIMER_NOT_INIT_RESP	0x80
124
125static DEFINE_MUTEX(ipmi_watchdog_mutex);
126static bool nowayout = WATCHDOG_NOWAYOUT;
127
128static struct ipmi_user *watchdog_user;
129static int watchdog_ifnum;
130
131/* Default the timeout to 10 seconds. */
132static int timeout = 10;
133
134/* The pre-timeout is disabled by default. */
135static int pretimeout;
136
137/* Default timeout to set on panic */
138static int panic_wdt_timeout = 255;
139
140/* Default action is to reset the board on a timeout. */
141static unsigned char action_val = WDOG_TIMEOUT_RESET;
142
143static char action[16] = "reset";
144
145static unsigned char preaction_val = WDOG_PRETIMEOUT_NONE;
146
147static char preaction[16] = "pre_none";
148
149static unsigned char preop_val = WDOG_PREOP_NONE;
150
151static char preop[16] = "preop_none";
152static DEFINE_SPINLOCK(ipmi_read_lock);
153static char data_to_read;
154static DECLARE_WAIT_QUEUE_HEAD(read_q);
155static struct fasync_struct *fasync_q;
156static atomic_t pretimeout_since_last_heartbeat;
157static char expect_close;
158
159static int ifnum_to_use = -1;
160
161/* Parameters to ipmi_set_timeout */
162#define IPMI_SET_TIMEOUT_NO_HB			0
163#define IPMI_SET_TIMEOUT_HB_IF_NECESSARY	1
164#define IPMI_SET_TIMEOUT_FORCE_HB		2
165
166static int ipmi_set_timeout(int do_heartbeat);
167static void ipmi_register_watchdog(int ipmi_intf);
168static void ipmi_unregister_watchdog(int ipmi_intf);
169
170/*
171 * If true, the driver will start running as soon as it is configured
172 * and ready.
173 */
174static int start_now;
175
176static int set_param_timeout(const char *val, const struct kernel_param *kp)
177{
178	char *endp;
179	int  l;
180	int  rv = 0;
181
182	if (!val)
183		return -EINVAL;
184	l = simple_strtoul(val, &endp, 0);
185	if (endp == val)
186		return -EINVAL;
187
188	*((int *)kp->arg) = l;
189	if (watchdog_user)
190		rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
191
192	return rv;
193}
194
195static const struct kernel_param_ops param_ops_timeout = {
196	.set = set_param_timeout,
197	.get = param_get_int,
198};
199#define param_check_timeout param_check_int
200
201typedef int (*action_fn)(const char *intval, char *outval);
202
203static int action_op(const char *inval, char *outval);
204static int preaction_op(const char *inval, char *outval);
205static int preop_op(const char *inval, char *outval);
206static void check_parms(void);
207
208static int set_param_str(const char *val, const struct kernel_param *kp)
209{
210	action_fn  fn = (action_fn) kp->arg;
211	int        rv = 0;
212	char       valcp[16];
213	char       *s;
214
215	strncpy(valcp, val, 15);
216	valcp[15] = '\0';
217
218	s = strstrip(valcp);
219
220	rv = fn(s, NULL);
221	if (rv)
222		goto out;
223
224	check_parms();
225	if (watchdog_user)
226		rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
227
228 out:
229	return rv;
230}
231
232static int get_param_str(char *buffer, const struct kernel_param *kp)
233{
234	action_fn fn = (action_fn) kp->arg;
235	int rv, len;
236
237	rv = fn(NULL, buffer);
238	if (rv)
239		return rv;
240
241	len = strlen(buffer);
242	buffer[len++] = '\n';
243	buffer[len] = 0;
244
245	return len;
246}
247
248
249static int set_param_wdog_ifnum(const char *val, const struct kernel_param *kp)
250{
251	int rv = param_set_int(val, kp);
252	if (rv)
253		return rv;
254	if ((ifnum_to_use < 0) || (ifnum_to_use == watchdog_ifnum))
255		return 0;
256
257	ipmi_unregister_watchdog(watchdog_ifnum);
258	ipmi_register_watchdog(ifnum_to_use);
259	return 0;
260}
261
262static const struct kernel_param_ops param_ops_wdog_ifnum = {
263	.set = set_param_wdog_ifnum,
264	.get = param_get_int,
265};
266
267#define param_check_wdog_ifnum param_check_int
268
269static const struct kernel_param_ops param_ops_str = {
270	.set = set_param_str,
271	.get = get_param_str,
272};
273
274module_param(ifnum_to_use, wdog_ifnum, 0644);
275MODULE_PARM_DESC(ifnum_to_use, "The interface number to use for the watchdog "
276		 "timer.  Setting to -1 defaults to the first registered "
277		 "interface");
278
279module_param(timeout, timeout, 0644);
280MODULE_PARM_DESC(timeout, "Timeout value in seconds.");
281
282module_param(pretimeout, timeout, 0644);
283MODULE_PARM_DESC(pretimeout, "Pretimeout value in seconds.");
284
285module_param(panic_wdt_timeout, timeout, 0644);
286MODULE_PARM_DESC(panic_wdt_timeout, "Timeout value on kernel panic in seconds.");
287
288module_param_cb(action, &param_ops_str, action_op, 0644);
289MODULE_PARM_DESC(action, "Timeout action. One of: "
290		 "reset, none, power_cycle, power_off.");
291
292module_param_cb(preaction, &param_ops_str, preaction_op, 0644);
293MODULE_PARM_DESC(preaction, "Pretimeout action.  One of: "
294		 "pre_none, pre_smi, pre_nmi, pre_int.");
295
296module_param_cb(preop, &param_ops_str, preop_op, 0644);
297MODULE_PARM_DESC(preop, "Pretimeout driver operation.  One of: "
298		 "preop_none, preop_panic, preop_give_data.");
299
300module_param(start_now, int, 0444);
301MODULE_PARM_DESC(start_now, "Set to 1 to start the watchdog as"
302		 "soon as the driver is loaded.");
303
304module_param(nowayout, bool, 0644);
305MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started "
306		 "(default=CONFIG_WATCHDOG_NOWAYOUT)");
307
308/* Default state of the timer. */
309static unsigned char ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
310
311/* Is someone using the watchdog?  Only one user is allowed. */
312static unsigned long ipmi_wdog_open;
313
314/*
315 * If set to 1, the heartbeat command will set the state to reset and
316 * start the timer.  The timer doesn't normally run when the driver is
317 * first opened until the heartbeat is set the first time, this
318 * variable is used to accomplish this.
319 */
320static int ipmi_start_timer_on_heartbeat;
321
322/* IPMI version of the BMC. */
323static unsigned char ipmi_version_major;
324static unsigned char ipmi_version_minor;
325
326/* If a pretimeout occurs, this is used to allow only one panic to happen. */
327static atomic_t preop_panic_excl = ATOMIC_INIT(-1);
328
329#ifdef HAVE_DIE_NMI
330static int testing_nmi;
331static int nmi_handler_registered;
332#endif
333
334static int __ipmi_heartbeat(void);
335
336/*
337 * We use a mutex to make sure that only one thing can send a set a
338 * message at one time.  The mutex is claimed when a message is sent
339 * and freed when both the send and receive messages are free.
340 */
341static atomic_t msg_tofree = ATOMIC_INIT(0);
342static DECLARE_COMPLETION(msg_wait);
343static void msg_free_smi(struct ipmi_smi_msg *msg)
344{
345	if (atomic_dec_and_test(&msg_tofree)) {
346		if (!oops_in_progress)
347			complete(&msg_wait);
348	}
349}
350static void msg_free_recv(struct ipmi_recv_msg *msg)
351{
352	if (atomic_dec_and_test(&msg_tofree)) {
353		if (!oops_in_progress)
354			complete(&msg_wait);
355	}
356}
357static struct ipmi_smi_msg smi_msg = {
358	.done = msg_free_smi
359};
360static struct ipmi_recv_msg recv_msg = {
361	.done = msg_free_recv
362};
363
364static int __ipmi_set_timeout(struct ipmi_smi_msg  *smi_msg,
365			      struct ipmi_recv_msg *recv_msg,
366			      int                  *send_heartbeat_now)
367{
368	struct kernel_ipmi_msg            msg;
369	unsigned char                     data[6];
370	int                               rv;
371	struct ipmi_system_interface_addr addr;
372	int                               hbnow = 0;
373
374
375	data[0] = 0;
376	WDOG_SET_TIMER_USE(data[0], WDOG_TIMER_USE_SMS_OS);
377
378	if (ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
379		if ((ipmi_version_major > 1) ||
380		    ((ipmi_version_major == 1) && (ipmi_version_minor >= 5))) {
381			/* This is an IPMI 1.5-only feature. */
382			data[0] |= WDOG_DONT_STOP_ON_SET;
383		} else {
384			/*
385			 * In ipmi 1.0, setting the timer stops the watchdog, we
386			 * need to start it back up again.
387			 */
388			hbnow = 1;
389		}
390	}
391
392	data[1] = 0;
393	WDOG_SET_TIMEOUT_ACT(data[1], ipmi_watchdog_state);
394	if ((pretimeout > 0) && (ipmi_watchdog_state != WDOG_TIMEOUT_NONE)) {
395	    WDOG_SET_PRETIMEOUT_ACT(data[1], preaction_val);
396	    data[2] = pretimeout;
397	} else {
398	    WDOG_SET_PRETIMEOUT_ACT(data[1], WDOG_PRETIMEOUT_NONE);
399	    data[2] = 0; /* No pretimeout. */
400	}
401	data[3] = 0;
402	WDOG_SET_TIMEOUT(data[4], data[5], timeout);
403
404	addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
405	addr.channel = IPMI_BMC_CHANNEL;
406	addr.lun = 0;
407
408	msg.netfn = 0x06;
409	msg.cmd = IPMI_WDOG_SET_TIMER;
410	msg.data = data;
411	msg.data_len = sizeof(data);
412	rv = ipmi_request_supply_msgs(watchdog_user,
413				      (struct ipmi_addr *) &addr,
414				      0,
415				      &msg,
416				      NULL,
417				      smi_msg,
418				      recv_msg,
419				      1);
420	if (rv)
421		pr_warn("set timeout error: %d\n", rv);
422	else if (send_heartbeat_now)
423		*send_heartbeat_now = hbnow;
424
425	return rv;
426}
427
428static int _ipmi_set_timeout(int do_heartbeat)
429{
430	int send_heartbeat_now;
431	int rv;
432
433	if (!watchdog_user)
434		return -ENODEV;
435
436	atomic_set(&msg_tofree, 2);
437
438	rv = __ipmi_set_timeout(&smi_msg,
439				&recv_msg,
440				&send_heartbeat_now);
441	if (rv) {
442		atomic_set(&msg_tofree, 0);
443		return rv;
444	}
445
446	wait_for_completion(&msg_wait);
447
448	if ((do_heartbeat == IPMI_SET_TIMEOUT_FORCE_HB)
449		|| ((send_heartbeat_now)
450		    && (do_heartbeat == IPMI_SET_TIMEOUT_HB_IF_NECESSARY)))
451		rv = __ipmi_heartbeat();
452
453	return rv;
454}
455
456static int ipmi_set_timeout(int do_heartbeat)
457{
458	int rv;
459
460	mutex_lock(&ipmi_watchdog_mutex);
461	rv = _ipmi_set_timeout(do_heartbeat);
462	mutex_unlock(&ipmi_watchdog_mutex);
463
464	return rv;
465}
466
467static atomic_t panic_done_count = ATOMIC_INIT(0);
468
469static void panic_smi_free(struct ipmi_smi_msg *msg)
470{
471	atomic_dec(&panic_done_count);
472}
473static void panic_recv_free(struct ipmi_recv_msg *msg)
474{
475	atomic_dec(&panic_done_count);
476}
477
478static struct ipmi_smi_msg panic_halt_heartbeat_smi_msg = {
479	.done = panic_smi_free
480};
481static struct ipmi_recv_msg panic_halt_heartbeat_recv_msg = {
482	.done = panic_recv_free
483};
484
485static void panic_halt_ipmi_heartbeat(void)
486{
487	struct kernel_ipmi_msg             msg;
488	struct ipmi_system_interface_addr addr;
489	int rv;
490
491	/*
492	 * Don't reset the timer if we have the timer turned off, that
493	 * re-enables the watchdog.
494	 */
495	if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
496		return;
497
498	addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
499	addr.channel = IPMI_BMC_CHANNEL;
500	addr.lun = 0;
501
502	msg.netfn = 0x06;
503	msg.cmd = IPMI_WDOG_RESET_TIMER;
504	msg.data = NULL;
505	msg.data_len = 0;
506	atomic_add(2, &panic_done_count);
507	rv = ipmi_request_supply_msgs(watchdog_user,
508				      (struct ipmi_addr *) &addr,
509				      0,
510				      &msg,
511				      NULL,
512				      &panic_halt_heartbeat_smi_msg,
513				      &panic_halt_heartbeat_recv_msg,
514				      1);
515	if (rv)
516		atomic_sub(2, &panic_done_count);
517}
518
519static struct ipmi_smi_msg panic_halt_smi_msg = {
520	.done = panic_smi_free
521};
522static struct ipmi_recv_msg panic_halt_recv_msg = {
523	.done = panic_recv_free
524};
525
526/*
527 * Special call, doesn't claim any locks.  This is only to be called
528 * at panic or halt time, in run-to-completion mode, when the caller
529 * is the only CPU and the only thing that will be going is these IPMI
530 * calls.
531 */
532static void panic_halt_ipmi_set_timeout(void)
533{
534	int send_heartbeat_now;
535	int rv;
536
537	/* Wait for the messages to be free. */
538	while (atomic_read(&panic_done_count) != 0)
539		ipmi_poll_interface(watchdog_user);
540	atomic_add(2, &panic_done_count);
541	rv = __ipmi_set_timeout(&panic_halt_smi_msg,
542				&panic_halt_recv_msg,
543				&send_heartbeat_now);
544	if (rv) {
545		atomic_sub(2, &panic_done_count);
546		pr_warn("Unable to extend the watchdog timeout\n");
547	} else {
548		if (send_heartbeat_now)
549			panic_halt_ipmi_heartbeat();
550	}
551	while (atomic_read(&panic_done_count) != 0)
552		ipmi_poll_interface(watchdog_user);
553}
554
555static int __ipmi_heartbeat(void)
556{
557	struct kernel_ipmi_msg msg;
558	int rv;
559	struct ipmi_system_interface_addr addr;
560	int timeout_retries = 0;
561
562restart:
563	/*
564	 * Don't reset the timer if we have the timer turned off, that
565	 * re-enables the watchdog.
566	 */
567	if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
568		return 0;
569
570	atomic_set(&msg_tofree, 2);
571
572	addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
573	addr.channel = IPMI_BMC_CHANNEL;
574	addr.lun = 0;
575
576	msg.netfn = 0x06;
577	msg.cmd = IPMI_WDOG_RESET_TIMER;
578	msg.data = NULL;
579	msg.data_len = 0;
580	rv = ipmi_request_supply_msgs(watchdog_user,
581				      (struct ipmi_addr *) &addr,
582				      0,
583				      &msg,
584				      NULL,
585				      &smi_msg,
586				      &recv_msg,
587				      1);
588	if (rv) {
589		atomic_set(&msg_tofree, 0);
590		pr_warn("heartbeat send failure: %d\n", rv);
591		return rv;
592	}
593
594	/* Wait for the heartbeat to be sent. */
595	wait_for_completion(&msg_wait);
596
597	if (recv_msg.msg.data[0] == IPMI_WDOG_TIMER_NOT_INIT_RESP)  {
598		timeout_retries++;
599		if (timeout_retries > 3) {
600			pr_err("Unable to restore the IPMI watchdog's settings, giving up\n");
601			rv = -EIO;
602			goto out;
603		}
604
605		/*
606		 * The timer was not initialized, that means the BMC was
607		 * probably reset and lost the watchdog information.  Attempt
608		 * to restore the timer's info.  Note that we still hold
609		 * the heartbeat lock, to keep a heartbeat from happening
610		 * in this process, so must say no heartbeat to avoid a
611		 * deadlock on this mutex
612		 */
613		rv = _ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
614		if (rv) {
615			pr_err("Unable to send the command to set the watchdog's settings, giving up\n");
616			goto out;
617		}
618
619		/* Might need a heartbeat send, go ahead and do it. */
620		goto restart;
621	} else if (recv_msg.msg.data[0] != 0) {
622		/*
623		 * Got an error in the heartbeat response.  It was already
624		 * reported in ipmi_wdog_msg_handler, but we should return
625		 * an error here.
626		 */
627		rv = -EINVAL;
628	}
629
630out:
631	return rv;
632}
633
634static int _ipmi_heartbeat(void)
635{
636	int rv;
637
638	if (!watchdog_user)
639		return -ENODEV;
640
641	if (ipmi_start_timer_on_heartbeat) {
642		ipmi_start_timer_on_heartbeat = 0;
643		ipmi_watchdog_state = action_val;
644		rv = _ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
645	} else if (atomic_cmpxchg(&pretimeout_since_last_heartbeat, 1, 0)) {
646		/*
647		 * A pretimeout occurred, make sure we set the timeout.
648		 * We don't want to set the action, though, we want to
649		 * leave that alone (thus it can't be combined with the
650		 * above operation.
651		 */
652		rv = _ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
653	} else {
654		rv = __ipmi_heartbeat();
655	}
656
657	return rv;
658}
659
660static int ipmi_heartbeat(void)
661{
662	int rv;
663
664	mutex_lock(&ipmi_watchdog_mutex);
665	rv = _ipmi_heartbeat();
666	mutex_unlock(&ipmi_watchdog_mutex);
667
668	return rv;
669}
670
671static struct watchdog_info ident = {
672	.options	= 0,	/* WDIOF_SETTIMEOUT, */
673	.firmware_version = 1,
674	.identity	= "IPMI"
675};
676
677static int ipmi_ioctl(struct file *file,
678		      unsigned int cmd, unsigned long arg)
679{
680	void __user *argp = (void __user *)arg;
681	int i;
682	int val;
683
684	switch (cmd) {
685	case WDIOC_GETSUPPORT:
686		i = copy_to_user(argp, &ident, sizeof(ident));
687		return i ? -EFAULT : 0;
688
689	case WDIOC_SETTIMEOUT:
690		i = copy_from_user(&val, argp, sizeof(int));
691		if (i)
692			return -EFAULT;
693		timeout = val;
694		return _ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
695
696	case WDIOC_GETTIMEOUT:
697		i = copy_to_user(argp, &timeout, sizeof(timeout));
698		if (i)
699			return -EFAULT;
700		return 0;
701
702	case WDIOC_SETPRETIMEOUT:
703		i = copy_from_user(&val, argp, sizeof(int));
704		if (i)
705			return -EFAULT;
706		pretimeout = val;
707		return _ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
708
709	case WDIOC_GETPRETIMEOUT:
710		i = copy_to_user(argp, &pretimeout, sizeof(pretimeout));
711		if (i)
712			return -EFAULT;
713		return 0;
714
715	case WDIOC_KEEPALIVE:
716		return _ipmi_heartbeat();
717
718	case WDIOC_SETOPTIONS:
719		i = copy_from_user(&val, argp, sizeof(int));
720		if (i)
721			return -EFAULT;
722		if (val & WDIOS_DISABLECARD) {
723			ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
724			_ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
725			ipmi_start_timer_on_heartbeat = 0;
726		}
727
728		if (val & WDIOS_ENABLECARD) {
729			ipmi_watchdog_state = action_val;
730			_ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
731		}
732		return 0;
733
734	case WDIOC_GETSTATUS:
735		val = 0;
736		i = copy_to_user(argp, &val, sizeof(val));
737		if (i)
738			return -EFAULT;
739		return 0;
740
741	default:
742		return -ENOIOCTLCMD;
743	}
744}
745
746static long ipmi_unlocked_ioctl(struct file *file,
747				unsigned int cmd,
748				unsigned long arg)
749{
750	int ret;
751
752	mutex_lock(&ipmi_watchdog_mutex);
753	ret = ipmi_ioctl(file, cmd, arg);
754	mutex_unlock(&ipmi_watchdog_mutex);
755
756	return ret;
757}
758
759static ssize_t ipmi_write(struct file *file,
760			  const char  __user *buf,
761			  size_t      len,
762			  loff_t      *ppos)
763{
764	int rv;
765
766	if (len) {
767		if (!nowayout) {
768			size_t i;
769
770			/* In case it was set long ago */
771			expect_close = 0;
772
773			for (i = 0; i != len; i++) {
774				char c;
775
776				if (get_user(c, buf + i))
777					return -EFAULT;
778				if (c == 'V')
779					expect_close = 42;
780			}
781		}
782		rv = ipmi_heartbeat();
783		if (rv)
784			return rv;
785	}
786	return len;
787}
788
789static ssize_t ipmi_read(struct file *file,
790			 char        __user *buf,
791			 size_t      count,
792			 loff_t      *ppos)
793{
794	int          rv = 0;
795	wait_queue_entry_t wait;
796
797	if (count <= 0)
798		return 0;
799
800	/*
801	 * Reading returns if the pretimeout has gone off, and it only does
802	 * it once per pretimeout.
803	 */
804	spin_lock_irq(&ipmi_read_lock);
805	if (!data_to_read) {
806		if (file->f_flags & O_NONBLOCK) {
807			rv = -EAGAIN;
808			goto out;
809		}
810
811		init_waitqueue_entry(&wait, current);
812		add_wait_queue(&read_q, &wait);
813		while (!data_to_read) {
814			set_current_state(TASK_INTERRUPTIBLE);
815			spin_unlock_irq(&ipmi_read_lock);
816			schedule();
817			spin_lock_irq(&ipmi_read_lock);
818		}
819		remove_wait_queue(&read_q, &wait);
820
821		if (signal_pending(current)) {
822			rv = -ERESTARTSYS;
823			goto out;
824		}
825	}
826	data_to_read = 0;
827
828 out:
829	spin_unlock_irq(&ipmi_read_lock);
830
831	if (rv == 0) {
832		if (copy_to_user(buf, &data_to_read, 1))
833			rv = -EFAULT;
834		else
835			rv = 1;
836	}
837
838	return rv;
839}
840
841static int ipmi_open(struct inode *ino, struct file *filep)
842{
843	switch (iminor(ino)) {
844	case WATCHDOG_MINOR:
845		if (test_and_set_bit(0, &ipmi_wdog_open))
846			return -EBUSY;
847
848
849		/*
850		 * Don't start the timer now, let it start on the
851		 * first heartbeat.
852		 */
853		ipmi_start_timer_on_heartbeat = 1;
854		return stream_open(ino, filep);
855
856	default:
857		return (-ENODEV);
858	}
859}
860
861static __poll_t ipmi_poll(struct file *file, poll_table *wait)
862{
863	__poll_t mask = 0;
864
865	poll_wait(file, &read_q, wait);
866
867	spin_lock_irq(&ipmi_read_lock);
868	if (data_to_read)
869		mask |= (EPOLLIN | EPOLLRDNORM);
870	spin_unlock_irq(&ipmi_read_lock);
871
872	return mask;
873}
874
875static int ipmi_fasync(int fd, struct file *file, int on)
876{
877	int result;
878
879	result = fasync_helper(fd, file, on, &fasync_q);
880
881	return (result);
882}
883
884static int ipmi_close(struct inode *ino, struct file *filep)
885{
886	if (iminor(ino) == WATCHDOG_MINOR) {
887		if (expect_close == 42) {
888			mutex_lock(&ipmi_watchdog_mutex);
889			ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
890			_ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
891			mutex_unlock(&ipmi_watchdog_mutex);
892		} else {
893			pr_crit("Unexpected close, not stopping watchdog!\n");
894			ipmi_heartbeat();
895		}
896		clear_bit(0, &ipmi_wdog_open);
897	}
898
899	expect_close = 0;
900
901	return 0;
902}
903
904static const struct file_operations ipmi_wdog_fops = {
905	.owner   = THIS_MODULE,
906	.read    = ipmi_read,
907	.poll    = ipmi_poll,
908	.write   = ipmi_write,
909	.unlocked_ioctl = ipmi_unlocked_ioctl,
910	.compat_ioctl	= compat_ptr_ioctl,
911	.open    = ipmi_open,
912	.release = ipmi_close,
913	.fasync  = ipmi_fasync,
914	.llseek  = no_llseek,
915};
916
917static struct miscdevice ipmi_wdog_miscdev = {
918	.minor		= WATCHDOG_MINOR,
919	.name		= "watchdog",
920	.fops		= &ipmi_wdog_fops
921};
922
923static void ipmi_wdog_msg_handler(struct ipmi_recv_msg *msg,
924				  void                 *handler_data)
925{
926	if (msg->msg.cmd == IPMI_WDOG_RESET_TIMER &&
927			msg->msg.data[0] == IPMI_WDOG_TIMER_NOT_INIT_RESP)
928		pr_info("response: The IPMI controller appears to have been reset, will attempt to reinitialize the watchdog timer\n");
929	else if (msg->msg.data[0] != 0)
930		pr_err("response: Error %x on cmd %x\n",
931		       msg->msg.data[0],
932		       msg->msg.cmd);
933
934	ipmi_free_recv_msg(msg);
935}
936
937static void ipmi_wdog_pretimeout_handler(void *handler_data)
938{
939	if (preaction_val != WDOG_PRETIMEOUT_NONE) {
940		if (preop_val == WDOG_PREOP_PANIC) {
941			if (atomic_inc_and_test(&preop_panic_excl))
942				panic("Watchdog pre-timeout");
943		} else if (preop_val == WDOG_PREOP_GIVE_DATA) {
944			unsigned long flags;
945
946			spin_lock_irqsave(&ipmi_read_lock, flags);
947			data_to_read = 1;
948			wake_up_interruptible(&read_q);
949			kill_fasync(&fasync_q, SIGIO, POLL_IN);
950			spin_unlock_irqrestore(&ipmi_read_lock, flags);
951		}
952	}
953
954	/*
955	 * On some machines, the heartbeat will give an error and not
956	 * work unless we re-enable the timer.  So do so.
957	 */
958	atomic_set(&pretimeout_since_last_heartbeat, 1);
959}
960
961static void ipmi_wdog_panic_handler(void *user_data)
962{
963	static int panic_event_handled;
964
965	/*
966	 * On a panic, if we have a panic timeout, make sure to extend
967	 * the watchdog timer to a reasonable value to complete the
968	 * panic, if the watchdog timer is running.  Plus the
969	 * pretimeout is meaningless at panic time.
970	 */
971	if (watchdog_user && !panic_event_handled &&
972	    ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
973		/* Make sure we do this only once. */
974		panic_event_handled = 1;
975
976		timeout = panic_wdt_timeout;
977		pretimeout = 0;
978		panic_halt_ipmi_set_timeout();
979	}
980}
981
982static const struct ipmi_user_hndl ipmi_hndlrs = {
983	.ipmi_recv_hndl           = ipmi_wdog_msg_handler,
984	.ipmi_watchdog_pretimeout = ipmi_wdog_pretimeout_handler,
985	.ipmi_panic_handler       = ipmi_wdog_panic_handler
986};
987
988static void ipmi_register_watchdog(int ipmi_intf)
989{
990	int rv = -EBUSY;
991
992	if (watchdog_user)
993		goto out;
994
995	if ((ifnum_to_use >= 0) && (ifnum_to_use != ipmi_intf))
996		goto out;
997
998	watchdog_ifnum = ipmi_intf;
999
1000	rv = ipmi_create_user(ipmi_intf, &ipmi_hndlrs, NULL, &watchdog_user);
1001	if (rv < 0) {
1002		pr_crit("Unable to register with ipmi\n");
1003		goto out;
1004	}
1005
1006	rv = ipmi_get_version(watchdog_user,
1007			      &ipmi_version_major,
1008			      &ipmi_version_minor);
1009	if (rv) {
1010		pr_warn("Unable to get IPMI version, assuming 1.0\n");
1011		ipmi_version_major = 1;
1012		ipmi_version_minor = 0;
1013	}
1014
1015	rv = misc_register(&ipmi_wdog_miscdev);
1016	if (rv < 0) {
1017		ipmi_destroy_user(watchdog_user);
1018		watchdog_user = NULL;
1019		pr_crit("Unable to register misc device\n");
1020	}
1021
1022#ifdef HAVE_DIE_NMI
1023	if (nmi_handler_registered) {
1024		int old_pretimeout = pretimeout;
1025		int old_timeout = timeout;
1026		int old_preop_val = preop_val;
1027
1028		/*
1029		 * Set the pretimeout to go off in a second and give
1030		 * ourselves plenty of time to stop the timer.
1031		 */
1032		ipmi_watchdog_state = WDOG_TIMEOUT_RESET;
1033		preop_val = WDOG_PREOP_NONE; /* Make sure nothing happens */
1034		pretimeout = 99;
1035		timeout = 100;
1036
1037		testing_nmi = 1;
1038
1039		rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
1040		if (rv) {
1041			pr_warn("Error starting timer to test NMI: 0x%x.  The NMI pretimeout will likely not work\n",
1042				rv);
1043			rv = 0;
1044			goto out_restore;
1045		}
1046
1047		msleep(1500);
1048
1049		if (testing_nmi != 2) {
1050			pr_warn("IPMI NMI didn't seem to occur.  The NMI pretimeout will likely not work\n");
1051		}
1052 out_restore:
1053		testing_nmi = 0;
1054		preop_val = old_preop_val;
1055		pretimeout = old_pretimeout;
1056		timeout = old_timeout;
1057	}
1058#endif
1059
1060 out:
1061	if ((start_now) && (rv == 0)) {
1062		/* Run from startup, so start the timer now. */
1063		start_now = 0; /* Disable this function after first startup. */
1064		ipmi_watchdog_state = action_val;
1065		ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
1066		pr_info("Starting now!\n");
1067	} else {
1068		/* Stop the timer now. */
1069		ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
1070		ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
1071	}
1072}
1073
1074static void ipmi_unregister_watchdog(int ipmi_intf)
1075{
1076	int rv;
1077	struct ipmi_user *loc_user = watchdog_user;
1078
1079	if (!loc_user)
1080		return;
1081
1082	if (watchdog_ifnum != ipmi_intf)
1083		return;
1084
1085	/* Make sure no one can call us any more. */
1086	misc_deregister(&ipmi_wdog_miscdev);
1087
1088	watchdog_user = NULL;
1089
1090	/*
1091	 * Wait to make sure the message makes it out.  The lower layer has
1092	 * pointers to our buffers, we want to make sure they are done before
1093	 * we release our memory.
1094	 */
1095	while (atomic_read(&msg_tofree))
1096		msg_free_smi(NULL);
1097
1098	mutex_lock(&ipmi_watchdog_mutex);
1099
1100	/* Disconnect from IPMI. */
1101	rv = ipmi_destroy_user(loc_user);
1102	if (rv)
1103		pr_warn("error unlinking from IPMI: %d\n",  rv);
1104
1105	/* If it comes back, restart it properly. */
1106	ipmi_start_timer_on_heartbeat = 1;
1107
1108	mutex_unlock(&ipmi_watchdog_mutex);
1109}
1110
1111#ifdef HAVE_DIE_NMI
1112static int
1113ipmi_nmi(unsigned int val, struct pt_regs *regs)
1114{
1115	/*
1116	 * If we get here, it's an NMI that's not a memory or I/O
1117	 * error.  We can't truly tell if it's from IPMI or not
1118	 * without sending a message, and sending a message is almost
1119	 * impossible because of locking.
1120	 */
1121
1122	if (testing_nmi) {
1123		testing_nmi = 2;
1124		return NMI_HANDLED;
1125	}
1126
1127	/* If we are not expecting a timeout, ignore it. */
1128	if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
1129		return NMI_DONE;
1130
1131	if (preaction_val != WDOG_PRETIMEOUT_NMI)
1132		return NMI_DONE;
1133
1134	/*
1135	 * If no one else handled the NMI, we assume it was the IPMI
1136	 * watchdog.
1137	 */
1138	if (preop_val == WDOG_PREOP_PANIC) {
1139		/* On some machines, the heartbeat will give
1140		   an error and not work unless we re-enable
1141		   the timer.   So do so. */
1142		atomic_set(&pretimeout_since_last_heartbeat, 1);
1143		if (atomic_inc_and_test(&preop_panic_excl))
1144			nmi_panic(regs, "pre-timeout");
1145	}
1146
1147	return NMI_HANDLED;
1148}
1149#endif
1150
1151static int wdog_reboot_handler(struct notifier_block *this,
1152			       unsigned long         code,
1153			       void                  *unused)
1154{
1155	static int reboot_event_handled;
1156
1157	if ((watchdog_user) && (!reboot_event_handled)) {
1158		/* Make sure we only do this once. */
1159		reboot_event_handled = 1;
1160
1161		if (code == SYS_POWER_OFF || code == SYS_HALT) {
1162			/* Disable the WDT if we are shutting down. */
1163			ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
1164			ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
1165		} else if (ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
1166			/* Set a long timer to let the reboot happen or
1167			   reset if it hangs, but only if the watchdog
1168			   timer was already running. */
1169			if (timeout < 120)
1170				timeout = 120;
1171			pretimeout = 0;
1172			ipmi_watchdog_state = WDOG_TIMEOUT_RESET;
1173			ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
1174		}
1175	}
1176	return NOTIFY_OK;
1177}
1178
1179static struct notifier_block wdog_reboot_notifier = {
1180	.notifier_call	= wdog_reboot_handler,
1181	.next		= NULL,
1182	.priority	= 0
1183};
1184
1185static void ipmi_new_smi(int if_num, struct device *device)
1186{
1187	ipmi_register_watchdog(if_num);
1188}
1189
1190static void ipmi_smi_gone(int if_num)
1191{
1192	ipmi_unregister_watchdog(if_num);
1193}
1194
1195static struct ipmi_smi_watcher smi_watcher = {
1196	.owner    = THIS_MODULE,
1197	.new_smi  = ipmi_new_smi,
1198	.smi_gone = ipmi_smi_gone
1199};
1200
1201static int action_op(const char *inval, char *outval)
1202{
1203	if (outval)
1204		strcpy(outval, action);
1205
1206	if (!inval)
1207		return 0;
1208
1209	if (strcmp(inval, "reset") == 0)
1210		action_val = WDOG_TIMEOUT_RESET;
1211	else if (strcmp(inval, "none") == 0)
1212		action_val = WDOG_TIMEOUT_NONE;
1213	else if (strcmp(inval, "power_cycle") == 0)
1214		action_val = WDOG_TIMEOUT_POWER_CYCLE;
1215	else if (strcmp(inval, "power_off") == 0)
1216		action_val = WDOG_TIMEOUT_POWER_DOWN;
1217	else
1218		return -EINVAL;
1219	strcpy(action, inval);
1220	return 0;
1221}
1222
1223static int preaction_op(const char *inval, char *outval)
1224{
1225	if (outval)
1226		strcpy(outval, preaction);
1227
1228	if (!inval)
1229		return 0;
1230
1231	if (strcmp(inval, "pre_none") == 0)
1232		preaction_val = WDOG_PRETIMEOUT_NONE;
1233	else if (strcmp(inval, "pre_smi") == 0)
1234		preaction_val = WDOG_PRETIMEOUT_SMI;
1235#ifdef HAVE_DIE_NMI
1236	else if (strcmp(inval, "pre_nmi") == 0)
1237		preaction_val = WDOG_PRETIMEOUT_NMI;
1238#endif
1239	else if (strcmp(inval, "pre_int") == 0)
1240		preaction_val = WDOG_PRETIMEOUT_MSG_INT;
1241	else
1242		return -EINVAL;
1243	strcpy(preaction, inval);
1244	return 0;
1245}
1246
1247static int preop_op(const char *inval, char *outval)
1248{
1249	if (outval)
1250		strcpy(outval, preop);
1251
1252	if (!inval)
1253		return 0;
1254
1255	if (strcmp(inval, "preop_none") == 0)
1256		preop_val = WDOG_PREOP_NONE;
1257	else if (strcmp(inval, "preop_panic") == 0)
1258		preop_val = WDOG_PREOP_PANIC;
1259	else if (strcmp(inval, "preop_give_data") == 0)
1260		preop_val = WDOG_PREOP_GIVE_DATA;
1261	else
1262		return -EINVAL;
1263	strcpy(preop, inval);
1264	return 0;
1265}
1266
1267static void check_parms(void)
1268{
1269#ifdef HAVE_DIE_NMI
1270	int do_nmi = 0;
1271	int rv;
1272
1273	if (preaction_val == WDOG_PRETIMEOUT_NMI) {
1274		do_nmi = 1;
1275		if (preop_val == WDOG_PREOP_GIVE_DATA) {
1276			pr_warn("Pretimeout op is to give data but NMI pretimeout is enabled, setting pretimeout op to none\n");
1277			preop_op("preop_none", NULL);
1278			do_nmi = 0;
1279		}
1280	}
1281	if (do_nmi && !nmi_handler_registered) {
1282		rv = register_nmi_handler(NMI_UNKNOWN, ipmi_nmi, 0,
1283						"ipmi");
1284		if (rv) {
1285			pr_warn("Can't register nmi handler\n");
1286			return;
1287		} else
1288			nmi_handler_registered = 1;
1289	} else if (!do_nmi && nmi_handler_registered) {
1290		unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
1291		nmi_handler_registered = 0;
1292	}
1293#endif
1294}
1295
1296static int __init ipmi_wdog_init(void)
1297{
1298	int rv;
1299
1300	if (action_op(action, NULL)) {
1301		action_op("reset", NULL);
1302		pr_info("Unknown action '%s', defaulting to reset\n", action);
1303	}
1304
1305	if (preaction_op(preaction, NULL)) {
1306		preaction_op("pre_none", NULL);
1307		pr_info("Unknown preaction '%s', defaulting to none\n",
1308			preaction);
1309	}
1310
1311	if (preop_op(preop, NULL)) {
1312		preop_op("preop_none", NULL);
1313		pr_info("Unknown preop '%s', defaulting to none\n", preop);
1314	}
1315
1316	check_parms();
1317
1318	register_reboot_notifier(&wdog_reboot_notifier);
1319
1320	rv = ipmi_smi_watcher_register(&smi_watcher);
1321	if (rv) {
1322#ifdef HAVE_DIE_NMI
1323		if (nmi_handler_registered)
1324			unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
1325#endif
1326		unregister_reboot_notifier(&wdog_reboot_notifier);
1327		pr_warn("can't register smi watcher\n");
1328		return rv;
1329	}
1330
1331	pr_info("driver initialized\n");
1332
1333	return 0;
1334}
1335
1336static void __exit ipmi_wdog_exit(void)
1337{
1338	ipmi_smi_watcher_unregister(&smi_watcher);
1339	ipmi_unregister_watchdog(watchdog_ifnum);
1340
1341#ifdef HAVE_DIE_NMI
1342	if (nmi_handler_registered)
1343		unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
1344#endif
1345
1346	unregister_reboot_notifier(&wdog_reboot_notifier);
1347}
1348module_exit(ipmi_wdog_exit);
1349module_init(ipmi_wdog_init);
1350MODULE_LICENSE("GPL");
1351MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
1352MODULE_DESCRIPTION("watchdog timer based upon the IPMI interface.");
1353