xref: /openbsd-src/sys/kern/kern_timeout.c (revision b725ae7711052a2233e31a66fefb8a752c388d7a)
1 /*	$OpenBSD: kern_timeout.c,v 1.18 2003/06/03 12:05:25 art Exp $	*/
2 /*
3  * Copyright (c) 2001 Thomas Nordin <nordin@openbsd.org>
4  * Copyright (c) 2000-2001 Artur Grabowski <art@openbsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
17  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
19  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/lock.h>
31 #include <sys/timeout.h>
32 
33 #ifdef DDB
34 #include <machine/db_machdep.h>
35 #include <ddb/db_interface.h>
36 #include <ddb/db_access.h>
37 #include <ddb/db_sym.h>
38 #include <ddb/db_output.h>
39 #endif
40 
41 /*
42  * Timeouts are kept in a hierarchical timing wheel. The to_time is the value
43  * of the global variable "ticks" when the timeout should be called. There are
44  * four levels with 256 buckets each. See 'Scheme 7' in
45  * "Hashed and Hierarchical Timing Wheels: Efficient Data Structures for
46  * Implementing a Timer Facility" by George Varghese and Tony Lauck.
47  */
48 #define BUCKETS 1024
49 #define WHEELSIZE 256
50 #define WHEELMASK 255
51 #define WHEELBITS 8
52 
53 struct circq timeout_wheel[BUCKETS];	/* Queues of timeouts */
54 struct circq timeout_todo;		/* Worklist */
55 
56 #define MASKWHEEL(wheel, time) (((time) >> ((wheel)*WHEELBITS)) & WHEELMASK)
57 
58 #define BUCKET(rel, abs)						\
59     (((rel) <= (1 << (2*WHEELBITS)))					\
60     	? ((rel) <= (1 << WHEELBITS))					\
61             ? timeout_wheel[MASKWHEEL(0, (abs))]			\
62             : timeout_wheel[MASKWHEEL(1, (abs)) + WHEELSIZE]		\
63         : ((rel) <= (1 << (3*WHEELBITS)))				\
64             ? timeout_wheel[MASKWHEEL(2, (abs)) + 2*WHEELSIZE]		\
65             : timeout_wheel[MASKWHEEL(3, (abs)) + 3*WHEELSIZE])
66 
67 #define MOVEBUCKET(wheel, time)						\
68     CIRCQ_APPEND(&timeout_todo,						\
69         &timeout_wheel[MASKWHEEL((wheel), (time)) + (wheel)*WHEELSIZE])
70 
71 /*
72  * All wheels are locked with the same lock (which must also block out all
73  * interrupts).
74  */
75 struct simplelock _timeout_lock;
76 
77 #define timeout_wheel_lock(s) \
78 	do { *(s) = splhigh(); simple_lock(&_timeout_lock); } while (0)
79 #define timeout_wheel_unlock(s) \
80 	do { simple_unlock(&_timeout_lock); splx(s); } while (0)
81 
82 /*
83  * Circular queue definitions.
84  */
85 
86 #define CIRCQ_INIT(elem) do {                   \
87         (elem)->next = (elem);                  \
88         (elem)->prev = (elem);                  \
89 } while (0)
90 
91 #define CIRCQ_INSERT(elem, list) do {           \
92         (elem)->prev = (list)->prev;            \
93         (elem)->next = (list);                  \
94         (list)->prev->next = (elem);            \
95         (list)->prev = (elem);                  \
96 } while (0)
97 
98 #define CIRCQ_APPEND(fst, snd) do {             \
99         if (!CIRCQ_EMPTY(snd)) {                \
100                 (fst)->prev->next = (snd)->next;\
101                 (snd)->next->prev = (fst)->prev;\
102                 (snd)->prev->next = (fst);      \
103                 (fst)->prev = (snd)->prev;      \
104                 CIRCQ_INIT(snd);                \
105         }                                       \
106 } while (0)
107 
108 #define CIRCQ_REMOVE(elem) do {                 \
109         (elem)->next->prev = (elem)->prev;      \
110         (elem)->prev->next = (elem)->next;      \
111 } while (0)
112 
113 #define CIRCQ_FIRST(elem) ((elem)->next)
114 
115 #define CIRCQ_EMPTY(elem) (CIRCQ_FIRST(elem) == (elem))
116 
117 /*
118  * Some of the "math" in here is a bit tricky.
119  *
120  * We have to beware of wrapping ints.
121  * We use the fact that any element added to the queue must be added with a
122  * positive time. That means that any element `to' on the queue cannot be
123  * scheduled to timeout further in time than INT_MAX, but to->to_time can
124  * be positive or negative so comparing it with anything is dangerous.
125  * The only way we can use the to->to_time value in any predictable way
126  * is when we calculate how far in the future `to' will timeout -
127  * "to->to_time - ticks". The result will always be positive for future
128  * timeouts and 0 or negative for due timeouts.
129  */
130 extern int ticks;		/* XXX - move to sys/X.h */
131 
132 void
133 timeout_startup(void)
134 {
135 	int b;
136 
137 	CIRCQ_INIT(&timeout_todo);
138 	for (b = 0; b < BUCKETS; b++)
139 		CIRCQ_INIT(&timeout_wheel[b]);
140 	simple_lock_init(&_timeout_lock);
141 }
142 
143 void
144 timeout_set(struct timeout *new, void (*fn)(void *), void *arg)
145 {
146 	new->to_func = fn;
147 	new->to_arg = arg;
148 	new->to_flags = TIMEOUT_INITIALIZED;
149 }
150 
151 
152 void
153 timeout_add(struct timeout *new, int to_ticks)
154 {
155 	int s;
156 	int old_time;
157 
158 #ifdef DIAGNOSTIC
159 	if (!(new->to_flags & TIMEOUT_INITIALIZED))
160 		panic("timeout_add: not initialized");
161 	if (to_ticks < 0)
162 		panic("timeout_add: to_ticks < 0");
163 #endif
164 
165 	timeout_wheel_lock(&s);
166 	/* Initialize the time here, it won't change. */
167 	old_time = new->to_time;
168 	new->to_time = to_ticks + ticks;
169 	new->to_flags &= ~TIMEOUT_TRIGGERED;
170 
171 	/*
172 	 * If this timeout already is scheduled and now is moved
173 	 * earlier, reschedule it now. Otherwise leave it in place
174 	 * and let it be rescheduled later.
175 	 */
176 	if (new->to_flags & TIMEOUT_ONQUEUE) {
177 		if (new->to_time - ticks < old_time - ticks) {
178 			CIRCQ_REMOVE(&new->to_list);
179 			CIRCQ_INSERT(&new->to_list, &timeout_todo);
180 		}
181 	} else {
182 		new->to_flags |= TIMEOUT_ONQUEUE;
183 		CIRCQ_INSERT(&new->to_list, &timeout_todo);
184 	}
185 
186 	timeout_wheel_unlock(s);
187 }
188 
189 void
190 timeout_del(struct timeout *to)
191 {
192 	int s;
193 
194 	timeout_wheel_lock(&s);
195 	if (to->to_flags & TIMEOUT_ONQUEUE) {
196 		CIRCQ_REMOVE(&to->to_list);
197 		to->to_flags &= ~TIMEOUT_ONQUEUE;
198 	}
199 	to->to_flags &= ~TIMEOUT_TRIGGERED;
200 	timeout_wheel_unlock(s);
201 }
202 
203 /*
204  * This is called from hardclock() once every tick.
205  * We return !0 if we need to schedule a softclock.
206  *
207  * We don't need locking in here.
208  */
209 int
210 timeout_hardclock_update(void)
211 {
212 	MOVEBUCKET(0, ticks);
213 	if (MASKWHEEL(0, ticks) == 0) {
214 		MOVEBUCKET(1, ticks);
215 		if (MASKWHEEL(1, ticks) == 0) {
216 			MOVEBUCKET(2, ticks);
217 			if (MASKWHEEL(2, ticks) == 0)
218 				MOVEBUCKET(3, ticks);
219 		}
220 	}
221 	return (!CIRCQ_EMPTY(&timeout_todo));
222 }
223 
224 void
225 softclock(void)
226 {
227 	struct timeout *to;
228 	int s;
229 	void (*fn)(void *);
230 	void *arg;
231 
232 	timeout_wheel_lock(&s);
233 	while (!CIRCQ_EMPTY(&timeout_todo)) {
234 
235 		to = (struct timeout *)CIRCQ_FIRST(&timeout_todo); /* XXX */
236 		CIRCQ_REMOVE(&to->to_list);
237 
238 		/* If due run it, otherwise insert it into the right bucket. */
239 		if (to->to_time - ticks > 0) {
240 			CIRCQ_INSERT(&to->to_list,
241 			    &BUCKET((to->to_time - ticks), to->to_time));
242 		} else {
243 #ifdef DEBUG
244 			if (to->to_time - ticks < 0)
245 				printf("timeout delayed %d\n", to->to_time -
246 				    ticks);
247 #endif
248 			to->to_flags &= ~TIMEOUT_ONQUEUE;
249 			to->to_flags |= TIMEOUT_TRIGGERED;
250 
251 			fn = to->to_func;
252 			arg = to->to_arg;
253 
254 			timeout_wheel_unlock(s);
255 			fn(arg);
256 			timeout_wheel_lock(&s);
257 		}
258 	}
259 	timeout_wheel_unlock(s);
260 }
261 
262 #ifdef DDB
263 void db_show_callout_bucket(struct circq *);
264 
265 void
266 db_show_callout_bucket(struct circq *bucket)
267 {
268 	struct timeout *to;
269 	struct circq *p;
270 	db_expr_t offset;
271 	char *name;
272 
273 	for (p = CIRCQ_FIRST(bucket); p != bucket; p = CIRCQ_FIRST(p)) {
274 		to = (struct timeout *)p; /* XXX */
275 		db_find_sym_and_offset((db_addr_t)to->to_func, &name, &offset);
276 		name = name ? name : "?";
277 		db_printf("%9d %2d/%-4d %8x  %s\n", to->to_time - ticks,
278 		    (bucket - timeout_wheel) / WHEELSIZE,
279 		    bucket - timeout_wheel, to->to_arg, name);
280 	}
281 }
282 
283 void
284 db_show_callout(db_expr_t addr, int haddr, db_expr_t count, char *modif)
285 {
286 	int s;
287 	int b;
288 
289 	db_printf("ticks now: %d\n", ticks);
290 	db_printf("    ticks  wheel       arg  func\n");
291 
292 	timeout_wheel_lock(&s);
293 
294 	db_show_callout_bucket(&timeout_todo);
295 	for (b = 0; b < BUCKETS; b++)
296 		db_show_callout_bucket(&timeout_wheel[b]);
297 
298 	timeout_wheel_unlock(s);
299 }
300 #endif
301