~kris/9p

9hist

ref: 05490cdb1d38889d0d0e0fed6e5e48ee209cd86f 9hist/port/watchdog.c -rw-r--r-- 2.0 KiB
05490cdb — David du Colombier Plan 9 from Bell Labs 2001-04-07 25 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include	"u.h"
#include	"../port/lib.h"
#include	"mem.h"
#include	"dat.h"
#include	"fns.h"
#include	"../port/error.h"

#define WDMAGIC 0xfaceface

struct Watchdog
{
	Watchdog *next;
	ulong	magic;
	ulong	ticks;
	void	(*f)(int);
	ulong	arg;
	uchar	armed;
};

struct {
	Lock;
	Watchdog *wd;
} wdalloc;

Watchdog*
wdCreate(void)
{
	Watchdog *wd;

	wd = mallocz(sizeof(Watchdog), 1);
	if(wd == nil)
		return nil;
	wd->magic = WDMAGIC;
	return wd;
}

static char*
wdunlink(Watchdog *wd, ulong magic)
{
	char *rv;
	Watchdog **l;

	rv = "not started";
	ilock(&wdalloc);
	wd->magic = magic;
	for(l = &wdalloc.wd; *l != nil; l = &(*l)->next)
		if(*l == wd){
			*l = wd->next;
			rv = nil;
			break;
		}
	wd->armed = 0;
	iunlock(&wdalloc);
	return rv;
}

char*
wdDelete(Watchdog *wd)
{
	if(wd->magic != WDMAGIC)
		return "not a watchdog";

	wdunlink(wd, ~WDMAGIC);
	free(wd);

	return nil;
}

char*
wdStart(Watchdog *wd, ulong ms, void (*f)(int), int arg)
{
	Watchdog **l;

	if(wd->magic != WDMAGIC)
		return "not a watchdog";

	/* unchain it in case it already is chained */
	if(wd->armed)
		wdunlink(wd, WDMAGIC);

	/* chain the watchdogs in time order */
	ilock(&wdalloc);
	wd->ticks = MS2TK(ms) + MACHP(0)->ticks;
	wd->f = f;
	wd->arg = arg;
	wd->armed = 1;
	for(l = &wdalloc.wd; *l != nil; l = &(*l)->next)
		if(wd->ticks < (*l)->ticks)
			break;
	wd->next = *l;
	*l = wd;
	iunlock(&wdalloc);

	return nil;
}

char*
wdCancel(Watchdog *wd)
{
	if(wd->magic != WDMAGIC)
		return "not a watchdog";
	return wdunlink(wd, WDMAGIC);
}

static void
wdclock(void)
{
	Watchdog *wd, **l;

	/* find the barking dogs, remoe from the chain */
	ilock(&wdalloc);
	wd = wdalloc.wd;
	for(l = &wdalloc.wd; *l != nil; l = &(*l)->next)
		if(MACHP(0)->ticks - (*l)->ticks >= 0x10000000)
			break;
	if(l == &wdalloc.wd)
		wd = nil;
	else {
		wdalloc.wd = *l;
		*l = nil;
	}
	iunlock(&wdalloc);

	/* let them run */
	for(; wd != nil; wd = wd->next){
		wd->ticks = 0;
		wd->armed = 0;
		(*wd->f)(wd->arg);
	}
}

void
watchdoglink(void)
{
	addclock0link(wdclock);
}