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"
42 #include "opt_timer.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/callout.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
54 #include <sys/malloc.h>
55 #include <sys/mutex.h>
58 #include <sys/sleepqueue.h>
59 #include <sys/sysctl.h>
63 #include <machine/cpu.h>
66 #ifndef NO_EVENTTIMERS
67 DPCPU_DECLARE(sbintime_t, hardclocktime);
70 SDT_PROVIDER_DEFINE(callout_execute);
71 SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__start,
73 SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__end,
76 #ifdef CALLOUT_PROFILING
78 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
79 "Average number of items examined per softclock call. Units = 1/1000");
80 static int avg_gcalls;
81 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
82 "Average number of Giant callouts made per softclock call. Units = 1/1000");
83 static int avg_lockcalls;
84 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
85 "Average number of lock callouts made per softclock call. Units = 1/1000");
86 static int avg_mpcalls;
87 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
88 "Average number of MP callouts made per softclock call. Units = 1/1000");
89 static int avg_depth_dir;
90 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
91 "Average number of direct callouts examined per callout_process call. "
93 static int avg_lockcalls_dir;
94 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
95 &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
96 "callout_process call. Units = 1/1000");
97 static int avg_mpcalls_dir;
98 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
99 0, "Average number of MP direct callouts made per callout_process call. "
104 SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN, &ncallout, 0,
105 "Number of entries in callwheel and size of timeout() preallocation");
109 * allocate more timeout table slots when table overflows.
111 u_int callwheelsize, callwheelmask;
114 * The callout cpu exec entities represent informations necessary for
115 * describing the state of callouts currently running on the CPU and the ones
116 * necessary for migrating callouts to the new callout cpu. In particular,
117 * the first entry of the array cc_exec_entity holds informations for callout
118 * running in SWI thread context, while the second one holds informations
119 * for callout running directly from hardware interrupt context.
120 * The cached informations are very important for deferring migration when
121 * the migrating callout is already running.
124 struct callout *cc_next;
125 struct callout *cc_curr;
127 void (*ce_migration_func)(void *);
128 void *ce_migration_arg;
129 int ce_migration_cpu;
130 sbintime_t ce_migration_time;
131 sbintime_t ce_migration_prec;
138 * There is one struct callout_cpu per cpu, holding all relevant
139 * state for the callout processing thread on the individual CPU.
142 struct mtx_padalign cc_lock;
143 struct cc_exec cc_exec_entity[2];
144 struct callout *cc_callout;
145 struct callout_list *cc_callwheel;
146 struct callout_tailq cc_expireq;
147 struct callout_slist cc_callfree;
148 sbintime_t cc_firstevent;
149 sbintime_t cc_lastscan;
154 #define cc_exec_curr cc_exec_entity[0].cc_curr
155 #define cc_exec_next cc_exec_entity[0].cc_next
156 #define cc_exec_cancel cc_exec_entity[0].cc_cancel
157 #define cc_exec_waiting cc_exec_entity[0].cc_waiting
158 #define cc_exec_curr_dir cc_exec_entity[1].cc_curr
159 #define cc_exec_next_dir cc_exec_entity[1].cc_next
160 #define cc_exec_cancel_dir cc_exec_entity[1].cc_cancel
161 #define cc_exec_waiting_dir cc_exec_entity[1].cc_waiting
164 #define cc_migration_func cc_exec_entity[0].ce_migration_func
165 #define cc_migration_arg cc_exec_entity[0].ce_migration_arg
166 #define cc_migration_cpu cc_exec_entity[0].ce_migration_cpu
167 #define cc_migration_time cc_exec_entity[0].ce_migration_time
168 #define cc_migration_prec cc_exec_entity[0].ce_migration_prec
169 #define cc_migration_func_dir cc_exec_entity[1].ce_migration_func
170 #define cc_migration_arg_dir cc_exec_entity[1].ce_migration_arg
171 #define cc_migration_cpu_dir cc_exec_entity[1].ce_migration_cpu
172 #define cc_migration_time_dir cc_exec_entity[1].ce_migration_time
173 #define cc_migration_prec_dir cc_exec_entity[1].ce_migration_prec
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_prec = 0;
231 cc->cc_exec_entity[direct].ce_migration_func = NULL;
232 cc->cc_exec_entity[direct].ce_migration_arg = NULL;
237 * Checks if migration is requested by a specific callout cpu.
240 cc_cce_migrating(struct callout_cpu *cc, int direct)
244 return (cc->cc_exec_entity[direct].ce_migration_cpu != CPUBLOCK);
251 * Kernel low level callwheel initialization
252 * called on cpu0 during kernel startup.
255 callout_callwheel_init(void *dummy)
257 struct callout_cpu *cc;
260 * Calculate the size of the callout wheel and the preallocated
261 * timeout() structures.
262 * XXX: Clip callout to result of previous function of maxusers
263 * maximum 384. This is still huge, but acceptable.
265 ncallout = imin(16 + maxproc + maxfiles, 18508);
266 TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
269 * Calculate callout wheel size, should be next power of two higher
272 callwheelsize = 1 << fls(ncallout);
273 callwheelmask = callwheelsize - 1;
276 * Only cpu0 handles timeout(9) and receives a preallocation.
278 * XXX: Once all timeout(9) consumers are converted this can
281 timeout_cpu = PCPU_GET(cpuid);
282 cc = CC_CPU(timeout_cpu);
283 cc->cc_callout = malloc(ncallout * sizeof(struct callout),
284 M_CALLOUT, M_WAITOK);
285 callout_cpu_init(cc);
287 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
290 * Initialize the per-cpu callout structures.
293 callout_cpu_init(struct callout_cpu *cc)
298 mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
299 SLIST_INIT(&cc->cc_callfree);
300 cc->cc_callwheel = malloc(sizeof(struct callout_list) * callwheelsize,
301 M_CALLOUT, M_WAITOK);
302 for (i = 0; i < callwheelsize; i++)
303 LIST_INIT(&cc->cc_callwheel[i]);
304 TAILQ_INIT(&cc->cc_expireq);
305 cc->cc_firstevent = INT64_MAX;
306 for (i = 0; i < 2; i++)
307 cc_cce_cleanup(cc, i);
308 if (cc->cc_callout == NULL) /* Only cpu0 handles timeout(9) */
310 for (i = 0; i < ncallout; i++) {
311 c = &cc->cc_callout[i];
313 c->c_flags = CALLOUT_LOCAL_ALLOC;
314 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
320 * Switches the cpu tied to a specific callout.
321 * The function expects a locked incoming callout cpu and returns with
322 * locked outcoming callout cpu.
324 static struct callout_cpu *
325 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
327 struct callout_cpu *new_cc;
329 MPASS(c != NULL && cc != NULL);
333 * Avoid interrupts and preemption firing after the callout cpu
334 * is blocked in order to avoid deadlocks as the new thread
335 * may be willing to acquire the callout cpu lock.
340 new_cc = CC_CPU(new_cpu);
349 * Start standard softclock thread.
352 start_softclock(void *dummy)
354 struct callout_cpu *cc;
359 cc = CC_CPU(timeout_cpu);
360 if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
361 INTR_MPSAFE, &cc->cc_cookie))
362 panic("died while creating standard software ithreads");
365 if (cpu == timeout_cpu)
368 cc->cc_callout = NULL; /* Only cpu0 handles timeout(9). */
369 callout_cpu_init(cc);
370 if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
371 INTR_MPSAFE, &cc->cc_cookie))
372 panic("died while creating standard software ithreads");
376 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
378 #define CC_HASH_SHIFT 8
381 callout_hash(sbintime_t sbt)
384 return (sbt >> (32 - CC_HASH_SHIFT));
388 callout_get_bucket(sbintime_t sbt)
391 return (callout_hash(sbt) & callwheelmask);
395 callout_process(sbintime_t now)
397 struct callout *tmp, *tmpn;
398 struct callout_cpu *cc;
399 struct callout_list *sc;
400 sbintime_t first, last, max, tmp_max;
402 u_int firstb, lastb, nowb;
403 #ifdef CALLOUT_PROFILING
404 int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
408 mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
410 /* Compute the buckets of the last scan and present times. */
411 firstb = callout_hash(cc->cc_lastscan);
412 cc->cc_lastscan = now;
413 nowb = callout_hash(now);
415 /* Compute the last bucket and minimum time of the bucket after it. */
417 lookahead = (SBT_1S / 16);
418 else if (nowb - firstb == 1)
419 lookahead = (SBT_1S / 8);
421 lookahead = (SBT_1S / 2);
423 first += (lookahead / 2);
425 last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
426 lastb = callout_hash(last) - 1;
430 * Check if we wrapped around the entire wheel from the last scan.
431 * In case, we need to scan entirely the wheel for pending callouts.
433 if (lastb - firstb >= callwheelsize) {
434 lastb = firstb + callwheelsize - 1;
435 if (nowb - firstb >= callwheelsize)
439 /* Iterate callwheel from firstb to nowb and then up to lastb. */
441 sc = &cc->cc_callwheel[firstb & callwheelmask];
442 tmp = LIST_FIRST(sc);
443 while (tmp != NULL) {
444 /* Run the callout if present time within allowed. */
445 if (tmp->c_time <= now) {
447 * Consumer told us the callout may be run
448 * directly from hardware interrupt context.
450 if (tmp->c_flags & CALLOUT_DIRECT) {
451 #ifdef CALLOUT_PROFILING
454 cc->cc_exec_next_dir =
455 LIST_NEXT(tmp, c_links.le);
456 cc->cc_bucket = firstb & callwheelmask;
457 LIST_REMOVE(tmp, c_links.le);
458 softclock_call_cc(tmp, cc,
459 #ifdef CALLOUT_PROFILING
460 &mpcalls_dir, &lockcalls_dir, NULL,
463 tmp = cc->cc_exec_next_dir;
465 tmpn = LIST_NEXT(tmp, c_links.le);
466 LIST_REMOVE(tmp, c_links.le);
467 TAILQ_INSERT_TAIL(&cc->cc_expireq,
469 tmp->c_flags |= CALLOUT_PROCESSED;
474 /* Skip events from distant future. */
475 if (tmp->c_time >= max)
478 * Event minimal time is bigger than present maximal
479 * time, so it cannot be aggregated.
481 if (tmp->c_time > last) {
485 /* Update first and last time, respecting this event. */
486 if (tmp->c_time < first)
488 tmp_max = tmp->c_time + tmp->c_precision;
492 tmp = LIST_NEXT(tmp, c_links.le);
494 /* Proceed with the next bucket. */
497 * Stop if we looked after present time and found
498 * some event we can't execute at now.
499 * Stop if we looked far enough into the future.
501 } while (((int)(firstb - lastb)) <= 0);
502 cc->cc_firstevent = last;
503 #ifndef NO_EVENTTIMERS
504 cpu_new_callout(curcpu, last, first);
506 #ifdef CALLOUT_PROFILING
507 avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
508 avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
509 avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
511 mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
513 * swi_sched acquires the thread lock, so we don't want to call it
514 * with cc_lock held; incorrect locking order.
516 if (!TAILQ_EMPTY(&cc->cc_expireq))
517 swi_sched(cc->cc_cookie, 0);
520 static struct callout_cpu *
521 callout_lock(struct callout *c)
523 struct callout_cpu *cc;
529 if (cpu == CPUBLOCK) {
530 while (c->c_cpu == CPUBLOCK)
545 callout_cc_add(struct callout *c, struct callout_cpu *cc,
546 sbintime_t sbt, sbintime_t precision, void (*func)(void *),
547 void *arg, int cpu, int flags)
552 if (sbt < cc->cc_lastscan)
553 sbt = cc->cc_lastscan;
555 c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
556 if (flags & C_DIRECT_EXEC)
557 c->c_flags |= CALLOUT_DIRECT;
558 c->c_flags &= ~CALLOUT_PROCESSED;
561 c->c_precision = precision;
562 bucket = callout_get_bucket(c->c_time);
563 CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
564 c, (int)(c->c_precision >> 32),
565 (u_int)(c->c_precision & 0xffffffff));
566 LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
567 if (cc->cc_bucket == bucket)
568 cc->cc_exec_next_dir = c;
569 #ifndef NO_EVENTTIMERS
571 * Inform the eventtimers(4) subsystem there's a new callout
572 * that has been inserted, but only if really required.
574 if (INT64_MAX - c->c_time < c->c_precision)
575 c->c_precision = INT64_MAX - c->c_time;
576 sbt = c->c_time + c->c_precision;
577 if (sbt < cc->cc_firstevent) {
578 cc->cc_firstevent = sbt;
579 cpu_new_callout(cpu, sbt, c->c_time);
585 callout_cc_del(struct callout *c, struct callout_cpu *cc)
588 if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
591 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
595 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
596 #ifdef CALLOUT_PROFILING
597 int *mpcalls, int *lockcalls, int *gcalls,
601 struct rm_priotracker tracker;
602 void (*c_func)(void *);
604 struct lock_class *class;
605 struct lock_object *c_lock;
606 uintptr_t lock_status;
609 struct callout_cpu *new_cc;
610 void (*new_func)(void *);
613 sbintime_t new_prec, new_time;
615 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
616 sbintime_t sbt1, sbt2;
618 static sbintime_t maxdt = 2 * SBT_1MS; /* 2 msec */
619 static timeout_t *lastfunc;
622 KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
623 (CALLOUT_PENDING | CALLOUT_ACTIVE),
624 ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
625 class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
627 if (c->c_flags & CALLOUT_SHAREDLOCK) {
628 if (class == &lock_class_rm)
629 lock_status = (uintptr_t)&tracker;
636 c_flags = c->c_flags;
637 if (c->c_flags & CALLOUT_LOCAL_ALLOC)
638 c->c_flags = CALLOUT_LOCAL_ALLOC;
640 c->c_flags &= ~CALLOUT_PENDING;
641 cc->cc_exec_entity[direct].cc_curr = c;
642 cc->cc_exec_entity[direct].cc_cancel = false;
644 if (c_lock != NULL) {
645 class->lc_lock(c_lock, lock_status);
647 * The callout may have been cancelled
648 * while we switched locks.
650 if (cc->cc_exec_entity[direct].cc_cancel) {
651 class->lc_unlock(c_lock);
654 /* The callout cannot be stopped now. */
655 cc->cc_exec_entity[direct].cc_cancel = true;
656 if (c_lock == &Giant.lock_object) {
657 #ifdef CALLOUT_PROFILING
660 CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
663 #ifdef CALLOUT_PROFILING
666 CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
670 #ifdef CALLOUT_PROFILING
673 CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
676 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
679 THREAD_NO_SLEEPING();
680 SDT_PROBE(callout_execute, kernel, , callout__start, c, 0, 0, 0, 0);
682 SDT_PROBE(callout_execute, kernel, , callout__end, c, 0, 0, 0, 0);
683 THREAD_SLEEPING_OK();
684 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
688 if (lastfunc != c_func || sbt2 > maxdt * 2) {
691 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
692 c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
698 CTR1(KTR_CALLOUT, "callout %p finished", c);
699 if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
700 class->lc_unlock(c_lock);
703 KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
704 cc->cc_exec_entity[direct].cc_curr = NULL;
705 if (cc->cc_exec_entity[direct].cc_waiting) {
707 * There is someone waiting for the
708 * callout to complete.
709 * If the callout was scheduled for
710 * migration just cancel it.
712 if (cc_cce_migrating(cc, direct)) {
713 cc_cce_cleanup(cc, direct);
716 * It should be assert here that the callout is not
717 * destroyed but that is not easy.
719 c->c_flags &= ~CALLOUT_DFRMIGRATION;
721 cc->cc_exec_entity[direct].cc_waiting = false;
723 wakeup(&cc->cc_exec_entity[direct].cc_waiting);
725 } else if (cc_cce_migrating(cc, direct)) {
726 KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
727 ("Migrating legacy callout %p", c));
730 * If the callout was scheduled for
731 * migration just perform it now.
733 new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
734 new_time = cc->cc_exec_entity[direct].ce_migration_time;
735 new_prec = cc->cc_exec_entity[direct].ce_migration_prec;
736 new_func = cc->cc_exec_entity[direct].ce_migration_func;
737 new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
738 cc_cce_cleanup(cc, direct);
741 * It should be assert here that the callout is not destroyed
742 * but that is not easy.
744 * As first thing, handle deferred callout stops.
746 if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
748 "deferred cancelled %p func %p arg %p",
749 c, new_func, new_arg);
750 callout_cc_del(c, cc);
753 c->c_flags &= ~CALLOUT_DFRMIGRATION;
755 new_cc = callout_cpu_switch(c, cc, new_cpu);
756 flags = (direct) ? C_DIRECT_EXEC : 0;
757 callout_cc_add(c, new_cc, new_time, new_prec, new_func,
758 new_arg, new_cpu, flags);
762 panic("migration should not happen");
766 * If the current callout is locally allocated (from
767 * timeout(9)) then put it on the freelist.
769 * Note: we need to check the cached copy of c_flags because
770 * if it was not local, then it's not safe to deref the
773 KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
774 c->c_flags == CALLOUT_LOCAL_ALLOC,
775 ("corrupted callout"));
776 if (c_flags & CALLOUT_LOCAL_ALLOC)
777 callout_cc_del(c, cc);
781 * The callout mechanism is based on the work of Adam M. Costello and
782 * George Varghese, published in a technical report entitled "Redesigning
783 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
784 * in FreeBSD by Justin T. Gibbs. The original work on the data structures
785 * used in this implementation was published by G. Varghese and T. Lauck in
786 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
787 * the Efficient Implementation of a Timer Facility" in the Proceedings of
788 * the 11th ACM Annual Symposium on Operating Systems Principles,
789 * Austin, Texas Nov 1987.
793 * Software (low priority) clock interrupt.
794 * Run periodic events from timeout queue.
799 struct callout_cpu *cc;
801 #ifdef CALLOUT_PROFILING
802 int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
805 cc = (struct callout_cpu *)arg;
807 while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
808 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
809 softclock_call_cc(c, cc,
810 #ifdef CALLOUT_PROFILING
811 &mpcalls, &lockcalls, &gcalls,
814 #ifdef CALLOUT_PROFILING
818 #ifdef CALLOUT_PROFILING
819 avg_depth += (depth * 1000 - avg_depth) >> 8;
820 avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
821 avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
822 avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
829 * Execute a function after a specified length of time.
832 * Cancel previous timeout function call.
834 * callout_handle_init --
835 * Initialize a handle so that using it with untimeout is benign.
837 * See AT&T BCI Driver Reference Manual for specification. This
838 * implementation differs from that one in that although an
839 * identification value is returned from timeout, the original
840 * arguments to timeout as well as the identifier are used to
841 * identify entries for untimeout.
843 struct callout_handle
844 timeout(ftn, arg, to_ticks)
849 struct callout_cpu *cc;
851 struct callout_handle handle;
853 cc = CC_CPU(timeout_cpu);
855 /* Fill in the next free callout structure. */
856 new = SLIST_FIRST(&cc->cc_callfree);
858 /* XXX Attempt to malloc first */
859 panic("timeout table full");
860 SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
861 callout_reset(new, to_ticks, ftn, arg);
862 handle.callout = new;
869 untimeout(ftn, arg, handle)
872 struct callout_handle handle;
874 struct callout_cpu *cc;
877 * Check for a handle that was initialized
878 * by callout_handle_init, but never used
879 * for a real timeout.
881 if (handle.callout == NULL)
884 cc = callout_lock(handle.callout);
885 if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
886 callout_stop(handle.callout);
891 callout_handle_init(struct callout_handle *handle)
893 handle->callout = NULL;
897 * New interface; clients allocate their own callout structures.
899 * callout_reset() - establish or change a timeout
900 * callout_stop() - disestablish a timeout
901 * callout_init() - initialize a callout structure so that it can
902 * safely be passed to callout_reset() and callout_stop()
904 * <sys/callout.h> defines three convenience macros:
906 * callout_active() - returns truth if callout has not been stopped,
907 * drained, or deactivated since the last time the callout was
909 * callout_pending() - returns truth if callout is still waiting for timeout
910 * callout_deactivate() - marks the callout as having been serviced
913 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
914 void (*ftn)(void *), void *arg, int cpu, int flags)
916 sbintime_t to_sbt, pr;
917 struct callout_cpu *cc;
918 int cancelled, direct;
921 if (flags & C_ABSOLUTE) {
924 if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
926 if ((flags & C_HARDCLOCK) ||
927 #ifdef NO_EVENTTIMERS
928 sbt >= sbt_timethreshold) {
929 to_sbt = getsbinuptime();
931 /* Add safety belt for the case of hz > 1000. */
932 to_sbt += tc_tick_sbt - tick_sbt;
934 sbt >= sbt_tickthreshold) {
936 * Obtain the time of the last hardclock() call on
937 * this CPU directly from the kern_clocksource.c.
938 * This value is per-CPU, but it is equal for all
942 to_sbt = DPCPU_GET(hardclocktime);
945 to_sbt = DPCPU_GET(hardclocktime);
949 if ((flags & C_HARDCLOCK) == 0)
952 to_sbt = sbinuptime();
953 if (INT64_MAX - to_sbt < sbt)
957 pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
958 sbt >> C_PRELGET(flags));
963 * Don't allow migration of pre-allocated callouts lest they
966 if (c->c_flags & CALLOUT_LOCAL_ALLOC)
968 direct = (c->c_flags & CALLOUT_DIRECT) != 0;
969 KASSERT(!direct || c->c_lock == NULL,
970 ("%s: direct callout %p has lock", __func__, c));
971 cc = callout_lock(c);
972 if (cc->cc_exec_entity[direct].cc_curr == c) {
974 * We're being asked to reschedule a callout which is
975 * currently in progress. If there is a lock then we
976 * can cancel the callout if it has not really started.
978 if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
979 cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
980 if (cc->cc_exec_entity[direct].cc_waiting) {
982 * Someone has called callout_drain to kill this
983 * callout. Don't reschedule.
985 CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
986 cancelled ? "cancelled" : "failed to cancel",
987 c, c->c_func, c->c_arg);
992 if (c->c_flags & CALLOUT_PENDING) {
993 if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
994 if (cc->cc_exec_next_dir == c)
995 cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
996 LIST_REMOVE(c, c_links.le);
998 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1000 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1005 * If the callout must migrate try to perform it immediately.
1006 * If the callout is currently running, just defer the migration
1007 * to a more appropriate moment.
1009 if (c->c_cpu != cpu) {
1010 if (cc->cc_exec_entity[direct].cc_curr == c) {
1011 cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
1012 cc->cc_exec_entity[direct].ce_migration_time
1014 cc->cc_exec_entity[direct].ce_migration_prec
1016 cc->cc_exec_entity[direct].ce_migration_func = ftn;
1017 cc->cc_exec_entity[direct].ce_migration_arg = arg;
1018 c->c_flags |= CALLOUT_DFRMIGRATION;
1020 "migration of %p func %p arg %p in %d.%08x to %u deferred",
1021 c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1022 (u_int)(to_sbt & 0xffffffff), cpu);
1026 cc = callout_cpu_switch(c, cc, cpu);
1030 callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1031 CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1032 cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1033 (u_int)(to_sbt & 0xffffffff));
1040 * Common idioms that can be optimized in the future.
1043 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1045 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1049 callout_schedule(struct callout *c, int to_ticks)
1051 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1055 _callout_stop_safe(c, safe)
1059 struct callout_cpu *cc, *old_cc;
1060 struct lock_class *class;
1061 int direct, sq_locked, use_lock;
1064 * Some old subsystems don't hold Giant while running a callout_stop(),
1065 * so just discard this check for the moment.
1067 if (!safe && c->c_lock != NULL) {
1068 if (c->c_lock == &Giant.lock_object)
1069 use_lock = mtx_owned(&Giant);
1072 class = LOCK_CLASS(c->c_lock);
1073 class->lc_assert(c->c_lock, LA_XLOCKED);
1077 direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1081 cc = callout_lock(c);
1084 * If the callout was migrating while the callout cpu lock was
1085 * dropped, just drop the sleepqueue lock and check the states
1088 if (sq_locked != 0 && cc != old_cc) {
1091 sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
1096 panic("migration should not happen");
1101 * If the callout isn't pending, it's not on the queue, so
1102 * don't attempt to remove it from the queue. We can try to
1103 * stop it by other means however.
1105 if (!(c->c_flags & CALLOUT_PENDING)) {
1106 c->c_flags &= ~CALLOUT_ACTIVE;
1109 * If it wasn't on the queue and it isn't the current
1110 * callout, then we can't stop it, so just bail.
1112 if (cc->cc_exec_entity[direct].cc_curr != c) {
1113 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1114 c, c->c_func, c->c_arg);
1118 &cc->cc_exec_entity[direct].cc_waiting);
1124 * The current callout is running (or just
1125 * about to run) and blocking is allowed, so
1126 * just wait for the current invocation to
1129 while (cc->cc_exec_entity[direct].cc_curr == c) {
1131 * Use direct calls to sleepqueue interface
1132 * instead of cv/msleep in order to avoid
1133 * a LOR between cc_lock and sleepqueue
1134 * chain spinlocks. This piece of code
1135 * emulates a msleep_spin() call actually.
1137 * If we already have the sleepqueue chain
1138 * locked, then we can safely block. If we
1139 * don't already have it locked, however,
1140 * we have to drop the cc_lock to lock
1141 * it. This opens several races, so we
1142 * restart at the beginning once we have
1143 * both locks. If nothing has changed, then
1144 * we will end up back here with sq_locked
1150 &cc->cc_exec_entity[direct].cc_waiting);
1157 * Migration could be cancelled here, but
1158 * as long as it is still not sure when it
1159 * will be packed up, just let softclock()
1162 cc->cc_exec_entity[direct].cc_waiting = true;
1166 &cc->cc_exec_entity[direct].cc_waiting,
1167 &cc->cc_lock.lock_object, "codrain",
1170 &cc->cc_exec_entity[direct].cc_waiting,
1175 /* Reacquire locks previously released. */
1179 } else if (use_lock &&
1180 !cc->cc_exec_entity[direct].cc_cancel) {
1182 * The current callout is waiting for its
1183 * lock which we hold. Cancel the callout
1184 * and return. After our caller drops the
1185 * lock, the callout will be skipped in
1188 cc->cc_exec_entity[direct].cc_cancel = true;
1189 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1190 c, c->c_func, c->c_arg);
1191 KASSERT(!cc_cce_migrating(cc, direct),
1192 ("callout wrongly scheduled for migration"));
1194 KASSERT(!sq_locked, ("sleepqueue chain locked"));
1196 } else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
1197 c->c_flags &= ~CALLOUT_DFRMIGRATION;
1198 CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1199 c, c->c_func, c->c_arg);
1203 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1204 c, c->c_func, c->c_arg);
1206 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1210 sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
1212 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1214 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1215 c, c->c_func, c->c_arg);
1216 if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1217 if (cc->cc_exec_next_dir == c)
1218 cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1219 LIST_REMOVE(c, c_links.le);
1221 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1222 callout_cc_del(c, cc);
1229 callout_init(c, mpsafe)
1233 bzero(c, sizeof *c);
1236 c->c_flags = CALLOUT_RETURNUNLOCKED;
1238 c->c_lock = &Giant.lock_object;
1241 c->c_cpu = timeout_cpu;
1245 _callout_init_lock(c, lock, flags)
1247 struct lock_object *lock;
1250 bzero(c, sizeof *c);
1252 KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1253 ("callout_init_lock: bad flags %d", flags));
1254 KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1255 ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1256 KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1257 (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1259 c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1260 c->c_cpu = timeout_cpu;
1263 #ifdef APM_FIXUP_CALLTODO
1265 * Adjust the kernel calltodo timeout list. This routine is used after
1266 * an APM resume to recalculate the calltodo timer list values with the
1267 * number of hz's we have been sleeping. The next hardclock() will detect
1268 * that there are fired timers and run softclock() to execute them.
1270 * Please note, I have not done an exhaustive analysis of what code this
1271 * might break. I am motivated to have my select()'s and alarm()'s that
1272 * have expired during suspend firing upon resume so that the applications
1273 * which set the timer can do the maintanence the timer was for as close
1274 * as possible to the originally intended time. Testing this code for a
1275 * week showed that resuming from a suspend resulted in 22 to 25 timers
1276 * firing, which seemed independant on whether the suspend was 2 hours or
1277 * 2 days. Your milage may vary. - Ken Key <key@cs.utk.edu>
1280 adjust_timeout_calltodo(time_change)
1281 struct timeval *time_change;
1283 register struct callout *p;
1284 unsigned long delta_ticks;
1287 * How many ticks were we asleep?
1288 * (stolen from tvtohz()).
1291 /* Don't do anything */
1292 if (time_change->tv_sec < 0)
1294 else if (time_change->tv_sec <= LONG_MAX / 1000000)
1295 delta_ticks = (time_change->tv_sec * 1000000 +
1296 time_change->tv_usec + (tick - 1)) / tick + 1;
1297 else if (time_change->tv_sec <= LONG_MAX / hz)
1298 delta_ticks = time_change->tv_sec * hz +
1299 (time_change->tv_usec + (tick - 1)) / tick + 1;
1301 delta_ticks = LONG_MAX;
1303 if (delta_ticks > INT_MAX)
1304 delta_ticks = INT_MAX;
1307 * Now rip through the timer calltodo list looking for timers
1311 /* don't collide with softclock() */
1313 for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1314 p->c_time -= delta_ticks;
1316 /* Break if the timer had more time on it than delta_ticks */
1320 /* take back the ticks the timer didn't use (p->c_time <= 0) */
1321 delta_ticks = -p->c_time;
1327 #endif /* APM_FIXUP_CALLTODO */
1330 flssbt(sbintime_t sbt)
1333 sbt += (uint64_t)sbt >> 1;
1334 if (sizeof(long) >= sizeof(sbintime_t))
1337 return (flsl(((uint64_t)sbt) >> 32) + 32);
1342 * Dump immediate statistic snapshot of the scheduled callouts.
1345 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1347 struct callout *tmp;
1348 struct callout_cpu *cc;
1349 struct callout_list *sc;
1350 sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1351 int ct[64], cpr[64], ccpbk[32];
1352 int error, val, i, count, tcum, pcum, maxc, c, medc;
1358 error = sysctl_handle_int(oidp, &val, 0, req);
1359 if (error != 0 || req->newptr == NULL)
1362 st = spr = maxt = maxpr = 0;
1363 bzero(ccpbk, sizeof(ccpbk));
1364 bzero(ct, sizeof(ct));
1365 bzero(cpr, sizeof(cpr));
1371 cc = CC_CPU(timeout_cpu);
1374 for (i = 0; i < callwheelsize; i++) {
1375 sc = &cc->cc_callwheel[i];
1377 LIST_FOREACH(tmp, sc, c_links.le) {
1379 t = tmp->c_time - now;
1383 spr += tmp->c_precision / SBT_1US;
1386 if (tmp->c_precision > maxpr)
1387 maxpr = tmp->c_precision;
1389 cpr[flssbt(tmp->c_precision)]++;
1393 ccpbk[fls(c + c / 2)]++;
1401 for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1403 medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1404 for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1406 medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1407 for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1409 medc = (i >= 2) ? (1 << (i - 2)) : 0;
1411 printf("Scheduled callouts statistic snapshot:\n");
1412 printf(" Callouts: %6d Buckets: %6d*%-3d Bucket size: 0.%06ds\n",
1413 count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1414 printf(" C/Bk: med %5d avg %6d.%06jd max %6d\n",
1416 count / callwheelsize / mp_ncpus,
1417 (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1419 printf(" Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1420 medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1421 (st / count) / 1000000, (st / count) % 1000000,
1422 maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1423 printf(" Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1424 medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1425 (spr / count) / 1000000, (spr / count) % 1000000,
1426 maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1427 printf(" Distribution: \tbuckets\t time\t tcum\t"
1429 for (i = 0, tcum = pcum = 0; i < 64; i++) {
1430 if (ct[i] == 0 && cpr[i] == 0)
1432 t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1435 printf(" %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1436 t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1437 i - 1 - (32 - CC_HASH_SHIFT),
1438 ct[i], tcum, cpr[i], pcum);
1442 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1443 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1444 0, 0, sysctl_kern_callout_stat, "I",
1445 "Dump immediate statistic snapshot of the scheduled callouts");