xref: /openbsd-src/sys/kern/kern_timeout.c (revision 06ccd5dad87daa7ede3ae33928857a729a8043ea)
1 /*	$OpenBSD: kern_timeout.c,v 1.19 2004/07/20 20:20:52 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 #include <sys/mutex.h>
33 
34 #ifdef DDB
35 #include <machine/db_machdep.h>
36 #include <ddb/db_interface.h>
37 #include <ddb/db_access.h>
38 #include <ddb/db_sym.h>
39 #include <ddb/db_output.h>
40 #endif
41 
42 /*
43  * Timeouts are kept in a hierarchical timing wheel. The to_time is the value
44  * of the global variable "ticks" when the timeout should be called. There are
45  * four levels with 256 buckets each. See 'Scheme 7' in
46  * "Hashed and Hierarchical Timing Wheels: Efficient Data Structures for
47  * Implementing a Timer Facility" by George Varghese and Tony Lauck.
48  */
49 #define BUCKETS 1024
50 #define WHEELSIZE 256
51 #define WHEELMASK 255
52 #define WHEELBITS 8
53 
54 struct circq timeout_wheel[BUCKETS];	/* Queues of timeouts */
55 struct circq timeout_todo;		/* Worklist */
56 
57 #define MASKWHEEL(wheel, time) (((time) >> ((wheel)*WHEELBITS)) & WHEELMASK)
58 
59 #define BUCKET(rel, abs)						\
60     (((rel) <= (1 << (2*WHEELBITS)))					\
61     	? ((rel) <= (1 << WHEELBITS))					\
62             ? timeout_wheel[MASKWHEEL(0, (abs))]			\
63             : timeout_wheel[MASKWHEEL(1, (abs)) + WHEELSIZE]		\
64         : ((rel) <= (1 << (3*WHEELBITS)))				\
65             ? timeout_wheel[MASKWHEEL(2, (abs)) + 2*WHEELSIZE]		\
66             : timeout_wheel[MASKWHEEL(3, (abs)) + 3*WHEELSIZE])
67 
68 #define MOVEBUCKET(wheel, time)						\
69     CIRCQ_APPEND(&timeout_todo,						\
70         &timeout_wheel[MASKWHEEL((wheel), (time)) + (wheel)*WHEELSIZE])
71 
72 /*
73  * All wheels are locked with the same mutex.
74  *
75  * We need locking since the timeouts are manipulated from hardclock that's
76  * not behind the big lock.
77  */
78 struct mutex timeout_mutex = MUTEX_INITIALIZER(IPL_HIGH);
79 
80 /*
81  * Circular queue definitions.
82  */
83 
84 #define CIRCQ_INIT(elem) do {                   \
85         (elem)->next = (elem);                  \
86         (elem)->prev = (elem);                  \
87 } while (0)
88 
89 #define CIRCQ_INSERT(elem, list) do {           \
90         (elem)->prev = (list)->prev;            \
91         (elem)->next = (list);                  \
92         (list)->prev->next = (elem);            \
93         (list)->prev = (elem);                  \
94 } while (0)
95 
96 #define CIRCQ_APPEND(fst, snd) do {             \
97         if (!CIRCQ_EMPTY(snd)) {                \
98                 (fst)->prev->next = (snd)->next;\
99                 (snd)->next->prev = (fst)->prev;\
100                 (snd)->prev->next = (fst);      \
101                 (fst)->prev = (snd)->prev;      \
102                 CIRCQ_INIT(snd);                \
103         }                                       \
104 } while (0)
105 
106 #define CIRCQ_REMOVE(elem) do {                 \
107         (elem)->next->prev = (elem)->prev;      \
108         (elem)->prev->next = (elem)->next;      \
109 } while (0)
110 
111 #define CIRCQ_FIRST(elem) ((elem)->next)
112 
113 #define CIRCQ_EMPTY(elem) (CIRCQ_FIRST(elem) == (elem))
114 
115 /*
116  * Some of the "math" in here is a bit tricky.
117  *
118  * We have to beware of wrapping ints.
119  * We use the fact that any element added to the queue must be added with a
120  * positive time. That means that any element `to' on the queue cannot be
121  * scheduled to timeout further in time than INT_MAX, but to->to_time can
122  * be positive or negative so comparing it with anything is dangerous.
123  * The only way we can use the to->to_time value in any predictable way
124  * is when we calculate how far in the future `to' will timeout -
125  * "to->to_time - ticks". The result will always be positive for future
126  * timeouts and 0 or negative for due timeouts.
127  */
128 extern int ticks;		/* XXX - move to sys/X.h */
129 
130 void
131 timeout_startup(void)
132 {
133 	int b;
134 
135 	CIRCQ_INIT(&timeout_todo);
136 	for (b = 0; b < BUCKETS; b++)
137 		CIRCQ_INIT(&timeout_wheel[b]);
138 }
139 
140 void
141 timeout_set(struct timeout *new, void (*fn)(void *), void *arg)
142 {
143 	new->to_func = fn;
144 	new->to_arg = arg;
145 	new->to_flags = TIMEOUT_INITIALIZED;
146 }
147 
148 
149 void
150 timeout_add(struct timeout *new, int to_ticks)
151 {
152 	int old_time;
153 
154 #ifdef DIAGNOSTIC
155 	if (!(new->to_flags & TIMEOUT_INITIALIZED))
156 		panic("timeout_add: not initialized");
157 	if (to_ticks < 0)
158 		panic("timeout_add: to_ticks < 0");
159 #endif
160 
161 	mtx_enter(&timeout_mutex);
162 	/* Initialize the time here, it won't change. */
163 	old_time = new->to_time;
164 	new->to_time = to_ticks + ticks;
165 	new->to_flags &= ~TIMEOUT_TRIGGERED;
166 
167 	/*
168 	 * If this timeout already is scheduled and now is moved
169 	 * earlier, reschedule it now. Otherwise leave it in place
170 	 * and let it be rescheduled later.
171 	 */
172 	if (new->to_flags & TIMEOUT_ONQUEUE) {
173 		if (new->to_time - ticks < old_time - ticks) {
174 			CIRCQ_REMOVE(&new->to_list);
175 			CIRCQ_INSERT(&new->to_list, &timeout_todo);
176 		}
177 	} else {
178 		new->to_flags |= TIMEOUT_ONQUEUE;
179 		CIRCQ_INSERT(&new->to_list, &timeout_todo);
180 	}
181 	mtx_leave(&timeout_mutex);
182 }
183 
184 void
185 timeout_del(struct timeout *to)
186 {
187 	mtx_enter(&timeout_mutex);
188 	if (to->to_flags & TIMEOUT_ONQUEUE) {
189 		CIRCQ_REMOVE(&to->to_list);
190 		to->to_flags &= ~TIMEOUT_ONQUEUE;
191 	}
192 	to->to_flags &= ~TIMEOUT_TRIGGERED;
193 	mtx_leave(&timeout_mutex);
194 }
195 
196 /*
197  * This is called from hardclock() once every tick.
198  * We return !0 if we need to schedule a softclock.
199  */
200 int
201 timeout_hardclock_update(void)
202 {
203 	mtx_enter(&timeout_mutex);
204 	MOVEBUCKET(0, ticks);
205 	if (MASKWHEEL(0, ticks) == 0) {
206 		MOVEBUCKET(1, ticks);
207 		if (MASKWHEEL(1, ticks) == 0) {
208 			MOVEBUCKET(2, ticks);
209 			if (MASKWHEEL(2, ticks) == 0)
210 				MOVEBUCKET(3, ticks);
211 		}
212 	}
213 	mtx_leave(&timeout_mutex);
214 	return (!CIRCQ_EMPTY(&timeout_todo));
215 }
216 
217 void
218 softclock(void)
219 {
220 	struct timeout *to;
221 	void (*fn)(void *);
222 	void *arg;
223 
224 	mtx_enter(&timeout_mutex);
225 	while (!CIRCQ_EMPTY(&timeout_todo)) {
226 
227 		to = (struct timeout *)CIRCQ_FIRST(&timeout_todo); /* XXX */
228 		CIRCQ_REMOVE(&to->to_list);
229 
230 		/* If due run it, otherwise insert it into the right bucket. */
231 		if (to->to_time - ticks > 0) {
232 			CIRCQ_INSERT(&to->to_list,
233 			    &BUCKET((to->to_time - ticks), to->to_time));
234 		} else {
235 #ifdef DEBUG
236 			if (to->to_time - ticks < 0)
237 				printf("timeout delayed %d\n", to->to_time -
238 				    ticks);
239 #endif
240 			to->to_flags &= ~TIMEOUT_ONQUEUE;
241 			to->to_flags |= TIMEOUT_TRIGGERED;
242 
243 			fn = to->to_func;
244 			arg = to->to_arg;
245 
246 			mtx_leave(&timeout_mutex);
247 			fn(arg);
248 			mtx_enter(&timeout_mutex);
249 		}
250 	}
251 	mtx_leave(&timeout_mutex);
252 }
253 
254 #ifdef DDB
255 void db_show_callout_bucket(struct circq *);
256 
257 void
258 db_show_callout_bucket(struct circq *bucket)
259 {
260 	struct timeout *to;
261 	struct circq *p;
262 	db_expr_t offset;
263 	char *name;
264 
265 	for (p = CIRCQ_FIRST(bucket); p != bucket; p = CIRCQ_FIRST(p)) {
266 		to = (struct timeout *)p; /* XXX */
267 		db_find_sym_and_offset((db_addr_t)to->to_func, &name, &offset);
268 		name = name ? name : "?";
269 		db_printf("%9d %2d/%-4d %8x  %s\n", to->to_time - ticks,
270 		    (bucket - timeout_wheel) / WHEELSIZE,
271 		    bucket - timeout_wheel, to->to_arg, name);
272 	}
273 }
274 
275 void
276 db_show_callout(db_expr_t addr, int haddr, db_expr_t count, char *modif)
277 {
278 	int b;
279 
280 	db_printf("ticks now: %d\n", ticks);
281 	db_printf("    ticks  wheel       arg  func\n");
282 
283 	mtx_enter(&timeout_mutex);
284 	db_show_callout_bucket(&timeout_todo);
285 	for (b = 0; b < BUCKETS; b++)
286 		db_show_callout_bucket(&timeout_wheel[b]);
287 	mtx_leave(&timeout_mutex);
288 }
289 #endif
290