summaryrefslogtreecommitdiff
path: root/sys/src/boot/pc/alarm.c
blob: f07d038b7393f880d1a277eadc9a03c6dbc4c484 (plain)
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
#include	"u.h"
#include	"lib.h"
#include	"mem.h"
#include	"dat.h"
#include	"fns.h"
#include	"io.h"

#define NA	10		/* max. alarms per clock tick */
#define	MAXALARM (3 * NA)

Alarm	alarmtab[MAXALARM];

/*
 * Insert new into list after where
 */
void
insert(List **head, List *where, List *new)
{
	if(where == 0){
		new->next = *head;
		*head = new;
	}else{
		new->next = where->next;
		where->next = new;
	}
		
}

/*
 * Delete old from list.  where->next is known to be old.
 */
void
delete(List **head, List *where, List *old)
{
	if(where == 0){
		*head = old->next;
		return;
	}
	where->next = old->next;
}

Alarm*
newalarm(void)
{
	int i;
	Alarm *a;

	for(i=0,a=alarmtab; i < nelem(alarmtab); i++,a++)
		if(a->busy==0 && a->f==0){
			a->f = 0;
			a->arg = 0;
			a->busy = 1;
			return a;
		}
	panic("newalarm");
	return 0;	/* not reached */
}

Alarm*
alarm(int ms, void (*f)(Alarm*), void *arg)
{
	Alarm *a, *w, *pw;
	ulong s;

	if(ms < 0)
		ms = 0;
	s = splhi();
	a = newalarm();
	a->dt = MS2TK(ms);
	a->f = f;
	a->arg = arg;
	pw = 0;
	for(w=m->alarm; w; pw=w, w=w->next){
		if(w->dt <= a->dt){
			a->dt -= w->dt;
			continue;
		}
		w->dt -= a->dt;
		break;
	}
	insert(&m->alarm, pw, a);
	splx(s);
	return a;
}

void
cancel(Alarm *a)
{
	a->f = 0;
}

void
alarminit(void)
{
}

void
checkalarms(void)
{
	int i, n, s;
	Alarm *a;
	void (*f)(Alarm*);
	Alarm *alist[NA];

	s = splhi();
	a = m->alarm;
	if(a){
		for(n=0; a && a->dt<=0 && n<NA; n++){
			alist[n] = a;
			delete(&m->alarm, 0, a);
			a = m->alarm;
		}
		if(a)
			a->dt--;

		for(i = 0; i < n; i++){
			f = alist[i]->f;	/* avoid race with cancel */
			if(f)
				(*f)(alist[i]);
			alist[i]->busy = 0;
		}
	}
	splx(s);
}