2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * From: @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include "opt_callout_profiling.h"
45 #include "opt_timer.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
52 #include <sys/callout.h>
53 #include <sys/domainset.h>
55 #include <sys/interrupt.h>
56 #include <sys/kernel.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
63 #include <sys/sleepqueue.h>
64 #include <sys/sysctl.h>
69 #include <ddb/db_sym.h>
70 #include <machine/_inttypes.h>
74 #include <machine/cpu.h>
77 #ifndef NO_EVENTTIMERS
78 DPCPU_DECLARE(sbintime_t, hardclocktime);
81 SDT_PROVIDER_DEFINE(callout_execute);
82 SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
83 SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
85 #ifdef CALLOUT_PROFILING
87 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
88 "Average number of items examined per softclock call. Units = 1/1000");
89 static int avg_gcalls;
90 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
91 "Average number of Giant callouts made per softclock call. Units = 1/1000");
92 static int avg_lockcalls;
93 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
94 "Average number of lock callouts made per softclock call. Units = 1/1000");
95 static int avg_mpcalls;
96 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
97 "Average number of MP callouts made per softclock call. Units = 1/1000");
98 static int avg_depth_dir;
99 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
100 "Average number of direct callouts examined per callout_process call. "
102 static int avg_lockcalls_dir;
103 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
104 &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
105 "callout_process call. Units = 1/1000");
106 static int avg_mpcalls_dir;
107 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
108 0, "Average number of MP direct callouts made per callout_process call. "
113 SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
114 "Number of entries in callwheel and size of timeout() preallocation");
117 static int pin_default_swi = 1;
118 static int pin_pcpu_swi = 1;
120 static int pin_default_swi = 0;
121 static int pin_pcpu_swi = 0;
124 SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
125 0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
126 SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
127 0, "Pin the per-CPU swis (except PCPU 0, which is also default");
131 * allocate more timeout table slots when table overflows.
133 u_int callwheelsize, callwheelmask;
136 * The callout cpu exec entities represent informations necessary for
137 * describing the state of callouts currently running on the CPU and the ones
138 * necessary for migrating callouts to the new callout cpu. In particular,
139 * the first entry of the array cc_exec_entity holds informations for callout
140 * running in SWI thread context, while the second one holds informations
141 * for callout running directly from hardware interrupt context.
142 * The cached informations are very important for deferring migration when
143 * the migrating callout is already running.
146 struct callout *cc_curr;
147 void (*cc_drain)(void *);
151 void (*ce_migration_func)(void *);
152 void *ce_migration_arg;
153 sbintime_t ce_migration_time;
154 sbintime_t ce_migration_prec;
155 int ce_migration_cpu;
162 * There is one struct callout_cpu per cpu, holding all relevant
163 * state for the callout processing thread on the individual CPU.
166 struct mtx_padalign cc_lock;
167 struct cc_exec cc_exec_entity[2];
168 struct callout *cc_next;
169 struct callout *cc_callout;
170 struct callout_list *cc_callwheel;
171 struct callout_tailq cc_expireq;
172 struct callout_slist cc_callfree;
173 sbintime_t cc_firstevent;
174 sbintime_t cc_lastscan;
178 char cc_ktr_event_name[20];
181 #define callout_migrating(c) ((c)->c_iflags & CALLOUT_DFRMIGRATION)
183 #define cc_exec_curr(cc, dir) cc->cc_exec_entity[dir].cc_curr
184 #define cc_exec_last_func(cc, dir) cc->cc_exec_entity[dir].cc_last_func
185 #define cc_exec_last_arg(cc, dir) cc->cc_exec_entity[dir].cc_last_arg
186 #define cc_exec_drain(cc, dir) cc->cc_exec_entity[dir].cc_drain
187 #define cc_exec_next(cc) cc->cc_next
188 #define cc_exec_cancel(cc, dir) cc->cc_exec_entity[dir].cc_cancel
189 #define cc_exec_waiting(cc, dir) cc->cc_exec_entity[dir].cc_waiting
191 #define cc_migration_func(cc, dir) cc->cc_exec_entity[dir].ce_migration_func
192 #define cc_migration_arg(cc, dir) cc->cc_exec_entity[dir].ce_migration_arg
193 #define cc_migration_cpu(cc, dir) cc->cc_exec_entity[dir].ce_migration_cpu
194 #define cc_migration_time(cc, dir) cc->cc_exec_entity[dir].ce_migration_time
195 #define cc_migration_prec(cc, dir) cc->cc_exec_entity[dir].ce_migration_prec
197 struct callout_cpu cc_cpu[MAXCPU];
198 #define CPUBLOCK MAXCPU
199 #define CC_CPU(cpu) (&cc_cpu[(cpu)])
200 #define CC_SELF() CC_CPU(PCPU_GET(cpuid))
202 struct callout_cpu cc_cpu;
203 #define CC_CPU(cpu) &cc_cpu
204 #define CC_SELF() &cc_cpu
206 #define CC_LOCK(cc) mtx_lock_spin(&(cc)->cc_lock)
207 #define CC_UNLOCK(cc) mtx_unlock_spin(&(cc)->cc_lock)
208 #define CC_LOCK_ASSERT(cc) mtx_assert(&(cc)->cc_lock, MA_OWNED)
210 static int timeout_cpu;
212 static void callout_cpu_init(struct callout_cpu *cc, int cpu);
213 static void softclock_call_cc(struct callout *c, struct callout_cpu *cc,
214 #ifdef CALLOUT_PROFILING
215 int *mpcalls, int *lockcalls, int *gcalls,
219 static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
223 * cc_curr - If a callout is in progress, it is cc_curr.
224 * If cc_curr is non-NULL, threads waiting in
225 * callout_drain() will be woken up as soon as the
226 * relevant callout completes.
227 * cc_cancel - Changing to 1 with both callout_lock and cc_lock held
228 * guarantees that the current callout will not run.
229 * The softclock() function sets this to 0 before it
230 * drops callout_lock to acquire c_lock, and it calls
231 * the handler only if curr_cancelled is still 0 after
232 * cc_lock is successfully acquired.
233 * cc_waiting - If a thread is waiting in callout_drain(), then
234 * callout_wait is nonzero. Set only when
235 * cc_curr is non-NULL.
239 * Resets the execution entity tied to a specific callout cpu.
242 cc_cce_cleanup(struct callout_cpu *cc, int direct)
245 cc_exec_curr(cc, direct) = NULL;
246 cc_exec_cancel(cc, direct) = false;
247 cc_exec_waiting(cc, direct) = false;
249 cc_migration_cpu(cc, direct) = CPUBLOCK;
250 cc_migration_time(cc, direct) = 0;
251 cc_migration_prec(cc, direct) = 0;
252 cc_migration_func(cc, direct) = NULL;
253 cc_migration_arg(cc, direct) = NULL;
258 * Checks if migration is requested by a specific callout cpu.
261 cc_cce_migrating(struct callout_cpu *cc, int direct)
265 return (cc_migration_cpu(cc, direct) != CPUBLOCK);
272 * Kernel low level callwheel initialization
273 * called on the BSP during kernel startup.
276 callout_callwheel_init(void *dummy)
278 struct callout_cpu *cc;
281 * Calculate the size of the callout wheel and the preallocated
282 * timeout() structures.
283 * XXX: Clip callout to result of previous function of maxusers
284 * maximum 384. This is still huge, but acceptable.
286 memset(CC_CPU(curcpu), 0, sizeof(cc_cpu));
287 ncallout = imin(16 + maxproc + maxfiles, 18508);
288 TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
291 * Calculate callout wheel size, should be next power of two higher
294 callwheelsize = 1 << fls(ncallout);
295 callwheelmask = callwheelsize - 1;
298 * Fetch whether we're pinning the swi's or not.
300 TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
301 TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
304 * Only BSP handles timeout(9) and receives a preallocation.
306 * XXX: Once all timeout(9) consumers are converted this can
309 timeout_cpu = PCPU_GET(cpuid);
310 cc = CC_CPU(timeout_cpu);
311 cc->cc_callout = malloc(ncallout * sizeof(struct callout),
312 M_CALLOUT, M_WAITOK);
313 callout_cpu_init(cc, timeout_cpu);
315 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
318 * Initialize the per-cpu callout structures.
321 callout_cpu_init(struct callout_cpu *cc, int cpu)
326 mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
327 SLIST_INIT(&cc->cc_callfree);
329 cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
330 callwheelsize, M_CALLOUT,
331 DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
332 for (i = 0; i < callwheelsize; i++)
333 LIST_INIT(&cc->cc_callwheel[i]);
334 TAILQ_INIT(&cc->cc_expireq);
335 cc->cc_firstevent = SBT_MAX;
336 for (i = 0; i < 2; i++)
337 cc_cce_cleanup(cc, i);
338 snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
339 "callwheel cpu %d", cpu);
340 if (cc->cc_callout == NULL) /* Only BSP handles timeout(9) */
342 for (i = 0; i < ncallout; i++) {
343 c = &cc->cc_callout[i];
345 c->c_iflags = CALLOUT_LOCAL_ALLOC;
346 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
352 * Switches the cpu tied to a specific callout.
353 * The function expects a locked incoming callout cpu and returns with
354 * locked outcoming callout cpu.
356 static struct callout_cpu *
357 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
359 struct callout_cpu *new_cc;
361 MPASS(c != NULL && cc != NULL);
365 * Avoid interrupts and preemption firing after the callout cpu
366 * is blocked in order to avoid deadlocks as the new thread
367 * may be willing to acquire the callout cpu lock.
372 new_cc = CC_CPU(new_cpu);
381 * Start standard softclock thread.
384 start_softclock(void *dummy)
386 struct callout_cpu *cc;
387 char name[MAXCOMLEN];
390 struct intr_event *ie;
393 cc = CC_CPU(timeout_cpu);
394 snprintf(name, sizeof(name), "clock (%d)", timeout_cpu);
395 if (swi_add(&clk_intr_event, name, softclock, cc, SWI_CLOCK,
396 INTR_MPSAFE, &cc->cc_cookie))
397 panic("died while creating standard software ithreads");
398 if (pin_default_swi &&
399 (intr_event_bind(clk_intr_event, timeout_cpu) != 0)) {
400 printf("%s: timeout clock couldn't be pinned to cpu %d\n",
407 if (cpu == timeout_cpu)
410 cc->cc_callout = NULL; /* Only BSP handles timeout(9). */
411 callout_cpu_init(cc, cpu);
412 snprintf(name, sizeof(name), "clock (%d)", cpu);
414 if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
415 INTR_MPSAFE, &cc->cc_cookie))
416 panic("died while creating standard software ithreads");
417 if (pin_pcpu_swi && (intr_event_bind(ie, cpu) != 0)) {
418 printf("%s: per-cpu clock couldn't be pinned to "
426 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
428 #define CC_HASH_SHIFT 8
431 callout_hash(sbintime_t sbt)
434 return (sbt >> (32 - CC_HASH_SHIFT));
438 callout_get_bucket(sbintime_t sbt)
441 return (callout_hash(sbt) & callwheelmask);
445 callout_process(sbintime_t now)
447 struct callout *tmp, *tmpn;
448 struct callout_cpu *cc;
449 struct callout_list *sc;
450 sbintime_t first, last, max, tmp_max;
452 u_int firstb, lastb, nowb;
453 #ifdef CALLOUT_PROFILING
454 int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
458 mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
460 /* Compute the buckets of the last scan and present times. */
461 firstb = callout_hash(cc->cc_lastscan);
462 cc->cc_lastscan = now;
463 nowb = callout_hash(now);
465 /* Compute the last bucket and minimum time of the bucket after it. */
467 lookahead = (SBT_1S / 16);
468 else if (nowb - firstb == 1)
469 lookahead = (SBT_1S / 8);
471 lookahead = (SBT_1S / 2);
473 first += (lookahead / 2);
475 last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
476 lastb = callout_hash(last) - 1;
480 * Check if we wrapped around the entire wheel from the last scan.
481 * In case, we need to scan entirely the wheel for pending callouts.
483 if (lastb - firstb >= callwheelsize) {
484 lastb = firstb + callwheelsize - 1;
485 if (nowb - firstb >= callwheelsize)
489 /* Iterate callwheel from firstb to nowb and then up to lastb. */
491 sc = &cc->cc_callwheel[firstb & callwheelmask];
492 tmp = LIST_FIRST(sc);
493 while (tmp != NULL) {
494 /* Run the callout if present time within allowed. */
495 if (tmp->c_time <= now) {
497 * Consumer told us the callout may be run
498 * directly from hardware interrupt context.
500 if (tmp->c_iflags & CALLOUT_DIRECT) {
501 #ifdef CALLOUT_PROFILING
505 LIST_NEXT(tmp, c_links.le);
506 cc->cc_bucket = firstb & callwheelmask;
507 LIST_REMOVE(tmp, c_links.le);
508 softclock_call_cc(tmp, cc,
509 #ifdef CALLOUT_PROFILING
510 &mpcalls_dir, &lockcalls_dir, NULL,
513 tmp = cc_exec_next(cc);
514 cc_exec_next(cc) = NULL;
516 tmpn = LIST_NEXT(tmp, c_links.le);
517 LIST_REMOVE(tmp, c_links.le);
518 TAILQ_INSERT_TAIL(&cc->cc_expireq,
520 tmp->c_iflags |= CALLOUT_PROCESSED;
525 /* Skip events from distant future. */
526 if (tmp->c_time >= max)
529 * Event minimal time is bigger than present maximal
530 * time, so it cannot be aggregated.
532 if (tmp->c_time > last) {
536 /* Update first and last time, respecting this event. */
537 if (tmp->c_time < first)
539 tmp_max = tmp->c_time + tmp->c_precision;
543 tmp = LIST_NEXT(tmp, c_links.le);
545 /* Proceed with the next bucket. */
548 * Stop if we looked after present time and found
549 * some event we can't execute at now.
550 * Stop if we looked far enough into the future.
552 } while (((int)(firstb - lastb)) <= 0);
553 cc->cc_firstevent = last;
554 #ifndef NO_EVENTTIMERS
555 cpu_new_callout(curcpu, last, first);
557 #ifdef CALLOUT_PROFILING
558 avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
559 avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
560 avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
562 mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
564 * swi_sched acquires the thread lock, so we don't want to call it
565 * with cc_lock held; incorrect locking order.
567 if (!TAILQ_EMPTY(&cc->cc_expireq))
568 swi_sched(cc->cc_cookie, 0);
571 static struct callout_cpu *
572 callout_lock(struct callout *c)
574 struct callout_cpu *cc;
580 if (cpu == CPUBLOCK) {
581 while (c->c_cpu == CPUBLOCK)
596 callout_cc_add(struct callout *c, struct callout_cpu *cc,
597 sbintime_t sbt, sbintime_t precision, void (*func)(void *),
598 void *arg, int cpu, int flags)
603 if (sbt < cc->cc_lastscan)
604 sbt = cc->cc_lastscan;
606 c->c_iflags |= CALLOUT_PENDING;
607 c->c_iflags &= ~CALLOUT_PROCESSED;
608 c->c_flags |= CALLOUT_ACTIVE;
609 if (flags & C_DIRECT_EXEC)
610 c->c_iflags |= CALLOUT_DIRECT;
613 c->c_precision = precision;
614 bucket = callout_get_bucket(c->c_time);
615 CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
616 c, (int)(c->c_precision >> 32),
617 (u_int)(c->c_precision & 0xffffffff));
618 LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
619 if (cc->cc_bucket == bucket)
620 cc_exec_next(cc) = c;
621 #ifndef NO_EVENTTIMERS
623 * Inform the eventtimers(4) subsystem there's a new callout
624 * that has been inserted, but only if really required.
626 if (SBT_MAX - c->c_time < c->c_precision)
627 c->c_precision = SBT_MAX - c->c_time;
628 sbt = c->c_time + c->c_precision;
629 if (sbt < cc->cc_firstevent) {
630 cc->cc_firstevent = sbt;
631 cpu_new_callout(cpu, sbt, c->c_time);
637 callout_cc_del(struct callout *c, struct callout_cpu *cc)
640 if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) == 0)
643 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
647 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
648 #ifdef CALLOUT_PROFILING
649 int *mpcalls, int *lockcalls, int *gcalls,
653 struct rm_priotracker tracker;
654 void (*c_func)(void *);
656 struct lock_class *class;
657 struct lock_object *c_lock;
658 uintptr_t lock_status;
661 struct callout_cpu *new_cc;
662 void (*new_func)(void *);
665 sbintime_t new_prec, new_time;
667 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
668 sbintime_t sbt1, sbt2;
670 static sbintime_t maxdt = 2 * SBT_1MS; /* 2 msec */
671 static timeout_t *lastfunc;
674 KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
675 ("softclock_call_cc: pend %p %x", c, c->c_iflags));
676 KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
677 ("softclock_call_cc: act %p %x", c, c->c_flags));
678 class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
680 if (c->c_flags & CALLOUT_SHAREDLOCK) {
681 if (class == &lock_class_rm)
682 lock_status = (uintptr_t)&tracker;
689 c_iflags = c->c_iflags;
690 if (c->c_iflags & CALLOUT_LOCAL_ALLOC)
691 c->c_iflags = CALLOUT_LOCAL_ALLOC;
693 c->c_iflags &= ~CALLOUT_PENDING;
695 cc_exec_curr(cc, direct) = c;
696 cc_exec_last_func(cc, direct) = c_func;
697 cc_exec_last_arg(cc, direct) = c_arg;
698 cc_exec_cancel(cc, direct) = false;
699 cc_exec_drain(cc, direct) = NULL;
701 if (c_lock != NULL) {
702 class->lc_lock(c_lock, lock_status);
704 * The callout may have been cancelled
705 * while we switched locks.
707 if (cc_exec_cancel(cc, direct)) {
708 class->lc_unlock(c_lock);
711 /* The callout cannot be stopped now. */
712 cc_exec_cancel(cc, direct) = true;
713 if (c_lock == &Giant.lock_object) {
714 #ifdef CALLOUT_PROFILING
717 CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
720 #ifdef CALLOUT_PROFILING
723 CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
727 #ifdef CALLOUT_PROFILING
730 CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
733 KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
734 "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
735 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
738 THREAD_NO_SLEEPING();
739 SDT_PROBE1(callout_execute, , , callout__start, c);
741 SDT_PROBE1(callout_execute, , , callout__end, c);
742 THREAD_SLEEPING_OK();
743 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
747 if (lastfunc != c_func || sbt2 > maxdt * 2) {
750 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
751 c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
757 KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
758 CTR1(KTR_CALLOUT, "callout %p finished", c);
759 if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
760 class->lc_unlock(c_lock);
763 KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
764 cc_exec_curr(cc, direct) = NULL;
765 if (cc_exec_drain(cc, direct)) {
766 void (*drain)(void *);
768 drain = cc_exec_drain(cc, direct);
769 cc_exec_drain(cc, direct) = NULL;
774 if (cc_exec_waiting(cc, direct)) {
776 * There is someone waiting for the
777 * callout to complete.
778 * If the callout was scheduled for
779 * migration just cancel it.
781 if (cc_cce_migrating(cc, direct)) {
782 cc_cce_cleanup(cc, direct);
785 * It should be assert here that the callout is not
786 * destroyed but that is not easy.
788 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
790 cc_exec_waiting(cc, direct) = false;
792 wakeup(&cc_exec_waiting(cc, direct));
794 } else if (cc_cce_migrating(cc, direct)) {
795 KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0,
796 ("Migrating legacy callout %p", c));
799 * If the callout was scheduled for
800 * migration just perform it now.
802 new_cpu = cc_migration_cpu(cc, direct);
803 new_time = cc_migration_time(cc, direct);
804 new_prec = cc_migration_prec(cc, direct);
805 new_func = cc_migration_func(cc, direct);
806 new_arg = cc_migration_arg(cc, direct);
807 cc_cce_cleanup(cc, direct);
810 * It should be assert here that the callout is not destroyed
811 * but that is not easy.
813 * As first thing, handle deferred callout stops.
815 if (!callout_migrating(c)) {
817 "deferred cancelled %p func %p arg %p",
818 c, new_func, new_arg);
819 callout_cc_del(c, cc);
822 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
824 new_cc = callout_cpu_switch(c, cc, new_cpu);
825 flags = (direct) ? C_DIRECT_EXEC : 0;
826 callout_cc_add(c, new_cc, new_time, new_prec, new_func,
827 new_arg, new_cpu, flags);
831 panic("migration should not happen");
835 * If the current callout is locally allocated (from
836 * timeout(9)) then put it on the freelist.
838 * Note: we need to check the cached copy of c_iflags because
839 * if it was not local, then it's not safe to deref the
842 KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0 ||
843 c->c_iflags == CALLOUT_LOCAL_ALLOC,
844 ("corrupted callout"));
845 if (c_iflags & CALLOUT_LOCAL_ALLOC)
846 callout_cc_del(c, cc);
850 * The callout mechanism is based on the work of Adam M. Costello and
851 * George Varghese, published in a technical report entitled "Redesigning
852 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
853 * in FreeBSD by Justin T. Gibbs. The original work on the data structures
854 * used in this implementation was published by G. Varghese and T. Lauck in
855 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
856 * the Efficient Implementation of a Timer Facility" in the Proceedings of
857 * the 11th ACM Annual Symposium on Operating Systems Principles,
858 * Austin, Texas Nov 1987.
862 * Software (low priority) clock interrupt.
863 * Run periodic events from timeout queue.
868 struct callout_cpu *cc;
870 #ifdef CALLOUT_PROFILING
871 int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
874 cc = (struct callout_cpu *)arg;
876 while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
877 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
878 softclock_call_cc(c, cc,
879 #ifdef CALLOUT_PROFILING
880 &mpcalls, &lockcalls, &gcalls,
883 #ifdef CALLOUT_PROFILING
887 #ifdef CALLOUT_PROFILING
888 avg_depth += (depth * 1000 - avg_depth) >> 8;
889 avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
890 avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
891 avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
898 * Execute a function after a specified length of time.
901 * Cancel previous timeout function call.
903 * callout_handle_init --
904 * Initialize a handle so that using it with untimeout is benign.
906 * See AT&T BCI Driver Reference Manual for specification. This
907 * implementation differs from that one in that although an
908 * identification value is returned from timeout, the original
909 * arguments to timeout as well as the identifier are used to
910 * identify entries for untimeout.
912 struct callout_handle
913 timeout(timeout_t *ftn, void *arg, int to_ticks)
915 struct callout_cpu *cc;
917 struct callout_handle handle;
919 cc = CC_CPU(timeout_cpu);
921 /* Fill in the next free callout structure. */
922 new = SLIST_FIRST(&cc->cc_callfree);
924 /* XXX Attempt to malloc first */
925 panic("timeout table full");
926 SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
927 callout_reset(new, to_ticks, ftn, arg);
928 handle.callout = new;
935 untimeout(timeout_t *ftn, void *arg, struct callout_handle handle)
937 struct callout_cpu *cc;
940 * Check for a handle that was initialized
941 * by callout_handle_init, but never used
942 * for a real timeout.
944 if (handle.callout == NULL)
947 cc = callout_lock(handle.callout);
948 if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
949 callout_stop(handle.callout);
954 callout_handle_init(struct callout_handle *handle)
956 handle->callout = NULL;
960 callout_when(sbintime_t sbt, sbintime_t precision, int flags,
961 sbintime_t *res, sbintime_t *prec_res)
963 sbintime_t to_sbt, to_pr;
965 if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
967 *prec_res = precision;
970 if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
972 if ((flags & C_HARDCLOCK) != 0 ||
973 #ifdef NO_EVENTTIMERS
974 sbt >= sbt_timethreshold) {
975 to_sbt = getsbinuptime();
977 /* Add safety belt for the case of hz > 1000. */
978 to_sbt += tc_tick_sbt - tick_sbt;
980 sbt >= sbt_tickthreshold) {
982 * Obtain the time of the last hardclock() call on
983 * this CPU directly from the kern_clocksource.c.
984 * This value is per-CPU, but it is equal for all
988 to_sbt = DPCPU_GET(hardclocktime);
991 to_sbt = DPCPU_GET(hardclocktime);
995 if (cold && to_sbt == 0)
996 to_sbt = sbinuptime();
997 if ((flags & C_HARDCLOCK) == 0)
1000 to_sbt = sbinuptime();
1001 if (SBT_MAX - to_sbt < sbt)
1006 to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
1007 sbt >> C_PRELGET(flags));
1008 *prec_res = to_pr > precision ? to_pr : precision;
1012 * New interface; clients allocate their own callout structures.
1014 * callout_reset() - establish or change a timeout
1015 * callout_stop() - disestablish a timeout
1016 * callout_init() - initialize a callout structure so that it can
1017 * safely be passed to callout_reset() and callout_stop()
1019 * <sys/callout.h> defines three convenience macros:
1021 * callout_active() - returns truth if callout has not been stopped,
1022 * drained, or deactivated since the last time the callout was
1024 * callout_pending() - returns truth if callout is still waiting for timeout
1025 * callout_deactivate() - marks the callout as having been serviced
1028 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
1029 void (*ftn)(void *), void *arg, int cpu, int flags)
1031 sbintime_t to_sbt, precision;
1032 struct callout_cpu *cc;
1033 int cancelled, direct;
1039 } else if ((cpu >= MAXCPU) ||
1040 ((CC_CPU(cpu))->cc_inited == 0)) {
1041 /* Invalid CPU spec */
1042 panic("Invalid CPU in callout %d", cpu);
1044 callout_when(sbt, prec, flags, &to_sbt, &precision);
1047 * This flag used to be added by callout_cc_add, but the
1048 * first time you call this we could end up with the
1049 * wrong direct flag if we don't do it before we add.
1051 if (flags & C_DIRECT_EXEC) {
1056 KASSERT(!direct || c->c_lock == NULL,
1057 ("%s: direct callout %p has lock", __func__, c));
1058 cc = callout_lock(c);
1060 * Don't allow migration of pre-allocated callouts lest they
1061 * become unbalanced or handle the case where the user does
1064 if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) ||
1069 if (cc_exec_curr(cc, direct) == c) {
1071 * We're being asked to reschedule a callout which is
1072 * currently in progress. If there is a lock then we
1073 * can cancel the callout if it has not really started.
1075 if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
1076 cancelled = cc_exec_cancel(cc, direct) = true;
1077 if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
1079 * Someone has called callout_drain to kill this
1080 * callout. Don't reschedule.
1082 CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1083 cancelled ? "cancelled" : "failed to cancel",
1084 c, c->c_func, c->c_arg);
1089 if (callout_migrating(c)) {
1091 * This only occurs when a second callout_reset_sbt_on
1092 * is made after a previous one moved it into
1093 * deferred migration (below). Note we do *not* change
1094 * the prev_cpu even though the previous target may
1097 cc_migration_cpu(cc, direct) = cpu;
1098 cc_migration_time(cc, direct) = to_sbt;
1099 cc_migration_prec(cc, direct) = precision;
1100 cc_migration_func(cc, direct) = ftn;
1101 cc_migration_arg(cc, direct) = arg;
1108 if (c->c_iflags & CALLOUT_PENDING) {
1109 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1110 if (cc_exec_next(cc) == c)
1111 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1112 LIST_REMOVE(c, c_links.le);
1114 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1117 c->c_iflags &= ~ CALLOUT_PENDING;
1118 c->c_flags &= ~ CALLOUT_ACTIVE;
1123 * If the callout must migrate try to perform it immediately.
1124 * If the callout is currently running, just defer the migration
1125 * to a more appropriate moment.
1127 if (c->c_cpu != cpu) {
1128 if (cc_exec_curr(cc, direct) == c) {
1130 * Pending will have been removed since we are
1131 * actually executing the callout on another
1132 * CPU. That callout should be waiting on the
1133 * lock the caller holds. If we set both
1134 * active/and/pending after we return and the
1135 * lock on the executing callout proceeds, it
1136 * will then see pending is true and return.
1137 * At the return from the actual callout execution
1138 * the migration will occur in softclock_call_cc
1139 * and this new callout will be placed on the
1140 * new CPU via a call to callout_cpu_switch() which
1141 * will get the lock on the right CPU followed
1142 * by a call callout_cc_add() which will add it there.
1143 * (see above in softclock_call_cc()).
1145 cc_migration_cpu(cc, direct) = cpu;
1146 cc_migration_time(cc, direct) = to_sbt;
1147 cc_migration_prec(cc, direct) = precision;
1148 cc_migration_func(cc, direct) = ftn;
1149 cc_migration_arg(cc, direct) = arg;
1150 c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
1151 c->c_flags |= CALLOUT_ACTIVE;
1153 "migration of %p func %p arg %p in %d.%08x to %u deferred",
1154 c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1155 (u_int)(to_sbt & 0xffffffff), cpu);
1159 cc = callout_cpu_switch(c, cc, cpu);
1163 callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1164 CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1165 cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1166 (u_int)(to_sbt & 0xffffffff));
1173 * Common idioms that can be optimized in the future.
1176 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1178 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1182 callout_schedule(struct callout *c, int to_ticks)
1184 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1188 _callout_stop_safe(struct callout *c, int flags, void (*drain)(void *))
1190 struct callout_cpu *cc, *old_cc;
1191 struct lock_class *class;
1192 int direct, sq_locked, use_lock;
1193 int cancelled, not_on_a_list;
1195 if ((flags & CS_DRAIN) != 0)
1196 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
1197 "calling %s", __func__);
1200 * Some old subsystems don't hold Giant while running a callout_stop(),
1201 * so just discard this check for the moment.
1203 if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1204 if (c->c_lock == &Giant.lock_object)
1205 use_lock = mtx_owned(&Giant);
1208 class = LOCK_CLASS(c->c_lock);
1209 class->lc_assert(c->c_lock, LA_XLOCKED);
1213 if (c->c_iflags & CALLOUT_DIRECT) {
1221 cc = callout_lock(c);
1223 if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
1224 (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
1225 ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1227 * Special case where this slipped in while we
1228 * were migrating *as* the callout is about to
1229 * execute. The caller probably holds the lock
1230 * the callout wants.
1232 * Get rid of the migration first. Then set
1233 * the flag that tells this code *not* to
1234 * try to remove it from any lists (its not
1235 * on one yet). When the callout wheel runs,
1236 * it will ignore this callout.
1238 c->c_iflags &= ~CALLOUT_PENDING;
1239 c->c_flags &= ~CALLOUT_ACTIVE;
1246 * If the callout was migrating while the callout cpu lock was
1247 * dropped, just drop the sleepqueue lock and check the states
1250 if (sq_locked != 0 && cc != old_cc) {
1253 sleepq_release(&cc_exec_waiting(old_cc, direct));
1258 panic("migration should not happen");
1263 * If the callout is running, try to stop it or drain it.
1265 if (cc_exec_curr(cc, direct) == c) {
1267 * Succeed we to stop it or not, we must clear the
1268 * active flag - this is what API users expect. If we're
1269 * draining and the callout is currently executing, first wait
1270 * until it finishes.
1272 if ((flags & CS_DRAIN) == 0)
1273 c->c_flags &= ~CALLOUT_ACTIVE;
1275 if ((flags & CS_DRAIN) != 0) {
1277 * The current callout is running (or just
1278 * about to run) and blocking is allowed, so
1279 * just wait for the current invocation to
1282 while (cc_exec_curr(cc, direct) == c) {
1284 * Use direct calls to sleepqueue interface
1285 * instead of cv/msleep in order to avoid
1286 * a LOR between cc_lock and sleepqueue
1287 * chain spinlocks. This piece of code
1288 * emulates a msleep_spin() call actually.
1290 * If we already have the sleepqueue chain
1291 * locked, then we can safely block. If we
1292 * don't already have it locked, however,
1293 * we have to drop the cc_lock to lock
1294 * it. This opens several races, so we
1295 * restart at the beginning once we have
1296 * both locks. If nothing has changed, then
1297 * we will end up back here with sq_locked
1303 &cc_exec_waiting(cc, direct));
1310 * Migration could be cancelled here, but
1311 * as long as it is still not sure when it
1312 * will be packed up, just let softclock()
1315 cc_exec_waiting(cc, direct) = true;
1319 &cc_exec_waiting(cc, direct),
1320 &cc->cc_lock.lock_object, "codrain",
1323 &cc_exec_waiting(cc, direct),
1328 /* Reacquire locks previously released. */
1332 c->c_flags &= ~CALLOUT_ACTIVE;
1333 } else if (use_lock &&
1334 !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1337 * The current callout is waiting for its
1338 * lock which we hold. Cancel the callout
1339 * and return. After our caller drops the
1340 * lock, the callout will be skipped in
1341 * softclock(). This *only* works with a
1342 * callout_stop() *not* callout_drain() or
1343 * callout_async_drain().
1345 cc_exec_cancel(cc, direct) = true;
1346 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1347 c, c->c_func, c->c_arg);
1348 KASSERT(!cc_cce_migrating(cc, direct),
1349 ("callout wrongly scheduled for migration"));
1350 if (callout_migrating(c)) {
1351 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1353 cc_migration_cpu(cc, direct) = CPUBLOCK;
1354 cc_migration_time(cc, direct) = 0;
1355 cc_migration_prec(cc, direct) = 0;
1356 cc_migration_func(cc, direct) = NULL;
1357 cc_migration_arg(cc, direct) = NULL;
1361 KASSERT(!sq_locked, ("sleepqueue chain locked"));
1363 } else if (callout_migrating(c)) {
1365 * The callout is currently being serviced
1366 * and the "next" callout is scheduled at
1367 * its completion with a migration. We remove
1368 * the migration flag so it *won't* get rescheduled,
1369 * but we can't stop the one thats running so
1372 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1375 * We can't call cc_cce_cleanup here since
1376 * if we do it will remove .ce_curr and
1377 * its still running. This will prevent a
1378 * reschedule of the callout when the
1379 * execution completes.
1381 cc_migration_cpu(cc, direct) = CPUBLOCK;
1382 cc_migration_time(cc, direct) = 0;
1383 cc_migration_prec(cc, direct) = 0;
1384 cc_migration_func(cc, direct) = NULL;
1385 cc_migration_arg(cc, direct) = NULL;
1387 CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1388 c, c->c_func, c->c_arg);
1390 cc_exec_drain(cc, direct) = drain;
1393 return ((flags & CS_EXECUTING) != 0);
1395 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1396 c, c->c_func, c->c_arg);
1398 cc_exec_drain(cc, direct) = drain;
1400 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1401 cancelled = ((flags & CS_EXECUTING) != 0);
1406 sleepq_release(&cc_exec_waiting(cc, direct));
1408 if ((c->c_iflags & CALLOUT_PENDING) == 0) {
1409 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1410 c, c->c_func, c->c_arg);
1412 * For not scheduled and not executing callout return
1415 if (cc_exec_curr(cc, direct) != c)
1421 c->c_iflags &= ~CALLOUT_PENDING;
1422 c->c_flags &= ~CALLOUT_ACTIVE;
1424 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1425 c, c->c_func, c->c_arg);
1426 if (not_on_a_list == 0) {
1427 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1428 if (cc_exec_next(cc) == c)
1429 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1430 LIST_REMOVE(c, c_links.le);
1432 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1435 callout_cc_del(c, cc);
1441 callout_init(struct callout *c, int mpsafe)
1443 bzero(c, sizeof *c);
1446 c->c_iflags = CALLOUT_RETURNUNLOCKED;
1448 c->c_lock = &Giant.lock_object;
1451 c->c_cpu = timeout_cpu;
1455 _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
1457 bzero(c, sizeof *c);
1459 KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1460 ("callout_init_lock: bad flags %d", flags));
1461 KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1462 ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1463 KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1464 (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1466 c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1467 c->c_cpu = timeout_cpu;
1470 #ifdef APM_FIXUP_CALLTODO
1472 * Adjust the kernel calltodo timeout list. This routine is used after
1473 * an APM resume to recalculate the calltodo timer list values with the
1474 * number of hz's we have been sleeping. The next hardclock() will detect
1475 * that there are fired timers and run softclock() to execute them.
1477 * Please note, I have not done an exhaustive analysis of what code this
1478 * might break. I am motivated to have my select()'s and alarm()'s that
1479 * have expired during suspend firing upon resume so that the applications
1480 * which set the timer can do the maintanence the timer was for as close
1481 * as possible to the originally intended time. Testing this code for a
1482 * week showed that resuming from a suspend resulted in 22 to 25 timers
1483 * firing, which seemed independent on whether the suspend was 2 hours or
1484 * 2 days. Your milage may vary. - Ken Key <key@cs.utk.edu>
1487 adjust_timeout_calltodo(struct timeval *time_change)
1490 unsigned long delta_ticks;
1493 * How many ticks were we asleep?
1494 * (stolen from tvtohz()).
1497 /* Don't do anything */
1498 if (time_change->tv_sec < 0)
1500 else if (time_change->tv_sec <= LONG_MAX / 1000000)
1501 delta_ticks = howmany(time_change->tv_sec * 1000000 +
1502 time_change->tv_usec, tick) + 1;
1503 else if (time_change->tv_sec <= LONG_MAX / hz)
1504 delta_ticks = time_change->tv_sec * hz +
1505 howmany(time_change->tv_usec, tick) + 1;
1507 delta_ticks = LONG_MAX;
1509 if (delta_ticks > INT_MAX)
1510 delta_ticks = INT_MAX;
1513 * Now rip through the timer calltodo list looking for timers
1517 /* don't collide with softclock() */
1519 for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1520 p->c_time -= delta_ticks;
1522 /* Break if the timer had more time on it than delta_ticks */
1526 /* take back the ticks the timer didn't use (p->c_time <= 0) */
1527 delta_ticks = -p->c_time;
1533 #endif /* APM_FIXUP_CALLTODO */
1536 flssbt(sbintime_t sbt)
1539 sbt += (uint64_t)sbt >> 1;
1540 if (sizeof(long) >= sizeof(sbintime_t))
1543 return (flsl(((uint64_t)sbt) >> 32) + 32);
1548 * Dump immediate statistic snapshot of the scheduled callouts.
1551 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1553 struct callout *tmp;
1554 struct callout_cpu *cc;
1555 struct callout_list *sc;
1556 sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1557 int ct[64], cpr[64], ccpbk[32];
1558 int error, val, i, count, tcum, pcum, maxc, c, medc;
1564 error = sysctl_handle_int(oidp, &val, 0, req);
1565 if (error != 0 || req->newptr == NULL)
1568 st = spr = maxt = maxpr = 0;
1569 bzero(ccpbk, sizeof(ccpbk));
1570 bzero(ct, sizeof(ct));
1571 bzero(cpr, sizeof(cpr));
1577 cc = CC_CPU(timeout_cpu);
1580 for (i = 0; i < callwheelsize; i++) {
1581 sc = &cc->cc_callwheel[i];
1583 LIST_FOREACH(tmp, sc, c_links.le) {
1585 t = tmp->c_time - now;
1589 spr += tmp->c_precision / SBT_1US;
1592 if (tmp->c_precision > maxpr)
1593 maxpr = tmp->c_precision;
1595 cpr[flssbt(tmp->c_precision)]++;
1599 ccpbk[fls(c + c / 2)]++;
1607 for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1609 medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1610 for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1612 medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1613 for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1615 medc = (i >= 2) ? (1 << (i - 2)) : 0;
1617 printf("Scheduled callouts statistic snapshot:\n");
1618 printf(" Callouts: %6d Buckets: %6d*%-3d Bucket size: 0.%06ds\n",
1619 count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1620 printf(" C/Bk: med %5d avg %6d.%06jd max %6d\n",
1622 count / callwheelsize / mp_ncpus,
1623 (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1625 printf(" Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1626 medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1627 (st / count) / 1000000, (st / count) % 1000000,
1628 maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1629 printf(" Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1630 medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1631 (spr / count) / 1000000, (spr / count) % 1000000,
1632 maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1633 printf(" Distribution: \tbuckets\t time\t tcum\t"
1635 for (i = 0, tcum = pcum = 0; i < 64; i++) {
1636 if (ct[i] == 0 && cpr[i] == 0)
1638 t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1641 printf(" %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1642 t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1643 i - 1 - (32 - CC_HASH_SHIFT),
1644 ct[i], tcum, cpr[i], pcum);
1648 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1649 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1650 0, 0, sysctl_kern_callout_stat, "I",
1651 "Dump immediate statistic snapshot of the scheduled callouts");
1655 _show_callout(struct callout *c)
1658 db_printf("callout %p\n", c);
1659 #define C_DB_PRINTF(f, e) db_printf(" %s = " f "\n", #e, c->e);
1660 db_printf(" &c_links = %p\n", &(c->c_links));
1661 C_DB_PRINTF("%" PRId64, c_time);
1662 C_DB_PRINTF("%" PRId64, c_precision);
1663 C_DB_PRINTF("%p", c_arg);
1664 C_DB_PRINTF("%p", c_func);
1665 C_DB_PRINTF("%p", c_lock);
1666 C_DB_PRINTF("%#x", c_flags);
1667 C_DB_PRINTF("%#x", c_iflags);
1668 C_DB_PRINTF("%d", c_cpu);
1672 DB_SHOW_COMMAND(callout, db_show_callout)
1676 db_printf("usage: show callout <struct callout *>\n");
1680 _show_callout((struct callout *)addr);
1684 _show_last_callout(int cpu, int direct, const char *dirstr)
1686 struct callout_cpu *cc;
1690 func = cc_exec_last_func(cc, direct);
1691 arg = cc_exec_last_arg(cc, direct);
1692 db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
1693 db_printsym((db_expr_t)func, DB_STGY_ANY);
1694 db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
1697 DB_SHOW_COMMAND(callout_last, db_show_callout_last)
1702 if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
1703 db_printf("no such cpu: %d\n", (int)addr);
1712 while (cpu <= last) {
1713 if (!CPU_ABSENT(cpu)) {
1714 _show_last_callout(cpu, 0, "");
1715 _show_last_callout(cpu, 1, " direct");