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;
179 char cc_ktr_event_name[20];
183 #define callout_migrating(c) ((c)->c_iflags & CALLOUT_DFRMIGRATION)
185 #define cc_exec_curr(cc, dir) cc->cc_exec_entity[dir].cc_curr
186 #define cc_exec_last_func(cc, dir) cc->cc_exec_entity[dir].cc_last_func
187 #define cc_exec_last_arg(cc, dir) cc->cc_exec_entity[dir].cc_last_arg
188 #define cc_exec_drain(cc, dir) cc->cc_exec_entity[dir].cc_drain
189 #define cc_exec_next(cc) cc->cc_next
190 #define cc_exec_cancel(cc, dir) cc->cc_exec_entity[dir].cc_cancel
191 #define cc_exec_waiting(cc, dir) cc->cc_exec_entity[dir].cc_waiting
193 #define cc_migration_func(cc, dir) cc->cc_exec_entity[dir].ce_migration_func
194 #define cc_migration_arg(cc, dir) cc->cc_exec_entity[dir].ce_migration_arg
195 #define cc_migration_cpu(cc, dir) cc->cc_exec_entity[dir].ce_migration_cpu
196 #define cc_migration_time(cc, dir) cc->cc_exec_entity[dir].ce_migration_time
197 #define cc_migration_prec(cc, dir) cc->cc_exec_entity[dir].ce_migration_prec
199 struct callout_cpu cc_cpu[MAXCPU];
200 #define CPUBLOCK MAXCPU
201 #define CC_CPU(cpu) (&cc_cpu[(cpu)])
202 #define CC_SELF() CC_CPU(PCPU_GET(cpuid))
204 struct callout_cpu cc_cpu;
205 #define CC_CPU(cpu) &cc_cpu
206 #define CC_SELF() &cc_cpu
208 #define CC_LOCK(cc) mtx_lock_spin(&(cc)->cc_lock)
209 #define CC_UNLOCK(cc) mtx_unlock_spin(&(cc)->cc_lock)
210 #define CC_LOCK_ASSERT(cc) mtx_assert(&(cc)->cc_lock, MA_OWNED)
212 static int timeout_cpu;
214 static void callout_cpu_init(struct callout_cpu *cc, int cpu);
215 static void softclock_call_cc(struct callout *c, struct callout_cpu *cc,
216 #ifdef CALLOUT_PROFILING
217 int *mpcalls, int *lockcalls, int *gcalls,
221 static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
225 * cc_curr - If a callout is in progress, it is cc_curr.
226 * If cc_curr is non-NULL, threads waiting in
227 * callout_drain() will be woken up as soon as the
228 * relevant callout completes.
229 * cc_cancel - Changing to 1 with both callout_lock and cc_lock held
230 * guarantees that the current callout will not run.
231 * The softclock() function sets this to 0 before it
232 * drops callout_lock to acquire c_lock, and it calls
233 * the handler only if curr_cancelled is still 0 after
234 * cc_lock is successfully acquired.
235 * cc_waiting - If a thread is waiting in callout_drain(), then
236 * callout_wait is nonzero. Set only when
237 * cc_curr is non-NULL.
241 * Resets the execution entity tied to a specific callout cpu.
244 cc_cce_cleanup(struct callout_cpu *cc, int direct)
247 cc_exec_curr(cc, direct) = NULL;
248 cc_exec_cancel(cc, direct) = false;
249 cc_exec_waiting(cc, direct) = false;
251 cc_migration_cpu(cc, direct) = CPUBLOCK;
252 cc_migration_time(cc, direct) = 0;
253 cc_migration_prec(cc, direct) = 0;
254 cc_migration_func(cc, direct) = NULL;
255 cc_migration_arg(cc, direct) = NULL;
260 * Checks if migration is requested by a specific callout cpu.
263 cc_cce_migrating(struct callout_cpu *cc, int direct)
267 return (cc_migration_cpu(cc, direct) != CPUBLOCK);
274 * Kernel low level callwheel initialization
275 * called on the BSP during kernel startup.
278 callout_callwheel_init(void *dummy)
280 struct callout_cpu *cc;
283 * Calculate the size of the callout wheel and the preallocated
284 * timeout() structures.
285 * XXX: Clip callout to result of previous function of maxusers
286 * maximum 384. This is still huge, but acceptable.
288 memset(CC_CPU(curcpu), 0, sizeof(cc_cpu));
289 ncallout = imin(16 + maxproc + maxfiles, 18508);
290 TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
293 * Calculate callout wheel size, should be next power of two higher
296 callwheelsize = 1 << fls(ncallout);
297 callwheelmask = callwheelsize - 1;
300 * Fetch whether we're pinning the swi's or not.
302 TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
303 TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
306 * Only BSP handles timeout(9) and receives a preallocation.
308 * XXX: Once all timeout(9) consumers are converted this can
311 timeout_cpu = PCPU_GET(cpuid);
312 cc = CC_CPU(timeout_cpu);
313 cc->cc_callout = malloc(ncallout * sizeof(struct callout),
314 M_CALLOUT, M_WAITOK);
315 callout_cpu_init(cc, timeout_cpu);
317 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
320 * Initialize the per-cpu callout structures.
323 callout_cpu_init(struct callout_cpu *cc, int cpu)
328 mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
329 SLIST_INIT(&cc->cc_callfree);
331 cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
332 callwheelsize, M_CALLOUT,
333 DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
334 for (i = 0; i < callwheelsize; i++)
335 LIST_INIT(&cc->cc_callwheel[i]);
336 TAILQ_INIT(&cc->cc_expireq);
337 cc->cc_firstevent = SBT_MAX;
338 for (i = 0; i < 2; i++)
339 cc_cce_cleanup(cc, i);
341 snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
342 "callwheel cpu %d", cpu);
344 if (cc->cc_callout == NULL) /* Only BSP handles timeout(9) */
346 for (i = 0; i < ncallout; i++) {
347 c = &cc->cc_callout[i];
349 c->c_iflags = CALLOUT_LOCAL_ALLOC;
350 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
356 * Switches the cpu tied to a specific callout.
357 * The function expects a locked incoming callout cpu and returns with
358 * locked outcoming callout cpu.
360 static struct callout_cpu *
361 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
363 struct callout_cpu *new_cc;
365 MPASS(c != NULL && cc != NULL);
369 * Avoid interrupts and preemption firing after the callout cpu
370 * is blocked in order to avoid deadlocks as the new thread
371 * may be willing to acquire the callout cpu lock.
376 new_cc = CC_CPU(new_cpu);
385 * Start standard softclock thread.
388 start_softclock(void *dummy)
390 struct callout_cpu *cc;
391 char name[MAXCOMLEN];
394 struct intr_event *ie;
397 cc = CC_CPU(timeout_cpu);
398 snprintf(name, sizeof(name), "clock (%d)", timeout_cpu);
399 if (swi_add(&clk_intr_event, name, softclock, cc, SWI_CLOCK,
400 INTR_MPSAFE, &cc->cc_cookie))
401 panic("died while creating standard software ithreads");
402 if (pin_default_swi &&
403 (intr_event_bind(clk_intr_event, timeout_cpu) != 0)) {
404 printf("%s: timeout clock couldn't be pinned to cpu %d\n",
411 if (cpu == timeout_cpu)
414 cc->cc_callout = NULL; /* Only BSP handles timeout(9). */
415 callout_cpu_init(cc, cpu);
416 snprintf(name, sizeof(name), "clock (%d)", cpu);
418 if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
419 INTR_MPSAFE, &cc->cc_cookie))
420 panic("died while creating standard software ithreads");
421 if (pin_pcpu_swi && (intr_event_bind(ie, cpu) != 0)) {
422 printf("%s: per-cpu clock couldn't be pinned to "
430 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
432 #define CC_HASH_SHIFT 8
435 callout_hash(sbintime_t sbt)
438 return (sbt >> (32 - CC_HASH_SHIFT));
442 callout_get_bucket(sbintime_t sbt)
445 return (callout_hash(sbt) & callwheelmask);
449 callout_process(sbintime_t now)
451 struct callout *tmp, *tmpn;
452 struct callout_cpu *cc;
453 struct callout_list *sc;
454 sbintime_t first, last, max, tmp_max;
456 u_int firstb, lastb, nowb;
457 #ifdef CALLOUT_PROFILING
458 int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
462 mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
464 /* Compute the buckets of the last scan and present times. */
465 firstb = callout_hash(cc->cc_lastscan);
466 cc->cc_lastscan = now;
467 nowb = callout_hash(now);
469 /* Compute the last bucket and minimum time of the bucket after it. */
471 lookahead = (SBT_1S / 16);
472 else if (nowb - firstb == 1)
473 lookahead = (SBT_1S / 8);
475 lookahead = (SBT_1S / 2);
477 first += (lookahead / 2);
479 last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
480 lastb = callout_hash(last) - 1;
484 * Check if we wrapped around the entire wheel from the last scan.
485 * In case, we need to scan entirely the wheel for pending callouts.
487 if (lastb - firstb >= callwheelsize) {
488 lastb = firstb + callwheelsize - 1;
489 if (nowb - firstb >= callwheelsize)
493 /* Iterate callwheel from firstb to nowb and then up to lastb. */
495 sc = &cc->cc_callwheel[firstb & callwheelmask];
496 tmp = LIST_FIRST(sc);
497 while (tmp != NULL) {
498 /* Run the callout if present time within allowed. */
499 if (tmp->c_time <= now) {
501 * Consumer told us the callout may be run
502 * directly from hardware interrupt context.
504 if (tmp->c_iflags & CALLOUT_DIRECT) {
505 #ifdef CALLOUT_PROFILING
509 LIST_NEXT(tmp, c_links.le);
510 cc->cc_bucket = firstb & callwheelmask;
511 LIST_REMOVE(tmp, c_links.le);
512 softclock_call_cc(tmp, cc,
513 #ifdef CALLOUT_PROFILING
514 &mpcalls_dir, &lockcalls_dir, NULL,
517 tmp = cc_exec_next(cc);
518 cc_exec_next(cc) = NULL;
520 tmpn = LIST_NEXT(tmp, c_links.le);
521 LIST_REMOVE(tmp, c_links.le);
522 TAILQ_INSERT_TAIL(&cc->cc_expireq,
524 tmp->c_iflags |= CALLOUT_PROCESSED;
529 /* Skip events from distant future. */
530 if (tmp->c_time >= max)
533 * Event minimal time is bigger than present maximal
534 * time, so it cannot be aggregated.
536 if (tmp->c_time > last) {
540 /* Update first and last time, respecting this event. */
541 if (tmp->c_time < first)
543 tmp_max = tmp->c_time + tmp->c_precision;
547 tmp = LIST_NEXT(tmp, c_links.le);
549 /* Proceed with the next bucket. */
552 * Stop if we looked after present time and found
553 * some event we can't execute at now.
554 * Stop if we looked far enough into the future.
556 } while (((int)(firstb - lastb)) <= 0);
557 cc->cc_firstevent = last;
558 #ifndef NO_EVENTTIMERS
559 cpu_new_callout(curcpu, last, first);
561 #ifdef CALLOUT_PROFILING
562 avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
563 avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
564 avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
566 mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
568 * swi_sched acquires the thread lock, so we don't want to call it
569 * with cc_lock held; incorrect locking order.
571 if (!TAILQ_EMPTY(&cc->cc_expireq))
572 swi_sched(cc->cc_cookie, 0);
575 static struct callout_cpu *
576 callout_lock(struct callout *c)
578 struct callout_cpu *cc;
584 if (cpu == CPUBLOCK) {
585 while (c->c_cpu == CPUBLOCK)
600 callout_cc_add(struct callout *c, struct callout_cpu *cc,
601 sbintime_t sbt, sbintime_t precision, void (*func)(void *),
602 void *arg, int cpu, int flags)
607 if (sbt < cc->cc_lastscan)
608 sbt = cc->cc_lastscan;
610 c->c_iflags |= CALLOUT_PENDING;
611 c->c_iflags &= ~CALLOUT_PROCESSED;
612 c->c_flags |= CALLOUT_ACTIVE;
613 if (flags & C_DIRECT_EXEC)
614 c->c_iflags |= CALLOUT_DIRECT;
617 c->c_precision = precision;
618 bucket = callout_get_bucket(c->c_time);
619 CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
620 c, (int)(c->c_precision >> 32),
621 (u_int)(c->c_precision & 0xffffffff));
622 LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
623 if (cc->cc_bucket == bucket)
624 cc_exec_next(cc) = c;
625 #ifndef NO_EVENTTIMERS
627 * Inform the eventtimers(4) subsystem there's a new callout
628 * that has been inserted, but only if really required.
630 if (SBT_MAX - c->c_time < c->c_precision)
631 c->c_precision = SBT_MAX - c->c_time;
632 sbt = c->c_time + c->c_precision;
633 if (sbt < cc->cc_firstevent) {
634 cc->cc_firstevent = sbt;
635 cpu_new_callout(cpu, sbt, c->c_time);
641 callout_cc_del(struct callout *c, struct callout_cpu *cc)
644 if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) == 0)
647 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
651 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
652 #ifdef CALLOUT_PROFILING
653 int *mpcalls, int *lockcalls, int *gcalls,
657 struct rm_priotracker tracker;
658 void (*c_func)(void *);
660 struct lock_class *class;
661 struct lock_object *c_lock;
662 uintptr_t lock_status;
665 struct callout_cpu *new_cc;
666 void (*new_func)(void *);
669 sbintime_t new_prec, new_time;
671 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
672 sbintime_t sbt1, sbt2;
674 static sbintime_t maxdt = 2 * SBT_1MS; /* 2 msec */
675 static timeout_t *lastfunc;
678 KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
679 ("softclock_call_cc: pend %p %x", c, c->c_iflags));
680 KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
681 ("softclock_call_cc: act %p %x", c, c->c_flags));
682 class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
684 if (c->c_flags & CALLOUT_SHAREDLOCK) {
685 if (class == &lock_class_rm)
686 lock_status = (uintptr_t)&tracker;
693 c_iflags = c->c_iflags;
694 if (c->c_iflags & CALLOUT_LOCAL_ALLOC)
695 c->c_iflags = CALLOUT_LOCAL_ALLOC;
697 c->c_iflags &= ~CALLOUT_PENDING;
699 cc_exec_curr(cc, direct) = c;
700 cc_exec_last_func(cc, direct) = c_func;
701 cc_exec_last_arg(cc, direct) = c_arg;
702 cc_exec_cancel(cc, direct) = false;
703 cc_exec_drain(cc, direct) = NULL;
705 if (c_lock != NULL) {
706 class->lc_lock(c_lock, lock_status);
708 * The callout may have been cancelled
709 * while we switched locks.
711 if (cc_exec_cancel(cc, direct)) {
712 class->lc_unlock(c_lock);
715 /* The callout cannot be stopped now. */
716 cc_exec_cancel(cc, direct) = true;
717 if (c_lock == &Giant.lock_object) {
718 #ifdef CALLOUT_PROFILING
721 CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
724 #ifdef CALLOUT_PROFILING
727 CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
731 #ifdef CALLOUT_PROFILING
734 CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
737 KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
738 "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
739 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
742 THREAD_NO_SLEEPING();
743 SDT_PROBE1(callout_execute, , , callout__start, c);
745 SDT_PROBE1(callout_execute, , , callout__end, c);
746 THREAD_SLEEPING_OK();
747 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
751 if (lastfunc != c_func || sbt2 > maxdt * 2) {
754 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
755 c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
761 KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
762 CTR1(KTR_CALLOUT, "callout %p finished", c);
763 if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
764 class->lc_unlock(c_lock);
767 KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
768 cc_exec_curr(cc, direct) = NULL;
769 if (cc_exec_drain(cc, direct)) {
770 void (*drain)(void *);
772 drain = cc_exec_drain(cc, direct);
773 cc_exec_drain(cc, direct) = NULL;
778 if (cc_exec_waiting(cc, direct)) {
780 * There is someone waiting for the
781 * callout to complete.
782 * If the callout was scheduled for
783 * migration just cancel it.
785 if (cc_cce_migrating(cc, direct)) {
786 cc_cce_cleanup(cc, direct);
789 * It should be assert here that the callout is not
790 * destroyed but that is not easy.
792 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
794 cc_exec_waiting(cc, direct) = false;
796 wakeup(&cc_exec_waiting(cc, direct));
798 } else if (cc_cce_migrating(cc, direct)) {
799 KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0,
800 ("Migrating legacy callout %p", c));
803 * If the callout was scheduled for
804 * migration just perform it now.
806 new_cpu = cc_migration_cpu(cc, direct);
807 new_time = cc_migration_time(cc, direct);
808 new_prec = cc_migration_prec(cc, direct);
809 new_func = cc_migration_func(cc, direct);
810 new_arg = cc_migration_arg(cc, direct);
811 cc_cce_cleanup(cc, direct);
814 * It should be assert here that the callout is not destroyed
815 * but that is not easy.
817 * As first thing, handle deferred callout stops.
819 if (!callout_migrating(c)) {
821 "deferred cancelled %p func %p arg %p",
822 c, new_func, new_arg);
823 callout_cc_del(c, cc);
826 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
828 new_cc = callout_cpu_switch(c, cc, new_cpu);
829 flags = (direct) ? C_DIRECT_EXEC : 0;
830 callout_cc_add(c, new_cc, new_time, new_prec, new_func,
831 new_arg, new_cpu, flags);
835 panic("migration should not happen");
839 * If the current callout is locally allocated (from
840 * timeout(9)) then put it on the freelist.
842 * Note: we need to check the cached copy of c_iflags because
843 * if it was not local, then it's not safe to deref the
846 KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0 ||
847 c->c_iflags == CALLOUT_LOCAL_ALLOC,
848 ("corrupted callout"));
849 if (c_iflags & CALLOUT_LOCAL_ALLOC)
850 callout_cc_del(c, cc);
854 * The callout mechanism is based on the work of Adam M. Costello and
855 * George Varghese, published in a technical report entitled "Redesigning
856 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
857 * in FreeBSD by Justin T. Gibbs. The original work on the data structures
858 * used in this implementation was published by G. Varghese and T. Lauck in
859 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
860 * the Efficient Implementation of a Timer Facility" in the Proceedings of
861 * the 11th ACM Annual Symposium on Operating Systems Principles,
862 * Austin, Texas Nov 1987.
866 * Software (low priority) clock interrupt.
867 * Run periodic events from timeout queue.
872 struct callout_cpu *cc;
874 #ifdef CALLOUT_PROFILING
875 int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
878 cc = (struct callout_cpu *)arg;
880 while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
881 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
882 softclock_call_cc(c, cc,
883 #ifdef CALLOUT_PROFILING
884 &mpcalls, &lockcalls, &gcalls,
887 #ifdef CALLOUT_PROFILING
891 #ifdef CALLOUT_PROFILING
892 avg_depth += (depth * 1000 - avg_depth) >> 8;
893 avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
894 avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
895 avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
902 * Execute a function after a specified length of time.
905 * Cancel previous timeout function call.
907 * callout_handle_init --
908 * Initialize a handle so that using it with untimeout is benign.
910 * See AT&T BCI Driver Reference Manual for specification. This
911 * implementation differs from that one in that although an
912 * identification value is returned from timeout, the original
913 * arguments to timeout as well as the identifier are used to
914 * identify entries for untimeout.
916 struct callout_handle
917 timeout(timeout_t *ftn, void *arg, int to_ticks)
919 struct callout_cpu *cc;
921 struct callout_handle handle;
923 cc = CC_CPU(timeout_cpu);
925 /* Fill in the next free callout structure. */
926 new = SLIST_FIRST(&cc->cc_callfree);
928 /* XXX Attempt to malloc first */
929 panic("timeout table full");
930 SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
931 callout_reset(new, to_ticks, ftn, arg);
932 handle.callout = new;
939 untimeout(timeout_t *ftn, void *arg, struct callout_handle handle)
941 struct callout_cpu *cc;
944 * Check for a handle that was initialized
945 * by callout_handle_init, but never used
946 * for a real timeout.
948 if (handle.callout == NULL)
951 cc = callout_lock(handle.callout);
952 if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
953 callout_stop(handle.callout);
958 callout_handle_init(struct callout_handle *handle)
960 handle->callout = NULL;
964 callout_when(sbintime_t sbt, sbintime_t precision, int flags,
965 sbintime_t *res, sbintime_t *prec_res)
967 sbintime_t to_sbt, to_pr;
969 if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
971 *prec_res = precision;
974 if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
976 if ((flags & C_HARDCLOCK) != 0 ||
977 #ifdef NO_EVENTTIMERS
978 sbt >= sbt_timethreshold) {
979 to_sbt = getsbinuptime();
981 /* Add safety belt for the case of hz > 1000. */
982 to_sbt += tc_tick_sbt - tick_sbt;
984 sbt >= sbt_tickthreshold) {
986 * Obtain the time of the last hardclock() call on
987 * this CPU directly from the kern_clocksource.c.
988 * This value is per-CPU, but it is equal for all
992 to_sbt = DPCPU_GET(hardclocktime);
995 to_sbt = DPCPU_GET(hardclocktime);
999 if (cold && to_sbt == 0)
1000 to_sbt = sbinuptime();
1001 if ((flags & C_HARDCLOCK) == 0)
1004 to_sbt = sbinuptime();
1005 if (SBT_MAX - to_sbt < sbt)
1010 to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
1011 sbt >> C_PRELGET(flags));
1012 *prec_res = to_pr > precision ? to_pr : precision;
1016 * New interface; clients allocate their own callout structures.
1018 * callout_reset() - establish or change a timeout
1019 * callout_stop() - disestablish a timeout
1020 * callout_init() - initialize a callout structure so that it can
1021 * safely be passed to callout_reset() and callout_stop()
1023 * <sys/callout.h> defines three convenience macros:
1025 * callout_active() - returns truth if callout has not been stopped,
1026 * drained, or deactivated since the last time the callout was
1028 * callout_pending() - returns truth if callout is still waiting for timeout
1029 * callout_deactivate() - marks the callout as having been serviced
1032 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
1033 void (*ftn)(void *), void *arg, int cpu, int flags)
1035 sbintime_t to_sbt, precision;
1036 struct callout_cpu *cc;
1037 int cancelled, direct;
1043 } else if ((cpu >= MAXCPU) ||
1044 ((CC_CPU(cpu))->cc_inited == 0)) {
1045 /* Invalid CPU spec */
1046 panic("Invalid CPU in callout %d", cpu);
1048 callout_when(sbt, prec, flags, &to_sbt, &precision);
1051 * This flag used to be added by callout_cc_add, but the
1052 * first time you call this we could end up with the
1053 * wrong direct flag if we don't do it before we add.
1055 if (flags & C_DIRECT_EXEC) {
1060 KASSERT(!direct || c->c_lock == NULL,
1061 ("%s: direct callout %p has lock", __func__, c));
1062 cc = callout_lock(c);
1064 * Don't allow migration of pre-allocated callouts lest they
1065 * become unbalanced or handle the case where the user does
1068 if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) ||
1073 if (cc_exec_curr(cc, direct) == c) {
1075 * We're being asked to reschedule a callout which is
1076 * currently in progress. If there is a lock then we
1077 * can cancel the callout if it has not really started.
1079 if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
1080 cancelled = cc_exec_cancel(cc, direct) = true;
1081 if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
1083 * Someone has called callout_drain to kill this
1084 * callout. Don't reschedule.
1086 CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1087 cancelled ? "cancelled" : "failed to cancel",
1088 c, c->c_func, c->c_arg);
1093 if (callout_migrating(c)) {
1095 * This only occurs when a second callout_reset_sbt_on
1096 * is made after a previous one moved it into
1097 * deferred migration (below). Note we do *not* change
1098 * the prev_cpu even though the previous target may
1101 cc_migration_cpu(cc, direct) = cpu;
1102 cc_migration_time(cc, direct) = to_sbt;
1103 cc_migration_prec(cc, direct) = precision;
1104 cc_migration_func(cc, direct) = ftn;
1105 cc_migration_arg(cc, direct) = arg;
1112 if (c->c_iflags & CALLOUT_PENDING) {
1113 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1114 if (cc_exec_next(cc) == c)
1115 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1116 LIST_REMOVE(c, c_links.le);
1118 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1121 c->c_iflags &= ~ CALLOUT_PENDING;
1122 c->c_flags &= ~ CALLOUT_ACTIVE;
1127 * If the callout must migrate try to perform it immediately.
1128 * If the callout is currently running, just defer the migration
1129 * to a more appropriate moment.
1131 if (c->c_cpu != cpu) {
1132 if (cc_exec_curr(cc, direct) == c) {
1134 * Pending will have been removed since we are
1135 * actually executing the callout on another
1136 * CPU. That callout should be waiting on the
1137 * lock the caller holds. If we set both
1138 * active/and/pending after we return and the
1139 * lock on the executing callout proceeds, it
1140 * will then see pending is true and return.
1141 * At the return from the actual callout execution
1142 * the migration will occur in softclock_call_cc
1143 * and this new callout will be placed on the
1144 * new CPU via a call to callout_cpu_switch() which
1145 * will get the lock on the right CPU followed
1146 * by a call callout_cc_add() which will add it there.
1147 * (see above in softclock_call_cc()).
1149 cc_migration_cpu(cc, direct) = cpu;
1150 cc_migration_time(cc, direct) = to_sbt;
1151 cc_migration_prec(cc, direct) = precision;
1152 cc_migration_func(cc, direct) = ftn;
1153 cc_migration_arg(cc, direct) = arg;
1154 c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
1155 c->c_flags |= CALLOUT_ACTIVE;
1157 "migration of %p func %p arg %p in %d.%08x to %u deferred",
1158 c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1159 (u_int)(to_sbt & 0xffffffff), cpu);
1163 cc = callout_cpu_switch(c, cc, cpu);
1167 callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1168 CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1169 cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1170 (u_int)(to_sbt & 0xffffffff));
1177 * Common idioms that can be optimized in the future.
1180 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1182 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1186 callout_schedule(struct callout *c, int to_ticks)
1188 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1192 _callout_stop_safe(struct callout *c, int flags, void (*drain)(void *))
1194 struct callout_cpu *cc, *old_cc;
1195 struct lock_class *class;
1196 int direct, sq_locked, use_lock;
1197 int cancelled, not_on_a_list;
1199 if ((flags & CS_DRAIN) != 0)
1200 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
1201 "calling %s", __func__);
1204 * Some old subsystems don't hold Giant while running a callout_stop(),
1205 * so just discard this check for the moment.
1207 if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1208 if (c->c_lock == &Giant.lock_object)
1209 use_lock = mtx_owned(&Giant);
1212 class = LOCK_CLASS(c->c_lock);
1213 class->lc_assert(c->c_lock, LA_XLOCKED);
1217 if (c->c_iflags & CALLOUT_DIRECT) {
1225 cc = callout_lock(c);
1227 if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
1228 (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
1229 ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1231 * Special case where this slipped in while we
1232 * were migrating *as* the callout is about to
1233 * execute. The caller probably holds the lock
1234 * the callout wants.
1236 * Get rid of the migration first. Then set
1237 * the flag that tells this code *not* to
1238 * try to remove it from any lists (its not
1239 * on one yet). When the callout wheel runs,
1240 * it will ignore this callout.
1242 c->c_iflags &= ~CALLOUT_PENDING;
1243 c->c_flags &= ~CALLOUT_ACTIVE;
1250 * If the callout was migrating while the callout cpu lock was
1251 * dropped, just drop the sleepqueue lock and check the states
1254 if (sq_locked != 0 && cc != old_cc) {
1257 sleepq_release(&cc_exec_waiting(old_cc, direct));
1262 panic("migration should not happen");
1267 * If the callout is running, try to stop it or drain it.
1269 if (cc_exec_curr(cc, direct) == c) {
1271 * Succeed we to stop it or not, we must clear the
1272 * active flag - this is what API users expect. If we're
1273 * draining and the callout is currently executing, first wait
1274 * until it finishes.
1276 if ((flags & CS_DRAIN) == 0)
1277 c->c_flags &= ~CALLOUT_ACTIVE;
1279 if ((flags & CS_DRAIN) != 0) {
1281 * The current callout is running (or just
1282 * about to run) and blocking is allowed, so
1283 * just wait for the current invocation to
1286 while (cc_exec_curr(cc, direct) == c) {
1288 * Use direct calls to sleepqueue interface
1289 * instead of cv/msleep in order to avoid
1290 * a LOR between cc_lock and sleepqueue
1291 * chain spinlocks. This piece of code
1292 * emulates a msleep_spin() call actually.
1294 * If we already have the sleepqueue chain
1295 * locked, then we can safely block. If we
1296 * don't already have it locked, however,
1297 * we have to drop the cc_lock to lock
1298 * it. This opens several races, so we
1299 * restart at the beginning once we have
1300 * both locks. If nothing has changed, then
1301 * we will end up back here with sq_locked
1307 &cc_exec_waiting(cc, direct));
1314 * Migration could be cancelled here, but
1315 * as long as it is still not sure when it
1316 * will be packed up, just let softclock()
1319 cc_exec_waiting(cc, direct) = true;
1323 &cc_exec_waiting(cc, direct),
1324 &cc->cc_lock.lock_object, "codrain",
1327 &cc_exec_waiting(cc, direct),
1332 /* Reacquire locks previously released. */
1336 c->c_flags &= ~CALLOUT_ACTIVE;
1337 } else if (use_lock &&
1338 !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1341 * The current callout is waiting for its
1342 * lock which we hold. Cancel the callout
1343 * and return. After our caller drops the
1344 * lock, the callout will be skipped in
1345 * softclock(). This *only* works with a
1346 * callout_stop() *not* callout_drain() or
1347 * callout_async_drain().
1349 cc_exec_cancel(cc, direct) = true;
1350 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1351 c, c->c_func, c->c_arg);
1352 KASSERT(!cc_cce_migrating(cc, direct),
1353 ("callout wrongly scheduled for migration"));
1354 if (callout_migrating(c)) {
1355 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1357 cc_migration_cpu(cc, direct) = CPUBLOCK;
1358 cc_migration_time(cc, direct) = 0;
1359 cc_migration_prec(cc, direct) = 0;
1360 cc_migration_func(cc, direct) = NULL;
1361 cc_migration_arg(cc, direct) = NULL;
1365 KASSERT(!sq_locked, ("sleepqueue chain locked"));
1367 } else if (callout_migrating(c)) {
1369 * The callout is currently being serviced
1370 * and the "next" callout is scheduled at
1371 * its completion with a migration. We remove
1372 * the migration flag so it *won't* get rescheduled,
1373 * but we can't stop the one thats running so
1376 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1379 * We can't call cc_cce_cleanup here since
1380 * if we do it will remove .ce_curr and
1381 * its still running. This will prevent a
1382 * reschedule of the callout when the
1383 * execution completes.
1385 cc_migration_cpu(cc, direct) = CPUBLOCK;
1386 cc_migration_time(cc, direct) = 0;
1387 cc_migration_prec(cc, direct) = 0;
1388 cc_migration_func(cc, direct) = NULL;
1389 cc_migration_arg(cc, direct) = NULL;
1391 CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1392 c, c->c_func, c->c_arg);
1394 cc_exec_drain(cc, direct) = drain;
1397 return ((flags & CS_EXECUTING) != 0);
1399 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1400 c, c->c_func, c->c_arg);
1402 cc_exec_drain(cc, direct) = drain;
1404 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1405 cancelled = ((flags & CS_EXECUTING) != 0);
1410 sleepq_release(&cc_exec_waiting(cc, direct));
1412 if ((c->c_iflags & CALLOUT_PENDING) == 0) {
1413 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1414 c, c->c_func, c->c_arg);
1416 * For not scheduled and not executing callout return
1419 if (cc_exec_curr(cc, direct) != c)
1425 c->c_iflags &= ~CALLOUT_PENDING;
1426 c->c_flags &= ~CALLOUT_ACTIVE;
1428 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1429 c, c->c_func, c->c_arg);
1430 if (not_on_a_list == 0) {
1431 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1432 if (cc_exec_next(cc) == c)
1433 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1434 LIST_REMOVE(c, c_links.le);
1436 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1439 callout_cc_del(c, cc);
1445 callout_init(struct callout *c, int mpsafe)
1447 bzero(c, sizeof *c);
1450 c->c_iflags = CALLOUT_RETURNUNLOCKED;
1452 c->c_lock = &Giant.lock_object;
1455 c->c_cpu = timeout_cpu;
1459 _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
1461 bzero(c, sizeof *c);
1463 KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1464 ("callout_init_lock: bad flags %d", flags));
1465 KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1466 ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1467 KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1468 (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1470 c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1471 c->c_cpu = timeout_cpu;
1474 #ifdef APM_FIXUP_CALLTODO
1476 * Adjust the kernel calltodo timeout list. This routine is used after
1477 * an APM resume to recalculate the calltodo timer list values with the
1478 * number of hz's we have been sleeping. The next hardclock() will detect
1479 * that there are fired timers and run softclock() to execute them.
1481 * Please note, I have not done an exhaustive analysis of what code this
1482 * might break. I am motivated to have my select()'s and alarm()'s that
1483 * have expired during suspend firing upon resume so that the applications
1484 * which set the timer can do the maintanence the timer was for as close
1485 * as possible to the originally intended time. Testing this code for a
1486 * week showed that resuming from a suspend resulted in 22 to 25 timers
1487 * firing, which seemed independent on whether the suspend was 2 hours or
1488 * 2 days. Your milage may vary. - Ken Key <key@cs.utk.edu>
1491 adjust_timeout_calltodo(struct timeval *time_change)
1494 unsigned long delta_ticks;
1497 * How many ticks were we asleep?
1498 * (stolen from tvtohz()).
1501 /* Don't do anything */
1502 if (time_change->tv_sec < 0)
1504 else if (time_change->tv_sec <= LONG_MAX / 1000000)
1505 delta_ticks = howmany(time_change->tv_sec * 1000000 +
1506 time_change->tv_usec, tick) + 1;
1507 else if (time_change->tv_sec <= LONG_MAX / hz)
1508 delta_ticks = time_change->tv_sec * hz +
1509 howmany(time_change->tv_usec, tick) + 1;
1511 delta_ticks = LONG_MAX;
1513 if (delta_ticks > INT_MAX)
1514 delta_ticks = INT_MAX;
1517 * Now rip through the timer calltodo list looking for timers
1521 /* don't collide with softclock() */
1523 for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1524 p->c_time -= delta_ticks;
1526 /* Break if the timer had more time on it than delta_ticks */
1530 /* take back the ticks the timer didn't use (p->c_time <= 0) */
1531 delta_ticks = -p->c_time;
1537 #endif /* APM_FIXUP_CALLTODO */
1540 flssbt(sbintime_t sbt)
1543 sbt += (uint64_t)sbt >> 1;
1544 if (sizeof(long) >= sizeof(sbintime_t))
1547 return (flsl(((uint64_t)sbt) >> 32) + 32);
1552 * Dump immediate statistic snapshot of the scheduled callouts.
1555 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1557 struct callout *tmp;
1558 struct callout_cpu *cc;
1559 struct callout_list *sc;
1560 sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1561 int ct[64], cpr[64], ccpbk[32];
1562 int error, val, i, count, tcum, pcum, maxc, c, medc;
1568 error = sysctl_handle_int(oidp, &val, 0, req);
1569 if (error != 0 || req->newptr == NULL)
1572 st = spr = maxt = maxpr = 0;
1573 bzero(ccpbk, sizeof(ccpbk));
1574 bzero(ct, sizeof(ct));
1575 bzero(cpr, sizeof(cpr));
1581 cc = CC_CPU(timeout_cpu);
1584 for (i = 0; i < callwheelsize; i++) {
1585 sc = &cc->cc_callwheel[i];
1587 LIST_FOREACH(tmp, sc, c_links.le) {
1589 t = tmp->c_time - now;
1593 spr += tmp->c_precision / SBT_1US;
1596 if (tmp->c_precision > maxpr)
1597 maxpr = tmp->c_precision;
1599 cpr[flssbt(tmp->c_precision)]++;
1603 ccpbk[fls(c + c / 2)]++;
1611 for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1613 medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1614 for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1616 medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1617 for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1619 medc = (i >= 2) ? (1 << (i - 2)) : 0;
1621 printf("Scheduled callouts statistic snapshot:\n");
1622 printf(" Callouts: %6d Buckets: %6d*%-3d Bucket size: 0.%06ds\n",
1623 count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1624 printf(" C/Bk: med %5d avg %6d.%06jd max %6d\n",
1626 count / callwheelsize / mp_ncpus,
1627 (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1629 printf(" Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1630 medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1631 (st / count) / 1000000, (st / count) % 1000000,
1632 maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1633 printf(" Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1634 medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1635 (spr / count) / 1000000, (spr / count) % 1000000,
1636 maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1637 printf(" Distribution: \tbuckets\t time\t tcum\t"
1639 for (i = 0, tcum = pcum = 0; i < 64; i++) {
1640 if (ct[i] == 0 && cpr[i] == 0)
1642 t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1645 printf(" %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1646 t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1647 i - 1 - (32 - CC_HASH_SHIFT),
1648 ct[i], tcum, cpr[i], pcum);
1652 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1653 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1654 0, 0, sysctl_kern_callout_stat, "I",
1655 "Dump immediate statistic snapshot of the scheduled callouts");
1659 _show_callout(struct callout *c)
1662 db_printf("callout %p\n", c);
1663 #define C_DB_PRINTF(f, e) db_printf(" %s = " f "\n", #e, c->e);
1664 db_printf(" &c_links = %p\n", &(c->c_links));
1665 C_DB_PRINTF("%" PRId64, c_time);
1666 C_DB_PRINTF("%" PRId64, c_precision);
1667 C_DB_PRINTF("%p", c_arg);
1668 C_DB_PRINTF("%p", c_func);
1669 C_DB_PRINTF("%p", c_lock);
1670 C_DB_PRINTF("%#x", c_flags);
1671 C_DB_PRINTF("%#x", c_iflags);
1672 C_DB_PRINTF("%d", c_cpu);
1676 DB_SHOW_COMMAND(callout, db_show_callout)
1680 db_printf("usage: show callout <struct callout *>\n");
1684 _show_callout((struct callout *)addr);
1688 _show_last_callout(int cpu, int direct, const char *dirstr)
1690 struct callout_cpu *cc;
1694 func = cc_exec_last_func(cc, direct);
1695 arg = cc_exec_last_arg(cc, direct);
1696 db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
1697 db_printsym((db_expr_t)func, DB_STGY_ANY);
1698 db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
1701 DB_SHOW_COMMAND(callout_last, db_show_callout_last)
1706 if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
1707 db_printf("no such cpu: %d\n", (int)addr);
1716 while (cpu <= last) {
1717 if (!CPU_ABSENT(cpu)) {
1718 _show_last_callout(cpu, 0, "");
1719 _show_last_callout(cpu, 1, " direct");