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 #include "opt_callout_profiling.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
47 #include <sys/callout.h>
48 #include <sys/domainset.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>
64 #include <ddb/db_sym.h>
65 #include <machine/_inttypes.h>
69 #include <machine/cpu.h>
72 DPCPU_DECLARE(sbintime_t, hardclocktime);
74 SDT_PROVIDER_DEFINE(callout_execute);
75 SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
76 SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
78 #ifdef CALLOUT_PROFILING
80 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
81 "Average number of items examined per softclock call. Units = 1/1000");
82 static int avg_gcalls;
83 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
84 "Average number of Giant callouts made per softclock call. Units = 1/1000");
85 static int avg_lockcalls;
86 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
87 "Average number of lock callouts made per softclock call. Units = 1/1000");
88 static int avg_mpcalls;
89 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
90 "Average number of MP callouts made per softclock call. Units = 1/1000");
91 static int avg_depth_dir;
92 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
93 "Average number of direct callouts examined per callout_process call. "
95 static int avg_lockcalls_dir;
96 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
97 &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
98 "callout_process call. Units = 1/1000");
99 static int avg_mpcalls_dir;
100 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
101 0, "Average number of MP direct callouts made per callout_process call. "
106 SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
107 "Number of entries in callwheel and size of timeout() preallocation");
110 static int pin_default_swi = 1;
111 static int pin_pcpu_swi = 1;
113 static int pin_default_swi = 0;
114 static int pin_pcpu_swi = 0;
117 SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
118 0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
119 SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
120 0, "Pin the per-CPU swis (except PCPU 0, which is also default)");
124 * allocate more timeout table slots when table overflows.
126 static u_int __read_mostly callwheelsize;
127 static u_int __read_mostly callwheelmask;
130 * The callout cpu exec entities represent informations necessary for
131 * describing the state of callouts currently running on the CPU and the ones
132 * necessary for migrating callouts to the new callout cpu. In particular,
133 * the first entry of the array cc_exec_entity holds informations for callout
134 * running in SWI thread context, while the second one holds informations
135 * for callout running directly from hardware interrupt context.
136 * The cached informations are very important for deferring migration when
137 * the migrating callout is already running.
140 struct callout *cc_curr;
141 callout_func_t *cc_drain;
145 callout_func_t *ce_migration_func;
146 void *ce_migration_arg;
147 sbintime_t ce_migration_time;
148 sbintime_t ce_migration_prec;
149 int ce_migration_cpu;
156 * There is one struct callout_cpu per cpu, holding all relevant
157 * state for the callout processing thread on the individual CPU.
160 struct mtx_padalign cc_lock;
161 struct cc_exec cc_exec_entity[2];
162 struct callout *cc_next;
163 struct callout_list *cc_callwheel;
164 struct callout_tailq cc_expireq;
165 sbintime_t cc_firstevent;
166 sbintime_t cc_lastscan;
171 char cc_ktr_event_name[20];
175 #define callout_migrating(c) ((c)->c_iflags & CALLOUT_DFRMIGRATION)
177 #define cc_exec_curr(cc, dir) cc->cc_exec_entity[dir].cc_curr
178 #define cc_exec_last_func(cc, dir) cc->cc_exec_entity[dir].cc_last_func
179 #define cc_exec_last_arg(cc, dir) cc->cc_exec_entity[dir].cc_last_arg
180 #define cc_exec_drain(cc, dir) cc->cc_exec_entity[dir].cc_drain
181 #define cc_exec_next(cc) cc->cc_next
182 #define cc_exec_cancel(cc, dir) cc->cc_exec_entity[dir].cc_cancel
183 #define cc_exec_waiting(cc, dir) cc->cc_exec_entity[dir].cc_waiting
185 #define cc_migration_func(cc, dir) cc->cc_exec_entity[dir].ce_migration_func
186 #define cc_migration_arg(cc, dir) cc->cc_exec_entity[dir].ce_migration_arg
187 #define cc_migration_cpu(cc, dir) cc->cc_exec_entity[dir].ce_migration_cpu
188 #define cc_migration_time(cc, dir) cc->cc_exec_entity[dir].ce_migration_time
189 #define cc_migration_prec(cc, dir) cc->cc_exec_entity[dir].ce_migration_prec
191 static struct callout_cpu cc_cpu[MAXCPU];
192 #define CPUBLOCK MAXCPU
193 #define CC_CPU(cpu) (&cc_cpu[(cpu)])
194 #define CC_SELF() CC_CPU(PCPU_GET(cpuid))
196 static struct callout_cpu cc_cpu;
197 #define CC_CPU(cpu) (&cc_cpu)
198 #define CC_SELF() (&cc_cpu)
200 #define CC_LOCK(cc) mtx_lock_spin(&(cc)->cc_lock)
201 #define CC_UNLOCK(cc) mtx_unlock_spin(&(cc)->cc_lock)
202 #define CC_LOCK_ASSERT(cc) mtx_assert(&(cc)->cc_lock, MA_OWNED)
204 static int __read_mostly cc_default_cpu;
206 static void callout_cpu_init(struct callout_cpu *cc, int cpu);
207 static void softclock_call_cc(struct callout *c, struct callout_cpu *cc,
208 #ifdef CALLOUT_PROFILING
209 int *mpcalls, int *lockcalls, int *gcalls,
213 static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
217 * cc_curr - If a callout is in progress, it is cc_curr.
218 * If cc_curr is non-NULL, threads waiting in
219 * callout_drain() will be woken up as soon as the
220 * relevant callout completes.
221 * cc_cancel - Changing to 1 with both callout_lock and cc_lock held
222 * guarantees that the current callout will not run.
223 * The softclock() function sets this to 0 before it
224 * drops callout_lock to acquire c_lock, and it calls
225 * the handler only if curr_cancelled is still 0 after
226 * cc_lock is successfully acquired.
227 * cc_waiting - If a thread is waiting in callout_drain(), then
228 * callout_wait is nonzero. Set only when
229 * cc_curr is non-NULL.
233 * Resets the execution entity tied to a specific callout cpu.
236 cc_cce_cleanup(struct callout_cpu *cc, int direct)
239 cc_exec_curr(cc, direct) = NULL;
240 cc_exec_cancel(cc, direct) = false;
241 cc_exec_waiting(cc, direct) = false;
243 cc_migration_cpu(cc, direct) = CPUBLOCK;
244 cc_migration_time(cc, direct) = 0;
245 cc_migration_prec(cc, direct) = 0;
246 cc_migration_func(cc, direct) = NULL;
247 cc_migration_arg(cc, direct) = NULL;
252 * Checks if migration is requested by a specific callout cpu.
255 cc_cce_migrating(struct callout_cpu *cc, int direct)
259 return (cc_migration_cpu(cc, direct) != CPUBLOCK);
266 * Kernel low level callwheel initialization
267 * called on the BSP during kernel startup.
270 callout_callwheel_init(void *dummy)
272 struct callout_cpu *cc;
276 * Calculate the size of the callout wheel and the preallocated
277 * timeout() structures.
278 * XXX: Clip callout to result of previous function of maxusers
279 * maximum 384. This is still huge, but acceptable.
281 ncallout = imin(16 + maxproc + maxfiles, 18508);
282 TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
285 * Calculate callout wheel size, should be next power of two higher
288 callwheelsize = 1 << fls(ncallout);
289 callwheelmask = callwheelsize - 1;
292 * Fetch whether we're pinning the swi's or not.
294 TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
295 TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
298 * Initialize callout wheels. The software interrupt threads
301 cc_default_cpu = PCPU_GET(cpuid);
304 callout_cpu_init(cc, cpu);
307 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
310 * Initialize the per-cpu callout structures.
313 callout_cpu_init(struct callout_cpu *cc, int cpu)
317 mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
319 cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
320 callwheelsize, M_CALLOUT,
321 DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
322 for (i = 0; i < callwheelsize; i++)
323 LIST_INIT(&cc->cc_callwheel[i]);
324 TAILQ_INIT(&cc->cc_expireq);
325 cc->cc_firstevent = SBT_MAX;
326 for (i = 0; i < 2; i++)
327 cc_cce_cleanup(cc, i);
329 snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
330 "callwheel cpu %d", cpu);
336 * Switches the cpu tied to a specific callout.
337 * The function expects a locked incoming callout cpu and returns with
338 * locked outcoming callout cpu.
340 static struct callout_cpu *
341 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
343 struct callout_cpu *new_cc;
345 MPASS(c != NULL && cc != NULL);
349 * Avoid interrupts and preemption firing after the callout cpu
350 * is blocked in order to avoid deadlocks as the new thread
351 * may be willing to acquire the callout cpu lock.
356 new_cc = CC_CPU(new_cpu);
365 * Start softclock threads.
368 start_softclock(void *dummy)
370 struct callout_cpu *cc;
371 char name[MAXCOMLEN];
374 struct intr_event *ie;
378 snprintf(name, sizeof(name), "clock (%d)", cpu);
380 if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
381 INTR_MPSAFE, &cc->cc_cookie))
382 panic("died while creating standard software ithreads");
383 if (cpu == cc_default_cpu)
384 pin_swi = pin_default_swi;
386 pin_swi = pin_pcpu_swi;
387 if (pin_swi && (intr_event_bind(ie, cpu) != 0)) {
388 printf("%s: %s clock couldn't be pinned to cpu %d\n",
390 cpu == cc_default_cpu ? "default" : "per-cpu",
395 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
397 #define CC_HASH_SHIFT 8
400 callout_hash(sbintime_t sbt)
403 return (sbt >> (32 - CC_HASH_SHIFT));
407 callout_get_bucket(sbintime_t sbt)
410 return (callout_hash(sbt) & callwheelmask);
414 callout_process(sbintime_t now)
416 struct callout *c, *next;
417 struct callout_cpu *cc;
418 struct callout_list *sc;
419 sbintime_t first, last, lookahead, max, tmp_max;
420 u_int firstb, lastb, nowb;
421 #ifdef CALLOUT_PROFILING
422 int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
426 mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
428 /* Compute the buckets of the last scan and present times. */
429 firstb = callout_hash(cc->cc_lastscan);
430 cc->cc_lastscan = now;
431 nowb = callout_hash(now);
433 /* Compute the last bucket and minimum time of the bucket after it. */
435 lookahead = (SBT_1S / 16);
436 else if (nowb - firstb == 1)
437 lookahead = (SBT_1S / 8);
441 first += (lookahead / 2);
443 last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
444 lastb = callout_hash(last) - 1;
448 * Check if we wrapped around the entire wheel from the last scan.
449 * In case, we need to scan entirely the wheel for pending callouts.
451 if (lastb - firstb >= callwheelsize) {
452 lastb = firstb + callwheelsize - 1;
453 if (nowb - firstb >= callwheelsize)
457 /* Iterate callwheel from firstb to nowb and then up to lastb. */
459 sc = &cc->cc_callwheel[firstb & callwheelmask];
460 LIST_FOREACH_SAFE(c, sc, c_links.le, next) {
461 /* Run the callout if present time within allowed. */
462 if (c->c_time <= now) {
464 * Consumer told us the callout may be run
465 * directly from hardware interrupt context.
467 if (c->c_iflags & CALLOUT_DIRECT) {
468 #ifdef CALLOUT_PROFILING
471 cc_exec_next(cc) = next;
472 cc->cc_bucket = firstb & callwheelmask;
473 LIST_REMOVE(c, c_links.le);
474 softclock_call_cc(c, cc,
475 #ifdef CALLOUT_PROFILING
476 &mpcalls_dir, &lockcalls_dir, NULL,
479 next = cc_exec_next(cc);
480 cc_exec_next(cc) = NULL;
482 LIST_REMOVE(c, c_links.le);
483 TAILQ_INSERT_TAIL(&cc->cc_expireq,
485 c->c_iflags |= CALLOUT_PROCESSED;
487 } else if (c->c_time >= max) {
489 * Skip events in the distant future.
492 } else if (c->c_time > last) {
494 * Event minimal time is bigger than present
495 * maximal time, so it cannot be aggregated.
500 * Update first and last time, respecting this
503 if (c->c_time < first)
505 tmp_max = c->c_time + c->c_precision;
510 /* Proceed with the next bucket. */
513 * Stop if we looked after present time and found
514 * some event we can't execute at now.
515 * Stop if we looked far enough into the future.
517 } while (((int)(firstb - lastb)) <= 0);
518 cc->cc_firstevent = last;
519 cpu_new_callout(curcpu, last, first);
521 #ifdef CALLOUT_PROFILING
522 avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
523 avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
524 avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
526 mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
528 * swi_sched acquires the thread lock, so we don't want to call it
529 * with cc_lock held; incorrect locking order.
531 if (!TAILQ_EMPTY(&cc->cc_expireq))
532 swi_sched(cc->cc_cookie, 0);
535 static struct callout_cpu *
536 callout_lock(struct callout *c)
538 struct callout_cpu *cc;
544 if (cpu == CPUBLOCK) {
545 while (c->c_cpu == CPUBLOCK)
560 callout_cc_add(struct callout *c, struct callout_cpu *cc,
561 sbintime_t sbt, sbintime_t precision, void (*func)(void *),
562 void *arg, int flags)
567 if (sbt < cc->cc_lastscan)
568 sbt = cc->cc_lastscan;
570 c->c_iflags |= CALLOUT_PENDING;
571 c->c_iflags &= ~CALLOUT_PROCESSED;
572 c->c_flags |= CALLOUT_ACTIVE;
573 if (flags & C_DIRECT_EXEC)
574 c->c_iflags |= CALLOUT_DIRECT;
577 c->c_precision = precision;
578 bucket = callout_get_bucket(c->c_time);
579 CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
580 c, (int)(c->c_precision >> 32),
581 (u_int)(c->c_precision & 0xffffffff));
582 LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
583 if (cc->cc_bucket == bucket)
584 cc_exec_next(cc) = c;
587 * Inform the eventtimers(4) subsystem there's a new callout
588 * that has been inserted, but only if really required.
590 if (SBT_MAX - c->c_time < c->c_precision)
591 c->c_precision = SBT_MAX - c->c_time;
592 sbt = c->c_time + c->c_precision;
593 if (sbt < cc->cc_firstevent) {
594 cc->cc_firstevent = sbt;
595 cpu_new_callout(c->c_cpu, sbt, c->c_time);
600 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
601 #ifdef CALLOUT_PROFILING
602 int *mpcalls, int *lockcalls, int *gcalls,
606 struct rm_priotracker tracker;
607 callout_func_t *c_func, *drain;
609 struct lock_class *class;
610 struct lock_object *c_lock;
611 uintptr_t lock_status;
614 struct callout_cpu *new_cc;
615 callout_func_t *new_func;
618 sbintime_t new_prec, new_time;
620 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
621 sbintime_t sbt1, sbt2;
623 static sbintime_t maxdt = 2 * SBT_1MS; /* 2 msec */
624 static callout_func_t *lastfunc;
627 KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
628 ("softclock_call_cc: pend %p %x", c, c->c_iflags));
629 KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
630 ("softclock_call_cc: act %p %x", c, c->c_flags));
631 class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
633 if (c->c_iflags & CALLOUT_SHAREDLOCK) {
634 if (class == &lock_class_rm)
635 lock_status = (uintptr_t)&tracker;
642 c_iflags = c->c_iflags;
643 c->c_iflags &= ~CALLOUT_PENDING;
645 cc_exec_curr(cc, direct) = c;
646 cc_exec_last_func(cc, direct) = c_func;
647 cc_exec_last_arg(cc, direct) = c_arg;
648 cc_exec_cancel(cc, direct) = false;
649 cc_exec_drain(cc, direct) = NULL;
651 if (c_lock != NULL) {
652 class->lc_lock(c_lock, lock_status);
654 * The callout may have been cancelled
655 * while we switched locks.
657 if (cc_exec_cancel(cc, direct)) {
658 class->lc_unlock(c_lock);
661 /* The callout cannot be stopped now. */
662 cc_exec_cancel(cc, direct) = true;
663 if (c_lock == &Giant.lock_object) {
664 #ifdef CALLOUT_PROFILING
667 CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
670 #ifdef CALLOUT_PROFILING
673 CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
677 #ifdef CALLOUT_PROFILING
680 CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
683 KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
684 "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
685 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
688 THREAD_NO_SLEEPING();
689 SDT_PROBE1(callout_execute, , , callout__start, c);
691 SDT_PROBE1(callout_execute, , , callout__end, c);
692 THREAD_SLEEPING_OK();
693 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
697 if (lastfunc != c_func || sbt2 > maxdt * 2) {
700 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
701 c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
707 KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
708 CTR1(KTR_CALLOUT, "callout %p finished", c);
709 if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
710 class->lc_unlock(c_lock);
713 KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
714 cc_exec_curr(cc, direct) = NULL;
715 if (cc_exec_drain(cc, direct)) {
716 drain = cc_exec_drain(cc, direct);
717 cc_exec_drain(cc, direct) = NULL;
722 if (cc_exec_waiting(cc, direct)) {
724 * There is someone waiting for the
725 * callout to complete.
726 * If the callout was scheduled for
727 * migration just cancel it.
729 if (cc_cce_migrating(cc, direct)) {
730 cc_cce_cleanup(cc, direct);
733 * It should be assert here that the callout is not
734 * destroyed but that is not easy.
736 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
738 cc_exec_waiting(cc, direct) = false;
740 wakeup(&cc_exec_waiting(cc, direct));
742 } else if (cc_cce_migrating(cc, direct)) {
745 * If the callout was scheduled for
746 * migration just perform it now.
748 new_cpu = cc_migration_cpu(cc, direct);
749 new_time = cc_migration_time(cc, direct);
750 new_prec = cc_migration_prec(cc, direct);
751 new_func = cc_migration_func(cc, direct);
752 new_arg = cc_migration_arg(cc, direct);
753 cc_cce_cleanup(cc, direct);
756 * It should be assert here that the callout is not destroyed
757 * but that is not easy.
759 * As first thing, handle deferred callout stops.
761 if (!callout_migrating(c)) {
763 "deferred cancelled %p func %p arg %p",
764 c, new_func, new_arg);
767 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
769 new_cc = callout_cpu_switch(c, cc, new_cpu);
770 flags = (direct) ? C_DIRECT_EXEC : 0;
771 callout_cc_add(c, new_cc, new_time, new_prec, new_func,
776 panic("migration should not happen");
782 * The callout mechanism is based on the work of Adam M. Costello and
783 * George Varghese, published in a technical report entitled "Redesigning
784 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
785 * in FreeBSD by Justin T. Gibbs. The original work on the data structures
786 * used in this implementation was published by G. Varghese and T. Lauck in
787 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
788 * the Efficient Implementation of a Timer Facility" in the Proceedings of
789 * the 11th ACM Annual Symposium on Operating Systems Principles,
790 * Austin, Texas Nov 1987.
794 * Software (low priority) clock interrupt.
795 * Run periodic events from timeout queue.
800 struct callout_cpu *cc;
802 #ifdef CALLOUT_PROFILING
803 int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
806 cc = (struct callout_cpu *)arg;
808 while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
809 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
810 softclock_call_cc(c, cc,
811 #ifdef CALLOUT_PROFILING
812 &mpcalls, &lockcalls, &gcalls,
815 #ifdef CALLOUT_PROFILING
819 #ifdef CALLOUT_PROFILING
820 avg_depth += (depth * 1000 - avg_depth) >> 8;
821 avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
822 avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
823 avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
829 callout_when(sbintime_t sbt, sbintime_t precision, int flags,
830 sbintime_t *res, sbintime_t *prec_res)
832 sbintime_t to_sbt, to_pr;
834 if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
836 *prec_res = precision;
839 if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
841 if ((flags & C_HARDCLOCK) != 0 || sbt >= sbt_tickthreshold) {
843 * Obtain the time of the last hardclock() call on
844 * this CPU directly from the kern_clocksource.c.
845 * This value is per-CPU, but it is equal for all
849 to_sbt = DPCPU_GET(hardclocktime);
852 to_sbt = DPCPU_GET(hardclocktime);
855 if (cold && to_sbt == 0)
856 to_sbt = sbinuptime();
857 if ((flags & C_HARDCLOCK) == 0)
860 to_sbt = sbinuptime();
861 if (SBT_MAX - to_sbt < sbt)
866 to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
867 sbt >> C_PRELGET(flags));
868 *prec_res = to_pr > precision ? to_pr : precision;
872 * New interface; clients allocate their own callout structures.
874 * callout_reset() - establish or change a timeout
875 * callout_stop() - disestablish a timeout
876 * callout_init() - initialize a callout structure so that it can
877 * safely be passed to callout_reset() and callout_stop()
879 * <sys/callout.h> defines three convenience macros:
881 * callout_active() - returns truth if callout has not been stopped,
882 * drained, or deactivated since the last time the callout was
884 * callout_pending() - returns truth if callout is still waiting for timeout
885 * callout_deactivate() - marks the callout as having been serviced
888 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
889 callout_func_t *ftn, void *arg, int cpu, int flags)
891 sbintime_t to_sbt, precision;
892 struct callout_cpu *cc;
893 int cancelled, direct;
899 } else if ((cpu >= MAXCPU) ||
900 ((CC_CPU(cpu))->cc_inited == 0)) {
901 /* Invalid CPU spec */
902 panic("Invalid CPU in callout %d", cpu);
904 callout_when(sbt, prec, flags, &to_sbt, &precision);
907 * This flag used to be added by callout_cc_add, but the
908 * first time you call this we could end up with the
909 * wrong direct flag if we don't do it before we add.
911 if (flags & C_DIRECT_EXEC) {
916 KASSERT(!direct || c->c_lock == NULL ||
917 (LOCK_CLASS(c->c_lock)->lc_flags & LC_SPINLOCK),
918 ("%s: direct callout %p has non-spin lock", __func__, c));
919 cc = callout_lock(c);
921 * Don't allow migration if the user does not care.
927 if (cc_exec_curr(cc, direct) == c) {
929 * We're being asked to reschedule a callout which is
930 * currently in progress. If there is a lock then we
931 * can cancel the callout if it has not really started.
933 if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
934 cancelled = cc_exec_cancel(cc, direct) = true;
935 if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
937 * Someone has called callout_drain to kill this
938 * callout. Don't reschedule.
940 CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
941 cancelled ? "cancelled" : "failed to cancel",
942 c, c->c_func, c->c_arg);
947 if (callout_migrating(c)) {
949 * This only occurs when a second callout_reset_sbt_on
950 * is made after a previous one moved it into
951 * deferred migration (below). Note we do *not* change
952 * the prev_cpu even though the previous target may
955 cc_migration_cpu(cc, direct) = cpu;
956 cc_migration_time(cc, direct) = to_sbt;
957 cc_migration_prec(cc, direct) = precision;
958 cc_migration_func(cc, direct) = ftn;
959 cc_migration_arg(cc, direct) = arg;
966 if (c->c_iflags & CALLOUT_PENDING) {
967 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
968 if (cc_exec_next(cc) == c)
969 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
970 LIST_REMOVE(c, c_links.le);
972 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
975 c->c_iflags &= ~ CALLOUT_PENDING;
976 c->c_flags &= ~ CALLOUT_ACTIVE;
981 * If the callout must migrate try to perform it immediately.
982 * If the callout is currently running, just defer the migration
983 * to a more appropriate moment.
985 if (c->c_cpu != cpu) {
986 if (cc_exec_curr(cc, direct) == c) {
988 * Pending will have been removed since we are
989 * actually executing the callout on another
990 * CPU. That callout should be waiting on the
991 * lock the caller holds. If we set both
992 * active/and/pending after we return and the
993 * lock on the executing callout proceeds, it
994 * will then see pending is true and return.
995 * At the return from the actual callout execution
996 * the migration will occur in softclock_call_cc
997 * and this new callout will be placed on the
998 * new CPU via a call to callout_cpu_switch() which
999 * will get the lock on the right CPU followed
1000 * by a call callout_cc_add() which will add it there.
1001 * (see above in softclock_call_cc()).
1003 cc_migration_cpu(cc, direct) = cpu;
1004 cc_migration_time(cc, direct) = to_sbt;
1005 cc_migration_prec(cc, direct) = precision;
1006 cc_migration_func(cc, direct) = ftn;
1007 cc_migration_arg(cc, direct) = arg;
1008 c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
1009 c->c_flags |= CALLOUT_ACTIVE;
1011 "migration of %p func %p arg %p in %d.%08x to %u deferred",
1012 c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1013 (u_int)(to_sbt & 0xffffffff), cpu);
1017 cc = callout_cpu_switch(c, cc, cpu);
1021 callout_cc_add(c, cc, to_sbt, precision, ftn, arg, flags);
1022 CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1023 cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1024 (u_int)(to_sbt & 0xffffffff));
1031 * Common idioms that can be optimized in the future.
1034 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1036 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1040 callout_schedule(struct callout *c, int to_ticks)
1042 return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1046 _callout_stop_safe(struct callout *c, int flags, callout_func_t *drain)
1048 struct callout_cpu *cc, *old_cc;
1049 struct lock_class *class;
1050 int direct, sq_locked, use_lock;
1051 int cancelled, not_on_a_list;
1053 if ((flags & CS_DRAIN) != 0)
1054 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
1055 "calling %s", __func__);
1057 KASSERT((flags & CS_DRAIN) == 0 || drain == NULL,
1058 ("Cannot set drain callback and CS_DRAIN flag at the same time"));
1061 * Some old subsystems don't hold Giant while running a callout_stop(),
1062 * so just discard this check for the moment.
1064 if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1065 if (c->c_lock == &Giant.lock_object)
1066 use_lock = mtx_owned(&Giant);
1069 class = LOCK_CLASS(c->c_lock);
1070 class->lc_assert(c->c_lock, LA_XLOCKED);
1074 if (c->c_iflags & CALLOUT_DIRECT) {
1082 cc = callout_lock(c);
1084 if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
1085 (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
1086 ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1088 * Special case where this slipped in while we
1089 * were migrating *as* the callout is about to
1090 * execute. The caller probably holds the lock
1091 * the callout wants.
1093 * Get rid of the migration first. Then set
1094 * the flag that tells this code *not* to
1095 * try to remove it from any lists (its not
1096 * on one yet). When the callout wheel runs,
1097 * it will ignore this callout.
1099 c->c_iflags &= ~CALLOUT_PENDING;
1100 c->c_flags &= ~CALLOUT_ACTIVE;
1107 * If the callout was migrating while the callout cpu lock was
1108 * dropped, just drop the sleepqueue lock and check the states
1111 if (sq_locked != 0 && cc != old_cc) {
1114 sleepq_release(&cc_exec_waiting(old_cc, direct));
1119 panic("migration should not happen");
1124 * If the callout is running, try to stop it or drain it.
1126 if (cc_exec_curr(cc, direct) == c) {
1128 * Succeed we to stop it or not, we must clear the
1129 * active flag - this is what API users expect. If we're
1130 * draining and the callout is currently executing, first wait
1131 * until it finishes.
1133 if ((flags & CS_DRAIN) == 0)
1134 c->c_flags &= ~CALLOUT_ACTIVE;
1136 if ((flags & CS_DRAIN) != 0) {
1138 * The current callout is running (or just
1139 * about to run) and blocking is allowed, so
1140 * just wait for the current invocation to
1143 if (cc_exec_curr(cc, direct) == c) {
1145 * Use direct calls to sleepqueue interface
1146 * instead of cv/msleep in order to avoid
1147 * a LOR between cc_lock and sleepqueue
1148 * chain spinlocks. This piece of code
1149 * emulates a msleep_spin() call actually.
1151 * If we already have the sleepqueue chain
1152 * locked, then we can safely block. If we
1153 * don't already have it locked, however,
1154 * we have to drop the cc_lock to lock
1155 * it. This opens several races, so we
1156 * restart at the beginning once we have
1157 * both locks. If nothing has changed, then
1158 * we will end up back here with sq_locked
1164 &cc_exec_waiting(cc, direct));
1171 * Migration could be cancelled here, but
1172 * as long as it is still not sure when it
1173 * will be packed up, just let softclock()
1176 cc_exec_waiting(cc, direct) = true;
1180 &cc_exec_waiting(cc, direct),
1181 &cc->cc_lock.lock_object, "codrain",
1184 &cc_exec_waiting(cc, direct),
1189 /* Reacquire locks previously released. */
1193 c->c_flags &= ~CALLOUT_ACTIVE;
1194 } else if (use_lock &&
1195 !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1198 * The current callout is waiting for its
1199 * lock which we hold. Cancel the callout
1200 * and return. After our caller drops the
1201 * lock, the callout will be skipped in
1202 * softclock(). This *only* works with a
1203 * callout_stop() *not* callout_drain() or
1204 * callout_async_drain().
1206 cc_exec_cancel(cc, direct) = true;
1207 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1208 c, c->c_func, c->c_arg);
1209 KASSERT(!cc_cce_migrating(cc, direct),
1210 ("callout wrongly scheduled for migration"));
1211 if (callout_migrating(c)) {
1212 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1214 cc_migration_cpu(cc, direct) = CPUBLOCK;
1215 cc_migration_time(cc, direct) = 0;
1216 cc_migration_prec(cc, direct) = 0;
1217 cc_migration_func(cc, direct) = NULL;
1218 cc_migration_arg(cc, direct) = NULL;
1222 KASSERT(!sq_locked, ("sleepqueue chain locked"));
1224 } else if (callout_migrating(c)) {
1226 * The callout is currently being serviced
1227 * and the "next" callout is scheduled at
1228 * its completion with a migration. We remove
1229 * the migration flag so it *won't* get rescheduled,
1230 * but we can't stop the one thats running so
1233 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1236 * We can't call cc_cce_cleanup here since
1237 * if we do it will remove .ce_curr and
1238 * its still running. This will prevent a
1239 * reschedule of the callout when the
1240 * execution completes.
1242 cc_migration_cpu(cc, direct) = CPUBLOCK;
1243 cc_migration_time(cc, direct) = 0;
1244 cc_migration_prec(cc, direct) = 0;
1245 cc_migration_func(cc, direct) = NULL;
1246 cc_migration_arg(cc, direct) = NULL;
1248 CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1249 c, c->c_func, c->c_arg);
1251 KASSERT(cc_exec_drain(cc, direct) == NULL,
1252 ("callout drain function already set to %p",
1253 cc_exec_drain(cc, direct)));
1254 cc_exec_drain(cc, direct) = drain;
1259 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1260 c, c->c_func, c->c_arg);
1262 KASSERT(cc_exec_drain(cc, direct) == NULL,
1263 ("callout drain function already set to %p",
1264 cc_exec_drain(cc, direct)));
1265 cc_exec_drain(cc, direct) = drain;
1268 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1274 sleepq_release(&cc_exec_waiting(cc, direct));
1276 if ((c->c_iflags & CALLOUT_PENDING) == 0) {
1277 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1278 c, c->c_func, c->c_arg);
1280 * For not scheduled and not executing callout return
1283 if (cc_exec_curr(cc, direct) != c)
1289 c->c_iflags &= ~CALLOUT_PENDING;
1290 c->c_flags &= ~CALLOUT_ACTIVE;
1292 CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1293 c, c->c_func, c->c_arg);
1294 if (not_on_a_list == 0) {
1295 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1296 if (cc_exec_next(cc) == c)
1297 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1298 LIST_REMOVE(c, c_links.le);
1300 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1308 callout_init(struct callout *c, int mpsafe)
1310 bzero(c, sizeof *c);
1313 c->c_iflags = CALLOUT_RETURNUNLOCKED;
1315 c->c_lock = &Giant.lock_object;
1318 c->c_cpu = cc_default_cpu;
1322 _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
1324 bzero(c, sizeof *c);
1326 KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1327 ("callout_init_lock: bad flags %d", flags));
1328 KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1329 ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1330 KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags & LC_SLEEPABLE),
1331 ("%s: callout %p has sleepable lock", __func__, c));
1332 c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1333 c->c_cpu = cc_default_cpu;
1337 flssbt(sbintime_t sbt)
1340 sbt += (uint64_t)sbt >> 1;
1341 if (sizeof(long) >= sizeof(sbintime_t))
1344 return (flsl(((uint64_t)sbt) >> 32) + 32);
1349 * Dump immediate statistic snapshot of the scheduled callouts.
1352 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1354 struct callout *tmp;
1355 struct callout_cpu *cc;
1356 struct callout_list *sc;
1357 sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1358 int ct[64], cpr[64], ccpbk[32];
1359 int error, val, i, count, tcum, pcum, maxc, c, medc;
1363 error = sysctl_handle_int(oidp, &val, 0, req);
1364 if (error != 0 || req->newptr == NULL)
1367 st = spr = maxt = maxpr = 0;
1368 bzero(ccpbk, sizeof(ccpbk));
1369 bzero(ct, sizeof(ct));
1370 bzero(cpr, sizeof(cpr));
1375 for (i = 0; i < callwheelsize; i++) {
1376 sc = &cc->cc_callwheel[i];
1378 LIST_FOREACH(tmp, sc, c_links.le) {
1380 t = tmp->c_time - now;
1384 spr += tmp->c_precision / SBT_1US;
1387 if (tmp->c_precision > maxpr)
1388 maxpr = tmp->c_precision;
1390 cpr[flssbt(tmp->c_precision)]++;
1394 ccpbk[fls(c + c / 2)]++;
1400 for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1402 medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1403 for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1405 medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1406 for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1408 medc = (i >= 2) ? (1 << (i - 2)) : 0;
1410 printf("Scheduled callouts statistic snapshot:\n");
1411 printf(" Callouts: %6d Buckets: %6d*%-3d Bucket size: 0.%06ds\n",
1412 count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1413 printf(" C/Bk: med %5d avg %6d.%06jd max %6d\n",
1415 count / callwheelsize / mp_ncpus,
1416 (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1418 printf(" Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1419 medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1420 (st / count) / 1000000, (st / count) % 1000000,
1421 maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1422 printf(" Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1423 medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1424 (spr / count) / 1000000, (spr / count) % 1000000,
1425 maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1426 printf(" Distribution: \tbuckets\t time\t tcum\t"
1428 for (i = 0, tcum = pcum = 0; i < 64; i++) {
1429 if (ct[i] == 0 && cpr[i] == 0)
1431 t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1434 printf(" %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1435 t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1436 i - 1 - (32 - CC_HASH_SHIFT),
1437 ct[i], tcum, cpr[i], pcum);
1441 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1442 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1443 0, 0, sysctl_kern_callout_stat, "I",
1444 "Dump immediate statistic snapshot of the scheduled callouts");
1448 _show_callout(struct callout *c)
1451 db_printf("callout %p\n", c);
1452 #define C_DB_PRINTF(f, e) db_printf(" %s = " f "\n", #e, c->e);
1453 db_printf(" &c_links = %p\n", &(c->c_links));
1454 C_DB_PRINTF("%" PRId64, c_time);
1455 C_DB_PRINTF("%" PRId64, c_precision);
1456 C_DB_PRINTF("%p", c_arg);
1457 C_DB_PRINTF("%p", c_func);
1458 C_DB_PRINTF("%p", c_lock);
1459 C_DB_PRINTF("%#x", c_flags);
1460 C_DB_PRINTF("%#x", c_iflags);
1461 C_DB_PRINTF("%d", c_cpu);
1465 DB_SHOW_COMMAND(callout, db_show_callout)
1469 db_printf("usage: show callout <struct callout *>\n");
1473 _show_callout((struct callout *)addr);
1477 _show_last_callout(int cpu, int direct, const char *dirstr)
1479 struct callout_cpu *cc;
1483 func = cc_exec_last_func(cc, direct);
1484 arg = cc_exec_last_arg(cc, direct);
1485 db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
1486 db_printsym((db_expr_t)func, DB_STGY_ANY);
1487 db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
1490 DB_SHOW_COMMAND(callout_last, db_show_callout_last)
1495 if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
1496 db_printf("no such cpu: %d\n", (int)addr);
1505 while (cpu <= last) {
1506 if (!CPU_ABSENT(cpu)) {
1507 _show_last_callout(cpu, 0, "");
1508 _show_last_callout(cpu, 1, " direct");