xref: /freebsd/sys/kern/kern_timeout.c (revision d2854fa4884e90e47fbcb3e455703b2b4b8c4904)
1df8bae1dSRodney W. Grimes /*-
2df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1991, 1993
3df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
5df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
6df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
7df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
18df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
19df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
20df8bae1dSRodney W. Grimes  *    without specific prior written permission.
21df8bae1dSRodney W. Grimes  *
22df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
33df8bae1dSRodney W. Grimes  *
34acc8326dSGarrett Wollman  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
37677b542eSDavid E. O'Brien #include <sys/cdefs.h>
38677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
39677b542eSDavid E. O'Brien 
405b999a6bSDavide Italiano #include "opt_callout_profiling.h"
415b999a6bSDavide Italiano #if defined(__arm__)
425b999a6bSDavide Italiano #include "opt_timer.h"
435b999a6bSDavide Italiano #endif
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>
50f8ccf82aSAndre Oppermann #include <sys/file.h>
518d809d50SJeff Roberson #include <sys/interrupt.h>
52df8bae1dSRodney W. Grimes #include <sys/kernel.h>
53ff7ec58aSRobert Watson #include <sys/ktr.h>
54f34fa851SJohn Baldwin #include <sys/lock.h>
558d809d50SJeff Roberson #include <sys/malloc.h>
56cb799bfeSJohn Baldwin #include <sys/mutex.h>
5721f9e816SJohn Baldwin #include <sys/proc.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>
62df8bae1dSRodney W. Grimes 
631283e9cdSAttilio Rao #ifdef SMP
641283e9cdSAttilio Rao #include <machine/cpu.h>
651283e9cdSAttilio Rao #endif
661283e9cdSAttilio Rao 
675b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
685b999a6bSDavide Italiano DPCPU_DECLARE(sbintime_t, hardclocktime);
695b999a6bSDavide Italiano #endif
705b999a6bSDavide Italiano 
7191dd9aaeSRobert Watson SDT_PROVIDER_DEFINE(callout_execute);
72d9fae5abSAndriy Gapon SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__start,
7391dd9aaeSRobert Watson     "struct callout *");
74d9fae5abSAndriy Gapon SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__end,
7591dd9aaeSRobert Watson     "struct callout *");
7691dd9aaeSRobert Watson 
775b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7822ee8c4fSPoul-Henning Kamp static int avg_depth;
7922ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8022ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
8122ee8c4fSPoul-Henning Kamp static int avg_gcalls;
8222ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
8322ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
8464b9ee20SAttilio Rao static int avg_lockcalls;
8564b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
8664b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
8722ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
8822ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
8922ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
905b999a6bSDavide Italiano static int avg_depth_dir;
915b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
925b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
935b999a6bSDavide Italiano     "Units = 1/1000");
945b999a6bSDavide Italiano static int avg_lockcalls_dir;
955b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
965b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
975b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
985b999a6bSDavide Italiano static int avg_mpcalls_dir;
995b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1005b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1015b999a6bSDavide Italiano     "Units = 1/1000");
1025b999a6bSDavide Italiano #endif
103f8ccf82aSAndre Oppermann 
104f8ccf82aSAndre Oppermann static int ncallout;
105af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
106f8ccf82aSAndre Oppermann     "Number of entries in callwheel and size of timeout() preallocation");
107f8ccf82aSAndre Oppermann 
108c445c3c7SAdrian Chadd #ifdef	RSS
109c445c3c7SAdrian Chadd static int pin_default_swi = 1;
110c445c3c7SAdrian Chadd static int pin_pcpu_swi = 1;
111c445c3c7SAdrian Chadd #else
112ac75ee9fSAdrian Chadd static int pin_default_swi = 0;
113ac75ee9fSAdrian Chadd static int pin_pcpu_swi = 0;
114c445c3c7SAdrian Chadd #endif
115ac75ee9fSAdrian Chadd 
116af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
117ac75ee9fSAdrian Chadd     0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
118af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
119ac75ee9fSAdrian Chadd     0, "Pin the per-CPU swis (except PCPU 0, which is also default");
120ac75ee9fSAdrian Chadd 
12115b7a470SPoul-Henning Kamp /*
12215b7a470SPoul-Henning Kamp  * TODO:
12315b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
12415b7a470SPoul-Henning Kamp  */
1253f555c45SDavide Italiano u_int callwheelsize, callwheelmask;
126f23b4c91SGarrett Wollman 
12720c510f8SLuigi Rizzo /*
128a115fb62SHans Petter Selasky  * The callout cpu exec entities represent informations necessary for
129a115fb62SHans Petter Selasky  * describing the state of callouts currently running on the CPU and the ones
130a115fb62SHans Petter Selasky  * necessary for migrating callouts to the new callout cpu. In particular,
131a115fb62SHans Petter Selasky  * the first entry of the array cc_exec_entity holds informations for callout
132a115fb62SHans Petter Selasky  * running in SWI thread context, while the second one holds informations
133a115fb62SHans Petter Selasky  * for callout running directly from hardware interrupt context.
134a115fb62SHans Petter Selasky  * The cached informations are very important for deferring migration when
135a115fb62SHans Petter Selasky  * the migrating callout is already running.
1361283e9cdSAttilio Rao  */
1375b999a6bSDavide Italiano struct cc_exec {
138a115fb62SHans Petter Selasky 	struct callout		*cc_next;
1395b999a6bSDavide Italiano 	struct callout		*cc_curr;
140a115fb62SHans Petter Selasky #ifdef SMP
141a115fb62SHans Petter Selasky 	void			(*ce_migration_func)(void *);
142a115fb62SHans Petter Selasky 	void			*ce_migration_arg;
143a115fb62SHans Petter Selasky 	int			ce_migration_cpu;
144a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_time;
145a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_prec;
146a115fb62SHans Petter Selasky #endif
147a4a3ce99SDavide Italiano 	bool			cc_cancel;
148a115fb62SHans Petter Selasky 	bool			cc_waiting;
1491283e9cdSAttilio Rao };
1501283e9cdSAttilio Rao 
1511283e9cdSAttilio Rao /*
152a115fb62SHans Petter Selasky  * There is one struct callout_cpu per cpu, holding all relevant
15320c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
15420c510f8SLuigi Rizzo  */
1558d809d50SJeff Roberson struct callout_cpu {
1564ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1575b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
1588d809d50SJeff Roberson 	struct callout		*cc_callout;
1595b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1605b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1615b999a6bSDavide Italiano 	struct callout_slist	cc_callfree;
1625b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1635b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
1648d809d50SJeff Roberson 	void			*cc_cookie;
1655b999a6bSDavide Italiano 	u_int			cc_bucket;
166232e8b52SJohn Baldwin 	char			cc_ktr_event_name[20];
1678d809d50SJeff Roberson };
1688d809d50SJeff Roberson 
169*d2854fa4SRandall Stewart #define	cc_exec_curr(cc, dir)		cc->cc_exec_entity[dir].cc_curr
170*d2854fa4SRandall Stewart #define	cc_exec_next(cc, dir)		cc->cc_exec_entity[dir].cc_next
171*d2854fa4SRandall Stewart #define	cc_exec_cancel(cc, dir)		cc->cc_exec_entity[dir].cc_cancel
172*d2854fa4SRandall Stewart #define	cc_exec_waiting(cc, dir)	cc->cc_exec_entity[dir].cc_waiting
1738d809d50SJeff Roberson #ifdef SMP
174*d2854fa4SRandall Stewart #define	cc_migration_func(cc, dir)	cc->cc_exec_entity[dir].ce_migration_func
175*d2854fa4SRandall Stewart #define	cc_migration_arg(cc, dir)	cc->cc_exec_entity[dir].ce_migration_arg
176*d2854fa4SRandall Stewart #define	cc_migration_cpu(cc, dir)	cc->cc_exec_entity[dir].ce_migration_cpu
177*d2854fa4SRandall Stewart #define	cc_migration_time(cc, dir)	cc->cc_exec_entity[dir].ce_migration_time
178*d2854fa4SRandall Stewart #define	cc_migration_prec(cc, dir)	cc->cc_exec_entity[dir].ce_migration_prec
179a115fb62SHans Petter Selasky 
1808d809d50SJeff Roberson struct callout_cpu cc_cpu[MAXCPU];
1811283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
1828d809d50SJeff Roberson #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
1838d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
1848d809d50SJeff Roberson #else
1858d809d50SJeff Roberson struct callout_cpu cc_cpu;
1868d809d50SJeff Roberson #define	CC_CPU(cpu)	&cc_cpu
1878d809d50SJeff Roberson #define	CC_SELF()	&cc_cpu
1888d809d50SJeff Roberson #endif
1898d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
1908d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
1911283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
1928d809d50SJeff Roberson 
1938d809d50SJeff Roberson static int timeout_cpu;
1945b999a6bSDavide Italiano 
195232e8b52SJohn Baldwin static void	callout_cpu_init(struct callout_cpu *cc, int cpu);
1965b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
1975b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
1985b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
1995b999a6bSDavide Italiano #endif
2005b999a6bSDavide Italiano 		    int direct);
2018d809d50SJeff Roberson 
202d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
20349a74476SColin Percival 
204a115fb62SHans Petter Selasky /**
205a115fb62SHans Petter Selasky  * Locked by cc_lock:
206a115fb62SHans Petter Selasky  *   cc_curr         - If a callout is in progress, it is cc_curr.
207a115fb62SHans Petter Selasky  *                     If cc_curr is non-NULL, threads waiting in
208a115fb62SHans Petter Selasky  *                     callout_drain() will be woken up as soon as the
209a115fb62SHans Petter Selasky  *                     relevant callout completes.
210a115fb62SHans Petter Selasky  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
211a115fb62SHans Petter Selasky  *                     guarantees that the current callout will not run.
212a115fb62SHans Petter Selasky  *                     The softclock() function sets this to 0 before it
213a115fb62SHans Petter Selasky  *                     drops callout_lock to acquire c_lock, and it calls
214a115fb62SHans Petter Selasky  *                     the handler only if curr_cancelled is still 0 after
215a115fb62SHans Petter Selasky  *                     cc_lock is successfully acquired.
216a115fb62SHans Petter Selasky  *   cc_waiting      - If a thread is waiting in callout_drain(), then
217a115fb62SHans Petter Selasky  *                     callout_wait is nonzero.  Set only when
218a115fb62SHans Petter Selasky  *                     cc_curr is non-NULL.
219a115fb62SHans Petter Selasky  */
220a115fb62SHans Petter Selasky 
221df8bae1dSRodney W. Grimes /*
222a115fb62SHans Petter Selasky  * Resets the execution entity tied to a specific callout cpu.
223a115fb62SHans Petter Selasky  */
224a115fb62SHans Petter Selasky static void
225a115fb62SHans Petter Selasky cc_cce_cleanup(struct callout_cpu *cc, int direct)
226a115fb62SHans Petter Selasky {
227a115fb62SHans Petter Selasky 
228*d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
229*d2854fa4SRandall Stewart 	cc_exec_next(cc, direct) = NULL;
230*d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
231*d2854fa4SRandall Stewart 	cc_exec_waiting(cc, direct) = false;
232a115fb62SHans Petter Selasky #ifdef SMP
233*d2854fa4SRandall Stewart 	cc_migration_cpu(cc, direct) = CPUBLOCK;
234*d2854fa4SRandall Stewart 	cc_migration_time(cc, direct) = 0;
235*d2854fa4SRandall Stewart 	cc_migration_prec(cc, direct) = 0;
236*d2854fa4SRandall Stewart 	cc_migration_func(cc, direct) = NULL;
237*d2854fa4SRandall Stewart 	cc_migration_arg(cc, direct) = NULL;
238a115fb62SHans Petter Selasky #endif
239a115fb62SHans Petter Selasky }
240a115fb62SHans Petter Selasky 
241a115fb62SHans Petter Selasky /*
242a115fb62SHans Petter Selasky  * Checks if migration is requested by a specific callout cpu.
243a115fb62SHans Petter Selasky  */
244a115fb62SHans Petter Selasky static int
245a115fb62SHans Petter Selasky cc_cce_migrating(struct callout_cpu *cc, int direct)
246a115fb62SHans Petter Selasky {
247a115fb62SHans Petter Selasky 
248a115fb62SHans Petter Selasky #ifdef SMP
249*d2854fa4SRandall Stewart 	return (cc_migration_cpu(cc, direct) != CPUBLOCK);
250a115fb62SHans Petter Selasky #else
251a115fb62SHans Petter Selasky 	return (0);
252a115fb62SHans Petter Selasky #endif
253a115fb62SHans Petter Selasky }
254a115fb62SHans Petter Selasky 
255a115fb62SHans Petter Selasky /*
256a115fb62SHans Petter Selasky  * Kernel low level callwheel initialization
257a115fb62SHans Petter Selasky  * called on cpu0 during kernel startup.
258219d632cSMatthew Dillon  */
25915ae0c9aSAndre Oppermann static void
26015ae0c9aSAndre Oppermann callout_callwheel_init(void *dummy)
261219d632cSMatthew Dillon {
2628d809d50SJeff Roberson 	struct callout_cpu *cc;
2638d809d50SJeff Roberson 
264f8ccf82aSAndre Oppermann 	/*
265f8ccf82aSAndre Oppermann 	 * Calculate the size of the callout wheel and the preallocated
266f8ccf82aSAndre Oppermann 	 * timeout() structures.
267a7aea132SAndre Oppermann 	 * XXX: Clip callout to result of previous function of maxusers
268a7aea132SAndre Oppermann 	 * maximum 384.  This is still huge, but acceptable.
269f8ccf82aSAndre Oppermann 	 */
270f8ccf82aSAndre Oppermann 	ncallout = imin(16 + maxproc + maxfiles, 18508);
271f8ccf82aSAndre Oppermann 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
272f8ccf82aSAndre Oppermann 
273219d632cSMatthew Dillon 	/*
274922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
275922314f0SAlfred Perlstein 	 * than 'ncallout'.
276219d632cSMatthew Dillon 	 */
277922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
278219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
279219d632cSMatthew Dillon 
28015ae0c9aSAndre Oppermann 	/*
281ac75ee9fSAdrian Chadd 	 * Fetch whether we're pinning the swi's or not.
282ac75ee9fSAdrian Chadd 	 */
283ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
284ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
285ac75ee9fSAdrian Chadd 
286ac75ee9fSAdrian Chadd 	/*
28715ae0c9aSAndre Oppermann 	 * Only cpu0 handles timeout(9) and receives a preallocation.
28815ae0c9aSAndre Oppermann 	 *
28915ae0c9aSAndre Oppermann 	 * XXX: Once all timeout(9) consumers are converted this can
29015ae0c9aSAndre Oppermann 	 * be removed.
29115ae0c9aSAndre Oppermann 	 */
29215ae0c9aSAndre Oppermann 	timeout_cpu = PCPU_GET(cpuid);
29315ae0c9aSAndre Oppermann 	cc = CC_CPU(timeout_cpu);
29415ae0c9aSAndre Oppermann 	cc->cc_callout = malloc(ncallout * sizeof(struct callout),
29515ae0c9aSAndre Oppermann 	    M_CALLOUT, M_WAITOK);
296232e8b52SJohn Baldwin 	callout_cpu_init(cc, timeout_cpu);
297219d632cSMatthew Dillon }
29815ae0c9aSAndre Oppermann SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
299219d632cSMatthew Dillon 
30015ae0c9aSAndre Oppermann /*
30115ae0c9aSAndre Oppermann  * Initialize the per-cpu callout structures.
30215ae0c9aSAndre Oppermann  */
3038d809d50SJeff Roberson static void
304232e8b52SJohn Baldwin callout_cpu_init(struct callout_cpu *cc, int cpu)
3058d809d50SJeff Roberson {
3068d809d50SJeff Roberson 	struct callout *c;
3078d809d50SJeff Roberson 	int i;
3088d809d50SJeff Roberson 
3098d809d50SJeff Roberson 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
3108d809d50SJeff Roberson 	SLIST_INIT(&cc->cc_callfree);
311c5904471SDavide Italiano 	cc->cc_callwheel = malloc(sizeof(struct callout_list) * callwheelsize,
31215ae0c9aSAndre Oppermann 	    M_CALLOUT, M_WAITOK);
3135b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
3145b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
3155b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
3164bc38a5aSDavide Italiano 	cc->cc_firstevent = SBT_MAX;
317a115fb62SHans Petter Selasky 	for (i = 0; i < 2; i++)
318a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, i);
319232e8b52SJohn Baldwin 	snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
320232e8b52SJohn Baldwin 	    "callwheel cpu %d", cpu);
32115ae0c9aSAndre Oppermann 	if (cc->cc_callout == NULL)	/* Only cpu0 handles timeout(9) */
3228d809d50SJeff Roberson 		return;
3238d809d50SJeff Roberson 	for (i = 0; i < ncallout; i++) {
3248d809d50SJeff Roberson 		c = &cc->cc_callout[i];
3258d809d50SJeff Roberson 		callout_init(c, 0);
326a115fb62SHans Petter Selasky 		c->c_flags = CALLOUT_LOCAL_ALLOC;
3278d809d50SJeff Roberson 		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
3288d809d50SJeff Roberson 	}
3298d809d50SJeff Roberson }
3308d809d50SJeff Roberson 
331a115fb62SHans Petter Selasky #ifdef SMP
332a115fb62SHans Petter Selasky /*
333a115fb62SHans Petter Selasky  * Switches the cpu tied to a specific callout.
334a115fb62SHans Petter Selasky  * The function expects a locked incoming callout cpu and returns with
335a115fb62SHans Petter Selasky  * locked outcoming callout cpu.
336a115fb62SHans Petter Selasky  */
337a115fb62SHans Petter Selasky static struct callout_cpu *
338a115fb62SHans Petter Selasky callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
339a115fb62SHans Petter Selasky {
340a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
341a115fb62SHans Petter Selasky 
342a115fb62SHans Petter Selasky 	MPASS(c != NULL && cc != NULL);
343a115fb62SHans Petter Selasky 	CC_LOCK_ASSERT(cc);
344a115fb62SHans Petter Selasky 
345a115fb62SHans Petter Selasky 	/*
346a115fb62SHans Petter Selasky 	 * Avoid interrupts and preemption firing after the callout cpu
347a115fb62SHans Petter Selasky 	 * is blocked in order to avoid deadlocks as the new thread
348a115fb62SHans Petter Selasky 	 * may be willing to acquire the callout cpu lock.
349a115fb62SHans Petter Selasky 	 */
350a115fb62SHans Petter Selasky 	c->c_cpu = CPUBLOCK;
351a115fb62SHans Petter Selasky 	spinlock_enter();
352a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
353a115fb62SHans Petter Selasky 	new_cc = CC_CPU(new_cpu);
354a115fb62SHans Petter Selasky 	CC_LOCK(new_cc);
355a115fb62SHans Petter Selasky 	spinlock_exit();
356a115fb62SHans Petter Selasky 	c->c_cpu = new_cpu;
357a115fb62SHans Petter Selasky 	return (new_cc);
358a115fb62SHans Petter Selasky }
359a115fb62SHans Petter Selasky #endif
360a115fb62SHans Petter Selasky 
361219d632cSMatthew Dillon /*
3628d809d50SJeff Roberson  * Start standard softclock thread.
3638d809d50SJeff Roberson  */
3648d809d50SJeff Roberson static void
3658d809d50SJeff Roberson start_softclock(void *dummy)
3668d809d50SJeff Roberson {
3678d809d50SJeff Roberson 	struct callout_cpu *cc;
368f44e2a4cSAdrian Chadd 	char name[MAXCOMLEN];
3698d809d50SJeff Roberson #ifdef SMP
3708d809d50SJeff Roberson 	int cpu;
371ac75ee9fSAdrian Chadd 	struct intr_event *ie;
3728d809d50SJeff Roberson #endif
3738d809d50SJeff Roberson 
3748d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
375f44e2a4cSAdrian Chadd 	snprintf(name, sizeof(name), "clock (%d)", timeout_cpu);
376f44e2a4cSAdrian Chadd 	if (swi_add(&clk_intr_event, name, softclock, cc, SWI_CLOCK,
3773350df48SJohn Baldwin 	    INTR_MPSAFE, &cc->cc_cookie))
3788d809d50SJeff Roberson 		panic("died while creating standard software ithreads");
379ac75ee9fSAdrian Chadd 	if (pin_default_swi &&
380ac75ee9fSAdrian Chadd 	    (intr_event_bind(clk_intr_event, timeout_cpu) != 0)) {
381ac75ee9fSAdrian Chadd 		printf("%s: timeout clock couldn't be pinned to cpu %d\n",
382ac75ee9fSAdrian Chadd 		    __func__,
383ac75ee9fSAdrian Chadd 		    timeout_cpu);
384ac75ee9fSAdrian Chadd 	}
385ac75ee9fSAdrian Chadd 
3868d809d50SJeff Roberson #ifdef SMP
3873aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
3888d809d50SJeff Roberson 		if (cpu == timeout_cpu)
3898d809d50SJeff Roberson 			continue;
3908d809d50SJeff Roberson 		cc = CC_CPU(cpu);
39115ae0c9aSAndre Oppermann 		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(9). */
392232e8b52SJohn Baldwin 		callout_cpu_init(cc, cpu);
393f44e2a4cSAdrian Chadd 		snprintf(name, sizeof(name), "clock (%d)", cpu);
394ac75ee9fSAdrian Chadd 		ie = NULL;
395ac75ee9fSAdrian Chadd 		if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
3968d809d50SJeff Roberson 		    INTR_MPSAFE, &cc->cc_cookie))
3978d809d50SJeff Roberson 			panic("died while creating standard software ithreads");
398ac75ee9fSAdrian Chadd 		if (pin_pcpu_swi && (intr_event_bind(ie, cpu) != 0)) {
399ac75ee9fSAdrian Chadd 			printf("%s: per-cpu clock couldn't be pinned to "
400ac75ee9fSAdrian Chadd 			    "cpu %d\n",
401ac75ee9fSAdrian Chadd 			    __func__,
402ac75ee9fSAdrian Chadd 			    cpu);
403ac75ee9fSAdrian Chadd 		}
404219d632cSMatthew Dillon 	}
4058d809d50SJeff Roberson #endif
406219d632cSMatthew Dillon }
4078d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
4088d809d50SJeff Roberson 
4095b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
4108d809d50SJeff Roberson 
4115b999a6bSDavide Italiano static inline u_int
4125b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
4135b999a6bSDavide Italiano {
4145b999a6bSDavide Italiano 
4155b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
4165b999a6bSDavide Italiano }
4175b999a6bSDavide Italiano 
4185b999a6bSDavide Italiano static inline u_int
4195b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
4205b999a6bSDavide Italiano {
4215b999a6bSDavide Italiano 
4225b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
4235b999a6bSDavide Italiano }
4245b999a6bSDavide Italiano 
4255b999a6bSDavide Italiano void
4265b999a6bSDavide Italiano callout_process(sbintime_t now)
4275b999a6bSDavide Italiano {
4285b999a6bSDavide Italiano 	struct callout *tmp, *tmpn;
4295b999a6bSDavide Italiano 	struct callout_cpu *cc;
4305b999a6bSDavide Italiano 	struct callout_list *sc;
4315b999a6bSDavide Italiano 	sbintime_t first, last, max, tmp_max;
4325b999a6bSDavide Italiano 	uint32_t lookahead;
4335b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
4345b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4355b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
4365b999a6bSDavide Italiano #endif
437a115fb62SHans Petter Selasky 
4388d809d50SJeff Roberson 	cc = CC_SELF();
439a115fb62SHans Petter Selasky 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4405b999a6bSDavide Italiano 
4415b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4425b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4435b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4445b999a6bSDavide Italiano 	nowb = callout_hash(now);
4455b999a6bSDavide Italiano 
4465b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4475b999a6bSDavide Italiano 	if (nowb == firstb)
4485b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4495b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4505b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4515b999a6bSDavide Italiano 	else
4525b999a6bSDavide Italiano 		lookahead = (SBT_1S / 2);
4535b999a6bSDavide Italiano 	first = last = now;
4545b999a6bSDavide Italiano 	first += (lookahead / 2);
4555b999a6bSDavide Italiano 	last += lookahead;
4565b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4575b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4585b999a6bSDavide Italiano 	max = last;
4595b999a6bSDavide Italiano 
4605b999a6bSDavide Italiano 	/*
4615b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4625b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4635b999a6bSDavide Italiano 	 */
4645b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4655b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4665b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4675b999a6bSDavide Italiano 			nowb = lastb;
4689fc51b0bSJeff Roberson 	}
4695b999a6bSDavide Italiano 
4705b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4715b999a6bSDavide Italiano 	do {
4725b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
4735b999a6bSDavide Italiano 		tmp = LIST_FIRST(sc);
4745b999a6bSDavide Italiano 		while (tmp != NULL) {
4755b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
4765b999a6bSDavide Italiano 			if (tmp->c_time <= now) {
4775b999a6bSDavide Italiano 				/*
4785b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
4795b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
4805b999a6bSDavide Italiano 				 */
4815b999a6bSDavide Italiano 				if (tmp->c_flags & CALLOUT_DIRECT) {
4825b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4835b999a6bSDavide Italiano 					++depth_dir;
4845b999a6bSDavide Italiano #endif
485*d2854fa4SRandall Stewart 					cc_exec_next(cc, 1) =
4865b999a6bSDavide Italiano 					    LIST_NEXT(tmp, c_links.le);
4875b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
4885b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4895b999a6bSDavide Italiano 					softclock_call_cc(tmp, cc,
4905b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4915b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
4925b999a6bSDavide Italiano #endif
4935b999a6bSDavide Italiano 					    1);
494*d2854fa4SRandall Stewart 					tmp = cc_exec_next(cc, 1);
4955b999a6bSDavide Italiano 				} else {
4965b999a6bSDavide Italiano 					tmpn = LIST_NEXT(tmp, c_links.le);
4975b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4985b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
4995b999a6bSDavide Italiano 					    tmp, c_links.tqe);
5005b999a6bSDavide Italiano 					tmp->c_flags |= CALLOUT_PROCESSED;
5015b999a6bSDavide Italiano 					tmp = tmpn;
5029fc51b0bSJeff Roberson 				}
5035b999a6bSDavide Italiano 				continue;
5045b999a6bSDavide Italiano 			}
5055b999a6bSDavide Italiano 			/* Skip events from distant future. */
5065b999a6bSDavide Italiano 			if (tmp->c_time >= max)
5075b999a6bSDavide Italiano 				goto next;
5085b999a6bSDavide Italiano 			/*
5095b999a6bSDavide Italiano 			 * Event minimal time is bigger than present maximal
5105b999a6bSDavide Italiano 			 * time, so it cannot be aggregated.
5115b999a6bSDavide Italiano 			 */
5125b999a6bSDavide Italiano 			if (tmp->c_time > last) {
5135b999a6bSDavide Italiano 				lastb = nowb;
5145b999a6bSDavide Italiano 				goto next;
5155b999a6bSDavide Italiano 			}
5165b999a6bSDavide Italiano 			/* Update first and last time, respecting this event. */
5175b999a6bSDavide Italiano 			if (tmp->c_time < first)
5185b999a6bSDavide Italiano 				first = tmp->c_time;
5195b999a6bSDavide Italiano 			tmp_max = tmp->c_time + tmp->c_precision;
5205b999a6bSDavide Italiano 			if (tmp_max < last)
5215b999a6bSDavide Italiano 				last = tmp_max;
5225b999a6bSDavide Italiano next:
5235b999a6bSDavide Italiano 			tmp = LIST_NEXT(tmp, c_links.le);
5245b999a6bSDavide Italiano 		}
5255b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
5265b999a6bSDavide Italiano 		firstb++;
5275b999a6bSDavide Italiano 		/*
5285b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
5295b999a6bSDavide Italiano 		 * some event we can't execute at now.
5305b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
5315b999a6bSDavide Italiano 		 */
5325b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
5335b999a6bSDavide Italiano 	cc->cc_firstevent = last;
5345b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
5355b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
5365b999a6bSDavide Italiano #endif
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
542a115fb62SHans Petter Selasky 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5438d809d50SJeff Roberson 	/*
5448d809d50SJeff Roberson 	 * swi_sched acquires the thread lock, so we don't want to call it
5458d809d50SJeff Roberson 	 * with cc_lock held; incorrect locking order.
5468d809d50SJeff Roberson 	 */
5475b999a6bSDavide Italiano 	if (!TAILQ_EMPTY(&cc->cc_expireq))
5488d809d50SJeff Roberson 		swi_sched(cc->cc_cookie, 0);
5498d809d50SJeff Roberson }
5508d809d50SJeff Roberson 
5518d809d50SJeff Roberson static struct callout_cpu *
5528d809d50SJeff Roberson callout_lock(struct callout *c)
5538d809d50SJeff Roberson {
5548d809d50SJeff Roberson 	struct callout_cpu *cc;
555a115fb62SHans Petter Selasky 	int cpu;
556a115fb62SHans Petter Selasky 
557a115fb62SHans Petter Selasky 	for (;;) {
558a115fb62SHans Petter Selasky 		cpu = c->c_cpu;
559a115fb62SHans Petter Selasky #ifdef SMP
560a115fb62SHans Petter Selasky 		if (cpu == CPUBLOCK) {
561a115fb62SHans Petter Selasky 			while (c->c_cpu == CPUBLOCK)
562a115fb62SHans Petter Selasky 				cpu_spinwait();
563a115fb62SHans Petter Selasky 			continue;
564a115fb62SHans Petter Selasky 		}
565a115fb62SHans Petter Selasky #endif
566a115fb62SHans Petter Selasky 		cc = CC_CPU(cpu);
5678d809d50SJeff Roberson 		CC_LOCK(cc);
568a115fb62SHans Petter Selasky 		if (cpu == c->c_cpu)
569a115fb62SHans Petter Selasky 			break;
570a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
571a115fb62SHans Petter Selasky 	}
5728d809d50SJeff Roberson 	return (cc);
573219d632cSMatthew Dillon }
574219d632cSMatthew Dillon 
575a115fb62SHans Petter Selasky static void
576a115fb62SHans Petter Selasky callout_cc_add(struct callout *c, struct callout_cpu *cc,
577a115fb62SHans Petter Selasky     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
578*d2854fa4SRandall Stewart     void *arg, int cpu, int flags, int direct)
5791283e9cdSAttilio Rao {
5805b999a6bSDavide Italiano 	int bucket;
5811283e9cdSAttilio Rao 
5821283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
583a115fb62SHans Petter Selasky 	if (sbt < cc->cc_lastscan)
584a115fb62SHans Petter Selasky 		sbt = cc->cc_lastscan;
585a115fb62SHans Petter Selasky 	c->c_arg = arg;
5861283e9cdSAttilio Rao 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
587a115fb62SHans Petter Selasky 	if (flags & C_DIRECT_EXEC)
588a115fb62SHans Petter Selasky 		c->c_flags |= CALLOUT_DIRECT;
589a115fb62SHans Petter Selasky 	c->c_flags &= ~CALLOUT_PROCESSED;
590a115fb62SHans Petter Selasky 	c->c_func = func;
591a115fb62SHans Petter Selasky 	c->c_time = sbt;
592a115fb62SHans Petter Selasky 	c->c_precision = precision;
5935b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
5945b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
5955b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
5965b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
5975b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
5985b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
599*d2854fa4SRandall Stewart 		cc_exec_next(cc, direct) = c;
6005b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
6015b999a6bSDavide Italiano 	/*
6025b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
6035b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
6045b999a6bSDavide Italiano 	 */
6054bc38a5aSDavide Italiano 	if (SBT_MAX - c->c_time < c->c_precision)
6064bc38a5aSDavide Italiano 		c->c_precision = SBT_MAX - c->c_time;
6075b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
6085b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
6095b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
610a115fb62SHans Petter Selasky 		cpu_new_callout(cpu, sbt, c->c_time);
6111283e9cdSAttilio Rao 	}
6125b999a6bSDavide Italiano #endif
6131283e9cdSAttilio Rao }
6141283e9cdSAttilio Rao 
6156098e7acSKonstantin Belousov static void
6166098e7acSKonstantin Belousov callout_cc_del(struct callout *c, struct callout_cpu *cc)
6176098e7acSKonstantin Belousov {
6186098e7acSKonstantin Belousov 
619a115fb62SHans Petter Selasky 	if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
620a115fb62SHans Petter Selasky 		return;
6216098e7acSKonstantin Belousov 	c->c_func = NULL;
6226098e7acSKonstantin Belousov 	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
6236098e7acSKonstantin Belousov }
6246098e7acSKonstantin Belousov 
625eb8a7186SKonstantin Belousov static void
6265b999a6bSDavide Italiano softclock_call_cc(struct callout *c, struct callout_cpu *cc,
6275b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6285b999a6bSDavide Italiano     int *mpcalls, int *lockcalls, int *gcalls,
6295b999a6bSDavide Italiano #endif
6305b999a6bSDavide Italiano     int direct)
6316098e7acSKonstantin Belousov {
632a115fb62SHans Petter Selasky 	struct rm_priotracker tracker;
633a115fb62SHans Petter Selasky 	void (*c_func)(void *);
6346098e7acSKonstantin Belousov 	void *c_arg;
635a115fb62SHans Petter Selasky 	struct lock_class *class;
6366098e7acSKonstantin Belousov 	struct lock_object *c_lock;
637a115fb62SHans Petter Selasky 	uintptr_t lock_status;
6381f96759fSDavide Italiano 	int c_flags;
639a115fb62SHans Petter Selasky #ifdef SMP
640a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
641a115fb62SHans Petter Selasky 	void (*new_func)(void *);
642a115fb62SHans Petter Selasky 	void *new_arg;
643a115fb62SHans Petter Selasky 	int flags, new_cpu;
644a115fb62SHans Petter Selasky 	sbintime_t new_prec, new_time;
645a115fb62SHans Petter Selasky #endif
6465b999a6bSDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
64703763781SDavide Italiano 	sbintime_t sbt1, sbt2;
6486098e7acSKonstantin Belousov 	struct timespec ts2;
6495b999a6bSDavide Italiano 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
6506098e7acSKonstantin Belousov 	static timeout_t *lastfunc;
6516098e7acSKonstantin Belousov #endif
6526098e7acSKonstantin Belousov 
653eb8a7186SKonstantin Belousov 	KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
654eb8a7186SKonstantin Belousov 	    (CALLOUT_PENDING | CALLOUT_ACTIVE),
655eb8a7186SKonstantin Belousov 	    ("softclock_call_cc: pend|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;
658a115fb62SHans Petter Selasky 	if (c->c_flags & 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;
6676098e7acSKonstantin Belousov 	c_flags = c->c_flags;
668a115fb62SHans Petter Selasky 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
669a115fb62SHans Petter Selasky 		c->c_flags = CALLOUT_LOCAL_ALLOC;
670a115fb62SHans Petter Selasky 	else
6716098e7acSKonstantin Belousov 		c->c_flags &= ~CALLOUT_PENDING;
672*d2854fa4SRandall Stewart 
673*d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = c;
674*d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
6756098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
676a115fb62SHans Petter Selasky 	if (c_lock != NULL) {
677a115fb62SHans Petter Selasky 		class->lc_lock(c_lock, lock_status);
6786098e7acSKonstantin Belousov 		/*
679a115fb62SHans Petter Selasky 		 * The callout may have been cancelled
680a115fb62SHans Petter Selasky 		 * while we switched locks.
6816098e7acSKonstantin Belousov 		 */
682*d2854fa4SRandall Stewart 		if (cc_exec_cancel(cc, direct)) {
683a115fb62SHans Petter Selasky 			class->lc_unlock(c_lock);
684a115fb62SHans Petter Selasky 			goto skip;
6856098e7acSKonstantin Belousov 		}
686a115fb62SHans Petter Selasky 		/* The callout cannot be stopped now. */
687*d2854fa4SRandall Stewart 		cc_exec_cancel(cc, direct) = true;
6886098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
6895b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6906098e7acSKonstantin Belousov 			(*gcalls)++;
6915b999a6bSDavide Italiano #endif
6925b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
6936098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6946098e7acSKonstantin Belousov 		} else {
6955b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6966098e7acSKonstantin Belousov 			(*lockcalls)++;
6975b999a6bSDavide Italiano #endif
6986098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
6996098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7006098e7acSKonstantin Belousov 		}
7016098e7acSKonstantin Belousov 	} else {
7025b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7036098e7acSKonstantin Belousov 		(*mpcalls)++;
7045b999a6bSDavide Italiano #endif
7055b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
7066098e7acSKonstantin Belousov 		    c, c_func, c_arg);
7076098e7acSKonstantin Belousov 	}
708232e8b52SJohn Baldwin 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
709232e8b52SJohn Baldwin 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
71003763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
7115b999a6bSDavide Italiano 	sbt1 = sbinuptime();
7126098e7acSKonstantin Belousov #endif
7136098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
714d9fae5abSAndriy Gapon 	SDT_PROBE(callout_execute, kernel, , callout__start, c, 0, 0, 0, 0);
7156098e7acSKonstantin Belousov 	c_func(c_arg);
716d9fae5abSAndriy Gapon 	SDT_PROBE(callout_execute, kernel, , callout__end, c, 0, 0, 0, 0);
7176098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
71803763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
71903763781SDavide Italiano 	sbt2 = sbinuptime();
72003763781SDavide Italiano 	sbt2 -= sbt1;
72103763781SDavide Italiano 	if (sbt2 > maxdt) {
72203763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
72303763781SDavide Italiano 			ts2 = sbttots(sbt2);
7246098e7acSKonstantin Belousov 			printf(
7256098e7acSKonstantin Belousov 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
7266098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
7276098e7acSKonstantin Belousov 		}
72803763781SDavide Italiano 		maxdt = sbt2;
7296098e7acSKonstantin Belousov 		lastfunc = c_func;
7306098e7acSKonstantin Belousov 	}
7316098e7acSKonstantin Belousov #endif
732232e8b52SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
7336098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
7346098e7acSKonstantin Belousov 	if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
735a115fb62SHans Petter Selasky 		class->lc_unlock(c_lock);
736a115fb62SHans Petter Selasky skip:
7376098e7acSKonstantin Belousov 	CC_LOCK(cc);
738*d2854fa4SRandall Stewart 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
739*d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
740*d2854fa4SRandall Stewart 	if (cc_exec_waiting(cc, direct)) {
741bdf9120cSAttilio Rao 		/*
742a115fb62SHans Petter Selasky 		 * There is someone waiting for the
743a115fb62SHans Petter Selasky 		 * callout to complete.
744a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
745a115fb62SHans Petter Selasky 		 * migration just cancel it.
746bdf9120cSAttilio Rao 		 */
747a115fb62SHans Petter Selasky 		if (cc_cce_migrating(cc, direct)) {
748a115fb62SHans Petter Selasky 			cc_cce_cleanup(cc, direct);
749a115fb62SHans Petter Selasky 
750a115fb62SHans Petter Selasky 			/*
751a115fb62SHans Petter Selasky 			 * It should be assert here that the callout is not
752a115fb62SHans Petter Selasky 			 * destroyed but that is not easy.
753a115fb62SHans Petter Selasky 			 */
754a115fb62SHans Petter Selasky 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
7556098e7acSKonstantin Belousov 		}
756*d2854fa4SRandall Stewart 		cc_exec_waiting(cc, direct) = false;
757a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
758*d2854fa4SRandall Stewart 		wakeup(&cc_exec_waiting(cc, direct));
759a115fb62SHans Petter Selasky 		CC_LOCK(cc);
760a115fb62SHans Petter Selasky 	} else if (cc_cce_migrating(cc, direct)) {
761a115fb62SHans Petter Selasky 		KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
762a115fb62SHans Petter Selasky 		    ("Migrating legacy callout %p", c));
763a115fb62SHans Petter Selasky #ifdef SMP
764a115fb62SHans Petter Selasky 		/*
765a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
766a115fb62SHans Petter Selasky 		 * migration just perform it now.
767a115fb62SHans Petter Selasky 		 */
768*d2854fa4SRandall Stewart 		new_cpu = cc_migration_cpu(cc, direct);
769*d2854fa4SRandall Stewart 		new_time = cc_migration_time(cc, direct);
770*d2854fa4SRandall Stewart 		new_prec = cc_migration_prec(cc, direct);
771*d2854fa4SRandall Stewart 		new_func = cc_migration_func(cc, direct);
772*d2854fa4SRandall Stewart 		new_arg = cc_migration_arg(cc, direct);
773a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, direct);
774a115fb62SHans Petter Selasky 
775a115fb62SHans Petter Selasky 		/*
776a115fb62SHans Petter Selasky 		 * It should be assert here that the callout is not destroyed
777a115fb62SHans Petter Selasky 		 * but that is not easy.
778a115fb62SHans Petter Selasky 		 *
779a115fb62SHans Petter Selasky 		 * As first thing, handle deferred callout stops.
780a115fb62SHans Petter Selasky 		 */
781*d2854fa4SRandall Stewart 		if (!callout_migrating(c)) {
782a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT,
783a115fb62SHans Petter Selasky 			     "deferred cancelled %p func %p arg %p",
784a115fb62SHans Petter Selasky 			     c, new_func, new_arg);
785a115fb62SHans Petter Selasky 			callout_cc_del(c, cc);
786a115fb62SHans Petter Selasky 			return;
787a115fb62SHans Petter Selasky 		}
788a115fb62SHans Petter Selasky 		c->c_flags &= ~CALLOUT_DFRMIGRATION;
789a115fb62SHans Petter Selasky 
790a115fb62SHans Petter Selasky 		new_cc = callout_cpu_switch(c, cc, new_cpu);
791a115fb62SHans Petter Selasky 		flags = (direct) ? C_DIRECT_EXEC : 0;
792a115fb62SHans Petter Selasky 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
793*d2854fa4SRandall Stewart 		    new_arg, new_cpu, flags, direct);
794a115fb62SHans Petter Selasky 		CC_UNLOCK(new_cc);
795a115fb62SHans Petter Selasky 		CC_LOCK(cc);
796a115fb62SHans Petter Selasky #else
797a115fb62SHans Petter Selasky 		panic("migration should not happen");
798a115fb62SHans Petter Selasky #endif
799a115fb62SHans Petter Selasky 	}
800a115fb62SHans Petter Selasky 	/*
801a115fb62SHans Petter Selasky 	 * If the current callout is locally allocated (from
802a115fb62SHans Petter Selasky 	 * timeout(9)) then put it on the freelist.
803a115fb62SHans Petter Selasky 	 *
804a115fb62SHans Petter Selasky 	 * Note: we need to check the cached copy of c_flags because
805a115fb62SHans Petter Selasky 	 * if it was not local, then it's not safe to deref the
806a115fb62SHans Petter Selasky 	 * callout pointer.
807a115fb62SHans Petter Selasky 	 */
808a115fb62SHans Petter Selasky 	KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
809a115fb62SHans Petter Selasky 	    c->c_flags == CALLOUT_LOCAL_ALLOC,
810a115fb62SHans Petter Selasky 	    ("corrupted callout"));
811a115fb62SHans Petter Selasky 	if (c_flags & CALLOUT_LOCAL_ALLOC)
812a115fb62SHans Petter Selasky 		callout_cc_del(c, cc);
8136098e7acSKonstantin Belousov }
8146098e7acSKonstantin Belousov 
815219d632cSMatthew Dillon /*
816ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
817ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
818ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
819ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
820024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
821ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
822ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
823ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
824ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
825ab36c067SJustin T. Gibbs  */
826a50ec505SPoul-Henning Kamp 
827ab36c067SJustin T. Gibbs /*
828df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
829df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
830df8bae1dSRodney W. Grimes  */
831df8bae1dSRodney W. Grimes void
8328d809d50SJeff Roberson softclock(void *arg)
833df8bae1dSRodney W. Grimes {
8348d809d50SJeff Roberson 	struct callout_cpu *cc;
835b336df68SPoul-Henning Kamp 	struct callout *c;
8365b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8375b999a6bSDavide Italiano 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
8385b999a6bSDavide Italiano #endif
839df8bae1dSRodney W. Grimes 
8408d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
8418d809d50SJeff Roberson 	CC_LOCK(cc);
8425b999a6bSDavide Italiano 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
8435b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
8445b999a6bSDavide Italiano 		softclock_call_cc(c, cc,
8455b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8465b999a6bSDavide Italiano 		    &mpcalls, &lockcalls, &gcalls,
8475b999a6bSDavide Italiano #endif
8485b999a6bSDavide Italiano 		    0);
8495b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8505b999a6bSDavide Italiano 		++depth;
8515b999a6bSDavide Italiano #endif
852df8bae1dSRodney W. Grimes 	}
8535b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
85422ee8c4fSPoul-Henning Kamp 	avg_depth += (depth * 1000 - avg_depth) >> 8;
85522ee8c4fSPoul-Henning Kamp 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
85664b9ee20SAttilio Rao 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
85722ee8c4fSPoul-Henning Kamp 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8585b999a6bSDavide Italiano #endif
8598d809d50SJeff Roberson 	CC_UNLOCK(cc);
860df8bae1dSRodney W. Grimes }
861df8bae1dSRodney W. Grimes 
862df8bae1dSRodney W. Grimes /*
863df8bae1dSRodney W. Grimes  * timeout --
864df8bae1dSRodney W. Grimes  *	Execute a function after a specified length of time.
865df8bae1dSRodney W. Grimes  *
866df8bae1dSRodney W. Grimes  * untimeout --
867df8bae1dSRodney W. Grimes  *	Cancel previous timeout function call.
868df8bae1dSRodney W. Grimes  *
869ab36c067SJustin T. Gibbs  * callout_handle_init --
870ab36c067SJustin T. Gibbs  *	Initialize a handle so that using it with untimeout is benign.
871ab36c067SJustin T. Gibbs  *
872df8bae1dSRodney W. Grimes  *	See AT&T BCI Driver Reference Manual for specification.  This
873ab36c067SJustin T. Gibbs  *	implementation differs from that one in that although an
874ab36c067SJustin T. Gibbs  *	identification value is returned from timeout, the original
875ab36c067SJustin T. Gibbs  *	arguments to timeout as well as the identifier are used to
876ab36c067SJustin T. Gibbs  *	identify entries for untimeout.
877df8bae1dSRodney W. Grimes  */
878ab36c067SJustin T. Gibbs struct callout_handle
879e392e44cSDavide Italiano timeout(timeout_t *ftn, void *arg, int to_ticks)
880df8bae1dSRodney W. Grimes {
8818d809d50SJeff Roberson 	struct callout_cpu *cc;
882ab36c067SJustin T. Gibbs 	struct callout *new;
883ab36c067SJustin T. Gibbs 	struct callout_handle handle;
884df8bae1dSRodney W. Grimes 
8858d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
8868d809d50SJeff Roberson 	CC_LOCK(cc);
887df8bae1dSRodney W. Grimes 	/* Fill in the next free callout structure. */
8888d809d50SJeff Roberson 	new = SLIST_FIRST(&cc->cc_callfree);
889ab36c067SJustin T. Gibbs 	if (new == NULL)
890ab36c067SJustin T. Gibbs 		/* XXX Attempt to malloc first */
891df8bae1dSRodney W. Grimes 		panic("timeout table full");
8928d809d50SJeff Roberson 	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
893a115fb62SHans Petter Selasky 	callout_reset(new, to_ticks, ftn, arg);
894ab36c067SJustin T. Gibbs 	handle.callout = new;
8958d809d50SJeff Roberson 	CC_UNLOCK(cc);
8968d809d50SJeff Roberson 
897ab36c067SJustin T. Gibbs 	return (handle);
898df8bae1dSRodney W. Grimes }
899df8bae1dSRodney W. Grimes 
900df8bae1dSRodney W. Grimes void
901e392e44cSDavide Italiano untimeout(timeout_t *ftn, void *arg, struct callout_handle handle)
902df8bae1dSRodney W. Grimes {
9038d809d50SJeff Roberson 	struct callout_cpu *cc;
904df8bae1dSRodney W. Grimes 
905ab36c067SJustin T. Gibbs 	/*
906ab36c067SJustin T. Gibbs 	 * Check for a handle that was initialized
907ab36c067SJustin T. Gibbs 	 * by callout_handle_init, but never used
908ab36c067SJustin T. Gibbs 	 * for a real timeout.
909ab36c067SJustin T. Gibbs 	 */
910ab36c067SJustin T. Gibbs 	if (handle.callout == NULL)
911ab36c067SJustin T. Gibbs 		return;
912df8bae1dSRodney W. Grimes 
9138d809d50SJeff Roberson 	cc = callout_lock(handle.callout);
914a115fb62SHans Petter Selasky 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
9151a26c3c0SHans Petter Selasky 		callout_stop(handle.callout);
916a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
917df8bae1dSRodney W. Grimes }
918df8bae1dSRodney W. Grimes 
9193c816944SBruce Evans void
920ab36c067SJustin T. Gibbs callout_handle_init(struct callout_handle *handle)
921ab36c067SJustin T. Gibbs {
922ab36c067SJustin T. Gibbs 	handle->callout = NULL;
923ab36c067SJustin T. Gibbs }
924ab36c067SJustin T. Gibbs 
925acc8326dSGarrett Wollman /*
926acc8326dSGarrett Wollman  * New interface; clients allocate their own callout structures.
927acc8326dSGarrett Wollman  *
928acc8326dSGarrett Wollman  * callout_reset() - establish or change a timeout
929acc8326dSGarrett Wollman  * callout_stop() - disestablish a timeout
930acc8326dSGarrett Wollman  * callout_init() - initialize a callout structure so that it can
931acc8326dSGarrett Wollman  *	safely be passed to callout_reset() and callout_stop()
932acc8326dSGarrett Wollman  *
9339b8b58e0SJonathan Lemon  * <sys/callout.h> defines three convenience macros:
934acc8326dSGarrett Wollman  *
93586fd19deSColin Percival  * callout_active() - returns truth if callout has not been stopped,
93686fd19deSColin Percival  *	drained, or deactivated since the last time the callout was
93786fd19deSColin Percival  *	reset.
9389b8b58e0SJonathan Lemon  * callout_pending() - returns truth if callout is still waiting for timeout
9399b8b58e0SJonathan Lemon  * callout_deactivate() - marks the callout as having been serviced
940acc8326dSGarrett Wollman  */
941d04304d1SGleb Smirnoff int
9425b999a6bSDavide Italiano callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
943a115fb62SHans Petter Selasky     void (*ftn)(void *), void *arg, int cpu, int flags)
944acc8326dSGarrett Wollman {
945a115fb62SHans Petter Selasky 	sbintime_t to_sbt, pr;
946a115fb62SHans Petter Selasky 	struct callout_cpu *cc;
947a115fb62SHans Petter Selasky 	int cancelled, direct;
948acc8326dSGarrett Wollman 
949a115fb62SHans Petter Selasky 	cancelled = 0;
950a115fb62SHans Petter Selasky 	if (flags & C_ABSOLUTE) {
951a115fb62SHans Petter Selasky 		to_sbt = sbt;
9525b999a6bSDavide Italiano 	} else {
953a115fb62SHans Petter Selasky 		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
9545b999a6bSDavide Italiano 			sbt = tick_sbt;
955a115fb62SHans Petter Selasky 		if ((flags & C_HARDCLOCK) ||
9565b999a6bSDavide Italiano #ifdef NO_EVENTTIMERS
9575b999a6bSDavide Italiano 		    sbt >= sbt_timethreshold) {
958a115fb62SHans Petter Selasky 			to_sbt = getsbinuptime();
9595b999a6bSDavide Italiano 
9605b999a6bSDavide Italiano 			/* Add safety belt for the case of hz > 1000. */
961a115fb62SHans Petter Selasky 			to_sbt += tc_tick_sbt - tick_sbt;
9625b999a6bSDavide Italiano #else
9635b999a6bSDavide Italiano 		    sbt >= sbt_tickthreshold) {
9645b999a6bSDavide Italiano 			/*
9655b999a6bSDavide Italiano 			 * Obtain the time of the last hardclock() call on
9665b999a6bSDavide Italiano 			 * this CPU directly from the kern_clocksource.c.
9675b999a6bSDavide Italiano 			 * This value is per-CPU, but it is equal for all
9685b999a6bSDavide Italiano 			 * active ones.
9695b999a6bSDavide Italiano 			 */
9705b999a6bSDavide Italiano #ifdef __LP64__
971a115fb62SHans Petter Selasky 			to_sbt = DPCPU_GET(hardclocktime);
9725b999a6bSDavide Italiano #else
9735b999a6bSDavide Italiano 			spinlock_enter();
974a115fb62SHans Petter Selasky 			to_sbt = DPCPU_GET(hardclocktime);
9755b999a6bSDavide Italiano 			spinlock_exit();
9765b999a6bSDavide Italiano #endif
9775b999a6bSDavide Italiano #endif
978a115fb62SHans Petter Selasky 			if ((flags & C_HARDCLOCK) == 0)
979a115fb62SHans Petter Selasky 				to_sbt += tick_sbt;
9805b999a6bSDavide Italiano 		} else
981a115fb62SHans Petter Selasky 			to_sbt = sbinuptime();
982a115fb62SHans Petter Selasky 		if (SBT_MAX - to_sbt < sbt)
983a115fb62SHans Petter Selasky 			to_sbt = SBT_MAX;
9841b0c144fSDavide Italiano 		else
985a115fb62SHans Petter Selasky 			to_sbt += sbt;
986a115fb62SHans Petter Selasky 		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
987a115fb62SHans Petter Selasky 		    sbt >> C_PRELGET(flags));
988a115fb62SHans Petter Selasky 		if (pr > precision)
989a115fb62SHans Petter Selasky 			precision = pr;
990a115fb62SHans Petter Selasky 	}
991a115fb62SHans Petter Selasky 	/*
992a115fb62SHans Petter Selasky 	 * Don't allow migration of pre-allocated callouts lest they
993a115fb62SHans Petter Selasky 	 * become unbalanced.
994a115fb62SHans Petter Selasky 	 */
995a115fb62SHans Petter Selasky 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
996a115fb62SHans Petter Selasky 		cpu = c->c_cpu;
997a115fb62SHans Petter Selasky 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
998a115fb62SHans Petter Selasky 	KASSERT(!direct || c->c_lock == NULL,
999a115fb62SHans Petter Selasky 	    ("%s: direct callout %p has lock", __func__, c));
1000a115fb62SHans Petter Selasky 	cc = callout_lock(c);
1001*d2854fa4SRandall Stewart 	if (cc_exec_curr(cc, direct) == c) {
1002a115fb62SHans Petter Selasky 		/*
1003a115fb62SHans Petter Selasky 		 * We're being asked to reschedule a callout which is
1004a115fb62SHans Petter Selasky 		 * currently in progress.  If there is a lock then we
1005a115fb62SHans Petter Selasky 		 * can cancel the callout if it has not really started.
1006a115fb62SHans Petter Selasky 		 */
1007*d2854fa4SRandall Stewart 		if (c->c_lock != NULL && cc_exec_cancel(cc, direct))
1008*d2854fa4SRandall Stewart 			cancelled = cc_exec_cancel(cc, direct) = true;
1009*d2854fa4SRandall Stewart 		if (cc_exec_waiting(cc, direct)) {
1010a115fb62SHans Petter Selasky 			/*
1011a115fb62SHans Petter Selasky 			 * Someone has called callout_drain to kill this
1012a115fb62SHans Petter Selasky 			 * callout.  Don't reschedule.
1013a115fb62SHans Petter Selasky 			 */
1014a115fb62SHans Petter Selasky 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1015a115fb62SHans Petter Selasky 			    cancelled ? "cancelled" : "failed to cancel",
1016a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1017a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1018a115fb62SHans Petter Selasky 			return (cancelled);
1019a115fb62SHans Petter Selasky 		}
1020*d2854fa4SRandall Stewart #ifdef SMP
1021*d2854fa4SRandall Stewart 		if (callout_migrating(c)) {
1022*d2854fa4SRandall Stewart 			/*
1023*d2854fa4SRandall Stewart 			 * This only occurs when a second callout_reset_sbt_on
1024*d2854fa4SRandall Stewart 			 * is made after a previous one moved it into
1025*d2854fa4SRandall Stewart 			 * deferred migration (below). Note we do *not* change
1026*d2854fa4SRandall Stewart 			 * the prev_cpu even though the previous target may
1027*d2854fa4SRandall Stewart 			 * be different.
1028*d2854fa4SRandall Stewart 			 */
1029*d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1030*d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1031*d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1032*d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1033*d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
1034*d2854fa4SRandall Stewart 			cancelled = 1;
1035*d2854fa4SRandall Stewart 			CC_UNLOCK(cc);
1036*d2854fa4SRandall Stewart 			return (cancelled);
1037*d2854fa4SRandall Stewart 		}
1038*d2854fa4SRandall Stewart #endif
1039a115fb62SHans Petter Selasky 	}
1040a115fb62SHans Petter Selasky 	if (c->c_flags & CALLOUT_PENDING) {
1041a115fb62SHans Petter Selasky 		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1042*d2854fa4SRandall Stewart 			if (cc_exec_next(cc, direct) == c)
1043*d2854fa4SRandall Stewart 				cc_exec_next(cc, direct) = LIST_NEXT(c, c_links.le);
1044a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
1045a115fb62SHans Petter Selasky 		} else
1046a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1047a115fb62SHans Petter Selasky 		cancelled = 1;
1048a115fb62SHans Petter Selasky 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
10498d809d50SJeff Roberson 	}
10501283e9cdSAttilio Rao 
1051a115fb62SHans Petter Selasky #ifdef SMP
1052a115fb62SHans Petter Selasky 	/*
1053a115fb62SHans Petter Selasky 	 * If the callout must migrate try to perform it immediately.
1054a115fb62SHans Petter Selasky 	 * If the callout is currently running, just defer the migration
1055a115fb62SHans Petter Selasky 	 * to a more appropriate moment.
1056a115fb62SHans Petter Selasky 	 */
1057a115fb62SHans Petter Selasky 	if (c->c_cpu != cpu) {
1058*d2854fa4SRandall Stewart 		if (cc_exec_curr(cc, direct) == c) {
1059*d2854fa4SRandall Stewart 			/*
1060*d2854fa4SRandall Stewart 			 * Pending will have been removed since we are
1061*d2854fa4SRandall Stewart 			 * actually executing the callout on another
1062*d2854fa4SRandall Stewart 			 * CPU. That callout should be waiting on the
1063*d2854fa4SRandall Stewart 			 * lock the caller holds. If we set both
1064*d2854fa4SRandall Stewart 			 * active/and/pending after we return and the
1065*d2854fa4SRandall Stewart 			 * lock on the executing callout proceeds, it
1066*d2854fa4SRandall Stewart 			 * will then see pending is true and return.
1067*d2854fa4SRandall Stewart 			 * At the return from the actual callout execution
1068*d2854fa4SRandall Stewart 			 * the migration will occur in softclock_call_cc
1069*d2854fa4SRandall Stewart 			 * and this new callout will be placed on the
1070*d2854fa4SRandall Stewart 			 * new CPU via a call to callout_cpu_switch() which
1071*d2854fa4SRandall Stewart 			 * will get the lock on the right CPU followed
1072*d2854fa4SRandall Stewart 			 * by a call callout_cc_add() which will add it there.
1073*d2854fa4SRandall Stewart 			 * (see above in softclock_call_cc()).
1074*d2854fa4SRandall Stewart 			 */
1075*d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1076*d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1077*d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1078*d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1079*d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
1080*d2854fa4SRandall Stewart 			c->c_flags |= (CALLOUT_DFRMIGRATION | CALLOUT_ACTIVE | CALLOUT_PENDING);
1081a115fb62SHans Petter Selasky 			CTR6(KTR_CALLOUT,
1082a115fb62SHans Petter Selasky 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1083a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1084a115fb62SHans Petter Selasky 			    (u_int)(to_sbt & 0xffffffff), cpu);
1085a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1086a115fb62SHans Petter Selasky 			return (cancelled);
1087a115fb62SHans Petter Selasky 		}
1088a115fb62SHans Petter Selasky 		cc = callout_cpu_switch(c, cc, cpu);
1089a115fb62SHans Petter Selasky 	}
1090a115fb62SHans Petter Selasky #endif
1091a115fb62SHans Petter Selasky 
1092*d2854fa4SRandall Stewart 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags, direct);
1093a115fb62SHans Petter Selasky 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1094a115fb62SHans Petter Selasky 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1095a115fb62SHans Petter Selasky 	    (u_int)(to_sbt & 0xffffffff));
1096a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
1097a115fb62SHans Petter Selasky 
1098a115fb62SHans Petter Selasky 	return (cancelled);
1099acc8326dSGarrett Wollman }
1100acc8326dSGarrett Wollman 
11016e0186d5SSam Leffler /*
11026e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
11036e0186d5SSam Leffler  */
11046e0186d5SSam Leffler int
11056e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
11066e0186d5SSam Leffler {
11076e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
11086e0186d5SSam Leffler }
11096e0186d5SSam Leffler 
11106e0186d5SSam Leffler int
11116e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
11126e0186d5SSam Leffler {
11136e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
11146e0186d5SSam Leffler }
11156e0186d5SSam Leffler 
11162c1bb207SColin Percival int
1117a115fb62SHans Petter Selasky _callout_stop_safe(struct callout *c, int safe)
11182c1bb207SColin Percival {
1119a115fb62SHans Petter Selasky 	struct callout_cpu *cc, *old_cc;
1120a115fb62SHans Petter Selasky 	struct lock_class *class;
1121a115fb62SHans Petter Selasky 	int direct, sq_locked, use_lock;
1122*d2854fa4SRandall Stewart 	int not_on_a_list;
11231283e9cdSAttilio Rao 
11249500dd9fSAdrian Chadd 	if (safe)
11259500dd9fSAdrian Chadd 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
11269500dd9fSAdrian Chadd 		    "calling %s", __func__);
11279500dd9fSAdrian Chadd 
11281283e9cdSAttilio Rao 	/*
1129a115fb62SHans Petter Selasky 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1130a115fb62SHans Petter Selasky 	 * so just discard this check for the moment.
11311283e9cdSAttilio Rao 	 */
1132a115fb62SHans Petter Selasky 	if (!safe && c->c_lock != NULL) {
1133a115fb62SHans Petter Selasky 		if (c->c_lock == &Giant.lock_object)
1134a115fb62SHans Petter Selasky 			use_lock = mtx_owned(&Giant);
1135a115fb62SHans Petter Selasky 		else {
1136a115fb62SHans Petter Selasky 			use_lock = 1;
1137a115fb62SHans Petter Selasky 			class = LOCK_CLASS(c->c_lock);
1138a115fb62SHans Petter Selasky 			class->lc_assert(c->c_lock, LA_XLOCKED);
11391283e9cdSAttilio Rao 		}
1140a115fb62SHans Petter Selasky 	} else
1141a115fb62SHans Petter Selasky 		use_lock = 0;
1142a115fb62SHans Petter Selasky 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1143a115fb62SHans Petter Selasky 	sq_locked = 0;
1144a115fb62SHans Petter Selasky 	old_cc = NULL;
1145a115fb62SHans Petter Selasky again:
1146a115fb62SHans Petter Selasky 	cc = callout_lock(c);
1147a115fb62SHans Petter Selasky 
1148*d2854fa4SRandall Stewart 	if ((c->c_flags & (CALLOUT_DFRMIGRATION | CALLOUT_ACTIVE | CALLOUT_PENDING)) ==
1149*d2854fa4SRandall Stewart 	    (CALLOUT_DFRMIGRATION | CALLOUT_ACTIVE | CALLOUT_PENDING)) {
1150*d2854fa4SRandall Stewart 		/*
1151*d2854fa4SRandall Stewart 		 * Special case where this slipped in while we
1152*d2854fa4SRandall Stewart 		 * were migrating *as* the callout is about to
1153*d2854fa4SRandall Stewart 		 * execute. The caller probably holds the lock
1154*d2854fa4SRandall Stewart 		 * the callout wants.
1155*d2854fa4SRandall Stewart 		 *
1156*d2854fa4SRandall Stewart 		 * Get rid of the migration first. Then set
1157*d2854fa4SRandall Stewart 		 * the flag that tells this code *not* to
1158*d2854fa4SRandall Stewart 		 * try to remove it from any lists (its not
1159*d2854fa4SRandall Stewart 		 * on one yet). When the callout wheel runs,
1160*d2854fa4SRandall Stewart 		 * it will ignore this callout.
1161*d2854fa4SRandall Stewart 		 */
1162*d2854fa4SRandall Stewart 		c->c_flags &= ~(CALLOUT_PENDING|CALLOUT_ACTIVE);
1163*d2854fa4SRandall Stewart 		not_on_a_list = 1;
1164*d2854fa4SRandall Stewart 	} else {
1165*d2854fa4SRandall Stewart 		not_on_a_list = 0;
1166*d2854fa4SRandall Stewart 	}
1167*d2854fa4SRandall Stewart 
1168a115fb62SHans Petter Selasky 	/*
1169a115fb62SHans Petter Selasky 	 * If the callout was migrating while the callout cpu lock was
1170a115fb62SHans Petter Selasky 	 * dropped,  just drop the sleepqueue lock and check the states
1171a115fb62SHans Petter Selasky 	 * again.
1172a115fb62SHans Petter Selasky 	 */
1173a115fb62SHans Petter Selasky 	if (sq_locked != 0 && cc != old_cc) {
1174a115fb62SHans Petter Selasky #ifdef SMP
1175a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
1176*d2854fa4SRandall Stewart 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1177a115fb62SHans Petter Selasky 		sq_locked = 0;
1178a115fb62SHans Petter Selasky 		old_cc = NULL;
1179a115fb62SHans Petter Selasky 		goto again;
1180a115fb62SHans Petter Selasky #else
1181a115fb62SHans Petter Selasky 		panic("migration should not happen");
1182a115fb62SHans Petter Selasky #endif
1183a115fb62SHans Petter Selasky 	}
1184a115fb62SHans Petter Selasky 
1185a115fb62SHans Petter Selasky 	/*
1186a115fb62SHans Petter Selasky 	 * If the callout isn't pending, it's not on the queue, so
1187a115fb62SHans Petter Selasky 	 * don't attempt to remove it from the queue.  We can try to
1188a115fb62SHans Petter Selasky 	 * stop it by other means however.
1189a115fb62SHans Petter Selasky 	 */
1190a115fb62SHans Petter Selasky 	if (!(c->c_flags & CALLOUT_PENDING)) {
1191a115fb62SHans Petter Selasky 		c->c_flags &= ~CALLOUT_ACTIVE;
1192a115fb62SHans Petter Selasky 
1193a115fb62SHans Petter Selasky 		/*
1194a115fb62SHans Petter Selasky 		 * If it wasn't on the queue and it isn't the current
1195a115fb62SHans Petter Selasky 		 * callout, then we can't stop it, so just bail.
1196a115fb62SHans Petter Selasky 		 */
1197*d2854fa4SRandall Stewart 		if (cc_exec_curr(cc, direct) != c) {
1198a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1199a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1200a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1201a115fb62SHans Petter Selasky 			if (sq_locked)
1202*d2854fa4SRandall Stewart 				sleepq_release(&cc_exec_waiting(cc, direct));
1203a115fb62SHans Petter Selasky 			return (0);
1204a115fb62SHans Petter Selasky 		}
1205a115fb62SHans Petter Selasky 
1206a115fb62SHans Petter Selasky 		if (safe) {
1207a115fb62SHans Petter Selasky 			/*
1208a115fb62SHans Petter Selasky 			 * The current callout is running (or just
1209a115fb62SHans Petter Selasky 			 * about to run) and blocking is allowed, so
1210a115fb62SHans Petter Selasky 			 * just wait for the current invocation to
1211a115fb62SHans Petter Selasky 			 * finish.
1212a115fb62SHans Petter Selasky 			 */
1213*d2854fa4SRandall Stewart 			while (cc_exec_curr(cc, direct) == c) {
1214a115fb62SHans Petter Selasky 				/*
1215a115fb62SHans Petter Selasky 				 * Use direct calls to sleepqueue interface
1216a115fb62SHans Petter Selasky 				 * instead of cv/msleep in order to avoid
1217a115fb62SHans Petter Selasky 				 * a LOR between cc_lock and sleepqueue
1218a115fb62SHans Petter Selasky 				 * chain spinlocks.  This piece of code
1219a115fb62SHans Petter Selasky 				 * emulates a msleep_spin() call actually.
1220a115fb62SHans Petter Selasky 				 *
1221a115fb62SHans Petter Selasky 				 * If we already have the sleepqueue chain
1222a115fb62SHans Petter Selasky 				 * locked, then we can safely block.  If we
1223a115fb62SHans Petter Selasky 				 * don't already have it locked, however,
1224a115fb62SHans Petter Selasky 				 * we have to drop the cc_lock to lock
1225a115fb62SHans Petter Selasky 				 * it.  This opens several races, so we
1226a115fb62SHans Petter Selasky 				 * restart at the beginning once we have
1227a115fb62SHans Petter Selasky 				 * both locks.  If nothing has changed, then
1228a115fb62SHans Petter Selasky 				 * we will end up back here with sq_locked
1229a115fb62SHans Petter Selasky 				 * set.
1230a115fb62SHans Petter Selasky 				 */
1231a115fb62SHans Petter Selasky 				if (!sq_locked) {
1232a115fb62SHans Petter Selasky 					CC_UNLOCK(cc);
1233a115fb62SHans Petter Selasky 					sleepq_lock(
1234*d2854fa4SRandall Stewart 					    &cc_exec_waiting(cc, direct));
1235a115fb62SHans Petter Selasky 					sq_locked = 1;
1236a115fb62SHans Petter Selasky 					old_cc = cc;
1237a115fb62SHans Petter Selasky 					goto again;
1238a115fb62SHans Petter Selasky 				}
1239a115fb62SHans Petter Selasky 
1240a115fb62SHans Petter Selasky 				/*
1241a115fb62SHans Petter Selasky 				 * Migration could be cancelled here, but
1242a115fb62SHans Petter Selasky 				 * as long as it is still not sure when it
1243a115fb62SHans Petter Selasky 				 * will be packed up, just let softclock()
1244a115fb62SHans Petter Selasky 				 * take care of it.
1245a115fb62SHans Petter Selasky 				 */
1246*d2854fa4SRandall Stewart 				cc_exec_waiting(cc, direct) = true;
1247a115fb62SHans Petter Selasky 				DROP_GIANT();
1248a115fb62SHans Petter Selasky 				CC_UNLOCK(cc);
1249a115fb62SHans Petter Selasky 				sleepq_add(
1250*d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1251a115fb62SHans Petter Selasky 				    &cc->cc_lock.lock_object, "codrain",
1252a115fb62SHans Petter Selasky 				    SLEEPQ_SLEEP, 0);
1253a115fb62SHans Petter Selasky 				sleepq_wait(
1254*d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1255a115fb62SHans Petter Selasky 					     0);
1256a115fb62SHans Petter Selasky 				sq_locked = 0;
1257a115fb62SHans Petter Selasky 				old_cc = NULL;
1258a115fb62SHans Petter Selasky 
1259a115fb62SHans Petter Selasky 				/* Reacquire locks previously released. */
1260a115fb62SHans Petter Selasky 				PICKUP_GIANT();
1261a115fb62SHans Petter Selasky 				CC_LOCK(cc);
1262a115fb62SHans Petter Selasky 			}
1263a115fb62SHans Petter Selasky 		} else if (use_lock &&
1264*d2854fa4SRandall Stewart 			   !cc_exec_cancel(cc, direct)) {
1265*d2854fa4SRandall Stewart 
1266a115fb62SHans Petter Selasky 			/*
1267a115fb62SHans Petter Selasky 			 * The current callout is waiting for its
1268a115fb62SHans Petter Selasky 			 * lock which we hold.  Cancel the callout
1269a115fb62SHans Petter Selasky 			 * and return.  After our caller drops the
1270a115fb62SHans Petter Selasky 			 * lock, the callout will be skipped in
1271a115fb62SHans Petter Selasky 			 * softclock().
1272a115fb62SHans Petter Selasky 			 */
1273*d2854fa4SRandall Stewart 			cc_exec_cancel(cc, direct) = true;
1274a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1275a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1276a115fb62SHans Petter Selasky 			KASSERT(!cc_cce_migrating(cc, direct),
1277a115fb62SHans Petter Selasky 			    ("callout wrongly scheduled for migration"));
1278a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1279a115fb62SHans Petter Selasky 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1280a115fb62SHans Petter Selasky 			return (1);
1281*d2854fa4SRandall Stewart 		} else if (callout_migrating(c)) {
1282*d2854fa4SRandall Stewart 			/*
1283*d2854fa4SRandall Stewart 			 * The callout is currently being serviced
1284*d2854fa4SRandall Stewart 			 * and the "next" callout is scheduled at
1285*d2854fa4SRandall Stewart 			 * its completion with a migration. We remove
1286*d2854fa4SRandall Stewart 			 * the migration flag so it *won't* get rescheduled,
1287*d2854fa4SRandall Stewart 			 * but we can't stop the one thats running so
1288*d2854fa4SRandall Stewart 			 * we return 0.
1289*d2854fa4SRandall Stewart 			 */
1290a115fb62SHans Petter Selasky 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
1291*d2854fa4SRandall Stewart #ifdef SMP
1292*d2854fa4SRandall Stewart 			/*
1293*d2854fa4SRandall Stewart 			 * We can't call cc_cce_cleanup here since
1294*d2854fa4SRandall Stewart 			 * if we do it will remove .ce_curr and
1295*d2854fa4SRandall Stewart 			 * its still running. This will prevent a
1296*d2854fa4SRandall Stewart 			 * reschedule of the callout when the
1297*d2854fa4SRandall Stewart 			 * execution completes.
1298*d2854fa4SRandall Stewart 			 */
1299*d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1300*d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = 0;
1301*d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = 0;
1302*d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = NULL;
1303*d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = NULL;
1304*d2854fa4SRandall Stewart #endif
1305a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1306a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1307a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1308*d2854fa4SRandall Stewart 			return (0);
1309a115fb62SHans Petter Selasky 		}
1310a115fb62SHans Petter Selasky 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1311a115fb62SHans Petter Selasky 		    c, c->c_func, c->c_arg);
1312a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
1313a115fb62SHans Petter Selasky 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1314a115fb62SHans Petter Selasky 		return (0);
1315a115fb62SHans Petter Selasky 	}
1316a115fb62SHans Petter Selasky 	if (sq_locked)
1317*d2854fa4SRandall Stewart 		sleepq_release(&cc_exec_waiting(cc, direct));
1318a115fb62SHans Petter Selasky 
1319a115fb62SHans Petter Selasky 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
13201283e9cdSAttilio Rao 
132168a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
132268a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
1323*d2854fa4SRandall Stewart 	if (not_on_a_list == 0) {
1324a115fb62SHans Petter Selasky 		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1325*d2854fa4SRandall Stewart 			if (cc_exec_next(cc, direct) == c)
1326*d2854fa4SRandall Stewart 				cc_exec_next(cc, direct) = LIST_NEXT(c, c_links.le);
1327a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
1328a115fb62SHans Petter Selasky 		} else
1329a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1330*d2854fa4SRandall Stewart 	}
1331a115fb62SHans Petter Selasky 	callout_cc_del(c, cc);
1332a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
1333a115fb62SHans Petter Selasky 	return (1);
1334acc8326dSGarrett Wollman }
1335acc8326dSGarrett Wollman 
1336acc8326dSGarrett Wollman void
1337e392e44cSDavide Italiano callout_init(struct callout *c, int mpsafe)
1338acc8326dSGarrett Wollman {
1339a115fb62SHans Petter Selasky 	bzero(c, sizeof *c);
134098c926b2SIan Dowse 	if (mpsafe) {
1341a115fb62SHans Petter Selasky 		c->c_lock = NULL;
1342a115fb62SHans Petter Selasky 		c->c_flags = CALLOUT_RETURNUNLOCKED;
134398c926b2SIan Dowse 	} else {
1344a115fb62SHans Petter Selasky 		c->c_lock = &Giant.lock_object;
1345a115fb62SHans Petter Selasky 		c->c_flags = 0;
134698c926b2SIan Dowse 	}
1347a115fb62SHans Petter Selasky 	c->c_cpu = timeout_cpu;
134898c926b2SIan Dowse }
134998c926b2SIan Dowse 
135098c926b2SIan Dowse void
1351e392e44cSDavide Italiano _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
135298c926b2SIan Dowse {
135398c926b2SIan Dowse 	bzero(c, sizeof *c);
135464b9ee20SAttilio Rao 	c->c_lock = lock;
1355a115fb62SHans Petter Selasky 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1356a115fb62SHans Petter Selasky 	    ("callout_init_lock: bad flags %d", flags));
1357a115fb62SHans Petter Selasky 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1358a115fb62SHans Petter Selasky 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1359a115fb62SHans Petter Selasky 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1360a115fb62SHans Petter Selasky 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1361a115fb62SHans Petter Selasky 	    __func__));
1362a115fb62SHans Petter Selasky 	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
13638d809d50SJeff Roberson 	c->c_cpu = timeout_cpu;
1364acc8326dSGarrett Wollman }
1365acc8326dSGarrett Wollman 
1366e1d6dc65SNate Williams #ifdef APM_FIXUP_CALLTODO
1367e1d6dc65SNate Williams /*
1368e1d6dc65SNate Williams  * Adjust the kernel calltodo timeout list.  This routine is used after
1369e1d6dc65SNate Williams  * an APM resume to recalculate the calltodo timer list values with the
1370e1d6dc65SNate Williams  * number of hz's we have been sleeping.  The next hardclock() will detect
1371e1d6dc65SNate Williams  * that there are fired timers and run softclock() to execute them.
1372e1d6dc65SNate Williams  *
1373e1d6dc65SNate Williams  * Please note, I have not done an exhaustive analysis of what code this
1374e1d6dc65SNate Williams  * might break.  I am motivated to have my select()'s and alarm()'s that
1375e1d6dc65SNate Williams  * have expired during suspend firing upon resume so that the applications
1376e1d6dc65SNate Williams  * which set the timer can do the maintanence the timer was for as close
1377e1d6dc65SNate Williams  * as possible to the originally intended time.  Testing this code for a
1378e1d6dc65SNate Williams  * week showed that resuming from a suspend resulted in 22 to 25 timers
1379e1d6dc65SNate Williams  * firing, which seemed independant on whether the suspend was 2 hours or
1380e1d6dc65SNate Williams  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1381e1d6dc65SNate Williams  */
1382e1d6dc65SNate Williams void
1383e392e44cSDavide Italiano adjust_timeout_calltodo(struct timeval *time_change)
1384e1d6dc65SNate Williams {
1385e1d6dc65SNate Williams 	register struct callout *p;
1386e1d6dc65SNate Williams 	unsigned long delta_ticks;
1387e1d6dc65SNate Williams 
1388e1d6dc65SNate Williams 	/*
1389e1d6dc65SNate Williams 	 * How many ticks were we asleep?
1390c8b47828SBruce Evans 	 * (stolen from tvtohz()).
1391e1d6dc65SNate Williams 	 */
1392e1d6dc65SNate Williams 
1393e1d6dc65SNate Williams 	/* Don't do anything */
1394e1d6dc65SNate Williams 	if (time_change->tv_sec < 0)
1395e1d6dc65SNate Williams 		return;
1396e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
1397e1d6dc65SNate Williams 		delta_ticks = (time_change->tv_sec * 1000000 +
1398e1d6dc65SNate Williams 			       time_change->tv_usec + (tick - 1)) / tick + 1;
1399e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / hz)
1400e1d6dc65SNate Williams 		delta_ticks = time_change->tv_sec * hz +
1401e1d6dc65SNate Williams 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
1402e1d6dc65SNate Williams 	else
1403e1d6dc65SNate Williams 		delta_ticks = LONG_MAX;
1404e1d6dc65SNate Williams 
1405e1d6dc65SNate Williams 	if (delta_ticks > INT_MAX)
1406e1d6dc65SNate Williams 		delta_ticks = INT_MAX;
1407e1d6dc65SNate Williams 
1408e1d6dc65SNate Williams 	/*
1409e1d6dc65SNate Williams 	 * Now rip through the timer calltodo list looking for timers
1410e1d6dc65SNate Williams 	 * to expire.
1411e1d6dc65SNate Williams 	 */
1412e1d6dc65SNate Williams 
1413e1d6dc65SNate Williams 	/* don't collide with softclock() */
14148d809d50SJeff Roberson 	CC_LOCK(cc);
1415e1d6dc65SNate Williams 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1416e1d6dc65SNate Williams 		p->c_time -= delta_ticks;
1417e1d6dc65SNate Williams 
1418e1d6dc65SNate Williams 		/* Break if the timer had more time on it than delta_ticks */
1419e1d6dc65SNate Williams 		if (p->c_time > 0)
1420e1d6dc65SNate Williams 			break;
1421e1d6dc65SNate Williams 
1422e1d6dc65SNate Williams 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1423e1d6dc65SNate Williams 		delta_ticks = -p->c_time;
1424e1d6dc65SNate Williams 	}
14258d809d50SJeff Roberson 	CC_UNLOCK(cc);
1426e1d6dc65SNate Williams 
1427e1d6dc65SNate Williams 	return;
1428e1d6dc65SNate Williams }
1429e1d6dc65SNate Williams #endif /* APM_FIXUP_CALLTODO */
14305b999a6bSDavide Italiano 
14315b999a6bSDavide Italiano static int
14325b999a6bSDavide Italiano flssbt(sbintime_t sbt)
14335b999a6bSDavide Italiano {
14345b999a6bSDavide Italiano 
14355b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
14365b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
14375b999a6bSDavide Italiano 		return (flsl(sbt));
14385b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
14395b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
14405b999a6bSDavide Italiano 	return (flsl(sbt));
14415b999a6bSDavide Italiano }
14425b999a6bSDavide Italiano 
14435b999a6bSDavide Italiano /*
14445b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
14455b999a6bSDavide Italiano  */
14465b999a6bSDavide Italiano static int
14475b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
14485b999a6bSDavide Italiano {
14495b999a6bSDavide Italiano 	struct callout *tmp;
14505b999a6bSDavide Italiano 	struct callout_cpu *cc;
14515b999a6bSDavide Italiano 	struct callout_list *sc;
14525b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
14535b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
14545b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
14555b999a6bSDavide Italiano #ifdef SMP
14565b999a6bSDavide Italiano 	int cpu;
14575b999a6bSDavide Italiano #endif
14585b999a6bSDavide Italiano 
14595b999a6bSDavide Italiano 	val = 0;
14605b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
14615b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
14625b999a6bSDavide Italiano 		return (error);
14635b999a6bSDavide Italiano 	count = maxc = 0;
14645b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
14655b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
14665b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
14675b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
14685b999a6bSDavide Italiano 	now = sbinuptime();
14695b999a6bSDavide Italiano #ifdef SMP
14705b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
14715b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
14725b999a6bSDavide Italiano #else
14735b999a6bSDavide Italiano 		cc = CC_CPU(timeout_cpu);
14745b999a6bSDavide Italiano #endif
14755b999a6bSDavide Italiano 		CC_LOCK(cc);
14765b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
14775b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
14785b999a6bSDavide Italiano 			c = 0;
14795b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
14805b999a6bSDavide Italiano 				c++;
14815b999a6bSDavide Italiano 				t = tmp->c_time - now;
14825b999a6bSDavide Italiano 				if (t < 0)
14835b999a6bSDavide Italiano 					t = 0;
14845b999a6bSDavide Italiano 				st += t / SBT_1US;
14855b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
14865b999a6bSDavide Italiano 				if (t > maxt)
14875b999a6bSDavide Italiano 					maxt = t;
14885b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
14895b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
14905b999a6bSDavide Italiano 				ct[flssbt(t)]++;
14915b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
14925b999a6bSDavide Italiano 			}
14935b999a6bSDavide Italiano 			if (c > maxc)
14945b999a6bSDavide Italiano 				maxc = c;
14955b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
14965b999a6bSDavide Italiano 			count += c;
14975b999a6bSDavide Italiano 		}
14985b999a6bSDavide Italiano 		CC_UNLOCK(cc);
14995b999a6bSDavide Italiano #ifdef SMP
15005b999a6bSDavide Italiano 	}
15015b999a6bSDavide Italiano #endif
15025b999a6bSDavide Italiano 
15035b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
15045b999a6bSDavide Italiano 		tcum += ct[i];
15055b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
15065b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
15075b999a6bSDavide Italiano 		pcum += cpr[i];
15085b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
15095b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
15105b999a6bSDavide Italiano 		c += ccpbk[i];
15115b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
15125b999a6bSDavide Italiano 
15135b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
15145b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
15155b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
15165b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
15175b999a6bSDavide Italiano 	    medc,
15185b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
15195b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
15205b999a6bSDavide Italiano 	    maxc);
15215b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
15225b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
15235b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
15245b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
15255b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
15265b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
15275b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
15285b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
15295b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
15305b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
15315b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
15325b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
15335b999a6bSDavide Italiano 			continue;
15345b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
15355b999a6bSDavide Italiano 		tcum += ct[i];
15365b999a6bSDavide Italiano 		pcum += cpr[i];
15375b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
15385b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
15395b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
15405b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
15415b999a6bSDavide Italiano 	}
15425b999a6bSDavide Italiano 	return (error);
15435b999a6bSDavide Italiano }
15445b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
15455b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
15465b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
15475b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
1548