1/*
2 *	SMsC 37B787 Watchdog Timer driver for Linux 2.6.x.x
3 *
4 *      Based on acquirewdt.c by Alan Cox <alan@redhat.com>
5 *       and some other existing drivers
6 *
7 *	This program is free software; you can redistribute it and/or
8 *	modify it under the terms of the GNU General Public License
9 *	as published by the Free Software Foundation; either version
10 *	2 of the License, or (at your option) any later version.
11 *
12 *	The authors do NOT admit liability nor provide warranty for
13 *	any of this software. This material is provided "AS-IS" in
14 *      the hope that it may be useful for others.
15 *
16 *	(C) Copyright 2003-2006  Sven Anders <anders@anduras.de>
17 *
18 *  History:
19 *	2003 - Created version 1.0 for Linux 2.4.x.
20 *	2006 - Ported to Linux 2.6, added nowayout and MAGICCLOSE
21 *             features. Released version 1.1
22 *
23 *  Theory of operation:
24 *
25 *      A Watchdog Timer (WDT) is a hardware circuit that can
26 *      reset the computer system in case of a software fault.
27 *      You probably knew that already.
28 *
29 *      Usually a userspace daemon will notify the kernel WDT driver
30 *      via the /dev/watchdog special device file that userspace is
31 *      still alive, at regular intervals.  When such a notification
32 *      occurs, the driver will usually tell the hardware watchdog
33 *      that everything is in order, and that the watchdog should wait
34 *      for yet another little while to reset the system.
35 *      If userspace fails (RAM error, kernel bug, whatever), the
36 *      notifications cease to occur, and the hardware watchdog will
37 *      reset the system (causing a reboot) after the timeout occurs.
38 *
39 * Create device with:
40 *  mknod /dev/watchdog c 10 130
41 *
42 * For an example userspace keep-alive daemon, see:
43 *   Documentation/watchdog/watchdog.txt
44 */
45
46#include <linux/module.h>
47#include <linux/moduleparam.h>
48#include <linux/types.h>
49#include <linux/miscdevice.h>
50#include <linux/watchdog.h>
51#include <linux/delay.h>
52#include <linux/fs.h>
53#include <linux/ioport.h>
54#include <linux/notifier.h>
55#include <linux/reboot.h>
56#include <linux/init.h>
57#include <linux/spinlock.h>
58
59#include <asm/io.h>
60#include <asm/uaccess.h>
61#include <asm/system.h>
62
63/* enable support for minutes as units? */
64/* (does not always work correctly, so disabled by default!) */
65#define SMSC_SUPPORT_MINUTES
66#undef SMSC_SUPPORT_MINUTES
67
68#define MAX_TIMEOUT     255
69
70#define UNIT_SECOND     0
71#define UNIT_MINUTE     1
72
73#define MODNAME		"smsc37b787_wdt: "
74#define VERSION         "1.1"
75
76#define IOPORT          0x3F0
77#define IOPORT_SIZE     2
78#define IODEV_NO        8
79
80static int unit = UNIT_SECOND;  /* timer's unit */
81static int timeout = 60;        /* timeout value: default is 60 "units" */
82static unsigned long timer_enabled = 0;   /* is the timer enabled? */
83
84static char expect_close;       /* is the close expected? */
85
86static spinlock_t io_lock;	/* to guard the watchdog from io races */
87
88static int nowayout = WATCHDOG_NOWAYOUT;
89
90/* -- Low level function ----------------------------------------*/
91
92/* unlock the IO chip */
93
94static inline void open_io_config(void)
95{
96        outb(0x55, IOPORT);
97	mdelay(1);
98        outb(0x55, IOPORT);
99}
100
101/* lock the IO chip */
102static inline void close_io_config(void)
103{
104        outb(0xAA, IOPORT);
105}
106
107/* select the IO device */
108static inline void select_io_device(unsigned char devno)
109{
110        outb(0x07, IOPORT);
111        outb(devno, IOPORT+1);
112}
113
114/* write to the control register */
115static inline void write_io_cr(unsigned char reg, unsigned char data)
116{
117        outb(reg, IOPORT);
118        outb(data, IOPORT+1);
119}
120
121/* read from the control register */
122static inline char read_io_cr(unsigned char reg)
123{
124        outb(reg, IOPORT);
125        return inb(IOPORT+1);
126}
127
128/* -- Medium level functions ------------------------------------*/
129
130static inline void gpio_bit12(unsigned char reg)
131{
132	// -- General Purpose I/O Bit 1.2 --
133	// Bit 0,   In/Out: 0 = Output, 1 = Input
134	// Bit 1,   Polarity: 0 = No Invert, 1 = Invert
135	// Bit 2,   Group Enable Intr.: 0 = Disable, 1 = Enable
136	// Bit 3/4, Function select: 00 = GPI/O, 01 = WDT, 10 = P17,
137	//                           11 = Either Edge Triggered Intr. 2
138        // Bit 5/6  (Reserved)
139	// Bit 7,   Output Type: 0 = Push Pull Bit, 1 = Open Drain
140        write_io_cr(0xE2, reg);
141}
142
143static inline void gpio_bit13(unsigned char reg)
144{
145	// -- General Purpose I/O Bit 1.3 --
146	// Bit 0,  In/Out: 0 = Output, 1 = Input
147	// Bit 1,  Polarity: 0 = No Invert, 1 = Invert
148	// Bit 2,  Group Enable Intr.: 0 = Disable, 1 = Enable
149	// Bit 3,  Function select: 0 = GPI/O, 1 = LED
150        // Bit 4-6 (Reserved)
151	// Bit 7,  Output Type: 0 = Push Pull Bit, 1 = Open Drain
152        write_io_cr(0xE3, reg);
153}
154
155static inline void wdt_timer_units(unsigned char new_units)
156{
157	// -- Watchdog timer units --
158	// Bit 0-6 (Reserved)
159	// Bit 7,  WDT Time-out Value Units Select
160	//         (0 = Minutes, 1 = Seconds)
161        write_io_cr(0xF1, new_units);
162}
163
164static inline void wdt_timeout_value(unsigned char new_timeout)
165{
166	// -- Watchdog Timer Time-out Value --
167	// Bit 0-7 Binary coded units (0=Disabled, 1..255)
168        write_io_cr(0xF2, new_timeout);
169}
170
171static inline void wdt_timer_conf(unsigned char conf)
172{
173	// -- Watchdog timer configuration --
174	// Bit 0   Joystick enable: 0* = No Reset, 1 = Reset WDT upon Gameport I/O
175	// Bit 1   Keyboard enable: 0* = No Reset, 1 = Reset WDT upon KBD Intr.
176	// Bit 2   Mouse enable: 0* = No Reset, 1 = Reset WDT upon Mouse Intr.
177        // Bit 3   Reset the timer
178        //         (Wrong in SMsC documentation? Given as: PowerLED Timout Enabled)
179	// Bit 4-7 WDT Interrupt Mapping: (0000* = Disabled,
180	//            0001=IRQ1, 0010=(Invalid), 0011=IRQ3 to 1111=IRQ15)
181        write_io_cr(0xF3, conf);
182}
183
184static inline void wdt_timer_ctrl(unsigned char reg)
185{
186	// -- Watchdog timer control --
187	// Bit 0   Status Bit: 0 = Timer counting, 1 = Timeout occured
188	// Bit 1   Power LED Toggle: 0 = Disable Toggle, 1 = Toggle at 1 Hz
189	// Bit 2   Force Timeout: 1 = Forces WD timeout event (self-cleaning)
190	// Bit 3   P20 Force Timeout enabled:
191	//          0 = P20 activity does not generate the WD timeout event
192	//          1 = P20 Allows rising edge of P20, from the keyboard
193	//              controller, to force the WD timeout event.
194	// Bit 4   (Reserved)
195	// -- Soft power management --
196	// Bit 5   Stop Counter: 1 = Stop software power down counter
197	//            set via register 0xB8, (self-cleaning)
198	//            (Upon read: 0 = Counter running, 1 = Counter stopped)
199	// Bit 6   Restart Counter: 1 = Restart software power down counter
200	//            set via register 0xB8, (self-cleaning)
201	// Bit 7   SPOFF: 1 = Force software power down (self-cleaning)
202
203        write_io_cr(0xF4, reg);
204}
205
206/* -- Higher level functions ------------------------------------*/
207
208/* initialize watchdog */
209
210static void wb_smsc_wdt_initialize(void)
211{
212        unsigned char old;
213
214	spin_lock(&io_lock);
215        open_io_config();
216        select_io_device(IODEV_NO);
217
218	// enable the watchdog
219	gpio_bit13(0x08);  // Select pin 80 = LED not GPIO
220	gpio_bit12(0x0A);  // Set pin 79 = WDT not GPIO/Output/Polarity=Invert
221
222	// disable the timeout
223        wdt_timeout_value(0);
224
225	// reset control register
226        wdt_timer_ctrl(0x00);
227
228	// reset configuration register
229	wdt_timer_conf(0x00);
230
231	// read old (timer units) register
232        old = read_io_cr(0xF1) & 0x7F;
233        if (unit == UNIT_SECOND) old |= 0x80; // set to seconds
234
235	// set the watchdog timer units
236        wdt_timer_units(old);
237
238        close_io_config();
239	spin_unlock(&io_lock);
240}
241
242/* shutdown the watchdog */
243
244static void wb_smsc_wdt_shutdown(void)
245{
246	spin_lock(&io_lock);
247        open_io_config();
248        select_io_device(IODEV_NO);
249
250	// disable the watchdog
251        gpio_bit13(0x09);
252        gpio_bit12(0x09);
253
254	// reset watchdog config register
255	wdt_timer_conf(0x00);
256
257	// reset watchdog control register
258        wdt_timer_ctrl(0x00);
259
260	// disable timeout
261        wdt_timeout_value(0x00);
262
263        close_io_config();
264	spin_unlock(&io_lock);
265}
266
267/* set timeout => enable watchdog */
268
269static void wb_smsc_wdt_set_timeout(unsigned char new_timeout)
270{
271	spin_lock(&io_lock);
272        open_io_config();
273        select_io_device(IODEV_NO);
274
275	// set Power LED to blink, if we enable the timeout
276        wdt_timer_ctrl((new_timeout == 0) ? 0x00 : 0x02);
277
278	// set timeout value
279        wdt_timeout_value(new_timeout);
280
281        close_io_config();
282	spin_unlock(&io_lock);
283}
284
285/* get timeout */
286
287static unsigned char wb_smsc_wdt_get_timeout(void)
288{
289        unsigned char set_timeout;
290
291	spin_lock(&io_lock);
292        open_io_config();
293        select_io_device(IODEV_NO);
294        set_timeout = read_io_cr(0xF2);
295        close_io_config();
296	spin_unlock(&io_lock);
297
298        return set_timeout;
299}
300
301/* disable watchdog */
302
303static void wb_smsc_wdt_disable(void)
304{
305        // set the timeout to 0 to disable the watchdog
306        wb_smsc_wdt_set_timeout(0);
307}
308
309/* enable watchdog by setting the current timeout */
310
311static void wb_smsc_wdt_enable(void)
312{
313        // set the current timeout...
314        wb_smsc_wdt_set_timeout(timeout);
315}
316
317/* reset the timer */
318
319static void wb_smsc_wdt_reset_timer(void)
320{
321	spin_lock(&io_lock);
322        open_io_config();
323        select_io_device(IODEV_NO);
324
325	// reset the timer
326	wdt_timeout_value(timeout);
327	wdt_timer_conf(0x08);
328
329        close_io_config();
330	spin_unlock(&io_lock);
331}
332
333/* return, if the watchdog is enabled (timeout is set...) */
334
335static int wb_smsc_wdt_status(void)
336{
337	return (wb_smsc_wdt_get_timeout() == 0) ? 0 : WDIOF_KEEPALIVEPING;
338}
339
340
341/* -- File operations -------------------------------------------*/
342
343/* open => enable watchdog and set initial timeout */
344
345static int wb_smsc_wdt_open(struct inode *inode, struct file *file)
346{
347	/* /dev/watchdog can only be opened once */
348
349	if (test_and_set_bit(0, &timer_enabled))
350		return -EBUSY;
351
352	if (nowayout)
353		__module_get(THIS_MODULE);
354
355	/* Reload and activate timer */
356	wb_smsc_wdt_enable();
357
358	printk(KERN_INFO MODNAME "Watchdog enabled. Timeout set to %d %s.\n", timeout, (unit == UNIT_SECOND) ? "second(s)" : "minute(s)");
359
360	return nonseekable_open(inode, file);
361}
362
363/* close => shut off the timer */
364
365static int wb_smsc_wdt_release(struct inode *inode, struct file *file)
366{
367	/* Shut off the timer. */
368
369	if (expect_close == 42) {
370	        wb_smsc_wdt_disable();
371		printk(KERN_INFO MODNAME "Watchdog disabled, sleeping again...\n");
372	} else {
373		printk(KERN_CRIT MODNAME "Unexpected close, not stopping watchdog!\n");
374		wb_smsc_wdt_reset_timer();
375	}
376
377	clear_bit(0, &timer_enabled);
378	expect_close = 0;
379	return 0;
380}
381
382/* write => update the timer to keep the machine alive */
383
384static ssize_t wb_smsc_wdt_write(struct file *file, const char __user *data,
385				 size_t len, loff_t *ppos)
386{
387	/* See if we got the magic character 'V' and reload the timer */
388	if (len) {
389		if (!nowayout) {
390			size_t i;
391
392			/* reset expect flag */
393			expect_close = 0;
394
395			/* scan to see whether or not we got the magic character */
396			for (i = 0; i != len; i++) {
397				char c;
398				if (get_user(c, data+i))
399					return -EFAULT;
400				if (c == 'V')
401					expect_close = 42;
402			}
403		}
404
405		/* someone wrote to us, we should reload the timer */
406		wb_smsc_wdt_reset_timer();
407	}
408	return len;
409}
410
411/* ioctl => control interface */
412
413static int wb_smsc_wdt_ioctl(struct inode *inode, struct file *file,
414			     unsigned int cmd, unsigned long arg)
415{
416	int new_timeout;
417
418	union {
419		struct watchdog_info __user *ident;
420		int __user *i;
421	} uarg;
422
423	static struct watchdog_info ident = {
424		.options = 		WDIOF_KEEPALIVEPING |
425		                        WDIOF_SETTIMEOUT |
426					WDIOF_MAGICCLOSE,
427		.firmware_version =	0,
428		.identity = 		"SMsC 37B787 Watchdog"
429	};
430
431	uarg.i = (int __user *)arg;
432
433	switch (cmd) {
434		default:
435			return -ENOTTY;
436
437		case WDIOC_GETSUPPORT:
438			return copy_to_user(uarg.ident, &ident,
439				sizeof(ident)) ? -EFAULT : 0;
440
441		case WDIOC_GETSTATUS:
442			return put_user(wb_smsc_wdt_status(), uarg.i);
443
444		case WDIOC_GETBOOTSTATUS:
445			return put_user(0, uarg.i);
446
447		case WDIOC_KEEPALIVE:
448			wb_smsc_wdt_reset_timer();
449			return 0;
450
451		case WDIOC_SETTIMEOUT:
452			if (get_user(new_timeout, uarg.i))
453				return -EFAULT;
454
455			// the API states this is given in secs
456			if (unit == UNIT_MINUTE)
457			  new_timeout /= 60;
458
459			if (new_timeout < 0 || new_timeout > MAX_TIMEOUT)
460				return -EINVAL;
461
462			timeout = new_timeout;
463			wb_smsc_wdt_set_timeout(timeout);
464
465			// fall through and return the new timeout...
466
467		case WDIOC_GETTIMEOUT:
468
469		        new_timeout = timeout;
470
471			if (unit == UNIT_MINUTE)
472			  new_timeout *= 60;
473
474			return put_user(new_timeout, uarg.i);
475
476		case WDIOC_SETOPTIONS:
477		{
478			int options, retval = -EINVAL;
479
480			if (get_user(options, uarg.i))
481				return -EFAULT;
482
483			if (options & WDIOS_DISABLECARD) {
484				wb_smsc_wdt_disable();
485				retval = 0;
486			}
487
488			if (options & WDIOS_ENABLECARD) {
489				wb_smsc_wdt_enable();
490				retval = 0;
491			}
492
493			return retval;
494		}
495	}
496}
497
498/* -- Notifier funtions -----------------------------------------*/
499
500static int wb_smsc_wdt_notify_sys(struct notifier_block *this, unsigned long code, void *unused)
501{
502	if (code == SYS_DOWN || code == SYS_HALT)
503	{
504                // set timeout to 0, to avoid possible race-condition
505	        timeout = 0;
506		wb_smsc_wdt_disable();
507	}
508	return NOTIFY_DONE;
509}
510
511/* -- Module's structures ---------------------------------------*/
512
513static const struct file_operations wb_smsc_wdt_fops =
514{
515	.owner          = THIS_MODULE,
516	.llseek		= no_llseek,
517	.write		= wb_smsc_wdt_write,
518	.ioctl		= wb_smsc_wdt_ioctl,
519	.open		= wb_smsc_wdt_open,
520	.release	= wb_smsc_wdt_release,
521};
522
523static struct notifier_block wb_smsc_wdt_notifier =
524{
525	.notifier_call  = wb_smsc_wdt_notify_sys,
526};
527
528static struct miscdevice wb_smsc_wdt_miscdev =
529{
530	.minor		= WATCHDOG_MINOR,
531	.name		= "watchdog",
532	.fops		= &wb_smsc_wdt_fops,
533};
534
535/* -- Module init functions -------------------------------------*/
536
537/* module's "constructor" */
538
539static int __init wb_smsc_wdt_init(void)
540{
541	int ret;
542
543	spin_lock_init(&io_lock);
544
545	printk("SMsC 37B787 watchdog component driver " VERSION " initialising...\n");
546
547	if (!request_region(IOPORT, IOPORT_SIZE, "SMsC 37B787 watchdog")) {
548		printk(KERN_ERR MODNAME "Unable to register IO port %#x\n", IOPORT);
549		ret = -EBUSY;
550		goto out_pnp;
551	}
552
553        // set new maximum, if it's too big
554        if (timeout > MAX_TIMEOUT)
555               timeout = MAX_TIMEOUT;
556
557        // init the watchdog timer
558        wb_smsc_wdt_initialize();
559
560	ret = register_reboot_notifier(&wb_smsc_wdt_notifier);
561	if (ret) {
562		printk(KERN_ERR MODNAME "Unable to register reboot notifier err = %d\n", ret);
563		goto out_io;
564	}
565
566	ret = misc_register(&wb_smsc_wdt_miscdev);
567	if (ret) {
568		printk(KERN_ERR MODNAME "Unable to register miscdev on minor %d\n", WATCHDOG_MINOR);
569		goto out_rbt;
570	}
571
572	// output info
573	printk(KERN_INFO MODNAME "Timeout set to %d %s.\n", timeout, (unit == UNIT_SECOND) ? "second(s)" : "minute(s)");
574	printk(KERN_INFO MODNAME "Watchdog initialized and sleeping (nowayout=%d)...\n", nowayout);
575
576	// ret = 0
577
578out_clean:
579	return ret;
580
581out_rbt:
582	unregister_reboot_notifier(&wb_smsc_wdt_notifier);
583
584out_io:
585	release_region(IOPORT, IOPORT_SIZE);
586
587out_pnp:
588	goto out_clean;
589}
590
591/* module's "destructor" */
592
593static void __exit wb_smsc_wdt_exit(void)
594{
595	/* Stop the timer before we leave */
596	if (!nowayout)
597	{
598		wb_smsc_wdt_shutdown();
599		printk(KERN_INFO MODNAME "Watchdog disabled.\n");
600	}
601
602	misc_deregister(&wb_smsc_wdt_miscdev);
603	unregister_reboot_notifier(&wb_smsc_wdt_notifier);
604	release_region(IOPORT, IOPORT_SIZE);
605
606	printk("SMsC 37B787 watchdog component driver removed.\n");
607}
608
609module_init(wb_smsc_wdt_init);
610module_exit(wb_smsc_wdt_exit);
611
612MODULE_AUTHOR("Sven Anders <anders@anduras.de>");
613MODULE_DESCRIPTION("Driver for SMsC 37B787 watchdog component (Version " VERSION ")");
614MODULE_LICENSE("GPL");
615
616MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
617
618#ifdef SMSC_SUPPORT_MINUTES
619module_param(unit, int, 0);
620MODULE_PARM_DESC(unit, "set unit to use, 0=seconds or 1=minutes, default is 0");
621#endif
622
623module_param(timeout, int, 0);
624MODULE_PARM_DESC(timeout, "range is 1-255 units, default is 60");
625
626module_param(nowayout, int, 0);
627MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
628