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 "opt_callout_profiling.h"
41 #include "opt_kdtrace.h"
43 #include "opt_timer.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/callout.h>
51 #include <sys/interrupt.h>
52 #include <sys/kernel.h>
55 #include <sys/malloc.h>
56 #include <sys/mutex.h>
59 #include <sys/sleepqueue.h>
60 #include <sys/sysctl.h>
64 #include <machine/cpu.h>
67 #ifndef NO_EVENTTIMERS
68 DPCPU_DECLARE(sbintime_t, hardclocktime);
71 SDT_PROVIDER_DEFINE(callout_execute);
72 SDT_PROBE_DEFINE(callout_execute, kernel, , callout_start, callout-start);
73 SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_start, 0,
75 SDT_PROBE_DEFINE(callout_execute, kernel, , callout_end, callout-end);
76 SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_end, 0,
79 #ifdef CALLOUT_PROFILING
81 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
82 "Average number of items examined per softclock call. Units = 1/1000");
83 static int avg_gcalls;
84 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
85 "Average number of Giant callouts made per softclock call. Units = 1/1000");
86 static int avg_lockcalls;
87 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
88 "Average number of lock callouts made per softclock call. Units = 1/1000");
89 static int avg_mpcalls;
90 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
91 "Average number of MP callouts made per softclock call. Units = 1/1000");
92 static int avg_depth_dir;
93 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
94 "Average number of direct callouts examined per callout_process call. "
96 static int avg_lockcalls_dir;
97 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
98 &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
99 "callout_process call. Units = 1/1000");
100 static int avg_mpcalls_dir;
101 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
102 0, "Average number of MP direct callouts made per callout_process call. "
107 SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN, &ncallout, 0,
108 "Number of entries in callwheel and size of timeout() preallocation");
112 * allocate more timeout table slots when table overflows.
114 u_int callwheelsize, callwheelmask;
117 * The callout cpu exec entities represent informations necessary for
118 * describing the state of callouts currently running on the CPU and the ones
119 * necessary for migrating callouts to the new callout cpu. In particular,
120 * the first entry of the array cc_exec_entity holds informations for callout
121 * running in SWI thread context, while the second one holds informations
122 * for callout running directly from hardware interrupt context.
123 * The cached informations are very important for deferring migration when
124 * the migrating callout is already running.
127 struct callout *cc_next;
128 struct callout *cc_curr;
130 void (*ce_migration_func)(void *);
131 void *ce_migration_arg;
132 int ce_migration_cpu;
133 sbintime_t ce_migration_time;
140 * There is one struct callout_cpu per cpu, holding all relevant
141 * state for the callout processing thread on the individual CPU.
144 struct mtx_padalign cc_lock;
145 struct cc_exec cc_exec_entity[2];
146 struct callout *cc_callout;
147 struct callout_list *cc_callwheel;
148 struct callout_tailq cc_expireq;
149 struct callout_slist cc_callfree;
150 sbintime_t cc_firstevent;
151 sbintime_t cc_lastscan;
156 #define cc_exec_curr cc_exec_entity[0].cc_curr
157 #define cc_exec_next cc_exec_entity[0].cc_next
158 #define cc_exec_cancel cc_exec_entity[0].cc_cancel
159 #define cc_exec_waiting cc_exec_entity[0].cc_waiting
160 #define cc_exec_curr_dir cc_exec_entity[1].cc_curr
161 #define cc_exec_next_dir cc_exec_entity[1].cc_next
162 #define cc_exec_cancel_dir cc_exec_entity[1].cc_cancel
163 #define cc_exec_waiting_dir cc_exec_entity[1].cc_waiting
166 #define cc_migration_func cc_exec_entity[0].ce_migration_func
167 #define cc_migration_arg cc_exec_entity[0].ce_migration_arg
168 #define cc_migration_cpu cc_exec_entity[0].ce_migration_cpu
169 #define cc_migration_time cc_exec_entity[0].ce_migration_time
170 #define cc_migration_func_dir cc_exec_entity[1].ce_migration_func
171 #define cc_migration_arg_dir cc_exec_entity[1].ce_migration_arg
172 #define cc_migration_cpu_dir cc_exec_entity[1].ce_migration_cpu
173 #define cc_migration_time_dir cc_exec_entity[1].ce_migration_time
175 struct callout_cpu cc_cpu[MAXCPU];
176 #define CPUBLOCK MAXCPU
177 #define CC_CPU(cpu) (&cc_cpu[(cpu)])
178 #define CC_SELF() CC_CPU(PCPU_GET(cpuid))
180 struct callout_cpu cc_cpu;
181 #define CC_CPU(cpu) &cc_cpu
182 #define CC_SELF() &cc_cpu
184 #define CC_LOCK(cc) mtx_lock_spin(&(cc)->cc_lock)
185 #define CC_UNLOCK(cc) mtx_unlock_spin(&(cc)->cc_lock)
186 #define CC_LOCK_ASSERT(cc) mtx_assert(&(cc)->cc_lock, MA_OWNED)
188 static int timeout_cpu;
190 static void callout_cpu_init(struct callout_cpu *cc);
191 static void softclock_call_cc(struct callout *c, struct callout_cpu *cc,
192 #ifdef CALLOUT_PROFILING
193 int *mpcalls, int *lockcalls, int *gcalls,
197 static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
201 * cc_curr - If a callout is in progress, it is cc_curr.
202 * If cc_curr is non-NULL, threads waiting in
203 * callout_drain() will be woken up as soon as the
204 * relevant callout completes.
205 * cc_cancel - Changing to 1 with both callout_lock and cc_lock held
206 * guarantees that the current callout will not run.
207 * The softclock() function sets this to 0 before it
208 * drops callout_lock to acquire c_lock, and it calls
209 * the handler only if curr_cancelled is still 0 after
210 * cc_lock is successfully acquired.
211 * cc_waiting - If a thread is waiting in callout_drain(), then
212 * callout_wait is nonzero. Set only when
213 * cc_curr is non-NULL.
217 * Resets the execution entity tied to a specific callout cpu.
220 cc_cce_cleanup(struct callout_cpu *cc, int direct)
223 cc->cc_exec_entity[direct].cc_curr = NULL;
224 cc->cc_exec_entity[direct].cc_next = NULL;
225 cc->cc_exec_entity[direct].cc_cancel = false;
226 cc->cc_exec_entity[direct].cc_waiting = false;
228 cc->cc_exec_entity[direct].ce_migration_cpu = CPUBLOCK;
229 cc->cc_exec_entity[direct].ce_migration_time = 0;
230 cc->cc_exec_entity[direct].ce_migration_func = NULL;
231 cc->cc_exec_entity[direct].ce_migration_arg = NULL;
236 * Checks if migration is requested by a specific callout cpu.
239 cc_cce_migrating(struct callout_cpu *cc, int direct)
243 return (cc->cc_exec_entity[direct].ce_migration_cpu != CPUBLOCK);
250 * Kernel low level callwheel initialization
251 * called on cpu0 during kernel startup.
254 callout_callwheel_init(void *dummy)
256 struct callout_cpu *cc;
259 * Calculate the size of the callout wheel and the preallocated
260 * timeout() structures.
262 ncallout = imin(16 + maxproc + maxfiles, 18508);
263 TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
266 * Calculate callout wheel size, should be next power of two higher
269 callwheelsize = 1 << fls(ncallout);
270 callwheelmask = callwheelsize - 1;
273 * Only cpu0 handles timeout(9) and receives a preallocation.
275 * XXX: Once all timeout(9) consumers are converted this can
278 timeout_cpu = PCPU_GET(cpuid);
279 cc = CC_CPU(timeout_cpu);
280 cc->cc_callout = malloc(ncallout * sizeof(struct callout),
281 M_CALLOUT, M_WAITOK);
282 callout_cpu_init(cc);
284 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
287 * Initialize the per-cpu callout structures.
290 callout_cpu_init(struct callout_cpu *cc)
295 mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
296 SLIST_INIT(&cc->cc_callfree);
297 cc->cc_callwheel = malloc(sizeof(struct callout_tailq) * callwheelsize,
298 M_CALLOUT, M_WAITOK);
299 for (i = 0; i < callwheelsize; i++)
300 LIST_INIT(&cc->cc_callwheel[i]);
301 TAILQ_INIT(&cc->cc_expireq);
302 cc->cc_firstevent = INT64_MAX;
303 for (i = 0; i < 2; i++)
304 cc_cce_cleanup(cc, i);
305 if (cc->cc_callout == NULL) /* Only cpu0 handles timeout(9) */
307 for (i = 0; i < ncallout; i++) {
308 c = &cc->cc_callout[i];
310 c->c_flags = CALLOUT_LOCAL_ALLOC;
311 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
317 * Switches the cpu tied to a specific callout.
318 * The function expects a locked incoming callout cpu and returns with
319 * locked outcoming callout cpu.
321 static struct callout_cpu *
322 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
324 struct callout_cpu *new_cc;
326 MPASS(c != NULL && cc != NULL);
330 * Avoid interrupts and preemption firing after the callout cpu
331 * is blocked in order to avoid deadlocks as the new thread
332 * may be willing to acquire the callout cpu lock.
337 new_cc = CC_CPU(new_cpu);
346 * Start standard softclock thread.
349 start_softclock(void *dummy)
351 struct callout_cpu *cc;
356 cc = CC_CPU(timeout_cpu);
357 if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
358 INTR_MPSAFE, &cc->cc_cookie))
359 panic("died while creating standard software ithreads");
362 if (cpu == timeout_cpu)
365 cc->cc_callout = NULL; /* Only cpu0 handles timeout(9). */
366 callout_cpu_init(cc);
367 if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
368 INTR_MPSAFE, &cc->cc_cookie))
369 panic("died while creating standard software ithreads");
373 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
375 #define CC_HASH_SHIFT 8
378 callout_hash(sbintime_t sbt)
381 return (sbt >> (32 - CC_HASH_SHIFT));
385 callout_get_bucket(sbintime_t sbt)
388 return (callout_hash(sbt) & callwheelmask);
392 callout_process(sbintime_t now)
394 struct callout *tmp, *tmpn;
395 struct callout_cpu *cc;
396 struct callout_list *sc;
397 sbintime_t first, last, max, tmp_max;
399 u_int firstb, lastb, nowb;
400 #ifdef CALLOUT_PROFILING
401 int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
405 mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
407 /* Compute the buckets of the last scan and present times. */
408 firstb = callout_hash(cc->cc_lastscan);
409 cc->cc_lastscan = now;
410 nowb = callout_hash(now);
412 /* Compute the last bucket and minimum time of the bucket after it. */
414 lookahead = (SBT_1S / 16);
415 else if (nowb - firstb == 1)
416 lookahead = (SBT_1S / 8);
418 lookahead = (SBT_1S / 2);
420 first += (lookahead / 2);
422 last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
423 lastb = callout_hash(last) - 1;
427 * Check if we wrapped around the entire wheel from the last scan.
428 * In case, we need to scan entirely the wheel for pending callouts.
430 if (lastb - firstb >= callwheelsize) {
431 lastb = firstb + callwheelsize - 1;
432 if (nowb - firstb >= callwheelsize)
436 /* Iterate callwheel from firstb to nowb and then up to lastb. */
438 sc = &cc->cc_callwheel[firstb & callwheelmask];
439 tmp = LIST_FIRST(sc);
440 while (tmp != NULL) {
441 /* Run the callout if present time within allowed. */
442 if (tmp->c_time <= now) {
444 * Consumer told us the callout may be run
445 * directly from hardware interrupt context.
447 if (tmp->c_flags & CALLOUT_DIRECT) {
448 #ifdef CALLOUT_PROFILING
451 cc->cc_exec_next_dir =
452 LIST_NEXT(tmp, c_links.le);
453 cc->cc_bucket = firstb & callwheelmask;
454 LIST_REMOVE(tmp, c_links.le);
455 softclock_call_cc(tmp, cc,
456 #ifdef CALLOUT_PROFILING
457 &mpcalls_dir, &lockcalls_dir, NULL,
460 tmp = cc->cc_exec_next_dir;
462 tmpn = LIST_NEXT(tmp, c_links.le);
463 LIST_REMOVE(tmp, c_links.le);
464 TAILQ_INSERT_TAIL(&cc->cc_expireq,
466 tmp->c_flags |= CALLOUT_PROCESSED;
471 /* Skip events from distant future. */
472 if (tmp->c_time >= max)
475 * Event minimal time is bigger than present maximal
476 * time, so it cannot be aggregated.
478 if (tmp->c_time > last) {
482 /* Update first and last time, respecting this event. */
483 if (tmp->c_time < first)
485 tmp_max = tmp->c_time + tmp->c_precision;
489 tmp = LIST_NEXT(tmp, c_links.le);
491 /* Proceed with the next bucket. */
494 * Stop if we looked after present time and found
495 * some event we can't execute at now.
496 * Stop if we looked far enough into the future.
498 } while (((int)(firstb - lastb)) <= 0);
499 cc->cc_firstevent = last;
500 #ifndef NO_EVENTTIMERS
501 cpu_new_callout(curcpu, last, first);
503 #ifdef CALLOUT_PROFILING
504 avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
505 avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
506 avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
508 mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
510 * swi_sched acquires the thread lock, so we don't want to call it
511 * with cc_lock held; incorrect locking order.
513 if (!TAILQ_EMPTY(&cc->cc_expireq))
514 swi_sched(cc->cc_cookie, 0);
517 static struct callout_cpu *
518 callout_lock(struct callout *c)
520 struct callout_cpu *cc;
526 if (cpu == CPUBLOCK) {
527 while (c->c_cpu == CPUBLOCK)
542 callout_cc_add(struct callout *c, struct callout_cpu *cc,
543 sbintime_t sbt, sbintime_t precision, void (*func)(void *),
544 void *arg, int cpu, int flags)
549 if (sbt < cc->cc_lastscan)
550 sbt = cc->cc_lastscan;
552 c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
553 if (flags & C_DIRECT_EXEC)
554 c->c_flags |= CALLOUT_DIRECT;
555 c->c_flags &= ~CALLOUT_PROCESSED;
558 c->c_precision = precision;
559 bucket = callout_get_bucket(c->c_time);
560 CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
561 c, (int)(c->c_precision >> 32),
562 (u_int)(c->c_precision & 0xffffffff));
563 LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
564 if (cc->cc_bucket == bucket)
565 cc->cc_exec_next_dir = c;
566 #ifndef NO_EVENTTIMERS
568 * Inform the eventtimers(4) subsystem there's a new callout
569 * that has been inserted, but only if really required.
571 sbt = c->c_time + c->c_precision;
572 if (sbt < cc->cc_firstevent) {
573 cc->cc_firstevent = sbt;
574 cpu_new_callout(cpu, sbt, c->c_time);
580 callout_cc_del(struct callout *c, struct callout_cpu *cc)
583 if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
586 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
590 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
591 #ifdef CALLOUT_PROFILING
592 int *mpcalls, int *lockcalls, int *gcalls,
596 void (*c_func)(void *);
598 struct lock_class *class;
599 struct lock_object *c_lock;
600 int c_flags, sharedlock;
602 struct callout_cpu *new_cc;
603 void (*new_func)(void *);
608 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
609 sbintime_t sbt1, sbt2;
611 static sbintime_t maxdt = 2 * SBT_1MS; /* 2 msec */
612 static timeout_t *lastfunc;
615 KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
616 (CALLOUT_PENDING | CALLOUT_ACTIVE),
617 ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
618 class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
619 sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ? 0 : 1;
623 c_flags = c->c_flags;
624 if (c->c_flags & CALLOUT_LOCAL_ALLOC)
625 c->c_flags = CALLOUT_LOCAL_ALLOC;
627 c->c_flags &= ~CALLOUT_PENDING;
628 cc->cc_exec_entity[direct].cc_curr = c;
629 cc->cc_exec_entity[direct].cc_cancel = false;
631 if (c_lock != NULL) {
632 class->lc_lock(c_lock, sharedlock);
634 * The callout may have been cancelled
635 * while we switched locks.
637 if (cc->cc_exec_entity[direct].cc_cancel) {
638 class->lc_unlock(c_lock);
641 /* The callout cannot be stopped now. */
642 cc->cc_exec_entity[direct].cc_cancel = true;
643 if (c_lock == &Giant.lock_object) {
644 #ifdef CALLOUT_PROFILING
647 CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
650 #ifdef CALLOUT_PROFILING
653 CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
657 #ifdef CALLOUT_PROFILING
660 CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
663 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
666 THREAD_NO_SLEEPING();
667 SDT_PROBE(callout_execute, kernel, , callout_start, c, 0, 0, 0, 0);
669 SDT_PROBE(callout_execute, kernel, , callout_end, c, 0, 0, 0, 0);
670 THREAD_SLEEPING_OK();
671 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
675 if (lastfunc != c_func || sbt2 > maxdt * 2) {
678 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
679 c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
685 CTR1(KTR_CALLOUT, "callout %p finished", c);
686 if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
687 class->lc_unlock(c_lock);
690 KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
691 cc->cc_exec_entity[direct].cc_curr = NULL;
692 if (cc->cc_exec_entity[direct].cc_waiting) {
694 * There is someone waiting for the
695 * callout to complete.
696 * If the callout was scheduled for
697 * migration just cancel it.
699 if (cc_cce_migrating(cc, direct)) {
700 cc_cce_cleanup(cc, direct);
703 * It should be assert here that the callout is not
704 * destroyed but that is not easy.
706 c->c_flags &= ~CALLOUT_DFRMIGRATION;
708 cc->cc_exec_entity[direct].cc_waiting = false;
710 wakeup(&cc->cc_exec_entity[direct].cc_waiting);
712 } else if (cc_cce_migrating(cc, direct)) {
713 KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
714 ("Migrating legacy callout %p", c));
717 * If the callout was scheduled for
718 * migration just perform it now.
720 new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
721 new_time = cc->cc_exec_entity[direct].ce_migration_time;
722 new_func = cc->cc_exec_entity[direct].ce_migration_func;
723 new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
724 cc_cce_cleanup(cc, direct);
727 * It should be assert here that the callout is not destroyed
728 * but that is not easy.
730 * As first thing, handle deferred callout stops.
732 if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
734 "deferred cancelled %p func %p arg %p",
735 c, new_func, new_arg);
736 callout_cc_del(c, cc);
739 c->c_flags &= ~CALLOUT_DFRMIGRATION;
741 new_cc = callout_cpu_switch(c, cc, new_cpu);
742 flags = (direct) ? C_DIRECT_EXEC : 0;
743 callout_cc_add(c, new_cc, new_time, c->c_precision, new_func,
744 new_arg, new_cpu, flags);
748 panic("migration should not happen");
752 * If the current callout is locally allocated (from
753 * timeout(9)) then put it on the freelist.
755 * Note: we need to check the cached copy of c_flags because
756 * if it was not local, then it's not safe to deref the
759 KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
760 c->c_flags == CALLOUT_LOCAL_ALLOC,
761 ("corrupted callout"));
762 if (c_flags & CALLOUT_LOCAL_ALLOC)
763 callout_cc_del(c, cc);
767 * The callout mechanism is based on the work of Adam M. Costello and
768 * George Varghese, published in a technical report entitled "Redesigning
769 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
770 * in FreeBSD by Justin T. Gibbs. The original work on the data structures
771 * used in this implementation was published by G. Varghese and T. Lauck in
772 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
773 * the Efficient Implementation of a Timer Facility" in the Proceedings of
774 * the 11th ACM Annual Symposium on Operating Systems Principles,
775 * Austin, Texas Nov 1987.
779 * Software (low priority) clock interrupt.
780 * Run periodic events from timeout queue.
785 struct callout_cpu *cc;
787 #ifdef CALLOUT_PROFILING
788 int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
791 cc = (struct callout_cpu *)arg;
793 while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
794 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
795 softclock_call_cc(c, cc,
796 #ifdef CALLOUT_PROFILING
797 &mpcalls, &lockcalls, &gcalls,
800 #ifdef CALLOUT_PROFILING
804 #ifdef CALLOUT_PROFILING
805 avg_depth += (depth * 1000 - avg_depth) >> 8;
806 avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
807 avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
808 avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
815 * Execute a function after a specified length of time.
818 * Cancel previous timeout function call.
820 * callout_handle_init --
821 * Initialize a handle so that using it with untimeout is benign.
823 * See AT&T BCI Driver Reference Manual for specification. This
824 * implementation differs from that one in that although an
825 * identification value is returned from timeout, the original
826 * arguments to timeout as well as the identifier are used to
827 * identify entries for untimeout.
829 struct callout_handle
830 timeout(ftn, arg, to_ticks)
835 struct callout_cpu *cc;
837 struct callout_handle handle;
839 cc = CC_CPU(timeout_cpu);
841 /* Fill in the next free callout structure. */
842 new = SLIST_FIRST(&cc->cc_callfree);
844 /* XXX Attempt to malloc first */
845 panic("timeout table full");
846 SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
847 callout_reset(new, to_ticks, ftn, arg);
848 handle.callout = new;
855 untimeout(ftn, arg, handle)
858 struct callout_handle handle;
860 struct callout_cpu *cc;
863 * Check for a handle that was initialized
864 * by callout_handle_init, but never used
865 * for a real timeout.
867 if (handle.callout == NULL)
870 cc = callout_lock(handle.callout);
871 if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
872 callout_stop(handle.callout);
877 callout_handle_init(struct callout_handle *handle)
879 handle->callout = NULL;
883 * New interface; clients allocate their own callout structures.
885 * callout_reset() - establish or change a timeout
886 * callout_stop() - disestablish a timeout
887 * callout_init() - initialize a callout structure so that it can
888 * safely be passed to callout_reset() and callout_stop()
890 * <sys/callout.h> defines three convenience macros:
892 * callout_active() - returns truth if callout has not been stopped,
893 * drained, or deactivated since the last time the callout was
895 * callout_pending() - returns truth if callout is still waiting for timeout
896 * callout_deactivate() - marks the callout as having been serviced
899 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
900 void (*ftn)(void *), void *arg, int cpu, int flags)
902 sbintime_t to_sbt, pr;
903 struct callout_cpu *cc;
904 int cancelled, direct;
907 if (flags & C_ABSOLUTE) {
910 if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
912 if ((flags & C_HARDCLOCK) ||
913 #ifdef NO_EVENTTIMERS
914 sbt >= sbt_timethreshold) {
915 to_sbt = getsbinuptime();
917 /* Add safety belt for the case of hz > 1000. */
918 to_sbt += tc_tick_sbt - tick_sbt;
920 sbt >= sbt_tickthreshold) {
922 * Obtain the time of the last hardclock() call on
923 * this CPU directly from the kern_clocksource.c.
924 * This value is per-CPU, but it is equal for all
928 to_sbt = DPCPU_GET(hardclocktime);
931 to_sbt = DPCPU_GET(hardclocktime);
935 if ((flags & C_HARDCLOCK) == 0)
938 to_sbt = sbinuptime();
940 pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
941 sbt >> C_PRELGET(flags));
946 * Don't allow migration of pre-allocated callouts lest they
949 if (c->c_flags & CALLOUT_LOCAL_ALLOC)
951 direct = (c->c_flags & CALLOUT_DIRECT) != 0;
952 KASSERT(!direct || c->c_lock == NULL,
953 ("%s: direct callout %p has lock", __func__, c));
954 cc = callout_lock(c);
955 if (cc->cc_exec_entity[direct].cc_curr == c) {
957 * We're being asked to reschedule a callout which is
958 * currently in progress. If there is a lock then we
959 * can cancel the callout if it has not really started.
961 if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
962 cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
963 if (cc->cc_exec_entity[direct].cc_waiting) {
965 * Someone has called callout_drain to kill this
966 * callout. Don't reschedule.
968 CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
969 cancelled ? "cancelled" : "failed to cancel",
970 c, c->c_func, c->c_arg);
975 if (c->c_flags & CALLOUT_PENDING) {
976 if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
977 if (cc->cc_exec_next_dir == c)
978 cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
979 LIST_REMOVE(c, c_links.le);
981 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
983 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
988 * If the callout must migrate try to perform it immediately.
989 * If the callout is currently running, just defer the migration
990 * to a more appropriate moment.
992 if (c->c_cpu != cpu) {
993 if (cc->cc_exec_entity[direct].cc_curr == c) {
994 cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
995 cc->cc_exec_entity[direct].ce_migration_time
997 cc->cc_exec_entity[direct].ce_migration_func = ftn;
998 cc->cc_exec_entity[direct].ce_migration_arg = arg;
999 c->c_flags |= CALLOUT_DFRMIGRATION;
1001 "migration of %p func %p arg %p in %d.%08x to %u deferred",
1002 c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1003 (u_int)(to_sbt & 0xffffffff), cpu);
1007 cc = callout_cpu_switch(c, cc, cpu);
1011 callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1012 CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1013 cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1014 (u_int)(to_sbt & 0xffffffff));
1021 * Common idioms that can be optimized in the future.
1024 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1026 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1030 callout_schedule(struct callout *c, int to_ticks)
1032 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1036 _callout_stop_safe(c, safe)
1040 struct callout_cpu *cc, *old_cc;
1041 struct lock_class *class;
1042 int direct, sq_locked, use_lock;
1045 * Some old subsystems don't hold Giant while running a callout_stop(),
1046 * so just discard this check for the moment.
1048 if (!safe && c->c_lock != NULL) {
1049 if (c->c_lock == &Giant.lock_object)
1050 use_lock = mtx_owned(&Giant);
1053 class = LOCK_CLASS(c->c_lock);
1054 class->lc_assert(c->c_lock, LA_XLOCKED);
1058 direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1062 cc = callout_lock(c);
1065 * If the callout was migrating while the callout cpu lock was
1066 * dropped, just drop the sleepqueue lock and check the states
1069 if (sq_locked != 0 && cc != old_cc) {
1072 sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
1077 panic("migration should not happen");
1082 * If the callout isn't pending, it's not on the queue, so
1083 * don't attempt to remove it from the queue. We can try to
1084 * stop it by other means however.
1086 if (!(c->c_flags & CALLOUT_PENDING)) {
1087 c->c_flags &= ~CALLOUT_ACTIVE;
1090 * If it wasn't on the queue and it isn't the current
1091 * callout, then we can't stop it, so just bail.
1093 if (cc->cc_exec_entity[direct].cc_curr != c) {
1094 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1095 c, c->c_func, c->c_arg);
1099 &cc->cc_exec_entity[direct].cc_waiting);
1105 * The current callout is running (or just
1106 * about to run) and blocking is allowed, so
1107 * just wait for the current invocation to
1110 while (cc->cc_exec_entity[direct].cc_curr == c) {
1112 * Use direct calls to sleepqueue interface
1113 * instead of cv/msleep in order to avoid
1114 * a LOR between cc_lock and sleepqueue
1115 * chain spinlocks. This piece of code
1116 * emulates a msleep_spin() call actually.
1118 * If we already have the sleepqueue chain
1119 * locked, then we can safely block. If we
1120 * don't already have it locked, however,
1121 * we have to drop the cc_lock to lock
1122 * it. This opens several races, so we
1123 * restart at the beginning once we have
1124 * both locks. If nothing has changed, then
1125 * we will end up back here with sq_locked
1131 &cc->cc_exec_entity[direct].cc_waiting);
1138 * Migration could be cancelled here, but
1139 * as long as it is still not sure when it
1140 * will be packed up, just let softclock()
1143 cc->cc_exec_entity[direct].cc_waiting = true;
1147 &cc->cc_exec_entity[direct].cc_waiting,
1148 &cc->cc_lock.lock_object, "codrain",
1151 &cc->cc_exec_entity[direct].cc_waiting,
1156 /* Reacquire locks previously released. */
1160 } else if (use_lock &&
1161 !cc->cc_exec_entity[direct].cc_cancel) {
1163 * The current callout is waiting for its
1164 * lock which we hold. Cancel the callout
1165 * and return. After our caller drops the
1166 * lock, the callout will be skipped in
1169 cc->cc_exec_entity[direct].cc_cancel = true;
1170 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1171 c, c->c_func, c->c_arg);
1172 KASSERT(!cc_cce_migrating(cc, direct),
1173 ("callout wrongly scheduled for migration"));
1175 KASSERT(!sq_locked, ("sleepqueue chain locked"));
1177 } else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
1178 c->c_flags &= ~CALLOUT_DFRMIGRATION;
1179 CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1180 c, c->c_func, c->c_arg);
1184 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1185 c, c->c_func, c->c_arg);
1187 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1191 sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
1193 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1195 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1196 c, c->c_func, c->c_arg);
1197 if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1198 if (cc->cc_exec_next_dir == c)
1199 cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1200 LIST_REMOVE(c, c_links.le);
1202 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1203 callout_cc_del(c, cc);
1210 callout_init(c, mpsafe)
1214 bzero(c, sizeof *c);
1217 c->c_flags = CALLOUT_RETURNUNLOCKED;
1219 c->c_lock = &Giant.lock_object;
1222 c->c_cpu = timeout_cpu;
1226 _callout_init_lock(c, lock, flags)
1228 struct lock_object *lock;
1231 bzero(c, sizeof *c);
1233 KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1234 ("callout_init_lock: bad flags %d", flags));
1235 KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1236 ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1237 KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1238 (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1240 c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1241 c->c_cpu = timeout_cpu;
1244 #ifdef APM_FIXUP_CALLTODO
1246 * Adjust the kernel calltodo timeout list. This routine is used after
1247 * an APM resume to recalculate the calltodo timer list values with the
1248 * number of hz's we have been sleeping. The next hardclock() will detect
1249 * that there are fired timers and run softclock() to execute them.
1251 * Please note, I have not done an exhaustive analysis of what code this
1252 * might break. I am motivated to have my select()'s and alarm()'s that
1253 * have expired during suspend firing upon resume so that the applications
1254 * which set the timer can do the maintanence the timer was for as close
1255 * as possible to the originally intended time. Testing this code for a
1256 * week showed that resuming from a suspend resulted in 22 to 25 timers
1257 * firing, which seemed independant on whether the suspend was 2 hours or
1258 * 2 days. Your milage may vary. - Ken Key <key@cs.utk.edu>
1261 adjust_timeout_calltodo(time_change)
1262 struct timeval *time_change;
1264 register struct callout *p;
1265 unsigned long delta_ticks;
1268 * How many ticks were we asleep?
1269 * (stolen from tvtohz()).
1272 /* Don't do anything */
1273 if (time_change->tv_sec < 0)
1275 else if (time_change->tv_sec <= LONG_MAX / 1000000)
1276 delta_ticks = (time_change->tv_sec * 1000000 +
1277 time_change->tv_usec + (tick - 1)) / tick + 1;
1278 else if (time_change->tv_sec <= LONG_MAX / hz)
1279 delta_ticks = time_change->tv_sec * hz +
1280 (time_change->tv_usec + (tick - 1)) / tick + 1;
1282 delta_ticks = LONG_MAX;
1284 if (delta_ticks > INT_MAX)
1285 delta_ticks = INT_MAX;
1288 * Now rip through the timer calltodo list looking for timers
1292 /* don't collide with softclock() */
1294 for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1295 p->c_time -= delta_ticks;
1297 /* Break if the timer had more time on it than delta_ticks */
1301 /* take back the ticks the timer didn't use (p->c_time <= 0) */
1302 delta_ticks = -p->c_time;
1308 #endif /* APM_FIXUP_CALLTODO */
1311 flssbt(sbintime_t sbt)
1314 sbt += (uint64_t)sbt >> 1;
1315 if (sizeof(long) >= sizeof(sbintime_t))
1318 return (flsl(((uint64_t)sbt) >> 32) + 32);
1323 * Dump immediate statistic snapshot of the scheduled callouts.
1326 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1328 struct callout *tmp;
1329 struct callout_cpu *cc;
1330 struct callout_list *sc;
1331 sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1332 int ct[64], cpr[64], ccpbk[32];
1333 int error, val, i, count, tcum, pcum, maxc, c, medc;
1339 error = sysctl_handle_int(oidp, &val, 0, req);
1340 if (error != 0 || req->newptr == NULL)
1343 st = spr = maxt = maxpr = 0;
1344 bzero(ccpbk, sizeof(ccpbk));
1345 bzero(ct, sizeof(ct));
1346 bzero(cpr, sizeof(cpr));
1352 cc = CC_CPU(timeout_cpu);
1355 for (i = 0; i < callwheelsize; i++) {
1356 sc = &cc->cc_callwheel[i];
1358 LIST_FOREACH(tmp, sc, c_links.le) {
1360 t = tmp->c_time - now;
1364 spr += tmp->c_precision / SBT_1US;
1367 if (tmp->c_precision > maxpr)
1368 maxpr = tmp->c_precision;
1370 cpr[flssbt(tmp->c_precision)]++;
1374 ccpbk[fls(c + c / 2)]++;
1382 for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1384 medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1385 for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1387 medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1388 for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1390 medc = (i >= 2) ? (1 << (i - 2)) : 0;
1392 printf("Scheduled callouts statistic snapshot:\n");
1393 printf(" Callouts: %6d Buckets: %6d*%-3d Bucket size: 0.%06ds\n",
1394 count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1395 printf(" C/Bk: med %5d avg %6d.%06jd max %6d\n",
1397 count / callwheelsize / mp_ncpus,
1398 (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1400 printf(" Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1401 medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1402 (st / count) / 1000000, (st / count) % 1000000,
1403 maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1404 printf(" Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1405 medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1406 (spr / count) / 1000000, (spr / count) % 1000000,
1407 maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1408 printf(" Distribution: \tbuckets\t time\t tcum\t"
1410 for (i = 0, tcum = pcum = 0; i < 64; i++) {
1411 if (ct[i] == 0 && cpr[i] == 0)
1413 t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1416 printf(" %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1417 t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1418 i - 1 - (32 - CC_HASH_SHIFT),
1419 ct[i], tcum, cpr[i], pcum);
1423 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1424 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1425 0, 0, sysctl_kern_callout_stat, "I",
1426 "Dump immediate statistic snapshot of the scheduled callouts");