xref: /freebsd/sys/kern/kern_timeout.c (revision 390e8cc2974df1888369c06339ef8e0e92b312b6)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
39  * $FreeBSD$
40  */
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/callout.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
49 
50 static int avg_depth;
51 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
52     "Average number of items examined per softclock call. Units = 1/1000");
53 static int avg_gcalls;
54 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
55     "Average number of Giant callouts made per softclock call. Units = 1/1000");
56 static int avg_mpcalls;
57 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
58     "Average number of MP callouts made per softclock call. Units = 1/1000");
59 /*
60  * TODO:
61  *	allocate more timeout table slots when table overflows.
62  */
63 
64 /* Exported to machdep.c and/or kern_clock.c.  */
65 struct callout *callout;
66 struct callout_list callfree;
67 int callwheelsize, callwheelbits, callwheelmask;
68 struct callout_tailq *callwheel;
69 int softticks;			/* Like ticks, but for softclock(). */
70 struct mtx callout_lock;
71 
72 static struct callout *nextsoftcheck;	/* Next callout to be checked. */
73 
74 /*
75  * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization
76  *
77  *	This code is called very early in the kernel initialization sequence,
78  *	and may be called more then once.
79  */
80 caddr_t
81 kern_timeout_callwheel_alloc(caddr_t v)
82 {
83 	/*
84 	 * Calculate callout wheel size
85 	 */
86 	for (callwheelsize = 1, callwheelbits = 0;
87 	     callwheelsize < ncallout;
88 	     callwheelsize <<= 1, ++callwheelbits)
89 		;
90 	callwheelmask = callwheelsize - 1;
91 
92 	callout = (struct callout *)v;
93 	v = (caddr_t)(callout + ncallout);
94 	callwheel = (struct callout_tailq *)v;
95 	v = (caddr_t)(callwheel + callwheelsize);
96 	return(v);
97 }
98 
99 /*
100  * kern_timeout_callwheel_init() - initialize previously reserved callwheel
101  *				   space.
102  *
103  *	This code is called just once, after the space reserved for the
104  *	callout wheel has been finalized.
105  */
106 void
107 kern_timeout_callwheel_init(void)
108 {
109 	int i;
110 
111 	SLIST_INIT(&callfree);
112 	for (i = 0; i < ncallout; i++) {
113 		callout_init(&callout[i], 0);
114 		callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
115 		SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
116 	}
117 	for (i = 0; i < callwheelsize; i++) {
118 		TAILQ_INIT(&callwheel[i]);
119 	}
120 	mtx_init(&callout_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
121 }
122 
123 /*
124  * The callout mechanism is based on the work of Adam M. Costello and
125  * George Varghese, published in a technical report entitled "Redesigning
126  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
127  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
128  * used in this implementation was published by G.Varghese and A. Lauck in
129  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
130  * the Efficient Implementation of a Timer Facility" in the Proceedings of
131  * the 11th ACM Annual Symposium on Operating Systems Principles,
132  * Austin, Texas Nov 1987.
133  */
134 
135 /*
136  * Software (low priority) clock interrupt.
137  * Run periodic events from timeout queue.
138  */
139 void
140 softclock(void *dummy)
141 {
142 	struct callout *c;
143 	struct callout_tailq *bucket;
144 	int curticks;
145 	int steps;	/* #steps since we last allowed interrupts */
146 	int depth;
147 	int mpcalls;
148 	int gcalls;
149 #ifdef DIAGNOSTIC
150 	struct bintime bt1, bt2;
151 	struct timespec ts2;
152 	static uint64_t maxdt = 18446744073709551LL;	/* 1 msec */
153 #endif
154 
155 #ifndef MAX_SOFTCLOCK_STEPS
156 #define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
157 #endif /* MAX_SOFTCLOCK_STEPS */
158 
159 	mpcalls = 0;
160 	gcalls = 0;
161 	depth = 0;
162 	steps = 0;
163 	mtx_lock_spin(&callout_lock);
164 	while (softticks != ticks) {
165 		softticks++;
166 		/*
167 		 * softticks may be modified by hard clock, so cache
168 		 * it while we work on a given bucket.
169 		 */
170 		curticks = softticks;
171 		bucket = &callwheel[curticks & callwheelmask];
172 		c = TAILQ_FIRST(bucket);
173 		while (c) {
174 			depth++;
175 			if (c->c_time != curticks) {
176 				c = TAILQ_NEXT(c, c_links.tqe);
177 				++steps;
178 				if (steps >= MAX_SOFTCLOCK_STEPS) {
179 					nextsoftcheck = c;
180 					/* Give interrupts a chance. */
181 					mtx_unlock_spin(&callout_lock);
182 					;	/* nothing */
183 					mtx_lock_spin(&callout_lock);
184 					c = nextsoftcheck;
185 					steps = 0;
186 				}
187 			} else {
188 				void (*c_func)(void *);
189 				void *c_arg;
190 				int c_flags;
191 
192 				nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
193 				TAILQ_REMOVE(bucket, c, c_links.tqe);
194 				c_func = c->c_func;
195 				c_arg = c->c_arg;
196 				c_flags = c->c_flags;
197 				c->c_func = NULL;
198 				if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
199 					c->c_flags = CALLOUT_LOCAL_ALLOC;
200 					SLIST_INSERT_HEAD(&callfree, c,
201 							  c_links.sle);
202 				} else {
203 					c->c_flags =
204 					    (c->c_flags & ~CALLOUT_PENDING);
205 				}
206 				mtx_unlock_spin(&callout_lock);
207 				if (!(c_flags & CALLOUT_MPSAFE)) {
208 					mtx_lock(&Giant);
209 					gcalls++;
210 				} else {
211 					mpcalls++;
212 				}
213 #ifdef DIAGNOSTIC
214 				binuptime(&bt1);
215 #endif
216 				c_func(c_arg);
217 #ifdef DIAGNOSTIC
218 				binuptime(&bt2);
219 				bintime_sub(&bt2, &bt1);
220 				if (bt2.frac > maxdt) {
221 					maxdt = bt2.frac;
222 					bintime2timespec(&bt2, &ts2);
223 					printf(
224 			"Expensive timeout(9) function: %p(%p) %d.%09ld s\n",
225 					c_func, c_arg,
226 					ts2.tv_sec, ts2.tv_nsec);
227 				}
228 #endif
229 				if (!(c_flags & CALLOUT_MPSAFE))
230 					mtx_unlock(&Giant);
231 				mtx_lock_spin(&callout_lock);
232 				steps = 0;
233 				c = nextsoftcheck;
234 			}
235 		}
236 	}
237 	avg_depth += (depth * 1000 - avg_depth) >> 8;
238 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
239 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
240 	nextsoftcheck = NULL;
241 	mtx_unlock_spin(&callout_lock);
242 }
243 
244 /*
245  * timeout --
246  *	Execute a function after a specified length of time.
247  *
248  * untimeout --
249  *	Cancel previous timeout function call.
250  *
251  * callout_handle_init --
252  *	Initialize a handle so that using it with untimeout is benign.
253  *
254  *	See AT&T BCI Driver Reference Manual for specification.  This
255  *	implementation differs from that one in that although an
256  *	identification value is returned from timeout, the original
257  *	arguments to timeout as well as the identifier are used to
258  *	identify entries for untimeout.
259  */
260 struct callout_handle
261 timeout(ftn, arg, to_ticks)
262 	timeout_t *ftn;
263 	void *arg;
264 	int to_ticks;
265 {
266 	struct callout *new;
267 	struct callout_handle handle;
268 
269 	mtx_lock_spin(&callout_lock);
270 
271 	/* Fill in the next free callout structure. */
272 	new = SLIST_FIRST(&callfree);
273 	if (new == NULL)
274 		/* XXX Attempt to malloc first */
275 		panic("timeout table full");
276 	SLIST_REMOVE_HEAD(&callfree, c_links.sle);
277 
278 	callout_reset(new, to_ticks, ftn, arg);
279 
280 	handle.callout = new;
281 	mtx_unlock_spin(&callout_lock);
282 	return (handle);
283 }
284 
285 void
286 untimeout(ftn, arg, handle)
287 	timeout_t *ftn;
288 	void *arg;
289 	struct callout_handle handle;
290 {
291 
292 	/*
293 	 * Check for a handle that was initialized
294 	 * by callout_handle_init, but never used
295 	 * for a real timeout.
296 	 */
297 	if (handle.callout == NULL)
298 		return;
299 
300 	mtx_lock_spin(&callout_lock);
301 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
302 		callout_stop(handle.callout);
303 	mtx_unlock_spin(&callout_lock);
304 }
305 
306 void
307 callout_handle_init(struct callout_handle *handle)
308 {
309 	handle->callout = NULL;
310 }
311 
312 /*
313  * New interface; clients allocate their own callout structures.
314  *
315  * callout_reset() - establish or change a timeout
316  * callout_stop() - disestablish a timeout
317  * callout_init() - initialize a callout structure so that it can
318  *	safely be passed to callout_reset() and callout_stop()
319  *
320  * <sys/callout.h> defines three convenience macros:
321  *
322  * callout_active() - returns truth if callout has not been serviced
323  * callout_pending() - returns truth if callout is still waiting for timeout
324  * callout_deactivate() - marks the callout as having been serviced
325  */
326 void
327 callout_reset(c, to_ticks, ftn, arg)
328 	struct	callout *c;
329 	int	to_ticks;
330 	void	(*ftn)(void *);
331 	void	*arg;
332 {
333 
334 	mtx_lock_spin(&callout_lock);
335 	if (c->c_flags & CALLOUT_PENDING)
336 		callout_stop(c);
337 
338 	/*
339 	 * We could unlock callout_lock here and lock it again before the
340 	 * TAILQ_INSERT_TAIL, but there's no point since doing this setup
341 	 * doesn't take much time.
342 	 */
343 	if (to_ticks <= 0)
344 		to_ticks = 1;
345 
346 	c->c_arg = arg;
347 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
348 	c->c_func = ftn;
349 	c->c_time = ticks + to_ticks;
350 	TAILQ_INSERT_TAIL(&callwheel[c->c_time & callwheelmask],
351 			  c, c_links.tqe);
352 	mtx_unlock_spin(&callout_lock);
353 }
354 
355 int
356 callout_stop(c)
357 	struct	callout *c;
358 {
359 
360 	mtx_lock_spin(&callout_lock);
361 	/*
362 	 * Don't attempt to delete a callout that's not on the queue.
363 	 */
364 	if (!(c->c_flags & CALLOUT_PENDING)) {
365 		c->c_flags &= ~CALLOUT_ACTIVE;
366 		mtx_unlock_spin(&callout_lock);
367 		return (0);
368 	}
369 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
370 
371 	if (nextsoftcheck == c) {
372 		nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
373 	}
374 	TAILQ_REMOVE(&callwheel[c->c_time & callwheelmask], c, c_links.tqe);
375 	c->c_func = NULL;
376 
377 	if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
378 		SLIST_INSERT_HEAD(&callfree, c, c_links.sle);
379 	}
380 	mtx_unlock_spin(&callout_lock);
381 	return (1);
382 }
383 
384 void
385 callout_init(c, mpsafe)
386 	struct	callout *c;
387 	int mpsafe;
388 {
389 	bzero(c, sizeof *c);
390 	if (mpsafe)
391 		c->c_flags |= CALLOUT_MPSAFE;
392 }
393 
394 #ifdef APM_FIXUP_CALLTODO
395 /*
396  * Adjust the kernel calltodo timeout list.  This routine is used after
397  * an APM resume to recalculate the calltodo timer list values with the
398  * number of hz's we have been sleeping.  The next hardclock() will detect
399  * that there are fired timers and run softclock() to execute them.
400  *
401  * Please note, I have not done an exhaustive analysis of what code this
402  * might break.  I am motivated to have my select()'s and alarm()'s that
403  * have expired during suspend firing upon resume so that the applications
404  * which set the timer can do the maintanence the timer was for as close
405  * as possible to the originally intended time.  Testing this code for a
406  * week showed that resuming from a suspend resulted in 22 to 25 timers
407  * firing, which seemed independant on whether the suspend was 2 hours or
408  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
409  */
410 void
411 adjust_timeout_calltodo(time_change)
412     struct timeval *time_change;
413 {
414 	register struct callout *p;
415 	unsigned long delta_ticks;
416 
417 	/*
418 	 * How many ticks were we asleep?
419 	 * (stolen from tvtohz()).
420 	 */
421 
422 	/* Don't do anything */
423 	if (time_change->tv_sec < 0)
424 		return;
425 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
426 		delta_ticks = (time_change->tv_sec * 1000000 +
427 			       time_change->tv_usec + (tick - 1)) / tick + 1;
428 	else if (time_change->tv_sec <= LONG_MAX / hz)
429 		delta_ticks = time_change->tv_sec * hz +
430 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
431 	else
432 		delta_ticks = LONG_MAX;
433 
434 	if (delta_ticks > INT_MAX)
435 		delta_ticks = INT_MAX;
436 
437 	/*
438 	 * Now rip through the timer calltodo list looking for timers
439 	 * to expire.
440 	 */
441 
442 	/* don't collide with softclock() */
443 	mtx_lock_spin(&callout_lock);
444 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
445 		p->c_time -= delta_ticks;
446 
447 		/* Break if the timer had more time on it than delta_ticks */
448 		if (p->c_time > 0)
449 			break;
450 
451 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
452 		delta_ticks = -p->c_time;
453 	}
454 	mtx_unlock_spin(&callout_lock);
455 
456 	return;
457 }
458 #endif /* APM_FIXUP_CALLTODO */
459