xref: /freebsd/sys/kern/kern_timeout.c (revision a879e40ca2a9e95b3e3dc4810127d3cf105ec0d3)
1df8bae1dSRodney W. Grimes /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1991, 1993
5df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
6df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
7df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
8df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
9df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
11df8bae1dSRodney W. Grimes  *
12df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
13df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
14df8bae1dSRodney W. Grimes  * are met:
15df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
17df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
18df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
19df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
2069a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
21df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
22df8bae1dSRodney W. Grimes  *    without specific prior written permission.
23df8bae1dSRodney W. Grimes  *
24df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
35df8bae1dSRodney W. Grimes  *
36acc8326dSGarrett Wollman  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
37df8bae1dSRodney W. Grimes  */
38df8bae1dSRodney W. Grimes 
39677b542eSDavid E. O'Brien #include <sys/cdefs.h>
40677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
41677b542eSDavid E. O'Brien 
425b999a6bSDavide Italiano #include "opt_callout_profiling.h"
433af72c11SBjoern A. Zeeb #include "opt_ddb.h"
44c445c3c7SAdrian Chadd #include "opt_rss.h"
4591dd9aaeSRobert Watson 
46df8bae1dSRodney W. Grimes #include <sys/param.h>
47df8bae1dSRodney W. Grimes #include <sys/systm.h>
488d809d50SJeff Roberson #include <sys/bus.h>
4915b7a470SPoul-Henning Kamp #include <sys/callout.h>
5036d151a2SAlexander Motin #include <sys/domainset.h>
51f8ccf82aSAndre Oppermann #include <sys/file.h>
528d809d50SJeff Roberson #include <sys/interrupt.h>
53df8bae1dSRodney W. Grimes #include <sys/kernel.h>
54ff7ec58aSRobert Watson #include <sys/ktr.h>
5574cf7caeSJohn Baldwin #include <sys/kthread.h>
56f34fa851SJohn Baldwin #include <sys/lock.h>
578d809d50SJeff Roberson #include <sys/malloc.h>
58cb799bfeSJohn Baldwin #include <sys/mutex.h>
5921f9e816SJohn Baldwin #include <sys/proc.h>
60642701abSKyle Evans #include <sys/random.h>
6174cf7caeSJohn Baldwin #include <sys/sched.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>
6674cf7caeSJohn Baldwin #include <sys/unistd.h>
67df8bae1dSRodney W. Grimes 
683af72c11SBjoern A. Zeeb #ifdef DDB
693af72c11SBjoern A. Zeeb #include <ddb/ddb.h>
708c5a9161SEric van Gyzen #include <ddb/db_sym.h>
713af72c11SBjoern A. Zeeb #include <machine/_inttypes.h>
723af72c11SBjoern A. Zeeb #endif
733af72c11SBjoern A. Zeeb 
741283e9cdSAttilio Rao #ifdef SMP
751283e9cdSAttilio Rao #include <machine/cpu.h>
761283e9cdSAttilio Rao #endif
771283e9cdSAttilio Rao 
785b999a6bSDavide Italiano DPCPU_DECLARE(sbintime_t, hardclocktime);
795b999a6bSDavide Italiano 
8091dd9aaeSRobert Watson SDT_PROVIDER_DEFINE(callout_execute);
8136160958SMark Johnston SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
8236160958SMark Johnston SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
8391dd9aaeSRobert Watson 
8474cf7caeSJohn Baldwin static void	softclock_thread(void *arg);
8574cf7caeSJohn Baldwin 
865b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8722ee8c4fSPoul-Henning Kamp static int avg_depth;
8822ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8922ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
9022ee8c4fSPoul-Henning Kamp static int avg_gcalls;
9122ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
9222ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
9364b9ee20SAttilio Rao static int avg_lockcalls;
9464b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
9564b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
9622ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
9722ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
9822ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
995b999a6bSDavide Italiano static int avg_depth_dir;
1005b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
1015b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
1025b999a6bSDavide Italiano     "Units = 1/1000");
1035b999a6bSDavide Italiano static int avg_lockcalls_dir;
1045b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
1055b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
1065b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
1075b999a6bSDavide Italiano static int avg_mpcalls_dir;
1085b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1095b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1105b999a6bSDavide Italiano     "Units = 1/1000");
1115b999a6bSDavide Italiano #endif
112f8ccf82aSAndre Oppermann 
113f8ccf82aSAndre Oppermann static int ncallout;
114af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
115f8ccf82aSAndre Oppermann     "Number of entries in callwheel and size of timeout() preallocation");
116f8ccf82aSAndre Oppermann 
117c445c3c7SAdrian Chadd #ifdef	RSS
118c445c3c7SAdrian Chadd static int pin_default_swi = 1;
119c445c3c7SAdrian Chadd static int pin_pcpu_swi = 1;
120c445c3c7SAdrian Chadd #else
121ac75ee9fSAdrian Chadd static int pin_default_swi = 0;
122ac75ee9fSAdrian Chadd static int pin_pcpu_swi = 0;
123c445c3c7SAdrian Chadd #endif
124ac75ee9fSAdrian Chadd 
125af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
126ac75ee9fSAdrian Chadd     0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
127af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
128a212f56dSPiotr Pawel Stefaniak     0, "Pin the per-CPU swis (except PCPU 0, which is also default)");
129ac75ee9fSAdrian Chadd 
13015b7a470SPoul-Henning Kamp /*
13115b7a470SPoul-Henning Kamp  * TODO:
13215b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
13315b7a470SPoul-Henning Kamp  */
13461322a0aSAlexander Motin static u_int __read_mostly callwheelsize;
13561322a0aSAlexander Motin static u_int __read_mostly callwheelmask;
136f23b4c91SGarrett Wollman 
13720c510f8SLuigi Rizzo /*
138a115fb62SHans Petter Selasky  * The callout cpu exec entities represent informations necessary for
139a115fb62SHans Petter Selasky  * describing the state of callouts currently running on the CPU and the ones
140a115fb62SHans Petter Selasky  * necessary for migrating callouts to the new callout cpu. In particular,
141a115fb62SHans Petter Selasky  * the first entry of the array cc_exec_entity holds informations for callout
142a115fb62SHans Petter Selasky  * running in SWI thread context, while the second one holds informations
143a115fb62SHans Petter Selasky  * for callout running directly from hardware interrupt context.
144a115fb62SHans Petter Selasky  * The cached informations are very important for deferring migration when
145a115fb62SHans Petter Selasky  * the migrating callout is already running.
1461283e9cdSAttilio Rao  */
1475b999a6bSDavide Italiano struct cc_exec {
1485b999a6bSDavide Italiano 	struct callout		*cc_curr;
149a8a03706SJohn Baldwin 	callout_func_t		*cc_drain;
1508c5a9161SEric van Gyzen 	void			*cc_last_func;
1518c5a9161SEric van Gyzen 	void			*cc_last_arg;
152a115fb62SHans Petter Selasky #ifdef SMP
153a8a03706SJohn Baldwin 	callout_func_t		*ce_migration_func;
154a115fb62SHans Petter Selasky 	void			*ce_migration_arg;
155a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_time;
156a115fb62SHans Petter Selasky 	sbintime_t		ce_migration_prec;
1578c5a9161SEric van Gyzen 	int			ce_migration_cpu;
158a115fb62SHans Petter Selasky #endif
159a4a3ce99SDavide Italiano 	bool			cc_cancel;
160a115fb62SHans Petter Selasky 	bool			cc_waiting;
1611283e9cdSAttilio Rao };
1621283e9cdSAttilio Rao 
1631283e9cdSAttilio Rao /*
164a115fb62SHans Petter Selasky  * There is one struct callout_cpu per cpu, holding all relevant
16520c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
16620c510f8SLuigi Rizzo  */
1678d809d50SJeff Roberson struct callout_cpu {
1684ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1695b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
17066525b2dSRandall Stewart 	struct callout		*cc_next;
1715b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1725b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1735b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1745b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
17574cf7caeSJohn Baldwin 	struct thread		*cc_thread;
1765b999a6bSDavide Italiano 	u_int			cc_bucket;
17715b1eb14SRandall Stewart 	u_int			cc_inited;
178329377f4SGleb Smirnoff #ifdef KTR
179232e8b52SJohn Baldwin 	char			cc_ktr_event_name[20];
180329377f4SGleb Smirnoff #endif
1818d809d50SJeff Roberson };
1828d809d50SJeff Roberson 
183403df7a6SRandall Stewart #define	callout_migrating(c)	((c)->c_iflags & CALLOUT_DFRMIGRATION)
184403df7a6SRandall Stewart 
185d2854fa4SRandall Stewart #define	cc_exec_curr(cc, dir)		cc->cc_exec_entity[dir].cc_curr
1868c5a9161SEric van Gyzen #define	cc_exec_last_func(cc, dir)	cc->cc_exec_entity[dir].cc_last_func
1878c5a9161SEric van Gyzen #define	cc_exec_last_arg(cc, dir)	cc->cc_exec_entity[dir].cc_last_arg
18818b4fd62SRandall Stewart #define	cc_exec_drain(cc, dir)		cc->cc_exec_entity[dir].cc_drain
18966525b2dSRandall Stewart #define	cc_exec_next(cc)		cc->cc_next
190d2854fa4SRandall Stewart #define	cc_exec_cancel(cc, dir)		cc->cc_exec_entity[dir].cc_cancel
191d2854fa4SRandall Stewart #define	cc_exec_waiting(cc, dir)	cc->cc_exec_entity[dir].cc_waiting
1928d809d50SJeff Roberson #ifdef SMP
193d2854fa4SRandall Stewart #define	cc_migration_func(cc, dir)	cc->cc_exec_entity[dir].ce_migration_func
194d2854fa4SRandall Stewart #define	cc_migration_arg(cc, dir)	cc->cc_exec_entity[dir].ce_migration_arg
195d2854fa4SRandall Stewart #define	cc_migration_cpu(cc, dir)	cc->cc_exec_entity[dir].ce_migration_cpu
196d2854fa4SRandall Stewart #define	cc_migration_time(cc, dir)	cc->cc_exec_entity[dir].ce_migration_time
197d2854fa4SRandall Stewart #define	cc_migration_prec(cc, dir)	cc->cc_exec_entity[dir].ce_migration_prec
198a115fb62SHans Petter Selasky 
199c1aff72cSMark Johnston static struct callout_cpu cc_cpu[MAXCPU];
2001283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
2018d809d50SJeff Roberson #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
2028d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
2038d809d50SJeff Roberson #else
204c1aff72cSMark Johnston static struct callout_cpu cc_cpu;
205c1aff72cSMark Johnston #define	CC_CPU(cpu)	(&cc_cpu)
206c1aff72cSMark Johnston #define	CC_SELF()	(&cc_cpu)
2078d809d50SJeff Roberson #endif
2088d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
2098d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
2101283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
2118d809d50SJeff Roberson 
2124b28d96eSJohn Baldwin static int __read_mostly cc_default_cpu;
2135b999a6bSDavide Italiano 
214232e8b52SJohn Baldwin static void	callout_cpu_init(struct callout_cpu *cc, int cpu);
2155b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
2165b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
2175b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
2185b999a6bSDavide Italiano #endif
2195b999a6bSDavide Italiano 		    int direct);
2208d809d50SJeff Roberson 
221d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
22249a74476SColin Percival 
223a115fb62SHans Petter Selasky /**
224a115fb62SHans Petter Selasky  * Locked by cc_lock:
225a115fb62SHans Petter Selasky  *   cc_curr         - If a callout is in progress, it is cc_curr.
226a115fb62SHans Petter Selasky  *                     If cc_curr is non-NULL, threads waiting in
227a115fb62SHans Petter Selasky  *                     callout_drain() will be woken up as soon as the
228a115fb62SHans Petter Selasky  *                     relevant callout completes.
229a115fb62SHans Petter Selasky  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
230a115fb62SHans Petter Selasky  *                     guarantees that the current callout will not run.
23174cf7caeSJohn Baldwin  *                     The softclock_call_cc() function sets this to 0 before it
232a115fb62SHans Petter Selasky  *                     drops callout_lock to acquire c_lock, and it calls
233a115fb62SHans Petter Selasky  *                     the handler only if curr_cancelled is still 0 after
234a115fb62SHans Petter Selasky  *                     cc_lock is successfully acquired.
235a115fb62SHans Petter Selasky  *   cc_waiting      - If a thread is waiting in callout_drain(), then
236a115fb62SHans Petter Selasky  *                     callout_wait is nonzero.  Set only when
237a115fb62SHans Petter Selasky  *                     cc_curr is non-NULL.
238a115fb62SHans Petter Selasky  */
239a115fb62SHans Petter Selasky 
240df8bae1dSRodney W. Grimes /*
241a115fb62SHans Petter Selasky  * Resets the execution entity tied to a specific callout cpu.
242a115fb62SHans Petter Selasky  */
243a115fb62SHans Petter Selasky static void
244a115fb62SHans Petter Selasky cc_cce_cleanup(struct callout_cpu *cc, int direct)
245a115fb62SHans Petter Selasky {
246a115fb62SHans Petter Selasky 
247d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
248d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
249d2854fa4SRandall Stewart 	cc_exec_waiting(cc, direct) = false;
250a115fb62SHans Petter Selasky #ifdef SMP
251d2854fa4SRandall Stewart 	cc_migration_cpu(cc, direct) = CPUBLOCK;
252d2854fa4SRandall Stewart 	cc_migration_time(cc, direct) = 0;
253d2854fa4SRandall Stewart 	cc_migration_prec(cc, direct) = 0;
254d2854fa4SRandall Stewart 	cc_migration_func(cc, direct) = NULL;
255d2854fa4SRandall Stewart 	cc_migration_arg(cc, direct) = NULL;
256a115fb62SHans Petter Selasky #endif
257a115fb62SHans Petter Selasky }
258a115fb62SHans Petter Selasky 
259a115fb62SHans Petter Selasky /*
260a115fb62SHans Petter Selasky  * Checks if migration is requested by a specific callout cpu.
261a115fb62SHans Petter Selasky  */
262a115fb62SHans Petter Selasky static int
263a115fb62SHans Petter Selasky cc_cce_migrating(struct callout_cpu *cc, int direct)
264a115fb62SHans Petter Selasky {
265a115fb62SHans Petter Selasky 
266a115fb62SHans Petter Selasky #ifdef SMP
267d2854fa4SRandall Stewart 	return (cc_migration_cpu(cc, direct) != CPUBLOCK);
268a115fb62SHans Petter Selasky #else
269a115fb62SHans Petter Selasky 	return (0);
270a115fb62SHans Petter Selasky #endif
271a115fb62SHans Petter Selasky }
272a115fb62SHans Petter Selasky 
273a115fb62SHans Petter Selasky /*
274a115fb62SHans Petter Selasky  * Kernel low level callwheel initialization
275efe67753SNathan Whitehorn  * called on the BSP during kernel startup.
276219d632cSMatthew Dillon  */
27715ae0c9aSAndre Oppermann static void
27815ae0c9aSAndre Oppermann callout_callwheel_init(void *dummy)
279219d632cSMatthew Dillon {
2808d809d50SJeff Roberson 	struct callout_cpu *cc;
2814b28d96eSJohn Baldwin 	int cpu;
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 	 */
289f8ccf82aSAndre Oppermann 	ncallout = imin(16 + maxproc + maxfiles, 18508);
290f8ccf82aSAndre Oppermann 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
291f8ccf82aSAndre Oppermann 
292219d632cSMatthew Dillon 	/*
293922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
294922314f0SAlfred Perlstein 	 * than 'ncallout'.
295219d632cSMatthew Dillon 	 */
296922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
297219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
298219d632cSMatthew Dillon 
29915ae0c9aSAndre Oppermann 	/*
300ac75ee9fSAdrian Chadd 	 * Fetch whether we're pinning the swi's or not.
301ac75ee9fSAdrian Chadd 	 */
302ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
303ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
304ac75ee9fSAdrian Chadd 
305ac75ee9fSAdrian Chadd 	/*
3064b28d96eSJohn Baldwin 	 * Initialize callout wheels.  The software interrupt threads
3074b28d96eSJohn Baldwin 	 * are created later.
30815ae0c9aSAndre Oppermann 	 */
3094b28d96eSJohn Baldwin 	cc_default_cpu = PCPU_GET(cpuid);
3104b28d96eSJohn Baldwin 	CPU_FOREACH(cpu) {
3114b28d96eSJohn Baldwin 		cc = CC_CPU(cpu);
3124b28d96eSJohn Baldwin 		callout_cpu_init(cc, cpu);
3134b28d96eSJohn Baldwin 	}
314219d632cSMatthew Dillon }
31515ae0c9aSAndre Oppermann SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
316219d632cSMatthew Dillon 
31715ae0c9aSAndre Oppermann /*
31815ae0c9aSAndre Oppermann  * Initialize the per-cpu callout structures.
31915ae0c9aSAndre Oppermann  */
3208d809d50SJeff Roberson static void
321232e8b52SJohn Baldwin callout_cpu_init(struct callout_cpu *cc, int cpu)
3228d809d50SJeff Roberson {
3238d809d50SJeff Roberson 	int i;
3248d809d50SJeff Roberson 
32574cf7caeSJohn Baldwin 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN);
32615b1eb14SRandall Stewart 	cc->cc_inited = 1;
32736d151a2SAlexander Motin 	cc->cc_callwheel = malloc_domainset(sizeof(struct callout_list) *
32836d151a2SAlexander Motin 	    callwheelsize, M_CALLOUT,
32936d151a2SAlexander Motin 	    DOMAINSET_PREF(pcpu_find(cpu)->pc_domain), M_WAITOK);
3305b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
3315b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
3325b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
3334bc38a5aSDavide Italiano 	cc->cc_firstevent = SBT_MAX;
334a115fb62SHans Petter Selasky 	for (i = 0; i < 2; i++)
335a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, i);
336329377f4SGleb Smirnoff #ifdef KTR
337232e8b52SJohn Baldwin 	snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
338232e8b52SJohn Baldwin 	    "callwheel cpu %d", cpu);
339329377f4SGleb Smirnoff #endif
3408d809d50SJeff Roberson }
3418d809d50SJeff Roberson 
342a115fb62SHans Petter Selasky #ifdef SMP
343a115fb62SHans Petter Selasky /*
344a115fb62SHans Petter Selasky  * Switches the cpu tied to a specific callout.
345a115fb62SHans Petter Selasky  * The function expects a locked incoming callout cpu and returns with
346a115fb62SHans Petter Selasky  * locked outcoming callout cpu.
347a115fb62SHans Petter Selasky  */
348a115fb62SHans Petter Selasky static struct callout_cpu *
349a115fb62SHans Petter Selasky callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
350a115fb62SHans Petter Selasky {
351a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
352a115fb62SHans Petter Selasky 
353a115fb62SHans Petter Selasky 	MPASS(c != NULL && cc != NULL);
354a115fb62SHans Petter Selasky 	CC_LOCK_ASSERT(cc);
355a115fb62SHans Petter Selasky 
356a115fb62SHans Petter Selasky 	/*
357a115fb62SHans Petter Selasky 	 * Avoid interrupts and preemption firing after the callout cpu
358a115fb62SHans Petter Selasky 	 * is blocked in order to avoid deadlocks as the new thread
359a115fb62SHans Petter Selasky 	 * may be willing to acquire the callout cpu lock.
360a115fb62SHans Petter Selasky 	 */
361a115fb62SHans Petter Selasky 	c->c_cpu = CPUBLOCK;
362a115fb62SHans Petter Selasky 	spinlock_enter();
363a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
364a115fb62SHans Petter Selasky 	new_cc = CC_CPU(new_cpu);
365a115fb62SHans Petter Selasky 	CC_LOCK(new_cc);
366a115fb62SHans Petter Selasky 	spinlock_exit();
367a115fb62SHans Petter Selasky 	c->c_cpu = new_cpu;
368a115fb62SHans Petter Selasky 	return (new_cc);
369a115fb62SHans Petter Selasky }
370a115fb62SHans Petter Selasky #endif
371a115fb62SHans Petter Selasky 
372219d632cSMatthew Dillon /*
3734b28d96eSJohn Baldwin  * Start softclock threads.
3748d809d50SJeff Roberson  */
3758d809d50SJeff Roberson static void
3768d809d50SJeff Roberson start_softclock(void *dummy)
3778d809d50SJeff Roberson {
37874cf7caeSJohn Baldwin 	struct proc *p;
37974cf7caeSJohn Baldwin 	struct thread *td;
3808d809d50SJeff Roberson 	struct callout_cpu *cc;
38174cf7caeSJohn Baldwin 	int cpu, error;
3824b28d96eSJohn Baldwin 	bool pin_swi;
3838d809d50SJeff Roberson 
38474cf7caeSJohn Baldwin 	p = NULL;
3853aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
3868d809d50SJeff Roberson 		cc = CC_CPU(cpu);
38774cf7caeSJohn Baldwin 		error = kproc_kthread_add(softclock_thread, cc, &p, &td,
38874cf7caeSJohn Baldwin 		    RFSTOPPED, 0, "clock", "clock (%d)", cpu);
38974cf7caeSJohn Baldwin 		if (error != 0)
39074cf7caeSJohn Baldwin 			panic("failed to create softclock thread for cpu %d: %d",
39174cf7caeSJohn Baldwin 			    cpu, error);
39274cf7caeSJohn Baldwin 		CC_LOCK(cc);
39374cf7caeSJohn Baldwin 		cc->cc_thread = td;
39474cf7caeSJohn Baldwin 		thread_lock(td);
39574cf7caeSJohn Baldwin 		sched_class(td, PRI_ITHD);
39674cf7caeSJohn Baldwin 		sched_prio(td, PI_SWI(SWI_CLOCK));
39774cf7caeSJohn Baldwin 		TD_SET_IWAIT(td);
39874cf7caeSJohn Baldwin 		thread_lock_set(td, (struct mtx *)&cc->cc_lock);
39974cf7caeSJohn Baldwin 		thread_unlock(td);
4004b28d96eSJohn Baldwin 		if (cpu == cc_default_cpu)
4014b28d96eSJohn Baldwin 			pin_swi = pin_default_swi;
4024b28d96eSJohn Baldwin 		else
4034b28d96eSJohn Baldwin 			pin_swi = pin_pcpu_swi;
40474cf7caeSJohn Baldwin 		if (pin_swi) {
40574cf7caeSJohn Baldwin 			error = cpuset_setithread(td->td_tid, cpu);
40674cf7caeSJohn Baldwin 			if (error != 0)
40774cf7caeSJohn Baldwin 				printf("%s: %s clock couldn't be pinned to cpu %d: %d\n",
40874cf7caeSJohn Baldwin 				    __func__, cpu == cc_default_cpu ?
40974cf7caeSJohn Baldwin 				    "default" : "per-cpu", cpu, error);
410ac75ee9fSAdrian Chadd 		}
411219d632cSMatthew Dillon 	}
412219d632cSMatthew Dillon }
4138d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
4148d809d50SJeff Roberson 
4155b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
4168d809d50SJeff Roberson 
4175b999a6bSDavide Italiano static inline u_int
4185b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
4195b999a6bSDavide Italiano {
4205b999a6bSDavide Italiano 
4215b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
4225b999a6bSDavide Italiano }
4235b999a6bSDavide Italiano 
4245b999a6bSDavide Italiano static inline u_int
4255b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
4265b999a6bSDavide Italiano {
4275b999a6bSDavide Italiano 
4285b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
4295b999a6bSDavide Italiano }
4305b999a6bSDavide Italiano 
4315b999a6bSDavide Italiano void
4325b999a6bSDavide Italiano callout_process(sbintime_t now)
4335b999a6bSDavide Italiano {
434642701abSKyle Evans 	struct callout_entropy {
435642701abSKyle Evans 		struct callout_cpu *cc;
436642701abSKyle Evans 		struct thread *td;
437642701abSKyle Evans 		sbintime_t now;
438642701abSKyle Evans 	} entropy;
4395b999a6bSDavide Italiano 	struct callout *tmp, *tmpn;
4405b999a6bSDavide Italiano 	struct callout_cpu *cc;
4415b999a6bSDavide Italiano 	struct callout_list *sc;
44274cf7caeSJohn Baldwin 	struct thread *td;
443cb1f5d11SAlexander Motin 	sbintime_t first, last, lookahead, max, tmp_max;
4445b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
4455b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4465b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
4475b999a6bSDavide Italiano #endif
448a115fb62SHans Petter Selasky 
4498d809d50SJeff Roberson 	cc = CC_SELF();
450a115fb62SHans Petter Selasky 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4515b999a6bSDavide Italiano 
4525b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4535b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4545b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4555b999a6bSDavide Italiano 	nowb = callout_hash(now);
4565b999a6bSDavide Italiano 
4575b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4585b999a6bSDavide Italiano 	if (nowb == firstb)
4595b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4605b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4615b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4625b999a6bSDavide Italiano 	else
463cb1f5d11SAlexander Motin 		lookahead = SBT_1S;
4645b999a6bSDavide Italiano 	first = last = now;
4655b999a6bSDavide Italiano 	first += (lookahead / 2);
4665b999a6bSDavide Italiano 	last += lookahead;
4675b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4685b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4695b999a6bSDavide Italiano 	max = last;
4705b999a6bSDavide Italiano 
4715b999a6bSDavide Italiano 	/*
4725b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4735b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4745b999a6bSDavide Italiano 	 */
4755b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4765b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4775b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4785b999a6bSDavide Italiano 			nowb = lastb;
4799fc51b0bSJeff Roberson 	}
4805b999a6bSDavide Italiano 
4815b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4825b999a6bSDavide Italiano 	do {
4835b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
4845b999a6bSDavide Italiano 		tmp = LIST_FIRST(sc);
4855b999a6bSDavide Italiano 		while (tmp != NULL) {
4865b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
4875b999a6bSDavide Italiano 			if (tmp->c_time <= now) {
4885b999a6bSDavide Italiano 				/*
4895b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
4905b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
4915b999a6bSDavide Italiano 				 */
49215b1eb14SRandall Stewart 				if (tmp->c_iflags & CALLOUT_DIRECT) {
4935b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4945b999a6bSDavide Italiano 					++depth_dir;
4955b999a6bSDavide Italiano #endif
49666525b2dSRandall Stewart 					cc_exec_next(cc) =
4975b999a6bSDavide Italiano 					    LIST_NEXT(tmp, c_links.le);
4985b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
4995b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
5005b999a6bSDavide Italiano 					softclock_call_cc(tmp, cc,
5015b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5025b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
5035b999a6bSDavide Italiano #endif
5045b999a6bSDavide Italiano 					    1);
50566525b2dSRandall Stewart 					tmp = cc_exec_next(cc);
50666525b2dSRandall Stewart 					cc_exec_next(cc) = NULL;
5075b999a6bSDavide Italiano 				} else {
5085b999a6bSDavide Italiano 					tmpn = LIST_NEXT(tmp, c_links.le);
5095b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
5105b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
5115b999a6bSDavide Italiano 					    tmp, c_links.tqe);
51215b1eb14SRandall Stewart 					tmp->c_iflags |= CALLOUT_PROCESSED;
5135b999a6bSDavide Italiano 					tmp = tmpn;
5149fc51b0bSJeff Roberson 				}
5155b999a6bSDavide Italiano 				continue;
5165b999a6bSDavide Italiano 			}
5175b999a6bSDavide Italiano 			/* Skip events from distant future. */
5185b999a6bSDavide Italiano 			if (tmp->c_time >= max)
5195b999a6bSDavide Italiano 				goto next;
5205b999a6bSDavide Italiano 			/*
5215b999a6bSDavide Italiano 			 * Event minimal time is bigger than present maximal
5225b999a6bSDavide Italiano 			 * time, so it cannot be aggregated.
5235b999a6bSDavide Italiano 			 */
5245b999a6bSDavide Italiano 			if (tmp->c_time > last) {
5255b999a6bSDavide Italiano 				lastb = nowb;
5265b999a6bSDavide Italiano 				goto next;
5275b999a6bSDavide Italiano 			}
5285b999a6bSDavide Italiano 			/* Update first and last time, respecting this event. */
5295b999a6bSDavide Italiano 			if (tmp->c_time < first)
5305b999a6bSDavide Italiano 				first = tmp->c_time;
5315b999a6bSDavide Italiano 			tmp_max = tmp->c_time + tmp->c_precision;
5325b999a6bSDavide Italiano 			if (tmp_max < last)
5335b999a6bSDavide Italiano 				last = tmp_max;
5345b999a6bSDavide Italiano next:
5355b999a6bSDavide Italiano 			tmp = LIST_NEXT(tmp, c_links.le);
5365b999a6bSDavide Italiano 		}
5375b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
5385b999a6bSDavide Italiano 		firstb++;
5395b999a6bSDavide Italiano 		/*
5405b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
5415b999a6bSDavide Italiano 		 * some event we can't execute at now.
5425b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
5435b999a6bSDavide Italiano 		 */
5445b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
5455b999a6bSDavide Italiano 	cc->cc_firstevent = last;
5465b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
547a28c28e6SMark Johnston 
5485b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5495b999a6bSDavide Italiano 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
5505b999a6bSDavide Italiano 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
5515b999a6bSDavide Italiano 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
5525b999a6bSDavide Italiano #endif
55374cf7caeSJohn Baldwin 	if (!TAILQ_EMPTY(&cc->cc_expireq)) {
554642701abSKyle Evans 		entropy.cc = cc;
555642701abSKyle Evans 		entropy.td = curthread;
556642701abSKyle Evans 		entropy.now = now;
557642701abSKyle Evans 		random_harvest_queue(&entropy, sizeof(entropy), RANDOM_CALLOUT);
558642701abSKyle Evans 
55974cf7caeSJohn Baldwin 		td = cc->cc_thread;
56074cf7caeSJohn Baldwin 		if (TD_AWAITING_INTR(td)) {
5616b95cf5bSMark Johnston 			thread_lock_block_wait(td);
5626b95cf5bSMark Johnston 			THREAD_LOCK_ASSERT(td, MA_OWNED);
56374cf7caeSJohn Baldwin 			TD_CLR_IWAIT(td);
56474cf7caeSJohn Baldwin 			sched_add(td, SRQ_INTR);
56574cf7caeSJohn Baldwin 		} else
566a115fb62SHans Petter Selasky 			mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
56774cf7caeSJohn Baldwin 	} else
56874cf7caeSJohn Baldwin 		mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5698d809d50SJeff Roberson }
5708d809d50SJeff Roberson 
5718d809d50SJeff Roberson static struct callout_cpu *
5728d809d50SJeff Roberson callout_lock(struct callout *c)
5738d809d50SJeff Roberson {
5748d809d50SJeff Roberson 	struct callout_cpu *cc;
575a115fb62SHans Petter Selasky 	int cpu;
576a115fb62SHans Petter Selasky 
577a115fb62SHans Petter Selasky 	for (;;) {
578a115fb62SHans Petter Selasky 		cpu = c->c_cpu;
579a115fb62SHans Petter Selasky #ifdef SMP
580a115fb62SHans Petter Selasky 		if (cpu == CPUBLOCK) {
581a115fb62SHans Petter Selasky 			while (c->c_cpu == CPUBLOCK)
582a115fb62SHans Petter Selasky 				cpu_spinwait();
583a115fb62SHans Petter Selasky 			continue;
584a115fb62SHans Petter Selasky 		}
585a115fb62SHans Petter Selasky #endif
586a115fb62SHans Petter Selasky 		cc = CC_CPU(cpu);
5878d809d50SJeff Roberson 		CC_LOCK(cc);
588a115fb62SHans Petter Selasky 		if (cpu == c->c_cpu)
589a115fb62SHans Petter Selasky 			break;
590a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
591a115fb62SHans Petter Selasky 	}
5928d809d50SJeff Roberson 	return (cc);
593219d632cSMatthew Dillon }
594219d632cSMatthew Dillon 
595a115fb62SHans Petter Selasky static void
596a115fb62SHans Petter Selasky callout_cc_add(struct callout *c, struct callout_cpu *cc,
597a115fb62SHans Petter Selasky     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
59866525b2dSRandall Stewart     void *arg, int cpu, int flags)
5991283e9cdSAttilio Rao {
6005b999a6bSDavide Italiano 	int bucket;
6011283e9cdSAttilio Rao 
6021283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
603a115fb62SHans Petter Selasky 	if (sbt < cc->cc_lastscan)
604a115fb62SHans Petter Selasky 		sbt = cc->cc_lastscan;
605a115fb62SHans Petter Selasky 	c->c_arg = arg;
60615b1eb14SRandall Stewart 	c->c_iflags |= CALLOUT_PENDING;
60715b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PROCESSED;
60815b1eb14SRandall Stewart 	c->c_flags |= CALLOUT_ACTIVE;
60907a2df5dSRandall Stewart 	if (flags & C_DIRECT_EXEC)
610b132edb5SRandall Stewart 		c->c_iflags |= CALLOUT_DIRECT;
611a115fb62SHans Petter Selasky 	c->c_func = func;
612a115fb62SHans Petter Selasky 	c->c_time = sbt;
613a115fb62SHans Petter Selasky 	c->c_precision = precision;
6145b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
6155b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
6165b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
6175b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
6185b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
6195b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
62066525b2dSRandall Stewart 		cc_exec_next(cc) = c;
621a28c28e6SMark Johnston 
6225b999a6bSDavide Italiano 	/*
6235b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
6245b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
6255b999a6bSDavide Italiano 	 */
6264bc38a5aSDavide Italiano 	if (SBT_MAX - c->c_time < c->c_precision)
6274bc38a5aSDavide Italiano 		c->c_precision = SBT_MAX - c->c_time;
6285b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
6295b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
6305b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
631a115fb62SHans Petter Selasky 		cpu_new_callout(cpu, sbt, c->c_time);
6321283e9cdSAttilio Rao 	}
6331283e9cdSAttilio Rao }
6341283e9cdSAttilio Rao 
6356098e7acSKonstantin Belousov static void
6365b999a6bSDavide Italiano softclock_call_cc(struct callout *c, struct callout_cpu *cc,
6375b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6385b999a6bSDavide Italiano     int *mpcalls, int *lockcalls, int *gcalls,
6395b999a6bSDavide Italiano #endif
6405b999a6bSDavide Italiano     int direct)
6416098e7acSKonstantin Belousov {
642a115fb62SHans Petter Selasky 	struct rm_priotracker tracker;
643a8a03706SJohn Baldwin 	callout_func_t *c_func, *drain;
6446098e7acSKonstantin Belousov 	void *c_arg;
645a115fb62SHans Petter Selasky 	struct lock_class *class;
6466098e7acSKonstantin Belousov 	struct lock_object *c_lock;
647a115fb62SHans Petter Selasky 	uintptr_t lock_status;
64815b1eb14SRandall Stewart 	int c_iflags;
649a115fb62SHans Petter Selasky #ifdef SMP
650a115fb62SHans Petter Selasky 	struct callout_cpu *new_cc;
651a8a03706SJohn Baldwin 	callout_func_t *new_func;
652a115fb62SHans Petter Selasky 	void *new_arg;
653a115fb62SHans Petter Selasky 	int flags, new_cpu;
654a115fb62SHans Petter Selasky 	sbintime_t new_prec, new_time;
655a115fb62SHans Petter Selasky #endif
6565b999a6bSDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
65703763781SDavide Italiano 	sbintime_t sbt1, sbt2;
6586098e7acSKonstantin Belousov 	struct timespec ts2;
6595b999a6bSDavide Italiano 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
660a8a03706SJohn Baldwin 	static callout_func_t *lastfunc;
6616098e7acSKonstantin Belousov #endif
6626098e7acSKonstantin Belousov 
66315b1eb14SRandall Stewart 	KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
66415b1eb14SRandall Stewart 	    ("softclock_call_cc: pend %p %x", c, c->c_iflags));
66515b1eb14SRandall Stewart 	KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
66615b1eb14SRandall Stewart 	    ("softclock_call_cc: act %p %x", c, c->c_flags));
667a115fb62SHans Petter Selasky 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
668a115fb62SHans Petter Selasky 	lock_status = 0;
669*a879e40cSKristof Provost 	if (c->c_iflags & CALLOUT_SHAREDLOCK) {
670a115fb62SHans Petter Selasky 		if (class == &lock_class_rm)
671a115fb62SHans Petter Selasky 			lock_status = (uintptr_t)&tracker;
672a115fb62SHans Petter Selasky 		else
673a115fb62SHans Petter Selasky 			lock_status = 1;
674a115fb62SHans Petter Selasky 	}
6756098e7acSKonstantin Belousov 	c_lock = c->c_lock;
6766098e7acSKonstantin Belousov 	c_func = c->c_func;
6776098e7acSKonstantin Belousov 	c_arg = c->c_arg;
67815b1eb14SRandall Stewart 	c_iflags = c->c_iflags;
67915b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
680d2854fa4SRandall Stewart 
681d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = c;
6828c5a9161SEric van Gyzen 	cc_exec_last_func(cc, direct) = c_func;
6838c5a9161SEric van Gyzen 	cc_exec_last_arg(cc, direct) = c_arg;
684d2854fa4SRandall Stewart 	cc_exec_cancel(cc, direct) = false;
68518b4fd62SRandall Stewart 	cc_exec_drain(cc, direct) = NULL;
6866098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
687a115fb62SHans Petter Selasky 	if (c_lock != NULL) {
688a115fb62SHans Petter Selasky 		class->lc_lock(c_lock, lock_status);
6896098e7acSKonstantin Belousov 		/*
690a115fb62SHans Petter Selasky 		 * The callout may have been cancelled
691a115fb62SHans Petter Selasky 		 * while we switched locks.
6926098e7acSKonstantin Belousov 		 */
693d2854fa4SRandall Stewart 		if (cc_exec_cancel(cc, direct)) {
694a115fb62SHans Petter Selasky 			class->lc_unlock(c_lock);
695a115fb62SHans Petter Selasky 			goto skip;
6966098e7acSKonstantin Belousov 		}
697a115fb62SHans Petter Selasky 		/* The callout cannot be stopped now. */
698d2854fa4SRandall Stewart 		cc_exec_cancel(cc, direct) = true;
6996098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
7005b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7016098e7acSKonstantin Belousov 			(*gcalls)++;
7025b999a6bSDavide Italiano #endif
7035b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
7046098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7056098e7acSKonstantin Belousov 		} else {
7065b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7076098e7acSKonstantin Belousov 			(*lockcalls)++;
7085b999a6bSDavide Italiano #endif
7096098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
7106098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7116098e7acSKonstantin Belousov 		}
7126098e7acSKonstantin Belousov 	} else {
7135b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7146098e7acSKonstantin Belousov 		(*mpcalls)++;
7155b999a6bSDavide Italiano #endif
7165b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
7176098e7acSKonstantin Belousov 		    c, c_func, c_arg);
7186098e7acSKonstantin Belousov 	}
719232e8b52SJohn Baldwin 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
720232e8b52SJohn Baldwin 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
72103763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
7225b999a6bSDavide Italiano 	sbt1 = sbinuptime();
7236098e7acSKonstantin Belousov #endif
7246098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
72536160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__start, c);
7266098e7acSKonstantin Belousov 	c_func(c_arg);
72736160958SMark Johnston 	SDT_PROBE1(callout_execute, , , callout__end, c);
7286098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
72903763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
73003763781SDavide Italiano 	sbt2 = sbinuptime();
73103763781SDavide Italiano 	sbt2 -= sbt1;
73203763781SDavide Italiano 	if (sbt2 > maxdt) {
73303763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
73403763781SDavide Italiano 			ts2 = sbttots(sbt2);
7356098e7acSKonstantin Belousov 			printf(
7366098e7acSKonstantin Belousov 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
7376098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
7386098e7acSKonstantin Belousov 		}
73903763781SDavide Italiano 		maxdt = sbt2;
7406098e7acSKonstantin Belousov 		lastfunc = c_func;
7416098e7acSKonstantin Belousov 	}
7426098e7acSKonstantin Belousov #endif
743232e8b52SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
7446098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
74515b1eb14SRandall Stewart 	if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
746a115fb62SHans Petter Selasky 		class->lc_unlock(c_lock);
747a115fb62SHans Petter Selasky skip:
7486098e7acSKonstantin Belousov 	CC_LOCK(cc);
749d2854fa4SRandall Stewart 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
750d2854fa4SRandall Stewart 	cc_exec_curr(cc, direct) = NULL;
75118b4fd62SRandall Stewart 	if (cc_exec_drain(cc, direct)) {
75218b4fd62SRandall Stewart 		drain = cc_exec_drain(cc, direct);
75318b4fd62SRandall Stewart 		cc_exec_drain(cc, direct) = NULL;
75418b4fd62SRandall Stewart 		CC_UNLOCK(cc);
75518b4fd62SRandall Stewart 		drain(c_arg);
75618b4fd62SRandall Stewart 		CC_LOCK(cc);
75718b4fd62SRandall Stewart 	}
758d2854fa4SRandall Stewart 	if (cc_exec_waiting(cc, direct)) {
759bdf9120cSAttilio Rao 		/*
760a115fb62SHans Petter Selasky 		 * There is someone waiting for the
761a115fb62SHans Petter Selasky 		 * callout to complete.
762a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
763a115fb62SHans Petter Selasky 		 * migration just cancel it.
764bdf9120cSAttilio Rao 		 */
765a115fb62SHans Petter Selasky 		if (cc_cce_migrating(cc, direct)) {
766a115fb62SHans Petter Selasky 			cc_cce_cleanup(cc, direct);
767a115fb62SHans Petter Selasky 
768a115fb62SHans Petter Selasky 			/*
769a115fb62SHans Petter Selasky 			 * It should be assert here that the callout is not
770a115fb62SHans Petter Selasky 			 * destroyed but that is not easy.
771a115fb62SHans Petter Selasky 			 */
77215b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
7736098e7acSKonstantin Belousov 		}
774d2854fa4SRandall Stewart 		cc_exec_waiting(cc, direct) = false;
775a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
776d2854fa4SRandall Stewart 		wakeup(&cc_exec_waiting(cc, direct));
777a115fb62SHans Petter Selasky 		CC_LOCK(cc);
778a115fb62SHans Petter Selasky 	} else if (cc_cce_migrating(cc, direct)) {
779a115fb62SHans Petter Selasky #ifdef SMP
780a115fb62SHans Petter Selasky 		/*
781a115fb62SHans Petter Selasky 		 * If the callout was scheduled for
782a115fb62SHans Petter Selasky 		 * migration just perform it now.
783a115fb62SHans Petter Selasky 		 */
784d2854fa4SRandall Stewart 		new_cpu = cc_migration_cpu(cc, direct);
785d2854fa4SRandall Stewart 		new_time = cc_migration_time(cc, direct);
786d2854fa4SRandall Stewart 		new_prec = cc_migration_prec(cc, direct);
787d2854fa4SRandall Stewart 		new_func = cc_migration_func(cc, direct);
788d2854fa4SRandall Stewart 		new_arg = cc_migration_arg(cc, direct);
789a115fb62SHans Petter Selasky 		cc_cce_cleanup(cc, direct);
790a115fb62SHans Petter Selasky 
791a115fb62SHans Petter Selasky 		/*
792a115fb62SHans Petter Selasky 		 * It should be assert here that the callout is not destroyed
793a115fb62SHans Petter Selasky 		 * but that is not easy.
794a115fb62SHans Petter Selasky 		 *
795a115fb62SHans Petter Selasky 		 * As first thing, handle deferred callout stops.
796a115fb62SHans Petter Selasky 		 */
797d2854fa4SRandall Stewart 		if (!callout_migrating(c)) {
798a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT,
799a115fb62SHans Petter Selasky 			     "deferred cancelled %p func %p arg %p",
800a115fb62SHans Petter Selasky 			     c, new_func, new_arg);
801a115fb62SHans Petter Selasky 			return;
802a115fb62SHans Petter Selasky 		}
80315b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_DFRMIGRATION;
804a115fb62SHans Petter Selasky 
805a115fb62SHans Petter Selasky 		new_cc = callout_cpu_switch(c, cc, new_cpu);
806a115fb62SHans Petter Selasky 		flags = (direct) ? C_DIRECT_EXEC : 0;
807a115fb62SHans Petter Selasky 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
80866525b2dSRandall Stewart 		    new_arg, new_cpu, flags);
809a115fb62SHans Petter Selasky 		CC_UNLOCK(new_cc);
810a115fb62SHans Petter Selasky 		CC_LOCK(cc);
811a115fb62SHans Petter Selasky #else
812a115fb62SHans Petter Selasky 		panic("migration should not happen");
813a115fb62SHans Petter Selasky #endif
814a115fb62SHans Petter Selasky 	}
8156098e7acSKonstantin Belousov }
8166098e7acSKonstantin Belousov 
817219d632cSMatthew Dillon /*
818ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
819ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
820ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
821ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
822024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
823ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
824ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
825ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
826ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
827ab36c067SJustin T. Gibbs  */
828a50ec505SPoul-Henning Kamp 
829ab36c067SJustin T. Gibbs /*
83074cf7caeSJohn Baldwin  * Software (low priority) clock interrupt thread handler.
831df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
832df8bae1dSRodney W. Grimes  */
83374cf7caeSJohn Baldwin static void
83474cf7caeSJohn Baldwin softclock_thread(void *arg)
835df8bae1dSRodney W. Grimes {
83674cf7caeSJohn Baldwin 	struct thread *td = curthread;
8378d809d50SJeff Roberson 	struct callout_cpu *cc;
838b336df68SPoul-Henning Kamp 	struct callout *c;
8395b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
84074cf7caeSJohn Baldwin 	int depth, gcalls, lockcalls, mpcalls;
8415b999a6bSDavide Italiano #endif
842df8bae1dSRodney W. Grimes 
8438d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
8448d809d50SJeff Roberson 	CC_LOCK(cc);
84574cf7caeSJohn Baldwin 	for (;;) {
84674cf7caeSJohn Baldwin 		while (TAILQ_EMPTY(&cc->cc_expireq)) {
84774cf7caeSJohn Baldwin 			/*
84874cf7caeSJohn Baldwin 			 * Use CC_LOCK(cc) as the thread_lock while
84974cf7caeSJohn Baldwin 			 * idle.
85074cf7caeSJohn Baldwin 			 */
85174cf7caeSJohn Baldwin 			thread_lock(td);
85274cf7caeSJohn Baldwin 			thread_lock_set(td, (struct mtx *)&cc->cc_lock);
85374cf7caeSJohn Baldwin 			TD_SET_IWAIT(td);
85474cf7caeSJohn Baldwin 			mi_switch(SW_VOL | SWT_IWAIT);
85574cf7caeSJohn Baldwin 
85674cf7caeSJohn Baldwin 			/* mi_switch() drops thread_lock(). */
85774cf7caeSJohn Baldwin 			CC_LOCK(cc);
85874cf7caeSJohn Baldwin 		}
85974cf7caeSJohn Baldwin 
86074cf7caeSJohn Baldwin #ifdef CALLOUT_PROFILING
86174cf7caeSJohn Baldwin 		depth = gcalls = lockcalls = mpcalls = 0;
86274cf7caeSJohn Baldwin #endif
8635b999a6bSDavide Italiano 		while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
8645b999a6bSDavide Italiano 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
8655b999a6bSDavide Italiano 			softclock_call_cc(c, cc,
8665b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8675b999a6bSDavide Italiano 			    &mpcalls, &lockcalls, &gcalls,
8685b999a6bSDavide Italiano #endif
8695b999a6bSDavide Italiano 			    0);
8705b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8715b999a6bSDavide Italiano 			++depth;
8725b999a6bSDavide Italiano #endif
873df8bae1dSRodney W. Grimes 		}
8745b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
87522ee8c4fSPoul-Henning Kamp 		avg_depth += (depth * 1000 - avg_depth) >> 8;
87622ee8c4fSPoul-Henning Kamp 		avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
87764b9ee20SAttilio Rao 		avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
87822ee8c4fSPoul-Henning Kamp 		avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8795b999a6bSDavide Italiano #endif
88074cf7caeSJohn Baldwin 	}
881df8bae1dSRodney W. Grimes }
882df8bae1dSRodney W. Grimes 
883a9e182e8SKonstantin Belousov void
884a9e182e8SKonstantin Belousov callout_when(sbintime_t sbt, sbintime_t precision, int flags,
885a9e182e8SKonstantin Belousov     sbintime_t *res, sbintime_t *prec_res)
886acc8326dSGarrett Wollman {
887a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, to_pr;
888acc8326dSGarrett Wollman 
889a9e182e8SKonstantin Belousov 	if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
890a9e182e8SKonstantin Belousov 		*res = sbt;
891a9e182e8SKonstantin Belousov 		*prec_res = precision;
892a9e182e8SKonstantin Belousov 		return;
89315b1eb14SRandall Stewart 	}
894a9e182e8SKonstantin Belousov 	if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
8955b999a6bSDavide Italiano 		sbt = tick_sbt;
896a28c28e6SMark Johnston 	if ((flags & C_HARDCLOCK) != 0 || sbt >= sbt_tickthreshold) {
8975b999a6bSDavide Italiano 		/*
8985b999a6bSDavide Italiano 		 * Obtain the time of the last hardclock() call on
8995b999a6bSDavide Italiano 		 * this CPU directly from the kern_clocksource.c.
9005b999a6bSDavide Italiano 		 * This value is per-CPU, but it is equal for all
9015b999a6bSDavide Italiano 		 * active ones.
9025b999a6bSDavide Italiano 		 */
9035b999a6bSDavide Italiano #ifdef __LP64__
904a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
9055b999a6bSDavide Italiano #else
9065b999a6bSDavide Italiano 		spinlock_enter();
907a115fb62SHans Petter Selasky 		to_sbt = DPCPU_GET(hardclocktime);
9085b999a6bSDavide Italiano 		spinlock_exit();
9095b999a6bSDavide Italiano #endif
9109f3aabb9SJohn Baldwin 		if (cold && to_sbt == 0)
9119f3aabb9SJohn Baldwin 			to_sbt = sbinuptime();
912a115fb62SHans Petter Selasky 		if ((flags & C_HARDCLOCK) == 0)
913a115fb62SHans Petter Selasky 			to_sbt += tick_sbt;
9145b999a6bSDavide Italiano 	} else
915a115fb62SHans Petter Selasky 		to_sbt = sbinuptime();
916a115fb62SHans Petter Selasky 	if (SBT_MAX - to_sbt < sbt)
917a115fb62SHans Petter Selasky 		to_sbt = SBT_MAX;
9181b0c144fSDavide Italiano 	else
919a115fb62SHans Petter Selasky 		to_sbt += sbt;
920a9e182e8SKonstantin Belousov 	*res = to_sbt;
921a9e182e8SKonstantin Belousov 	to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
922a115fb62SHans Petter Selasky 	    sbt >> C_PRELGET(flags));
923a9e182e8SKonstantin Belousov 	*prec_res = to_pr > precision ? to_pr : precision;
924a115fb62SHans Petter Selasky }
925a9e182e8SKonstantin Belousov 
926a9e182e8SKonstantin Belousov /*
927a9e182e8SKonstantin Belousov  * New interface; clients allocate their own callout structures.
928a9e182e8SKonstantin Belousov  *
929a9e182e8SKonstantin Belousov  * callout_reset() - establish or change a timeout
930a9e182e8SKonstantin Belousov  * callout_stop() - disestablish a timeout
931a9e182e8SKonstantin Belousov  * callout_init() - initialize a callout structure so that it can
932a9e182e8SKonstantin Belousov  *	safely be passed to callout_reset() and callout_stop()
933a9e182e8SKonstantin Belousov  *
934a9e182e8SKonstantin Belousov  * <sys/callout.h> defines three convenience macros:
935a9e182e8SKonstantin Belousov  *
936a9e182e8SKonstantin Belousov  * callout_active() - returns truth if callout has not been stopped,
937a9e182e8SKonstantin Belousov  *	drained, or deactivated since the last time the callout was
938a9e182e8SKonstantin Belousov  *	reset.
939a9e182e8SKonstantin Belousov  * callout_pending() - returns truth if callout is still waiting for timeout
940a9e182e8SKonstantin Belousov  * callout_deactivate() - marks the callout as having been serviced
941a9e182e8SKonstantin Belousov  */
942a9e182e8SKonstantin Belousov int
943a9e182e8SKonstantin Belousov callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
944a8a03706SJohn Baldwin     callout_func_t *ftn, void *arg, int cpu, int flags)
945a9e182e8SKonstantin Belousov {
946a9e182e8SKonstantin Belousov 	sbintime_t to_sbt, precision;
947a9e182e8SKonstantin Belousov 	struct callout_cpu *cc;
948a9e182e8SKonstantin Belousov 	int cancelled, direct;
949a9e182e8SKonstantin Belousov 	int ignore_cpu=0;
950a9e182e8SKonstantin Belousov 
951a9e182e8SKonstantin Belousov 	cancelled = 0;
952a9e182e8SKonstantin Belousov 	if (cpu == -1) {
953a9e182e8SKonstantin Belousov 		ignore_cpu = 1;
954a9e182e8SKonstantin Belousov 	} else if ((cpu >= MAXCPU) ||
955a9e182e8SKonstantin Belousov 		   ((CC_CPU(cpu))->cc_inited == 0)) {
956a9e182e8SKonstantin Belousov 		/* Invalid CPU spec */
957a9e182e8SKonstantin Belousov 		panic("Invalid CPU in callout %d", cpu);
958a9e182e8SKonstantin Belousov 	}
959a9e182e8SKonstantin Belousov 	callout_when(sbt, prec, flags, &to_sbt, &precision);
960a9e182e8SKonstantin Belousov 
961a115fb62SHans Petter Selasky 	/*
96266525b2dSRandall Stewart 	 * This flag used to be added by callout_cc_add, but the
96366525b2dSRandall Stewart 	 * first time you call this we could end up with the
96466525b2dSRandall Stewart 	 * wrong direct flag if we don't do it before we add.
96566525b2dSRandall Stewart 	 */
96666525b2dSRandall Stewart 	if (flags & C_DIRECT_EXEC) {
96715b1eb14SRandall Stewart 		direct = 1;
96815b1eb14SRandall Stewart 	} else {
96915b1eb14SRandall Stewart 		direct = 0;
97066525b2dSRandall Stewart 	}
9714730a897SAlexander Motin 	KASSERT(!direct || c->c_lock == NULL ||
9724730a897SAlexander Motin 	    (LOCK_CLASS(c->c_lock)->lc_flags & LC_SPINLOCK),
9734730a897SAlexander Motin 	    ("%s: direct callout %p has non-spin lock", __func__, c));
974a115fb62SHans Petter Selasky 	cc = callout_lock(c);
97515b1eb14SRandall Stewart 	/*
9764b28d96eSJohn Baldwin 	 * Don't allow migration if the user does not care.
97715b1eb14SRandall Stewart 	 */
9784b28d96eSJohn Baldwin 	if (ignore_cpu) {
97915b1eb14SRandall Stewart 		cpu = c->c_cpu;
98015b1eb14SRandall Stewart 	}
98115b1eb14SRandall Stewart 
982d2854fa4SRandall Stewart 	if (cc_exec_curr(cc, direct) == c) {
983a115fb62SHans Petter Selasky 		/*
984a115fb62SHans Petter Selasky 		 * We're being asked to reschedule a callout which is
985a115fb62SHans Petter Selasky 		 * currently in progress.  If there is a lock then we
986a115fb62SHans Petter Selasky 		 * can cancel the callout if it has not really started.
987a115fb62SHans Petter Selasky 		 */
988378d5c6cSAndriy Gapon 		if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
989d2854fa4SRandall Stewart 			cancelled = cc_exec_cancel(cc, direct) = true;
990dc4ee9a8SGleb Smirnoff 		if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
991a115fb62SHans Petter Selasky 			/*
992a115fb62SHans Petter Selasky 			 * Someone has called callout_drain to kill this
993a115fb62SHans Petter Selasky 			 * callout.  Don't reschedule.
994a115fb62SHans Petter Selasky 			 */
995a115fb62SHans Petter Selasky 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
996a115fb62SHans Petter Selasky 			    cancelled ? "cancelled" : "failed to cancel",
997a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
998a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
999a115fb62SHans Petter Selasky 			return (cancelled);
1000a115fb62SHans Petter Selasky 		}
1001d2854fa4SRandall Stewart #ifdef SMP
1002d2854fa4SRandall Stewart 		if (callout_migrating(c)) {
1003d2854fa4SRandall Stewart 			/*
1004d2854fa4SRandall Stewart 			 * This only occurs when a second callout_reset_sbt_on
1005d2854fa4SRandall Stewart 			 * is made after a previous one moved it into
1006d2854fa4SRandall Stewart 			 * deferred migration (below). Note we do *not* change
1007d2854fa4SRandall Stewart 			 * the prev_cpu even though the previous target may
1008d2854fa4SRandall Stewart 			 * be different.
1009d2854fa4SRandall Stewart 			 */
1010d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1011d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1012d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1013d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1014d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
1015d2854fa4SRandall Stewart 			cancelled = 1;
1016d2854fa4SRandall Stewart 			CC_UNLOCK(cc);
1017d2854fa4SRandall Stewart 			return (cancelled);
1018d2854fa4SRandall Stewart 		}
1019d2854fa4SRandall Stewart #endif
1020a115fb62SHans Petter Selasky 	}
102115b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_PENDING) {
102215b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
102366525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
102466525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1025a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
102615b1eb14SRandall Stewart 		} else {
1027a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
102815b1eb14SRandall Stewart 		}
1029a115fb62SHans Petter Selasky 		cancelled = 1;
103015b1eb14SRandall Stewart 		c->c_iflags &= ~ CALLOUT_PENDING;
103115b1eb14SRandall Stewart 		c->c_flags &= ~ CALLOUT_ACTIVE;
10328d809d50SJeff Roberson 	}
10331283e9cdSAttilio Rao 
1034a115fb62SHans Petter Selasky #ifdef SMP
1035a115fb62SHans Petter Selasky 	/*
1036a115fb62SHans Petter Selasky 	 * If the callout must migrate try to perform it immediately.
1037a115fb62SHans Petter Selasky 	 * If the callout is currently running, just defer the migration
1038a115fb62SHans Petter Selasky 	 * to a more appropriate moment.
1039a115fb62SHans Petter Selasky 	 */
1040a115fb62SHans Petter Selasky 	if (c->c_cpu != cpu) {
1041d2854fa4SRandall Stewart 		if (cc_exec_curr(cc, direct) == c) {
1042d2854fa4SRandall Stewart 			/*
1043d2854fa4SRandall Stewart 			 * Pending will have been removed since we are
1044d2854fa4SRandall Stewart 			 * actually executing the callout on another
1045d2854fa4SRandall Stewart 			 * CPU. That callout should be waiting on the
1046d2854fa4SRandall Stewart 			 * lock the caller holds. If we set both
1047d2854fa4SRandall Stewart 			 * active/and/pending after we return and the
1048d2854fa4SRandall Stewart 			 * lock on the executing callout proceeds, it
1049d2854fa4SRandall Stewart 			 * will then see pending is true and return.
1050d2854fa4SRandall Stewart 			 * At the return from the actual callout execution
1051d2854fa4SRandall Stewart 			 * the migration will occur in softclock_call_cc
1052d2854fa4SRandall Stewart 			 * and this new callout will be placed on the
1053d2854fa4SRandall Stewart 			 * new CPU via a call to callout_cpu_switch() which
1054d2854fa4SRandall Stewart 			 * will get the lock on the right CPU followed
1055d2854fa4SRandall Stewart 			 * by a call callout_cc_add() which will add it there.
1056d2854fa4SRandall Stewart 			 * (see above in softclock_call_cc()).
1057d2854fa4SRandall Stewart 			 */
1058d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = cpu;
1059d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = to_sbt;
1060d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = precision;
1061d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = ftn;
1062d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = arg;
106315b1eb14SRandall Stewart 			c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
106415b1eb14SRandall Stewart 			c->c_flags |= CALLOUT_ACTIVE;
1065a115fb62SHans Petter Selasky 			CTR6(KTR_CALLOUT,
1066a115fb62SHans Petter Selasky 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1067a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1068a115fb62SHans Petter Selasky 			    (u_int)(to_sbt & 0xffffffff), cpu);
1069a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1070a115fb62SHans Petter Selasky 			return (cancelled);
1071a115fb62SHans Petter Selasky 		}
1072a115fb62SHans Petter Selasky 		cc = callout_cpu_switch(c, cc, cpu);
1073a115fb62SHans Petter Selasky 	}
1074a115fb62SHans Petter Selasky #endif
1075a115fb62SHans Petter Selasky 
107666525b2dSRandall Stewart 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1077a115fb62SHans Petter Selasky 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1078a115fb62SHans Petter Selasky 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1079a115fb62SHans Petter Selasky 	    (u_int)(to_sbt & 0xffffffff));
1080a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
1081a115fb62SHans Petter Selasky 
1082a115fb62SHans Petter Selasky 	return (cancelled);
1083acc8326dSGarrett Wollman }
1084acc8326dSGarrett Wollman 
10856e0186d5SSam Leffler /*
10866e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
10876e0186d5SSam Leffler  */
10886e0186d5SSam Leffler int
10896e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
10906e0186d5SSam Leffler {
10916e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
10926e0186d5SSam Leffler }
10936e0186d5SSam Leffler 
10946e0186d5SSam Leffler int
10956e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
10966e0186d5SSam Leffler {
10976e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
10986e0186d5SSam Leffler }
10996e0186d5SSam Leffler 
11002c1bb207SColin Percival int
1101a8a03706SJohn Baldwin _callout_stop_safe(struct callout *c, int flags, callout_func_t *drain)
11022c1bb207SColin Percival {
1103a115fb62SHans Petter Selasky 	struct callout_cpu *cc, *old_cc;
1104a115fb62SHans Petter Selasky 	struct lock_class *class;
1105a115fb62SHans Petter Selasky 	int direct, sq_locked, use_lock;
110647e42809SGleb Smirnoff 	int cancelled, not_on_a_list;
11071283e9cdSAttilio Rao 
11085db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) != 0)
11099500dd9fSAdrian Chadd 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
11109500dd9fSAdrian Chadd 		    "calling %s", __func__);
11119500dd9fSAdrian Chadd 
11120d0053d7SHans Petter Selasky 	KASSERT((flags & CS_DRAIN) == 0 || drain == NULL,
11130d0053d7SHans Petter Selasky 	    ("Cannot set drain callback and CS_DRAIN flag at the same time"));
11140d0053d7SHans Petter Selasky 
11151283e9cdSAttilio Rao 	/*
1116a115fb62SHans Petter Selasky 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1117a115fb62SHans Petter Selasky 	 * so just discard this check for the moment.
11181283e9cdSAttilio Rao 	 */
11195db9ed80SKonstantin Belousov 	if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1120a115fb62SHans Petter Selasky 		if (c->c_lock == &Giant.lock_object)
1121a115fb62SHans Petter Selasky 			use_lock = mtx_owned(&Giant);
1122a115fb62SHans Petter Selasky 		else {
1123a115fb62SHans Petter Selasky 			use_lock = 1;
1124a115fb62SHans Petter Selasky 			class = LOCK_CLASS(c->c_lock);
1125a115fb62SHans Petter Selasky 			class->lc_assert(c->c_lock, LA_XLOCKED);
11261283e9cdSAttilio Rao 		}
1127a115fb62SHans Petter Selasky 	} else
1128a115fb62SHans Petter Selasky 		use_lock = 0;
112915b1eb14SRandall Stewart 	if (c->c_iflags & CALLOUT_DIRECT) {
113015b1eb14SRandall Stewart 		direct = 1;
113115b1eb14SRandall Stewart 	} else {
113215b1eb14SRandall Stewart 		direct = 0;
113315b1eb14SRandall Stewart 	}
1134a115fb62SHans Petter Selasky 	sq_locked = 0;
1135a115fb62SHans Petter Selasky 	old_cc = NULL;
1136a115fb62SHans Petter Selasky again:
1137a115fb62SHans Petter Selasky 	cc = callout_lock(c);
1138a115fb62SHans Petter Selasky 
113915b1eb14SRandall Stewart 	if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
114015b1eb14SRandall Stewart 	    (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
114115b1eb14SRandall Stewart 	    ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1142d2854fa4SRandall Stewart 		/*
1143d2854fa4SRandall Stewart 		 * Special case where this slipped in while we
1144d2854fa4SRandall Stewart 		 * were migrating *as* the callout is about to
1145d2854fa4SRandall Stewart 		 * execute. The caller probably holds the lock
1146d2854fa4SRandall Stewart 		 * the callout wants.
1147d2854fa4SRandall Stewart 		 *
1148d2854fa4SRandall Stewart 		 * Get rid of the migration first. Then set
1149d2854fa4SRandall Stewart 		 * the flag that tells this code *not* to
1150d2854fa4SRandall Stewart 		 * try to remove it from any lists (its not
1151d2854fa4SRandall Stewart 		 * on one yet). When the callout wheel runs,
1152d2854fa4SRandall Stewart 		 * it will ignore this callout.
1153d2854fa4SRandall Stewart 		 */
115415b1eb14SRandall Stewart 		c->c_iflags &= ~CALLOUT_PENDING;
115515b1eb14SRandall Stewart 		c->c_flags &= ~CALLOUT_ACTIVE;
1156d2854fa4SRandall Stewart 		not_on_a_list = 1;
1157d2854fa4SRandall Stewart 	} else {
1158d2854fa4SRandall Stewart 		not_on_a_list = 0;
1159d2854fa4SRandall Stewart 	}
1160d2854fa4SRandall Stewart 
1161a115fb62SHans Petter Selasky 	/*
1162a115fb62SHans Petter Selasky 	 * If the callout was migrating while the callout cpu lock was
1163a115fb62SHans Petter Selasky 	 * dropped,  just drop the sleepqueue lock and check the states
1164a115fb62SHans Petter Selasky 	 * again.
1165a115fb62SHans Petter Selasky 	 */
1166a115fb62SHans Petter Selasky 	if (sq_locked != 0 && cc != old_cc) {
1167a115fb62SHans Petter Selasky #ifdef SMP
1168a115fb62SHans Petter Selasky 		CC_UNLOCK(cc);
1169d2854fa4SRandall Stewart 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1170a115fb62SHans Petter Selasky 		sq_locked = 0;
1171a115fb62SHans Petter Selasky 		old_cc = NULL;
1172a115fb62SHans Petter Selasky 		goto again;
1173a115fb62SHans Petter Selasky #else
1174a115fb62SHans Petter Selasky 		panic("migration should not happen");
1175a115fb62SHans Petter Selasky #endif
1176a115fb62SHans Petter Selasky 	}
117747e42809SGleb Smirnoff 
1178a115fb62SHans Petter Selasky 	/*
117947e42809SGleb Smirnoff 	 * If the callout is running, try to stop it or drain it.
1180a115fb62SHans Petter Selasky 	 */
118147e42809SGleb Smirnoff 	if (cc_exec_curr(cc, direct) == c) {
1182a115fb62SHans Petter Selasky 		/*
118347e42809SGleb Smirnoff 		 * Succeed we to stop it or not, we must clear the
11847d88be4cSMark Johnston 		 * active flag - this is what API users expect.  If we're
11857d88be4cSMark Johnston 		 * draining and the callout is currently executing, first wait
11867d88be4cSMark Johnston 		 * until it finishes.
1187a115fb62SHans Petter Selasky 		 */
11887d88be4cSMark Johnston 		if ((flags & CS_DRAIN) == 0)
118918b4fd62SRandall Stewart 			c->c_flags &= ~CALLOUT_ACTIVE;
119047e42809SGleb Smirnoff 
11915db9ed80SKonstantin Belousov 		if ((flags & CS_DRAIN) != 0) {
1192a115fb62SHans Petter Selasky 			/*
1193a115fb62SHans Petter Selasky 			 * The current callout is running (or just
1194a115fb62SHans Petter Selasky 			 * about to run) and blocking is allowed, so
1195a115fb62SHans Petter Selasky 			 * just wait for the current invocation to
1196a115fb62SHans Petter Selasky 			 * finish.
1197a115fb62SHans Petter Selasky 			 */
1198a33fef5eSMark Johnston 			if (cc_exec_curr(cc, direct) == c) {
1199a115fb62SHans Petter Selasky 				/*
1200a115fb62SHans Petter Selasky 				 * Use direct calls to sleepqueue interface
1201a115fb62SHans Petter Selasky 				 * instead of cv/msleep in order to avoid
1202a115fb62SHans Petter Selasky 				 * a LOR between cc_lock and sleepqueue
1203a115fb62SHans Petter Selasky 				 * chain spinlocks.  This piece of code
1204a115fb62SHans Petter Selasky 				 * emulates a msleep_spin() call actually.
1205a115fb62SHans Petter Selasky 				 *
1206a115fb62SHans Petter Selasky 				 * If we already have the sleepqueue chain
1207a115fb62SHans Petter Selasky 				 * locked, then we can safely block.  If we
1208a115fb62SHans Petter Selasky 				 * don't already have it locked, however,
1209a115fb62SHans Petter Selasky 				 * we have to drop the cc_lock to lock
1210a115fb62SHans Petter Selasky 				 * it.  This opens several races, so we
1211a115fb62SHans Petter Selasky 				 * restart at the beginning once we have
1212a115fb62SHans Petter Selasky 				 * both locks.  If nothing has changed, then
1213a115fb62SHans Petter Selasky 				 * we will end up back here with sq_locked
1214a115fb62SHans Petter Selasky 				 * set.
1215a115fb62SHans Petter Selasky 				 */
1216a115fb62SHans Petter Selasky 				if (!sq_locked) {
1217a115fb62SHans Petter Selasky 					CC_UNLOCK(cc);
1218a115fb62SHans Petter Selasky 					sleepq_lock(
1219d2854fa4SRandall Stewart 					    &cc_exec_waiting(cc, direct));
1220a115fb62SHans Petter Selasky 					sq_locked = 1;
1221a115fb62SHans Petter Selasky 					old_cc = cc;
1222a115fb62SHans Petter Selasky 					goto again;
1223a115fb62SHans Petter Selasky 				}
122447e42809SGleb Smirnoff 
1225a115fb62SHans Petter Selasky 				/*
1226a115fb62SHans Petter Selasky 				 * Migration could be cancelled here, but
1227a115fb62SHans Petter Selasky 				 * as long as it is still not sure when it
1228a115fb62SHans Petter Selasky 				 * will be packed up, just let softclock()
1229a115fb62SHans Petter Selasky 				 * take care of it.
1230a115fb62SHans Petter Selasky 				 */
1231d2854fa4SRandall Stewart 				cc_exec_waiting(cc, direct) = true;
1232a115fb62SHans Petter Selasky 				DROP_GIANT();
1233a115fb62SHans Petter Selasky 				CC_UNLOCK(cc);
1234a115fb62SHans Petter Selasky 				sleepq_add(
1235d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1236a115fb62SHans Petter Selasky 				    &cc->cc_lock.lock_object, "codrain",
1237a115fb62SHans Petter Selasky 				    SLEEPQ_SLEEP, 0);
1238a115fb62SHans Petter Selasky 				sleepq_wait(
1239d2854fa4SRandall Stewart 				    &cc_exec_waiting(cc, direct),
1240a115fb62SHans Petter Selasky 					     0);
1241a115fb62SHans Petter Selasky 				sq_locked = 0;
1242a115fb62SHans Petter Selasky 				old_cc = NULL;
1243a115fb62SHans Petter Selasky 
1244a115fb62SHans Petter Selasky 				/* Reacquire locks previously released. */
1245a115fb62SHans Petter Selasky 				PICKUP_GIANT();
1246a33fef5eSMark Johnston 				goto again;
1247a115fb62SHans Petter Selasky 			}
12487d88be4cSMark Johnston 			c->c_flags &= ~CALLOUT_ACTIVE;
1249a115fb62SHans Petter Selasky 		} else if (use_lock &&
125018b4fd62SRandall Stewart 			   !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1251d2854fa4SRandall Stewart 
1252a115fb62SHans Petter Selasky 			/*
1253a115fb62SHans Petter Selasky 			 * The current callout is waiting for its
1254a115fb62SHans Petter Selasky 			 * lock which we hold.  Cancel the callout
1255a115fb62SHans Petter Selasky 			 * and return.  After our caller drops the
1256a115fb62SHans Petter Selasky 			 * lock, the callout will be skipped in
125718b4fd62SRandall Stewart 			 * softclock(). This *only* works with a
125818b4fd62SRandall Stewart 			 * callout_stop() *not* callout_drain() or
125918b4fd62SRandall Stewart 			 * callout_async_drain().
1260a115fb62SHans Petter Selasky 			 */
1261d2854fa4SRandall Stewart 			cc_exec_cancel(cc, direct) = true;
1262a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1263a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
1264a115fb62SHans Petter Selasky 			KASSERT(!cc_cce_migrating(cc, direct),
1265a115fb62SHans Petter Selasky 			    ("callout wrongly scheduled for migration"));
126615b1eb14SRandall Stewart 			if (callout_migrating(c)) {
126715b1eb14SRandall Stewart 				c->c_iflags &= ~CALLOUT_DFRMIGRATION;
126815b1eb14SRandall Stewart #ifdef SMP
126915b1eb14SRandall Stewart 				cc_migration_cpu(cc, direct) = CPUBLOCK;
127015b1eb14SRandall Stewart 				cc_migration_time(cc, direct) = 0;
127115b1eb14SRandall Stewart 				cc_migration_prec(cc, direct) = 0;
127215b1eb14SRandall Stewart 				cc_migration_func(cc, direct) = NULL;
127315b1eb14SRandall Stewart 				cc_migration_arg(cc, direct) = NULL;
127415b1eb14SRandall Stewart #endif
127515b1eb14SRandall Stewart 			}
1276a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
1277a115fb62SHans Petter Selasky 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1278a115fb62SHans Petter Selasky 			return (1);
1279d2854fa4SRandall Stewart 		} else if (callout_migrating(c)) {
1280d2854fa4SRandall Stewart 			/*
1281d2854fa4SRandall Stewart 			 * The callout is currently being serviced
1282d2854fa4SRandall Stewart 			 * and the "next" callout is scheduled at
1283d2854fa4SRandall Stewart 			 * its completion with a migration. We remove
1284d2854fa4SRandall Stewart 			 * the migration flag so it *won't* get rescheduled,
1285d2854fa4SRandall Stewart 			 * but we can't stop the one thats running so
1286d2854fa4SRandall Stewart 			 * we return 0.
1287d2854fa4SRandall Stewart 			 */
128815b1eb14SRandall Stewart 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1289d2854fa4SRandall Stewart #ifdef SMP
1290d2854fa4SRandall Stewart 			/*
1291d2854fa4SRandall Stewart 			 * We can't call cc_cce_cleanup here since
1292d2854fa4SRandall Stewart 			 * if we do it will remove .ce_curr and
1293d2854fa4SRandall Stewart 			 * its still running. This will prevent a
1294d2854fa4SRandall Stewart 			 * reschedule of the callout when the
1295d2854fa4SRandall Stewart 			 * execution completes.
1296d2854fa4SRandall Stewart 			 */
1297d2854fa4SRandall Stewart 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1298d2854fa4SRandall Stewart 			cc_migration_time(cc, direct) = 0;
1299d2854fa4SRandall Stewart 			cc_migration_prec(cc, direct) = 0;
1300d2854fa4SRandall Stewart 			cc_migration_func(cc, direct) = NULL;
1301d2854fa4SRandall Stewart 			cc_migration_arg(cc, direct) = NULL;
1302d2854fa4SRandall Stewart #endif
1303a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1304a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
130518b4fd62SRandall Stewart  			if (drain) {
1306624677faSHans Petter Selasky 				KASSERT(cc_exec_drain(cc, direct) == NULL,
1307624677faSHans Petter Selasky 				    ("callout drain function already set to %p",
1308624677faSHans Petter Selasky 				    cc_exec_drain(cc, direct)));
130918b4fd62SRandall Stewart 				cc_exec_drain(cc, direct) = drain;
131018b4fd62SRandall Stewart 			}
1311a115fb62SHans Petter Selasky 			CC_UNLOCK(cc);
13127524994dSMark Johnston 			return (0);
13130d0053d7SHans Petter Selasky 		} else {
1314a115fb62SHans Petter Selasky 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1315a115fb62SHans Petter Selasky 			    c, c->c_func, c->c_arg);
131618b4fd62SRandall Stewart 			if (drain) {
1317624677faSHans Petter Selasky 				KASSERT(cc_exec_drain(cc, direct) == NULL,
1318624677faSHans Petter Selasky 				    ("callout drain function already set to %p",
1319624677faSHans Petter Selasky 				    cc_exec_drain(cc, direct)));
132018b4fd62SRandall Stewart 				cc_exec_drain(cc, direct) = drain;
132118b4fd62SRandall Stewart 			}
13220d0053d7SHans Petter Selasky 		}
13233d84a188SRandall Stewart 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
13247524994dSMark Johnston 		cancelled = 0;
132547e42809SGleb Smirnoff 	} else
132647e42809SGleb Smirnoff 		cancelled = 1;
132747e42809SGleb Smirnoff 
13283d84a188SRandall Stewart 	if (sq_locked)
13293d84a188SRandall Stewart 		sleepq_release(&cc_exec_waiting(cc, direct));
1330d153eeeeSGleb Smirnoff 
133147e42809SGleb Smirnoff 	if ((c->c_iflags & CALLOUT_PENDING) == 0) {
133247e42809SGleb Smirnoff 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
133347e42809SGleb Smirnoff 		    c, c->c_func, c->c_arg);
13349f339124SGleb Smirnoff 		/*
13359f339124SGleb Smirnoff 		 * For not scheduled and not executing callout return
13369f339124SGleb Smirnoff 		 * negative value.
13379f339124SGleb Smirnoff 		 */
13389f339124SGleb Smirnoff 		if (cc_exec_curr(cc, direct) != c)
13399f339124SGleb Smirnoff 			cancelled = -1;
134047e42809SGleb Smirnoff 		CC_UNLOCK(cc);
13419f339124SGleb Smirnoff 		return (cancelled);
134247e42809SGleb Smirnoff 	}
134347e42809SGleb Smirnoff 
134415b1eb14SRandall Stewart 	c->c_iflags &= ~CALLOUT_PENDING;
134515b1eb14SRandall Stewart 	c->c_flags &= ~CALLOUT_ACTIVE;
13461283e9cdSAttilio Rao 
134768a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
134868a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
1349d2854fa4SRandall Stewart 	if (not_on_a_list == 0) {
135015b1eb14SRandall Stewart 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
135166525b2dSRandall Stewart 			if (cc_exec_next(cc) == c)
135266525b2dSRandall Stewart 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1353a115fb62SHans Petter Selasky 			LIST_REMOVE(c, c_links.le);
135415b1eb14SRandall Stewart 		} else {
1355a115fb62SHans Petter Selasky 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1356d2854fa4SRandall Stewart 		}
135715b1eb14SRandall Stewart 	}
1358a115fb62SHans Petter Selasky 	CC_UNLOCK(cc);
135947e42809SGleb Smirnoff 	return (cancelled);
1360acc8326dSGarrett Wollman }
1361acc8326dSGarrett Wollman 
1362acc8326dSGarrett Wollman void
1363e392e44cSDavide Italiano callout_init(struct callout *c, int mpsafe)
1364acc8326dSGarrett Wollman {
1365a115fb62SHans Petter Selasky 	bzero(c, sizeof *c);
136698c926b2SIan Dowse 	if (mpsafe) {
1367a115fb62SHans Petter Selasky 		c->c_lock = NULL;
136815b1eb14SRandall Stewart 		c->c_iflags = CALLOUT_RETURNUNLOCKED;
136998c926b2SIan Dowse 	} else {
1370a115fb62SHans Petter Selasky 		c->c_lock = &Giant.lock_object;
137115b1eb14SRandall Stewart 		c->c_iflags = 0;
137298c926b2SIan Dowse 	}
13734b28d96eSJohn Baldwin 	c->c_cpu = cc_default_cpu;
137498c926b2SIan Dowse }
137598c926b2SIan Dowse 
137698c926b2SIan Dowse void
1377e392e44cSDavide Italiano _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
137898c926b2SIan Dowse {
137998c926b2SIan Dowse 	bzero(c, sizeof *c);
138064b9ee20SAttilio Rao 	c->c_lock = lock;
1381a115fb62SHans Petter Selasky 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1382a115fb62SHans Petter Selasky 	    ("callout_init_lock: bad flags %d", flags));
1383a115fb62SHans Petter Selasky 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1384a115fb62SHans Petter Selasky 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
13854730a897SAlexander Motin 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags & LC_SLEEPABLE),
13864730a897SAlexander Motin 	    ("%s: callout %p has sleepable lock", __func__, c));
138715b1eb14SRandall Stewart 	c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
13884b28d96eSJohn Baldwin 	c->c_cpu = cc_default_cpu;
1389acc8326dSGarrett Wollman }
1390acc8326dSGarrett Wollman 
13915b999a6bSDavide Italiano static int
13925b999a6bSDavide Italiano flssbt(sbintime_t sbt)
13935b999a6bSDavide Italiano {
13945b999a6bSDavide Italiano 
13955b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
13965b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
13975b999a6bSDavide Italiano 		return (flsl(sbt));
13985b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
13995b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
14005b999a6bSDavide Italiano 	return (flsl(sbt));
14015b999a6bSDavide Italiano }
14025b999a6bSDavide Italiano 
14035b999a6bSDavide Italiano /*
14045b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
14055b999a6bSDavide Italiano  */
14065b999a6bSDavide Italiano static int
14075b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
14085b999a6bSDavide Italiano {
14095b999a6bSDavide Italiano 	struct callout *tmp;
14105b999a6bSDavide Italiano 	struct callout_cpu *cc;
14115b999a6bSDavide Italiano 	struct callout_list *sc;
14125b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
14135b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
14145b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
14155b999a6bSDavide Italiano 	int cpu;
14165b999a6bSDavide Italiano 
14175b999a6bSDavide Italiano 	val = 0;
14185b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
14195b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
14205b999a6bSDavide Italiano 		return (error);
14215b999a6bSDavide Italiano 	count = maxc = 0;
14225b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
14235b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
14245b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
14255b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
14265b999a6bSDavide Italiano 	now = sbinuptime();
14275b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
14285b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
14295b999a6bSDavide Italiano 		CC_LOCK(cc);
14305b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
14315b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
14325b999a6bSDavide Italiano 			c = 0;
14335b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
14345b999a6bSDavide Italiano 				c++;
14355b999a6bSDavide Italiano 				t = tmp->c_time - now;
14365b999a6bSDavide Italiano 				if (t < 0)
14375b999a6bSDavide Italiano 					t = 0;
14385b999a6bSDavide Italiano 				st += t / SBT_1US;
14395b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
14405b999a6bSDavide Italiano 				if (t > maxt)
14415b999a6bSDavide Italiano 					maxt = t;
14425b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
14435b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
14445b999a6bSDavide Italiano 				ct[flssbt(t)]++;
14455b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
14465b999a6bSDavide Italiano 			}
14475b999a6bSDavide Italiano 			if (c > maxc)
14485b999a6bSDavide Italiano 				maxc = c;
14495b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
14505b999a6bSDavide Italiano 			count += c;
14515b999a6bSDavide Italiano 		}
14525b999a6bSDavide Italiano 		CC_UNLOCK(cc);
14535b999a6bSDavide Italiano 	}
14545b999a6bSDavide Italiano 
14555b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
14565b999a6bSDavide Italiano 		tcum += ct[i];
14575b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14585b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
14595b999a6bSDavide Italiano 		pcum += cpr[i];
14605b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14615b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
14625b999a6bSDavide Italiano 		c += ccpbk[i];
14635b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
14645b999a6bSDavide Italiano 
14655b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
14665b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
14675b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
14685b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
14695b999a6bSDavide Italiano 	    medc,
14705b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
14715b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
14725b999a6bSDavide Italiano 	    maxc);
14735b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14745b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
14755b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
14765b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
14775b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14785b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
14795b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
14805b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
14815b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
14825b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
14835b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
14845b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
14855b999a6bSDavide Italiano 			continue;
14865b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
14875b999a6bSDavide Italiano 		tcum += ct[i];
14885b999a6bSDavide Italiano 		pcum += cpr[i];
14895b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
14905b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
14915b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
14925b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
14935b999a6bSDavide Italiano 	}
14945b999a6bSDavide Italiano 	return (error);
14955b999a6bSDavide Italiano }
14965b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
14975b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
14985b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
14995b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
150047e42809SGleb Smirnoff 
15013af72c11SBjoern A. Zeeb #ifdef DDB
15023af72c11SBjoern A. Zeeb static void
15033af72c11SBjoern A. Zeeb _show_callout(struct callout *c)
15043af72c11SBjoern A. Zeeb {
15053af72c11SBjoern A. Zeeb 
15063af72c11SBjoern A. Zeeb 	db_printf("callout %p\n", c);
15073af72c11SBjoern A. Zeeb #define	C_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, c->e);
15083af72c11SBjoern A. Zeeb 	db_printf("   &c_links = %p\n", &(c->c_links));
15093af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_time);
15103af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%" PRId64,	c_precision);
15113af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_arg);
15123af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_func);
15133af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%p",	c_lock);
15143af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_flags);
15153af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%#x",	c_iflags);
15163af72c11SBjoern A. Zeeb 	C_DB_PRINTF("%d",	c_cpu);
15173af72c11SBjoern A. Zeeb #undef	C_DB_PRINTF
15183af72c11SBjoern A. Zeeb }
15193af72c11SBjoern A. Zeeb 
15203af72c11SBjoern A. Zeeb DB_SHOW_COMMAND(callout, db_show_callout)
15213af72c11SBjoern A. Zeeb {
15223af72c11SBjoern A. Zeeb 
15233af72c11SBjoern A. Zeeb 	if (!have_addr) {
15243af72c11SBjoern A. Zeeb 		db_printf("usage: show callout <struct callout *>\n");
15253af72c11SBjoern A. Zeeb 		return;
15263af72c11SBjoern A. Zeeb 	}
15273af72c11SBjoern A. Zeeb 
15283af72c11SBjoern A. Zeeb 	_show_callout((struct callout *)addr);
15293af72c11SBjoern A. Zeeb }
15308c5a9161SEric van Gyzen 
15318c5a9161SEric van Gyzen static void
15328c5a9161SEric van Gyzen _show_last_callout(int cpu, int direct, const char *dirstr)
15338c5a9161SEric van Gyzen {
15348c5a9161SEric van Gyzen 	struct callout_cpu *cc;
15358c5a9161SEric van Gyzen 	void *func, *arg;
15368c5a9161SEric van Gyzen 
15378c5a9161SEric van Gyzen 	cc = CC_CPU(cpu);
15388c5a9161SEric van Gyzen 	func = cc_exec_last_func(cc, direct);
15398c5a9161SEric van Gyzen 	arg = cc_exec_last_arg(cc, direct);
15408c5a9161SEric van Gyzen 	db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
15418c5a9161SEric van Gyzen 	db_printsym((db_expr_t)func, DB_STGY_ANY);
15428c5a9161SEric van Gyzen 	db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
15438c5a9161SEric van Gyzen }
15448c5a9161SEric van Gyzen 
15458c5a9161SEric van Gyzen DB_SHOW_COMMAND(callout_last, db_show_callout_last)
15468c5a9161SEric van Gyzen {
15478c5a9161SEric van Gyzen 	int cpu, last;
15488c5a9161SEric van Gyzen 
15498c5a9161SEric van Gyzen 	if (have_addr) {
15508c5a9161SEric van Gyzen 		if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
15518c5a9161SEric van Gyzen 			db_printf("no such cpu: %d\n", (int)addr);
15528c5a9161SEric van Gyzen 			return;
15538c5a9161SEric van Gyzen 		}
15548c5a9161SEric van Gyzen 		cpu = last = addr;
15558c5a9161SEric van Gyzen 	} else {
15568c5a9161SEric van Gyzen 		cpu = 0;
15578c5a9161SEric van Gyzen 		last = mp_maxid;
15588c5a9161SEric van Gyzen 	}
15598c5a9161SEric van Gyzen 
15608c5a9161SEric van Gyzen 	while (cpu <= last) {
15618c5a9161SEric van Gyzen 		if (!CPU_ABSENT(cpu)) {
15628c5a9161SEric van Gyzen 			_show_last_callout(cpu, 0, "");
15638c5a9161SEric van Gyzen 			_show_last_callout(cpu, 1, " direct");
15648c5a9161SEric van Gyzen 		}
15658c5a9161SEric van Gyzen 		cpu++;
15668c5a9161SEric van Gyzen 	}
15678c5a9161SEric van Gyzen }
15683af72c11SBjoern A. Zeeb #endif /* DDB */
1569