xref: /freebsd/sys/kern/kern_timeout.c (revision a8a03706fb01033b011bb795286f51444bab172d)
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"
445b999a6bSDavide Italiano #if defined(__arm__)
455b999a6bSDavide Italiano #include "opt_timer.h"
465b999a6bSDavide Italiano #endif
47c445c3c7SAdrian Chadd #include "opt_rss.h"
4891dd9aaeSRobert Watson 
49df8bae1dSRodney W. Grimes #include <sys/param.h>
50df8bae1dSRodney W. Grimes #include <sys/systm.h>
518d809d50SJeff Roberson #include <sys/bus.h>
5215b7a470SPoul-Henning Kamp #include <sys/callout.h>
5336d151a2SAlexander Motin #include <sys/domainset.h>
54f8ccf82aSAndre Oppermann #include <sys/file.h>
558d809d50SJeff Roberson #include <sys/interrupt.h>
56df8bae1dSRodney W. Grimes #include <sys/kernel.h>
57ff7ec58aSRobert Watson #include <sys/ktr.h>
58f34fa851SJohn Baldwin #include <sys/lock.h>
598d809d50SJeff Roberson #include <sys/malloc.h>
60cb799bfeSJohn Baldwin #include <sys/mutex.h>
6121f9e816SJohn Baldwin #include <sys/proc.h>
6291dd9aaeSRobert Watson #include <sys/sdt.h>
636a0ce57dSAttilio Rao #include <sys/sleepqueue.h>
6422ee8c4fSPoul-Henning Kamp #include <sys/sysctl.h>
658d809d50SJeff Roberson #include <sys/smp.h>
66df8bae1dSRodney W. Grimes 
673af72c11SBjoern A. Zeeb #ifdef DDB
683af72c11SBjoern A. Zeeb #include <ddb/ddb.h>
698c5a9161SEric van Gyzen #include <ddb/db_sym.h>
703af72c11SBjoern A. Zeeb #include <machine/_inttypes.h>
713af72c11SBjoern A. Zeeb #endif
723af72c11SBjoern A. Zeeb 
731283e9cdSAttilio Rao #ifdef SMP
741283e9cdSAttilio Rao #include <machine/cpu.h>
751283e9cdSAttilio Rao #endif
761283e9cdSAttilio Rao 
775b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
785b999a6bSDavide Italiano DPCPU_DECLARE(sbintime_t, hardclocktime);
795b999a6bSDavide Italiano #endif
805b999a6bSDavide Italiano 
8191dd9aaeSRobert Watson SDT_PROVIDER_DEFINE(callout_execute);
8236160958SMark Johnston SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
8336160958SMark Johnston SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
8491dd9aaeSRobert Watson 
855b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8622ee8c4fSPoul-Henning Kamp static int avg_depth;
8722ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8822ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
8922ee8c4fSPoul-Henning Kamp static int avg_gcalls;
9022ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
9122ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
9264b9ee20SAttilio Rao static int avg_lockcalls;
9364b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
9464b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
9522ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
9622ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
9722ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
985b999a6bSDavide Italiano static int avg_depth_dir;
995b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
1005b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
1015b999a6bSDavide Italiano     "Units = 1/1000");
1025b999a6bSDavide Italiano static int avg_lockcalls_dir;
1035b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
1045b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
1055b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
1065b999a6bSDavide Italiano static int avg_mpcalls_dir;
1075b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1085b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1095b999a6bSDavide Italiano     "Units = 1/1000");
1105b999a6bSDavide Italiano #endif
111f8ccf82aSAndre Oppermann 
112f8ccf82aSAndre Oppermann static int ncallout;
113af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
114f8ccf82aSAndre Oppermann     "Number of entries in callwheel and size of timeout() preallocation");
115f8ccf82aSAndre Oppermann 
116c445c3c7SAdrian Chadd #ifdef	RSS
117c445c3c7SAdrian Chadd static int pin_default_swi = 1;
118c445c3c7SAdrian Chadd static int pin_pcpu_swi = 1;
119c445c3c7SAdrian Chadd #else
120ac75ee9fSAdrian Chadd static int pin_default_swi = 0;
121ac75ee9fSAdrian Chadd static int pin_pcpu_swi = 0;
122c445c3c7SAdrian Chadd #endif
123ac75ee9fSAdrian Chadd 
124af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
125ac75ee9fSAdrian Chadd     0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
126af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
127ac75ee9fSAdrian Chadd     0, "Pin the per-CPU swis (except PCPU 0, which is also default");
128ac75ee9fSAdrian Chadd 
12915b7a470SPoul-Henning Kamp /*
13015b7a470SPoul-Henning Kamp  * TODO:
13115b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
13215b7a470SPoul-Henning Kamp  */
13361322a0aSAlexander Motin static u_int __read_mostly callwheelsize;
13461322a0aSAlexander Motin static u_int __read_mostly callwheelmask;
135f23b4c91SGarrett Wollman 
13620c510f8SLuigi Rizzo /*
137a115fb62SHans Petter Selasky  * The callout cpu exec entities represent informations necessary for
138a115fb62SHans Petter Selasky  * describing the state of callouts currently running on the CPU and the ones
139a115fb62SHans Petter Selasky  * necessary for migrating callouts to the new callout cpu. In particular,
140a115fb62SHans Petter Selasky  * the first entry of the array cc_exec_entity holds informations for callout
141a115fb62SHans Petter Selasky  * running in SWI thread context, while the second one holds informations
142a115fb62SHans Petter Selasky  * for callout running directly from hardware interrupt context.
143a115fb62SHans Petter Selasky  * The cached informations are very important for deferring migration when
144a115fb62SHans Petter Selasky  * the migrating callout is already running.
1451283e9cdSAttilio Rao  */
1465b999a6bSDavide Italiano struct cc_exec {
1475b999a6bSDavide Italiano 	struct callout		*cc_curr;
148*a8a03706SJohn Baldwin 	callout_func_t		*cc_drain;
1498c5a9161SEric van Gyzen 	void			*cc_last_func;
1508c5a9161SEric van Gyzen 	void			*cc_last_arg;
151a115fb62SHans Petter Selasky #ifdef SMP
152*a8a03706SJohn Baldwin 	callout_func_t		*ce_migration_func;
153a115fb62SHans Petter Selasky 	void			*ce_migration_arg;
154a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_time;
155a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_prec;
1568c5a9161SEric van Gyzen 	int			ce_migration_cpu;
157a115fb62SHans Petter Selasky #endif
158a4a3ce99SDavide Italiano 	bool			cc_cancel;
159a115fb62SHans Petter Selasky 	bool			cc_waiting;
1601283e9cdSAttilio Rao };
1611283e9cdSAttilio Rao 
1621283e9cdSAttilio Rao /*
163a115fb62SHans Petter Selasky  * There is one struct callout_cpu per cpu, holding all relevant
16420c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
16520c510f8SLuigi Rizzo  */
1668d809d50SJeff Roberson struct callout_cpu {
1674ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1685b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
16966525b2dSRandall Stewart 	struct callout		*cc_next;
1708d809d50SJeff Roberson 	struct callout		*cc_callout;
1715b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1725b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1735b999a6bSDavide Italiano 	struct callout_slist	cc_callfree;
1745b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1755b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
1768d809d50SJeff Roberson 	void			*cc_cookie;
1775b999a6bSDavide Italiano 	u_int			cc_bucket;
17815b1eb14SRandall Stewart 	u_int			cc_inited;
179329377f4SGleb Smirnoff #ifdef KTR
180232e8b52SJohn Baldwin 	char			cc_ktr_event_name[20];
181329377f4SGleb Smirnoff #endif
1828d809d50SJeff Roberson };
1838d809d50SJeff Roberson 
184403df7a6SRandall Stewart #define	callout_migrating(c)	((c)->c_iflags & CALLOUT_DFRMIGRATION)
185403df7a6SRandall Stewart 
186d2854fa4SRandall Stewart #define	cc_exec_curr(cc, dir)		cc->cc_exec_entity[dir].cc_curr
1878c5a9161SEric van Gyzen #define	cc_exec_last_func(cc, dir)	cc->cc_exec_entity[dir].cc_last_func
1888c5a9161SEric van Gyzen #define	cc_exec_last_arg(cc, dir)	cc->cc_exec_entity[dir].cc_last_arg
18918b4fd62SRandall Stewart #define	cc_exec_drain(cc, dir)		cc->cc_exec_entity[dir].cc_drain
19066525b2dSRandall Stewart #define	cc_exec_next(cc)		cc->cc_next
191d2854fa4SRandall Stewart #define	cc_exec_cancel(cc, dir)		cc->cc_exec_entity[dir].cc_cancel
192d2854fa4SRandall Stewart #define	cc_exec_waiting(cc, dir)	cc->cc_exec_entity[dir].cc_waiting
1938d809d50SJeff Roberson #ifdef SMP
194d2854fa4SRandall Stewart #define	cc_migration_func(cc, dir)	cc->cc_exec_entity[dir].ce_migration_func
195d2854fa4SRandall Stewart #define	cc_migration_arg(cc, dir)	cc->cc_exec_entity[dir].ce_migration_arg
196d2854fa4SRandall Stewart #define	cc_migration_cpu(cc, dir)	cc->cc_exec_entity[dir].ce_migration_cpu
197d2854fa4SRandall Stewart #define	cc_migration_time(cc, dir)	cc->cc_exec_entity[dir].ce_migration_time
198d2854fa4SRandall Stewart #define	cc_migration_prec(cc, dir)	cc->cc_exec_entity[dir].ce_migration_prec
199a115fb62SHans Petter Selasky 
2008d809d50SJeff Roberson struct callout_cpu cc_cpu[MAXCPU];
2011283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
2028d809d50SJeff Roberson #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
2038d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
2048d809d50SJeff Roberson #else
2058d809d50SJeff Roberson struct callout_cpu cc_cpu;
2068d809d50SJeff Roberson #define	CC_CPU(cpu)	&cc_cpu
2078d809d50SJeff Roberson #define	CC_SELF()	&cc_cpu
2088d809d50SJeff Roberson #endif
2098d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
2108d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
2111283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
2128d809d50SJeff Roberson 
21361322a0aSAlexander Motin static int __read_mostly timeout_cpu;
2145b999a6bSDavide Italiano 
215232e8b52SJohn Baldwin static void	callout_cpu_init(struct callout_cpu *cc, int cpu);
2165b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
2175b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
2185b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
2195b999a6bSDavide Italiano #endif
2205b999a6bSDavide Italiano 		    int direct);
2218d809d50SJeff Roberson 
222d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
22349a74476SColin Percival 
224a115fb62SHans Petter Selasky /**
225a115fb62SHans Petter Selasky  * Locked by cc_lock:
226a115fb62SHans Petter Selasky  *   cc_curr         - If a callout is in progress, it is cc_curr.
227a115fb62SHans Petter Selasky  *                     If cc_curr is non-NULL, threads waiting in
228a115fb62SHans Petter Selasky  *                     callout_drain() will be woken up as soon as the
229a115fb62SHans Petter Selasky  *                     relevant callout completes.
230a115fb62SHans Petter Selasky  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
231a115fb62SHans Petter Selasky  *                     guarantees that the current callout will not run.
232a115fb62SHans Petter Selasky  *                     The softclock() function sets this to 0 before it
233a115fb62SHans Petter Selasky  *                     drops callout_lock to acquire c_lock, and it calls
234a115fb62SHans Petter Selasky  *                     the handler only if curr_cancelled is still 0 after
235a115fb62SHans Petter Selasky  *                     cc_lock is successfully acquired.
236a115fb62SHans Petter Selasky  *   cc_waiting      - If a thread is waiting in callout_drain(), then
237a115fb62SHans Petter Selasky  *                     callout_wait is nonzero.  Set only when
238a115fb62SHans Petter Selasky  *                     cc_curr is non-NULL.
239a115fb62SHans Petter Selasky  */
240a115fb62SHans Petter Selasky 
241df8bae1dSRodney W. Grimes /*
242a115fb62SHans Petter Selasky  * Resets the execution entity tied to a specific callout cpu.
243a115fb62SHans Petter Selasky  */
244a115fb62SHans Petter Selasky static void
245a115fb62SHans Petter Selasky cc_cce_cleanup(struct callout_cpu *cc, int direct)
246a115fb62SHans Petter Selasky {
247a115fb62SHans Petter Selasky 
248d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
249d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
250d2854fa4SRandall Stewart 	cc_exec_waiting(cc, direct) = false;
251a115fb62SHans Petter Selasky #ifdef SMP
252d2854fa4SRandall Stewart 	cc_migration_cpu(cc, direct) = CPUBLOCK;
253d2854fa4SRandall Stewart 	cc_migration_time(cc, direct) = 0;
254d2854fa4SRandall Stewart 	cc_migration_prec(cc, direct) = 0;
255d2854fa4SRandall Stewart 	cc_migration_func(cc, direct) = NULL;
256d2854fa4SRandall Stewart 	cc_migration_arg(cc, direct) = NULL;
257a115fb62SHans Petter Selasky #endif
258a115fb62SHans Petter Selasky }
259a115fb62SHans Petter Selasky 
260a115fb62SHans Petter Selasky /*
261a115fb62SHans Petter Selasky  * Checks if migration is requested by a specific callout cpu.
262a115fb62SHans Petter Selasky  */
263a115fb62SHans Petter Selasky static int
264a115fb62SHans Petter Selasky cc_cce_migrating(struct callout_cpu *cc, int direct)
265a115fb62SHans Petter Selasky {
266a115fb62SHans Petter Selasky 
267a115fb62SHans Petter Selasky #ifdef SMP
268d2854fa4SRandall Stewart 	return (cc_migration_cpu(cc, direct) != CPUBLOCK);
269a115fb62SHans Petter Selasky #else
270a115fb62SHans Petter Selasky 	return (0);
271a115fb62SHans Petter Selasky #endif
272a115fb62SHans Petter Selasky }
273a115fb62SHans Petter Selasky 
274a115fb62SHans Petter Selasky /*
275a115fb62SHans Petter Selasky  * Kernel low level callwheel initialization
276efe67753SNathan Whitehorn  * called on the BSP during kernel startup.
277219d632cSMatthew Dillon  */
27815ae0c9aSAndre Oppermann static void
27915ae0c9aSAndre Oppermann callout_callwheel_init(void *dummy)
280219d632cSMatthew Dillon {
2818d809d50SJeff Roberson 	struct callout_cpu *cc;
2828d809d50SJeff Roberson 
283f8ccf82aSAndre Oppermann 	/*
284f8ccf82aSAndre Oppermann 	 * Calculate the size of the callout wheel and the preallocated
285f8ccf82aSAndre Oppermann 	 * timeout() structures.
286a7aea132SAndre Oppermann 	 * XXX: Clip callout to result of previous function of maxusers
287a7aea132SAndre Oppermann 	 * maximum 384.  This is still huge, but acceptable.
288f8ccf82aSAndre Oppermann 	 */
289efe67753SNathan Whitehorn 	memset(CC_CPU(curcpu), 0, sizeof(cc_cpu));
290f8ccf82aSAndre Oppermann 	ncallout = imin(16 + maxproc + maxfiles, 18508);
291f8ccf82aSAndre Oppermann 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
292f8ccf82aSAndre Oppermann 
293219d632cSMatthew Dillon 	/*
294922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
295922314f0SAlfred Perlstein 	 * than 'ncallout'.
296219d632cSMatthew Dillon 	 */
297922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
298219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
299219d632cSMatthew Dillon 
30015ae0c9aSAndre Oppermann 	/*
301ac75ee9fSAdrian Chadd 	 * Fetch whether we're pinning the swi's or not.
302ac75ee9fSAdrian Chadd 	 */
303ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
304ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
305ac75ee9fSAdrian Chadd 
306ac75ee9fSAdrian Chadd 	/*
307efe67753SNathan Whitehorn 	 * Only BSP handles timeout(9) and receives a preallocation.
30815ae0c9aSAndre Oppermann 	 *
30915ae0c9aSAndre Oppermann 	 * XXX: Once all timeout(9) consumers are converted this can
31015ae0c9aSAndre Oppermann 	 * be removed.
31115ae0c9aSAndre Oppermann 	 */
31215ae0c9aSAndre Oppermann 	timeout_cpu = PCPU_GET(cpuid);
31315ae0c9aSAndre Oppermann 	cc = CC_CPU(timeout_cpu);
31415ae0c9aSAndre Oppermann 	cc->cc_callout = malloc(ncallout * sizeof(struct callout),
31515ae0c9aSAndre Oppermann 	    M_CALLOUT, M_WAITOK);
316232e8b52SJohn Baldwin 	callout_cpu_init(cc, timeout_cpu);
317219d632cSMatthew Dillon }
31815ae0c9aSAndre Oppermann SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
319219d632cSMatthew Dillon 
32015ae0c9aSAndre Oppermann /*
32115ae0c9aSAndre Oppermann  * Initialize the per-cpu callout structures.
32215ae0c9aSAndre Oppermann  */
3238d809d50SJeff Roberson static void
324232e8b52SJohn Baldwin callout_cpu_init(struct callout_cpu *cc, int cpu)
3258d809d50SJeff Roberson {
3268d809d50SJeff Roberson 	struct callout *c;
3278d809d50SJeff Roberson 	int i;
3288d809d50SJeff Roberson 
3298d809d50SJeff Roberson 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
3308d809d50SJeff Roberson 	SLIST_INIT(&cc->cc_callfree);
33115b1eb14SRandall Stewart 	cc->cc_inited = 1;
33236d151a2SAlexander Motin 	cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
33336d151a2SAlexander Motin 	    callwheelsize, M_CALLOUT,
33436d151a2SAlexander Motin 	    DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
3355b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
3365b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
3375b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
3384bc38a5aSDavide Italiano 	cc->cc_firstevent = SBT_MAX;
339a115fb62SHans Petter Selasky 	for (i = 0; i < 2; i++)
340a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, i);
341329377f4SGleb Smirnoff #ifdef KTR
342232e8b52SJohn Baldwin 	snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
343232e8b52SJohn Baldwin 	    "callwheel cpu %d", cpu);
344329377f4SGleb Smirnoff #endif
345efe67753SNathan Whitehorn 	if (cc->cc_callout == NULL)	/* Only BSP handles timeout(9) */
3468d809d50SJeff Roberson 		return;
3478d809d50SJeff Roberson 	for (i = 0; i < ncallout; i++) {
3488d809d50SJeff Roberson 		c = &cc->cc_callout[i];
3498d809d50SJeff Roberson 		callout_init(c, 0);
35015b1eb14SRandall Stewart 		c->c_iflags = CALLOUT_LOCAL_ALLOC;
3518d809d50SJeff Roberson 		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
3528d809d50SJeff Roberson 	}
3538d809d50SJeff Roberson }
3548d809d50SJeff Roberson 
355a115fb62SHans Petter Selasky #ifdef SMP
356a115fb62SHans Petter Selasky /*
357a115fb62SHans Petter Selasky  * Switches the cpu tied to a specific callout.
358a115fb62SHans Petter Selasky  * The function expects a locked incoming callout cpu and returns with
359a115fb62SHans Petter Selasky  * locked outcoming callout cpu.
360a115fb62SHans Petter Selasky  */
361a115fb62SHans Petter Selasky static struct callout_cpu *
362a115fb62SHans Petter Selasky callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
363a115fb62SHans Petter Selasky {
364a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
365a115fb62SHans Petter Selasky 
366a115fb62SHans Petter Selasky 	MPASS(c != NULL && cc != NULL);
367a115fb62SHans Petter Selasky 	CC_LOCK_ASSERT(cc);
368a115fb62SHans Petter Selasky 
369a115fb62SHans Petter Selasky 	/*
370a115fb62SHans Petter Selasky 	 * Avoid interrupts and preemption firing after the callout cpu
371a115fb62SHans Petter Selasky 	 * is blocked in order to avoid deadlocks as the new thread
372a115fb62SHans Petter Selasky 	 * may be willing to acquire the callout cpu lock.
373a115fb62SHans Petter Selasky 	 */
374a115fb62SHans Petter Selasky 	c->c_cpu = CPUBLOCK;
375a115fb62SHans Petter Selasky 	spinlock_enter();
376a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
377a115fb62SHans Petter Selasky 	new_cc = CC_CPU(new_cpu);
378a115fb62SHans Petter Selasky 	CC_LOCK(new_cc);
379a115fb62SHans Petter Selasky 	spinlock_exit();
380a115fb62SHans Petter Selasky 	c->c_cpu = new_cpu;
381a115fb62SHans Petter Selasky 	return (new_cc);
382a115fb62SHans Petter Selasky }
383a115fb62SHans Petter Selasky #endif
384a115fb62SHans Petter Selasky 
385219d632cSMatthew Dillon /*
3868d809d50SJeff Roberson  * Start standard softclock thread.
3878d809d50SJeff Roberson  */
3888d809d50SJeff Roberson static void
3898d809d50SJeff Roberson start_softclock(void *dummy)
3908d809d50SJeff Roberson {
3918d809d50SJeff Roberson 	struct callout_cpu *cc;
392f44e2a4cSAdrian Chadd 	char name[MAXCOMLEN];
3938d809d50SJeff Roberson #ifdef SMP
3948d809d50SJeff Roberson 	int cpu;
395ac75ee9fSAdrian Chadd 	struct intr_event *ie;
3968d809d50SJeff Roberson #endif
3978d809d50SJeff Roberson 
3988d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
399f44e2a4cSAdrian Chadd 	snprintf(name, sizeof(name), "clock (%d)", timeout_cpu);
400f44e2a4cSAdrian Chadd 	if (swi_add(&clk_intr_event, name, softclock, cc, SWI_CLOCK,
4013350df48SJohn Baldwin 	    INTR_MPSAFE, &cc->cc_cookie))
4028d809d50SJeff Roberson 		panic("died while creating standard software ithreads");
403ac75ee9fSAdrian Chadd 	if (pin_default_swi &&
404ac75ee9fSAdrian Chadd 	    (intr_event_bind(clk_intr_event, timeout_cpu) != 0)) {
405ac75ee9fSAdrian Chadd 		printf("%s: timeout clock couldn't be pinned to cpu %d\n",
406ac75ee9fSAdrian Chadd 		    __func__,
407ac75ee9fSAdrian Chadd 		    timeout_cpu);
408ac75ee9fSAdrian Chadd 	}
409ac75ee9fSAdrian Chadd 
4108d809d50SJeff Roberson #ifdef SMP
4113aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
4128d809d50SJeff Roberson 		if (cpu == timeout_cpu)
4138d809d50SJeff Roberson 			continue;
4148d809d50SJeff Roberson 		cc = CC_CPU(cpu);
415efe67753SNathan Whitehorn 		cc->cc_callout = NULL;	/* Only BSP handles timeout(9). */
416232e8b52SJohn Baldwin 		callout_cpu_init(cc, cpu);
417f44e2a4cSAdrian Chadd 		snprintf(name, sizeof(name), "clock (%d)", cpu);
418ac75ee9fSAdrian Chadd 		ie = NULL;
419ac75ee9fSAdrian Chadd 		if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
4208d809d50SJeff Roberson 		    INTR_MPSAFE, &cc->cc_cookie))
4218d809d50SJeff Roberson 			panic("died while creating standard software ithreads");
422ac75ee9fSAdrian Chadd 		if (pin_pcpu_swi && (intr_event_bind(ie, cpu) != 0)) {
423ac75ee9fSAdrian Chadd 			printf("%s: per-cpu clock couldn't be pinned to "
424ac75ee9fSAdrian Chadd 			    "cpu %d\n",
425ac75ee9fSAdrian Chadd 			    __func__,
426ac75ee9fSAdrian Chadd 			    cpu);
427ac75ee9fSAdrian Chadd 		}
428219d632cSMatthew Dillon 	}
4298d809d50SJeff Roberson #endif
430219d632cSMatthew Dillon }
4318d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
4328d809d50SJeff Roberson 
4335b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
4348d809d50SJeff Roberson 
4355b999a6bSDavide Italiano static inline u_int
4365b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
4375b999a6bSDavide Italiano {
4385b999a6bSDavide Italiano 
4395b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
4405b999a6bSDavide Italiano }
4415b999a6bSDavide Italiano 
4425b999a6bSDavide Italiano static inline u_int
4435b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
4445b999a6bSDavide Italiano {
4455b999a6bSDavide Italiano 
4465b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
4475b999a6bSDavide Italiano }
4485b999a6bSDavide Italiano 
4495b999a6bSDavide Italiano void
4505b999a6bSDavide Italiano callout_process(sbintime_t now)
4515b999a6bSDavide Italiano {
4525b999a6bSDavide Italiano 	struct callout *tmp, *tmpn;
4535b999a6bSDavide Italiano 	struct callout_cpu *cc;
4545b999a6bSDavide Italiano 	struct callout_list *sc;
4555b999a6bSDavide Italiano 	sbintime_t first, last, max, tmp_max;
4565b999a6bSDavide Italiano 	uint32_t lookahead;
4575b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
4585b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4595b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
4605b999a6bSDavide Italiano #endif
461a115fb62SHans Petter Selasky 
4628d809d50SJeff Roberson 	cc = CC_SELF();
463a115fb62SHans Petter Selasky 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4645b999a6bSDavide Italiano 
4655b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4665b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4675b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4685b999a6bSDavide Italiano 	nowb = callout_hash(now);
4695b999a6bSDavide Italiano 
4705b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4715b999a6bSDavide Italiano 	if (nowb == firstb)
4725b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4735b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4745b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4755b999a6bSDavide Italiano 	else
4765b999a6bSDavide Italiano 		lookahead = (SBT_1S / 2);
4775b999a6bSDavide Italiano 	first = last = now;
4785b999a6bSDavide Italiano 	first += (lookahead / 2);
4795b999a6bSDavide Italiano 	last += lookahead;
4805b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4815b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4825b999a6bSDavide Italiano 	max = last;
4835b999a6bSDavide Italiano 
4845b999a6bSDavide Italiano 	/*
4855b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4865b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4875b999a6bSDavide Italiano 	 */
4885b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4895b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4905b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4915b999a6bSDavide Italiano 			nowb = lastb;
4929fc51b0bSJeff Roberson 	}
4935b999a6bSDavide Italiano 
4945b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4955b999a6bSDavide Italiano 	do {
4965b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
4975b999a6bSDavide Italiano 		tmp = LIST_FIRST(sc);
4985b999a6bSDavide Italiano 		while (tmp != NULL) {
4995b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
5005b999a6bSDavide Italiano 			if (tmp->c_time <= now) {
5015b999a6bSDavide Italiano 				/*
5025b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
5035b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
5045b999a6bSDavide Italiano 				 */
50515b1eb14SRandall Stewart 				if (tmp->c_iflags & CALLOUT_DIRECT) {
5065b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5075b999a6bSDavide Italiano 					++depth_dir;
5085b999a6bSDavide Italiano #endif
50966525b2dSRandall Stewart 					cc_exec_next(cc) =
5105b999a6bSDavide Italiano 					    LIST_NEXT(tmp, c_links.le);
5115b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
5125b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
5135b999a6bSDavide Italiano 					softclock_call_cc(tmp, cc,
5145b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5155b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
5165b999a6bSDavide Italiano #endif
5175b999a6bSDavide Italiano 					    1);
51866525b2dSRandall Stewart 					tmp = cc_exec_next(cc);
51966525b2dSRandall Stewart 					cc_exec_next(cc) = NULL;
5205b999a6bSDavide Italiano 				} else {
5215b999a6bSDavide Italiano 					tmpn = LIST_NEXT(tmp, c_links.le);
5225b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
5235b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
5245b999a6bSDavide Italiano 					    tmp, c_links.tqe);
52515b1eb14SRandall Stewart 					tmp->c_iflags |= CALLOUT_PROCESSED;
5265b999a6bSDavide Italiano 					tmp = tmpn;
5279fc51b0bSJeff Roberson 				}
5285b999a6bSDavide Italiano 				continue;
5295b999a6bSDavide Italiano 			}
5305b999a6bSDavide Italiano 			/* Skip events from distant future. */
5315b999a6bSDavide Italiano 			if (tmp->c_time >= max)
5325b999a6bSDavide Italiano 				goto next;
5335b999a6bSDavide Italiano 			/*
5345b999a6bSDavide Italiano 			 * Event minimal time is bigger than present maximal
5355b999a6bSDavide Italiano 			 * time, so it cannot be aggregated.
5365b999a6bSDavide Italiano 			 */
5375b999a6bSDavide Italiano 			if (tmp->c_time > last) {
5385b999a6bSDavide Italiano 				lastb = nowb;
5395b999a6bSDavide Italiano 				goto next;
5405b999a6bSDavide Italiano 			}
5415b999a6bSDavide Italiano 			/* Update first and last time, respecting this event. */
5425b999a6bSDavide Italiano 			if (tmp->c_time < first)
5435b999a6bSDavide Italiano 				first = tmp->c_time;
5445b999a6bSDavide Italiano 			tmp_max = tmp->c_time + tmp->c_precision;
5455b999a6bSDavide Italiano 			if (tmp_max < last)
5465b999a6bSDavide Italiano 				last = tmp_max;
5475b999a6bSDavide Italiano next:
5485b999a6bSDavide Italiano 			tmp = LIST_NEXT(tmp, c_links.le);
5495b999a6bSDavide Italiano 		}
5505b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
5515b999a6bSDavide Italiano 		firstb++;
5525b999a6bSDavide Italiano 		/*
5535b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
5545b999a6bSDavide Italiano 		 * some event we can't execute at now.
5555b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
5565b999a6bSDavide Italiano 		 */
5575b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
5585b999a6bSDavide Italiano 	cc->cc_firstevent = last;
5595b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
5605b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
5615b999a6bSDavide Italiano #endif
5625b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5635b999a6bSDavide Italiano 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
5645b999a6bSDavide Italiano 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
5655b999a6bSDavide Italiano 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
5665b999a6bSDavide Italiano #endif
567a115fb62SHans Petter Selasky 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5688d809d50SJeff Roberson 	/*
5698d809d50SJeff Roberson 	 * swi_sched acquires the thread lock, so we don't want to call it
5708d809d50SJeff Roberson 	 * with cc_lock held; incorrect locking order.
5718d809d50SJeff Roberson 	 */
5725b999a6bSDavide Italiano 	if (!TAILQ_EMPTY(&cc->cc_expireq))
5738d809d50SJeff Roberson 		swi_sched(cc->cc_cookie, 0);
5748d809d50SJeff Roberson }
5758d809d50SJeff Roberson 
5768d809d50SJeff Roberson static struct callout_cpu *
5778d809d50SJeff Roberson callout_lock(struct callout *c)
5788d809d50SJeff Roberson {
5798d809d50SJeff Roberson 	struct callout_cpu *cc;
580a115fb62SHans Petter Selasky 	int cpu;
581a115fb62SHans Petter Selasky 
582a115fb62SHans Petter Selasky 	for (;;) {
583a115fb62SHans Petter Selasky 		cpu = c->c_cpu;
584a115fb62SHans Petter Selasky #ifdef SMP
585a115fb62SHans Petter Selasky 		if (cpu == CPUBLOCK) {
586a115fb62SHans Petter Selasky 			while (c->c_cpu == CPUBLOCK)
587a115fb62SHans Petter Selasky 				cpu_spinwait();
588a115fb62SHans Petter Selasky 			continue;
589a115fb62SHans Petter Selasky 		}
590a115fb62SHans Petter Selasky #endif
591a115fb62SHans Petter Selasky 		cc = CC_CPU(cpu);
5928d809d50SJeff Roberson 		CC_LOCK(cc);
593a115fb62SHans Petter Selasky 		if (cpu == c->c_cpu)
594a115fb62SHans Petter Selasky 			break;
595a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
596a115fb62SHans Petter Selasky 	}
5978d809d50SJeff Roberson 	return (cc);
598219d632cSMatthew Dillon }
599219d632cSMatthew Dillon 
600a115fb62SHans Petter Selasky static void
601a115fb62SHans Petter Selasky callout_cc_add(struct callout *c, struct callout_cpu *cc,
602a115fb62SHans Petter Selasky     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
60366525b2dSRandall Stewart     void *arg, int cpu, int flags)
6041283e9cdSAttilio Rao {
6055b999a6bSDavide Italiano 	int bucket;
6061283e9cdSAttilio Rao 
6071283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
608a115fb62SHans Petter Selasky 	if (sbt < cc->cc_lastscan)
609a115fb62SHans Petter Selasky 		sbt = cc->cc_lastscan;
610a115fb62SHans Petter Selasky 	c->c_arg = arg;
61115b1eb14SRandall Stewart 	c->c_iflags |= CALLOUT_PENDING;
61215b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PROCESSED;
61315b1eb14SRandall Stewart 	c->c_flags |= CALLOUT_ACTIVE;
61407a2df5dSRandall Stewart 	if (flags & C_DIRECT_EXEC)
615b132edb5SRandall Stewart 		c->c_iflags |= CALLOUT_DIRECT;
616a115fb62SHans Petter Selasky 	c->c_func = func;
617a115fb62SHans Petter Selasky 	c->c_time = sbt;
618a115fb62SHans Petter Selasky 	c->c_precision = precision;
6195b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
6205b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
6215b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
6225b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
6235b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
6245b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
62566525b2dSRandall Stewart 		cc_exec_next(cc) = c;
6265b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
6275b999a6bSDavide Italiano 	/*
6285b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
6295b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
6305b999a6bSDavide Italiano 	 */
6314bc38a5aSDavide Italiano 	if (SBT_MAX - c->c_time < c->c_precision)
6324bc38a5aSDavide Italiano 		c->c_precision = SBT_MAX - c->c_time;
6335b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
6345b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
6355b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
636a115fb62SHans Petter Selasky 		cpu_new_callout(cpu, sbt, c->c_time);
6371283e9cdSAttilio Rao 	}
6385b999a6bSDavide Italiano #endif
6391283e9cdSAttilio Rao }
6401283e9cdSAttilio Rao 
6416098e7acSKonstantin Belousov static void
6426098e7acSKonstantin Belousov callout_cc_del(struct callout *c, struct callout_cpu *cc)
6436098e7acSKonstantin Belousov {
6446098e7acSKonstantin Belousov 
64515b1eb14SRandall Stewart 	if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) == 0)
646a115fb62SHans Petter Selasky 		return;
6476098e7acSKonstantin Belousov 	c->c_func = NULL;
6486098e7acSKonstantin Belousov 	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
6496098e7acSKonstantin Belousov }
6506098e7acSKonstantin Belousov 
651eb8a7186SKonstantin Belousov static void
6525b999a6bSDavide Italiano softclock_call_cc(struct callout *c, struct callout_cpu *cc,
6535b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6545b999a6bSDavide Italiano     int *mpcalls, int *lockcalls, int *gcalls,
6555b999a6bSDavide Italiano #endif
6565b999a6bSDavide Italiano     int direct)
6576098e7acSKonstantin Belousov {
658a115fb62SHans Petter Selasky 	struct rm_priotracker tracker;
659*a8a03706SJohn Baldwin 	callout_func_t *c_func, *drain;
6606098e7acSKonstantin Belousov 	void *c_arg;
661a115fb62SHans Petter Selasky 	struct lock_class *class;
6626098e7acSKonstantin Belousov 	struct lock_object *c_lock;
663a115fb62SHans Petter Selasky 	uintptr_t lock_status;
66415b1eb14SRandall Stewart 	int c_iflags;
665a115fb62SHans Petter Selasky #ifdef SMP
666a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
667*a8a03706SJohn Baldwin 	callout_func_t *new_func;
668a115fb62SHans Petter Selasky 	void *new_arg;
669a115fb62SHans Petter Selasky 	int flags, new_cpu;
670a115fb62SHans Petter Selasky 	sbintime_t new_prec, new_time;
671a115fb62SHans Petter Selasky #endif
6725b999a6bSDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
67303763781SDavide Italiano 	sbintime_t sbt1, sbt2;
6746098e7acSKonstantin Belousov 	struct timespec ts2;
6755b999a6bSDavide Italiano 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
676*a8a03706SJohn Baldwin 	static callout_func_t *lastfunc;
6776098e7acSKonstantin Belousov #endif
6786098e7acSKonstantin Belousov 
67915b1eb14SRandall Stewart 	KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
68015b1eb14SRandall Stewart 	    ("softclock_call_cc: pend %p %x", c, c->c_iflags));
68115b1eb14SRandall Stewart 	KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
68215b1eb14SRandall Stewart 	    ("softclock_call_cc: act %p %x", c, c->c_flags));
683a115fb62SHans Petter Selasky 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
684a115fb62SHans Petter Selasky 	lock_status = 0;
685a115fb62SHans Petter Selasky 	if (c->c_flags & CALLOUT_SHAREDLOCK) {
686a115fb62SHans Petter Selasky 		if (class == &lock_class_rm)
687a115fb62SHans Petter Selasky 			lock_status = (uintptr_t)&tracker;
688a115fb62SHans Petter Selasky 		else
689a115fb62SHans Petter Selasky 			lock_status = 1;
690a115fb62SHans Petter Selasky 	}
6916098e7acSKonstantin Belousov 	c_lock = c->c_lock;
6926098e7acSKonstantin Belousov 	c_func = c->c_func;
6936098e7acSKonstantin Belousov 	c_arg = c->c_arg;
69415b1eb14SRandall Stewart 	c_iflags = c->c_iflags;
69515b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_LOCAL_ALLOC)
69615b1eb14SRandall Stewart 		c->c_iflags = CALLOUT_LOCAL_ALLOC;
697a115fb62SHans Petter Selasky 	else
69815b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_PENDING;
699d2854fa4SRandall Stewart 
700d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = c;
7018c5a9161SEric van Gyzen 	cc_exec_last_func(cc, direct) = c_func;
7028c5a9161SEric van Gyzen 	cc_exec_last_arg(cc, direct) = c_arg;
703d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
70418b4fd62SRandall Stewart 	cc_exec_drain(cc, direct) = NULL;
7056098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
706a115fb62SHans Petter Selasky 	if (c_lock != NULL) {
707a115fb62SHans Petter Selasky 		class->lc_lock(c_lock, lock_status);
7086098e7acSKonstantin Belousov 		/*
709a115fb62SHans Petter Selasky 		 * The callout may have been cancelled
710a115fb62SHans Petter Selasky 		 * while we switched locks.
7116098e7acSKonstantin Belousov 		 */
712d2854fa4SRandall Stewart 		if (cc_exec_cancel(cc, direct)) {
713a115fb62SHans Petter Selasky 			class->lc_unlock(c_lock);
714a115fb62SHans Petter Selasky 			goto skip;
7156098e7acSKonstantin Belousov 		}
716a115fb62SHans Petter Selasky 		/* The callout cannot be stopped now. */
717d2854fa4SRandall Stewart 		cc_exec_cancel(cc, direct) = true;
7186098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
7195b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7206098e7acSKonstantin Belousov 			(*gcalls)++;
7215b999a6bSDavide Italiano #endif
7225b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
7236098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7246098e7acSKonstantin Belousov 		} else {
7255b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7266098e7acSKonstantin Belousov 			(*lockcalls)++;
7275b999a6bSDavide Italiano #endif
7286098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
7296098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7306098e7acSKonstantin Belousov 		}
7316098e7acSKonstantin Belousov 	} else {
7325b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7336098e7acSKonstantin Belousov 		(*mpcalls)++;
7345b999a6bSDavide Italiano #endif
7355b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
7366098e7acSKonstantin Belousov 		    c, c_func, c_arg);
7376098e7acSKonstantin Belousov 	}
738232e8b52SJohn Baldwin 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
739232e8b52SJohn Baldwin 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
74003763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
7415b999a6bSDavide Italiano 	sbt1 = sbinuptime();
7426098e7acSKonstantin Belousov #endif
7436098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
74436160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__start, c);
7456098e7acSKonstantin Belousov 	c_func(c_arg);
74636160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__end, c);
7476098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
74803763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
74903763781SDavide Italiano 	sbt2 = sbinuptime();
75003763781SDavide Italiano 	sbt2 -= sbt1;
75103763781SDavide Italiano 	if (sbt2 > maxdt) {
75203763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
75303763781SDavide Italiano 			ts2 = sbttots(sbt2);
7546098e7acSKonstantin Belousov 			printf(
7556098e7acSKonstantin Belousov 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
7566098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
7576098e7acSKonstantin Belousov 		}
75803763781SDavide Italiano 		maxdt = sbt2;
7596098e7acSKonstantin Belousov 		lastfunc = c_func;
7606098e7acSKonstantin Belousov 	}
7616098e7acSKonstantin Belousov #endif
762232e8b52SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
7636098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
76415b1eb14SRandall Stewart 	if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
765a115fb62SHans Petter Selasky 		class->lc_unlock(c_lock);
766a115fb62SHans Petter Selasky skip:
7676098e7acSKonstantin Belousov 	CC_LOCK(cc);
768d2854fa4SRandall Stewart 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
769d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
77018b4fd62SRandall Stewart 	if (cc_exec_drain(cc, direct)) {
77118b4fd62SRandall Stewart 		drain = cc_exec_drain(cc, direct);
77218b4fd62SRandall Stewart 		cc_exec_drain(cc, direct) = NULL;
77318b4fd62SRandall Stewart 		CC_UNLOCK(cc);
77418b4fd62SRandall Stewart 		drain(c_arg);
77518b4fd62SRandall Stewart 		CC_LOCK(cc);
77618b4fd62SRandall Stewart 	}
777d2854fa4SRandall Stewart 	if (cc_exec_waiting(cc, direct)) {
778bdf9120cSAttilio Rao 		/*
779a115fb62SHans Petter Selasky 		 * There is someone waiting for the
780a115fb62SHans Petter Selasky 		 * callout to complete.
781a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
782a115fb62SHans Petter Selasky 		 * migration just cancel it.
783bdf9120cSAttilio Rao 		 */
784a115fb62SHans Petter Selasky 		if (cc_cce_migrating(cc, direct)) {
785a115fb62SHans Petter Selasky 			cc_cce_cleanup(cc, direct);
786a115fb62SHans Petter Selasky 
787a115fb62SHans Petter Selasky 			/*
788a115fb62SHans Petter Selasky 			 * It should be assert here that the callout is not
789a115fb62SHans Petter Selasky 			 * destroyed but that is not easy.
790a115fb62SHans Petter Selasky 			 */
79115b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
7926098e7acSKonstantin Belousov 		}
793d2854fa4SRandall Stewart 		cc_exec_waiting(cc, direct) = false;
794a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
795d2854fa4SRandall Stewart 		wakeup(&cc_exec_waiting(cc, direct));
796a115fb62SHans Petter Selasky 		CC_LOCK(cc);
797a115fb62SHans Petter Selasky 	} else if (cc_cce_migrating(cc, direct)) {
79815b1eb14SRandall Stewart 		KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0,
799a115fb62SHans Petter Selasky 		    ("Migrating legacy callout %p", c));
800a115fb62SHans Petter Selasky #ifdef SMP
801a115fb62SHans Petter Selasky 		/*
802a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
803a115fb62SHans Petter Selasky 		 * migration just perform it now.
804a115fb62SHans Petter Selasky 		 */
805d2854fa4SRandall Stewart 		new_cpu = cc_migration_cpu(cc, direct);
806d2854fa4SRandall Stewart 		new_time = cc_migration_time(cc, direct);
807d2854fa4SRandall Stewart 		new_prec = cc_migration_prec(cc, direct);
808d2854fa4SRandall Stewart 		new_func = cc_migration_func(cc, direct);
809d2854fa4SRandall Stewart 		new_arg = cc_migration_arg(cc, direct);
810a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, direct);
811a115fb62SHans Petter Selasky 
812a115fb62SHans Petter Selasky 		/*
813a115fb62SHans Petter Selasky 		 * It should be assert here that the callout is not destroyed
814a115fb62SHans Petter Selasky 		 * but that is not easy.
815a115fb62SHans Petter Selasky 		 *
816a115fb62SHans Petter Selasky 		 * As first thing, handle deferred callout stops.
817a115fb62SHans Petter Selasky 		 */
818d2854fa4SRandall Stewart 		if (!callout_migrating(c)) {
819a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT,
820a115fb62SHans Petter Selasky 			     "deferred cancelled %p func %p arg %p",
821a115fb62SHans Petter Selasky 			     c, new_func, new_arg);
822a115fb62SHans Petter Selasky 			callout_cc_del(c, cc);
823a115fb62SHans Petter Selasky 			return;
824a115fb62SHans Petter Selasky 		}
82515b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_DFRMIGRATION;
826a115fb62SHans Petter Selasky 
827a115fb62SHans Petter Selasky 		new_cc = callout_cpu_switch(c, cc, new_cpu);
828a115fb62SHans Petter Selasky 		flags = (direct) ? C_DIRECT_EXEC : 0;
829a115fb62SHans Petter Selasky 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
83066525b2dSRandall Stewart 		    new_arg, new_cpu, flags);
831a115fb62SHans Petter Selasky 		CC_UNLOCK(new_cc);
832a115fb62SHans Petter Selasky 		CC_LOCK(cc);
833a115fb62SHans Petter Selasky #else
834a115fb62SHans Petter Selasky 		panic("migration should not happen");
835a115fb62SHans Petter Selasky #endif
836a115fb62SHans Petter Selasky 	}
837a115fb62SHans Petter Selasky 	/*
838a115fb62SHans Petter Selasky 	 * If the current callout is locally allocated (from
839a115fb62SHans Petter Selasky 	 * timeout(9)) then put it on the freelist.
840a115fb62SHans Petter Selasky 	 *
84115b1eb14SRandall Stewart 	 * Note: we need to check the cached copy of c_iflags because
842a115fb62SHans Petter Selasky 	 * if it was not local, then it's not safe to deref the
843a115fb62SHans Petter Selasky 	 * callout pointer.
844a115fb62SHans Petter Selasky 	 */
84515b1eb14SRandall Stewart 	KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0 ||
84615b1eb14SRandall Stewart 	    c->c_iflags == CALLOUT_LOCAL_ALLOC,
847a115fb62SHans Petter Selasky 	    ("corrupted callout"));
84815b1eb14SRandall Stewart 	if (c_iflags & CALLOUT_LOCAL_ALLOC)
849a115fb62SHans Petter Selasky 		callout_cc_del(c, cc);
8506098e7acSKonstantin Belousov }
8516098e7acSKonstantin Belousov 
852219d632cSMatthew Dillon /*
853ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
854ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
855ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
856ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
857024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
858ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
859ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
860ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
861ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
862ab36c067SJustin T. Gibbs  */
863a50ec505SPoul-Henning Kamp 
864ab36c067SJustin T. Gibbs /*
865df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
866df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
867df8bae1dSRodney W. Grimes  */
868df8bae1dSRodney W. Grimes void
8698d809d50SJeff Roberson softclock(void *arg)
870df8bae1dSRodney W. Grimes {
8718d809d50SJeff Roberson 	struct callout_cpu *cc;
872b336df68SPoul-Henning Kamp 	struct callout *c;
8735b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8745b999a6bSDavide Italiano 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
8755b999a6bSDavide Italiano #endif
876df8bae1dSRodney W. Grimes 
8778d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
8788d809d50SJeff Roberson 	CC_LOCK(cc);
8795b999a6bSDavide Italiano 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
8805b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
8815b999a6bSDavide Italiano 		softclock_call_cc(c, cc,
8825b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8835b999a6bSDavide Italiano 		    &mpcalls, &lockcalls, &gcalls,
8845b999a6bSDavide Italiano #endif
8855b999a6bSDavide Italiano 		    0);
8865b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8875b999a6bSDavide Italiano 		++depth;
8885b999a6bSDavide Italiano #endif
889df8bae1dSRodney W. Grimes 	}
8905b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
89122ee8c4fSPoul-Henning Kamp 	avg_depth += (depth * 1000 - avg_depth) >> 8;
89222ee8c4fSPoul-Henning Kamp 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
89364b9ee20SAttilio Rao 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
89422ee8c4fSPoul-Henning Kamp 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8955b999a6bSDavide Italiano #endif
8968d809d50SJeff Roberson 	CC_UNLOCK(cc);
897df8bae1dSRodney W. Grimes }
898df8bae1dSRodney W. Grimes 
899df8bae1dSRodney W. Grimes /*
900df8bae1dSRodney W. Grimes  * timeout --
901df8bae1dSRodney W. Grimes  *	Execute a function after a specified length of time.
902df8bae1dSRodney W. Grimes  *
903df8bae1dSRodney W. Grimes  * untimeout --
904df8bae1dSRodney W. Grimes  *	Cancel previous timeout function call.
905df8bae1dSRodney W. Grimes  *
906ab36c067SJustin T. Gibbs  * callout_handle_init --
907ab36c067SJustin T. Gibbs  *	Initialize a handle so that using it with untimeout is benign.
908ab36c067SJustin T. Gibbs  *
909df8bae1dSRodney W. Grimes  *	See AT&T BCI Driver Reference Manual for specification.  This
910ab36c067SJustin T. Gibbs  *	implementation differs from that one in that although an
911ab36c067SJustin T. Gibbs  *	identification value is returned from timeout, the original
912ab36c067SJustin T. Gibbs  *	arguments to timeout as well as the identifier are used to
913ab36c067SJustin T. Gibbs  *	identify entries for untimeout.
914df8bae1dSRodney W. Grimes  */
915ab36c067SJustin T. Gibbs struct callout_handle
916e392e44cSDavide Italiano timeout(timeout_t *ftn, void *arg, int to_ticks)
917df8bae1dSRodney W. Grimes {
9188d809d50SJeff Roberson 	struct callout_cpu *cc;
919ab36c067SJustin T. Gibbs 	struct callout *new;
920ab36c067SJustin T. Gibbs 	struct callout_handle handle;
921df8bae1dSRodney W. Grimes 
9228d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
9238d809d50SJeff Roberson 	CC_LOCK(cc);
924df8bae1dSRodney W. Grimes 	/* Fill in the next free callout structure. */
9258d809d50SJeff Roberson 	new = SLIST_FIRST(&cc->cc_callfree);
926ab36c067SJustin T. Gibbs 	if (new == NULL)
927ab36c067SJustin T. Gibbs 		/* XXX Attempt to malloc first */
928df8bae1dSRodney W. Grimes 		panic("timeout table full");
9298d809d50SJeff Roberson 	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
930a115fb62SHans Petter Selasky 	callout_reset(new, to_ticks, ftn, arg);
931ab36c067SJustin T. Gibbs 	handle.callout = new;
9328d809d50SJeff Roberson 	CC_UNLOCK(cc);
9338d809d50SJeff Roberson 
934ab36c067SJustin T. Gibbs 	return (handle);
935df8bae1dSRodney W. Grimes }
936df8bae1dSRodney W. Grimes 
937df8bae1dSRodney W. Grimes void
938e392e44cSDavide Italiano untimeout(timeout_t *ftn, void *arg, struct callout_handle handle)
939df8bae1dSRodney W. Grimes {
9408d809d50SJeff Roberson 	struct callout_cpu *cc;
941df8bae1dSRodney W. Grimes 
942ab36c067SJustin T. Gibbs 	/*
943ab36c067SJustin T. Gibbs 	 * Check for a handle that was initialized
944ab36c067SJustin T. Gibbs 	 * by callout_handle_init, but never used
945ab36c067SJustin T. Gibbs 	 * for a real timeout.
946ab36c067SJustin T. Gibbs 	 */
947ab36c067SJustin T. Gibbs 	if (handle.callout == NULL)
948ab36c067SJustin T. Gibbs 		return;
949df8bae1dSRodney W. Grimes 
9508d809d50SJeff Roberson 	cc = callout_lock(handle.callout);
951a115fb62SHans Petter Selasky 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
9521a26c3c0SHans Petter Selasky 		callout_stop(handle.callout);
953a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
954df8bae1dSRodney W. Grimes }
955df8bae1dSRodney W. Grimes 
9563c816944SBruce Evans void
957ab36c067SJustin T. Gibbs callout_handle_init(struct callout_handle *handle)
958ab36c067SJustin T. Gibbs {
959ab36c067SJustin T. Gibbs 	handle->callout = NULL;
960ab36c067SJustin T. Gibbs }
961ab36c067SJustin T. Gibbs 
962a9e182e8SKonstantin Belousov void
963a9e182e8SKonstantin Belousov callout_when(sbintime_t sbt, sbintime_t precision, int flags,
964a9e182e8SKonstantin Belousov     sbintime_t *res, sbintime_t *prec_res)
965acc8326dSGarrett Wollman {
966a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, to_pr;
967acc8326dSGarrett Wollman 
968a9e182e8SKonstantin Belousov 	if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
969a9e182e8SKonstantin Belousov 		*res = sbt;
970a9e182e8SKonstantin Belousov 		*prec_res = precision;
971a9e182e8SKonstantin Belousov 		return;
97215b1eb14SRandall Stewart 	}
973a9e182e8SKonstantin Belousov 	if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
9745b999a6bSDavide Italiano 		sbt = tick_sbt;
975a9e182e8SKonstantin Belousov 	if ((flags & C_HARDCLOCK) != 0 ||
9765b999a6bSDavide Italiano #ifdef NO_EVENTTIMERS
9775b999a6bSDavide Italiano 	    sbt >= sbt_timethreshold) {
978a115fb62SHans Petter Selasky 		to_sbt = getsbinuptime();
9795b999a6bSDavide Italiano 
9805b999a6bSDavide Italiano 		/* Add safety belt for the case of hz > 1000. */
981a115fb62SHans Petter Selasky 		to_sbt += tc_tick_sbt - tick_sbt;
9825b999a6bSDavide Italiano #else
9835b999a6bSDavide Italiano 	    sbt >= sbt_tickthreshold) {
9845b999a6bSDavide Italiano 		/*
9855b999a6bSDavide Italiano 		 * Obtain the time of the last hardclock() call on
9865b999a6bSDavide Italiano 		 * this CPU directly from the kern_clocksource.c.
9875b999a6bSDavide Italiano 		 * This value is per-CPU, but it is equal for all
9885b999a6bSDavide Italiano 		 * active ones.
9895b999a6bSDavide Italiano 		 */
9905b999a6bSDavide Italiano #ifdef __LP64__
991a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
9925b999a6bSDavide Italiano #else
9935b999a6bSDavide Italiano 		spinlock_enter();
994a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
9955b999a6bSDavide Italiano 		spinlock_exit();
9965b999a6bSDavide Italiano #endif
9975b999a6bSDavide Italiano #endif
9989f3aabb9SJohn Baldwin 		if (cold && to_sbt == 0)
9999f3aabb9SJohn Baldwin 			to_sbt = sbinuptime();
1000a115fb62SHans Petter Selasky 		if ((flags & C_HARDCLOCK) == 0)
1001a115fb62SHans Petter Selasky 			to_sbt += tick_sbt;
10025b999a6bSDavide Italiano 	} else
1003a115fb62SHans Petter Selasky 		to_sbt = sbinuptime();
1004a115fb62SHans Petter Selasky 	if (SBT_MAX - to_sbt < sbt)
1005a115fb62SHans Petter Selasky 		to_sbt = SBT_MAX;
10061b0c144fSDavide Italiano 	else
1007a115fb62SHans Petter Selasky 		to_sbt += sbt;
1008a9e182e8SKonstantin Belousov 	*res = to_sbt;
1009a9e182e8SKonstantin Belousov 	to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
1010a115fb62SHans Petter Selasky 	    sbt >> C_PRELGET(flags));
1011a9e182e8SKonstantin Belousov 	*prec_res = to_pr > precision ? to_pr : precision;
1012a115fb62SHans Petter Selasky }
1013a9e182e8SKonstantin Belousov 
1014a9e182e8SKonstantin Belousov /*
1015a9e182e8SKonstantin Belousov  * New interface; clients allocate their own callout structures.
1016a9e182e8SKonstantin Belousov  *
1017a9e182e8SKonstantin Belousov  * callout_reset() - establish or change a timeout
1018a9e182e8SKonstantin Belousov  * callout_stop() - disestablish a timeout
1019a9e182e8SKonstantin Belousov  * callout_init() - initialize a callout structure so that it can
1020a9e182e8SKonstantin Belousov  *	safely be passed to callout_reset() and callout_stop()
1021a9e182e8SKonstantin Belousov  *
1022a9e182e8SKonstantin Belousov  * <sys/callout.h> defines three convenience macros:
1023a9e182e8SKonstantin Belousov  *
1024a9e182e8SKonstantin Belousov  * callout_active() - returns truth if callout has not been stopped,
1025a9e182e8SKonstantin Belousov  *	drained, or deactivated since the last time the callout was
1026a9e182e8SKonstantin Belousov  *	reset.
1027a9e182e8SKonstantin Belousov  * callout_pending() - returns truth if callout is still waiting for timeout
1028a9e182e8SKonstantin Belousov  * callout_deactivate() - marks the callout as having been serviced
1029a9e182e8SKonstantin Belousov  */
1030a9e182e8SKonstantin Belousov int
1031a9e182e8SKonstantin Belousov callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
1032*a8a03706SJohn Baldwin     callout_func_t *ftn, void *arg, int cpu, int flags)
1033a9e182e8SKonstantin Belousov {
1034a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, precision;
1035a9e182e8SKonstantin Belousov 	struct callout_cpu *cc;
1036a9e182e8SKonstantin Belousov 	int cancelled, direct;
1037a9e182e8SKonstantin Belousov 	int ignore_cpu=0;
1038a9e182e8SKonstantin Belousov 
1039a9e182e8SKonstantin Belousov 	cancelled = 0;
1040a9e182e8SKonstantin Belousov 	if (cpu == -1) {
1041a9e182e8SKonstantin Belousov 		ignore_cpu = 1;
1042a9e182e8SKonstantin Belousov 	} else if ((cpu >= MAXCPU) ||
1043a9e182e8SKonstantin Belousov 		   ((CC_CPU(cpu))->cc_inited == 0)) {
1044a9e182e8SKonstantin Belousov 		/* Invalid CPU spec */
1045a9e182e8SKonstantin Belousov 		panic("Invalid CPU in callout %d", cpu);
1046a9e182e8SKonstantin Belousov 	}
1047a9e182e8SKonstantin Belousov 	callout_when(sbt, prec, flags, &to_sbt, &precision);
1048a9e182e8SKonstantin Belousov 
1049a115fb62SHans Petter Selasky 	/*
105066525b2dSRandall Stewart 	 * This flag used to be added by callout_cc_add, but the
105166525b2dSRandall Stewart 	 * first time you call this we could end up with the
105266525b2dSRandall Stewart 	 * wrong direct flag if we don't do it before we add.
105366525b2dSRandall Stewart 	 */
105466525b2dSRandall Stewart 	if (flags & C_DIRECT_EXEC) {
105515b1eb14SRandall Stewart 		direct = 1;
105615b1eb14SRandall Stewart 	} else {
105715b1eb14SRandall Stewart 		direct = 0;
105866525b2dSRandall Stewart 	}
1059a115fb62SHans Petter Selasky 	KASSERT(!direct || c->c_lock == NULL,
1060a115fb62SHans Petter Selasky 	    ("%s: direct callout %p has lock", __func__, c));
1061a115fb62SHans Petter Selasky 	cc = callout_lock(c);
106215b1eb14SRandall Stewart 	/*
106315b1eb14SRandall Stewart 	 * Don't allow migration of pre-allocated callouts lest they
106415b1eb14SRandall Stewart 	 * become unbalanced or handle the case where the user does
106515b1eb14SRandall Stewart 	 * not care.
106615b1eb14SRandall Stewart 	 */
106715b1eb14SRandall Stewart 	if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) ||
106815b1eb14SRandall Stewart 	    ignore_cpu) {
106915b1eb14SRandall Stewart 		cpu = c->c_cpu;
107015b1eb14SRandall Stewart 	}
107115b1eb14SRandall Stewart 
1072d2854fa4SRandall Stewart 	if (cc_exec_curr(cc, direct) == c) {
1073a115fb62SHans Petter Selasky 		/*
1074a115fb62SHans Petter Selasky 		 * We're being asked to reschedule a callout which is
1075a115fb62SHans Petter Selasky 		 * currently in progress.  If there is a lock then we
1076a115fb62SHans Petter Selasky 		 * can cancel the callout if it has not really started.
1077a115fb62SHans Petter Selasky 		 */
1078378d5c6cSAndriy Gapon 		if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
1079d2854fa4SRandall Stewart 			cancelled = cc_exec_cancel(cc, direct) = true;
1080dc4ee9a8SGleb Smirnoff 		if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
1081a115fb62SHans Petter Selasky 			/*
1082a115fb62SHans Petter Selasky 			 * Someone has called callout_drain to kill this
1083a115fb62SHans Petter Selasky 			 * callout.  Don't reschedule.
1084a115fb62SHans Petter Selasky 			 */
1085a115fb62SHans Petter Selasky 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1086a115fb62SHans Petter Selasky 			    cancelled ? "cancelled" : "failed to cancel",
1087a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1088a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1089a115fb62SHans Petter Selasky 			return (cancelled);
1090a115fb62SHans Petter Selasky 		}
1091d2854fa4SRandall Stewart #ifdef SMP
1092d2854fa4SRandall Stewart 		if (callout_migrating(c)) {
1093d2854fa4SRandall Stewart 			/*
1094d2854fa4SRandall Stewart 			 * This only occurs when a second callout_reset_sbt_on
1095d2854fa4SRandall Stewart 			 * is made after a previous one moved it into
1096d2854fa4SRandall Stewart 			 * deferred migration (below). Note we do *not* change
1097d2854fa4SRandall Stewart 			 * the prev_cpu even though the previous target may
1098d2854fa4SRandall Stewart 			 * be different.
1099d2854fa4SRandall Stewart 			 */
1100d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1101d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1102d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1103d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1104d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
1105d2854fa4SRandall Stewart 			cancelled = 1;
1106d2854fa4SRandall Stewart 			CC_UNLOCK(cc);
1107d2854fa4SRandall Stewart 			return (cancelled);
1108d2854fa4SRandall Stewart 		}
1109d2854fa4SRandall Stewart #endif
1110a115fb62SHans Petter Selasky 	}
111115b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_PENDING) {
111215b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
111366525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
111466525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1115a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
111615b1eb14SRandall Stewart 		} else {
1117a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
111815b1eb14SRandall Stewart 		}
1119a115fb62SHans Petter Selasky 		cancelled = 1;
112015b1eb14SRandall Stewart 		c->c_iflags &= ~ CALLOUT_PENDING;
112115b1eb14SRandall Stewart 		c->c_flags &= ~ CALLOUT_ACTIVE;
11228d809d50SJeff Roberson 	}
11231283e9cdSAttilio Rao 
1124a115fb62SHans Petter Selasky #ifdef SMP
1125a115fb62SHans Petter Selasky 	/*
1126a115fb62SHans Petter Selasky 	 * If the callout must migrate try to perform it immediately.
1127a115fb62SHans Petter Selasky 	 * If the callout is currently running, just defer the migration
1128a115fb62SHans Petter Selasky 	 * to a more appropriate moment.
1129a115fb62SHans Petter Selasky 	 */
1130a115fb62SHans Petter Selasky 	if (c->c_cpu != cpu) {
1131d2854fa4SRandall Stewart 		if (cc_exec_curr(cc, direct) == c) {
1132d2854fa4SRandall Stewart 			/*
1133d2854fa4SRandall Stewart 			 * Pending will have been removed since we are
1134d2854fa4SRandall Stewart 			 * actually executing the callout on another
1135d2854fa4SRandall Stewart 			 * CPU. That callout should be waiting on the
1136d2854fa4SRandall Stewart 			 * lock the caller holds. If we set both
1137d2854fa4SRandall Stewart 			 * active/and/pending after we return and the
1138d2854fa4SRandall Stewart 			 * lock on the executing callout proceeds, it
1139d2854fa4SRandall Stewart 			 * will then see pending is true and return.
1140d2854fa4SRandall Stewart 			 * At the return from the actual callout execution
1141d2854fa4SRandall Stewart 			 * the migration will occur in softclock_call_cc
1142d2854fa4SRandall Stewart 			 * and this new callout will be placed on the
1143d2854fa4SRandall Stewart 			 * new CPU via a call to callout_cpu_switch() which
1144d2854fa4SRandall Stewart 			 * will get the lock on the right CPU followed
1145d2854fa4SRandall Stewart 			 * by a call callout_cc_add() which will add it there.
1146d2854fa4SRandall Stewart 			 * (see above in softclock_call_cc()).
1147d2854fa4SRandall Stewart 			 */
1148d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1149d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1150d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1151d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1152d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
115315b1eb14SRandall Stewart 			c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
115415b1eb14SRandall Stewart 			c->c_flags |= CALLOUT_ACTIVE;
1155a115fb62SHans Petter Selasky 			CTR6(KTR_CALLOUT,
1156a115fb62SHans Petter Selasky 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1157a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1158a115fb62SHans Petter Selasky 			    (u_int)(to_sbt & 0xffffffff), cpu);
1159a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1160a115fb62SHans Petter Selasky 			return (cancelled);
1161a115fb62SHans Petter Selasky 		}
1162a115fb62SHans Petter Selasky 		cc = callout_cpu_switch(c, cc, cpu);
1163a115fb62SHans Petter Selasky 	}
1164a115fb62SHans Petter Selasky #endif
1165a115fb62SHans Petter Selasky 
116666525b2dSRandall Stewart 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1167a115fb62SHans Petter Selasky 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1168a115fb62SHans Petter Selasky 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1169a115fb62SHans Petter Selasky 	    (u_int)(to_sbt & 0xffffffff));
1170a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
1171a115fb62SHans Petter Selasky 
1172a115fb62SHans Petter Selasky 	return (cancelled);
1173acc8326dSGarrett Wollman }
1174acc8326dSGarrett Wollman 
11756e0186d5SSam Leffler /*
11766e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
11776e0186d5SSam Leffler  */
11786e0186d5SSam Leffler int
11796e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
11806e0186d5SSam Leffler {
11816e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
11826e0186d5SSam Leffler }
11836e0186d5SSam Leffler 
11846e0186d5SSam Leffler int
11856e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
11866e0186d5SSam Leffler {
11876e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
11886e0186d5SSam Leffler }
11896e0186d5SSam Leffler 
11902c1bb207SColin Percival int
1191*a8a03706SJohn Baldwin _callout_stop_safe(struct callout *c, int flags, callout_func_t *drain)
11922c1bb207SColin Percival {
1193a115fb62SHans Petter Selasky 	struct callout_cpu *cc, *old_cc;
1194a115fb62SHans Petter Selasky 	struct lock_class *class;
1195a115fb62SHans Petter Selasky 	int direct, sq_locked, use_lock;
119647e42809SGleb Smirnoff 	int cancelled, not_on_a_list;
11971283e9cdSAttilio Rao 
11985db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) != 0)
11999500dd9fSAdrian Chadd 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
12009500dd9fSAdrian Chadd 		    "calling %s", __func__);
12019500dd9fSAdrian Chadd 
12021283e9cdSAttilio Rao 	/*
1203a115fb62SHans Petter Selasky 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1204a115fb62SHans Petter Selasky 	 * so just discard this check for the moment.
12051283e9cdSAttilio Rao 	 */
12065db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1207a115fb62SHans Petter Selasky 		if (c->c_lock == &Giant.lock_object)
1208a115fb62SHans Petter Selasky 			use_lock = mtx_owned(&Giant);
1209a115fb62SHans Petter Selasky 		else {
1210a115fb62SHans Petter Selasky 			use_lock = 1;
1211a115fb62SHans Petter Selasky 			class = LOCK_CLASS(c->c_lock);
1212a115fb62SHans Petter Selasky 			class->lc_assert(c->c_lock, LA_XLOCKED);
12131283e9cdSAttilio Rao 		}
1214a115fb62SHans Petter Selasky 	} else
1215a115fb62SHans Petter Selasky 		use_lock = 0;
121615b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_DIRECT) {
121715b1eb14SRandall Stewart 		direct = 1;
121815b1eb14SRandall Stewart 	} else {
121915b1eb14SRandall Stewart 		direct = 0;
122015b1eb14SRandall Stewart 	}
1221a115fb62SHans Petter Selasky 	sq_locked = 0;
1222a115fb62SHans Petter Selasky 	old_cc = NULL;
1223a115fb62SHans Petter Selasky again:
1224a115fb62SHans Petter Selasky 	cc = callout_lock(c);
1225a115fb62SHans Petter Selasky 
122615b1eb14SRandall Stewart 	if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
122715b1eb14SRandall Stewart 	    (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
122815b1eb14SRandall Stewart 	    ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1229d2854fa4SRandall Stewart 		/*
1230d2854fa4SRandall Stewart 		 * Special case where this slipped in while we
1231d2854fa4SRandall Stewart 		 * were migrating *as* the callout is about to
1232d2854fa4SRandall Stewart 		 * execute. The caller probably holds the lock
1233d2854fa4SRandall Stewart 		 * the callout wants.
1234d2854fa4SRandall Stewart 		 *
1235d2854fa4SRandall Stewart 		 * Get rid of the migration first. Then set
1236d2854fa4SRandall Stewart 		 * the flag that tells this code *not* to
1237d2854fa4SRandall Stewart 		 * try to remove it from any lists (its not
1238d2854fa4SRandall Stewart 		 * on one yet). When the callout wheel runs,
1239d2854fa4SRandall Stewart 		 * it will ignore this callout.
1240d2854fa4SRandall Stewart 		 */
124115b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_PENDING;
124215b1eb14SRandall Stewart 		c->c_flags &= ~CALLOUT_ACTIVE;
1243d2854fa4SRandall Stewart 		not_on_a_list = 1;
1244d2854fa4SRandall Stewart 	} else {
1245d2854fa4SRandall Stewart 		not_on_a_list = 0;
1246d2854fa4SRandall Stewart 	}
1247d2854fa4SRandall Stewart 
1248a115fb62SHans Petter Selasky 	/*
1249a115fb62SHans Petter Selasky 	 * If the callout was migrating while the callout cpu lock was
1250a115fb62SHans Petter Selasky 	 * dropped,  just drop the sleepqueue lock and check the states
1251a115fb62SHans Petter Selasky 	 * again.
1252a115fb62SHans Petter Selasky 	 */
1253a115fb62SHans Petter Selasky 	if (sq_locked != 0 && cc != old_cc) {
1254a115fb62SHans Petter Selasky #ifdef SMP
1255a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
1256d2854fa4SRandall Stewart 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1257a115fb62SHans Petter Selasky 		sq_locked = 0;
1258a115fb62SHans Petter Selasky 		old_cc = NULL;
1259a115fb62SHans Petter Selasky 		goto again;
1260a115fb62SHans Petter Selasky #else
1261a115fb62SHans Petter Selasky 		panic("migration should not happen");
1262a115fb62SHans Petter Selasky #endif
1263a115fb62SHans Petter Selasky 	}
126447e42809SGleb Smirnoff 
1265a115fb62SHans Petter Selasky 	/*
126647e42809SGleb Smirnoff 	 * If the callout is running, try to stop it or drain it.
1267a115fb62SHans Petter Selasky 	 */
126847e42809SGleb Smirnoff 	if (cc_exec_curr(cc, direct) == c) {
1269a115fb62SHans Petter Selasky 		/*
127047e42809SGleb Smirnoff 		 * Succeed we to stop it or not, we must clear the
12717d88be4cSMark Johnston 		 * active flag - this is what API users expect.  If we're
12727d88be4cSMark Johnston 		 * draining and the callout is currently executing, first wait
12737d88be4cSMark Johnston 		 * until it finishes.
1274a115fb62SHans Petter Selasky 		 */
12757d88be4cSMark Johnston 		if ((flags & CS_DRAIN) == 0)
127618b4fd62SRandall Stewart 			c->c_flags &= ~CALLOUT_ACTIVE;
127747e42809SGleb Smirnoff 
12785db9ed80SKonstantin Belousov 		if ((flags & CS_DRAIN) != 0) {
1279a115fb62SHans Petter Selasky 			/*
1280a115fb62SHans Petter Selasky 			 * The current callout is running (or just
1281a115fb62SHans Petter Selasky 			 * about to run) and blocking is allowed, so
1282a115fb62SHans Petter Selasky 			 * just wait for the current invocation to
1283a115fb62SHans Petter Selasky 			 * finish.
1284a115fb62SHans Petter Selasky 			 */
1285d2854fa4SRandall Stewart 			while (cc_exec_curr(cc, direct) == c) {
1286a115fb62SHans Petter Selasky 				/*
1287a115fb62SHans Petter Selasky 				 * Use direct calls to sleepqueue interface
1288a115fb62SHans Petter Selasky 				 * instead of cv/msleep in order to avoid
1289a115fb62SHans Petter Selasky 				 * a LOR between cc_lock and sleepqueue
1290a115fb62SHans Petter Selasky 				 * chain spinlocks.  This piece of code
1291a115fb62SHans Petter Selasky 				 * emulates a msleep_spin() call actually.
1292a115fb62SHans Petter Selasky 				 *
1293a115fb62SHans Petter Selasky 				 * If we already have the sleepqueue chain
1294a115fb62SHans Petter Selasky 				 * locked, then we can safely block.  If we
1295a115fb62SHans Petter Selasky 				 * don't already have it locked, however,
1296a115fb62SHans Petter Selasky 				 * we have to drop the cc_lock to lock
1297a115fb62SHans Petter Selasky 				 * it.  This opens several races, so we
1298a115fb62SHans Petter Selasky 				 * restart at the beginning once we have
1299a115fb62SHans Petter Selasky 				 * both locks.  If nothing has changed, then
1300a115fb62SHans Petter Selasky 				 * we will end up back here with sq_locked
1301a115fb62SHans Petter Selasky 				 * set.
1302a115fb62SHans Petter Selasky 				 */
1303a115fb62SHans Petter Selasky 				if (!sq_locked) {
1304a115fb62SHans Petter Selasky 					CC_UNLOCK(cc);
1305a115fb62SHans Petter Selasky 					sleepq_lock(
1306d2854fa4SRandall Stewart 					    &cc_exec_waiting(cc, direct));
1307a115fb62SHans Petter Selasky 					sq_locked = 1;
1308a115fb62SHans Petter Selasky 					old_cc = cc;
1309a115fb62SHans Petter Selasky 					goto again;
1310a115fb62SHans Petter Selasky 				}
131147e42809SGleb Smirnoff 
1312a115fb62SHans Petter Selasky 				/*
1313a115fb62SHans Petter Selasky 				 * Migration could be cancelled here, but
1314a115fb62SHans Petter Selasky 				 * as long as it is still not sure when it
1315a115fb62SHans Petter Selasky 				 * will be packed up, just let softclock()
1316a115fb62SHans Petter Selasky 				 * take care of it.
1317a115fb62SHans Petter Selasky 				 */
1318d2854fa4SRandall Stewart 				cc_exec_waiting(cc, direct) = true;
1319a115fb62SHans Petter Selasky 				DROP_GIANT();
1320a115fb62SHans Petter Selasky 				CC_UNLOCK(cc);
1321a115fb62SHans Petter Selasky 				sleepq_add(
1322d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1323a115fb62SHans Petter Selasky 				    &cc->cc_lock.lock_object, "codrain",
1324a115fb62SHans Petter Selasky 				    SLEEPQ_SLEEP, 0);
1325a115fb62SHans Petter Selasky 				sleepq_wait(
1326d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1327a115fb62SHans Petter Selasky 					     0);
1328a115fb62SHans Petter Selasky 				sq_locked = 0;
1329a115fb62SHans Petter Selasky 				old_cc = NULL;
1330a115fb62SHans Petter Selasky 
1331a115fb62SHans Petter Selasky 				/* Reacquire locks previously released. */
1332a115fb62SHans Petter Selasky 				PICKUP_GIANT();
1333a115fb62SHans Petter Selasky 				CC_LOCK(cc);
1334a115fb62SHans Petter Selasky 			}
13357d88be4cSMark Johnston 			c->c_flags &= ~CALLOUT_ACTIVE;
1336a115fb62SHans Petter Selasky 		} else if (use_lock &&
133718b4fd62SRandall Stewart 			   !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1338d2854fa4SRandall Stewart 
1339a115fb62SHans Petter Selasky 			/*
1340a115fb62SHans Petter Selasky 			 * The current callout is waiting for its
1341a115fb62SHans Petter Selasky 			 * lock which we hold.  Cancel the callout
1342a115fb62SHans Petter Selasky 			 * and return.  After our caller drops the
1343a115fb62SHans Petter Selasky 			 * lock, the callout will be skipped in
134418b4fd62SRandall Stewart 			 * softclock(). This *only* works with a
134518b4fd62SRandall Stewart 			 * callout_stop() *not* callout_drain() or
134618b4fd62SRandall Stewart 			 * callout_async_drain().
1347a115fb62SHans Petter Selasky 			 */
1348d2854fa4SRandall Stewart 			cc_exec_cancel(cc, direct) = true;
1349a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1350a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1351a115fb62SHans Petter Selasky 			KASSERT(!cc_cce_migrating(cc, direct),
1352a115fb62SHans Petter Selasky 			    ("callout wrongly scheduled for migration"));
135315b1eb14SRandall Stewart 			if (callout_migrating(c)) {
135415b1eb14SRandall Stewart 				c->c_iflags &= ~CALLOUT_DFRMIGRATION;
135515b1eb14SRandall Stewart #ifdef SMP
135615b1eb14SRandall Stewart 				cc_migration_cpu(cc, direct) = CPUBLOCK;
135715b1eb14SRandall Stewart 				cc_migration_time(cc, direct) = 0;
135815b1eb14SRandall Stewart 				cc_migration_prec(cc, direct) = 0;
135915b1eb14SRandall Stewart 				cc_migration_func(cc, direct) = NULL;
136015b1eb14SRandall Stewart 				cc_migration_arg(cc, direct) = NULL;
136115b1eb14SRandall Stewart #endif
136215b1eb14SRandall Stewart 			}
1363a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1364a115fb62SHans Petter Selasky 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1365a115fb62SHans Petter Selasky 			return (1);
1366d2854fa4SRandall Stewart 		} else if (callout_migrating(c)) {
1367d2854fa4SRandall Stewart 			/*
1368d2854fa4SRandall Stewart 			 * The callout is currently being serviced
1369d2854fa4SRandall Stewart 			 * and the "next" callout is scheduled at
1370d2854fa4SRandall Stewart 			 * its completion with a migration. We remove
1371d2854fa4SRandall Stewart 			 * the migration flag so it *won't* get rescheduled,
1372d2854fa4SRandall Stewart 			 * but we can't stop the one thats running so
1373d2854fa4SRandall Stewart 			 * we return 0.
1374d2854fa4SRandall Stewart 			 */
137515b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1376d2854fa4SRandall Stewart #ifdef SMP
1377d2854fa4SRandall Stewart 			/*
1378d2854fa4SRandall Stewart 			 * We can't call cc_cce_cleanup here since
1379d2854fa4SRandall Stewart 			 * if we do it will remove .ce_curr and
1380d2854fa4SRandall Stewart 			 * its still running. This will prevent a
1381d2854fa4SRandall Stewart 			 * reschedule of the callout when the
1382d2854fa4SRandall Stewart 			 * execution completes.
1383d2854fa4SRandall Stewart 			 */
1384d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1385d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = 0;
1386d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = 0;
1387d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = NULL;
1388d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = NULL;
1389d2854fa4SRandall Stewart #endif
1390a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1391a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
139218b4fd62SRandall Stewart  			if (drain) {
139318b4fd62SRandall Stewart 				cc_exec_drain(cc, direct) = drain;
139418b4fd62SRandall Stewart 			}
1395a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1396d153eeeeSGleb Smirnoff 			return ((flags & CS_EXECUTING) != 0);
1397a115fb62SHans Petter Selasky 		}
1398a115fb62SHans Petter Selasky 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1399a115fb62SHans Petter Selasky 		    c, c->c_func, c->c_arg);
140018b4fd62SRandall Stewart 		if (drain) {
140118b4fd62SRandall Stewart 			cc_exec_drain(cc, direct) = drain;
140218b4fd62SRandall Stewart 		}
14033d84a188SRandall Stewart 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
140447e42809SGleb Smirnoff 		cancelled = ((flags & CS_EXECUTING) != 0);
140547e42809SGleb Smirnoff 	} else
140647e42809SGleb Smirnoff 		cancelled = 1;
140747e42809SGleb Smirnoff 
14083d84a188SRandall Stewart 	if (sq_locked)
14093d84a188SRandall Stewart 		sleepq_release(&cc_exec_waiting(cc, direct));
1410d153eeeeSGleb Smirnoff 
141147e42809SGleb Smirnoff 	if ((c->c_iflags & CALLOUT_PENDING) == 0) {
141247e42809SGleb Smirnoff 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
141347e42809SGleb Smirnoff 		    c, c->c_func, c->c_arg);
14149f339124SGleb Smirnoff 		/*
14159f339124SGleb Smirnoff 		 * For not scheduled and not executing callout return
14169f339124SGleb Smirnoff 		 * negative value.
14179f339124SGleb Smirnoff 		 */
14189f339124SGleb Smirnoff 		if (cc_exec_curr(cc, direct) != c)
14199f339124SGleb Smirnoff 			cancelled = -1;
142047e42809SGleb Smirnoff 		CC_UNLOCK(cc);
14219f339124SGleb Smirnoff 		return (cancelled);
142247e42809SGleb Smirnoff 	}
142347e42809SGleb Smirnoff 
142415b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
142515b1eb14SRandall Stewart 	c->c_flags &= ~CALLOUT_ACTIVE;
14261283e9cdSAttilio Rao 
142768a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
142868a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
1429d2854fa4SRandall Stewart 	if (not_on_a_list == 0) {
143015b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
143166525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
143266525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1433a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
143415b1eb14SRandall Stewart 		} else {
1435a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1436d2854fa4SRandall Stewart 		}
143715b1eb14SRandall Stewart 	}
1438a115fb62SHans Petter Selasky 	callout_cc_del(c, cc);
1439a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
144047e42809SGleb Smirnoff 	return (cancelled);
1441acc8326dSGarrett Wollman }
1442acc8326dSGarrett Wollman 
1443acc8326dSGarrett Wollman void
1444e392e44cSDavide Italiano callout_init(struct callout *c, int mpsafe)
1445acc8326dSGarrett Wollman {
1446a115fb62SHans Petter Selasky 	bzero(c, sizeof *c);
144798c926b2SIan Dowse 	if (mpsafe) {
1448a115fb62SHans Petter Selasky 		c->c_lock = NULL;
144915b1eb14SRandall Stewart 		c->c_iflags = CALLOUT_RETURNUNLOCKED;
145098c926b2SIan Dowse 	} else {
1451a115fb62SHans Petter Selasky 		c->c_lock = &Giant.lock_object;
145215b1eb14SRandall Stewart 		c->c_iflags = 0;
145398c926b2SIan Dowse 	}
1454a115fb62SHans Petter Selasky 	c->c_cpu = timeout_cpu;
145598c926b2SIan Dowse }
145698c926b2SIan Dowse 
145798c926b2SIan Dowse void
1458e392e44cSDavide Italiano _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
145998c926b2SIan Dowse {
146098c926b2SIan Dowse 	bzero(c, sizeof *c);
146164b9ee20SAttilio Rao 	c->c_lock = lock;
1462a115fb62SHans Petter Selasky 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1463a115fb62SHans Petter Selasky 	    ("callout_init_lock: bad flags %d", flags));
1464a115fb62SHans Petter Selasky 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1465a115fb62SHans Petter Selasky 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1466a115fb62SHans Petter Selasky 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1467a115fb62SHans Petter Selasky 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1468a115fb62SHans Petter Selasky 	    __func__));
146915b1eb14SRandall Stewart 	c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
14708d809d50SJeff Roberson 	c->c_cpu = timeout_cpu;
1471acc8326dSGarrett Wollman }
1472acc8326dSGarrett Wollman 
1473e1d6dc65SNate Williams #ifdef APM_FIXUP_CALLTODO
1474e1d6dc65SNate Williams /*
1475e1d6dc65SNate Williams  * Adjust the kernel calltodo timeout list.  This routine is used after
1476e1d6dc65SNate Williams  * an APM resume to recalculate the calltodo timer list values with the
1477e1d6dc65SNate Williams  * number of hz's we have been sleeping.  The next hardclock() will detect
1478e1d6dc65SNate Williams  * that there are fired timers and run softclock() to execute them.
1479e1d6dc65SNate Williams  *
1480e1d6dc65SNate Williams  * Please note, I have not done an exhaustive analysis of what code this
1481e1d6dc65SNate Williams  * might break.  I am motivated to have my select()'s and alarm()'s that
1482e1d6dc65SNate Williams  * have expired during suspend firing upon resume so that the applications
1483e1d6dc65SNate Williams  * which set the timer can do the maintanence the timer was for as close
1484e1d6dc65SNate Williams  * as possible to the originally intended time.  Testing this code for a
1485e1d6dc65SNate Williams  * week showed that resuming from a suspend resulted in 22 to 25 timers
1486e3043798SPedro F. Giffuni  * firing, which seemed independent on whether the suspend was 2 hours or
1487e1d6dc65SNate Williams  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1488e1d6dc65SNate Williams  */
1489e1d6dc65SNate Williams void
1490e392e44cSDavide Italiano adjust_timeout_calltodo(struct timeval *time_change)
1491e1d6dc65SNate Williams {
14923e85b721SEd Maste 	struct callout *p;
1493e1d6dc65SNate Williams 	unsigned long delta_ticks;
1494e1d6dc65SNate Williams 
1495e1d6dc65SNate Williams 	/*
1496e1d6dc65SNate Williams 	 * How many ticks were we asleep?
1497c8b47828SBruce Evans 	 * (stolen from tvtohz()).
1498e1d6dc65SNate Williams 	 */
1499e1d6dc65SNate Williams 
1500e1d6dc65SNate Williams 	/* Don't do anything */
1501e1d6dc65SNate Williams 	if (time_change->tv_sec < 0)
1502e1d6dc65SNate Williams 		return;
1503e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
150455e0987aSPedro F. Giffuni 		delta_ticks = howmany(time_change->tv_sec * 1000000 +
150555e0987aSPedro F. Giffuni 		    time_change->tv_usec, tick) + 1;
1506e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / hz)
1507e1d6dc65SNate Williams 		delta_ticks = time_change->tv_sec * hz +
150855e0987aSPedro F. Giffuni 		    howmany(time_change->tv_usec, tick) + 1;
1509e1d6dc65SNate Williams 	else
1510e1d6dc65SNate Williams 		delta_ticks = LONG_MAX;
1511e1d6dc65SNate Williams 
1512e1d6dc65SNate Williams 	if (delta_ticks > INT_MAX)
1513e1d6dc65SNate Williams 		delta_ticks = INT_MAX;
1514e1d6dc65SNate Williams 
1515e1d6dc65SNate Williams 	/*
1516e1d6dc65SNate Williams 	 * Now rip through the timer calltodo list looking for timers
1517e1d6dc65SNate Williams 	 * to expire.
1518e1d6dc65SNate Williams 	 */
1519e1d6dc65SNate Williams 
1520e1d6dc65SNate Williams 	/* don't collide with softclock() */
15218d809d50SJeff Roberson 	CC_LOCK(cc);
1522e1d6dc65SNate Williams 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1523e1d6dc65SNate Williams 		p->c_time -= delta_ticks;
1524e1d6dc65SNate Williams 
1525e1d6dc65SNate Williams 		/* Break if the timer had more time on it than delta_ticks */
1526e1d6dc65SNate Williams 		if (p->c_time > 0)
1527e1d6dc65SNate Williams 			break;
1528e1d6dc65SNate Williams 
1529e1d6dc65SNate Williams 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1530e1d6dc65SNate Williams 		delta_ticks = -p->c_time;
1531e1d6dc65SNate Williams 	}
15328d809d50SJeff Roberson 	CC_UNLOCK(cc);
1533e1d6dc65SNate Williams 
1534e1d6dc65SNate Williams 	return;
1535e1d6dc65SNate Williams }
1536e1d6dc65SNate Williams #endif /* APM_FIXUP_CALLTODO */
15375b999a6bSDavide Italiano 
15385b999a6bSDavide Italiano static int
15395b999a6bSDavide Italiano flssbt(sbintime_t sbt)
15405b999a6bSDavide Italiano {
15415b999a6bSDavide Italiano 
15425b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
15435b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
15445b999a6bSDavide Italiano 		return (flsl(sbt));
15455b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
15465b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
15475b999a6bSDavide Italiano 	return (flsl(sbt));
15485b999a6bSDavide Italiano }
15495b999a6bSDavide Italiano 
15505b999a6bSDavide Italiano /*
15515b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
15525b999a6bSDavide Italiano  */
15535b999a6bSDavide Italiano static int
15545b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
15555b999a6bSDavide Italiano {
15565b999a6bSDavide Italiano 	struct callout *tmp;
15575b999a6bSDavide Italiano 	struct callout_cpu *cc;
15585b999a6bSDavide Italiano 	struct callout_list *sc;
15595b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
15605b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
15615b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
15625b999a6bSDavide Italiano #ifdef SMP
15635b999a6bSDavide Italiano 	int cpu;
15645b999a6bSDavide Italiano #endif
15655b999a6bSDavide Italiano 
15665b999a6bSDavide Italiano 	val = 0;
15675b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
15685b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
15695b999a6bSDavide Italiano 		return (error);
15705b999a6bSDavide Italiano 	count = maxc = 0;
15715b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
15725b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
15735b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
15745b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
15755b999a6bSDavide Italiano 	now = sbinuptime();
15765b999a6bSDavide Italiano #ifdef SMP
15775b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
15785b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
15795b999a6bSDavide Italiano #else
15805b999a6bSDavide Italiano 		cc = CC_CPU(timeout_cpu);
15815b999a6bSDavide Italiano #endif
15825b999a6bSDavide Italiano 		CC_LOCK(cc);
15835b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
15845b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
15855b999a6bSDavide Italiano 			c = 0;
15865b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
15875b999a6bSDavide Italiano 				c++;
15885b999a6bSDavide Italiano 				t = tmp->c_time - now;
15895b999a6bSDavide Italiano 				if (t < 0)
15905b999a6bSDavide Italiano 					t = 0;
15915b999a6bSDavide Italiano 				st += t / SBT_1US;
15925b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
15935b999a6bSDavide Italiano 				if (t > maxt)
15945b999a6bSDavide Italiano 					maxt = t;
15955b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
15965b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
15975b999a6bSDavide Italiano 				ct[flssbt(t)]++;
15985b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
15995b999a6bSDavide Italiano 			}
16005b999a6bSDavide Italiano 			if (c > maxc)
16015b999a6bSDavide Italiano 				maxc = c;
16025b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
16035b999a6bSDavide Italiano 			count += c;
16045b999a6bSDavide Italiano 		}
16055b999a6bSDavide Italiano 		CC_UNLOCK(cc);
16065b999a6bSDavide Italiano #ifdef SMP
16075b999a6bSDavide Italiano 	}
16085b999a6bSDavide Italiano #endif
16095b999a6bSDavide Italiano 
16105b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
16115b999a6bSDavide Italiano 		tcum += ct[i];
16125b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
16135b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
16145b999a6bSDavide Italiano 		pcum += cpr[i];
16155b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
16165b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
16175b999a6bSDavide Italiano 		c += ccpbk[i];
16185b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
16195b999a6bSDavide Italiano 
16205b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
16215b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
16225b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
16235b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
16245b999a6bSDavide Italiano 	    medc,
16255b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
16265b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
16275b999a6bSDavide Italiano 	    maxc);
16285b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
16295b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
16305b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
16315b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
16325b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
16335b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
16345b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
16355b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
16365b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
16375b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
16385b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
16395b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
16405b999a6bSDavide Italiano 			continue;
16415b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
16425b999a6bSDavide Italiano 		tcum += ct[i];
16435b999a6bSDavide Italiano 		pcum += cpr[i];
16445b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
16455b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
16465b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
16475b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
16485b999a6bSDavide Italiano 	}
16495b999a6bSDavide Italiano 	return (error);
16505b999a6bSDavide Italiano }
16515b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
16525b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
16535b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
16545b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
165547e42809SGleb Smirnoff 
16563af72c11SBjoern A. Zeeb #ifdef DDB
16573af72c11SBjoern A. Zeeb static void
16583af72c11SBjoern A. Zeeb _show_callout(struct callout *c)
16593af72c11SBjoern A. Zeeb {
16603af72c11SBjoern A. Zeeb 
16613af72c11SBjoern A. Zeeb 	db_printf("callout %p\n", c);
16623af72c11SBjoern A. Zeeb #define	C_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, c->e);
16633af72c11SBjoern A. Zeeb 	db_printf("   &c_links = %p\n", &(c->c_links));
16643af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_time);
16653af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_precision);
16663af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_arg);
16673af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_func);
16683af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_lock);
16693af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_flags);
16703af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_iflags);
16713af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%d",	c_cpu);
16723af72c11SBjoern A. Zeeb #undef	C_DB_PRINTF
16733af72c11SBjoern A. Zeeb }
16743af72c11SBjoern A. Zeeb 
16753af72c11SBjoern A. Zeeb DB_SHOW_COMMAND(callout, db_show_callout)
16763af72c11SBjoern A. Zeeb {
16773af72c11SBjoern A. Zeeb 
16783af72c11SBjoern A. Zeeb 	if (!have_addr) {
16793af72c11SBjoern A. Zeeb 		db_printf("usage: show callout <struct callout *>\n");
16803af72c11SBjoern A. Zeeb 		return;
16813af72c11SBjoern A. Zeeb 	}
16823af72c11SBjoern A. Zeeb 
16833af72c11SBjoern A. Zeeb 	_show_callout((struct callout *)addr);
16843af72c11SBjoern A. Zeeb }
16858c5a9161SEric van Gyzen 
16868c5a9161SEric van Gyzen static void
16878c5a9161SEric van Gyzen _show_last_callout(int cpu, int direct, const char *dirstr)
16888c5a9161SEric van Gyzen {
16898c5a9161SEric van Gyzen 	struct callout_cpu *cc;
16908c5a9161SEric van Gyzen 	void *func, *arg;
16918c5a9161SEric van Gyzen 
16928c5a9161SEric van Gyzen 	cc = CC_CPU(cpu);
16938c5a9161SEric van Gyzen 	func = cc_exec_last_func(cc, direct);
16948c5a9161SEric van Gyzen 	arg = cc_exec_last_arg(cc, direct);
16958c5a9161SEric van Gyzen 	db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
16968c5a9161SEric van Gyzen 	db_printsym((db_expr_t)func, DB_STGY_ANY);
16978c5a9161SEric van Gyzen 	db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
16988c5a9161SEric van Gyzen }
16998c5a9161SEric van Gyzen 
17008c5a9161SEric van Gyzen DB_SHOW_COMMAND(callout_last, db_show_callout_last)
17018c5a9161SEric van Gyzen {
17028c5a9161SEric van Gyzen 	int cpu, last;
17038c5a9161SEric van Gyzen 
17048c5a9161SEric van Gyzen 	if (have_addr) {
17058c5a9161SEric van Gyzen 		if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
17068c5a9161SEric van Gyzen 			db_printf("no such cpu: %d\n", (int)addr);
17078c5a9161SEric van Gyzen 			return;
17088c5a9161SEric van Gyzen 		}
17098c5a9161SEric van Gyzen 		cpu = last = addr;
17108c5a9161SEric van Gyzen 	} else {
17118c5a9161SEric van Gyzen 		cpu = 0;
17128c5a9161SEric van Gyzen 		last = mp_maxid;
17138c5a9161SEric van Gyzen 	}
17148c5a9161SEric van Gyzen 
17158c5a9161SEric van Gyzen 	while (cpu <= last) {
17168c5a9161SEric van Gyzen 		if (!CPU_ABSENT(cpu)) {
17178c5a9161SEric van Gyzen 			_show_last_callout(cpu, 0, "");
17188c5a9161SEric van Gyzen 			_show_last_callout(cpu, 1, " direct");
17198c5a9161SEric van Gyzen 		}
17208c5a9161SEric van Gyzen 		cpu++;
17218c5a9161SEric van Gyzen 	}
17228c5a9161SEric van Gyzen }
17233af72c11SBjoern A. Zeeb #endif /* DDB */
1724