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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
34 * From: @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
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>
47 #include <sys/mutex.h>
49 #include <sys/sleepqueue.h>
50 #include <sys/sysctl.h>
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");
66 * allocate more timeout table slots when table overflows.
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;
77 static struct callout *nextsoftcheck; /* Next callout to be checked. */
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.
95 static struct callout *curr_callout;
96 static int curr_cancelled;
97 static int callout_wait;
100 * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization
102 * This code is called very early in the kernel initialization sequence,
103 * and may be called more then once.
106 kern_timeout_callwheel_alloc(caddr_t v)
109 * Calculate callout wheel size
111 for (callwheelsize = 1, callwheelbits = 0;
112 callwheelsize < ncallout;
113 callwheelsize <<= 1, ++callwheelbits)
115 callwheelmask = callwheelsize - 1;
117 callout = (struct callout *)v;
118 v = (caddr_t)(callout + ncallout);
119 callwheel = (struct callout_tailq *)v;
120 v = (caddr_t)(callwheel + callwheelsize);
125 * kern_timeout_callwheel_init() - initialize previously reserved callwheel
128 * This code is called just once, after the space reserved for the
129 * callout wheel has been finalized.
132 kern_timeout_callwheel_init(void)
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);
142 for (i = 0; i < callwheelsize; i++) {
143 TAILQ_INIT(&callwheel[i]);
145 mtx_init(&callout_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
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.
161 * Software (low priority) clock interrupt.
162 * Run periodic events from timeout queue.
165 softclock(void *dummy)
168 struct callout_tailq *bucket;
170 int steps; /* #steps since we last allowed interrupts */
176 struct bintime bt1, bt2;
178 static uint64_t maxdt = 36893488147419102LL; /* 2 msec */
179 static timeout_t *lastfunc;
182 #ifndef MAX_SOFTCLOCK_STEPS
183 #define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
184 #endif /* MAX_SOFTCLOCK_STEPS */
191 mtx_lock_spin(&callout_lock);
192 while (softticks != ticks) {
195 * softticks may be modified by hard clock, so cache
196 * it while we work on a given bucket.
198 curticks = softticks;
199 bucket = &callwheel[curticks & callwheelmask];
200 c = TAILQ_FIRST(bucket);
203 if (c->c_time != curticks) {
204 c = TAILQ_NEXT(c, c_links.tqe);
206 if (steps >= MAX_SOFTCLOCK_STEPS) {
208 /* Give interrupts a chance. */
209 mtx_unlock_spin(&callout_lock);
211 mtx_lock_spin(&callout_lock);
216 void (*c_func)(void *);
221 nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
222 TAILQ_REMOVE(bucket, c, c_links.tqe);
226 c_flags = c->c_flags;
227 if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
229 c->c_flags = CALLOUT_LOCAL_ALLOC;
230 SLIST_INSERT_HEAD(&callfree, c,
235 (c->c_flags & ~CALLOUT_PENDING);
239 mtx_unlock_spin(&callout_lock);
243 * The callout may have been cancelled
244 * while we switched locks.
246 if (curr_cancelled) {
250 /* The callout cannot be stopped now. */
253 if (c_mtx == &Giant) {
256 "callout %p func %p arg %p",
260 CTR3(KTR_CALLOUT, "callout mtx"
261 " %p func %p arg %p",
267 "callout mpsafe %p func %p arg %p",
273 THREAD_NO_SLEEPING();
275 THREAD_SLEEPING_OK();
278 bintime_sub(&bt2, &bt1);
279 if (bt2.frac > maxdt) {
280 if (lastfunc != c_func ||
281 bt2.frac > maxdt * 2) {
282 bintime2timespec(&bt2, &ts2);
284 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
286 (intmax_t)ts2.tv_sec,
293 CTR1(KTR_CALLOUT, "callout %p finished", c);
294 if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
297 mtx_lock_spin(&callout_lock);
301 * There is someone waiting
302 * for the callout to complete.
305 mtx_unlock_spin(&callout_lock);
306 wakeup(&callout_wait);
307 mtx_lock_spin(&callout_lock);
314 avg_depth += (depth * 1000 - avg_depth) >> 8;
315 avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
316 avg_mtxcalls += (mtxcalls * 1000 - avg_mtxcalls) >> 8;
317 avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
318 nextsoftcheck = NULL;
319 mtx_unlock_spin(&callout_lock);
324 * Execute a function after a specified length of time.
327 * Cancel previous timeout function call.
329 * callout_handle_init --
330 * Initialize a handle so that using it with untimeout is benign.
332 * See AT&T BCI Driver Reference Manual for specification. This
333 * implementation differs from that one in that although an
334 * identification value is returned from timeout, the original
335 * arguments to timeout as well as the identifier are used to
336 * identify entries for untimeout.
338 struct callout_handle
339 timeout(ftn, arg, to_ticks)
345 struct callout_handle handle;
347 mtx_lock_spin(&callout_lock);
349 /* Fill in the next free callout structure. */
350 new = SLIST_FIRST(&callfree);
352 /* XXX Attempt to malloc first */
353 panic("timeout table full");
354 SLIST_REMOVE_HEAD(&callfree, c_links.sle);
356 callout_reset(new, to_ticks, ftn, arg);
358 handle.callout = new;
359 mtx_unlock_spin(&callout_lock);
364 untimeout(ftn, arg, handle)
367 struct callout_handle handle;
371 * Check for a handle that was initialized
372 * by callout_handle_init, but never used
373 * for a real timeout.
375 if (handle.callout == NULL)
378 mtx_lock_spin(&callout_lock);
379 if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
380 callout_stop(handle.callout);
381 mtx_unlock_spin(&callout_lock);
385 callout_handle_init(struct callout_handle *handle)
387 handle->callout = NULL;
391 * New interface; clients allocate their own callout structures.
393 * callout_reset() - establish or change a timeout
394 * callout_stop() - disestablish a timeout
395 * callout_init() - initialize a callout structure so that it can
396 * safely be passed to callout_reset() and callout_stop()
398 * <sys/callout.h> defines three convenience macros:
400 * callout_active() - returns truth if callout has not been stopped,
401 * drained, or deactivated since the last time the callout was
403 * callout_pending() - returns truth if callout is still waiting for timeout
404 * callout_deactivate() - marks the callout as having been serviced
407 callout_reset(c, to_ticks, ftn, arg)
415 #ifdef notyet /* Some callers of timeout() do not hold Giant. */
416 if (c->c_mtx != NULL)
417 mtx_assert(c->c_mtx, MA_OWNED);
420 mtx_lock_spin(&callout_lock);
421 if (c == curr_callout) {
423 * We're being asked to reschedule a callout which is
424 * currently in progress. If there is a mutex then we
425 * can cancel the callout if it has not really started.
427 if (c->c_mtx != NULL && !curr_cancelled)
428 cancelled = curr_cancelled = 1;
431 * Someone has called callout_drain to kill this
432 * callout. Don't reschedule.
434 CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
435 cancelled ? "cancelled" : "failed to cancel",
436 c, c->c_func, c->c_arg);
437 mtx_unlock_spin(&callout_lock);
441 if (c->c_flags & CALLOUT_PENDING) {
442 if (nextsoftcheck == c) {
443 nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
445 TAILQ_REMOVE(&callwheel[c->c_time & callwheelmask], c,
451 * Part of the normal "stop a pending callout" process
452 * is to clear the CALLOUT_ACTIVE and CALLOUT_PENDING
453 * flags. We're not going to bother doing that here,
454 * because we're going to be setting those flags ten lines
455 * after this point, and we're holding callout_lock
456 * between now and then.
461 * We could unlock callout_lock here and lock it again before the
462 * TAILQ_INSERT_TAIL, but there's no point since doing this setup
463 * doesn't take much time.
469 c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
471 c->c_time = ticks + to_ticks;
472 TAILQ_INSERT_TAIL(&callwheel[c->c_time & callwheelmask],
474 CTR5(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d",
475 cancelled ? "re" : "", c, c->c_func, c->c_arg, to_ticks);
476 mtx_unlock_spin(&callout_lock);
482 _callout_stop_safe(c, safe)
486 int use_mtx, sq_locked;
488 if (!safe && c->c_mtx != NULL) {
489 #ifdef notyet /* Some callers do not hold Giant for Giant-locked callouts. */
490 mtx_assert(c->c_mtx, MA_OWNED);
493 use_mtx = mtx_owned(c->c_mtx);
501 mtx_lock_spin(&callout_lock);
503 * If the callout isn't pending, it's not on the queue, so
504 * don't attempt to remove it from the queue. We can try to
505 * stop it by other means however.
507 if (!(c->c_flags & CALLOUT_PENDING)) {
508 c->c_flags &= ~CALLOUT_ACTIVE;
511 * If it wasn't on the queue and it isn't the current
512 * callout, then we can't stop it, so just bail.
514 if (c != curr_callout) {
515 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
516 c, c->c_func, c->c_arg);
517 mtx_unlock_spin(&callout_lock);
519 sleepq_release(&callout_wait);
525 * The current callout is running (or just
526 * about to run) and blocking is allowed, so
527 * just wait for the current invocation to
530 while (c == curr_callout) {
533 * Use direct calls to sleepqueue interface
534 * instead of cv/msleep in order to avoid
535 * a LOR between callout_lock and sleepqueue
536 * chain spinlocks. This piece of code
537 * emulates a msleep_spin() call actually.
539 * If we already have the sleepqueue chain
540 * locked, then we can safely block. If we
541 * don't already have it locked, however,
542 * we have to drop the callout_lock to lock
543 * it. This opens several races, so we
544 * restart at the beginning once we have
545 * both locks. If nothing has changed, then
546 * we will end up back here with sq_locked
550 mtx_unlock_spin(&callout_lock);
551 sleepq_lock(&callout_wait);
558 mtx_unlock_spin(&callout_lock);
559 sleepq_add(&callout_wait,
560 &callout_lock.lock_object, "codrain",
562 sleepq_wait(&callout_wait);
565 /* Reacquire locks previously released. */
567 mtx_lock_spin(&callout_lock);
569 } else if (use_mtx && !curr_cancelled) {
571 * The current callout is waiting for it's
572 * mutex which we hold. Cancel the callout
573 * and return. After our caller drops the
574 * mutex, the callout will be skipped in
578 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
579 c, c->c_func, c->c_arg);
580 mtx_unlock_spin(&callout_lock);
581 KASSERT(!sq_locked, ("sleepqueue chain locked"));
584 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
585 c, c->c_func, c->c_arg);
586 mtx_unlock_spin(&callout_lock);
587 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
591 sleepq_release(&callout_wait);
593 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
595 if (nextsoftcheck == c) {
596 nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
598 TAILQ_REMOVE(&callwheel[c->c_time & callwheelmask], c, c_links.tqe);
600 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
601 c, c->c_func, c->c_arg);
603 if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
605 SLIST_INSERT_HEAD(&callfree, c, c_links.sle);
607 mtx_unlock_spin(&callout_lock);
612 callout_init(c, mpsafe)
619 c->c_flags = CALLOUT_RETURNUNLOCKED;
627 callout_init_mtx(c, mtx, flags)
634 KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED)) == 0,
635 ("callout_init_mtx: bad flags %d", flags));
636 /* CALLOUT_RETURNUNLOCKED makes no sense without a mutex. */
637 KASSERT(mtx != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
638 ("callout_init_mtx: CALLOUT_RETURNUNLOCKED with no mutex"));
639 c->c_flags = flags & (CALLOUT_RETURNUNLOCKED);
642 #ifdef APM_FIXUP_CALLTODO
644 * Adjust the kernel calltodo timeout list. This routine is used after
645 * an APM resume to recalculate the calltodo timer list values with the
646 * number of hz's we have been sleeping. The next hardclock() will detect
647 * that there are fired timers and run softclock() to execute them.
649 * Please note, I have not done an exhaustive analysis of what code this
650 * might break. I am motivated to have my select()'s and alarm()'s that
651 * have expired during suspend firing upon resume so that the applications
652 * which set the timer can do the maintanence the timer was for as close
653 * as possible to the originally intended time. Testing this code for a
654 * week showed that resuming from a suspend resulted in 22 to 25 timers
655 * firing, which seemed independant on whether the suspend was 2 hours or
656 * 2 days. Your milage may vary. - Ken Key <key@cs.utk.edu>
659 adjust_timeout_calltodo(time_change)
660 struct timeval *time_change;
662 register struct callout *p;
663 unsigned long delta_ticks;
666 * How many ticks were we asleep?
667 * (stolen from tvtohz()).
670 /* Don't do anything */
671 if (time_change->tv_sec < 0)
673 else if (time_change->tv_sec <= LONG_MAX / 1000000)
674 delta_ticks = (time_change->tv_sec * 1000000 +
675 time_change->tv_usec + (tick - 1)) / tick + 1;
676 else if (time_change->tv_sec <= LONG_MAX / hz)
677 delta_ticks = time_change->tv_sec * hz +
678 (time_change->tv_usec + (tick - 1)) / tick + 1;
680 delta_ticks = LONG_MAX;
682 if (delta_ticks > INT_MAX)
683 delta_ticks = INT_MAX;
686 * Now rip through the timer calltodo list looking for timers
690 /* don't collide with softclock() */
691 mtx_lock_spin(&callout_lock);
692 for (p = calltodo.c_next; p != NULL; p = p->c_next) {
693 p->c_time -= delta_ticks;
695 /* Break if the timer had more time on it than delta_ticks */
699 /* take back the ticks the timer didn't use (p->c_time <= 0) */
700 delta_ticks = -p->c_time;
702 mtx_unlock_spin(&callout_lock);
706 #endif /* APM_FIXUP_CALLTODO */