xref: /freebsd/sys/kern/kern_timeout.c (revision 5fc3104ae7389a0937f55af5157761c64b8a0668)
1df8bae1dSRodney W. Grimes /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1991, 1993
5df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
6df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
7df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
8df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
9df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
11df8bae1dSRodney W. Grimes  *
12df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
13df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
14df8bae1dSRodney W. Grimes  * are met:
15df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
17df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
18df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
19df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
2069a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
21df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
22df8bae1dSRodney W. Grimes  *    without specific prior written permission.
23df8bae1dSRodney W. Grimes  *
24df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
37677b542eSDavid E. O'Brien #include <sys/cdefs.h>
385b999a6bSDavide Italiano #include "opt_callout_profiling.h"
393af72c11SBjoern A. Zeeb #include "opt_ddb.h"
40c445c3c7SAdrian Chadd #include "opt_rss.h"
4191dd9aaeSRobert Watson 
42df8bae1dSRodney W. Grimes #include <sys/param.h>
43df8bae1dSRodney W. Grimes #include <sys/systm.h>
448d809d50SJeff Roberson #include <sys/bus.h>
4515b7a470SPoul-Henning Kamp #include <sys/callout.h>
4636d151a2SAlexander Motin #include <sys/domainset.h>
47f8ccf82aSAndre Oppermann #include <sys/file.h>
488d809d50SJeff Roberson #include <sys/interrupt.h>
49df8bae1dSRodney W. Grimes #include <sys/kernel.h>
50ff7ec58aSRobert Watson #include <sys/ktr.h>
5174cf7caeSJohn Baldwin #include <sys/kthread.h>
52f34fa851SJohn Baldwin #include <sys/lock.h>
538d809d50SJeff Roberson #include <sys/malloc.h>
54cb799bfeSJohn Baldwin #include <sys/mutex.h>
5521f9e816SJohn Baldwin #include <sys/proc.h>
56642701abSKyle Evans #include <sys/random.h>
5774cf7caeSJohn Baldwin #include <sys/sched.h>
5891dd9aaeSRobert Watson #include <sys/sdt.h>
596a0ce57dSAttilio Rao #include <sys/sleepqueue.h>
6022ee8c4fSPoul-Henning Kamp #include <sys/sysctl.h>
618d809d50SJeff Roberson #include <sys/smp.h>
6274cf7caeSJohn Baldwin #include <sys/unistd.h>
63df8bae1dSRodney W. Grimes 
643af72c11SBjoern A. Zeeb #ifdef DDB
653af72c11SBjoern A. Zeeb #include <ddb/ddb.h>
668c5a9161SEric van Gyzen #include <ddb/db_sym.h>
673af72c11SBjoern A. Zeeb #include <machine/_inttypes.h>
683af72c11SBjoern A. Zeeb #endif
693af72c11SBjoern A. Zeeb 
701283e9cdSAttilio Rao #ifdef SMP
711283e9cdSAttilio Rao #include <machine/cpu.h>
721283e9cdSAttilio Rao #endif
731283e9cdSAttilio Rao 
745b999a6bSDavide Italiano DPCPU_DECLARE(sbintime_t, hardclocktime);
755b999a6bSDavide Italiano 
7691dd9aaeSRobert Watson SDT_PROVIDER_DEFINE(callout_execute);
7736160958SMark Johnston SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
7836160958SMark Johnston SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
7991dd9aaeSRobert Watson 
8074cf7caeSJohn Baldwin static void	softclock_thread(void *arg);
8174cf7caeSJohn Baldwin 
825b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8322ee8c4fSPoul-Henning Kamp static int avg_depth;
8422ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8522ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
8622ee8c4fSPoul-Henning Kamp static int avg_gcalls;
8722ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
8822ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
8964b9ee20SAttilio Rao static int avg_lockcalls;
9064b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
9164b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
9222ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
9322ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
9422ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
955b999a6bSDavide Italiano static int avg_depth_dir;
965b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
975b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
985b999a6bSDavide Italiano     "Units = 1/1000");
995b999a6bSDavide Italiano static int avg_lockcalls_dir;
1005b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
1015b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
1025b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
1035b999a6bSDavide Italiano static int avg_mpcalls_dir;
1045b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1055b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1065b999a6bSDavide Italiano     "Units = 1/1000");
1075b999a6bSDavide Italiano #endif
108f8ccf82aSAndre Oppermann 
109f8ccf82aSAndre Oppermann static int ncallout;
110af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
111f8ccf82aSAndre Oppermann     "Number of entries in callwheel and size of timeout() preallocation");
112f8ccf82aSAndre Oppermann 
113c445c3c7SAdrian Chadd #ifdef	RSS
114c445c3c7SAdrian Chadd static int pin_default_swi = 1;
115c445c3c7SAdrian Chadd static int pin_pcpu_swi = 1;
116c445c3c7SAdrian Chadd #else
117ac75ee9fSAdrian Chadd static int pin_default_swi = 0;
118ac75ee9fSAdrian Chadd static int pin_pcpu_swi = 0;
119c445c3c7SAdrian Chadd #endif
120ac75ee9fSAdrian Chadd 
121af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
122ac75ee9fSAdrian Chadd     0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
123af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
124a212f56dSPiotr Pawel Stefaniak     0, "Pin the per-CPU swis (except PCPU 0, which is also default)");
125ac75ee9fSAdrian Chadd 
12615b7a470SPoul-Henning Kamp /*
12715b7a470SPoul-Henning Kamp  * TODO:
12815b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
12915b7a470SPoul-Henning Kamp  */
13061322a0aSAlexander Motin static u_int __read_mostly callwheelsize;
13161322a0aSAlexander Motin static u_int __read_mostly callwheelmask;
132f23b4c91SGarrett Wollman 
13320c510f8SLuigi Rizzo /*
134a115fb62SHans Petter Selasky  * The callout cpu exec entities represent informations necessary for
135a115fb62SHans Petter Selasky  * describing the state of callouts currently running on the CPU and the ones
136a115fb62SHans Petter Selasky  * necessary for migrating callouts to the new callout cpu. In particular,
137a115fb62SHans Petter Selasky  * the first entry of the array cc_exec_entity holds informations for callout
138a115fb62SHans Petter Selasky  * running in SWI thread context, while the second one holds informations
139a115fb62SHans Petter Selasky  * for callout running directly from hardware interrupt context.
140a115fb62SHans Petter Selasky  * The cached informations are very important for deferring migration when
141a115fb62SHans Petter Selasky  * the migrating callout is already running.
1421283e9cdSAttilio Rao  */
1435b999a6bSDavide Italiano struct cc_exec {
1445b999a6bSDavide Italiano 	struct callout		*cc_curr;
1458c5a9161SEric van Gyzen 	void			*cc_last_func;
1468c5a9161SEric van Gyzen 	void			*cc_last_arg;
147a115fb62SHans Petter Selasky #ifdef SMP
148a8a03706SJohn Baldwin 	callout_func_t		*ce_migration_func;
149a115fb62SHans Petter Selasky 	void			*ce_migration_arg;
150a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_time;
151a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_prec;
1528c5a9161SEric van Gyzen 	int			ce_migration_cpu;
153a115fb62SHans Petter Selasky #endif
154a4a3ce99SDavide Italiano 	bool			cc_cancel;
155a115fb62SHans Petter Selasky 	bool			cc_waiting;
1561283e9cdSAttilio Rao };
1571283e9cdSAttilio Rao 
1581283e9cdSAttilio Rao /*
159a115fb62SHans Petter Selasky  * There is one struct callout_cpu per cpu, holding all relevant
16020c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
16120c510f8SLuigi Rizzo  */
1628d809d50SJeff Roberson struct callout_cpu {
1634ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1645b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
16566525b2dSRandall Stewart 	struct callout		*cc_next;
1665b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1675b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1685b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1695b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
17074cf7caeSJohn Baldwin 	struct thread		*cc_thread;
1715b999a6bSDavide Italiano 	u_int			cc_bucket;
172329377f4SGleb Smirnoff #ifdef KTR
173232e8b52SJohn Baldwin 	char			cc_ktr_event_name[20];
174329377f4SGleb Smirnoff #endif
1758d809d50SJeff Roberson };
1768d809d50SJeff Roberson 
177403df7a6SRandall Stewart #define	callout_migrating(c)	((c)->c_iflags & CALLOUT_DFRMIGRATION)
178403df7a6SRandall Stewart 
179d2854fa4SRandall Stewart #define	cc_exec_curr(cc, dir)		cc->cc_exec_entity[dir].cc_curr
1808c5a9161SEric van Gyzen #define	cc_exec_last_func(cc, dir)	cc->cc_exec_entity[dir].cc_last_func
1818c5a9161SEric van Gyzen #define	cc_exec_last_arg(cc, dir)	cc->cc_exec_entity[dir].cc_last_arg
18266525b2dSRandall Stewart #define	cc_exec_next(cc)		cc->cc_next
183d2854fa4SRandall Stewart #define	cc_exec_cancel(cc, dir)		cc->cc_exec_entity[dir].cc_cancel
184d2854fa4SRandall Stewart #define	cc_exec_waiting(cc, dir)	cc->cc_exec_entity[dir].cc_waiting
1858d809d50SJeff Roberson #ifdef SMP
186d2854fa4SRandall Stewart #define	cc_migration_func(cc, dir)	cc->cc_exec_entity[dir].ce_migration_func
187d2854fa4SRandall Stewart #define	cc_migration_arg(cc, dir)	cc->cc_exec_entity[dir].ce_migration_arg
188d2854fa4SRandall Stewart #define	cc_migration_cpu(cc, dir)	cc->cc_exec_entity[dir].ce_migration_cpu
189d2854fa4SRandall Stewart #define	cc_migration_time(cc, dir)	cc->cc_exec_entity[dir].ce_migration_time
190d2854fa4SRandall Stewart #define	cc_migration_prec(cc, dir)	cc->cc_exec_entity[dir].ce_migration_prec
191a115fb62SHans Petter Selasky 
19278cfa762SMark Johnston DPCPU_DEFINE_STATIC(struct callout_cpu, cc_cpu);
1931283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
19478cfa762SMark Johnston #define	CC_CPU(cpu)	DPCPU_ID_PTR(cpu, cc_cpu)
1958d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
1968d809d50SJeff Roberson #else
197c1aff72cSMark Johnston static struct callout_cpu cc_cpu;
198c1aff72cSMark Johnston #define	CC_CPU(cpu)	(&cc_cpu)
199c1aff72cSMark Johnston #define	CC_SELF()	(&cc_cpu)
2008d809d50SJeff Roberson #endif
2018d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
2028d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
2031283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
2048d809d50SJeff Roberson 
2054b28d96eSJohn Baldwin static int __read_mostly cc_default_cpu;
2065b999a6bSDavide Italiano 
207232e8b52SJohn Baldwin static void	callout_cpu_init(struct callout_cpu *cc, int cpu);
2085b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
2095b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
2105b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
2115b999a6bSDavide Italiano #endif
2125b999a6bSDavide Italiano 		    int direct);
2138d809d50SJeff Roberson 
214d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
21549a74476SColin Percival 
216a115fb62SHans Petter Selasky /**
217a115fb62SHans Petter Selasky  * Locked by cc_lock:
218a115fb62SHans Petter Selasky  *   cc_curr         - If a callout is in progress, it is cc_curr.
219a115fb62SHans Petter Selasky  *                     If cc_curr is non-NULL, threads waiting in
220a115fb62SHans Petter Selasky  *                     callout_drain() will be woken up as soon as the
221a115fb62SHans Petter Selasky  *                     relevant callout completes.
222a115fb62SHans Petter Selasky  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
223a115fb62SHans Petter Selasky  *                     guarantees that the current callout will not run.
22474cf7caeSJohn Baldwin  *                     The softclock_call_cc() function sets this to 0 before it
225a115fb62SHans Petter Selasky  *                     drops callout_lock to acquire c_lock, and it calls
226a115fb62SHans Petter Selasky  *                     the handler only if curr_cancelled is still 0 after
227a115fb62SHans Petter Selasky  *                     cc_lock is successfully acquired.
228a115fb62SHans Petter Selasky  *   cc_waiting      - If a thread is waiting in callout_drain(), then
229a115fb62SHans Petter Selasky  *                     callout_wait is nonzero.  Set only when
230a115fb62SHans Petter Selasky  *                     cc_curr is non-NULL.
231a115fb62SHans Petter Selasky  */
232a115fb62SHans Petter Selasky 
233df8bae1dSRodney W. Grimes /*
234a115fb62SHans Petter Selasky  * Resets the execution entity tied to a specific callout cpu.
235a115fb62SHans Petter Selasky  */
236a115fb62SHans Petter Selasky static void
237a115fb62SHans Petter Selasky cc_cce_cleanup(struct callout_cpu *cc, int direct)
238a115fb62SHans Petter Selasky {
239a115fb62SHans Petter Selasky 
240d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
241d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
242d2854fa4SRandall Stewart 	cc_exec_waiting(cc, direct) = false;
243a115fb62SHans Petter Selasky #ifdef SMP
244d2854fa4SRandall Stewart 	cc_migration_cpu(cc, direct) = CPUBLOCK;
245d2854fa4SRandall Stewart 	cc_migration_time(cc, direct) = 0;
246d2854fa4SRandall Stewart 	cc_migration_prec(cc, direct) = 0;
247d2854fa4SRandall Stewart 	cc_migration_func(cc, direct) = NULL;
248d2854fa4SRandall Stewart 	cc_migration_arg(cc, direct) = NULL;
249a115fb62SHans Petter Selasky #endif
250a115fb62SHans Petter Selasky }
251a115fb62SHans Petter Selasky 
252a115fb62SHans Petter Selasky /*
253a115fb62SHans Petter Selasky  * Checks if migration is requested by a specific callout cpu.
254a115fb62SHans Petter Selasky  */
255a115fb62SHans Petter Selasky static int
256a115fb62SHans Petter Selasky cc_cce_migrating(struct callout_cpu *cc, int direct)
257a115fb62SHans Petter Selasky {
258a115fb62SHans Petter Selasky 
259a115fb62SHans Petter Selasky #ifdef SMP
260d2854fa4SRandall Stewart 	return (cc_migration_cpu(cc, direct) != CPUBLOCK);
261a115fb62SHans Petter Selasky #else
262a115fb62SHans Petter Selasky 	return (0);
263a115fb62SHans Petter Selasky #endif
264a115fb62SHans Petter Selasky }
265a115fb62SHans Petter Selasky 
266a115fb62SHans Petter Selasky /*
267a115fb62SHans Petter Selasky  * Kernel low level callwheel initialization
268efe67753SNathan Whitehorn  * called on the BSP during kernel startup.
269219d632cSMatthew Dillon  */
27015ae0c9aSAndre Oppermann static void
27115ae0c9aSAndre Oppermann callout_callwheel_init(void *dummy)
272219d632cSMatthew Dillon {
2738d809d50SJeff Roberson 	struct callout_cpu *cc;
2744b28d96eSJohn Baldwin 	int cpu;
2758d809d50SJeff Roberson 
276f8ccf82aSAndre Oppermann 	/*
277f8ccf82aSAndre Oppermann 	 * Calculate the size of the callout wheel and the preallocated
278f8ccf82aSAndre Oppermann 	 * timeout() structures.
279a7aea132SAndre Oppermann 	 * XXX: Clip callout to result of previous function of maxusers
280a7aea132SAndre Oppermann 	 * maximum 384.  This is still huge, but acceptable.
281f8ccf82aSAndre Oppermann 	 */
282f8ccf82aSAndre Oppermann 	ncallout = imin(16 + maxproc + maxfiles, 18508);
283f8ccf82aSAndre Oppermann 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
284f8ccf82aSAndre Oppermann 
285219d632cSMatthew Dillon 	/*
286922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
287922314f0SAlfred Perlstein 	 * than 'ncallout'.
288219d632cSMatthew Dillon 	 */
289922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
290219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
291219d632cSMatthew Dillon 
29215ae0c9aSAndre Oppermann 	/*
293ac75ee9fSAdrian Chadd 	 * Fetch whether we're pinning the swi's or not.
294ac75ee9fSAdrian Chadd 	 */
295ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
296ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
297ac75ee9fSAdrian Chadd 
298ac75ee9fSAdrian Chadd 	/*
2994b28d96eSJohn Baldwin 	 * Initialize callout wheels.  The software interrupt threads
3004b28d96eSJohn Baldwin 	 * are created later.
30115ae0c9aSAndre Oppermann 	 */
3024b28d96eSJohn Baldwin 	cc_default_cpu = PCPU_GET(cpuid);
3034b28d96eSJohn Baldwin 	CPU_FOREACH(cpu) {
3044b28d96eSJohn Baldwin 		cc = CC_CPU(cpu);
3054b28d96eSJohn Baldwin 		callout_cpu_init(cc, cpu);
3064b28d96eSJohn Baldwin 	}
307219d632cSMatthew Dillon }
30815ae0c9aSAndre Oppermann SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
309219d632cSMatthew Dillon 
31015ae0c9aSAndre Oppermann /*
31115ae0c9aSAndre Oppermann  * Initialize the per-cpu callout structures.
31215ae0c9aSAndre Oppermann  */
3138d809d50SJeff Roberson static void
314232e8b52SJohn Baldwin callout_cpu_init(struct callout_cpu *cc, int cpu)
3158d809d50SJeff Roberson {
3168d809d50SJeff Roberson 	int i;
3178d809d50SJeff Roberson 
3182c0209a2SMark Johnston 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN);
31936d151a2SAlexander Motin 	cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
32036d151a2SAlexander Motin 	    callwheelsize, M_CALLOUT,
32136d151a2SAlexander Motin 	    DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
3225b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
3235b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
3245b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
3254bc38a5aSDavide Italiano 	cc->cc_firstevent = SBT_MAX;
326a115fb62SHans Petter Selasky 	for (i = 0; i < 2; i++)
327a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, i);
328329377f4SGleb Smirnoff #ifdef KTR
329232e8b52SJohn Baldwin 	snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
330232e8b52SJohn Baldwin 	    "callwheel cpu %d", cpu);
331329377f4SGleb Smirnoff #endif
3328d809d50SJeff Roberson }
3338d809d50SJeff Roberson 
334a115fb62SHans Petter Selasky #ifdef SMP
335a115fb62SHans Petter Selasky /*
336a115fb62SHans Petter Selasky  * Switches the cpu tied to a specific callout.
337a115fb62SHans Petter Selasky  * The function expects a locked incoming callout cpu and returns with
338a115fb62SHans Petter Selasky  * locked outcoming callout cpu.
339a115fb62SHans Petter Selasky  */
340a115fb62SHans Petter Selasky static struct callout_cpu *
341a115fb62SHans Petter Selasky callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
342a115fb62SHans Petter Selasky {
343a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
344a115fb62SHans Petter Selasky 
345a115fb62SHans Petter Selasky 	MPASS(c != NULL && cc != NULL);
346a115fb62SHans Petter Selasky 	CC_LOCK_ASSERT(cc);
347a115fb62SHans Petter Selasky 
348a115fb62SHans Petter Selasky 	/*
349a115fb62SHans Petter Selasky 	 * Avoid interrupts and preemption firing after the callout cpu
350a115fb62SHans Petter Selasky 	 * is blocked in order to avoid deadlocks as the new thread
351a115fb62SHans Petter Selasky 	 * may be willing to acquire the callout cpu lock.
352a115fb62SHans Petter Selasky 	 */
353a115fb62SHans Petter Selasky 	c->c_cpu = CPUBLOCK;
354a115fb62SHans Petter Selasky 	spinlock_enter();
355a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
356a115fb62SHans Petter Selasky 	new_cc = CC_CPU(new_cpu);
357a115fb62SHans Petter Selasky 	CC_LOCK(new_cc);
358a115fb62SHans Petter Selasky 	spinlock_exit();
359a115fb62SHans Petter Selasky 	c->c_cpu = new_cpu;
360a115fb62SHans Petter Selasky 	return (new_cc);
361a115fb62SHans Petter Selasky }
362a115fb62SHans Petter Selasky #endif
363a115fb62SHans Petter Selasky 
364219d632cSMatthew Dillon /*
3654b28d96eSJohn Baldwin  * Start softclock threads.
3668d809d50SJeff Roberson  */
3678d809d50SJeff Roberson static void
3688d809d50SJeff Roberson start_softclock(void *dummy)
3698d809d50SJeff Roberson {
37074cf7caeSJohn Baldwin 	struct proc *p;
37174cf7caeSJohn Baldwin 	struct thread *td;
3728d809d50SJeff Roberson 	struct callout_cpu *cc;
37374cf7caeSJohn Baldwin 	int cpu, error;
3744b28d96eSJohn Baldwin 	bool pin_swi;
3758d809d50SJeff Roberson 
37674cf7caeSJohn Baldwin 	p = NULL;
3773aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
3788d809d50SJeff Roberson 		cc = CC_CPU(cpu);
37974cf7caeSJohn Baldwin 		error = kproc_kthread_add(softclock_thread, cc, &p, &td,
38074cf7caeSJohn Baldwin 		    RFSTOPPED, 0, "clock", "clock (%d)", cpu);
38174cf7caeSJohn Baldwin 		if (error != 0)
38274cf7caeSJohn Baldwin 			panic("failed to create softclock thread for cpu %d: %d",
38374cf7caeSJohn Baldwin 			    cpu, error);
38474cf7caeSJohn Baldwin 		CC_LOCK(cc);
38574cf7caeSJohn Baldwin 		cc->cc_thread = td;
38674cf7caeSJohn Baldwin 		thread_lock(td);
38774cf7caeSJohn Baldwin 		sched_class(td, PRI_ITHD);
388fea89a28SJohn Baldwin 		sched_ithread_prio(td, PI_SOFTCLOCK);
38974cf7caeSJohn Baldwin 		TD_SET_IWAIT(td);
39074cf7caeSJohn Baldwin 		thread_lock_set(td, (struct mtx *)&cc->cc_lock);
39174cf7caeSJohn Baldwin 		thread_unlock(td);
3924b28d96eSJohn Baldwin 		if (cpu == cc_default_cpu)
3934b28d96eSJohn Baldwin 			pin_swi = pin_default_swi;
3944b28d96eSJohn Baldwin 		else
3954b28d96eSJohn Baldwin 			pin_swi = pin_pcpu_swi;
39674cf7caeSJohn Baldwin 		if (pin_swi) {
39774cf7caeSJohn Baldwin 			error = cpuset_setithread(td->td_tid, cpu);
39874cf7caeSJohn Baldwin 			if (error != 0)
39974cf7caeSJohn Baldwin 				printf("%s: %s clock couldn't be pinned to cpu %d: %d\n",
40074cf7caeSJohn Baldwin 				    __func__, cpu == cc_default_cpu ?
40174cf7caeSJohn Baldwin 				    "default" : "per-cpu", cpu, error);
402ac75ee9fSAdrian Chadd 		}
403219d632cSMatthew Dillon 	}
404219d632cSMatthew Dillon }
4058d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
4068d809d50SJeff Roberson 
4075b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
4088d809d50SJeff Roberson 
4095b999a6bSDavide Italiano static inline u_int
4105b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
4115b999a6bSDavide Italiano {
4125b999a6bSDavide Italiano 
4135b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
4145b999a6bSDavide Italiano }
4155b999a6bSDavide Italiano 
4165b999a6bSDavide Italiano static inline u_int
4175b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
4185b999a6bSDavide Italiano {
4195b999a6bSDavide Italiano 
4205b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
4215b999a6bSDavide Italiano }
4225b999a6bSDavide Italiano 
4235b999a6bSDavide Italiano void
4245b999a6bSDavide Italiano callout_process(sbintime_t now)
4255b999a6bSDavide Italiano {
426642701abSKyle Evans 	struct callout_entropy {
427642701abSKyle Evans 		struct callout_cpu *cc;
428642701abSKyle Evans 		struct thread *td;
429642701abSKyle Evans 		sbintime_t now;
430642701abSKyle Evans 	} entropy;
43146eab860SMark Johnston 	struct callout *c, *next;
4325b999a6bSDavide Italiano 	struct callout_cpu *cc;
4335b999a6bSDavide Italiano 	struct callout_list *sc;
43474cf7caeSJohn Baldwin 	struct thread *td;
435cb1f5d11SAlexander Motin 	sbintime_t first, last, lookahead, max, tmp_max;
4365b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
4375b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4385b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
4395b999a6bSDavide Italiano #endif
440a115fb62SHans Petter Selasky 
4418d809d50SJeff Roberson 	cc = CC_SELF();
442a115fb62SHans Petter Selasky 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4435b999a6bSDavide Italiano 
4445b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4455b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4465b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4475b999a6bSDavide Italiano 	nowb = callout_hash(now);
4485b999a6bSDavide Italiano 
4495b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4505b999a6bSDavide Italiano 	if (nowb == firstb)
4515b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4525b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4535b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4545b999a6bSDavide Italiano 	else
455cb1f5d11SAlexander Motin 		lookahead = SBT_1S;
4565b999a6bSDavide Italiano 	first = last = now;
4575b999a6bSDavide Italiano 	first += (lookahead / 2);
4585b999a6bSDavide Italiano 	last += lookahead;
4595b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4605b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4615b999a6bSDavide Italiano 	max = last;
4625b999a6bSDavide Italiano 
4635b999a6bSDavide Italiano 	/*
4645b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4655b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4665b999a6bSDavide Italiano 	 */
4675b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4685b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4695b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4705b999a6bSDavide Italiano 			nowb = lastb;
4719fc51b0bSJeff Roberson 	}
4725b999a6bSDavide Italiano 
4735b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4745b999a6bSDavide Italiano 	do {
4755b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
47646eab860SMark Johnston 		LIST_FOREACH_SAFE(c, sc, c_links.le, next) {
4775b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
47846eab860SMark Johnston 			if (c->c_time <= now) {
4795b999a6bSDavide Italiano 				/*
4805b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
4815b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
4825b999a6bSDavide Italiano 				 */
48346eab860SMark Johnston 				if (c->c_iflags & CALLOUT_DIRECT) {
4845b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4855b999a6bSDavide Italiano 					++depth_dir;
4865b999a6bSDavide Italiano #endif
48746eab860SMark Johnston 					cc_exec_next(cc) = next;
4885b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
48946eab860SMark Johnston 					LIST_REMOVE(c, c_links.le);
49046eab860SMark Johnston 					softclock_call_cc(c, cc,
4915b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4925b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
4935b999a6bSDavide Italiano #endif
4945b999a6bSDavide Italiano 					    1);
49546eab860SMark Johnston 					next = cc_exec_next(cc);
49666525b2dSRandall Stewart 					cc_exec_next(cc) = NULL;
4975b999a6bSDavide Italiano 				} else {
49846eab860SMark Johnston 					LIST_REMOVE(c, c_links.le);
4995b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
50046eab860SMark Johnston 					    c, c_links.tqe);
50146eab860SMark Johnston 					c->c_iflags |= CALLOUT_PROCESSED;
5029fc51b0bSJeff Roberson 				}
50346eab860SMark Johnston 			} else if (c->c_time >= max) {
5045b999a6bSDavide Italiano 				/*
50546eab860SMark Johnston 				 * Skip events in the distant future.
5065b999a6bSDavide Italiano 				 */
50746eab860SMark Johnston 				;
50846eab860SMark Johnston 			} else if (c->c_time > last) {
50946eab860SMark Johnston 				/*
51046eab860SMark Johnston 				 * Event minimal time is bigger than present
51146eab860SMark Johnston 				 * maximal time, so it cannot be aggregated.
51246eab860SMark Johnston 				 */
5135b999a6bSDavide Italiano 				lastb = nowb;
51446eab860SMark Johnston 			} else {
51546eab860SMark Johnston 				/*
51646eab860SMark Johnston 				 * Update first and last time, respecting this
51746eab860SMark Johnston 				 * event.
51846eab860SMark Johnston 				 */
51946eab860SMark Johnston 				if (c->c_time < first)
52046eab860SMark Johnston 					first = c->c_time;
52146eab860SMark Johnston 				tmp_max = c->c_time + c->c_precision;
5225b999a6bSDavide Italiano 				if (tmp_max < last)
5235b999a6bSDavide Italiano 					last = tmp_max;
52446eab860SMark Johnston 			}
5255b999a6bSDavide Italiano 		}
5265b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
5275b999a6bSDavide Italiano 		firstb++;
5285b999a6bSDavide Italiano 		/*
5295b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
5305b999a6bSDavide Italiano 		 * some event we can't execute at now.
5315b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
5325b999a6bSDavide Italiano 		 */
5335b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
5345b999a6bSDavide Italiano 	cc->cc_firstevent = last;
5355b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
536a28c28e6SMark Johnston 
5375b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5385b999a6bSDavide Italiano 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
5395b999a6bSDavide Italiano 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
5405b999a6bSDavide Italiano 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
5415b999a6bSDavide Italiano #endif
54274cf7caeSJohn Baldwin 	if (!TAILQ_EMPTY(&cc->cc_expireq)) {
543642701abSKyle Evans 		entropy.cc = cc;
544642701abSKyle Evans 		entropy.td = curthread;
545642701abSKyle Evans 		entropy.now = now;
546642701abSKyle Evans 		random_harvest_queue(&entropy, sizeof(entropy), RANDOM_CALLOUT);
547642701abSKyle Evans 
54874cf7caeSJohn Baldwin 		td = cc->cc_thread;
54974cf7caeSJohn Baldwin 		if (TD_AWAITING_INTR(td)) {
5506b95cf5bSMark Johnston 			thread_lock_block_wait(td);
5516b95cf5bSMark Johnston 			THREAD_LOCK_ASSERT(td, MA_OWNED);
55274cf7caeSJohn Baldwin 			TD_CLR_IWAIT(td);
553ed998d1cSJohn Baldwin 			sched_wakeup(td, SRQ_INTR);
55474cf7caeSJohn Baldwin 		} else
555a115fb62SHans Petter Selasky 			mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
55674cf7caeSJohn Baldwin 	} else
55774cf7caeSJohn Baldwin 		mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5588d809d50SJeff Roberson }
5598d809d50SJeff Roberson 
5608d809d50SJeff Roberson static struct callout_cpu *
5618d809d50SJeff Roberson callout_lock(struct callout *c)
5628d809d50SJeff Roberson {
5638d809d50SJeff Roberson 	struct callout_cpu *cc;
564a115fb62SHans Petter Selasky 	int cpu;
565a115fb62SHans Petter Selasky 
566a115fb62SHans Petter Selasky 	for (;;) {
567a115fb62SHans Petter Selasky 		cpu = c->c_cpu;
568a115fb62SHans Petter Selasky #ifdef SMP
569a115fb62SHans Petter Selasky 		if (cpu == CPUBLOCK) {
570a115fb62SHans Petter Selasky 			while (c->c_cpu == CPUBLOCK)
571a115fb62SHans Petter Selasky 				cpu_spinwait();
572a115fb62SHans Petter Selasky 			continue;
573a115fb62SHans Petter Selasky 		}
574a115fb62SHans Petter Selasky #endif
575a115fb62SHans Petter Selasky 		cc = CC_CPU(cpu);
5768d809d50SJeff Roberson 		CC_LOCK(cc);
577a115fb62SHans Petter Selasky 		if (cpu == c->c_cpu)
578a115fb62SHans Petter Selasky 			break;
579a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
580a115fb62SHans Petter Selasky 	}
5818d809d50SJeff Roberson 	return (cc);
582219d632cSMatthew Dillon }
583219d632cSMatthew Dillon 
584a115fb62SHans Petter Selasky static void
585a115fb62SHans Petter Selasky callout_cc_add(struct callout *c, struct callout_cpu *cc,
586a115fb62SHans Petter Selasky     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
587aac7c7acSMark Johnston     void *arg, int flags)
5881283e9cdSAttilio Rao {
5895b999a6bSDavide Italiano 	int bucket;
5901283e9cdSAttilio Rao 
5911283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
592a115fb62SHans Petter Selasky 	if (sbt < cc->cc_lastscan)
593a115fb62SHans Petter Selasky 		sbt = cc->cc_lastscan;
594a115fb62SHans Petter Selasky 	c->c_arg = arg;
59515b1eb14SRandall Stewart 	c->c_iflags |= CALLOUT_PENDING;
59615b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PROCESSED;
59715b1eb14SRandall Stewart 	c->c_flags |= CALLOUT_ACTIVE;
59807a2df5dSRandall Stewart 	if (flags & C_DIRECT_EXEC)
599b132edb5SRandall Stewart 		c->c_iflags |= CALLOUT_DIRECT;
600a115fb62SHans Petter Selasky 	c->c_func = func;
601a115fb62SHans Petter Selasky 	c->c_time = sbt;
602a115fb62SHans Petter Selasky 	c->c_precision = precision;
6035b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
6045b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
6055b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
6065b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
6075b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
6085b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
60966525b2dSRandall Stewart 		cc_exec_next(cc) = c;
610a28c28e6SMark Johnston 
6115b999a6bSDavide Italiano 	/*
6125b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
6135b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
6145b999a6bSDavide Italiano 	 */
6154bc38a5aSDavide Italiano 	if (SBT_MAX - c->c_time < c->c_precision)
6164bc38a5aSDavide Italiano 		c->c_precision = SBT_MAX - c->c_time;
6175b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
6185b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
6195b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
620aac7c7acSMark Johnston 		cpu_new_callout(c->c_cpu, sbt, c->c_time);
6211283e9cdSAttilio Rao 	}
6221283e9cdSAttilio Rao }
6231283e9cdSAttilio Rao 
6246098e7acSKonstantin Belousov static void
6255b999a6bSDavide Italiano softclock_call_cc(struct callout *c, struct callout_cpu *cc,
6265b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6275b999a6bSDavide Italiano     int *mpcalls, int *lockcalls, int *gcalls,
6285b999a6bSDavide Italiano #endif
6295b999a6bSDavide Italiano     int direct)
6306098e7acSKonstantin Belousov {
631a115fb62SHans Petter Selasky 	struct rm_priotracker tracker;
632*5fc3104aSGleb Smirnoff 	callout_func_t *c_func;
6336098e7acSKonstantin Belousov 	void *c_arg;
634a115fb62SHans Petter Selasky 	struct lock_class *class;
6356098e7acSKonstantin Belousov 	struct lock_object *c_lock;
636a115fb62SHans Petter Selasky 	uintptr_t lock_status;
63715b1eb14SRandall Stewart 	int c_iflags;
638a115fb62SHans Petter Selasky #ifdef SMP
639a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
640a8a03706SJohn Baldwin 	callout_func_t *new_func;
641a115fb62SHans Petter Selasky 	void *new_arg;
642a115fb62SHans Petter Selasky 	int flags, new_cpu;
643a115fb62SHans Petter Selasky 	sbintime_t new_prec, new_time;
644a115fb62SHans Petter Selasky #endif
6455b999a6bSDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
64603763781SDavide Italiano 	sbintime_t sbt1, sbt2;
6476098e7acSKonstantin Belousov 	struct timespec ts2;
6485b999a6bSDavide Italiano 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
649a8a03706SJohn Baldwin 	static callout_func_t *lastfunc;
6506098e7acSKonstantin Belousov #endif
6516098e7acSKonstantin Belousov 
65215b1eb14SRandall Stewart 	KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
65315b1eb14SRandall Stewart 	    ("softclock_call_cc: pend %p %x", c, c->c_iflags));
65415b1eb14SRandall Stewart 	KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
65515b1eb14SRandall Stewart 	    ("softclock_call_cc: act %p %x", c, c->c_flags));
656a115fb62SHans Petter Selasky 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
657a115fb62SHans Petter Selasky 	lock_status = 0;
658a879e40cSKristof Provost 	if (c->c_iflags & CALLOUT_SHAREDLOCK) {
659a115fb62SHans Petter Selasky 		if (class == &lock_class_rm)
660a115fb62SHans Petter Selasky 			lock_status = (uintptr_t)&tracker;
661a115fb62SHans Petter Selasky 		else
662a115fb62SHans Petter Selasky 			lock_status = 1;
663a115fb62SHans Petter Selasky 	}
6646098e7acSKonstantin Belousov 	c_lock = c->c_lock;
6656098e7acSKonstantin Belousov 	c_func = c->c_func;
6666098e7acSKonstantin Belousov 	c_arg = c->c_arg;
66715b1eb14SRandall Stewart 	c_iflags = c->c_iflags;
66815b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
669d2854fa4SRandall Stewart 
670d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = c;
6718c5a9161SEric van Gyzen 	cc_exec_last_func(cc, direct) = c_func;
6728c5a9161SEric van Gyzen 	cc_exec_last_arg(cc, direct) = c_arg;
673d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
6746098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
675a115fb62SHans Petter Selasky 	if (c_lock != NULL) {
676a115fb62SHans Petter Selasky 		class->lc_lock(c_lock, lock_status);
6776098e7acSKonstantin Belousov 		/*
678a115fb62SHans Petter Selasky 		 * The callout may have been cancelled
679a115fb62SHans Petter Selasky 		 * while we switched locks.
6806098e7acSKonstantin Belousov 		 */
681d2854fa4SRandall Stewart 		if (cc_exec_cancel(cc, direct)) {
682a115fb62SHans Petter Selasky 			class->lc_unlock(c_lock);
683a115fb62SHans Petter Selasky 			goto skip;
6846098e7acSKonstantin Belousov 		}
685a115fb62SHans Petter Selasky 		/* The callout cannot be stopped now. */
686d2854fa4SRandall Stewart 		cc_exec_cancel(cc, direct) = true;
6876098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
6885b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6896098e7acSKonstantin Belousov 			(*gcalls)++;
6905b999a6bSDavide Italiano #endif
6915b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
6926098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6936098e7acSKonstantin Belousov 		} else {
6945b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6956098e7acSKonstantin Belousov 			(*lockcalls)++;
6965b999a6bSDavide Italiano #endif
6976098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
6986098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6996098e7acSKonstantin Belousov 		}
7006098e7acSKonstantin Belousov 	} else {
7015b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7026098e7acSKonstantin Belousov 		(*mpcalls)++;
7035b999a6bSDavide Italiano #endif
7045b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
7056098e7acSKonstantin Belousov 		    c, c_func, c_arg);
7066098e7acSKonstantin Belousov 	}
707232e8b52SJohn Baldwin 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
708232e8b52SJohn Baldwin 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
70903763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
7105b999a6bSDavide Italiano 	sbt1 = sbinuptime();
7116098e7acSKonstantin Belousov #endif
7126098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
71336160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__start, c);
7146098e7acSKonstantin Belousov 	c_func(c_arg);
71536160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__end, c);
7166098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
71703763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
71803763781SDavide Italiano 	sbt2 = sbinuptime();
71903763781SDavide Italiano 	sbt2 -= sbt1;
72003763781SDavide Italiano 	if (sbt2 > maxdt) {
72103763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
72203763781SDavide Italiano 			ts2 = sbttots(sbt2);
7236098e7acSKonstantin Belousov 			printf(
7248965b303SMitchell Horne 		"Expensive callout(9) function: %p(%p) %jd.%09ld s\n",
7256098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
7266098e7acSKonstantin Belousov 		}
72703763781SDavide Italiano 		maxdt = sbt2;
7286098e7acSKonstantin Belousov 		lastfunc = c_func;
7296098e7acSKonstantin Belousov 	}
7306098e7acSKonstantin Belousov #endif
731232e8b52SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
7326098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
73315b1eb14SRandall Stewart 	if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
734a115fb62SHans Petter Selasky 		class->lc_unlock(c_lock);
735a115fb62SHans Petter Selasky skip:
7366098e7acSKonstantin Belousov 	CC_LOCK(cc);
737d2854fa4SRandall Stewart 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
738d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
739d2854fa4SRandall Stewart 	if (cc_exec_waiting(cc, direct)) {
740bdf9120cSAttilio Rao 		/*
741a115fb62SHans Petter Selasky 		 * There is someone waiting for the
742a115fb62SHans Petter Selasky 		 * callout to complete.
743a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
744a115fb62SHans Petter Selasky 		 * migration just cancel it.
745bdf9120cSAttilio Rao 		 */
746a115fb62SHans Petter Selasky 		if (cc_cce_migrating(cc, direct)) {
747a115fb62SHans Petter Selasky 			cc_cce_cleanup(cc, direct);
748a115fb62SHans Petter Selasky 
749a115fb62SHans Petter Selasky 			/*
750a115fb62SHans Petter Selasky 			 * It should be assert here that the callout is not
751a115fb62SHans Petter Selasky 			 * destroyed but that is not easy.
752a115fb62SHans Petter Selasky 			 */
75315b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
7546098e7acSKonstantin Belousov 		}
755d2854fa4SRandall Stewart 		cc_exec_waiting(cc, direct) = false;
756a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
757d2854fa4SRandall Stewart 		wakeup(&cc_exec_waiting(cc, direct));
758a115fb62SHans Petter Selasky 		CC_LOCK(cc);
759a115fb62SHans Petter Selasky 	} else if (cc_cce_migrating(cc, direct)) {
760a115fb62SHans Petter Selasky #ifdef SMP
761a115fb62SHans Petter Selasky 		/*
762a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
763a115fb62SHans Petter Selasky 		 * migration just perform it now.
764a115fb62SHans Petter Selasky 		 */
765d2854fa4SRandall Stewart 		new_cpu = cc_migration_cpu(cc, direct);
766d2854fa4SRandall Stewart 		new_time = cc_migration_time(cc, direct);
767d2854fa4SRandall Stewart 		new_prec = cc_migration_prec(cc, direct);
768d2854fa4SRandall Stewart 		new_func = cc_migration_func(cc, direct);
769d2854fa4SRandall Stewart 		new_arg = cc_migration_arg(cc, direct);
770a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, direct);
771a115fb62SHans Petter Selasky 
772a115fb62SHans Petter Selasky 		/*
773a115fb62SHans Petter Selasky 		 * It should be assert here that the callout is not destroyed
774a115fb62SHans Petter Selasky 		 * but that is not easy.
775a115fb62SHans Petter Selasky 		 *
776a115fb62SHans Petter Selasky 		 * As first thing, handle deferred callout stops.
777a115fb62SHans Petter Selasky 		 */
778d2854fa4SRandall Stewart 		if (!callout_migrating(c)) {
779a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT,
780a115fb62SHans Petter Selasky 			     "deferred cancelled %p func %p arg %p",
781a115fb62SHans Petter Selasky 			     c, new_func, new_arg);
782a115fb62SHans Petter Selasky 			return;
783a115fb62SHans Petter Selasky 		}
78415b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_DFRMIGRATION;
785a115fb62SHans Petter Selasky 
786a115fb62SHans Petter Selasky 		new_cc = callout_cpu_switch(c, cc, new_cpu);
787a115fb62SHans Petter Selasky 		flags = (direct) ? C_DIRECT_EXEC : 0;
788a115fb62SHans Petter Selasky 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
789aac7c7acSMark Johnston 		    new_arg, flags);
790a115fb62SHans Petter Selasky 		CC_UNLOCK(new_cc);
791a115fb62SHans Petter Selasky 		CC_LOCK(cc);
792a115fb62SHans Petter Selasky #else
793a115fb62SHans Petter Selasky 		panic("migration should not happen");
794a115fb62SHans Petter Selasky #endif
795a115fb62SHans Petter Selasky 	}
7966098e7acSKonstantin Belousov }
7976098e7acSKonstantin Belousov 
798219d632cSMatthew Dillon /*
799ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
800ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
801ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
802ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
803024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
804ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
805ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
806ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
807ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
808ab36c067SJustin T. Gibbs  */
809a50ec505SPoul-Henning Kamp 
810ab36c067SJustin T. Gibbs /*
81174cf7caeSJohn Baldwin  * Software (low priority) clock interrupt thread handler.
812df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
813df8bae1dSRodney W. Grimes  */
81474cf7caeSJohn Baldwin static void
81574cf7caeSJohn Baldwin softclock_thread(void *arg)
816df8bae1dSRodney W. Grimes {
81774cf7caeSJohn Baldwin 	struct thread *td = curthread;
8188d809d50SJeff Roberson 	struct callout_cpu *cc;
819b336df68SPoul-Henning Kamp 	struct callout *c;
8205b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
82174cf7caeSJohn Baldwin 	int depth, gcalls, lockcalls, mpcalls;
8225b999a6bSDavide Italiano #endif
823df8bae1dSRodney W. Grimes 
8248d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
8258d809d50SJeff Roberson 	CC_LOCK(cc);
82674cf7caeSJohn Baldwin 	for (;;) {
82774cf7caeSJohn Baldwin 		while (TAILQ_EMPTY(&cc->cc_expireq)) {
82874cf7caeSJohn Baldwin 			/*
82974cf7caeSJohn Baldwin 			 * Use CC_LOCK(cc) as the thread_lock while
83074cf7caeSJohn Baldwin 			 * idle.
83174cf7caeSJohn Baldwin 			 */
83274cf7caeSJohn Baldwin 			thread_lock(td);
83374cf7caeSJohn Baldwin 			thread_lock_set(td, (struct mtx *)&cc->cc_lock);
83474cf7caeSJohn Baldwin 			TD_SET_IWAIT(td);
83574cf7caeSJohn Baldwin 			mi_switch(SW_VOL | SWT_IWAIT);
83674cf7caeSJohn Baldwin 
83774cf7caeSJohn Baldwin 			/* mi_switch() drops thread_lock(). */
83874cf7caeSJohn Baldwin 			CC_LOCK(cc);
83974cf7caeSJohn Baldwin 		}
84074cf7caeSJohn Baldwin 
84174cf7caeSJohn Baldwin #ifdef CALLOUT_PROFILING
84274cf7caeSJohn Baldwin 		depth = gcalls = lockcalls = mpcalls = 0;
84374cf7caeSJohn Baldwin #endif
8445b999a6bSDavide Italiano 		while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
8455b999a6bSDavide Italiano 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
8465b999a6bSDavide Italiano 			softclock_call_cc(c, cc,
8475b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8485b999a6bSDavide Italiano 			    &mpcalls, &lockcalls, &gcalls,
8495b999a6bSDavide Italiano #endif
8505b999a6bSDavide Italiano 			    0);
8515b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8525b999a6bSDavide Italiano 			++depth;
8535b999a6bSDavide Italiano #endif
854df8bae1dSRodney W. Grimes 		}
8555b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
85622ee8c4fSPoul-Henning Kamp 		avg_depth += (depth * 1000 - avg_depth) >> 8;
85722ee8c4fSPoul-Henning Kamp 		avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
85864b9ee20SAttilio Rao 		avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
85922ee8c4fSPoul-Henning Kamp 		avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8605b999a6bSDavide Italiano #endif
86174cf7caeSJohn Baldwin 	}
862df8bae1dSRodney W. Grimes }
863df8bae1dSRodney W. Grimes 
864a9e182e8SKonstantin Belousov void
865a9e182e8SKonstantin Belousov callout_when(sbintime_t sbt, sbintime_t precision, int flags,
866a9e182e8SKonstantin Belousov     sbintime_t *res, sbintime_t *prec_res)
867acc8326dSGarrett Wollman {
868a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, to_pr;
869acc8326dSGarrett Wollman 
870a9e182e8SKonstantin Belousov 	if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
871a9e182e8SKonstantin Belousov 		*res = sbt;
872a9e182e8SKonstantin Belousov 		*prec_res = precision;
873a9e182e8SKonstantin Belousov 		return;
87415b1eb14SRandall Stewart 	}
875a9e182e8SKonstantin Belousov 	if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
8765b999a6bSDavide Italiano 		sbt = tick_sbt;
877a28c28e6SMark Johnston 	if ((flags & C_HARDCLOCK) != 0 || sbt >= sbt_tickthreshold) {
8785b999a6bSDavide Italiano 		/*
8795b999a6bSDavide Italiano 		 * Obtain the time of the last hardclock() call on
8805b999a6bSDavide Italiano 		 * this CPU directly from the kern_clocksource.c.
8815b999a6bSDavide Italiano 		 * This value is per-CPU, but it is equal for all
8825b999a6bSDavide Italiano 		 * active ones.
8835b999a6bSDavide Italiano 		 */
8845b999a6bSDavide Italiano #ifdef __LP64__
885a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
8865b999a6bSDavide Italiano #else
8875b999a6bSDavide Italiano 		spinlock_enter();
888a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
8895b999a6bSDavide Italiano 		spinlock_exit();
8905b999a6bSDavide Italiano #endif
8919f3aabb9SJohn Baldwin 		if (cold && to_sbt == 0)
8929f3aabb9SJohn Baldwin 			to_sbt = sbinuptime();
893a115fb62SHans Petter Selasky 		if ((flags & C_HARDCLOCK) == 0)
894a115fb62SHans Petter Selasky 			to_sbt += tick_sbt;
8955b999a6bSDavide Italiano 	} else
896a115fb62SHans Petter Selasky 		to_sbt = sbinuptime();
897a115fb62SHans Petter Selasky 	if (SBT_MAX - to_sbt < sbt)
898a115fb62SHans Petter Selasky 		to_sbt = SBT_MAX;
8991b0c144fSDavide Italiano 	else
900a115fb62SHans Petter Selasky 		to_sbt += sbt;
901a9e182e8SKonstantin Belousov 	*res = to_sbt;
902a9e182e8SKonstantin Belousov 	to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
903a115fb62SHans Petter Selasky 	    sbt >> C_PRELGET(flags));
904a9e182e8SKonstantin Belousov 	*prec_res = to_pr > precision ? to_pr : precision;
905a115fb62SHans Petter Selasky }
906a9e182e8SKonstantin Belousov 
907a9e182e8SKonstantin Belousov /*
908a9e182e8SKonstantin Belousov  * New interface; clients allocate their own callout structures.
909a9e182e8SKonstantin Belousov  *
910a9e182e8SKonstantin Belousov  * callout_reset() - establish or change a timeout
911a9e182e8SKonstantin Belousov  * callout_stop() - disestablish a timeout
912a9e182e8SKonstantin Belousov  * callout_init() - initialize a callout structure so that it can
913a9e182e8SKonstantin Belousov  *	safely be passed to callout_reset() and callout_stop()
914a9e182e8SKonstantin Belousov  *
915a9e182e8SKonstantin Belousov  * <sys/callout.h> defines three convenience macros:
916a9e182e8SKonstantin Belousov  *
917a9e182e8SKonstantin Belousov  * callout_active() - returns truth if callout has not been stopped,
918a9e182e8SKonstantin Belousov  *	drained, or deactivated since the last time the callout was
919a9e182e8SKonstantin Belousov  *	reset.
920a9e182e8SKonstantin Belousov  * callout_pending() - returns truth if callout is still waiting for timeout
921a9e182e8SKonstantin Belousov  * callout_deactivate() - marks the callout as having been serviced
922a9e182e8SKonstantin Belousov  */
923a9e182e8SKonstantin Belousov int
924a9e182e8SKonstantin Belousov callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
925a8a03706SJohn Baldwin     callout_func_t *ftn, void *arg, int cpu, int flags)
926a9e182e8SKonstantin Belousov {
927a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, precision;
928a9e182e8SKonstantin Belousov 	struct callout_cpu *cc;
929a9e182e8SKonstantin Belousov 	int cancelled, direct;
930a9e182e8SKonstantin Belousov 
931a9e182e8SKonstantin Belousov 	cancelled = 0;
932a9e182e8SKonstantin Belousov 	callout_when(sbt, prec, flags, &to_sbt, &precision);
933a9e182e8SKonstantin Belousov 
934a115fb62SHans Petter Selasky 	/*
93566525b2dSRandall Stewart 	 * This flag used to be added by callout_cc_add, but the
93666525b2dSRandall Stewart 	 * first time you call this we could end up with the
93766525b2dSRandall Stewart 	 * wrong direct flag if we don't do it before we add.
93866525b2dSRandall Stewart 	 */
93966525b2dSRandall Stewart 	if (flags & C_DIRECT_EXEC) {
94015b1eb14SRandall Stewart 		direct = 1;
94115b1eb14SRandall Stewart 	} else {
94215b1eb14SRandall Stewart 		direct = 0;
94366525b2dSRandall Stewart 	}
9444730a897SAlexander Motin 	KASSERT(!direct || c->c_lock == NULL ||
9454730a897SAlexander Motin 	    (LOCK_CLASS(c->c_lock)->lc_flags & LC_SPINLOCK),
9464730a897SAlexander Motin 	    ("%s: direct callout %p has non-spin lock", __func__, c));
94738e1d32dSMark Johnston 
948a115fb62SHans Petter Selasky 	cc = callout_lock(c);
94938e1d32dSMark Johnston 	if (cpu == -1)
95015b1eb14SRandall Stewart 		cpu = c->c_cpu;
95138e1d32dSMark Johnston 	KASSERT(cpu >= 0 && cpu <= mp_maxid && !CPU_ABSENT(cpu),
95238e1d32dSMark Johnston 	    ("%s: invalid cpu %d", __func__, cpu));
95315b1eb14SRandall Stewart 
954d2854fa4SRandall Stewart 	if (cc_exec_curr(cc, direct) == c) {
955a115fb62SHans Petter Selasky 		/*
956a115fb62SHans Petter Selasky 		 * We're being asked to reschedule a callout which is
957a115fb62SHans Petter Selasky 		 * currently in progress.  If there is a lock then we
958a115fb62SHans Petter Selasky 		 * can cancel the callout if it has not really started.
959a115fb62SHans Petter Selasky 		 */
960378d5c6cSAndriy Gapon 		if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
961d2854fa4SRandall Stewart 			cancelled = cc_exec_cancel(cc, direct) = true;
962*5fc3104aSGleb Smirnoff 		if (cc_exec_waiting(cc, direct)) {
963a115fb62SHans Petter Selasky 			/*
964a115fb62SHans Petter Selasky 			 * Someone has called callout_drain to kill this
965a115fb62SHans Petter Selasky 			 * callout.  Don't reschedule.
966a115fb62SHans Petter Selasky 			 */
967a115fb62SHans Petter Selasky 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
968a115fb62SHans Petter Selasky 			    cancelled ? "cancelled" : "failed to cancel",
969a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
970a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
971a115fb62SHans Petter Selasky 			return (cancelled);
972a115fb62SHans Petter Selasky 		}
973d2854fa4SRandall Stewart #ifdef SMP
974d2854fa4SRandall Stewart 		if (callout_migrating(c)) {
975d2854fa4SRandall Stewart 			/*
976d2854fa4SRandall Stewart 			 * This only occurs when a second callout_reset_sbt_on
977d2854fa4SRandall Stewart 			 * is made after a previous one moved it into
978d2854fa4SRandall Stewart 			 * deferred migration (below). Note we do *not* change
979d2854fa4SRandall Stewart 			 * the prev_cpu even though the previous target may
980d2854fa4SRandall Stewart 			 * be different.
981d2854fa4SRandall Stewart 			 */
982d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
983d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
984d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
985d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
986d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
987d2854fa4SRandall Stewart 			cancelled = 1;
988d2854fa4SRandall Stewart 			CC_UNLOCK(cc);
989d2854fa4SRandall Stewart 			return (cancelled);
990d2854fa4SRandall Stewart 		}
991d2854fa4SRandall Stewart #endif
992a115fb62SHans Petter Selasky 	}
99315b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_PENDING) {
99415b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
99566525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
99666525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
997a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
99815b1eb14SRandall Stewart 		} else {
999a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
100015b1eb14SRandall Stewart 		}
1001a115fb62SHans Petter Selasky 		cancelled = 1;
100215b1eb14SRandall Stewart 		c->c_iflags &= ~ CALLOUT_PENDING;
100315b1eb14SRandall Stewart 		c->c_flags &= ~ CALLOUT_ACTIVE;
10048d809d50SJeff Roberson 	}
10051283e9cdSAttilio Rao 
1006a115fb62SHans Petter Selasky #ifdef SMP
1007a115fb62SHans Petter Selasky 	/*
1008a115fb62SHans Petter Selasky 	 * If the callout must migrate try to perform it immediately.
1009a115fb62SHans Petter Selasky 	 * If the callout is currently running, just defer the migration
1010a115fb62SHans Petter Selasky 	 * to a more appropriate moment.
1011a115fb62SHans Petter Selasky 	 */
1012a115fb62SHans Petter Selasky 	if (c->c_cpu != cpu) {
1013d2854fa4SRandall Stewart 		if (cc_exec_curr(cc, direct) == c) {
1014d2854fa4SRandall Stewart 			/*
1015d2854fa4SRandall Stewart 			 * Pending will have been removed since we are
1016d2854fa4SRandall Stewart 			 * actually executing the callout on another
1017d2854fa4SRandall Stewart 			 * CPU. That callout should be waiting on the
1018d2854fa4SRandall Stewart 			 * lock the caller holds. If we set both
1019d2854fa4SRandall Stewart 			 * active/and/pending after we return and the
1020d2854fa4SRandall Stewart 			 * lock on the executing callout proceeds, it
1021d2854fa4SRandall Stewart 			 * will then see pending is true and return.
1022d2854fa4SRandall Stewart 			 * At the return from the actual callout execution
1023d2854fa4SRandall Stewart 			 * the migration will occur in softclock_call_cc
1024d2854fa4SRandall Stewart 			 * and this new callout will be placed on the
1025d2854fa4SRandall Stewart 			 * new CPU via a call to callout_cpu_switch() which
1026d2854fa4SRandall Stewart 			 * will get the lock on the right CPU followed
1027d2854fa4SRandall Stewart 			 * by a call callout_cc_add() which will add it there.
1028d2854fa4SRandall Stewart 			 * (see above in softclock_call_cc()).
1029d2854fa4SRandall Stewart 			 */
1030d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1031d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1032d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1033d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1034d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
103515b1eb14SRandall Stewart 			c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
103615b1eb14SRandall Stewart 			c->c_flags |= CALLOUT_ACTIVE;
1037a115fb62SHans Petter Selasky 			CTR6(KTR_CALLOUT,
1038a115fb62SHans Petter Selasky 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1039a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1040a115fb62SHans Petter Selasky 			    (u_int)(to_sbt & 0xffffffff), cpu);
1041a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1042a115fb62SHans Petter Selasky 			return (cancelled);
1043a115fb62SHans Petter Selasky 		}
1044a115fb62SHans Petter Selasky 		cc = callout_cpu_switch(c, cc, cpu);
1045a115fb62SHans Petter Selasky 	}
1046a115fb62SHans Petter Selasky #endif
1047a115fb62SHans Petter Selasky 
1048aac7c7acSMark Johnston 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, flags);
1049a115fb62SHans Petter Selasky 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1050a115fb62SHans Petter Selasky 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1051a115fb62SHans Petter Selasky 	    (u_int)(to_sbt & 0xffffffff));
1052a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
1053a115fb62SHans Petter Selasky 
1054a115fb62SHans Petter Selasky 	return (cancelled);
1055acc8326dSGarrett Wollman }
1056acc8326dSGarrett Wollman 
10576e0186d5SSam Leffler /*
10586e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
10596e0186d5SSam Leffler  */
10606e0186d5SSam Leffler int
10616e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
10626e0186d5SSam Leffler {
10636e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
10646e0186d5SSam Leffler }
10656e0186d5SSam Leffler 
10666e0186d5SSam Leffler int
10676e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
10686e0186d5SSam Leffler {
10696e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
10706e0186d5SSam Leffler }
10716e0186d5SSam Leffler 
10722c1bb207SColin Percival int
1073*5fc3104aSGleb Smirnoff _callout_stop_safe(struct callout *c, int flags)
10742c1bb207SColin Percival {
1075a115fb62SHans Petter Selasky 	struct callout_cpu *cc, *old_cc;
1076a115fb62SHans Petter Selasky 	struct lock_class *class;
1077a115fb62SHans Petter Selasky 	int direct, sq_locked, use_lock;
107847e42809SGleb Smirnoff 	int cancelled, not_on_a_list;
10791283e9cdSAttilio Rao 
10805db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) != 0)
10819500dd9fSAdrian Chadd 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
10829500dd9fSAdrian Chadd 		    "calling %s", __func__);
10839500dd9fSAdrian Chadd 
10841283e9cdSAttilio Rao 	/*
1085a115fb62SHans Petter Selasky 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1086a115fb62SHans Petter Selasky 	 * so just discard this check for the moment.
10871283e9cdSAttilio Rao 	 */
10885db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1089a115fb62SHans Petter Selasky 		if (c->c_lock == &Giant.lock_object)
1090a115fb62SHans Petter Selasky 			use_lock = mtx_owned(&Giant);
1091a115fb62SHans Petter Selasky 		else {
1092a115fb62SHans Petter Selasky 			use_lock = 1;
1093a115fb62SHans Petter Selasky 			class = LOCK_CLASS(c->c_lock);
1094a115fb62SHans Petter Selasky 			class->lc_assert(c->c_lock, LA_XLOCKED);
10951283e9cdSAttilio Rao 		}
1096a115fb62SHans Petter Selasky 	} else
1097a115fb62SHans Petter Selasky 		use_lock = 0;
109815b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_DIRECT) {
109915b1eb14SRandall Stewart 		direct = 1;
110015b1eb14SRandall Stewart 	} else {
110115b1eb14SRandall Stewart 		direct = 0;
110215b1eb14SRandall Stewart 	}
1103a115fb62SHans Petter Selasky 	sq_locked = 0;
1104a115fb62SHans Petter Selasky 	old_cc = NULL;
1105a115fb62SHans Petter Selasky again:
1106a115fb62SHans Petter Selasky 	cc = callout_lock(c);
1107a115fb62SHans Petter Selasky 
110815b1eb14SRandall Stewart 	if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
110915b1eb14SRandall Stewart 	    (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
111015b1eb14SRandall Stewart 	    ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1111d2854fa4SRandall Stewart 		/*
1112d2854fa4SRandall Stewart 		 * Special case where this slipped in while we
1113d2854fa4SRandall Stewart 		 * were migrating *as* the callout is about to
1114d2854fa4SRandall Stewart 		 * execute. The caller probably holds the lock
1115d2854fa4SRandall Stewart 		 * the callout wants.
1116d2854fa4SRandall Stewart 		 *
1117d2854fa4SRandall Stewart 		 * Get rid of the migration first. Then set
1118d2854fa4SRandall Stewart 		 * the flag that tells this code *not* to
1119d2854fa4SRandall Stewart 		 * try to remove it from any lists (its not
1120d2854fa4SRandall Stewart 		 * on one yet). When the callout wheel runs,
1121d2854fa4SRandall Stewart 		 * it will ignore this callout.
1122d2854fa4SRandall Stewart 		 */
112315b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_PENDING;
112415b1eb14SRandall Stewart 		c->c_flags &= ~CALLOUT_ACTIVE;
1125d2854fa4SRandall Stewart 		not_on_a_list = 1;
1126d2854fa4SRandall Stewart 	} else {
1127d2854fa4SRandall Stewart 		not_on_a_list = 0;
1128d2854fa4SRandall Stewart 	}
1129d2854fa4SRandall Stewart 
1130a115fb62SHans Petter Selasky 	/*
1131a115fb62SHans Petter Selasky 	 * If the callout was migrating while the callout cpu lock was
1132a115fb62SHans Petter Selasky 	 * dropped,  just drop the sleepqueue lock and check the states
1133a115fb62SHans Petter Selasky 	 * again.
1134a115fb62SHans Petter Selasky 	 */
1135a115fb62SHans Petter Selasky 	if (sq_locked != 0 && cc != old_cc) {
1136a115fb62SHans Petter Selasky #ifdef SMP
1137a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
1138d2854fa4SRandall Stewart 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1139a115fb62SHans Petter Selasky 		sq_locked = 0;
1140a115fb62SHans Petter Selasky 		old_cc = NULL;
1141a115fb62SHans Petter Selasky 		goto again;
1142a115fb62SHans Petter Selasky #else
1143a115fb62SHans Petter Selasky 		panic("migration should not happen");
1144a115fb62SHans Petter Selasky #endif
1145a115fb62SHans Petter Selasky 	}
114647e42809SGleb Smirnoff 
1147a115fb62SHans Petter Selasky 	/*
114847e42809SGleb Smirnoff 	 * If the callout is running, try to stop it or drain it.
1149a115fb62SHans Petter Selasky 	 */
115047e42809SGleb Smirnoff 	if (cc_exec_curr(cc, direct) == c) {
1151a115fb62SHans Petter Selasky 		/*
115247e42809SGleb Smirnoff 		 * Succeed we to stop it or not, we must clear the
11537d88be4cSMark Johnston 		 * active flag - this is what API users expect.  If we're
11547d88be4cSMark Johnston 		 * draining and the callout is currently executing, first wait
11557d88be4cSMark Johnston 		 * until it finishes.
1156a115fb62SHans Petter Selasky 		 */
11577d88be4cSMark Johnston 		if ((flags & CS_DRAIN) == 0)
115818b4fd62SRandall Stewart 			c->c_flags &= ~CALLOUT_ACTIVE;
115947e42809SGleb Smirnoff 
11605db9ed80SKonstantin Belousov 		if ((flags & CS_DRAIN) != 0) {
1161a115fb62SHans Petter Selasky 			/*
1162a115fb62SHans Petter Selasky 			 * The current callout is running (or just
1163a115fb62SHans Petter Selasky 			 * about to run) and blocking is allowed, so
1164a115fb62SHans Petter Selasky 			 * just wait for the current invocation to
1165a115fb62SHans Petter Selasky 			 * finish.
1166a115fb62SHans Petter Selasky 			 */
1167a33fef5eSMark Johnston 			if (cc_exec_curr(cc, direct) == c) {
1168a115fb62SHans Petter Selasky 				/*
1169a115fb62SHans Petter Selasky 				 * Use direct calls to sleepqueue interface
1170a115fb62SHans Petter Selasky 				 * instead of cv/msleep in order to avoid
1171a115fb62SHans Petter Selasky 				 * a LOR between cc_lock and sleepqueue
1172a115fb62SHans Petter Selasky 				 * chain spinlocks.  This piece of code
1173a115fb62SHans Petter Selasky 				 * emulates a msleep_spin() call actually.
1174a115fb62SHans Petter Selasky 				 *
1175a115fb62SHans Petter Selasky 				 * If we already have the sleepqueue chain
1176a115fb62SHans Petter Selasky 				 * locked, then we can safely block.  If we
1177a115fb62SHans Petter Selasky 				 * don't already have it locked, however,
1178a115fb62SHans Petter Selasky 				 * we have to drop the cc_lock to lock
1179a115fb62SHans Petter Selasky 				 * it.  This opens several races, so we
1180a115fb62SHans Petter Selasky 				 * restart at the beginning once we have
1181a115fb62SHans Petter Selasky 				 * both locks.  If nothing has changed, then
1182a115fb62SHans Petter Selasky 				 * we will end up back here with sq_locked
1183a115fb62SHans Petter Selasky 				 * set.
1184a115fb62SHans Petter Selasky 				 */
1185a115fb62SHans Petter Selasky 				if (!sq_locked) {
1186a115fb62SHans Petter Selasky 					CC_UNLOCK(cc);
1187a115fb62SHans Petter Selasky 					sleepq_lock(
1188d2854fa4SRandall Stewart 					    &cc_exec_waiting(cc, direct));
1189a115fb62SHans Petter Selasky 					sq_locked = 1;
1190a115fb62SHans Petter Selasky 					old_cc = cc;
1191a115fb62SHans Petter Selasky 					goto again;
1192a115fb62SHans Petter Selasky 				}
119347e42809SGleb Smirnoff 
1194a115fb62SHans Petter Selasky 				/*
1195a115fb62SHans Petter Selasky 				 * Migration could be cancelled here, but
1196a115fb62SHans Petter Selasky 				 * as long as it is still not sure when it
1197a115fb62SHans Petter Selasky 				 * will be packed up, just let softclock()
1198a115fb62SHans Petter Selasky 				 * take care of it.
1199a115fb62SHans Petter Selasky 				 */
1200d2854fa4SRandall Stewart 				cc_exec_waiting(cc, direct) = true;
1201a115fb62SHans Petter Selasky 				DROP_GIANT();
1202a115fb62SHans Petter Selasky 				CC_UNLOCK(cc);
1203a115fb62SHans Petter Selasky 				sleepq_add(
1204d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1205a115fb62SHans Petter Selasky 				    &cc->cc_lock.lock_object, "codrain",
1206a115fb62SHans Petter Selasky 				    SLEEPQ_SLEEP, 0);
1207a115fb62SHans Petter Selasky 				sleepq_wait(
1208d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1209a115fb62SHans Petter Selasky 					     0);
1210a115fb62SHans Petter Selasky 				sq_locked = 0;
1211a115fb62SHans Petter Selasky 				old_cc = NULL;
1212a115fb62SHans Petter Selasky 
1213a115fb62SHans Petter Selasky 				/* Reacquire locks previously released. */
1214a115fb62SHans Petter Selasky 				PICKUP_GIANT();
1215a33fef5eSMark Johnston 				goto again;
1216a115fb62SHans Petter Selasky 			}
12177d88be4cSMark Johnston 			c->c_flags &= ~CALLOUT_ACTIVE;
1218*5fc3104aSGleb Smirnoff 		} else if (use_lock && !cc_exec_cancel(cc, direct)) {
1219d2854fa4SRandall Stewart 
1220a115fb62SHans Petter Selasky 			/*
1221a115fb62SHans Petter Selasky 			 * The current callout is waiting for its
1222a115fb62SHans Petter Selasky 			 * lock which we hold.  Cancel the callout
1223a115fb62SHans Petter Selasky 			 * and return.  After our caller drops the
1224a115fb62SHans Petter Selasky 			 * lock, the callout will be skipped in
122518b4fd62SRandall Stewart 			 * softclock(). This *only* works with a
1226*5fc3104aSGleb Smirnoff 			 * callout_stop() *not* with callout_drain().
1227a115fb62SHans Petter Selasky 			 */
1228d2854fa4SRandall Stewart 			cc_exec_cancel(cc, direct) = true;
1229a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1230a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1231a115fb62SHans Petter Selasky 			KASSERT(!cc_cce_migrating(cc, direct),
1232a115fb62SHans Petter Selasky 			    ("callout wrongly scheduled for migration"));
123315b1eb14SRandall Stewart 			if (callout_migrating(c)) {
123415b1eb14SRandall Stewart 				c->c_iflags &= ~CALLOUT_DFRMIGRATION;
123515b1eb14SRandall Stewart #ifdef SMP
123615b1eb14SRandall Stewart 				cc_migration_cpu(cc, direct) = CPUBLOCK;
123715b1eb14SRandall Stewart 				cc_migration_time(cc, direct) = 0;
123815b1eb14SRandall Stewart 				cc_migration_prec(cc, direct) = 0;
123915b1eb14SRandall Stewart 				cc_migration_func(cc, direct) = NULL;
124015b1eb14SRandall Stewart 				cc_migration_arg(cc, direct) = NULL;
124115b1eb14SRandall Stewart #endif
124215b1eb14SRandall Stewart 			}
1243a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1244a115fb62SHans Petter Selasky 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1245a115fb62SHans Petter Selasky 			return (1);
1246d2854fa4SRandall Stewart 		} else if (callout_migrating(c)) {
1247d2854fa4SRandall Stewart 			/*
1248d2854fa4SRandall Stewart 			 * The callout is currently being serviced
1249d2854fa4SRandall Stewart 			 * and the "next" callout is scheduled at
1250d2854fa4SRandall Stewart 			 * its completion with a migration. We remove
1251d2854fa4SRandall Stewart 			 * the migration flag so it *won't* get rescheduled,
1252d2854fa4SRandall Stewart 			 * but we can't stop the one thats running so
1253d2854fa4SRandall Stewart 			 * we return 0.
1254d2854fa4SRandall Stewart 			 */
125515b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1256d2854fa4SRandall Stewart #ifdef SMP
1257d2854fa4SRandall Stewart 			/*
1258d2854fa4SRandall Stewart 			 * We can't call cc_cce_cleanup here since
1259d2854fa4SRandall Stewart 			 * if we do it will remove .ce_curr and
1260d2854fa4SRandall Stewart 			 * its still running. This will prevent a
1261d2854fa4SRandall Stewart 			 * reschedule of the callout when the
1262d2854fa4SRandall Stewart 			 * execution completes.
1263d2854fa4SRandall Stewart 			 */
1264d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1265d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = 0;
1266d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = 0;
1267d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = NULL;
1268d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = NULL;
1269d2854fa4SRandall Stewart #endif
1270a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1271a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1272a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
12737524994dSMark Johnston 			return (0);
12740d0053d7SHans Petter Selasky 		} else {
1275a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1276a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
12770d0053d7SHans Petter Selasky 		}
12783d84a188SRandall Stewart 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
12797524994dSMark Johnston 		cancelled = 0;
128047e42809SGleb Smirnoff 	} else
128147e42809SGleb Smirnoff 		cancelled = 1;
128247e42809SGleb Smirnoff 
12833d84a188SRandall Stewart 	if (sq_locked)
12843d84a188SRandall Stewart 		sleepq_release(&cc_exec_waiting(cc, direct));
1285d153eeeeSGleb Smirnoff 
128647e42809SGleb Smirnoff 	if ((c->c_iflags & CALLOUT_PENDING) == 0) {
128747e42809SGleb Smirnoff 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
128847e42809SGleb Smirnoff 		    c, c->c_func, c->c_arg);
12899f339124SGleb Smirnoff 		/*
12909f339124SGleb Smirnoff 		 * For not scheduled and not executing callout return
12919f339124SGleb Smirnoff 		 * negative value.
12929f339124SGleb Smirnoff 		 */
12939f339124SGleb Smirnoff 		if (cc_exec_curr(cc, direct) != c)
12949f339124SGleb Smirnoff 			cancelled = -1;
129547e42809SGleb Smirnoff 		CC_UNLOCK(cc);
12969f339124SGleb Smirnoff 		return (cancelled);
129747e42809SGleb Smirnoff 	}
129847e42809SGleb Smirnoff 
129915b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
130015b1eb14SRandall Stewart 	c->c_flags &= ~CALLOUT_ACTIVE;
13011283e9cdSAttilio Rao 
130268a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
130368a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
1304d2854fa4SRandall Stewart 	if (not_on_a_list == 0) {
130515b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
130666525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
130766525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1308a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
130915b1eb14SRandall Stewart 		} else {
1310a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1311d2854fa4SRandall Stewart 		}
131215b1eb14SRandall Stewart 	}
1313a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
131447e42809SGleb Smirnoff 	return (cancelled);
1315acc8326dSGarrett Wollman }
1316acc8326dSGarrett Wollman 
1317acc8326dSGarrett Wollman void
1318e392e44cSDavide Italiano callout_init(struct callout *c, int mpsafe)
1319acc8326dSGarrett Wollman {
1320a115fb62SHans Petter Selasky 	bzero(c, sizeof *c);
132198c926b2SIan Dowse 	if (mpsafe) {
1322a115fb62SHans Petter Selasky 		c->c_lock = NULL;
132315b1eb14SRandall Stewart 		c->c_iflags = CALLOUT_RETURNUNLOCKED;
132498c926b2SIan Dowse 	} else {
1325a115fb62SHans Petter Selasky 		c->c_lock = &Giant.lock_object;
132615b1eb14SRandall Stewart 		c->c_iflags = 0;
132798c926b2SIan Dowse 	}
13284b28d96eSJohn Baldwin 	c->c_cpu = cc_default_cpu;
132998c926b2SIan Dowse }
133098c926b2SIan Dowse 
133198c926b2SIan Dowse void
1332e392e44cSDavide Italiano _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
133398c926b2SIan Dowse {
133498c926b2SIan Dowse 	bzero(c, sizeof *c);
133564b9ee20SAttilio Rao 	c->c_lock = lock;
1336a115fb62SHans Petter Selasky 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1337a115fb62SHans Petter Selasky 	    ("callout_init_lock: bad flags %d", flags));
1338a115fb62SHans Petter Selasky 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1339a115fb62SHans Petter Selasky 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
13404730a897SAlexander Motin 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags & LC_SLEEPABLE),
13414730a897SAlexander Motin 	    ("%s: callout %p has sleepable lock", __func__, c));
134215b1eb14SRandall Stewart 	c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
13434b28d96eSJohn Baldwin 	c->c_cpu = cc_default_cpu;
1344acc8326dSGarrett Wollman }
1345acc8326dSGarrett Wollman 
13465b999a6bSDavide Italiano static int
13475b999a6bSDavide Italiano flssbt(sbintime_t sbt)
13485b999a6bSDavide Italiano {
13495b999a6bSDavide Italiano 
13505b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
13515b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
13525b999a6bSDavide Italiano 		return (flsl(sbt));
13535b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
13545b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
13555b999a6bSDavide Italiano 	return (flsl(sbt));
13565b999a6bSDavide Italiano }
13575b999a6bSDavide Italiano 
13585b999a6bSDavide Italiano /*
13595b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
13605b999a6bSDavide Italiano  */
13615b999a6bSDavide Italiano static int
13625b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
13635b999a6bSDavide Italiano {
13645b999a6bSDavide Italiano 	struct callout *tmp;
13655b999a6bSDavide Italiano 	struct callout_cpu *cc;
13665b999a6bSDavide Italiano 	struct callout_list *sc;
13675b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
13685b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
13695b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
13705b999a6bSDavide Italiano 	int cpu;
13715b999a6bSDavide Italiano 
13725b999a6bSDavide Italiano 	val = 0;
13735b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
13745b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
13755b999a6bSDavide Italiano 		return (error);
13765b999a6bSDavide Italiano 	count = maxc = 0;
13775b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
13785b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
13795b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
13805b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
13815b999a6bSDavide Italiano 	now = sbinuptime();
13825b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
13835b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
13845b999a6bSDavide Italiano 		CC_LOCK(cc);
13855b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
13865b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
13875b999a6bSDavide Italiano 			c = 0;
13885b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
13895b999a6bSDavide Italiano 				c++;
13905b999a6bSDavide Italiano 				t = tmp->c_time - now;
13915b999a6bSDavide Italiano 				if (t < 0)
13925b999a6bSDavide Italiano 					t = 0;
13935b999a6bSDavide Italiano 				st += t / SBT_1US;
13945b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
13955b999a6bSDavide Italiano 				if (t > maxt)
13965b999a6bSDavide Italiano 					maxt = t;
13975b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
13985b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
13995b999a6bSDavide Italiano 				ct[flssbt(t)]++;
14005b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
14015b999a6bSDavide Italiano 			}
14025b999a6bSDavide Italiano 			if (c > maxc)
14035b999a6bSDavide Italiano 				maxc = c;
14045b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
14055b999a6bSDavide Italiano 			count += c;
14065b999a6bSDavide Italiano 		}
14075b999a6bSDavide Italiano 		CC_UNLOCK(cc);
14085b999a6bSDavide Italiano 	}
14095b999a6bSDavide Italiano 
14105b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
14115b999a6bSDavide Italiano 		tcum += ct[i];
14125b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14135b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
14145b999a6bSDavide Italiano 		pcum += cpr[i];
14155b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14165b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
14175b999a6bSDavide Italiano 		c += ccpbk[i];
14185b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
14195b999a6bSDavide Italiano 
14205b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
14215b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
14225b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
14235b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
14245b999a6bSDavide Italiano 	    medc,
14255b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
14265b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
14275b999a6bSDavide Italiano 	    maxc);
14285b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14295b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
14305b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
14315b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
14325b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14335b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
14345b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
14355b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
14365b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
14375b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
14385b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
14395b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
14405b999a6bSDavide Italiano 			continue;
14415b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
14425b999a6bSDavide Italiano 		tcum += ct[i];
14435b999a6bSDavide Italiano 		pcum += cpr[i];
14445b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
14455b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
14465b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
14475b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
14485b999a6bSDavide Italiano 	}
14495b999a6bSDavide Italiano 	return (error);
14505b999a6bSDavide Italiano }
14515b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
14525b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
14535b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
14545b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
145547e42809SGleb Smirnoff 
14563af72c11SBjoern A. Zeeb #ifdef DDB
14573af72c11SBjoern A. Zeeb static void
14583af72c11SBjoern A. Zeeb _show_callout(struct callout *c)
14593af72c11SBjoern A. Zeeb {
14603af72c11SBjoern A. Zeeb 
14613af72c11SBjoern A. Zeeb 	db_printf("callout %p\n", c);
14623af72c11SBjoern A. Zeeb #define	C_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, c->e);
14633af72c11SBjoern A. Zeeb 	db_printf("   &c_links = %p\n", &(c->c_links));
14643af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_time);
14653af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_precision);
14663af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_arg);
14673af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_func);
14683af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_lock);
14693af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_flags);
14703af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_iflags);
14713af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%d",	c_cpu);
14723af72c11SBjoern A. Zeeb #undef	C_DB_PRINTF
14733af72c11SBjoern A. Zeeb }
14743af72c11SBjoern A. Zeeb 
14753af72c11SBjoern A. Zeeb DB_SHOW_COMMAND(callout, db_show_callout)
14763af72c11SBjoern A. Zeeb {
14773af72c11SBjoern A. Zeeb 
14783af72c11SBjoern A. Zeeb 	if (!have_addr) {
14793af72c11SBjoern A. Zeeb 		db_printf("usage: show callout <struct callout *>\n");
14803af72c11SBjoern A. Zeeb 		return;
14813af72c11SBjoern A. Zeeb 	}
14823af72c11SBjoern A. Zeeb 
14833af72c11SBjoern A. Zeeb 	_show_callout((struct callout *)addr);
14843af72c11SBjoern A. Zeeb }
14858c5a9161SEric van Gyzen 
14868c5a9161SEric van Gyzen static void
14878c5a9161SEric van Gyzen _show_last_callout(int cpu, int direct, const char *dirstr)
14888c5a9161SEric van Gyzen {
14898c5a9161SEric van Gyzen 	struct callout_cpu *cc;
14908c5a9161SEric van Gyzen 	void *func, *arg;
14918c5a9161SEric van Gyzen 
14928c5a9161SEric van Gyzen 	cc = CC_CPU(cpu);
14938c5a9161SEric van Gyzen 	func = cc_exec_last_func(cc, direct);
14948c5a9161SEric van Gyzen 	arg = cc_exec_last_arg(cc, direct);
14958c5a9161SEric van Gyzen 	db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
14968c5a9161SEric van Gyzen 	db_printsym((db_expr_t)func, DB_STGY_ANY);
14978c5a9161SEric van Gyzen 	db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
14988c5a9161SEric van Gyzen }
14998c5a9161SEric van Gyzen 
1500c84c5e00SMitchell Horne DB_SHOW_COMMAND_FLAGS(callout_last, db_show_callout_last, DB_CMD_MEMSAFE)
15018c5a9161SEric van Gyzen {
15028c5a9161SEric van Gyzen 	int cpu, last;
15038c5a9161SEric van Gyzen 
15048c5a9161SEric van Gyzen 	if (have_addr) {
15058c5a9161SEric van Gyzen 		if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
15068c5a9161SEric van Gyzen 			db_printf("no such cpu: %d\n", (int)addr);
15078c5a9161SEric van Gyzen 			return;
15088c5a9161SEric van Gyzen 		}
15098c5a9161SEric van Gyzen 		cpu = last = addr;
15108c5a9161SEric van Gyzen 	} else {
15118c5a9161SEric van Gyzen 		cpu = 0;
15128c5a9161SEric van Gyzen 		last = mp_maxid;
15138c5a9161SEric van Gyzen 	}
15148c5a9161SEric van Gyzen 
15158c5a9161SEric van Gyzen 	while (cpu <= last) {
15168c5a9161SEric van Gyzen 		if (!CPU_ABSENT(cpu)) {
15178c5a9161SEric van Gyzen 			_show_last_callout(cpu, 0, "");
15188c5a9161SEric van Gyzen 			_show_last_callout(cpu, 1, " direct");
15198c5a9161SEric van Gyzen 		}
15208c5a9161SEric van Gyzen 		cpu++;
15218c5a9161SEric van Gyzen 	}
15228c5a9161SEric van Gyzen }
15233af72c11SBjoern A. Zeeb #endif /* DDB */
1524