kern_timeout.c revision 81481
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: head/sys/kern/kern_timeout.c 81481 2001-08-10 21:06:59Z jhb $
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
49/*
50 * TODO:
51 *	allocate more timeout table slots when table overflows.
52 */
53
54/* Exported to machdep.c and/or kern_clock.c.  */
55struct callout *callout;
56struct callout_list callfree;
57int callwheelsize, callwheelbits, callwheelmask;
58struct callout_tailq *callwheel;
59int softticks;			/* Like ticks, but for softclock(). */
60struct mtx callout_lock;
61
62static struct callout *nextsoftcheck;	/* Next callout to be checked. */
63
64/*
65 * The callout mechanism is based on the work of Adam M. Costello and
66 * George Varghese, published in a technical report entitled "Redesigning
67 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
68 * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
69 * used in this implementation was published by G.Varghese and A. Lauck in
70 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
71 * the Efficient Implementation of a Timer Facility" in the Proceedings of
72 * the 11th ACM Annual Symposium on Operating Systems Principles,
73 * Austin, Texas Nov 1987.
74 */
75
76/*
77 * Software (low priority) clock interrupt.
78 * Run periodic events from timeout queue.
79 */
80void
81softclock(void *dummy)
82{
83	register struct callout *c;
84	register struct callout_tailq *bucket;
85	register int curticks;
86	register int steps;	/* #steps since we last allowed interrupts */
87
88#ifndef MAX_SOFTCLOCK_STEPS
89#define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
90#endif /* MAX_SOFTCLOCK_STEPS */
91
92	steps = 0;
93	mtx_lock_spin(&callout_lock);
94	while (softticks != ticks) {
95		softticks++;
96		/*
97		 * softticks may be modified by hard clock, so cache
98		 * it while we work on a given bucket.
99		 */
100		curticks = softticks;
101		bucket = &callwheel[curticks & callwheelmask];
102		c = TAILQ_FIRST(bucket);
103		while (c) {
104			if (c->c_time != curticks) {
105				c = TAILQ_NEXT(c, c_links.tqe);
106				++steps;
107				if (steps >= MAX_SOFTCLOCK_STEPS) {
108					nextsoftcheck = c;
109					/* Give interrupts a chance. */
110					mtx_unlock_spin(&callout_lock);
111					;	/* nothing */
112					mtx_lock_spin(&callout_lock);
113					c = nextsoftcheck;
114					steps = 0;
115				}
116			} else {
117				void (*c_func)(void *);
118				void *c_arg;
119				int c_flags;
120
121				nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
122				TAILQ_REMOVE(bucket, c, c_links.tqe);
123				c_func = c->c_func;
124				c_arg = c->c_arg;
125				c_flags = c->c_flags;
126				c->c_func = NULL;
127				if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
128					c->c_flags = CALLOUT_LOCAL_ALLOC;
129					SLIST_INSERT_HEAD(&callfree, c,
130							  c_links.sle);
131				} else {
132					c->c_flags =
133					    (c->c_flags & ~CALLOUT_PENDING);
134				}
135				mtx_unlock_spin(&callout_lock);
136				if (!(c_flags & CALLOUT_MPSAFE))
137					mtx_lock(&Giant);
138				c_func(c_arg);
139				if (!(c_flags & CALLOUT_MPSAFE))
140					mtx_unlock(&Giant);
141				mtx_lock_spin(&callout_lock);
142				steps = 0;
143				c = nextsoftcheck;
144			}
145		}
146	}
147	nextsoftcheck = NULL;
148	mtx_unlock_spin(&callout_lock);
149}
150
151/*
152 * timeout --
153 *	Execute a function after a specified length of time.
154 *
155 * untimeout --
156 *	Cancel previous timeout function call.
157 *
158 * callout_handle_init --
159 *	Initialize a handle so that using it with untimeout is benign.
160 *
161 *	See AT&T BCI Driver Reference Manual for specification.  This
162 *	implementation differs from that one in that although an
163 *	identification value is returned from timeout, the original
164 *	arguments to timeout as well as the identifier are used to
165 *	identify entries for untimeout.
166 */
167struct callout_handle
168timeout(ftn, arg, to_ticks)
169	timeout_t *ftn;
170	void *arg;
171	int to_ticks;
172{
173	struct callout *new;
174	struct callout_handle handle;
175
176	mtx_lock_spin(&callout_lock);
177
178	/* Fill in the next free callout structure. */
179	new = SLIST_FIRST(&callfree);
180	if (new == NULL)
181		/* XXX Attempt to malloc first */
182		panic("timeout table full");
183	SLIST_REMOVE_HEAD(&callfree, c_links.sle);
184
185	callout_reset(new, to_ticks, ftn, arg);
186
187	handle.callout = new;
188	mtx_unlock_spin(&callout_lock);
189	return (handle);
190}
191
192void
193untimeout(ftn, arg, handle)
194	timeout_t *ftn;
195	void *arg;
196	struct callout_handle handle;
197{
198
199	/*
200	 * Check for a handle that was initialized
201	 * by callout_handle_init, but never used
202	 * for a real timeout.
203	 */
204	if (handle.callout == NULL)
205		return;
206
207	mtx_lock_spin(&callout_lock);
208	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
209		callout_stop(handle.callout);
210	mtx_unlock_spin(&callout_lock);
211}
212
213void
214callout_handle_init(struct callout_handle *handle)
215{
216	handle->callout = NULL;
217}
218
219/*
220 * New interface; clients allocate their own callout structures.
221 *
222 * callout_reset() - establish or change a timeout
223 * callout_stop() - disestablish a timeout
224 * callout_init() - initialize a callout structure so that it can
225 *	safely be passed to callout_reset() and callout_stop()
226 *
227 * <sys/callout.h> defines three convenience macros:
228 *
229 * callout_active() - returns truth if callout has not been serviced
230 * callout_pending() - returns truth if callout is still waiting for timeout
231 * callout_deactivate() - marks the callout as having been serviced
232 */
233void
234callout_reset(c, to_ticks, ftn, arg)
235	struct	callout *c;
236	int	to_ticks;
237	void	(*ftn) __P((void *));
238	void	*arg;
239{
240
241	mtx_lock_spin(&callout_lock);
242	if (c->c_flags & CALLOUT_PENDING)
243		callout_stop(c);
244
245	/*
246	 * We could unlock callout_lock here and lock it again before the
247	 * TAILQ_INSERT_TAIL, but there's no point since doing this setup
248	 * doesn't take much time.
249	 */
250	if (to_ticks <= 0)
251		to_ticks = 1;
252
253	c->c_arg = arg;
254	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
255	c->c_func = ftn;
256	c->c_time = ticks + to_ticks;
257	TAILQ_INSERT_TAIL(&callwheel[c->c_time & callwheelmask],
258			  c, c_links.tqe);
259	mtx_unlock_spin(&callout_lock);
260}
261
262int
263callout_stop(c)
264	struct	callout *c;
265{
266
267	mtx_lock_spin(&callout_lock);
268	/*
269	 * Don't attempt to delete a callout that's not on the queue.
270	 */
271	if (!(c->c_flags & CALLOUT_PENDING)) {
272		c->c_flags &= ~CALLOUT_ACTIVE;
273		mtx_unlock_spin(&callout_lock);
274		return (0);
275	}
276	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
277
278	if (nextsoftcheck == c) {
279		nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
280	}
281	TAILQ_REMOVE(&callwheel[c->c_time & callwheelmask], c, c_links.tqe);
282	c->c_func = NULL;
283
284	if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
285		SLIST_INSERT_HEAD(&callfree, c, c_links.sle);
286	}
287	mtx_unlock_spin(&callout_lock);
288	return (1);
289}
290
291void
292callout_init(c, mpsafe)
293	struct	callout *c;
294	int mpsafe;
295{
296	bzero(c, sizeof *c);
297	if (mpsafe)
298		c->c_flags |= CALLOUT_MPSAFE;
299}
300
301#ifdef APM_FIXUP_CALLTODO
302/*
303 * Adjust the kernel calltodo timeout list.  This routine is used after
304 * an APM resume to recalculate the calltodo timer list values with the
305 * number of hz's we have been sleeping.  The next hardclock() will detect
306 * that there are fired timers and run softclock() to execute them.
307 *
308 * Please note, I have not done an exhaustive analysis of what code this
309 * might break.  I am motivated to have my select()'s and alarm()'s that
310 * have expired during suspend firing upon resume so that the applications
311 * which set the timer can do the maintanence the timer was for as close
312 * as possible to the originally intended time.  Testing this code for a
313 * week showed that resuming from a suspend resulted in 22 to 25 timers
314 * firing, which seemed independant on whether the suspend was 2 hours or
315 * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
316 */
317void
318adjust_timeout_calltodo(time_change)
319    struct timeval *time_change;
320{
321	register struct callout *p;
322	unsigned long delta_ticks;
323
324	/*
325	 * How many ticks were we asleep?
326	 * (stolen from tvtohz()).
327	 */
328
329	/* Don't do anything */
330	if (time_change->tv_sec < 0)
331		return;
332	else if (time_change->tv_sec <= LONG_MAX / 1000000)
333		delta_ticks = (time_change->tv_sec * 1000000 +
334			       time_change->tv_usec + (tick - 1)) / tick + 1;
335	else if (time_change->tv_sec <= LONG_MAX / hz)
336		delta_ticks = time_change->tv_sec * hz +
337			      (time_change->tv_usec + (tick - 1)) / tick + 1;
338	else
339		delta_ticks = LONG_MAX;
340
341	if (delta_ticks > INT_MAX)
342		delta_ticks = INT_MAX;
343
344	/*
345	 * Now rip through the timer calltodo list looking for timers
346	 * to expire.
347	 */
348
349	/* don't collide with softclock() */
350	mtx_lock_spin(&callout_lock);
351	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
352		p->c_time -= delta_ticks;
353
354		/* Break if the timer had more time on it than delta_ticks */
355		if (p->c_time > 0)
356			break;
357
358		/* take back the ticks the timer didn't use (p->c_time <= 0) */
359		delta_ticks = -p->c_time;
360	}
361	mtx_unlock_spin(&callout_lock);
362
363	return;
364}
365#endif /* APM_FIXUP_CALLTODO */
366