xref: /freebsd/sys/kern/kern_timeout.c (revision c1aff72cfa30fa27efe867a4feb667f1963e8cf7)
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  *
36acc8326dSGarrett Wollman  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
37df8bae1dSRodney W. Grimes  */
38df8bae1dSRodney W. Grimes 
39677b542eSDavid E. O'Brien #include <sys/cdefs.h>
40677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
41677b542eSDavid E. O'Brien 
425b999a6bSDavide Italiano #include "opt_callout_profiling.h"
433af72c11SBjoern A. Zeeb #include "opt_ddb.h"
44c445c3c7SAdrian Chadd #include "opt_rss.h"
4591dd9aaeSRobert Watson 
46df8bae1dSRodney W. Grimes #include <sys/param.h>
47df8bae1dSRodney W. Grimes #include <sys/systm.h>
488d809d50SJeff Roberson #include <sys/bus.h>
4915b7a470SPoul-Henning Kamp #include <sys/callout.h>
5036d151a2SAlexander Motin #include <sys/domainset.h>
51f8ccf82aSAndre Oppermann #include <sys/file.h>
528d809d50SJeff Roberson #include <sys/interrupt.h>
53df8bae1dSRodney W. Grimes #include <sys/kernel.h>
54ff7ec58aSRobert Watson #include <sys/ktr.h>
55f34fa851SJohn Baldwin #include <sys/lock.h>
568d809d50SJeff Roberson #include <sys/malloc.h>
57cb799bfeSJohn Baldwin #include <sys/mutex.h>
5821f9e816SJohn Baldwin #include <sys/proc.h>
5991dd9aaeSRobert Watson #include <sys/sdt.h>
606a0ce57dSAttilio Rao #include <sys/sleepqueue.h>
6122ee8c4fSPoul-Henning Kamp #include <sys/sysctl.h>
628d809d50SJeff Roberson #include <sys/smp.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 
805b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8122ee8c4fSPoul-Henning Kamp static int avg_depth;
8222ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8322ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
8422ee8c4fSPoul-Henning Kamp static int avg_gcalls;
8522ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
8622ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
8764b9ee20SAttilio Rao static int avg_lockcalls;
8864b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
8964b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
9022ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
9122ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
9222ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
935b999a6bSDavide Italiano static int avg_depth_dir;
945b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
955b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
965b999a6bSDavide Italiano     "Units = 1/1000");
975b999a6bSDavide Italiano static int avg_lockcalls_dir;
985b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
995b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
1005b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
1015b999a6bSDavide Italiano static int avg_mpcalls_dir;
1025b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1035b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1045b999a6bSDavide Italiano     "Units = 1/1000");
1055b999a6bSDavide Italiano #endif
106f8ccf82aSAndre Oppermann 
107f8ccf82aSAndre Oppermann static int ncallout;
108af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
109f8ccf82aSAndre Oppermann     "Number of entries in callwheel and size of timeout() preallocation");
110f8ccf82aSAndre Oppermann 
111c445c3c7SAdrian Chadd #ifdef	RSS
112c445c3c7SAdrian Chadd static int pin_default_swi = 1;
113c445c3c7SAdrian Chadd static int pin_pcpu_swi = 1;
114c445c3c7SAdrian Chadd #else
115ac75ee9fSAdrian Chadd static int pin_default_swi = 0;
116ac75ee9fSAdrian Chadd static int pin_pcpu_swi = 0;
117c445c3c7SAdrian Chadd #endif
118ac75ee9fSAdrian Chadd 
119af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
120ac75ee9fSAdrian Chadd     0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
121af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
122a212f56dSPiotr Pawel Stefaniak     0, "Pin the per-CPU swis (except PCPU 0, which is also default)");
123ac75ee9fSAdrian Chadd 
12415b7a470SPoul-Henning Kamp /*
12515b7a470SPoul-Henning Kamp  * TODO:
12615b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
12715b7a470SPoul-Henning Kamp  */
12861322a0aSAlexander Motin static u_int __read_mostly callwheelsize;
12961322a0aSAlexander Motin static u_int __read_mostly callwheelmask;
130f23b4c91SGarrett Wollman 
13120c510f8SLuigi Rizzo /*
132a115fb62SHans Petter Selasky  * The callout cpu exec entities represent informations necessary for
133a115fb62SHans Petter Selasky  * describing the state of callouts currently running on the CPU and the ones
134a115fb62SHans Petter Selasky  * necessary for migrating callouts to the new callout cpu. In particular,
135a115fb62SHans Petter Selasky  * the first entry of the array cc_exec_entity holds informations for callout
136a115fb62SHans Petter Selasky  * running in SWI thread context, while the second one holds informations
137a115fb62SHans Petter Selasky  * for callout running directly from hardware interrupt context.
138a115fb62SHans Petter Selasky  * The cached informations are very important for deferring migration when
139a115fb62SHans Petter Selasky  * the migrating callout is already running.
1401283e9cdSAttilio Rao  */
1415b999a6bSDavide Italiano struct cc_exec {
1425b999a6bSDavide Italiano 	struct callout		*cc_curr;
143a8a03706SJohn Baldwin 	callout_func_t		*cc_drain;
1448c5a9161SEric van Gyzen 	void			*cc_last_func;
1458c5a9161SEric van Gyzen 	void			*cc_last_arg;
146a115fb62SHans Petter Selasky #ifdef SMP
147a8a03706SJohn Baldwin 	callout_func_t		*ce_migration_func;
148a115fb62SHans Petter Selasky 	void			*ce_migration_arg;
149a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_time;
150a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_prec;
1518c5a9161SEric van Gyzen 	int			ce_migration_cpu;
152a115fb62SHans Petter Selasky #endif
153a4a3ce99SDavide Italiano 	bool			cc_cancel;
154a115fb62SHans Petter Selasky 	bool			cc_waiting;
1551283e9cdSAttilio Rao };
1561283e9cdSAttilio Rao 
1571283e9cdSAttilio Rao /*
158a115fb62SHans Petter Selasky  * There is one struct callout_cpu per cpu, holding all relevant
15920c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
16020c510f8SLuigi Rizzo  */
1618d809d50SJeff Roberson struct callout_cpu {
1624ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1635b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
16466525b2dSRandall Stewart 	struct callout		*cc_next;
1655b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1665b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1675b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1685b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
1698d809d50SJeff Roberson 	void			*cc_cookie;
1705b999a6bSDavide Italiano 	u_int			cc_bucket;
17115b1eb14SRandall Stewart 	u_int			cc_inited;
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
18218b4fd62SRandall Stewart #define	cc_exec_drain(cc, dir)		cc->cc_exec_entity[dir].cc_drain
18366525b2dSRandall Stewart #define	cc_exec_next(cc)		cc->cc_next
184d2854fa4SRandall Stewart #define	cc_exec_cancel(cc, dir)		cc->cc_exec_entity[dir].cc_cancel
185d2854fa4SRandall Stewart #define	cc_exec_waiting(cc, dir)	cc->cc_exec_entity[dir].cc_waiting
1868d809d50SJeff Roberson #ifdef SMP
187d2854fa4SRandall Stewart #define	cc_migration_func(cc, dir)	cc->cc_exec_entity[dir].ce_migration_func
188d2854fa4SRandall Stewart #define	cc_migration_arg(cc, dir)	cc->cc_exec_entity[dir].ce_migration_arg
189d2854fa4SRandall Stewart #define	cc_migration_cpu(cc, dir)	cc->cc_exec_entity[dir].ce_migration_cpu
190d2854fa4SRandall Stewart #define	cc_migration_time(cc, dir)	cc->cc_exec_entity[dir].ce_migration_time
191d2854fa4SRandall Stewart #define	cc_migration_prec(cc, dir)	cc->cc_exec_entity[dir].ce_migration_prec
192a115fb62SHans Petter Selasky 
193*c1aff72cSMark Johnston static struct callout_cpu cc_cpu[MAXCPU];
1941283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
1958d809d50SJeff Roberson #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
1968d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
1978d809d50SJeff Roberson #else
198*c1aff72cSMark Johnston static struct callout_cpu cc_cpu;
199*c1aff72cSMark Johnston #define	CC_CPU(cpu)	(&cc_cpu)
200*c1aff72cSMark Johnston #define	CC_SELF()	(&cc_cpu)
2018d809d50SJeff Roberson #endif
2028d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
2038d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
2041283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
2058d809d50SJeff Roberson 
2064b28d96eSJohn Baldwin static int __read_mostly cc_default_cpu;
2075b999a6bSDavide Italiano 
208232e8b52SJohn Baldwin static void	callout_cpu_init(struct callout_cpu *cc, int cpu);
2095b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
2105b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
2115b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
2125b999a6bSDavide Italiano #endif
2135b999a6bSDavide Italiano 		    int direct);
2148d809d50SJeff Roberson 
215d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
21649a74476SColin Percival 
217a115fb62SHans Petter Selasky /**
218a115fb62SHans Petter Selasky  * Locked by cc_lock:
219a115fb62SHans Petter Selasky  *   cc_curr         - If a callout is in progress, it is cc_curr.
220a115fb62SHans Petter Selasky  *                     If cc_curr is non-NULL, threads waiting in
221a115fb62SHans Petter Selasky  *                     callout_drain() will be woken up as soon as the
222a115fb62SHans Petter Selasky  *                     relevant callout completes.
223a115fb62SHans Petter Selasky  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
224a115fb62SHans Petter Selasky  *                     guarantees that the current callout will not run.
225a115fb62SHans Petter Selasky  *                     The softclock() function sets this to 0 before it
226a115fb62SHans Petter Selasky  *                     drops callout_lock to acquire c_lock, and it calls
227a115fb62SHans Petter Selasky  *                     the handler only if curr_cancelled is still 0 after
228a115fb62SHans Petter Selasky  *                     cc_lock is successfully acquired.
229a115fb62SHans Petter Selasky  *   cc_waiting      - If a thread is waiting in callout_drain(), then
230a115fb62SHans Petter Selasky  *                     callout_wait is nonzero.  Set only when
231a115fb62SHans Petter Selasky  *                     cc_curr is non-NULL.
232a115fb62SHans Petter Selasky  */
233a115fb62SHans Petter Selasky 
234df8bae1dSRodney W. Grimes /*
235a115fb62SHans Petter Selasky  * Resets the execution entity tied to a specific callout cpu.
236a115fb62SHans Petter Selasky  */
237a115fb62SHans Petter Selasky static void
238a115fb62SHans Petter Selasky cc_cce_cleanup(struct callout_cpu *cc, int direct)
239a115fb62SHans Petter Selasky {
240a115fb62SHans Petter Selasky 
241d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
242d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
243d2854fa4SRandall Stewart 	cc_exec_waiting(cc, direct) = false;
244a115fb62SHans Petter Selasky #ifdef SMP
245d2854fa4SRandall Stewart 	cc_migration_cpu(cc, direct) = CPUBLOCK;
246d2854fa4SRandall Stewart 	cc_migration_time(cc, direct) = 0;
247d2854fa4SRandall Stewart 	cc_migration_prec(cc, direct) = 0;
248d2854fa4SRandall Stewart 	cc_migration_func(cc, direct) = NULL;
249d2854fa4SRandall Stewart 	cc_migration_arg(cc, direct) = NULL;
250a115fb62SHans Petter Selasky #endif
251a115fb62SHans Petter Selasky }
252a115fb62SHans Petter Selasky 
253a115fb62SHans Petter Selasky /*
254a115fb62SHans Petter Selasky  * Checks if migration is requested by a specific callout cpu.
255a115fb62SHans Petter Selasky  */
256a115fb62SHans Petter Selasky static int
257a115fb62SHans Petter Selasky cc_cce_migrating(struct callout_cpu *cc, int direct)
258a115fb62SHans Petter Selasky {
259a115fb62SHans Petter Selasky 
260a115fb62SHans Petter Selasky #ifdef SMP
261d2854fa4SRandall Stewart 	return (cc_migration_cpu(cc, direct) != CPUBLOCK);
262a115fb62SHans Petter Selasky #else
263a115fb62SHans Petter Selasky 	return (0);
264a115fb62SHans Petter Selasky #endif
265a115fb62SHans Petter Selasky }
266a115fb62SHans Petter Selasky 
267a115fb62SHans Petter Selasky /*
268a115fb62SHans Petter Selasky  * Kernel low level callwheel initialization
269efe67753SNathan Whitehorn  * called on the BSP during kernel startup.
270219d632cSMatthew Dillon  */
27115ae0c9aSAndre Oppermann static void
27215ae0c9aSAndre Oppermann callout_callwheel_init(void *dummy)
273219d632cSMatthew Dillon {
2748d809d50SJeff Roberson 	struct callout_cpu *cc;
2754b28d96eSJohn Baldwin 	int cpu;
2768d809d50SJeff Roberson 
277f8ccf82aSAndre Oppermann 	/*
278f8ccf82aSAndre Oppermann 	 * Calculate the size of the callout wheel and the preallocated
279f8ccf82aSAndre Oppermann 	 * timeout() structures.
280a7aea132SAndre Oppermann 	 * XXX: Clip callout to result of previous function of maxusers
281a7aea132SAndre Oppermann 	 * maximum 384.  This is still huge, but acceptable.
282f8ccf82aSAndre Oppermann 	 */
283f8ccf82aSAndre Oppermann 	ncallout = imin(16 + maxproc + maxfiles, 18508);
284f8ccf82aSAndre Oppermann 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
285f8ccf82aSAndre Oppermann 
286219d632cSMatthew Dillon 	/*
287922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
288922314f0SAlfred Perlstein 	 * than 'ncallout'.
289219d632cSMatthew Dillon 	 */
290922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
291219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
292219d632cSMatthew Dillon 
29315ae0c9aSAndre Oppermann 	/*
294ac75ee9fSAdrian Chadd 	 * Fetch whether we're pinning the swi's or not.
295ac75ee9fSAdrian Chadd 	 */
296ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
297ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
298ac75ee9fSAdrian Chadd 
299ac75ee9fSAdrian Chadd 	/*
3004b28d96eSJohn Baldwin 	 * Initialize callout wheels.  The software interrupt threads
3014b28d96eSJohn Baldwin 	 * are created later.
30215ae0c9aSAndre Oppermann 	 */
3034b28d96eSJohn Baldwin 	cc_default_cpu = PCPU_GET(cpuid);
3044b28d96eSJohn Baldwin 	CPU_FOREACH(cpu) {
3054b28d96eSJohn Baldwin 		cc = CC_CPU(cpu);
3064b28d96eSJohn Baldwin 		callout_cpu_init(cc, cpu);
3074b28d96eSJohn Baldwin 	}
308219d632cSMatthew Dillon }
30915ae0c9aSAndre Oppermann SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
310219d632cSMatthew Dillon 
31115ae0c9aSAndre Oppermann /*
31215ae0c9aSAndre Oppermann  * Initialize the per-cpu callout structures.
31315ae0c9aSAndre Oppermann  */
3148d809d50SJeff Roberson static void
315232e8b52SJohn Baldwin callout_cpu_init(struct callout_cpu *cc, int cpu)
3168d809d50SJeff Roberson {
3178d809d50SJeff Roberson 	int i;
3188d809d50SJeff Roberson 
3198d809d50SJeff Roberson 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
32015b1eb14SRandall Stewart 	cc->cc_inited = 1;
32136d151a2SAlexander Motin 	cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
32236d151a2SAlexander Motin 	    callwheelsize, M_CALLOUT,
32336d151a2SAlexander Motin 	    DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
3245b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
3255b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
3265b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
3274bc38a5aSDavide Italiano 	cc->cc_firstevent = SBT_MAX;
328a115fb62SHans Petter Selasky 	for (i = 0; i < 2; i++)
329a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, i);
330329377f4SGleb Smirnoff #ifdef KTR
331232e8b52SJohn Baldwin 	snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
332232e8b52SJohn Baldwin 	    "callwheel cpu %d", cpu);
333329377f4SGleb Smirnoff #endif
3348d809d50SJeff Roberson }
3358d809d50SJeff Roberson 
336a115fb62SHans Petter Selasky #ifdef SMP
337a115fb62SHans Petter Selasky /*
338a115fb62SHans Petter Selasky  * Switches the cpu tied to a specific callout.
339a115fb62SHans Petter Selasky  * The function expects a locked incoming callout cpu and returns with
340a115fb62SHans Petter Selasky  * locked outcoming callout cpu.
341a115fb62SHans Petter Selasky  */
342a115fb62SHans Petter Selasky static struct callout_cpu *
343a115fb62SHans Petter Selasky callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
344a115fb62SHans Petter Selasky {
345a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
346a115fb62SHans Petter Selasky 
347a115fb62SHans Petter Selasky 	MPASS(c != NULL && cc != NULL);
348a115fb62SHans Petter Selasky 	CC_LOCK_ASSERT(cc);
349a115fb62SHans Petter Selasky 
350a115fb62SHans Petter Selasky 	/*
351a115fb62SHans Petter Selasky 	 * Avoid interrupts and preemption firing after the callout cpu
352a115fb62SHans Petter Selasky 	 * is blocked in order to avoid deadlocks as the new thread
353a115fb62SHans Petter Selasky 	 * may be willing to acquire the callout cpu lock.
354a115fb62SHans Petter Selasky 	 */
355a115fb62SHans Petter Selasky 	c->c_cpu = CPUBLOCK;
356a115fb62SHans Petter Selasky 	spinlock_enter();
357a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
358a115fb62SHans Petter Selasky 	new_cc = CC_CPU(new_cpu);
359a115fb62SHans Petter Selasky 	CC_LOCK(new_cc);
360a115fb62SHans Petter Selasky 	spinlock_exit();
361a115fb62SHans Petter Selasky 	c->c_cpu = new_cpu;
362a115fb62SHans Petter Selasky 	return (new_cc);
363a115fb62SHans Petter Selasky }
364a115fb62SHans Petter Selasky #endif
365a115fb62SHans Petter Selasky 
366219d632cSMatthew Dillon /*
3674b28d96eSJohn Baldwin  * Start softclock threads.
3688d809d50SJeff Roberson  */
3698d809d50SJeff Roberson static void
3708d809d50SJeff Roberson start_softclock(void *dummy)
3718d809d50SJeff Roberson {
3728d809d50SJeff Roberson 	struct callout_cpu *cc;
373f44e2a4cSAdrian Chadd 	char name[MAXCOMLEN];
3748d809d50SJeff Roberson 	int cpu;
3754b28d96eSJohn Baldwin 	bool pin_swi;
376ac75ee9fSAdrian Chadd 	struct intr_event *ie;
3778d809d50SJeff Roberson 
3783aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
3798d809d50SJeff Roberson 		cc = CC_CPU(cpu);
380f44e2a4cSAdrian Chadd 		snprintf(name, sizeof(name), "clock (%d)", cpu);
381ac75ee9fSAdrian Chadd 		ie = NULL;
382ac75ee9fSAdrian Chadd 		if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
3838d809d50SJeff Roberson 		    INTR_MPSAFE, &cc->cc_cookie))
3848d809d50SJeff Roberson 			panic("died while creating standard software ithreads");
3854b28d96eSJohn Baldwin 		if (cpu == cc_default_cpu)
3864b28d96eSJohn Baldwin 			pin_swi = pin_default_swi;
3874b28d96eSJohn Baldwin 		else
3884b28d96eSJohn Baldwin 			pin_swi = pin_pcpu_swi;
3894b28d96eSJohn Baldwin 		if (pin_swi && (intr_event_bind(ie, cpu) != 0)) {
3904b28d96eSJohn Baldwin 			printf("%s: %s clock couldn't be pinned to cpu %d\n",
391ac75ee9fSAdrian Chadd 			    __func__,
3924b28d96eSJohn Baldwin 			    cpu == cc_default_cpu ? "default" : "per-cpu",
393ac75ee9fSAdrian Chadd 			    cpu);
394ac75ee9fSAdrian Chadd 		}
395219d632cSMatthew Dillon 	}
396219d632cSMatthew Dillon }
3978d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
3988d809d50SJeff Roberson 
3995b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
4008d809d50SJeff Roberson 
4015b999a6bSDavide Italiano static inline u_int
4025b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
4035b999a6bSDavide Italiano {
4045b999a6bSDavide Italiano 
4055b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
4065b999a6bSDavide Italiano }
4075b999a6bSDavide Italiano 
4085b999a6bSDavide Italiano static inline u_int
4095b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
4105b999a6bSDavide Italiano {
4115b999a6bSDavide Italiano 
4125b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
4135b999a6bSDavide Italiano }
4145b999a6bSDavide Italiano 
4155b999a6bSDavide Italiano void
4165b999a6bSDavide Italiano callout_process(sbintime_t now)
4175b999a6bSDavide Italiano {
4185b999a6bSDavide Italiano 	struct callout *tmp, *tmpn;
4195b999a6bSDavide Italiano 	struct callout_cpu *cc;
4205b999a6bSDavide Italiano 	struct callout_list *sc;
4215b999a6bSDavide Italiano 	sbintime_t first, last, max, tmp_max;
4225b999a6bSDavide Italiano 	uint32_t lookahead;
4235b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
4245b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4255b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
4265b999a6bSDavide Italiano #endif
427a115fb62SHans Petter Selasky 
4288d809d50SJeff Roberson 	cc = CC_SELF();
429a115fb62SHans Petter Selasky 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4305b999a6bSDavide Italiano 
4315b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4325b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4335b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4345b999a6bSDavide Italiano 	nowb = callout_hash(now);
4355b999a6bSDavide Italiano 
4365b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4375b999a6bSDavide Italiano 	if (nowb == firstb)
4385b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4395b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4405b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4415b999a6bSDavide Italiano 	else
4425b999a6bSDavide Italiano 		lookahead = (SBT_1S / 2);
4435b999a6bSDavide Italiano 	first = last = now;
4445b999a6bSDavide Italiano 	first += (lookahead / 2);
4455b999a6bSDavide Italiano 	last += lookahead;
4465b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4475b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4485b999a6bSDavide Italiano 	max = last;
4495b999a6bSDavide Italiano 
4505b999a6bSDavide Italiano 	/*
4515b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4525b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4535b999a6bSDavide Italiano 	 */
4545b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4555b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4565b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4575b999a6bSDavide Italiano 			nowb = lastb;
4589fc51b0bSJeff Roberson 	}
4595b999a6bSDavide Italiano 
4605b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4615b999a6bSDavide Italiano 	do {
4625b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
4635b999a6bSDavide Italiano 		tmp = LIST_FIRST(sc);
4645b999a6bSDavide Italiano 		while (tmp != NULL) {
4655b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
4665b999a6bSDavide Italiano 			if (tmp->c_time <= now) {
4675b999a6bSDavide Italiano 				/*
4685b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
4695b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
4705b999a6bSDavide Italiano 				 */
47115b1eb14SRandall Stewart 				if (tmp->c_iflags & CALLOUT_DIRECT) {
4725b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4735b999a6bSDavide Italiano 					++depth_dir;
4745b999a6bSDavide Italiano #endif
47566525b2dSRandall Stewart 					cc_exec_next(cc) =
4765b999a6bSDavide Italiano 					    LIST_NEXT(tmp, c_links.le);
4775b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
4785b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4795b999a6bSDavide Italiano 					softclock_call_cc(tmp, cc,
4805b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4815b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
4825b999a6bSDavide Italiano #endif
4835b999a6bSDavide Italiano 					    1);
48466525b2dSRandall Stewart 					tmp = cc_exec_next(cc);
48566525b2dSRandall Stewart 					cc_exec_next(cc) = NULL;
4865b999a6bSDavide Italiano 				} else {
4875b999a6bSDavide Italiano 					tmpn = LIST_NEXT(tmp, c_links.le);
4885b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4895b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
4905b999a6bSDavide Italiano 					    tmp, c_links.tqe);
49115b1eb14SRandall Stewart 					tmp->c_iflags |= CALLOUT_PROCESSED;
4925b999a6bSDavide Italiano 					tmp = tmpn;
4939fc51b0bSJeff Roberson 				}
4945b999a6bSDavide Italiano 				continue;
4955b999a6bSDavide Italiano 			}
4965b999a6bSDavide Italiano 			/* Skip events from distant future. */
4975b999a6bSDavide Italiano 			if (tmp->c_time >= max)
4985b999a6bSDavide Italiano 				goto next;
4995b999a6bSDavide Italiano 			/*
5005b999a6bSDavide Italiano 			 * Event minimal time is bigger than present maximal
5015b999a6bSDavide Italiano 			 * time, so it cannot be aggregated.
5025b999a6bSDavide Italiano 			 */
5035b999a6bSDavide Italiano 			if (tmp->c_time > last) {
5045b999a6bSDavide Italiano 				lastb = nowb;
5055b999a6bSDavide Italiano 				goto next;
5065b999a6bSDavide Italiano 			}
5075b999a6bSDavide Italiano 			/* Update first and last time, respecting this event. */
5085b999a6bSDavide Italiano 			if (tmp->c_time < first)
5095b999a6bSDavide Italiano 				first = tmp->c_time;
5105b999a6bSDavide Italiano 			tmp_max = tmp->c_time + tmp->c_precision;
5115b999a6bSDavide Italiano 			if (tmp_max < last)
5125b999a6bSDavide Italiano 				last = tmp_max;
5135b999a6bSDavide Italiano next:
5145b999a6bSDavide Italiano 			tmp = LIST_NEXT(tmp, c_links.le);
5155b999a6bSDavide Italiano 		}
5165b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
5175b999a6bSDavide Italiano 		firstb++;
5185b999a6bSDavide Italiano 		/*
5195b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
5205b999a6bSDavide Italiano 		 * some event we can't execute at now.
5215b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
5225b999a6bSDavide Italiano 		 */
5235b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
5245b999a6bSDavide Italiano 	cc->cc_firstevent = last;
5255b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
526a28c28e6SMark Johnston 
5275b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5285b999a6bSDavide Italiano 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
5295b999a6bSDavide Italiano 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
5305b999a6bSDavide Italiano 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
5315b999a6bSDavide Italiano #endif
532a115fb62SHans Petter Selasky 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5338d809d50SJeff Roberson 	/*
5348d809d50SJeff Roberson 	 * swi_sched acquires the thread lock, so we don't want to call it
5358d809d50SJeff Roberson 	 * with cc_lock held; incorrect locking order.
5368d809d50SJeff Roberson 	 */
5375b999a6bSDavide Italiano 	if (!TAILQ_EMPTY(&cc->cc_expireq))
5388d809d50SJeff Roberson 		swi_sched(cc->cc_cookie, 0);
5398d809d50SJeff Roberson }
5408d809d50SJeff Roberson 
5418d809d50SJeff Roberson static struct callout_cpu *
5428d809d50SJeff Roberson callout_lock(struct callout *c)
5438d809d50SJeff Roberson {
5448d809d50SJeff Roberson 	struct callout_cpu *cc;
545a115fb62SHans Petter Selasky 	int cpu;
546a115fb62SHans Petter Selasky 
547a115fb62SHans Petter Selasky 	for (;;) {
548a115fb62SHans Petter Selasky 		cpu = c->c_cpu;
549a115fb62SHans Petter Selasky #ifdef SMP
550a115fb62SHans Petter Selasky 		if (cpu == CPUBLOCK) {
551a115fb62SHans Petter Selasky 			while (c->c_cpu == CPUBLOCK)
552a115fb62SHans Petter Selasky 				cpu_spinwait();
553a115fb62SHans Petter Selasky 			continue;
554a115fb62SHans Petter Selasky 		}
555a115fb62SHans Petter Selasky #endif
556a115fb62SHans Petter Selasky 		cc = CC_CPU(cpu);
5578d809d50SJeff Roberson 		CC_LOCK(cc);
558a115fb62SHans Petter Selasky 		if (cpu == c->c_cpu)
559a115fb62SHans Petter Selasky 			break;
560a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
561a115fb62SHans Petter Selasky 	}
5628d809d50SJeff Roberson 	return (cc);
563219d632cSMatthew Dillon }
564219d632cSMatthew Dillon 
565a115fb62SHans Petter Selasky static void
566a115fb62SHans Petter Selasky callout_cc_add(struct callout *c, struct callout_cpu *cc,
567a115fb62SHans Petter Selasky     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
56866525b2dSRandall Stewart     void *arg, int cpu, int flags)
5691283e9cdSAttilio Rao {
5705b999a6bSDavide Italiano 	int bucket;
5711283e9cdSAttilio Rao 
5721283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
573a115fb62SHans Petter Selasky 	if (sbt < cc->cc_lastscan)
574a115fb62SHans Petter Selasky 		sbt = cc->cc_lastscan;
575a115fb62SHans Petter Selasky 	c->c_arg = arg;
57615b1eb14SRandall Stewart 	c->c_iflags |= CALLOUT_PENDING;
57715b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PROCESSED;
57815b1eb14SRandall Stewart 	c->c_flags |= CALLOUT_ACTIVE;
57907a2df5dSRandall Stewart 	if (flags & C_DIRECT_EXEC)
580b132edb5SRandall Stewart 		c->c_iflags |= CALLOUT_DIRECT;
581a115fb62SHans Petter Selasky 	c->c_func = func;
582a115fb62SHans Petter Selasky 	c->c_time = sbt;
583a115fb62SHans Petter Selasky 	c->c_precision = precision;
5845b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
5855b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
5865b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
5875b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
5885b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
5895b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
59066525b2dSRandall Stewart 		cc_exec_next(cc) = c;
591a28c28e6SMark Johnston 
5925b999a6bSDavide Italiano 	/*
5935b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
5945b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
5955b999a6bSDavide Italiano 	 */
5964bc38a5aSDavide Italiano 	if (SBT_MAX - c->c_time < c->c_precision)
5974bc38a5aSDavide Italiano 		c->c_precision = SBT_MAX - c->c_time;
5985b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
5995b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
6005b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
601a115fb62SHans Petter Selasky 		cpu_new_callout(cpu, sbt, c->c_time);
6021283e9cdSAttilio Rao 	}
6031283e9cdSAttilio Rao }
6041283e9cdSAttilio Rao 
6056098e7acSKonstantin Belousov static void
6065b999a6bSDavide Italiano softclock_call_cc(struct callout *c, struct callout_cpu *cc,
6075b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6085b999a6bSDavide Italiano     int *mpcalls, int *lockcalls, int *gcalls,
6095b999a6bSDavide Italiano #endif
6105b999a6bSDavide Italiano     int direct)
6116098e7acSKonstantin Belousov {
612a115fb62SHans Petter Selasky 	struct rm_priotracker tracker;
613a8a03706SJohn Baldwin 	callout_func_t *c_func, *drain;
6146098e7acSKonstantin Belousov 	void *c_arg;
615a115fb62SHans Petter Selasky 	struct lock_class *class;
6166098e7acSKonstantin Belousov 	struct lock_object *c_lock;
617a115fb62SHans Petter Selasky 	uintptr_t lock_status;
61815b1eb14SRandall Stewart 	int c_iflags;
619a115fb62SHans Petter Selasky #ifdef SMP
620a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
621a8a03706SJohn Baldwin 	callout_func_t *new_func;
622a115fb62SHans Petter Selasky 	void *new_arg;
623a115fb62SHans Petter Selasky 	int flags, new_cpu;
624a115fb62SHans Petter Selasky 	sbintime_t new_prec, new_time;
625a115fb62SHans Petter Selasky #endif
6265b999a6bSDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
62703763781SDavide Italiano 	sbintime_t sbt1, sbt2;
6286098e7acSKonstantin Belousov 	struct timespec ts2;
6295b999a6bSDavide Italiano 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
630a8a03706SJohn Baldwin 	static callout_func_t *lastfunc;
6316098e7acSKonstantin Belousov #endif
6326098e7acSKonstantin Belousov 
63315b1eb14SRandall Stewart 	KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
63415b1eb14SRandall Stewart 	    ("softclock_call_cc: pend %p %x", c, c->c_iflags));
63515b1eb14SRandall Stewart 	KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
63615b1eb14SRandall Stewart 	    ("softclock_call_cc: act %p %x", c, c->c_flags));
637a115fb62SHans Petter Selasky 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
638a115fb62SHans Petter Selasky 	lock_status = 0;
639a115fb62SHans Petter Selasky 	if (c->c_flags & CALLOUT_SHAREDLOCK) {
640a115fb62SHans Petter Selasky 		if (class == &lock_class_rm)
641a115fb62SHans Petter Selasky 			lock_status = (uintptr_t)&tracker;
642a115fb62SHans Petter Selasky 		else
643a115fb62SHans Petter Selasky 			lock_status = 1;
644a115fb62SHans Petter Selasky 	}
6456098e7acSKonstantin Belousov 	c_lock = c->c_lock;
6466098e7acSKonstantin Belousov 	c_func = c->c_func;
6476098e7acSKonstantin Belousov 	c_arg = c->c_arg;
64815b1eb14SRandall Stewart 	c_iflags = c->c_iflags;
64915b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
650d2854fa4SRandall Stewart 
651d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = c;
6528c5a9161SEric van Gyzen 	cc_exec_last_func(cc, direct) = c_func;
6538c5a9161SEric van Gyzen 	cc_exec_last_arg(cc, direct) = c_arg;
654d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
65518b4fd62SRandall Stewart 	cc_exec_drain(cc, direct) = NULL;
6566098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
657a115fb62SHans Petter Selasky 	if (c_lock != NULL) {
658a115fb62SHans Petter Selasky 		class->lc_lock(c_lock, lock_status);
6596098e7acSKonstantin Belousov 		/*
660a115fb62SHans Petter Selasky 		 * The callout may have been cancelled
661a115fb62SHans Petter Selasky 		 * while we switched locks.
6626098e7acSKonstantin Belousov 		 */
663d2854fa4SRandall Stewart 		if (cc_exec_cancel(cc, direct)) {
664a115fb62SHans Petter Selasky 			class->lc_unlock(c_lock);
665a115fb62SHans Petter Selasky 			goto skip;
6666098e7acSKonstantin Belousov 		}
667a115fb62SHans Petter Selasky 		/* The callout cannot be stopped now. */
668d2854fa4SRandall Stewart 		cc_exec_cancel(cc, direct) = true;
6696098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
6705b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6716098e7acSKonstantin Belousov 			(*gcalls)++;
6725b999a6bSDavide Italiano #endif
6735b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
6746098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6756098e7acSKonstantin Belousov 		} else {
6765b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6776098e7acSKonstantin Belousov 			(*lockcalls)++;
6785b999a6bSDavide Italiano #endif
6796098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
6806098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6816098e7acSKonstantin Belousov 		}
6826098e7acSKonstantin Belousov 	} else {
6835b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6846098e7acSKonstantin Belousov 		(*mpcalls)++;
6855b999a6bSDavide Italiano #endif
6865b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
6876098e7acSKonstantin Belousov 		    c, c_func, c_arg);
6886098e7acSKonstantin Belousov 	}
689232e8b52SJohn Baldwin 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
690232e8b52SJohn Baldwin 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
69103763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
6925b999a6bSDavide Italiano 	sbt1 = sbinuptime();
6936098e7acSKonstantin Belousov #endif
6946098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
69536160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__start, c);
6966098e7acSKonstantin Belousov 	c_func(c_arg);
69736160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__end, c);
6986098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
69903763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
70003763781SDavide Italiano 	sbt2 = sbinuptime();
70103763781SDavide Italiano 	sbt2 -= sbt1;
70203763781SDavide Italiano 	if (sbt2 > maxdt) {
70303763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
70403763781SDavide Italiano 			ts2 = sbttots(sbt2);
7056098e7acSKonstantin Belousov 			printf(
7066098e7acSKonstantin Belousov 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
7076098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
7086098e7acSKonstantin Belousov 		}
70903763781SDavide Italiano 		maxdt = sbt2;
7106098e7acSKonstantin Belousov 		lastfunc = c_func;
7116098e7acSKonstantin Belousov 	}
7126098e7acSKonstantin Belousov #endif
713232e8b52SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
7146098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
71515b1eb14SRandall Stewart 	if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
716a115fb62SHans Petter Selasky 		class->lc_unlock(c_lock);
717a115fb62SHans Petter Selasky skip:
7186098e7acSKonstantin Belousov 	CC_LOCK(cc);
719d2854fa4SRandall Stewart 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
720d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
72118b4fd62SRandall Stewart 	if (cc_exec_drain(cc, direct)) {
72218b4fd62SRandall Stewart 		drain = cc_exec_drain(cc, direct);
72318b4fd62SRandall Stewart 		cc_exec_drain(cc, direct) = NULL;
72418b4fd62SRandall Stewart 		CC_UNLOCK(cc);
72518b4fd62SRandall Stewart 		drain(c_arg);
72618b4fd62SRandall Stewart 		CC_LOCK(cc);
72718b4fd62SRandall Stewart 	}
728d2854fa4SRandall Stewart 	if (cc_exec_waiting(cc, direct)) {
729bdf9120cSAttilio Rao 		/*
730a115fb62SHans Petter Selasky 		 * There is someone waiting for the
731a115fb62SHans Petter Selasky 		 * callout to complete.
732a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
733a115fb62SHans Petter Selasky 		 * migration just cancel it.
734bdf9120cSAttilio Rao 		 */
735a115fb62SHans Petter Selasky 		if (cc_cce_migrating(cc, direct)) {
736a115fb62SHans Petter Selasky 			cc_cce_cleanup(cc, direct);
737a115fb62SHans Petter Selasky 
738a115fb62SHans Petter Selasky 			/*
739a115fb62SHans Petter Selasky 			 * It should be assert here that the callout is not
740a115fb62SHans Petter Selasky 			 * destroyed but that is not easy.
741a115fb62SHans Petter Selasky 			 */
74215b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
7436098e7acSKonstantin Belousov 		}
744d2854fa4SRandall Stewart 		cc_exec_waiting(cc, direct) = false;
745a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
746d2854fa4SRandall Stewart 		wakeup(&cc_exec_waiting(cc, direct));
747a115fb62SHans Petter Selasky 		CC_LOCK(cc);
748a115fb62SHans Petter Selasky 	} else if (cc_cce_migrating(cc, direct)) {
749a115fb62SHans Petter Selasky #ifdef SMP
750a115fb62SHans Petter Selasky 		/*
751a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
752a115fb62SHans Petter Selasky 		 * migration just perform it now.
753a115fb62SHans Petter Selasky 		 */
754d2854fa4SRandall Stewart 		new_cpu = cc_migration_cpu(cc, direct);
755d2854fa4SRandall Stewart 		new_time = cc_migration_time(cc, direct);
756d2854fa4SRandall Stewart 		new_prec = cc_migration_prec(cc, direct);
757d2854fa4SRandall Stewart 		new_func = cc_migration_func(cc, direct);
758d2854fa4SRandall Stewart 		new_arg = cc_migration_arg(cc, direct);
759a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, direct);
760a115fb62SHans Petter Selasky 
761a115fb62SHans Petter Selasky 		/*
762a115fb62SHans Petter Selasky 		 * It should be assert here that the callout is not destroyed
763a115fb62SHans Petter Selasky 		 * but that is not easy.
764a115fb62SHans Petter Selasky 		 *
765a115fb62SHans Petter Selasky 		 * As first thing, handle deferred callout stops.
766a115fb62SHans Petter Selasky 		 */
767d2854fa4SRandall Stewart 		if (!callout_migrating(c)) {
768a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT,
769a115fb62SHans Petter Selasky 			     "deferred cancelled %p func %p arg %p",
770a115fb62SHans Petter Selasky 			     c, new_func, new_arg);
771a115fb62SHans Petter Selasky 			return;
772a115fb62SHans Petter Selasky 		}
77315b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_DFRMIGRATION;
774a115fb62SHans Petter Selasky 
775a115fb62SHans Petter Selasky 		new_cc = callout_cpu_switch(c, cc, new_cpu);
776a115fb62SHans Petter Selasky 		flags = (direct) ? C_DIRECT_EXEC : 0;
777a115fb62SHans Petter Selasky 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
77866525b2dSRandall Stewart 		    new_arg, new_cpu, flags);
779a115fb62SHans Petter Selasky 		CC_UNLOCK(new_cc);
780a115fb62SHans Petter Selasky 		CC_LOCK(cc);
781a115fb62SHans Petter Selasky #else
782a115fb62SHans Petter Selasky 		panic("migration should not happen");
783a115fb62SHans Petter Selasky #endif
784a115fb62SHans Petter Selasky 	}
7856098e7acSKonstantin Belousov }
7866098e7acSKonstantin Belousov 
787219d632cSMatthew Dillon /*
788ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
789ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
790ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
791ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
792024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
793ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
794ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
795ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
796ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
797ab36c067SJustin T. Gibbs  */
798a50ec505SPoul-Henning Kamp 
799ab36c067SJustin T. Gibbs /*
800df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
801df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
802df8bae1dSRodney W. Grimes  */
803df8bae1dSRodney W. Grimes void
8048d809d50SJeff Roberson softclock(void *arg)
805df8bae1dSRodney W. Grimes {
8068d809d50SJeff Roberson 	struct callout_cpu *cc;
807b336df68SPoul-Henning Kamp 	struct callout *c;
8085b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8095b999a6bSDavide Italiano 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
8105b999a6bSDavide Italiano #endif
811df8bae1dSRodney W. Grimes 
8128d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
8138d809d50SJeff Roberson 	CC_LOCK(cc);
8145b999a6bSDavide Italiano 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
8155b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
8165b999a6bSDavide Italiano 		softclock_call_cc(c, cc,
8175b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8185b999a6bSDavide Italiano 		    &mpcalls, &lockcalls, &gcalls,
8195b999a6bSDavide Italiano #endif
8205b999a6bSDavide Italiano 		    0);
8215b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8225b999a6bSDavide Italiano 		++depth;
8235b999a6bSDavide Italiano #endif
824df8bae1dSRodney W. Grimes 	}
8255b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
82622ee8c4fSPoul-Henning Kamp 	avg_depth += (depth * 1000 - avg_depth) >> 8;
82722ee8c4fSPoul-Henning Kamp 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
82864b9ee20SAttilio Rao 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
82922ee8c4fSPoul-Henning Kamp 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8305b999a6bSDavide Italiano #endif
8318d809d50SJeff Roberson 	CC_UNLOCK(cc);
832df8bae1dSRodney W. Grimes }
833df8bae1dSRodney W. Grimes 
834a9e182e8SKonstantin Belousov void
835a9e182e8SKonstantin Belousov callout_when(sbintime_t sbt, sbintime_t precision, int flags,
836a9e182e8SKonstantin Belousov     sbintime_t *res, sbintime_t *prec_res)
837acc8326dSGarrett Wollman {
838a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, to_pr;
839acc8326dSGarrett Wollman 
840a9e182e8SKonstantin Belousov 	if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
841a9e182e8SKonstantin Belousov 		*res = sbt;
842a9e182e8SKonstantin Belousov 		*prec_res = precision;
843a9e182e8SKonstantin Belousov 		return;
84415b1eb14SRandall Stewart 	}
845a9e182e8SKonstantin Belousov 	if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
8465b999a6bSDavide Italiano 		sbt = tick_sbt;
847a28c28e6SMark Johnston 	if ((flags & C_HARDCLOCK) != 0 || sbt >= sbt_tickthreshold) {
8485b999a6bSDavide Italiano 		/*
8495b999a6bSDavide Italiano 		 * Obtain the time of the last hardclock() call on
8505b999a6bSDavide Italiano 		 * this CPU directly from the kern_clocksource.c.
8515b999a6bSDavide Italiano 		 * This value is per-CPU, but it is equal for all
8525b999a6bSDavide Italiano 		 * active ones.
8535b999a6bSDavide Italiano 		 */
8545b999a6bSDavide Italiano #ifdef __LP64__
855a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
8565b999a6bSDavide Italiano #else
8575b999a6bSDavide Italiano 		spinlock_enter();
858a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
8595b999a6bSDavide Italiano 		spinlock_exit();
8605b999a6bSDavide Italiano #endif
8619f3aabb9SJohn Baldwin 		if (cold && to_sbt == 0)
8629f3aabb9SJohn Baldwin 			to_sbt = sbinuptime();
863a115fb62SHans Petter Selasky 		if ((flags & C_HARDCLOCK) == 0)
864a115fb62SHans Petter Selasky 			to_sbt += tick_sbt;
8655b999a6bSDavide Italiano 	} else
866a115fb62SHans Petter Selasky 		to_sbt = sbinuptime();
867a115fb62SHans Petter Selasky 	if (SBT_MAX - to_sbt < sbt)
868a115fb62SHans Petter Selasky 		to_sbt = SBT_MAX;
8691b0c144fSDavide Italiano 	else
870a115fb62SHans Petter Selasky 		to_sbt += sbt;
871a9e182e8SKonstantin Belousov 	*res = to_sbt;
872a9e182e8SKonstantin Belousov 	to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
873a115fb62SHans Petter Selasky 	    sbt >> C_PRELGET(flags));
874a9e182e8SKonstantin Belousov 	*prec_res = to_pr > precision ? to_pr : precision;
875a115fb62SHans Petter Selasky }
876a9e182e8SKonstantin Belousov 
877a9e182e8SKonstantin Belousov /*
878a9e182e8SKonstantin Belousov  * New interface; clients allocate their own callout structures.
879a9e182e8SKonstantin Belousov  *
880a9e182e8SKonstantin Belousov  * callout_reset() - establish or change a timeout
881a9e182e8SKonstantin Belousov  * callout_stop() - disestablish a timeout
882a9e182e8SKonstantin Belousov  * callout_init() - initialize a callout structure so that it can
883a9e182e8SKonstantin Belousov  *	safely be passed to callout_reset() and callout_stop()
884a9e182e8SKonstantin Belousov  *
885a9e182e8SKonstantin Belousov  * <sys/callout.h> defines three convenience macros:
886a9e182e8SKonstantin Belousov  *
887a9e182e8SKonstantin Belousov  * callout_active() - returns truth if callout has not been stopped,
888a9e182e8SKonstantin Belousov  *	drained, or deactivated since the last time the callout was
889a9e182e8SKonstantin Belousov  *	reset.
890a9e182e8SKonstantin Belousov  * callout_pending() - returns truth if callout is still waiting for timeout
891a9e182e8SKonstantin Belousov  * callout_deactivate() - marks the callout as having been serviced
892a9e182e8SKonstantin Belousov  */
893a9e182e8SKonstantin Belousov int
894a9e182e8SKonstantin Belousov callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
895a8a03706SJohn Baldwin     callout_func_t *ftn, void *arg, int cpu, int flags)
896a9e182e8SKonstantin Belousov {
897a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, precision;
898a9e182e8SKonstantin Belousov 	struct callout_cpu *cc;
899a9e182e8SKonstantin Belousov 	int cancelled, direct;
900a9e182e8SKonstantin Belousov 	int ignore_cpu=0;
901a9e182e8SKonstantin Belousov 
902a9e182e8SKonstantin Belousov 	cancelled = 0;
903a9e182e8SKonstantin Belousov 	if (cpu == -1) {
904a9e182e8SKonstantin Belousov 		ignore_cpu = 1;
905a9e182e8SKonstantin Belousov 	} else if ((cpu >= MAXCPU) ||
906a9e182e8SKonstantin Belousov 		   ((CC_CPU(cpu))->cc_inited == 0)) {
907a9e182e8SKonstantin Belousov 		/* Invalid CPU spec */
908a9e182e8SKonstantin Belousov 		panic("Invalid CPU in callout %d", cpu);
909a9e182e8SKonstantin Belousov 	}
910a9e182e8SKonstantin Belousov 	callout_when(sbt, prec, flags, &to_sbt, &precision);
911a9e182e8SKonstantin Belousov 
912a115fb62SHans Petter Selasky 	/*
91366525b2dSRandall Stewart 	 * This flag used to be added by callout_cc_add, but the
91466525b2dSRandall Stewart 	 * first time you call this we could end up with the
91566525b2dSRandall Stewart 	 * wrong direct flag if we don't do it before we add.
91666525b2dSRandall Stewart 	 */
91766525b2dSRandall Stewart 	if (flags & C_DIRECT_EXEC) {
91815b1eb14SRandall Stewart 		direct = 1;
91915b1eb14SRandall Stewart 	} else {
92015b1eb14SRandall Stewart 		direct = 0;
92166525b2dSRandall Stewart 	}
922a115fb62SHans Petter Selasky 	KASSERT(!direct || c->c_lock == NULL,
923a115fb62SHans Petter Selasky 	    ("%s: direct callout %p has lock", __func__, c));
924a115fb62SHans Petter Selasky 	cc = callout_lock(c);
92515b1eb14SRandall Stewart 	/*
9264b28d96eSJohn Baldwin 	 * Don't allow migration if the user does not care.
92715b1eb14SRandall Stewart 	 */
9284b28d96eSJohn Baldwin 	if (ignore_cpu) {
92915b1eb14SRandall Stewart 		cpu = c->c_cpu;
93015b1eb14SRandall Stewart 	}
93115b1eb14SRandall Stewart 
932d2854fa4SRandall Stewart 	if (cc_exec_curr(cc, direct) == c) {
933a115fb62SHans Petter Selasky 		/*
934a115fb62SHans Petter Selasky 		 * We're being asked to reschedule a callout which is
935a115fb62SHans Petter Selasky 		 * currently in progress.  If there is a lock then we
936a115fb62SHans Petter Selasky 		 * can cancel the callout if it has not really started.
937a115fb62SHans Petter Selasky 		 */
938378d5c6cSAndriy Gapon 		if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
939d2854fa4SRandall Stewart 			cancelled = cc_exec_cancel(cc, direct) = true;
940dc4ee9a8SGleb Smirnoff 		if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
941a115fb62SHans Petter Selasky 			/*
942a115fb62SHans Petter Selasky 			 * Someone has called callout_drain to kill this
943a115fb62SHans Petter Selasky 			 * callout.  Don't reschedule.
944a115fb62SHans Petter Selasky 			 */
945a115fb62SHans Petter Selasky 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
946a115fb62SHans Petter Selasky 			    cancelled ? "cancelled" : "failed to cancel",
947a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
948a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
949a115fb62SHans Petter Selasky 			return (cancelled);
950a115fb62SHans Petter Selasky 		}
951d2854fa4SRandall Stewart #ifdef SMP
952d2854fa4SRandall Stewart 		if (callout_migrating(c)) {
953d2854fa4SRandall Stewart 			/*
954d2854fa4SRandall Stewart 			 * This only occurs when a second callout_reset_sbt_on
955d2854fa4SRandall Stewart 			 * is made after a previous one moved it into
956d2854fa4SRandall Stewart 			 * deferred migration (below). Note we do *not* change
957d2854fa4SRandall Stewart 			 * the prev_cpu even though the previous target may
958d2854fa4SRandall Stewart 			 * be different.
959d2854fa4SRandall Stewart 			 */
960d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
961d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
962d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
963d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
964d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
965d2854fa4SRandall Stewart 			cancelled = 1;
966d2854fa4SRandall Stewart 			CC_UNLOCK(cc);
967d2854fa4SRandall Stewart 			return (cancelled);
968d2854fa4SRandall Stewart 		}
969d2854fa4SRandall Stewart #endif
970a115fb62SHans Petter Selasky 	}
97115b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_PENDING) {
97215b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
97366525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
97466525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
975a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
97615b1eb14SRandall Stewart 		} else {
977a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
97815b1eb14SRandall Stewart 		}
979a115fb62SHans Petter Selasky 		cancelled = 1;
98015b1eb14SRandall Stewart 		c->c_iflags &= ~ CALLOUT_PENDING;
98115b1eb14SRandall Stewart 		c->c_flags &= ~ CALLOUT_ACTIVE;
9828d809d50SJeff Roberson 	}
9831283e9cdSAttilio Rao 
984a115fb62SHans Petter Selasky #ifdef SMP
985a115fb62SHans Petter Selasky 	/*
986a115fb62SHans Petter Selasky 	 * If the callout must migrate try to perform it immediately.
987a115fb62SHans Petter Selasky 	 * If the callout is currently running, just defer the migration
988a115fb62SHans Petter Selasky 	 * to a more appropriate moment.
989a115fb62SHans Petter Selasky 	 */
990a115fb62SHans Petter Selasky 	if (c->c_cpu != cpu) {
991d2854fa4SRandall Stewart 		if (cc_exec_curr(cc, direct) == c) {
992d2854fa4SRandall Stewart 			/*
993d2854fa4SRandall Stewart 			 * Pending will have been removed since we are
994d2854fa4SRandall Stewart 			 * actually executing the callout on another
995d2854fa4SRandall Stewart 			 * CPU. That callout should be waiting on the
996d2854fa4SRandall Stewart 			 * lock the caller holds. If we set both
997d2854fa4SRandall Stewart 			 * active/and/pending after we return and the
998d2854fa4SRandall Stewart 			 * lock on the executing callout proceeds, it
999d2854fa4SRandall Stewart 			 * will then see pending is true and return.
1000d2854fa4SRandall Stewart 			 * At the return from the actual callout execution
1001d2854fa4SRandall Stewart 			 * the migration will occur in softclock_call_cc
1002d2854fa4SRandall Stewart 			 * and this new callout will be placed on the
1003d2854fa4SRandall Stewart 			 * new CPU via a call to callout_cpu_switch() which
1004d2854fa4SRandall Stewart 			 * will get the lock on the right CPU followed
1005d2854fa4SRandall Stewart 			 * by a call callout_cc_add() which will add it there.
1006d2854fa4SRandall Stewart 			 * (see above in softclock_call_cc()).
1007d2854fa4SRandall Stewart 			 */
1008d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1009d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1010d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1011d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1012d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
101315b1eb14SRandall Stewart 			c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
101415b1eb14SRandall Stewart 			c->c_flags |= CALLOUT_ACTIVE;
1015a115fb62SHans Petter Selasky 			CTR6(KTR_CALLOUT,
1016a115fb62SHans Petter Selasky 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1017a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1018a115fb62SHans Petter Selasky 			    (u_int)(to_sbt & 0xffffffff), cpu);
1019a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1020a115fb62SHans Petter Selasky 			return (cancelled);
1021a115fb62SHans Petter Selasky 		}
1022a115fb62SHans Petter Selasky 		cc = callout_cpu_switch(c, cc, cpu);
1023a115fb62SHans Petter Selasky 	}
1024a115fb62SHans Petter Selasky #endif
1025a115fb62SHans Petter Selasky 
102666525b2dSRandall Stewart 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1027a115fb62SHans Petter Selasky 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1028a115fb62SHans Petter Selasky 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1029a115fb62SHans Petter Selasky 	    (u_int)(to_sbt & 0xffffffff));
1030a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
1031a115fb62SHans Petter Selasky 
1032a115fb62SHans Petter Selasky 	return (cancelled);
1033acc8326dSGarrett Wollman }
1034acc8326dSGarrett Wollman 
10356e0186d5SSam Leffler /*
10366e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
10376e0186d5SSam Leffler  */
10386e0186d5SSam Leffler int
10396e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
10406e0186d5SSam Leffler {
10416e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
10426e0186d5SSam Leffler }
10436e0186d5SSam Leffler 
10446e0186d5SSam Leffler int
10456e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
10466e0186d5SSam Leffler {
10476e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
10486e0186d5SSam Leffler }
10496e0186d5SSam Leffler 
10502c1bb207SColin Percival int
1051a8a03706SJohn Baldwin _callout_stop_safe(struct callout *c, int flags, callout_func_t *drain)
10522c1bb207SColin Percival {
1053a115fb62SHans Petter Selasky 	struct callout_cpu *cc, *old_cc;
1054a115fb62SHans Petter Selasky 	struct lock_class *class;
1055a115fb62SHans Petter Selasky 	int direct, sq_locked, use_lock;
105647e42809SGleb Smirnoff 	int cancelled, not_on_a_list;
10571283e9cdSAttilio Rao 
10585db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) != 0)
10599500dd9fSAdrian Chadd 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
10609500dd9fSAdrian Chadd 		    "calling %s", __func__);
10619500dd9fSAdrian Chadd 
10620d0053d7SHans Petter Selasky 	KASSERT((flags & CS_DRAIN) == 0 || drain == NULL,
10630d0053d7SHans Petter Selasky 	    ("Cannot set drain callback and CS_DRAIN flag at the same time"));
10640d0053d7SHans Petter Selasky 
10651283e9cdSAttilio Rao 	/*
1066a115fb62SHans Petter Selasky 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1067a115fb62SHans Petter Selasky 	 * so just discard this check for the moment.
10681283e9cdSAttilio Rao 	 */
10695db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1070a115fb62SHans Petter Selasky 		if (c->c_lock == &Giant.lock_object)
1071a115fb62SHans Petter Selasky 			use_lock = mtx_owned(&Giant);
1072a115fb62SHans Petter Selasky 		else {
1073a115fb62SHans Petter Selasky 			use_lock = 1;
1074a115fb62SHans Petter Selasky 			class = LOCK_CLASS(c->c_lock);
1075a115fb62SHans Petter Selasky 			class->lc_assert(c->c_lock, LA_XLOCKED);
10761283e9cdSAttilio Rao 		}
1077a115fb62SHans Petter Selasky 	} else
1078a115fb62SHans Petter Selasky 		use_lock = 0;
107915b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_DIRECT) {
108015b1eb14SRandall Stewart 		direct = 1;
108115b1eb14SRandall Stewart 	} else {
108215b1eb14SRandall Stewart 		direct = 0;
108315b1eb14SRandall Stewart 	}
1084a115fb62SHans Petter Selasky 	sq_locked = 0;
1085a115fb62SHans Petter Selasky 	old_cc = NULL;
1086a115fb62SHans Petter Selasky again:
1087a115fb62SHans Petter Selasky 	cc = callout_lock(c);
1088a115fb62SHans Petter Selasky 
108915b1eb14SRandall Stewart 	if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
109015b1eb14SRandall Stewart 	    (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
109115b1eb14SRandall Stewart 	    ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1092d2854fa4SRandall Stewart 		/*
1093d2854fa4SRandall Stewart 		 * Special case where this slipped in while we
1094d2854fa4SRandall Stewart 		 * were migrating *as* the callout is about to
1095d2854fa4SRandall Stewart 		 * execute. The caller probably holds the lock
1096d2854fa4SRandall Stewart 		 * the callout wants.
1097d2854fa4SRandall Stewart 		 *
1098d2854fa4SRandall Stewart 		 * Get rid of the migration first. Then set
1099d2854fa4SRandall Stewart 		 * the flag that tells this code *not* to
1100d2854fa4SRandall Stewart 		 * try to remove it from any lists (its not
1101d2854fa4SRandall Stewart 		 * on one yet). When the callout wheel runs,
1102d2854fa4SRandall Stewart 		 * it will ignore this callout.
1103d2854fa4SRandall Stewart 		 */
110415b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_PENDING;
110515b1eb14SRandall Stewart 		c->c_flags &= ~CALLOUT_ACTIVE;
1106d2854fa4SRandall Stewart 		not_on_a_list = 1;
1107d2854fa4SRandall Stewart 	} else {
1108d2854fa4SRandall Stewart 		not_on_a_list = 0;
1109d2854fa4SRandall Stewart 	}
1110d2854fa4SRandall Stewart 
1111a115fb62SHans Petter Selasky 	/*
1112a115fb62SHans Petter Selasky 	 * If the callout was migrating while the callout cpu lock was
1113a115fb62SHans Petter Selasky 	 * dropped,  just drop the sleepqueue lock and check the states
1114a115fb62SHans Petter Selasky 	 * again.
1115a115fb62SHans Petter Selasky 	 */
1116a115fb62SHans Petter Selasky 	if (sq_locked != 0 && cc != old_cc) {
1117a115fb62SHans Petter Selasky #ifdef SMP
1118a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
1119d2854fa4SRandall Stewart 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1120a115fb62SHans Petter Selasky 		sq_locked = 0;
1121a115fb62SHans Petter Selasky 		old_cc = NULL;
1122a115fb62SHans Petter Selasky 		goto again;
1123a115fb62SHans Petter Selasky #else
1124a115fb62SHans Petter Selasky 		panic("migration should not happen");
1125a115fb62SHans Petter Selasky #endif
1126a115fb62SHans Petter Selasky 	}
112747e42809SGleb Smirnoff 
1128a115fb62SHans Petter Selasky 	/*
112947e42809SGleb Smirnoff 	 * If the callout is running, try to stop it or drain it.
1130a115fb62SHans Petter Selasky 	 */
113147e42809SGleb Smirnoff 	if (cc_exec_curr(cc, direct) == c) {
1132a115fb62SHans Petter Selasky 		/*
113347e42809SGleb Smirnoff 		 * Succeed we to stop it or not, we must clear the
11347d88be4cSMark Johnston 		 * active flag - this is what API users expect.  If we're
11357d88be4cSMark Johnston 		 * draining and the callout is currently executing, first wait
11367d88be4cSMark Johnston 		 * until it finishes.
1137a115fb62SHans Petter Selasky 		 */
11387d88be4cSMark Johnston 		if ((flags & CS_DRAIN) == 0)
113918b4fd62SRandall Stewart 			c->c_flags &= ~CALLOUT_ACTIVE;
114047e42809SGleb Smirnoff 
11415db9ed80SKonstantin Belousov 		if ((flags & CS_DRAIN) != 0) {
1142a115fb62SHans Petter Selasky 			/*
1143a115fb62SHans Petter Selasky 			 * The current callout is running (or just
1144a115fb62SHans Petter Selasky 			 * about to run) and blocking is allowed, so
1145a115fb62SHans Petter Selasky 			 * just wait for the current invocation to
1146a115fb62SHans Petter Selasky 			 * finish.
1147a115fb62SHans Petter Selasky 			 */
1148a33fef5eSMark Johnston 			if (cc_exec_curr(cc, direct) == c) {
1149a115fb62SHans Petter Selasky 				/*
1150a115fb62SHans Petter Selasky 				 * Use direct calls to sleepqueue interface
1151a115fb62SHans Petter Selasky 				 * instead of cv/msleep in order to avoid
1152a115fb62SHans Petter Selasky 				 * a LOR between cc_lock and sleepqueue
1153a115fb62SHans Petter Selasky 				 * chain spinlocks.  This piece of code
1154a115fb62SHans Petter Selasky 				 * emulates a msleep_spin() call actually.
1155a115fb62SHans Petter Selasky 				 *
1156a115fb62SHans Petter Selasky 				 * If we already have the sleepqueue chain
1157a115fb62SHans Petter Selasky 				 * locked, then we can safely block.  If we
1158a115fb62SHans Petter Selasky 				 * don't already have it locked, however,
1159a115fb62SHans Petter Selasky 				 * we have to drop the cc_lock to lock
1160a115fb62SHans Petter Selasky 				 * it.  This opens several races, so we
1161a115fb62SHans Petter Selasky 				 * restart at the beginning once we have
1162a115fb62SHans Petter Selasky 				 * both locks.  If nothing has changed, then
1163a115fb62SHans Petter Selasky 				 * we will end up back here with sq_locked
1164a115fb62SHans Petter Selasky 				 * set.
1165a115fb62SHans Petter Selasky 				 */
1166a115fb62SHans Petter Selasky 				if (!sq_locked) {
1167a115fb62SHans Petter Selasky 					CC_UNLOCK(cc);
1168a115fb62SHans Petter Selasky 					sleepq_lock(
1169d2854fa4SRandall Stewart 					    &cc_exec_waiting(cc, direct));
1170a115fb62SHans Petter Selasky 					sq_locked = 1;
1171a115fb62SHans Petter Selasky 					old_cc = cc;
1172a115fb62SHans Petter Selasky 					goto again;
1173a115fb62SHans Petter Selasky 				}
117447e42809SGleb Smirnoff 
1175a115fb62SHans Petter Selasky 				/*
1176a115fb62SHans Petter Selasky 				 * Migration could be cancelled here, but
1177a115fb62SHans Petter Selasky 				 * as long as it is still not sure when it
1178a115fb62SHans Petter Selasky 				 * will be packed up, just let softclock()
1179a115fb62SHans Petter Selasky 				 * take care of it.
1180a115fb62SHans Petter Selasky 				 */
1181d2854fa4SRandall Stewart 				cc_exec_waiting(cc, direct) = true;
1182a115fb62SHans Petter Selasky 				DROP_GIANT();
1183a115fb62SHans Petter Selasky 				CC_UNLOCK(cc);
1184a115fb62SHans Petter Selasky 				sleepq_add(
1185d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1186a115fb62SHans Petter Selasky 				    &cc->cc_lock.lock_object, "codrain",
1187a115fb62SHans Petter Selasky 				    SLEEPQ_SLEEP, 0);
1188a115fb62SHans Petter Selasky 				sleepq_wait(
1189d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1190a115fb62SHans Petter Selasky 					     0);
1191a115fb62SHans Petter Selasky 				sq_locked = 0;
1192a115fb62SHans Petter Selasky 				old_cc = NULL;
1193a115fb62SHans Petter Selasky 
1194a115fb62SHans Petter Selasky 				/* Reacquire locks previously released. */
1195a115fb62SHans Petter Selasky 				PICKUP_GIANT();
1196a33fef5eSMark Johnston 				goto again;
1197a115fb62SHans Petter Selasky 			}
11987d88be4cSMark Johnston 			c->c_flags &= ~CALLOUT_ACTIVE;
1199a115fb62SHans Petter Selasky 		} else if (use_lock &&
120018b4fd62SRandall Stewart 			   !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1201d2854fa4SRandall Stewart 
1202a115fb62SHans Petter Selasky 			/*
1203a115fb62SHans Petter Selasky 			 * The current callout is waiting for its
1204a115fb62SHans Petter Selasky 			 * lock which we hold.  Cancel the callout
1205a115fb62SHans Petter Selasky 			 * and return.  After our caller drops the
1206a115fb62SHans Petter Selasky 			 * lock, the callout will be skipped in
120718b4fd62SRandall Stewart 			 * softclock(). This *only* works with a
120818b4fd62SRandall Stewart 			 * callout_stop() *not* callout_drain() or
120918b4fd62SRandall Stewart 			 * callout_async_drain().
1210a115fb62SHans Petter Selasky 			 */
1211d2854fa4SRandall Stewart 			cc_exec_cancel(cc, direct) = true;
1212a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1213a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1214a115fb62SHans Petter Selasky 			KASSERT(!cc_cce_migrating(cc, direct),
1215a115fb62SHans Petter Selasky 			    ("callout wrongly scheduled for migration"));
121615b1eb14SRandall Stewart 			if (callout_migrating(c)) {
121715b1eb14SRandall Stewart 				c->c_iflags &= ~CALLOUT_DFRMIGRATION;
121815b1eb14SRandall Stewart #ifdef SMP
121915b1eb14SRandall Stewart 				cc_migration_cpu(cc, direct) = CPUBLOCK;
122015b1eb14SRandall Stewart 				cc_migration_time(cc, direct) = 0;
122115b1eb14SRandall Stewart 				cc_migration_prec(cc, direct) = 0;
122215b1eb14SRandall Stewart 				cc_migration_func(cc, direct) = NULL;
122315b1eb14SRandall Stewart 				cc_migration_arg(cc, direct) = NULL;
122415b1eb14SRandall Stewart #endif
122515b1eb14SRandall Stewart 			}
1226a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1227a115fb62SHans Petter Selasky 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1228a115fb62SHans Petter Selasky 			return (1);
1229d2854fa4SRandall Stewart 		} else if (callout_migrating(c)) {
1230d2854fa4SRandall Stewart 			/*
1231d2854fa4SRandall Stewart 			 * The callout is currently being serviced
1232d2854fa4SRandall Stewart 			 * and the "next" callout is scheduled at
1233d2854fa4SRandall Stewart 			 * its completion with a migration. We remove
1234d2854fa4SRandall Stewart 			 * the migration flag so it *won't* get rescheduled,
1235d2854fa4SRandall Stewart 			 * but we can't stop the one thats running so
1236d2854fa4SRandall Stewart 			 * we return 0.
1237d2854fa4SRandall Stewart 			 */
123815b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1239d2854fa4SRandall Stewart #ifdef SMP
1240d2854fa4SRandall Stewart 			/*
1241d2854fa4SRandall Stewart 			 * We can't call cc_cce_cleanup here since
1242d2854fa4SRandall Stewart 			 * if we do it will remove .ce_curr and
1243d2854fa4SRandall Stewart 			 * its still running. This will prevent a
1244d2854fa4SRandall Stewart 			 * reschedule of the callout when the
1245d2854fa4SRandall Stewart 			 * execution completes.
1246d2854fa4SRandall Stewart 			 */
1247d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1248d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = 0;
1249d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = 0;
1250d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = NULL;
1251d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = NULL;
1252d2854fa4SRandall Stewart #endif
1253a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1254a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
125518b4fd62SRandall Stewart  			if (drain) {
1256624677faSHans Petter Selasky 				KASSERT(cc_exec_drain(cc, direct) == NULL,
1257624677faSHans Petter Selasky 				    ("callout drain function already set to %p",
1258624677faSHans Petter Selasky 				    cc_exec_drain(cc, direct)));
125918b4fd62SRandall Stewart 				cc_exec_drain(cc, direct) = drain;
126018b4fd62SRandall Stewart 			}
1261a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1262d153eeeeSGleb Smirnoff 			return ((flags & CS_EXECUTING) != 0);
12630d0053d7SHans Petter Selasky 		} else {
1264a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1265a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
126618b4fd62SRandall Stewart 			if (drain) {
1267624677faSHans Petter Selasky 				KASSERT(cc_exec_drain(cc, direct) == NULL,
1268624677faSHans Petter Selasky 				    ("callout drain function already set to %p",
1269624677faSHans Petter Selasky 				    cc_exec_drain(cc, direct)));
127018b4fd62SRandall Stewart 				cc_exec_drain(cc, direct) = drain;
127118b4fd62SRandall Stewart 			}
12720d0053d7SHans Petter Selasky 		}
12733d84a188SRandall Stewart 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
127447e42809SGleb Smirnoff 		cancelled = ((flags & CS_EXECUTING) != 0);
127547e42809SGleb Smirnoff 	} else
127647e42809SGleb Smirnoff 		cancelled = 1;
127747e42809SGleb Smirnoff 
12783d84a188SRandall Stewart 	if (sq_locked)
12793d84a188SRandall Stewart 		sleepq_release(&cc_exec_waiting(cc, direct));
1280d153eeeeSGleb Smirnoff 
128147e42809SGleb Smirnoff 	if ((c->c_iflags & CALLOUT_PENDING) == 0) {
128247e42809SGleb Smirnoff 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
128347e42809SGleb Smirnoff 		    c, c->c_func, c->c_arg);
12849f339124SGleb Smirnoff 		/*
12859f339124SGleb Smirnoff 		 * For not scheduled and not executing callout return
12869f339124SGleb Smirnoff 		 * negative value.
12879f339124SGleb Smirnoff 		 */
12889f339124SGleb Smirnoff 		if (cc_exec_curr(cc, direct) != c)
12899f339124SGleb Smirnoff 			cancelled = -1;
129047e42809SGleb Smirnoff 		CC_UNLOCK(cc);
12919f339124SGleb Smirnoff 		return (cancelled);
129247e42809SGleb Smirnoff 	}
129347e42809SGleb Smirnoff 
129415b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
129515b1eb14SRandall Stewart 	c->c_flags &= ~CALLOUT_ACTIVE;
12961283e9cdSAttilio Rao 
129768a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
129868a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
1299d2854fa4SRandall Stewart 	if (not_on_a_list == 0) {
130015b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
130166525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
130266525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1303a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
130415b1eb14SRandall Stewart 		} else {
1305a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1306d2854fa4SRandall Stewart 		}
130715b1eb14SRandall Stewart 	}
1308a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
130947e42809SGleb Smirnoff 	return (cancelled);
1310acc8326dSGarrett Wollman }
1311acc8326dSGarrett Wollman 
1312acc8326dSGarrett Wollman void
1313e392e44cSDavide Italiano callout_init(struct callout *c, int mpsafe)
1314acc8326dSGarrett Wollman {
1315a115fb62SHans Petter Selasky 	bzero(c, sizeof *c);
131698c926b2SIan Dowse 	if (mpsafe) {
1317a115fb62SHans Petter Selasky 		c->c_lock = NULL;
131815b1eb14SRandall Stewart 		c->c_iflags = CALLOUT_RETURNUNLOCKED;
131998c926b2SIan Dowse 	} else {
1320a115fb62SHans Petter Selasky 		c->c_lock = &Giant.lock_object;
132115b1eb14SRandall Stewart 		c->c_iflags = 0;
132298c926b2SIan Dowse 	}
13234b28d96eSJohn Baldwin 	c->c_cpu = cc_default_cpu;
132498c926b2SIan Dowse }
132598c926b2SIan Dowse 
132698c926b2SIan Dowse void
1327e392e44cSDavide Italiano _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
132898c926b2SIan Dowse {
132998c926b2SIan Dowse 	bzero(c, sizeof *c);
133064b9ee20SAttilio Rao 	c->c_lock = lock;
1331a115fb62SHans Petter Selasky 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1332a115fb62SHans Petter Selasky 	    ("callout_init_lock: bad flags %d", flags));
1333a115fb62SHans Petter Selasky 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1334a115fb62SHans Petter Selasky 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1335a115fb62SHans Petter Selasky 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1336a115fb62SHans Petter Selasky 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1337a115fb62SHans Petter Selasky 	    __func__));
133815b1eb14SRandall Stewart 	c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
13394b28d96eSJohn Baldwin 	c->c_cpu = cc_default_cpu;
1340acc8326dSGarrett Wollman }
1341acc8326dSGarrett Wollman 
13425b999a6bSDavide Italiano static int
13435b999a6bSDavide Italiano flssbt(sbintime_t sbt)
13445b999a6bSDavide Italiano {
13455b999a6bSDavide Italiano 
13465b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
13475b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
13485b999a6bSDavide Italiano 		return (flsl(sbt));
13495b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
13505b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
13515b999a6bSDavide Italiano 	return (flsl(sbt));
13525b999a6bSDavide Italiano }
13535b999a6bSDavide Italiano 
13545b999a6bSDavide Italiano /*
13555b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
13565b999a6bSDavide Italiano  */
13575b999a6bSDavide Italiano static int
13585b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
13595b999a6bSDavide Italiano {
13605b999a6bSDavide Italiano 	struct callout *tmp;
13615b999a6bSDavide Italiano 	struct callout_cpu *cc;
13625b999a6bSDavide Italiano 	struct callout_list *sc;
13635b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
13645b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
13655b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
13665b999a6bSDavide Italiano 	int cpu;
13675b999a6bSDavide Italiano 
13685b999a6bSDavide Italiano 	val = 0;
13695b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
13705b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
13715b999a6bSDavide Italiano 		return (error);
13725b999a6bSDavide Italiano 	count = maxc = 0;
13735b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
13745b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
13755b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
13765b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
13775b999a6bSDavide Italiano 	now = sbinuptime();
13785b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
13795b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
13805b999a6bSDavide Italiano 		CC_LOCK(cc);
13815b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
13825b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
13835b999a6bSDavide Italiano 			c = 0;
13845b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
13855b999a6bSDavide Italiano 				c++;
13865b999a6bSDavide Italiano 				t = tmp->c_time - now;
13875b999a6bSDavide Italiano 				if (t < 0)
13885b999a6bSDavide Italiano 					t = 0;
13895b999a6bSDavide Italiano 				st += t / SBT_1US;
13905b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
13915b999a6bSDavide Italiano 				if (t > maxt)
13925b999a6bSDavide Italiano 					maxt = t;
13935b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
13945b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
13955b999a6bSDavide Italiano 				ct[flssbt(t)]++;
13965b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
13975b999a6bSDavide Italiano 			}
13985b999a6bSDavide Italiano 			if (c > maxc)
13995b999a6bSDavide Italiano 				maxc = c;
14005b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
14015b999a6bSDavide Italiano 			count += c;
14025b999a6bSDavide Italiano 		}
14035b999a6bSDavide Italiano 		CC_UNLOCK(cc);
14045b999a6bSDavide Italiano 	}
14055b999a6bSDavide Italiano 
14065b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
14075b999a6bSDavide Italiano 		tcum += ct[i];
14085b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14095b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
14105b999a6bSDavide Italiano 		pcum += cpr[i];
14115b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14125b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
14135b999a6bSDavide Italiano 		c += ccpbk[i];
14145b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
14155b999a6bSDavide Italiano 
14165b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
14175b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
14185b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
14195b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
14205b999a6bSDavide Italiano 	    medc,
14215b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
14225b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
14235b999a6bSDavide Italiano 	    maxc);
14245b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14255b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
14265b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
14275b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
14285b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14295b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
14305b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
14315b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
14325b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
14335b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
14345b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
14355b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
14365b999a6bSDavide Italiano 			continue;
14375b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
14385b999a6bSDavide Italiano 		tcum += ct[i];
14395b999a6bSDavide Italiano 		pcum += cpr[i];
14405b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
14415b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
14425b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
14435b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
14445b999a6bSDavide Italiano 	}
14455b999a6bSDavide Italiano 	return (error);
14465b999a6bSDavide Italiano }
14475b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
14485b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
14495b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
14505b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
145147e42809SGleb Smirnoff 
14523af72c11SBjoern A. Zeeb #ifdef DDB
14533af72c11SBjoern A. Zeeb static void
14543af72c11SBjoern A. Zeeb _show_callout(struct callout *c)
14553af72c11SBjoern A. Zeeb {
14563af72c11SBjoern A. Zeeb 
14573af72c11SBjoern A. Zeeb 	db_printf("callout %p\n", c);
14583af72c11SBjoern A. Zeeb #define	C_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, c->e);
14593af72c11SBjoern A. Zeeb 	db_printf("   &c_links = %p\n", &(c->c_links));
14603af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_time);
14613af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_precision);
14623af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_arg);
14633af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_func);
14643af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_lock);
14653af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_flags);
14663af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_iflags);
14673af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%d",	c_cpu);
14683af72c11SBjoern A. Zeeb #undef	C_DB_PRINTF
14693af72c11SBjoern A. Zeeb }
14703af72c11SBjoern A. Zeeb 
14713af72c11SBjoern A. Zeeb DB_SHOW_COMMAND(callout, db_show_callout)
14723af72c11SBjoern A. Zeeb {
14733af72c11SBjoern A. Zeeb 
14743af72c11SBjoern A. Zeeb 	if (!have_addr) {
14753af72c11SBjoern A. Zeeb 		db_printf("usage: show callout <struct callout *>\n");
14763af72c11SBjoern A. Zeeb 		return;
14773af72c11SBjoern A. Zeeb 	}
14783af72c11SBjoern A. Zeeb 
14793af72c11SBjoern A. Zeeb 	_show_callout((struct callout *)addr);
14803af72c11SBjoern A. Zeeb }
14818c5a9161SEric van Gyzen 
14828c5a9161SEric van Gyzen static void
14838c5a9161SEric van Gyzen _show_last_callout(int cpu, int direct, const char *dirstr)
14848c5a9161SEric van Gyzen {
14858c5a9161SEric van Gyzen 	struct callout_cpu *cc;
14868c5a9161SEric van Gyzen 	void *func, *arg;
14878c5a9161SEric van Gyzen 
14888c5a9161SEric van Gyzen 	cc = CC_CPU(cpu);
14898c5a9161SEric van Gyzen 	func = cc_exec_last_func(cc, direct);
14908c5a9161SEric van Gyzen 	arg = cc_exec_last_arg(cc, direct);
14918c5a9161SEric van Gyzen 	db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
14928c5a9161SEric van Gyzen 	db_printsym((db_expr_t)func, DB_STGY_ANY);
14938c5a9161SEric van Gyzen 	db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
14948c5a9161SEric van Gyzen }
14958c5a9161SEric van Gyzen 
14968c5a9161SEric van Gyzen DB_SHOW_COMMAND(callout_last, db_show_callout_last)
14978c5a9161SEric van Gyzen {
14988c5a9161SEric van Gyzen 	int cpu, last;
14998c5a9161SEric van Gyzen 
15008c5a9161SEric van Gyzen 	if (have_addr) {
15018c5a9161SEric van Gyzen 		if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
15028c5a9161SEric van Gyzen 			db_printf("no such cpu: %d\n", (int)addr);
15038c5a9161SEric van Gyzen 			return;
15048c5a9161SEric van Gyzen 		}
15058c5a9161SEric van Gyzen 		cpu = last = addr;
15068c5a9161SEric van Gyzen 	} else {
15078c5a9161SEric van Gyzen 		cpu = 0;
15088c5a9161SEric van Gyzen 		last = mp_maxid;
15098c5a9161SEric van Gyzen 	}
15108c5a9161SEric van Gyzen 
15118c5a9161SEric van Gyzen 	while (cpu <= last) {
15128c5a9161SEric van Gyzen 		if (!CPU_ABSENT(cpu)) {
15138c5a9161SEric van Gyzen 			_show_last_callout(cpu, 0, "");
15148c5a9161SEric van Gyzen 			_show_last_callout(cpu, 1, " direct");
15158c5a9161SEric van Gyzen 		}
15168c5a9161SEric van Gyzen 		cpu++;
15178c5a9161SEric van Gyzen 	}
15188c5a9161SEric van Gyzen }
15193af72c11SBjoern A. Zeeb #endif /* DDB */
1520