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