xref: /freebsd/sys/kern/kern_timeout.c (revision 30d239bc4c510432e65a84fa1c14ed67a3ab1c92)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/callout.h>
43 #include <sys/condvar.h>
44 #include <sys/kernel.h>
45 #include <sys/ktr.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/proc.h>
49 #include <sys/sleepqueue.h>
50 #include <sys/sysctl.h>
51 
52 static int avg_depth;
53 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
54     "Average number of items examined per softclock call. Units = 1/1000");
55 static int avg_gcalls;
56 SYSCTL_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");
58 static int avg_mtxcalls;
59 SYSCTL_INT(_debug, OID_AUTO, to_avg_mtxcalls, CTLFLAG_RD, &avg_mtxcalls, 0,
60     "Average number of mtx callouts made per softclock call. Units = 1/1000");
61 static int avg_mpcalls;
62 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
63     "Average number of MP callouts made per softclock call. Units = 1/1000");
64 /*
65  * TODO:
66  *	allocate more timeout table slots when table overflows.
67  */
68 
69 /* Exported to machdep.c and/or kern_clock.c.  */
70 struct callout *callout;
71 struct callout_list callfree;
72 int callwheelsize, callwheelbits, callwheelmask;
73 struct callout_tailq *callwheel;
74 int softticks;			/* Like ticks, but for softclock(). */
75 struct mtx callout_lock;
76 
77 static struct callout *nextsoftcheck;	/* Next callout to be checked. */
78 
79 /**
80  * Locked by callout_lock:
81  *   curr_callout    - If a callout is in progress, it is curr_callout.
82  *                     If curr_callout is non-NULL, threads waiting in
83  *                     callout_drain() will be woken up as soon as the
84  *                     relevant callout completes.
85  *   curr_cancelled  - Changing to 1 with both callout_lock and c_mtx held
86  *                     guarantees that the current callout will not run.
87  *                     The softclock() function sets this to 0 before it
88  *                     drops callout_lock to acquire c_mtx, and it calls
89  *                     the handler only if curr_cancelled is still 0 after
90  *                     c_mtx is successfully acquired.
91  *   callout_wait    - If a thread is waiting in callout_drain(), then
92  *                     callout_wait is nonzero.  Set only when
93  *                     curr_callout is non-NULL.
94  */
95 static struct callout *curr_callout;
96 static int curr_cancelled;
97 static int callout_wait;
98 
99 /*
100  * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization
101  *
102  *	This code is called very early in the kernel initialization sequence,
103  *	and may be called more then once.
104  */
105 caddr_t
106 kern_timeout_callwheel_alloc(caddr_t v)
107 {
108 	/*
109 	 * Calculate callout wheel size
110 	 */
111 	for (callwheelsize = 1, callwheelbits = 0;
112 	     callwheelsize < ncallout;
113 	     callwheelsize <<= 1, ++callwheelbits)
114 		;
115 	callwheelmask = callwheelsize - 1;
116 
117 	callout = (struct callout *)v;
118 	v = (caddr_t)(callout + ncallout);
119 	callwheel = (struct callout_tailq *)v;
120 	v = (caddr_t)(callwheel + callwheelsize);
121 	return(v);
122 }
123 
124 /*
125  * kern_timeout_callwheel_init() - initialize previously reserved callwheel
126  *				   space.
127  *
128  *	This code is called just once, after the space reserved for the
129  *	callout wheel has been finalized.
130  */
131 void
132 kern_timeout_callwheel_init(void)
133 {
134 	int i;
135 
136 	SLIST_INIT(&callfree);
137 	for (i = 0; i < ncallout; i++) {
138 		callout_init(&callout[i], 0);
139 		callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
140 		SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
141 	}
142 	for (i = 0; i < callwheelsize; i++) {
143 		TAILQ_INIT(&callwheel[i]);
144 	}
145 	mtx_init(&callout_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
146 }
147 
148 /*
149  * The callout mechanism is based on the work of Adam M. Costello and
150  * George Varghese, published in a technical report entitled "Redesigning
151  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
152  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
153  * used in this implementation was published by G. Varghese and T. Lauck in
154  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
155  * the Efficient Implementation of a Timer Facility" in the Proceedings of
156  * the 11th ACM Annual Symposium on Operating Systems Principles,
157  * Austin, Texas Nov 1987.
158  */
159 
160 /*
161  * Software (low priority) clock interrupt.
162  * Run periodic events from timeout queue.
163  */
164 void
165 softclock(void *dummy)
166 {
167 	struct callout *c;
168 	struct callout_tailq *bucket;
169 	int curticks;
170 	int steps;	/* #steps since we last allowed interrupts */
171 	int depth;
172 	int mpcalls;
173 	int mtxcalls;
174 	int gcalls;
175 #ifdef DIAGNOSTIC
176 	struct bintime bt1, bt2;
177 	struct timespec ts2;
178 	static uint64_t maxdt = 36893488147419102LL;	/* 2 msec */
179 	static timeout_t *lastfunc;
180 #endif
181 
182 #ifndef MAX_SOFTCLOCK_STEPS
183 #define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
184 #endif /* MAX_SOFTCLOCK_STEPS */
185 
186 	mpcalls = 0;
187 	mtxcalls = 0;
188 	gcalls = 0;
189 	depth = 0;
190 	steps = 0;
191 	mtx_lock_spin(&callout_lock);
192 	while (softticks != ticks) {
193 		softticks++;
194 		/*
195 		 * softticks may be modified by hard clock, so cache
196 		 * it while we work on a given bucket.
197 		 */
198 		curticks = softticks;
199 		bucket = &callwheel[curticks & callwheelmask];
200 		c = TAILQ_FIRST(bucket);
201 		while (c) {
202 			depth++;
203 			if (c->c_time != curticks) {
204 				c = TAILQ_NEXT(c, c_links.tqe);
205 				++steps;
206 				if (steps >= MAX_SOFTCLOCK_STEPS) {
207 					nextsoftcheck = c;
208 					/* Give interrupts a chance. */
209 					mtx_unlock_spin(&callout_lock);
210 					;	/* nothing */
211 					mtx_lock_spin(&callout_lock);
212 					c = nextsoftcheck;
213 					steps = 0;
214 				}
215 			} else {
216 				void (*c_func)(void *);
217 				void *c_arg;
218 				struct mtx *c_mtx;
219 				int c_flags;
220 
221 				nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
222 				TAILQ_REMOVE(bucket, c, c_links.tqe);
223 				c_func = c->c_func;
224 				c_arg = c->c_arg;
225 				c_mtx = c->c_mtx;
226 				c_flags = c->c_flags;
227 				if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
228 					c->c_func = NULL;
229 					c->c_flags = CALLOUT_LOCAL_ALLOC;
230 					SLIST_INSERT_HEAD(&callfree, c,
231 							  c_links.sle);
232 					curr_callout = NULL;
233 				} else {
234 					c->c_flags =
235 					    (c->c_flags & ~CALLOUT_PENDING);
236 					curr_callout = c;
237 				}
238 				curr_cancelled = 0;
239 				mtx_unlock_spin(&callout_lock);
240 				if (c_mtx != NULL) {
241 					mtx_lock(c_mtx);
242 					/*
243 					 * The callout may have been cancelled
244 					 * while we switched locks.
245 					 */
246 					if (curr_cancelled) {
247 						mtx_unlock(c_mtx);
248 						goto skip;
249 					}
250 					/* The callout cannot be stopped now. */
251 					curr_cancelled = 1;
252 
253 					if (c_mtx == &Giant) {
254 						gcalls++;
255 						CTR3(KTR_CALLOUT,
256 						    "callout %p func %p arg %p",
257 						    c, c_func, c_arg);
258 					} else {
259 						mtxcalls++;
260 						CTR3(KTR_CALLOUT, "callout mtx"
261 						    " %p func %p arg %p",
262 						    c, c_func, c_arg);
263 					}
264 				} else {
265 					mpcalls++;
266 					CTR3(KTR_CALLOUT,
267 					    "callout mpsafe %p func %p arg %p",
268 					    c, c_func, c_arg);
269 				}
270 #ifdef DIAGNOSTIC
271 				binuptime(&bt1);
272 #endif
273 				THREAD_NO_SLEEPING();
274 				c_func(c_arg);
275 				THREAD_SLEEPING_OK();
276 #ifdef DIAGNOSTIC
277 				binuptime(&bt2);
278 				bintime_sub(&bt2, &bt1);
279 				if (bt2.frac > maxdt) {
280 					if (lastfunc != c_func ||
281 					    bt2.frac > maxdt * 2) {
282 						bintime2timespec(&bt2, &ts2);
283 						printf(
284 			"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
285 						    c_func, c_arg,
286 						    (intmax_t)ts2.tv_sec,
287 						    ts2.tv_nsec);
288 					}
289 					maxdt = bt2.frac;
290 					lastfunc = c_func;
291 				}
292 #endif
293 				if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
294 					mtx_unlock(c_mtx);
295 			skip:
296 				mtx_lock_spin(&callout_lock);
297 				curr_callout = NULL;
298 				if (callout_wait) {
299 					/*
300 					 * There is someone waiting
301 					 * for the callout to complete.
302 					 */
303 					callout_wait = 0;
304 					mtx_unlock_spin(&callout_lock);
305 					wakeup(&callout_wait);
306 					mtx_lock_spin(&callout_lock);
307 				}
308 				steps = 0;
309 				c = nextsoftcheck;
310 			}
311 		}
312 	}
313 	avg_depth += (depth * 1000 - avg_depth) >> 8;
314 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
315 	avg_mtxcalls += (mtxcalls * 1000 - avg_mtxcalls) >> 8;
316 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
317 	nextsoftcheck = NULL;
318 	mtx_unlock_spin(&callout_lock);
319 }
320 
321 /*
322  * timeout --
323  *	Execute a function after a specified length of time.
324  *
325  * untimeout --
326  *	Cancel previous timeout function call.
327  *
328  * callout_handle_init --
329  *	Initialize a handle so that using it with untimeout is benign.
330  *
331  *	See AT&T BCI Driver Reference Manual for specification.  This
332  *	implementation differs from that one in that although an
333  *	identification value is returned from timeout, the original
334  *	arguments to timeout as well as the identifier are used to
335  *	identify entries for untimeout.
336  */
337 struct callout_handle
338 timeout(ftn, arg, to_ticks)
339 	timeout_t *ftn;
340 	void *arg;
341 	int to_ticks;
342 {
343 	struct callout *new;
344 	struct callout_handle handle;
345 
346 	mtx_lock_spin(&callout_lock);
347 
348 	/* Fill in the next free callout structure. */
349 	new = SLIST_FIRST(&callfree);
350 	if (new == NULL)
351 		/* XXX Attempt to malloc first */
352 		panic("timeout table full");
353 	SLIST_REMOVE_HEAD(&callfree, c_links.sle);
354 
355 	callout_reset(new, to_ticks, ftn, arg);
356 
357 	handle.callout = new;
358 	mtx_unlock_spin(&callout_lock);
359 	return (handle);
360 }
361 
362 void
363 untimeout(ftn, arg, handle)
364 	timeout_t *ftn;
365 	void *arg;
366 	struct callout_handle handle;
367 {
368 
369 	/*
370 	 * Check for a handle that was initialized
371 	 * by callout_handle_init, but never used
372 	 * for a real timeout.
373 	 */
374 	if (handle.callout == NULL)
375 		return;
376 
377 	mtx_lock_spin(&callout_lock);
378 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
379 		callout_stop(handle.callout);
380 	mtx_unlock_spin(&callout_lock);
381 }
382 
383 void
384 callout_handle_init(struct callout_handle *handle)
385 {
386 	handle->callout = NULL;
387 }
388 
389 /*
390  * New interface; clients allocate their own callout structures.
391  *
392  * callout_reset() - establish or change a timeout
393  * callout_stop() - disestablish a timeout
394  * callout_init() - initialize a callout structure so that it can
395  *	safely be passed to callout_reset() and callout_stop()
396  *
397  * <sys/callout.h> defines three convenience macros:
398  *
399  * callout_active() - returns truth if callout has not been stopped,
400  *	drained, or deactivated since the last time the callout was
401  *	reset.
402  * callout_pending() - returns truth if callout is still waiting for timeout
403  * callout_deactivate() - marks the callout as having been serviced
404  */
405 int
406 callout_reset(c, to_ticks, ftn, arg)
407 	struct	callout *c;
408 	int	to_ticks;
409 	void	(*ftn)(void *);
410 	void	*arg;
411 {
412 	int cancelled = 0;
413 
414 #ifdef notyet /* Some callers of timeout() do not hold Giant. */
415 	if (c->c_mtx != NULL)
416 		mtx_assert(c->c_mtx, MA_OWNED);
417 #endif
418 
419 	mtx_lock_spin(&callout_lock);
420 	if (c == curr_callout) {
421 		/*
422 		 * We're being asked to reschedule a callout which is
423 		 * currently in progress.  If there is a mutex then we
424 		 * can cancel the callout if it has not really started.
425 		 */
426 		if (c->c_mtx != NULL && !curr_cancelled)
427 			cancelled = curr_cancelled = 1;
428 		if (callout_wait) {
429 			/*
430 			 * Someone has called callout_drain to kill this
431 			 * callout.  Don't reschedule.
432 			 */
433 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
434 			    cancelled ? "cancelled" : "failed to cancel",
435 			    c, c->c_func, c->c_arg);
436 			mtx_unlock_spin(&callout_lock);
437 			return (cancelled);
438 		}
439 	}
440 	if (c->c_flags & CALLOUT_PENDING) {
441 		if (nextsoftcheck == c) {
442 			nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
443 		}
444 		TAILQ_REMOVE(&callwheel[c->c_time & callwheelmask], c,
445 		    c_links.tqe);
446 
447 		cancelled = 1;
448 
449 		/*
450 		 * Part of the normal "stop a pending callout" process
451 		 * is to clear the CALLOUT_ACTIVE and CALLOUT_PENDING
452 		 * flags.  We're not going to bother doing that here,
453 		 * because we're going to be setting those flags ten lines
454 		 * after this point, and we're holding callout_lock
455 		 * between now and then.
456 		 */
457 	}
458 
459 	/*
460 	 * We could unlock callout_lock here and lock it again before the
461 	 * TAILQ_INSERT_TAIL, but there's no point since doing this setup
462 	 * doesn't take much time.
463 	 */
464 	if (to_ticks <= 0)
465 		to_ticks = 1;
466 
467 	c->c_arg = arg;
468 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
469 	c->c_func = ftn;
470 	c->c_time = ticks + to_ticks;
471 	TAILQ_INSERT_TAIL(&callwheel[c->c_time & callwheelmask],
472 			  c, c_links.tqe);
473 	CTR5(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d",
474 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, to_ticks);
475 	mtx_unlock_spin(&callout_lock);
476 
477 	return (cancelled);
478 }
479 
480 int
481 _callout_stop_safe(c, safe)
482 	struct	callout *c;
483 	int	safe;
484 {
485 	int use_mtx, sq_locked;
486 
487 	if (!safe && c->c_mtx != NULL) {
488 #ifdef notyet /* Some callers do not hold Giant for Giant-locked callouts. */
489 		mtx_assert(c->c_mtx, MA_OWNED);
490 		use_mtx = 1;
491 #else
492 		use_mtx = mtx_owned(c->c_mtx);
493 #endif
494 	} else {
495 		use_mtx = 0;
496 	}
497 
498 	sq_locked = 0;
499 again:
500 	mtx_lock_spin(&callout_lock);
501 	/*
502 	 * If the callout isn't pending, it's not on the queue, so
503 	 * don't attempt to remove it from the queue.  We can try to
504 	 * stop it by other means however.
505 	 */
506 	if (!(c->c_flags & CALLOUT_PENDING)) {
507 		c->c_flags &= ~CALLOUT_ACTIVE;
508 
509 		/*
510 		 * If it wasn't on the queue and it isn't the current
511 		 * callout, then we can't stop it, so just bail.
512 		 */
513 		if (c != curr_callout) {
514 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
515 			    c, c->c_func, c->c_arg);
516 			mtx_unlock_spin(&callout_lock);
517 			if (sq_locked)
518 				sleepq_release(&callout_wait);
519 			return (0);
520 		}
521 
522 		if (safe) {
523 			/*
524 			 * The current callout is running (or just
525 			 * about to run) and blocking is allowed, so
526 			 * just wait for the current invocation to
527 			 * finish.
528 			 */
529 			while (c == curr_callout) {
530 
531 				/*
532 				 * Use direct calls to sleepqueue interface
533 				 * instead of cv/msleep in order to avoid
534 				 * a LOR between callout_lock and sleepqueue
535 				 * chain spinlocks.  This piece of code
536 				 * emulates a msleep_spin() call actually.
537 				 *
538 				 * If we already have the sleepqueue chain
539 				 * locked, then we can safely block.  If we
540 				 * don't already have it locked, however,
541 				 * we have to drop the callout_lock to lock
542 				 * it.  This opens several races, so we
543 				 * restart at the beginning once we have
544 				 * both locks.  If nothing has changed, then
545 				 * we will end up back here with sq_locked
546 				 * set.
547 				 */
548 				if (!sq_locked) {
549 					mtx_unlock_spin(&callout_lock);
550 					sleepq_lock(&callout_wait);
551 					sq_locked = 1;
552 					goto again;
553 				}
554 
555 				callout_wait = 1;
556 				DROP_GIANT();
557 				mtx_unlock_spin(&callout_lock);
558 				sleepq_add(&callout_wait,
559 				    &callout_lock.lock_object, "codrain",
560 				    SLEEPQ_SLEEP, 0);
561 				sleepq_wait(&callout_wait);
562 				sq_locked = 0;
563 
564 				/* Reacquire locks previously released. */
565 				PICKUP_GIANT();
566 				mtx_lock_spin(&callout_lock);
567 			}
568 		} else if (use_mtx && !curr_cancelled) {
569 			/*
570 			 * The current callout is waiting for it's
571 			 * mutex which we hold.  Cancel the callout
572 			 * and return.  After our caller drops the
573 			 * mutex, the callout will be skipped in
574 			 * softclock().
575 			 */
576 			curr_cancelled = 1;
577 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
578 			    c, c->c_func, c->c_arg);
579 			mtx_unlock_spin(&callout_lock);
580 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
581 			return (1);
582 		}
583 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
584 		    c, c->c_func, c->c_arg);
585 		mtx_unlock_spin(&callout_lock);
586 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
587 		return (0);
588 	}
589 	if (sq_locked)
590 		sleepq_release(&callout_wait);
591 
592 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
593 
594 	if (nextsoftcheck == c) {
595 		nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
596 	}
597 	TAILQ_REMOVE(&callwheel[c->c_time & callwheelmask], c, c_links.tqe);
598 
599 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
600 	    c, c->c_func, c->c_arg);
601 
602 	if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
603 		c->c_func = NULL;
604 		SLIST_INSERT_HEAD(&callfree, c, c_links.sle);
605 	}
606 	mtx_unlock_spin(&callout_lock);
607 	return (1);
608 }
609 
610 void
611 callout_init(c, mpsafe)
612 	struct	callout *c;
613 	int mpsafe;
614 {
615 	bzero(c, sizeof *c);
616 	if (mpsafe) {
617 		c->c_mtx = NULL;
618 		c->c_flags = CALLOUT_RETURNUNLOCKED;
619 	} else {
620 		c->c_mtx = &Giant;
621 		c->c_flags = 0;
622 	}
623 }
624 
625 void
626 callout_init_mtx(c, mtx, flags)
627 	struct	callout *c;
628 	struct	mtx *mtx;
629 	int flags;
630 {
631 	bzero(c, sizeof *c);
632 	c->c_mtx = mtx;
633 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED)) == 0,
634 	    ("callout_init_mtx: bad flags %d", flags));
635 	/* CALLOUT_RETURNUNLOCKED makes no sense without a mutex. */
636 	KASSERT(mtx != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
637 	    ("callout_init_mtx: CALLOUT_RETURNUNLOCKED with no mutex"));
638 	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED);
639 }
640 
641 #ifdef APM_FIXUP_CALLTODO
642 /*
643  * Adjust the kernel calltodo timeout list.  This routine is used after
644  * an APM resume to recalculate the calltodo timer list values with the
645  * number of hz's we have been sleeping.  The next hardclock() will detect
646  * that there are fired timers and run softclock() to execute them.
647  *
648  * Please note, I have not done an exhaustive analysis of what code this
649  * might break.  I am motivated to have my select()'s and alarm()'s that
650  * have expired during suspend firing upon resume so that the applications
651  * which set the timer can do the maintanence the timer was for as close
652  * as possible to the originally intended time.  Testing this code for a
653  * week showed that resuming from a suspend resulted in 22 to 25 timers
654  * firing, which seemed independant on whether the suspend was 2 hours or
655  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
656  */
657 void
658 adjust_timeout_calltodo(time_change)
659     struct timeval *time_change;
660 {
661 	register struct callout *p;
662 	unsigned long delta_ticks;
663 
664 	/*
665 	 * How many ticks were we asleep?
666 	 * (stolen from tvtohz()).
667 	 */
668 
669 	/* Don't do anything */
670 	if (time_change->tv_sec < 0)
671 		return;
672 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
673 		delta_ticks = (time_change->tv_sec * 1000000 +
674 			       time_change->tv_usec + (tick - 1)) / tick + 1;
675 	else if (time_change->tv_sec <= LONG_MAX / hz)
676 		delta_ticks = time_change->tv_sec * hz +
677 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
678 	else
679 		delta_ticks = LONG_MAX;
680 
681 	if (delta_ticks > INT_MAX)
682 		delta_ticks = INT_MAX;
683 
684 	/*
685 	 * Now rip through the timer calltodo list looking for timers
686 	 * to expire.
687 	 */
688 
689 	/* don't collide with softclock() */
690 	mtx_lock_spin(&callout_lock);
691 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
692 		p->c_time -= delta_ticks;
693 
694 		/* Break if the timer had more time on it than delta_ticks */
695 		if (p->c_time > 0)
696 			break;
697 
698 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
699 		delta_ticks = -p->c_time;
700 	}
701 	mtx_unlock_spin(&callout_lock);
702 
703 	return;
704 }
705 #endif /* APM_FIXUP_CALLTODO */
706