xref: /openbsd-src/sys/kern/kern_timeout.c (revision cb39b41371628601fbe4c618205356d538b9d08a)
1 /*	$OpenBSD: kern_timeout.c,v 1.42 2015/03/14 03:38:50 jsg 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 #include <sys/mutex.h>
33 #include <sys/kernel.h>
34 #include <sys/queue.h>			/* _Q_INVALIDATE */
35 
36 #ifdef DDB
37 #include <machine/db_machdep.h>
38 #include <ddb/db_interface.h>
39 #include <ddb/db_sym.h>
40 #include <ddb/db_output.h>
41 #endif
42 
43 /*
44  * Timeouts are kept in a hierarchical timing wheel. The to_time is the value
45  * of the global variable "ticks" when the timeout should be called. There are
46  * four levels with 256 buckets each. See 'Scheme 7' in
47  * "Hashed and Hierarchical Timing Wheels: Efficient Data Structures for
48  * Implementing a Timer Facility" by George Varghese and Tony Lauck.
49  */
50 #define BUCKETS 1024
51 #define WHEELSIZE 256
52 #define WHEELMASK 255
53 #define WHEELBITS 8
54 
55 struct circq timeout_wheel[BUCKETS];	/* Queues of timeouts */
56 struct circq timeout_todo;		/* Worklist */
57 
58 #define MASKWHEEL(wheel, time) (((time) >> ((wheel)*WHEELBITS)) & WHEELMASK)
59 
60 #define BUCKET(rel, abs)						\
61     (timeout_wheel[							\
62 	((rel) <= (1 << (2*WHEELBITS)))					\
63 	    ? ((rel) <= (1 << WHEELBITS))				\
64 		? MASKWHEEL(0, (abs))					\
65 		: MASKWHEEL(1, (abs)) + WHEELSIZE			\
66 	    : ((rel) <= (1 << (3*WHEELBITS)))				\
67 		? MASKWHEEL(2, (abs)) + 2*WHEELSIZE			\
68 		: MASKWHEEL(3, (abs)) + 3*WHEELSIZE])
69 
70 #define MOVEBUCKET(wheel, time)						\
71     CIRCQ_APPEND(&timeout_todo,						\
72         &timeout_wheel[MASKWHEEL((wheel), (time)) + (wheel)*WHEELSIZE])
73 
74 /*
75  * The first thing in a struct timeout is its struct circq, so we
76  * can get back from a pointer to the latter to a pointer to the
77  * whole timeout with just a cast.
78  */
79 static __inline struct timeout *
80 timeout_from_circq(struct circq *p)
81 {
82 	return ((struct timeout *)(p));
83 }
84 
85 /*
86  * All wheels are locked with the same mutex.
87  *
88  * We need locking since the timeouts are manipulated from hardclock that's
89  * not behind the big lock.
90  */
91 struct mutex timeout_mutex = MUTEX_INITIALIZER(IPL_HIGH);
92 
93 /*
94  * Circular queue definitions.
95  */
96 
97 #define CIRCQ_INIT(elem) do {                   \
98         (elem)->next = (elem);                  \
99         (elem)->prev = (elem);                  \
100 } while (0)
101 
102 #define CIRCQ_INSERT(elem, list) do {           \
103         (elem)->prev = (list)->prev;            \
104         (elem)->next = (list);                  \
105         (list)->prev->next = (elem);            \
106         (list)->prev = (elem);                  \
107 } while (0)
108 
109 #define CIRCQ_APPEND(fst, snd) do {             \
110         if (!CIRCQ_EMPTY(snd)) {                \
111                 (fst)->prev->next = (snd)->next;\
112                 (snd)->next->prev = (fst)->prev;\
113                 (snd)->prev->next = (fst);      \
114                 (fst)->prev = (snd)->prev;      \
115                 CIRCQ_INIT(snd);                \
116         }                                       \
117 } while (0)
118 
119 #define CIRCQ_REMOVE(elem) do {                 \
120         (elem)->next->prev = (elem)->prev;      \
121         (elem)->prev->next = (elem)->next;      \
122 	_Q_INVALIDATE((elem)->prev);		\
123 	_Q_INVALIDATE((elem)->next);		\
124 } while (0)
125 
126 #define CIRCQ_FIRST(elem) ((elem)->next)
127 
128 #define CIRCQ_EMPTY(elem) (CIRCQ_FIRST(elem) == (elem))
129 
130 /*
131  * Some of the "math" in here is a bit tricky.
132  *
133  * We have to beware of wrapping ints.
134  * We use the fact that any element added to the queue must be added with a
135  * positive time. That means that any element `to' on the queue cannot be
136  * scheduled to timeout further in time than INT_MAX, but to->to_time can
137  * be positive or negative so comparing it with anything is dangerous.
138  * The only way we can use the to->to_time value in any predictable way
139  * is when we calculate how far in the future `to' will timeout -
140  * "to->to_time - ticks". The result will always be positive for future
141  * timeouts and 0 or negative for due timeouts.
142  */
143 extern int ticks;		/* XXX - move to sys/X.h */
144 
145 void
146 timeout_startup(void)
147 {
148 	int b;
149 
150 	CIRCQ_INIT(&timeout_todo);
151 	for (b = 0; b < nitems(timeout_wheel); b++)
152 		CIRCQ_INIT(&timeout_wheel[b]);
153 }
154 
155 void
156 timeout_set(struct timeout *new, void (*fn)(void *), void *arg)
157 {
158 	new->to_func = fn;
159 	new->to_arg = arg;
160 	new->to_flags = TIMEOUT_INITIALIZED;
161 }
162 
163 
164 int
165 timeout_add(struct timeout *new, int to_ticks)
166 {
167 	int old_time;
168 	int ret = 1;
169 
170 #ifdef DIAGNOSTIC
171 	if (!(new->to_flags & TIMEOUT_INITIALIZED))
172 		panic("timeout_add: not initialized");
173 	if (to_ticks < 0)
174 		panic("timeout_add: to_ticks (%d) < 0", to_ticks);
175 #endif
176 
177 	mtx_enter(&timeout_mutex);
178 	/* Initialize the time here, it won't change. */
179 	old_time = new->to_time;
180 	new->to_time = to_ticks + ticks;
181 	new->to_flags &= ~TIMEOUT_TRIGGERED;
182 
183 	/*
184 	 * If this timeout already is scheduled and now is moved
185 	 * earlier, reschedule it now. Otherwise leave it in place
186 	 * and let it be rescheduled later.
187 	 */
188 	if (new->to_flags & TIMEOUT_ONQUEUE) {
189 		if (new->to_time - ticks < old_time - ticks) {
190 			CIRCQ_REMOVE(&new->to_list);
191 			CIRCQ_INSERT(&new->to_list, &timeout_todo);
192 		}
193 		ret = 0;
194 	} else {
195 		new->to_flags |= TIMEOUT_ONQUEUE;
196 		CIRCQ_INSERT(&new->to_list, &timeout_todo);
197 	}
198 	mtx_leave(&timeout_mutex);
199 
200 	return (ret);
201 }
202 
203 int
204 timeout_add_tv(struct timeout *to, const struct timeval *tv)
205 {
206 	long long to_ticks;
207 
208 	to_ticks = (long long)hz * tv->tv_sec + tv->tv_usec / tick;
209 	if (to_ticks > INT_MAX)
210 		to_ticks = INT_MAX;
211 
212 	return (timeout_add(to, (int)to_ticks));
213 }
214 
215 int
216 timeout_add_ts(struct timeout *to, const struct timespec *ts)
217 {
218 	long long to_ticks;
219 
220 	to_ticks = (long long)hz * ts->tv_sec + ts->tv_nsec / (tick * 1000);
221 	if (to_ticks > INT_MAX)
222 		to_ticks = INT_MAX;
223 
224 	return (timeout_add(to, (int)to_ticks));
225 }
226 
227 int
228 timeout_add_bt(struct timeout *to, const struct bintime *bt)
229 {
230 	long long to_ticks;
231 
232 	to_ticks = (long long)hz * bt->sec + (long)(((uint64_t)1000000 *
233 	    (uint32_t)(bt->frac >> 32)) >> 32) / tick;
234 	if (to_ticks > INT_MAX)
235 		to_ticks = INT_MAX;
236 
237 	return (timeout_add(to, (int)to_ticks));
238 }
239 
240 int
241 timeout_add_sec(struct timeout *to, int secs)
242 {
243 	long long to_ticks;
244 
245 	to_ticks = (long long)hz * secs;
246 	if (to_ticks > INT_MAX)
247 		to_ticks = INT_MAX;
248 
249 	return (timeout_add(to, (int)to_ticks));
250 }
251 
252 int
253 timeout_add_msec(struct timeout *to, int msecs)
254 {
255 	long long to_ticks;
256 
257 	to_ticks = (long long)msecs * 1000 / tick;
258 	if (to_ticks > INT_MAX)
259 		to_ticks = INT_MAX;
260 
261 	return (timeout_add(to, (int)to_ticks));
262 }
263 
264 int
265 timeout_add_usec(struct timeout *to, int usecs)
266 {
267 	int to_ticks = usecs / tick;
268 
269 	return (timeout_add(to, to_ticks));
270 }
271 
272 int
273 timeout_add_nsec(struct timeout *to, int nsecs)
274 {
275 	int to_ticks = nsecs / (tick * 1000);
276 
277 	return (timeout_add(to, to_ticks));
278 }
279 
280 int
281 timeout_del(struct timeout *to)
282 {
283 	int ret = 0;
284 
285 	mtx_enter(&timeout_mutex);
286 	if (to->to_flags & TIMEOUT_ONQUEUE) {
287 		CIRCQ_REMOVE(&to->to_list);
288 		to->to_flags &= ~TIMEOUT_ONQUEUE;
289 		ret = 1;
290 	}
291 	to->to_flags &= ~TIMEOUT_TRIGGERED;
292 	mtx_leave(&timeout_mutex);
293 
294 	return (ret);
295 }
296 
297 /*
298  * This is called from hardclock() once every tick.
299  * We return !0 if we need to schedule a softclock.
300  */
301 int
302 timeout_hardclock_update(void)
303 {
304 	int ret;
305 
306 	mtx_enter(&timeout_mutex);
307 
308 	ticks++;
309 
310 	MOVEBUCKET(0, ticks);
311 	if (MASKWHEEL(0, ticks) == 0) {
312 		MOVEBUCKET(1, ticks);
313 		if (MASKWHEEL(1, ticks) == 0) {
314 			MOVEBUCKET(2, ticks);
315 			if (MASKWHEEL(2, ticks) == 0)
316 				MOVEBUCKET(3, ticks);
317 		}
318 	}
319 	ret = !CIRCQ_EMPTY(&timeout_todo);
320 	mtx_leave(&timeout_mutex);
321 
322 	return (ret);
323 }
324 
325 void
326 softclock(void *arg)
327 {
328 	struct timeout *to;
329 	void (*fn)(void *);
330 
331 	mtx_enter(&timeout_mutex);
332 	while (!CIRCQ_EMPTY(&timeout_todo)) {
333 
334 		to = timeout_from_circq(CIRCQ_FIRST(&timeout_todo));
335 		CIRCQ_REMOVE(&to->to_list);
336 
337 		/* If due run it, otherwise insert it into the right bucket. */
338 		if (to->to_time - ticks > 0) {
339 			CIRCQ_INSERT(&to->to_list,
340 			    &BUCKET((to->to_time - ticks), to->to_time));
341 		} else {
342 #ifdef DEBUG
343 			if (to->to_time - ticks < 0)
344 				printf("timeout delayed %d\n", to->to_time -
345 				    ticks);
346 #endif
347 			to->to_flags &= ~TIMEOUT_ONQUEUE;
348 			to->to_flags |= TIMEOUT_TRIGGERED;
349 
350 			fn = to->to_func;
351 			arg = to->to_arg;
352 
353 			mtx_leave(&timeout_mutex);
354 			fn(arg);
355 			mtx_enter(&timeout_mutex);
356 		}
357 	}
358 	mtx_leave(&timeout_mutex);
359 }
360 
361 #ifndef SMALL_KERNEL
362 void
363 timeout_adjust_ticks(int adj)
364 {
365 	struct timeout *to;
366 	struct circq *p;
367 	int new_ticks, b;
368 
369 	/* adjusting the monotonic clock backwards would be a Bad Thing */
370 	if (adj <= 0)
371 		return;
372 
373 	mtx_enter(&timeout_mutex);
374 	new_ticks = ticks + adj;
375 	for (b = 0; b < nitems(timeout_wheel); b++) {
376 		p = CIRCQ_FIRST(&timeout_wheel[b]);
377 		while (p != &timeout_wheel[b]) {
378 			to = timeout_from_circq(p);
379 			p = CIRCQ_FIRST(p);
380 
381 			/* when moving a timeout forward need to reinsert it */
382 			if (to->to_time - ticks < adj)
383 				to->to_time = new_ticks;
384 			CIRCQ_REMOVE(&to->to_list);
385 			CIRCQ_INSERT(&to->to_list, &timeout_todo);
386 		}
387 	}
388 	ticks = new_ticks;
389 	mtx_leave(&timeout_mutex);
390 }
391 #endif
392 
393 #ifdef DDB
394 void db_show_callout_bucket(struct circq *);
395 
396 void
397 db_show_callout_bucket(struct circq *bucket)
398 {
399 	struct timeout *to;
400 	struct circq *p;
401 	db_expr_t offset;
402 	char *name;
403 
404 	for (p = CIRCQ_FIRST(bucket); p != bucket; p = CIRCQ_FIRST(p)) {
405 		to = timeout_from_circq(p);
406 		db_find_sym_and_offset((db_addr_t)to->to_func, &name, &offset);
407 		name = name ? name : "?";
408 		db_printf("%9d %2td/%-4td %p  %s\n", to->to_time - ticks,
409 		    (bucket - timeout_wheel) / WHEELSIZE,
410 		    bucket - timeout_wheel, to->to_arg, name);
411 	}
412 }
413 
414 void
415 db_show_callout(db_expr_t addr, int haddr, db_expr_t count, char *modif)
416 {
417 	int b;
418 
419 	db_printf("ticks now: %d\n", ticks);
420 	db_printf("    ticks  wheel       arg  func\n");
421 
422 	db_show_callout_bucket(&timeout_todo);
423 	for (b = 0; b < nitems(timeout_wheel); b++)
424 		db_show_callout_bucket(&timeout_wheel[b]);
425 }
426 #endif
427