xref: /freebsd/sys/kern/kern_timeout.c (revision 232e8b52b0d56a5b483ab233bbd0186ca954e127)
1df8bae1dSRodney W. Grimes /*-
2df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1991, 1993
3df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
5df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
6df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
7df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
9df8bae1dSRodney W. Grimes  *
10df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
11df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
12df8bae1dSRodney W. Grimes  * are met:
13df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
15df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
17df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
18df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
19df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
20df8bae1dSRodney W. Grimes  *    without specific prior written permission.
21df8bae1dSRodney W. Grimes  *
22df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
33df8bae1dSRodney W. Grimes  *
34acc8326dSGarrett Wollman  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
37677b542eSDavid E. O'Brien #include <sys/cdefs.h>
38677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
39677b542eSDavid E. O'Brien 
405b999a6bSDavide Italiano #include "opt_callout_profiling.h"
415b999a6bSDavide Italiano #if defined(__arm__)
425b999a6bSDavide Italiano #include "opt_timer.h"
435b999a6bSDavide Italiano #endif
44c445c3c7SAdrian Chadd #include "opt_rss.h"
4591dd9aaeSRobert Watson 
46df8bae1dSRodney W. Grimes #include <sys/param.h>
47df8bae1dSRodney W. Grimes #include <sys/systm.h>
488d809d50SJeff Roberson #include <sys/bus.h>
4915b7a470SPoul-Henning Kamp #include <sys/callout.h>
50f8ccf82aSAndre Oppermann #include <sys/file.h>
518d809d50SJeff Roberson #include <sys/interrupt.h>
52df8bae1dSRodney W. Grimes #include <sys/kernel.h>
53ff7ec58aSRobert Watson #include <sys/ktr.h>
54f34fa851SJohn Baldwin #include <sys/lock.h>
558d809d50SJeff Roberson #include <sys/malloc.h>
56cb799bfeSJohn Baldwin #include <sys/mutex.h>
5721f9e816SJohn Baldwin #include <sys/proc.h>
5891dd9aaeSRobert Watson #include <sys/sdt.h>
596a0ce57dSAttilio Rao #include <sys/sleepqueue.h>
6022ee8c4fSPoul-Henning Kamp #include <sys/sysctl.h>
618d809d50SJeff Roberson #include <sys/smp.h>
62df8bae1dSRodney W. Grimes 
631283e9cdSAttilio Rao #ifdef SMP
641283e9cdSAttilio Rao #include <machine/cpu.h>
651283e9cdSAttilio Rao #endif
661283e9cdSAttilio Rao 
675b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
685b999a6bSDavide Italiano DPCPU_DECLARE(sbintime_t, hardclocktime);
695b999a6bSDavide Italiano #endif
705b999a6bSDavide Italiano 
7191dd9aaeSRobert Watson SDT_PROVIDER_DEFINE(callout_execute);
72d9fae5abSAndriy Gapon SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__start,
7391dd9aaeSRobert Watson     "struct callout *");
74d9fae5abSAndriy Gapon SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__end,
7591dd9aaeSRobert Watson     "struct callout *");
7691dd9aaeSRobert Watson 
775b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7822ee8c4fSPoul-Henning Kamp static int avg_depth;
7922ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8022ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
8122ee8c4fSPoul-Henning Kamp static int avg_gcalls;
8222ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
8322ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
8464b9ee20SAttilio Rao static int avg_lockcalls;
8564b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
8664b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
8722ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
8822ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
8922ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
905b999a6bSDavide Italiano static int avg_depth_dir;
915b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
925b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
935b999a6bSDavide Italiano     "Units = 1/1000");
945b999a6bSDavide Italiano static int avg_lockcalls_dir;
955b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
965b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
975b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
985b999a6bSDavide Italiano static int avg_mpcalls_dir;
995b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1005b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1015b999a6bSDavide Italiano     "Units = 1/1000");
1025b999a6bSDavide Italiano #endif
103f8ccf82aSAndre Oppermann 
104f8ccf82aSAndre Oppermann static int ncallout;
105af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &ncallout, 0,
106f8ccf82aSAndre Oppermann     "Number of entries in callwheel and size of timeout() preallocation");
107f8ccf82aSAndre Oppermann 
108c445c3c7SAdrian Chadd #ifdef	RSS
109c445c3c7SAdrian Chadd static int pin_default_swi = 1;
110c445c3c7SAdrian Chadd static int pin_pcpu_swi = 1;
111c445c3c7SAdrian Chadd #else
112ac75ee9fSAdrian Chadd static int pin_default_swi = 0;
113ac75ee9fSAdrian Chadd static int pin_pcpu_swi = 0;
114c445c3c7SAdrian Chadd #endif
115ac75ee9fSAdrian Chadd 
116af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_default_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_default_swi,
117ac75ee9fSAdrian Chadd     0, "Pin the default (non-per-cpu) swi (shared with PCPU 0 swi)");
118af3b2549SHans Petter Selasky SYSCTL_INT(_kern, OID_AUTO, pin_pcpu_swi, CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &pin_pcpu_swi,
119ac75ee9fSAdrian Chadd     0, "Pin the per-CPU swis (except PCPU 0, which is also default");
120ac75ee9fSAdrian Chadd 
12115b7a470SPoul-Henning Kamp /*
12215b7a470SPoul-Henning Kamp  * TODO:
12315b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
12415b7a470SPoul-Henning Kamp  */
1253f555c45SDavide Italiano u_int callwheelsize, callwheelmask;
126f23b4c91SGarrett Wollman 
12720c510f8SLuigi Rizzo /*
1285b999a6bSDavide Italiano  * The callout cpu exec entities represent informations necessary for
1295b999a6bSDavide Italiano  * describing the state of callouts currently running on the CPU and the ones
1305b999a6bSDavide Italiano  * necessary for migrating callouts to the new callout cpu. In particular,
1315b999a6bSDavide Italiano  * the first entry of the array cc_exec_entity holds informations for callout
1325b999a6bSDavide Italiano  * running in SWI thread context, while the second one holds informations
1335b999a6bSDavide Italiano  * for callout running directly from hardware interrupt context.
1341283e9cdSAttilio Rao  * The cached informations are very important for deferring migration when
1351283e9cdSAttilio Rao  * the migrating callout is already running.
1361283e9cdSAttilio Rao  */
1375b999a6bSDavide Italiano struct cc_exec {
1385b999a6bSDavide Italiano 	struct callout		*cc_next;
1395b999a6bSDavide Italiano 	struct callout		*cc_curr;
1401283e9cdSAttilio Rao #ifdef SMP
1411283e9cdSAttilio Rao 	void			(*ce_migration_func)(void *);
1421283e9cdSAttilio Rao 	void			*ce_migration_arg;
1431283e9cdSAttilio Rao 	int			ce_migration_cpu;
1445b999a6bSDavide Italiano 	sbintime_t		ce_migration_time;
1453f321a4eSDavide Italiano 	sbintime_t		ce_migration_prec;
1461283e9cdSAttilio Rao #endif
147a4a3ce99SDavide Italiano 	bool			cc_cancel;
148a4a3ce99SDavide Italiano 	bool			cc_waiting;
1491283e9cdSAttilio Rao };
1501283e9cdSAttilio Rao 
1511283e9cdSAttilio Rao /*
15220c510f8SLuigi Rizzo  * There is one struct callout_cpu per cpu, holding all relevant
15320c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
15420c510f8SLuigi Rizzo  */
1558d809d50SJeff Roberson struct callout_cpu {
1564ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1575b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
1588d809d50SJeff Roberson 	struct callout		*cc_callout;
1595b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1605b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1615b999a6bSDavide Italiano 	struct callout_slist	cc_callfree;
1625b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1635b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
1648d809d50SJeff Roberson 	void			*cc_cookie;
1655b999a6bSDavide Italiano 	u_int			cc_bucket;
166*232e8b52SJohn Baldwin 	char			cc_ktr_event_name[20];
1678d809d50SJeff Roberson };
1688d809d50SJeff Roberson 
1695b999a6bSDavide Italiano #define	cc_exec_curr		cc_exec_entity[0].cc_curr
1705b999a6bSDavide Italiano #define	cc_exec_next		cc_exec_entity[0].cc_next
1715b999a6bSDavide Italiano #define	cc_exec_cancel		cc_exec_entity[0].cc_cancel
1725b999a6bSDavide Italiano #define	cc_exec_waiting		cc_exec_entity[0].cc_waiting
1735b999a6bSDavide Italiano #define	cc_exec_curr_dir	cc_exec_entity[1].cc_curr
1745b999a6bSDavide Italiano #define	cc_exec_next_dir	cc_exec_entity[1].cc_next
1755b999a6bSDavide Italiano #define	cc_exec_cancel_dir	cc_exec_entity[1].cc_cancel
1765b999a6bSDavide Italiano #define	cc_exec_waiting_dir	cc_exec_entity[1].cc_waiting
1775b999a6bSDavide Italiano 
1788d809d50SJeff Roberson #ifdef SMP
1795b999a6bSDavide Italiano #define	cc_migration_func	cc_exec_entity[0].ce_migration_func
1805b999a6bSDavide Italiano #define	cc_migration_arg	cc_exec_entity[0].ce_migration_arg
1815b999a6bSDavide Italiano #define	cc_migration_cpu	cc_exec_entity[0].ce_migration_cpu
1825b999a6bSDavide Italiano #define	cc_migration_time	cc_exec_entity[0].ce_migration_time
1833f321a4eSDavide Italiano #define	cc_migration_prec	cc_exec_entity[0].ce_migration_prec
1845b999a6bSDavide Italiano #define	cc_migration_func_dir	cc_exec_entity[1].ce_migration_func
1855b999a6bSDavide Italiano #define	cc_migration_arg_dir	cc_exec_entity[1].ce_migration_arg
1865b999a6bSDavide Italiano #define	cc_migration_cpu_dir	cc_exec_entity[1].ce_migration_cpu
1875b999a6bSDavide Italiano #define	cc_migration_time_dir	cc_exec_entity[1].ce_migration_time
1883f321a4eSDavide Italiano #define	cc_migration_prec_dir	cc_exec_entity[1].ce_migration_prec
1891283e9cdSAttilio Rao 
1908d809d50SJeff Roberson struct callout_cpu cc_cpu[MAXCPU];
1911283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
1928d809d50SJeff Roberson #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
1938d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
1948d809d50SJeff Roberson #else
1958d809d50SJeff Roberson struct callout_cpu cc_cpu;
1968d809d50SJeff Roberson #define	CC_CPU(cpu)	&cc_cpu
1978d809d50SJeff Roberson #define	CC_SELF()	&cc_cpu
1988d809d50SJeff Roberson #endif
1998d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
2008d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
2011283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
2028d809d50SJeff Roberson 
2038d809d50SJeff Roberson static int timeout_cpu;
2045b999a6bSDavide Italiano 
205*232e8b52SJohn Baldwin static void	callout_cpu_init(struct callout_cpu *cc, int cpu);
2065b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
2075b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
2085b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
2095b999a6bSDavide Italiano #endif
2105b999a6bSDavide Italiano 		    int direct);
2118d809d50SJeff Roberson 
212d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
21349a74476SColin Percival 
214e9dec2c4SColin Percival /**
2158d809d50SJeff Roberson  * Locked by cc_lock:
2165b999a6bSDavide Italiano  *   cc_curr         - If a callout is in progress, it is cc_curr.
2175b999a6bSDavide Italiano  *                     If cc_curr is non-NULL, threads waiting in
218b36f4588SJohn Baldwin  *                     callout_drain() will be woken up as soon as the
2192c1bb207SColin Percival  *                     relevant callout completes.
2205b999a6bSDavide Italiano  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
22198c926b2SIan Dowse  *                     guarantees that the current callout will not run.
22298c926b2SIan Dowse  *                     The softclock() function sets this to 0 before it
22364b9ee20SAttilio Rao  *                     drops callout_lock to acquire c_lock, and it calls
224b36f4588SJohn Baldwin  *                     the handler only if curr_cancelled is still 0 after
2255b999a6bSDavide Italiano  *                     cc_lock is successfully acquired.
2268d809d50SJeff Roberson  *   cc_waiting      - If a thread is waiting in callout_drain(), then
227b36f4588SJohn Baldwin  *                     callout_wait is nonzero.  Set only when
2285b999a6bSDavide Italiano  *                     cc_curr is non-NULL.
2292c1bb207SColin Percival  */
230df8bae1dSRodney W. Grimes 
231df8bae1dSRodney W. Grimes /*
2325b999a6bSDavide Italiano  * Resets the execution entity tied to a specific callout cpu.
2331283e9cdSAttilio Rao  */
2341283e9cdSAttilio Rao static void
2355b999a6bSDavide Italiano cc_cce_cleanup(struct callout_cpu *cc, int direct)
2361283e9cdSAttilio Rao {
2371283e9cdSAttilio Rao 
2385b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_curr = NULL;
2395b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_next = NULL;
240ac42a172SDavide Italiano 	cc->cc_exec_entity[direct].cc_cancel = false;
241ac42a172SDavide Italiano 	cc->cc_exec_entity[direct].cc_waiting = false;
2421283e9cdSAttilio Rao #ifdef SMP
2435b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_cpu = CPUBLOCK;
2445b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_time = 0;
2453f321a4eSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_prec = 0;
2465b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_func = NULL;
2475b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_arg = NULL;
2481283e9cdSAttilio Rao #endif
2491283e9cdSAttilio Rao }
2501283e9cdSAttilio Rao 
2511283e9cdSAttilio Rao /*
2521283e9cdSAttilio Rao  * Checks if migration is requested by a specific callout cpu.
2531283e9cdSAttilio Rao  */
2541283e9cdSAttilio Rao static int
2555b999a6bSDavide Italiano cc_cce_migrating(struct callout_cpu *cc, int direct)
2561283e9cdSAttilio Rao {
2571283e9cdSAttilio Rao 
2581283e9cdSAttilio Rao #ifdef SMP
2595b999a6bSDavide Italiano 	return (cc->cc_exec_entity[direct].ce_migration_cpu != CPUBLOCK);
2601283e9cdSAttilio Rao #else
2611283e9cdSAttilio Rao 	return (0);
2621283e9cdSAttilio Rao #endif
2631283e9cdSAttilio Rao }
2641283e9cdSAttilio Rao 
2651283e9cdSAttilio Rao /*
26615ae0c9aSAndre Oppermann  * Kernel low level callwheel initialization
26715ae0c9aSAndre Oppermann  * called on cpu0 during kernel startup.
268219d632cSMatthew Dillon  */
26915ae0c9aSAndre Oppermann static void
27015ae0c9aSAndre Oppermann callout_callwheel_init(void *dummy)
271219d632cSMatthew Dillon {
2728d809d50SJeff Roberson 	struct callout_cpu *cc;
2738d809d50SJeff Roberson 
274f8ccf82aSAndre Oppermann 	/*
275f8ccf82aSAndre Oppermann 	 * Calculate the size of the callout wheel and the preallocated
276f8ccf82aSAndre Oppermann 	 * timeout() structures.
277a7aea132SAndre Oppermann 	 * XXX: Clip callout to result of previous function of maxusers
278a7aea132SAndre Oppermann 	 * maximum 384.  This is still huge, but acceptable.
279f8ccf82aSAndre Oppermann 	 */
280f8ccf82aSAndre Oppermann 	ncallout = imin(16 + maxproc + maxfiles, 18508);
281f8ccf82aSAndre Oppermann 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
282f8ccf82aSAndre Oppermann 
283219d632cSMatthew Dillon 	/*
284922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
285922314f0SAlfred Perlstein 	 * than 'ncallout'.
286219d632cSMatthew Dillon 	 */
287922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
288219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
289219d632cSMatthew Dillon 
29015ae0c9aSAndre Oppermann 	/*
291ac75ee9fSAdrian Chadd 	 * Fetch whether we're pinning the swi's or not.
292ac75ee9fSAdrian Chadd 	 */
293ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_default_swi", &pin_default_swi);
294ac75ee9fSAdrian Chadd 	TUNABLE_INT_FETCH("kern.pin_pcpu_swi", &pin_pcpu_swi);
295ac75ee9fSAdrian Chadd 
296ac75ee9fSAdrian Chadd 	/*
29715ae0c9aSAndre Oppermann 	 * Only cpu0 handles timeout(9) and receives a preallocation.
29815ae0c9aSAndre Oppermann 	 *
29915ae0c9aSAndre Oppermann 	 * XXX: Once all timeout(9) consumers are converted this can
30015ae0c9aSAndre Oppermann 	 * be removed.
30115ae0c9aSAndre Oppermann 	 */
30215ae0c9aSAndre Oppermann 	timeout_cpu = PCPU_GET(cpuid);
30315ae0c9aSAndre Oppermann 	cc = CC_CPU(timeout_cpu);
30415ae0c9aSAndre Oppermann 	cc->cc_callout = malloc(ncallout * sizeof(struct callout),
30515ae0c9aSAndre Oppermann 	    M_CALLOUT, M_WAITOK);
306*232e8b52SJohn Baldwin 	callout_cpu_init(cc, timeout_cpu);
307219d632cSMatthew Dillon }
30815ae0c9aSAndre Oppermann SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
309219d632cSMatthew Dillon 
31015ae0c9aSAndre Oppermann /*
31115ae0c9aSAndre Oppermann  * Initialize the per-cpu callout structures.
31215ae0c9aSAndre Oppermann  */
3138d809d50SJeff Roberson static void
314*232e8b52SJohn Baldwin callout_cpu_init(struct callout_cpu *cc, int cpu)
3158d809d50SJeff Roberson {
3168d809d50SJeff Roberson 	struct callout *c;
3178d809d50SJeff Roberson 	int i;
3188d809d50SJeff Roberson 
3198d809d50SJeff Roberson 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
3208d809d50SJeff Roberson 	SLIST_INIT(&cc->cc_callfree);
321c5904471SDavide Italiano 	cc->cc_callwheel = malloc(sizeof(struct callout_list) * callwheelsize,
32215ae0c9aSAndre Oppermann 	    M_CALLOUT, M_WAITOK);
3235b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
3245b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
3255b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
3264bc38a5aSDavide Italiano 	cc->cc_firstevent = SBT_MAX;
3275b999a6bSDavide Italiano 	for (i = 0; i < 2; i++)
3285b999a6bSDavide Italiano 		cc_cce_cleanup(cc, i);
329*232e8b52SJohn Baldwin 	snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
330*232e8b52SJohn Baldwin 	    "callwheel cpu %d", cpu);
33115ae0c9aSAndre Oppermann 	if (cc->cc_callout == NULL)	/* Only cpu0 handles timeout(9) */
3328d809d50SJeff Roberson 		return;
3338d809d50SJeff Roberson 	for (i = 0; i < ncallout; i++) {
3348d809d50SJeff Roberson 		c = &cc->cc_callout[i];
3358d809d50SJeff Roberson 		callout_init(c, 0);
3368d809d50SJeff Roberson 		c->c_flags = CALLOUT_LOCAL_ALLOC;
3378d809d50SJeff Roberson 		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
3388d809d50SJeff Roberson 	}
3398d809d50SJeff Roberson }
3408d809d50SJeff Roberson 
3411283e9cdSAttilio Rao #ifdef SMP
3421283e9cdSAttilio Rao /*
3431283e9cdSAttilio Rao  * Switches the cpu tied to a specific callout.
3441283e9cdSAttilio Rao  * The function expects a locked incoming callout cpu and returns with
3451283e9cdSAttilio Rao  * locked outcoming callout cpu.
3461283e9cdSAttilio Rao  */
3471283e9cdSAttilio Rao static struct callout_cpu *
3481283e9cdSAttilio Rao callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
3491283e9cdSAttilio Rao {
3501283e9cdSAttilio Rao 	struct callout_cpu *new_cc;
3511283e9cdSAttilio Rao 
3521283e9cdSAttilio Rao 	MPASS(c != NULL && cc != NULL);
3531283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
3541283e9cdSAttilio Rao 
355e75baa28SAttilio Rao 	/*
356e75baa28SAttilio Rao 	 * Avoid interrupts and preemption firing after the callout cpu
357e75baa28SAttilio Rao 	 * is blocked in order to avoid deadlocks as the new thread
358e75baa28SAttilio Rao 	 * may be willing to acquire the callout cpu lock.
359e75baa28SAttilio Rao 	 */
3601283e9cdSAttilio Rao 	c->c_cpu = CPUBLOCK;
361e75baa28SAttilio Rao 	spinlock_enter();
3621283e9cdSAttilio Rao 	CC_UNLOCK(cc);
3631283e9cdSAttilio Rao 	new_cc = CC_CPU(new_cpu);
3641283e9cdSAttilio Rao 	CC_LOCK(new_cc);
365e75baa28SAttilio Rao 	spinlock_exit();
3661283e9cdSAttilio Rao 	c->c_cpu = new_cpu;
3671283e9cdSAttilio Rao 	return (new_cc);
3681283e9cdSAttilio Rao }
3691283e9cdSAttilio Rao #endif
3701283e9cdSAttilio Rao 
371219d632cSMatthew Dillon /*
3728d809d50SJeff Roberson  * Start standard softclock thread.
3738d809d50SJeff Roberson  */
3748d809d50SJeff Roberson static void
3758d809d50SJeff Roberson start_softclock(void *dummy)
3768d809d50SJeff Roberson {
3778d809d50SJeff Roberson 	struct callout_cpu *cc;
378f44e2a4cSAdrian Chadd 	char name[MAXCOMLEN];
3798d809d50SJeff Roberson #ifdef SMP
3808d809d50SJeff Roberson 	int cpu;
381ac75ee9fSAdrian Chadd 	struct intr_event *ie;
3828d809d50SJeff Roberson #endif
3838d809d50SJeff Roberson 
3848d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
385f44e2a4cSAdrian Chadd 	snprintf(name, sizeof(name), "clock (%d)", timeout_cpu);
386f44e2a4cSAdrian Chadd 	if (swi_add(&clk_intr_event, name, softclock, cc, SWI_CLOCK,
3873350df48SJohn Baldwin 	    INTR_MPSAFE, &cc->cc_cookie))
3888d809d50SJeff Roberson 		panic("died while creating standard software ithreads");
389ac75ee9fSAdrian Chadd 	if (pin_default_swi &&
390ac75ee9fSAdrian Chadd 	    (intr_event_bind(clk_intr_event, timeout_cpu) != 0)) {
391ac75ee9fSAdrian Chadd 		printf("%s: timeout clock couldn't be pinned to cpu %d\n",
392ac75ee9fSAdrian Chadd 		    __func__,
393ac75ee9fSAdrian Chadd 		    timeout_cpu);
394ac75ee9fSAdrian Chadd 	}
395ac75ee9fSAdrian Chadd 
3968d809d50SJeff Roberson #ifdef SMP
3973aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
3988d809d50SJeff Roberson 		if (cpu == timeout_cpu)
3998d809d50SJeff Roberson 			continue;
4008d809d50SJeff Roberson 		cc = CC_CPU(cpu);
40115ae0c9aSAndre Oppermann 		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(9). */
402*232e8b52SJohn Baldwin 		callout_cpu_init(cc, cpu);
403f44e2a4cSAdrian Chadd 		snprintf(name, sizeof(name), "clock (%d)", cpu);
404ac75ee9fSAdrian Chadd 		ie = NULL;
405ac75ee9fSAdrian Chadd 		if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
4068d809d50SJeff Roberson 		    INTR_MPSAFE, &cc->cc_cookie))
4078d809d50SJeff Roberson 			panic("died while creating standard software ithreads");
408ac75ee9fSAdrian Chadd 		if (pin_pcpu_swi && (intr_event_bind(ie, cpu) != 0)) {
409ac75ee9fSAdrian Chadd 			printf("%s: per-cpu clock couldn't be pinned to "
410ac75ee9fSAdrian Chadd 			    "cpu %d\n",
411ac75ee9fSAdrian Chadd 			    __func__,
412ac75ee9fSAdrian Chadd 			    cpu);
413ac75ee9fSAdrian Chadd 		}
414219d632cSMatthew Dillon 	}
4158d809d50SJeff Roberson #endif
416219d632cSMatthew Dillon }
4178d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
4188d809d50SJeff Roberson 
4195b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
4208d809d50SJeff Roberson 
4215b999a6bSDavide Italiano static inline u_int
4225b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
4235b999a6bSDavide Italiano {
4245b999a6bSDavide Italiano 
4255b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
4265b999a6bSDavide Italiano }
4275b999a6bSDavide Italiano 
4285b999a6bSDavide Italiano static inline u_int
4295b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
4305b999a6bSDavide Italiano {
4315b999a6bSDavide Italiano 
4325b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
4335b999a6bSDavide Italiano }
4345b999a6bSDavide Italiano 
4355b999a6bSDavide Italiano void
4365b999a6bSDavide Italiano callout_process(sbintime_t now)
4375b999a6bSDavide Italiano {
4385b999a6bSDavide Italiano 	struct callout *tmp, *tmpn;
4395b999a6bSDavide Italiano 	struct callout_cpu *cc;
4405b999a6bSDavide Italiano 	struct callout_list *sc;
4415b999a6bSDavide Italiano 	sbintime_t first, last, max, tmp_max;
4425b999a6bSDavide Italiano 	uint32_t lookahead;
4435b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
4445b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4455b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
4465b999a6bSDavide Italiano #endif
4475b999a6bSDavide Italiano 
4488d809d50SJeff Roberson 	cc = CC_SELF();
4498d809d50SJeff Roberson 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4505b999a6bSDavide Italiano 
4515b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4525b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4535b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4545b999a6bSDavide Italiano 	nowb = callout_hash(now);
4555b999a6bSDavide Italiano 
4565b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4575b999a6bSDavide Italiano 	if (nowb == firstb)
4585b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4595b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4605b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4615b999a6bSDavide Italiano 	else
4625b999a6bSDavide Italiano 		lookahead = (SBT_1S / 2);
4635b999a6bSDavide Italiano 	first = last = now;
4645b999a6bSDavide Italiano 	first += (lookahead / 2);
4655b999a6bSDavide Italiano 	last += lookahead;
4665b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4675b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4685b999a6bSDavide Italiano 	max = last;
4695b999a6bSDavide Italiano 
4705b999a6bSDavide Italiano 	/*
4715b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4725b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4735b999a6bSDavide Italiano 	 */
4745b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4755b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4765b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4775b999a6bSDavide Italiano 			nowb = lastb;
4789fc51b0bSJeff Roberson 	}
4795b999a6bSDavide Italiano 
4805b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4815b999a6bSDavide Italiano 	do {
4825b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
4835b999a6bSDavide Italiano 		tmp = LIST_FIRST(sc);
4845b999a6bSDavide Italiano 		while (tmp != NULL) {
4855b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
4865b999a6bSDavide Italiano 			if (tmp->c_time <= now) {
4875b999a6bSDavide Italiano 				/*
4885b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
4895b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
4905b999a6bSDavide Italiano 				 */
4915b999a6bSDavide Italiano 				if (tmp->c_flags & CALLOUT_DIRECT) {
4925b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4935b999a6bSDavide Italiano 					++depth_dir;
4945b999a6bSDavide Italiano #endif
4955b999a6bSDavide Italiano 					cc->cc_exec_next_dir =
4965b999a6bSDavide Italiano 					    LIST_NEXT(tmp, c_links.le);
4975b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
4985b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4995b999a6bSDavide Italiano 					softclock_call_cc(tmp, cc,
5005b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5015b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
5025b999a6bSDavide Italiano #endif
5035b999a6bSDavide Italiano 					    1);
5045b999a6bSDavide Italiano 					tmp = cc->cc_exec_next_dir;
5055b999a6bSDavide Italiano 				} else {
5065b999a6bSDavide Italiano 					tmpn = LIST_NEXT(tmp, c_links.le);
5075b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
5085b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
5095b999a6bSDavide Italiano 					    tmp, c_links.tqe);
5105b999a6bSDavide Italiano 					tmp->c_flags |= CALLOUT_PROCESSED;
5115b999a6bSDavide Italiano 					tmp = tmpn;
5129fc51b0bSJeff Roberson 				}
5135b999a6bSDavide Italiano 				continue;
5145b999a6bSDavide Italiano 			}
5155b999a6bSDavide Italiano 			/* Skip events from distant future. */
5165b999a6bSDavide Italiano 			if (tmp->c_time >= max)
5175b999a6bSDavide Italiano 				goto next;
5185b999a6bSDavide Italiano 			/*
5195b999a6bSDavide Italiano 			 * Event minimal time is bigger than present maximal
5205b999a6bSDavide Italiano 			 * time, so it cannot be aggregated.
5215b999a6bSDavide Italiano 			 */
5225b999a6bSDavide Italiano 			if (tmp->c_time > last) {
5235b999a6bSDavide Italiano 				lastb = nowb;
5245b999a6bSDavide Italiano 				goto next;
5255b999a6bSDavide Italiano 			}
5265b999a6bSDavide Italiano 			/* Update first and last time, respecting this event. */
5275b999a6bSDavide Italiano 			if (tmp->c_time < first)
5285b999a6bSDavide Italiano 				first = tmp->c_time;
5295b999a6bSDavide Italiano 			tmp_max = tmp->c_time + tmp->c_precision;
5305b999a6bSDavide Italiano 			if (tmp_max < last)
5315b999a6bSDavide Italiano 				last = tmp_max;
5325b999a6bSDavide Italiano next:
5335b999a6bSDavide Italiano 			tmp = LIST_NEXT(tmp, c_links.le);
5345b999a6bSDavide Italiano 		}
5355b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
5365b999a6bSDavide Italiano 		firstb++;
5375b999a6bSDavide Italiano 		/*
5385b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
5395b999a6bSDavide Italiano 		 * some event we can't execute at now.
5405b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
5415b999a6bSDavide Italiano 		 */
5425b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
5435b999a6bSDavide Italiano 	cc->cc_firstevent = last;
5445b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
5455b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
5465b999a6bSDavide Italiano #endif
5475b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5485b999a6bSDavide Italiano 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
5495b999a6bSDavide Italiano 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
5505b999a6bSDavide Italiano 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
5515b999a6bSDavide Italiano #endif
5528d809d50SJeff Roberson 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5538d809d50SJeff Roberson 	/*
5548d809d50SJeff Roberson 	 * swi_sched acquires the thread lock, so we don't want to call it
5558d809d50SJeff Roberson 	 * with cc_lock held; incorrect locking order.
5568d809d50SJeff Roberson 	 */
5575b999a6bSDavide Italiano 	if (!TAILQ_EMPTY(&cc->cc_expireq))
5588d809d50SJeff Roberson 		swi_sched(cc->cc_cookie, 0);
5598d809d50SJeff Roberson }
5608d809d50SJeff Roberson 
5618d809d50SJeff Roberson static struct callout_cpu *
5628d809d50SJeff Roberson callout_lock(struct callout *c)
5638d809d50SJeff Roberson {
5648d809d50SJeff Roberson 	struct callout_cpu *cc;
5658d809d50SJeff Roberson 	int cpu;
5668d809d50SJeff Roberson 
5678d809d50SJeff Roberson 	for (;;) {
5688d809d50SJeff Roberson 		cpu = c->c_cpu;
5691283e9cdSAttilio Rao #ifdef SMP
5701283e9cdSAttilio Rao 		if (cpu == CPUBLOCK) {
5711283e9cdSAttilio Rao 			while (c->c_cpu == CPUBLOCK)
5721283e9cdSAttilio Rao 				cpu_spinwait();
5731283e9cdSAttilio Rao 			continue;
5741283e9cdSAttilio Rao 		}
5751283e9cdSAttilio Rao #endif
5768d809d50SJeff Roberson 		cc = CC_CPU(cpu);
5778d809d50SJeff Roberson 		CC_LOCK(cc);
5788d809d50SJeff Roberson 		if (cpu == c->c_cpu)
5798d809d50SJeff Roberson 			break;
5808d809d50SJeff Roberson 		CC_UNLOCK(cc);
5818d809d50SJeff Roberson 	}
5828d809d50SJeff Roberson 	return (cc);
583219d632cSMatthew Dillon }
584219d632cSMatthew Dillon 
5851283e9cdSAttilio Rao static void
5865b999a6bSDavide Italiano callout_cc_add(struct callout *c, struct callout_cpu *cc,
5875b999a6bSDavide Italiano     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
5885b999a6bSDavide Italiano     void *arg, int cpu, int flags)
5891283e9cdSAttilio Rao {
5905b999a6bSDavide Italiano 	int bucket;
5911283e9cdSAttilio Rao 
5921283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
5935b999a6bSDavide Italiano 	if (sbt < cc->cc_lastscan)
5945b999a6bSDavide Italiano 		sbt = cc->cc_lastscan;
5951283e9cdSAttilio Rao 	c->c_arg = arg;
5961283e9cdSAttilio Rao 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
5975b999a6bSDavide Italiano 	if (flags & C_DIRECT_EXEC)
5985b999a6bSDavide Italiano 		c->c_flags |= CALLOUT_DIRECT;
5995b999a6bSDavide Italiano 	c->c_flags &= ~CALLOUT_PROCESSED;
6001283e9cdSAttilio Rao 	c->c_func = func;
6015b999a6bSDavide Italiano 	c->c_time = sbt;
6025b999a6bSDavide Italiano 	c->c_precision = precision;
6035b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
6045b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
6055b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
6065b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
6075b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
6085b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
6095b999a6bSDavide Italiano 		cc->cc_exec_next_dir = c;
6105b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
6115b999a6bSDavide Italiano 	/*
6125b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
6135b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
6145b999a6bSDavide Italiano 	 */
6154bc38a5aSDavide Italiano 	if (SBT_MAX - c->c_time < c->c_precision)
6164bc38a5aSDavide Italiano 		c->c_precision = SBT_MAX - c->c_time;
6175b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
6185b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
6195b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
6205b999a6bSDavide Italiano 		cpu_new_callout(cpu, sbt, c->c_time);
6211283e9cdSAttilio Rao 	}
6225b999a6bSDavide Italiano #endif
6231283e9cdSAttilio Rao }
6241283e9cdSAttilio Rao 
6256098e7acSKonstantin Belousov static void
6266098e7acSKonstantin Belousov callout_cc_del(struct callout *c, struct callout_cpu *cc)
6276098e7acSKonstantin Belousov {
6286098e7acSKonstantin Belousov 
629eb8a7186SKonstantin Belousov 	if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
630eb8a7186SKonstantin Belousov 		return;
6316098e7acSKonstantin Belousov 	c->c_func = NULL;
6326098e7acSKonstantin Belousov 	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
6336098e7acSKonstantin Belousov }
6346098e7acSKonstantin Belousov 
635eb8a7186SKonstantin 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 {
6421f96759fSDavide Italiano 	struct rm_priotracker tracker;
6436098e7acSKonstantin Belousov 	void (*c_func)(void *);
6446098e7acSKonstantin Belousov 	void *c_arg;
6456098e7acSKonstantin Belousov 	struct lock_class *class;
6466098e7acSKonstantin Belousov 	struct lock_object *c_lock;
6471f96759fSDavide Italiano 	uintptr_t lock_status;
6481f96759fSDavide Italiano 	int c_flags;
6496098e7acSKonstantin Belousov #ifdef SMP
6506098e7acSKonstantin Belousov 	struct callout_cpu *new_cc;
6516098e7acSKonstantin Belousov 	void (*new_func)(void *);
6526098e7acSKonstantin Belousov 	void *new_arg;
6535b999a6bSDavide Italiano 	int flags, new_cpu;
6543f321a4eSDavide Italiano 	sbintime_t new_prec, new_time;
6556098e7acSKonstantin Belousov #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 */
6606098e7acSKonstantin Belousov 	static timeout_t *lastfunc;
6616098e7acSKonstantin Belousov #endif
6626098e7acSKonstantin Belousov 
663eb8a7186SKonstantin Belousov 	KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
664eb8a7186SKonstantin Belousov 	    (CALLOUT_PENDING | CALLOUT_ACTIVE),
665eb8a7186SKonstantin Belousov 	    ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
6666098e7acSKonstantin Belousov 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
6671f96759fSDavide Italiano 	lock_status = 0;
6681f96759fSDavide Italiano 	if (c->c_flags & CALLOUT_SHAREDLOCK) {
6691f96759fSDavide Italiano 		if (class == &lock_class_rm)
6701f96759fSDavide Italiano 			lock_status = (uintptr_t)&tracker;
6711f96759fSDavide Italiano 		else
6721f96759fSDavide Italiano 			lock_status = 1;
6731f96759fSDavide Italiano 	}
6746098e7acSKonstantin Belousov 	c_lock = c->c_lock;
6756098e7acSKonstantin Belousov 	c_func = c->c_func;
6766098e7acSKonstantin Belousov 	c_arg = c->c_arg;
6776098e7acSKonstantin Belousov 	c_flags = c->c_flags;
6786098e7acSKonstantin Belousov 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
6796098e7acSKonstantin Belousov 		c->c_flags = CALLOUT_LOCAL_ALLOC;
6806098e7acSKonstantin Belousov 	else
6816098e7acSKonstantin Belousov 		c->c_flags &= ~CALLOUT_PENDING;
6825b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_curr = c;
683ac42a172SDavide Italiano 	cc->cc_exec_entity[direct].cc_cancel = false;
6846098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
6856098e7acSKonstantin Belousov 	if (c_lock != NULL) {
6861f96759fSDavide Italiano 		class->lc_lock(c_lock, lock_status);
6876098e7acSKonstantin Belousov 		/*
6886098e7acSKonstantin Belousov 		 * The callout may have been cancelled
6896098e7acSKonstantin Belousov 		 * while we switched locks.
6906098e7acSKonstantin Belousov 		 */
6915b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_cancel) {
6926098e7acSKonstantin Belousov 			class->lc_unlock(c_lock);
6936098e7acSKonstantin Belousov 			goto skip;
6946098e7acSKonstantin Belousov 		}
6956098e7acSKonstantin Belousov 		/* The callout cannot be stopped now. */
696ac42a172SDavide Italiano 		cc->cc_exec_entity[direct].cc_cancel = true;
6976098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
6985b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6996098e7acSKonstantin Belousov 			(*gcalls)++;
7005b999a6bSDavide Italiano #endif
7015b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
7026098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7036098e7acSKonstantin Belousov 		} else {
7045b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7056098e7acSKonstantin Belousov 			(*lockcalls)++;
7065b999a6bSDavide Italiano #endif
7076098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
7086098e7acSKonstantin Belousov 			    c, c_func, c_arg);
7096098e7acSKonstantin Belousov 		}
7106098e7acSKonstantin Belousov 	} else {
7115b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7126098e7acSKonstantin Belousov 		(*mpcalls)++;
7135b999a6bSDavide Italiano #endif
7145b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
7156098e7acSKonstantin Belousov 		    c, c_func, c_arg);
7166098e7acSKonstantin Belousov 	}
717*232e8b52SJohn Baldwin 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
718*232e8b52SJohn Baldwin 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
71903763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
7205b999a6bSDavide Italiano 	sbt1 = sbinuptime();
7216098e7acSKonstantin Belousov #endif
7226098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
723d9fae5abSAndriy Gapon 	SDT_PROBE(callout_execute, kernel, , callout__start, c, 0, 0, 0, 0);
7246098e7acSKonstantin Belousov 	c_func(c_arg);
725d9fae5abSAndriy Gapon 	SDT_PROBE(callout_execute, kernel, , callout__end, c, 0, 0, 0, 0);
7266098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
72703763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
72803763781SDavide Italiano 	sbt2 = sbinuptime();
72903763781SDavide Italiano 	sbt2 -= sbt1;
73003763781SDavide Italiano 	if (sbt2 > maxdt) {
73103763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
73203763781SDavide Italiano 			ts2 = sbttots(sbt2);
7336098e7acSKonstantin Belousov 			printf(
7346098e7acSKonstantin Belousov 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
7356098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
7366098e7acSKonstantin Belousov 		}
73703763781SDavide Italiano 		maxdt = sbt2;
7386098e7acSKonstantin Belousov 		lastfunc = c_func;
7396098e7acSKonstantin Belousov 	}
7406098e7acSKonstantin Belousov #endif
741*232e8b52SJohn Baldwin 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
7426098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
7436098e7acSKonstantin Belousov 	if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
7446098e7acSKonstantin Belousov 		class->lc_unlock(c_lock);
7456098e7acSKonstantin Belousov skip:
7466098e7acSKonstantin Belousov 	CC_LOCK(cc);
7475b999a6bSDavide Italiano 	KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
7485b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_curr = NULL;
7495b999a6bSDavide Italiano 	if (cc->cc_exec_entity[direct].cc_waiting) {
7506098e7acSKonstantin Belousov 		/*
7516098e7acSKonstantin Belousov 		 * There is someone waiting for the
7526098e7acSKonstantin Belousov 		 * callout to complete.
7536098e7acSKonstantin Belousov 		 * If the callout was scheduled for
7546098e7acSKonstantin Belousov 		 * migration just cancel it.
7556098e7acSKonstantin Belousov 		 */
7565b999a6bSDavide Italiano 		if (cc_cce_migrating(cc, direct)) {
7575b999a6bSDavide Italiano 			cc_cce_cleanup(cc, direct);
758bdf9120cSAttilio Rao 
759bdf9120cSAttilio Rao 			/*
760bdf9120cSAttilio Rao 			 * It should be assert here that the callout is not
761bdf9120cSAttilio Rao 			 * destroyed but that is not easy.
762bdf9120cSAttilio Rao 			 */
763eb8a7186SKonstantin Belousov 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
764eb8a7186SKonstantin Belousov 		}
765ac42a172SDavide Italiano 		cc->cc_exec_entity[direct].cc_waiting = false;
7666098e7acSKonstantin Belousov 		CC_UNLOCK(cc);
7675b999a6bSDavide Italiano 		wakeup(&cc->cc_exec_entity[direct].cc_waiting);
7686098e7acSKonstantin Belousov 		CC_LOCK(cc);
7695b999a6bSDavide Italiano 	} else if (cc_cce_migrating(cc, direct)) {
770bdf9120cSAttilio Rao 		KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
771eb8a7186SKonstantin Belousov 		    ("Migrating legacy callout %p", c));
7726098e7acSKonstantin Belousov #ifdef SMP
7736098e7acSKonstantin Belousov 		/*
7746098e7acSKonstantin Belousov 		 * If the callout was scheduled for
7756098e7acSKonstantin Belousov 		 * migration just perform it now.
7766098e7acSKonstantin Belousov 		 */
7775b999a6bSDavide Italiano 		new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
7785b999a6bSDavide Italiano 		new_time = cc->cc_exec_entity[direct].ce_migration_time;
7793f321a4eSDavide Italiano 		new_prec = cc->cc_exec_entity[direct].ce_migration_prec;
7805b999a6bSDavide Italiano 		new_func = cc->cc_exec_entity[direct].ce_migration_func;
7815b999a6bSDavide Italiano 		new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
7825b999a6bSDavide Italiano 		cc_cce_cleanup(cc, direct);
7836098e7acSKonstantin Belousov 
7846098e7acSKonstantin Belousov 		/*
785bdf9120cSAttilio Rao 		 * It should be assert here that the callout is not destroyed
786bdf9120cSAttilio Rao 		 * but that is not easy.
787bdf9120cSAttilio Rao 		 *
788bdf9120cSAttilio Rao 		 * As first thing, handle deferred callout stops.
7896098e7acSKonstantin Belousov 		 */
7906098e7acSKonstantin Belousov 		if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
7916098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT,
7926098e7acSKonstantin Belousov 			     "deferred cancelled %p func %p arg %p",
7936098e7acSKonstantin Belousov 			     c, new_func, new_arg);
7946098e7acSKonstantin Belousov 			callout_cc_del(c, cc);
795eb8a7186SKonstantin Belousov 			return;
7966098e7acSKonstantin Belousov 		}
7976098e7acSKonstantin Belousov 		c->c_flags &= ~CALLOUT_DFRMIGRATION;
7986098e7acSKonstantin Belousov 
7996098e7acSKonstantin Belousov 		new_cc = callout_cpu_switch(c, cc, new_cpu);
8005b999a6bSDavide Italiano 		flags = (direct) ? C_DIRECT_EXEC : 0;
8013f321a4eSDavide Italiano 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
8025b999a6bSDavide Italiano 		    new_arg, new_cpu, flags);
8036098e7acSKonstantin Belousov 		CC_UNLOCK(new_cc);
8046098e7acSKonstantin Belousov 		CC_LOCK(cc);
8056098e7acSKonstantin Belousov #else
8066098e7acSKonstantin Belousov 		panic("migration should not happen");
8076098e7acSKonstantin Belousov #endif
8086098e7acSKonstantin Belousov 	}
809eb8a7186SKonstantin Belousov 	/*
810eb8a7186SKonstantin Belousov 	 * If the current callout is locally allocated (from
811eb8a7186SKonstantin Belousov 	 * timeout(9)) then put it on the freelist.
812eb8a7186SKonstantin Belousov 	 *
813eb8a7186SKonstantin Belousov 	 * Note: we need to check the cached copy of c_flags because
814eb8a7186SKonstantin Belousov 	 * if it was not local, then it's not safe to deref the
815eb8a7186SKonstantin Belousov 	 * callout pointer.
816eb8a7186SKonstantin Belousov 	 */
817eb8a7186SKonstantin Belousov 	KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
818eb8a7186SKonstantin Belousov 	    c->c_flags == CALLOUT_LOCAL_ALLOC,
819eb8a7186SKonstantin Belousov 	    ("corrupted callout"));
820bdf9120cSAttilio Rao 	if (c_flags & CALLOUT_LOCAL_ALLOC)
821eb8a7186SKonstantin Belousov 		callout_cc_del(c, cc);
8226098e7acSKonstantin Belousov }
8236098e7acSKonstantin Belousov 
824219d632cSMatthew Dillon /*
825ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
826ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
827ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
828ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
829024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
830ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
831ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
832ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
833ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
834ab36c067SJustin T. Gibbs  */
835a50ec505SPoul-Henning Kamp 
836ab36c067SJustin T. Gibbs /*
837df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
838df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
839df8bae1dSRodney W. Grimes  */
840df8bae1dSRodney W. Grimes void
8418d809d50SJeff Roberson softclock(void *arg)
842df8bae1dSRodney W. Grimes {
8438d809d50SJeff Roberson 	struct callout_cpu *cc;
844b336df68SPoul-Henning Kamp 	struct callout *c;
8455b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8465b999a6bSDavide Italiano 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
8475b999a6bSDavide Italiano #endif
848df8bae1dSRodney W. Grimes 
8498d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
8508d809d50SJeff Roberson 	CC_LOCK(cc);
8515b999a6bSDavide Italiano 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
8525b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
8535b999a6bSDavide Italiano 		softclock_call_cc(c, cc,
8545b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8555b999a6bSDavide Italiano 		    &mpcalls, &lockcalls, &gcalls,
8565b999a6bSDavide Italiano #endif
8575b999a6bSDavide Italiano 		    0);
8585b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
8595b999a6bSDavide Italiano 		++depth;
8605b999a6bSDavide Italiano #endif
861df8bae1dSRodney W. Grimes 	}
8625b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
86322ee8c4fSPoul-Henning Kamp 	avg_depth += (depth * 1000 - avg_depth) >> 8;
86422ee8c4fSPoul-Henning Kamp 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
86564b9ee20SAttilio Rao 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
86622ee8c4fSPoul-Henning Kamp 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8675b999a6bSDavide Italiano #endif
8688d809d50SJeff Roberson 	CC_UNLOCK(cc);
869df8bae1dSRodney W. Grimes }
870df8bae1dSRodney W. Grimes 
871df8bae1dSRodney W. Grimes /*
872df8bae1dSRodney W. Grimes  * timeout --
873df8bae1dSRodney W. Grimes  *	Execute a function after a specified length of time.
874df8bae1dSRodney W. Grimes  *
875df8bae1dSRodney W. Grimes  * untimeout --
876df8bae1dSRodney W. Grimes  *	Cancel previous timeout function call.
877df8bae1dSRodney W. Grimes  *
878ab36c067SJustin T. Gibbs  * callout_handle_init --
879ab36c067SJustin T. Gibbs  *	Initialize a handle so that using it with untimeout is benign.
880ab36c067SJustin T. Gibbs  *
881df8bae1dSRodney W. Grimes  *	See AT&T BCI Driver Reference Manual for specification.  This
882ab36c067SJustin T. Gibbs  *	implementation differs from that one in that although an
883ab36c067SJustin T. Gibbs  *	identification value is returned from timeout, the original
884ab36c067SJustin T. Gibbs  *	arguments to timeout as well as the identifier are used to
885ab36c067SJustin T. Gibbs  *	identify entries for untimeout.
886df8bae1dSRodney W. Grimes  */
887ab36c067SJustin T. Gibbs struct callout_handle
888e392e44cSDavide Italiano timeout(timeout_t *ftn, void *arg, int to_ticks)
889df8bae1dSRodney W. Grimes {
8908d809d50SJeff Roberson 	struct callout_cpu *cc;
891ab36c067SJustin T. Gibbs 	struct callout *new;
892ab36c067SJustin T. Gibbs 	struct callout_handle handle;
893df8bae1dSRodney W. Grimes 
8948d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
8958d809d50SJeff Roberson 	CC_LOCK(cc);
896df8bae1dSRodney W. Grimes 	/* Fill in the next free callout structure. */
8978d809d50SJeff Roberson 	new = SLIST_FIRST(&cc->cc_callfree);
898ab36c067SJustin T. Gibbs 	if (new == NULL)
899ab36c067SJustin T. Gibbs 		/* XXX Attempt to malloc first */
900df8bae1dSRodney W. Grimes 		panic("timeout table full");
9018d809d50SJeff Roberson 	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
902acc8326dSGarrett Wollman 	callout_reset(new, to_ticks, ftn, arg);
903ab36c067SJustin T. Gibbs 	handle.callout = new;
9048d809d50SJeff Roberson 	CC_UNLOCK(cc);
9058d809d50SJeff Roberson 
906ab36c067SJustin T. Gibbs 	return (handle);
907df8bae1dSRodney W. Grimes }
908df8bae1dSRodney W. Grimes 
909df8bae1dSRodney W. Grimes void
910e392e44cSDavide Italiano untimeout(timeout_t *ftn, void *arg, struct callout_handle handle)
911df8bae1dSRodney W. Grimes {
9128d809d50SJeff Roberson 	struct callout_cpu *cc;
913df8bae1dSRodney W. Grimes 
914ab36c067SJustin T. Gibbs 	/*
915ab36c067SJustin T. Gibbs 	 * Check for a handle that was initialized
916ab36c067SJustin T. Gibbs 	 * by callout_handle_init, but never used
917ab36c067SJustin T. Gibbs 	 * for a real timeout.
918ab36c067SJustin T. Gibbs 	 */
919ab36c067SJustin T. Gibbs 	if (handle.callout == NULL)
920ab36c067SJustin T. Gibbs 		return;
921df8bae1dSRodney W. Grimes 
9228d809d50SJeff Roberson 	cc = callout_lock(handle.callout);
923acc8326dSGarrett Wollman 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
924acc8326dSGarrett Wollman 		callout_stop(handle.callout);
9258d809d50SJeff Roberson 	CC_UNLOCK(cc);
926df8bae1dSRodney W. Grimes }
927df8bae1dSRodney W. Grimes 
9283c816944SBruce Evans void
929ab36c067SJustin T. Gibbs callout_handle_init(struct callout_handle *handle)
930ab36c067SJustin T. Gibbs {
931ab36c067SJustin T. Gibbs 	handle->callout = NULL;
932ab36c067SJustin T. Gibbs }
933ab36c067SJustin T. Gibbs 
934acc8326dSGarrett Wollman /*
935acc8326dSGarrett Wollman  * New interface; clients allocate their own callout structures.
936acc8326dSGarrett Wollman  *
937acc8326dSGarrett Wollman  * callout_reset() - establish or change a timeout
938acc8326dSGarrett Wollman  * callout_stop() - disestablish a timeout
939acc8326dSGarrett Wollman  * callout_init() - initialize a callout structure so that it can
940acc8326dSGarrett Wollman  *	safely be passed to callout_reset() and callout_stop()
941acc8326dSGarrett Wollman  *
9429b8b58e0SJonathan Lemon  * <sys/callout.h> defines three convenience macros:
943acc8326dSGarrett Wollman  *
94486fd19deSColin Percival  * callout_active() - returns truth if callout has not been stopped,
94586fd19deSColin Percival  *	drained, or deactivated since the last time the callout was
94686fd19deSColin Percival  *	reset.
9479b8b58e0SJonathan Lemon  * callout_pending() - returns truth if callout is still waiting for timeout
9489b8b58e0SJonathan Lemon  * callout_deactivate() - marks the callout as having been serviced
949acc8326dSGarrett Wollman  */
950d04304d1SGleb Smirnoff int
9515b999a6bSDavide Italiano callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
9525b999a6bSDavide Italiano     void (*ftn)(void *), void *arg, int cpu, int flags)
953acc8326dSGarrett Wollman {
9545b999a6bSDavide Italiano 	sbintime_t to_sbt, pr;
9558d809d50SJeff Roberson 	struct callout_cpu *cc;
9565b999a6bSDavide Italiano 	int cancelled, direct;
957acc8326dSGarrett Wollman 
9585b999a6bSDavide Italiano 	cancelled = 0;
9595b999a6bSDavide Italiano 	if (flags & C_ABSOLUTE) {
9605b999a6bSDavide Italiano 		to_sbt = sbt;
9615b999a6bSDavide Italiano 	} else {
9625b999a6bSDavide Italiano 		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
9635b999a6bSDavide Italiano 			sbt = tick_sbt;
9645b999a6bSDavide Italiano 		if ((flags & C_HARDCLOCK) ||
9655b999a6bSDavide Italiano #ifdef NO_EVENTTIMERS
9665b999a6bSDavide Italiano 		    sbt >= sbt_timethreshold) {
9675b999a6bSDavide Italiano 			to_sbt = getsbinuptime();
9685b999a6bSDavide Italiano 
9695b999a6bSDavide Italiano 			/* Add safety belt for the case of hz > 1000. */
9705b999a6bSDavide Italiano 			to_sbt += tc_tick_sbt - tick_sbt;
9715b999a6bSDavide Italiano #else
9725b999a6bSDavide Italiano 		    sbt >= sbt_tickthreshold) {
9735b999a6bSDavide Italiano 			/*
9745b999a6bSDavide Italiano 			 * Obtain the time of the last hardclock() call on
9755b999a6bSDavide Italiano 			 * this CPU directly from the kern_clocksource.c.
9765b999a6bSDavide Italiano 			 * This value is per-CPU, but it is equal for all
9775b999a6bSDavide Italiano 			 * active ones.
9785b999a6bSDavide Italiano 			 */
9795b999a6bSDavide Italiano #ifdef __LP64__
9805b999a6bSDavide Italiano 			to_sbt = DPCPU_GET(hardclocktime);
9815b999a6bSDavide Italiano #else
9825b999a6bSDavide Italiano 			spinlock_enter();
9835b999a6bSDavide Italiano 			to_sbt = DPCPU_GET(hardclocktime);
9845b999a6bSDavide Italiano 			spinlock_exit();
9855b999a6bSDavide Italiano #endif
9865b999a6bSDavide Italiano #endif
9875b999a6bSDavide Italiano 			if ((flags & C_HARDCLOCK) == 0)
9885b999a6bSDavide Italiano 				to_sbt += tick_sbt;
9895b999a6bSDavide Italiano 		} else
9905b999a6bSDavide Italiano 			to_sbt = sbinuptime();
9914bc38a5aSDavide Italiano 		if (SBT_MAX - to_sbt < sbt)
9924bc38a5aSDavide Italiano 			to_sbt = SBT_MAX;
9931b0c144fSDavide Italiano 		else
9945b999a6bSDavide Italiano 			to_sbt += sbt;
9955b999a6bSDavide Italiano 		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
9965b999a6bSDavide Italiano 		    sbt >> C_PRELGET(flags));
9975b999a6bSDavide Italiano 		if (pr > precision)
9985b999a6bSDavide Italiano 			precision = pr;
9995b999a6bSDavide Italiano 	}
10008d809d50SJeff Roberson 	/*
10018d809d50SJeff Roberson 	 * Don't allow migration of pre-allocated callouts lest they
10028d809d50SJeff Roberson 	 * become unbalanced.
10038d809d50SJeff Roberson 	 */
10048d809d50SJeff Roberson 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
10058d809d50SJeff Roberson 		cpu = c->c_cpu;
10065b999a6bSDavide Italiano 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
10075b999a6bSDavide Italiano 	KASSERT(!direct || c->c_lock == NULL,
10085b999a6bSDavide Italiano 	    ("%s: direct callout %p has lock", __func__, c));
10098d809d50SJeff Roberson 	cc = callout_lock(c);
10105b999a6bSDavide Italiano 	if (cc->cc_exec_entity[direct].cc_curr == c) {
10112c1bb207SColin Percival 		/*
10122c1bb207SColin Percival 		 * We're being asked to reschedule a callout which is
101364b9ee20SAttilio Rao 		 * currently in progress.  If there is a lock then we
101498c926b2SIan Dowse 		 * can cancel the callout if it has not really started.
101598c926b2SIan Dowse 		 */
10165b999a6bSDavide Italiano 		if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
1017ac42a172SDavide Italiano 			cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
10185b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_waiting) {
101998c926b2SIan Dowse 			/*
102098c926b2SIan Dowse 			 * Someone has called callout_drain to kill this
102198c926b2SIan Dowse 			 * callout.  Don't reschedule.
10222c1bb207SColin Percival 			 */
102368a57ebfSGleb Smirnoff 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
102468a57ebfSGleb Smirnoff 			    cancelled ? "cancelled" : "failed to cancel",
102568a57ebfSGleb Smirnoff 			    c, c->c_func, c->c_arg);
10268d809d50SJeff Roberson 			CC_UNLOCK(cc);
1027d04304d1SGleb Smirnoff 			return (cancelled);
102849a74476SColin Percival 		}
102998c926b2SIan Dowse 	}
10300413bacdSColin Percival 	if (c->c_flags & CALLOUT_PENDING) {
10315b999a6bSDavide Italiano 		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
10325b999a6bSDavide Italiano 			if (cc->cc_exec_next_dir == c)
10335b999a6bSDavide Italiano 				cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
10345b999a6bSDavide Italiano 			LIST_REMOVE(c, c_links.le);
10355b999a6bSDavide Italiano 		} else
10365b999a6bSDavide Italiano 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1037d04304d1SGleb Smirnoff 		cancelled = 1;
10388d809d50SJeff Roberson 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
10398d809d50SJeff Roberson 	}
10401283e9cdSAttilio Rao 
10411283e9cdSAttilio Rao #ifdef SMP
10420413bacdSColin Percival 	/*
10431283e9cdSAttilio Rao 	 * If the callout must migrate try to perform it immediately.
10441283e9cdSAttilio Rao 	 * If the callout is currently running, just defer the migration
10451283e9cdSAttilio Rao 	 * to a more appropriate moment.
10460413bacdSColin Percival 	 */
10478d809d50SJeff Roberson 	if (c->c_cpu != cpu) {
10485b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_curr == c) {
10495b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
10505b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_time
10515b999a6bSDavide Italiano 			    = to_sbt;
10523f321a4eSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_prec
10533f321a4eSDavide Italiano 			    = precision;
10545b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_func = ftn;
10555b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_arg = arg;
105657d07ca9SKonstantin Belousov 			c->c_flags |= CALLOUT_DFRMIGRATION;
10575b999a6bSDavide Italiano 			CTR6(KTR_CALLOUT,
10585b999a6bSDavide Italiano 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
10595b999a6bSDavide Italiano 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
10605b999a6bSDavide Italiano 			    (u_int)(to_sbt & 0xffffffff), cpu);
106108e4ac8aSAttilio Rao 			CC_UNLOCK(cc);
10621283e9cdSAttilio Rao 			return (cancelled);
1063a157e425SAlexander Motin 		}
10641283e9cdSAttilio Rao 		cc = callout_cpu_switch(c, cc, cpu);
106508e4ac8aSAttilio Rao 	}
10661283e9cdSAttilio Rao #endif
10671283e9cdSAttilio Rao 
10685b999a6bSDavide Italiano 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
10695b999a6bSDavide Italiano 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
10705b999a6bSDavide Italiano 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
10715b999a6bSDavide Italiano 	    (u_int)(to_sbt & 0xffffffff));
10728d809d50SJeff Roberson 	CC_UNLOCK(cc);
1073d04304d1SGleb Smirnoff 
1074d04304d1SGleb Smirnoff 	return (cancelled);
1075acc8326dSGarrett Wollman }
1076acc8326dSGarrett Wollman 
10776e0186d5SSam Leffler /*
10786e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
10796e0186d5SSam Leffler  */
10806e0186d5SSam Leffler int
10816e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
10826e0186d5SSam Leffler {
10836e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
10846e0186d5SSam Leffler }
10856e0186d5SSam Leffler 
10866e0186d5SSam Leffler int
10876e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
10886e0186d5SSam Leffler {
10896e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
10906e0186d5SSam Leffler }
10916e0186d5SSam Leffler 
10922c1bb207SColin Percival int
1093e392e44cSDavide Italiano _callout_stop_safe(struct callout *c, int safe)
10942c1bb207SColin Percival {
10951283e9cdSAttilio Rao 	struct callout_cpu *cc, *old_cc;
109664b9ee20SAttilio Rao 	struct lock_class *class;
10975b999a6bSDavide Italiano 	int direct, sq_locked, use_lock;
109898c926b2SIan Dowse 
109964b9ee20SAttilio Rao 	/*
110064b9ee20SAttilio Rao 	 * Some old subsystems don't hold Giant while running a callout_stop(),
110164b9ee20SAttilio Rao 	 * so just discard this check for the moment.
110264b9ee20SAttilio Rao 	 */
110364b9ee20SAttilio Rao 	if (!safe && c->c_lock != NULL) {
110464b9ee20SAttilio Rao 		if (c->c_lock == &Giant.lock_object)
110564b9ee20SAttilio Rao 			use_lock = mtx_owned(&Giant);
110664b9ee20SAttilio Rao 		else {
110764b9ee20SAttilio Rao 			use_lock = 1;
110864b9ee20SAttilio Rao 			class = LOCK_CLASS(c->c_lock);
110964b9ee20SAttilio Rao 			class->lc_assert(c->c_lock, LA_XLOCKED);
111098c926b2SIan Dowse 		}
111164b9ee20SAttilio Rao 	} else
111264b9ee20SAttilio Rao 		use_lock = 0;
11135b999a6bSDavide Italiano 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
111467b158d8SJohn Baldwin 	sq_locked = 0;
11151283e9cdSAttilio Rao 	old_cc = NULL;
111667b158d8SJohn Baldwin again:
11178d809d50SJeff Roberson 	cc = callout_lock(c);
11181283e9cdSAttilio Rao 
11191283e9cdSAttilio Rao 	/*
11201283e9cdSAttilio Rao 	 * If the callout was migrating while the callout cpu lock was
11211283e9cdSAttilio Rao 	 * dropped,  just drop the sleepqueue lock and check the states
11221283e9cdSAttilio Rao 	 * again.
11231283e9cdSAttilio Rao 	 */
11241283e9cdSAttilio Rao 	if (sq_locked != 0 && cc != old_cc) {
11251283e9cdSAttilio Rao #ifdef SMP
11261283e9cdSAttilio Rao 		CC_UNLOCK(cc);
11275b999a6bSDavide Italiano 		sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
11281283e9cdSAttilio Rao 		sq_locked = 0;
11291283e9cdSAttilio Rao 		old_cc = NULL;
11301283e9cdSAttilio Rao 		goto again;
11311283e9cdSAttilio Rao #else
11321283e9cdSAttilio Rao 		panic("migration should not happen");
11331283e9cdSAttilio Rao #endif
11341283e9cdSAttilio Rao 	}
11351283e9cdSAttilio Rao 
1136acc8326dSGarrett Wollman 	/*
1137b36f4588SJohn Baldwin 	 * If the callout isn't pending, it's not on the queue, so
1138b36f4588SJohn Baldwin 	 * don't attempt to remove it from the queue.  We can try to
1139b36f4588SJohn Baldwin 	 * stop it by other means however.
1140acc8326dSGarrett Wollman 	 */
1141acc8326dSGarrett Wollman 	if (!(c->c_flags & CALLOUT_PENDING)) {
11429b8b58e0SJonathan Lemon 		c->c_flags &= ~CALLOUT_ACTIVE;
1143b36f4588SJohn Baldwin 
1144b36f4588SJohn Baldwin 		/*
1145b36f4588SJohn Baldwin 		 * If it wasn't on the queue and it isn't the current
1146b36f4588SJohn Baldwin 		 * callout, then we can't stop it, so just bail.
1147b36f4588SJohn Baldwin 		 */
11485b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_curr != c) {
114968a57ebfSGleb Smirnoff 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
115068a57ebfSGleb Smirnoff 			    c, c->c_func, c->c_arg);
11518d809d50SJeff Roberson 			CC_UNLOCK(cc);
115267b158d8SJohn Baldwin 			if (sq_locked)
11535b999a6bSDavide Italiano 				sleepq_release(
11545b999a6bSDavide Italiano 				    &cc->cc_exec_entity[direct].cc_waiting);
115598c926b2SIan Dowse 			return (0);
115698c926b2SIan Dowse 		}
1157b36f4588SJohn Baldwin 
115898c926b2SIan Dowse 		if (safe) {
11592c1bb207SColin Percival 			/*
1160b36f4588SJohn Baldwin 			 * The current callout is running (or just
1161b36f4588SJohn Baldwin 			 * about to run) and blocking is allowed, so
1162b36f4588SJohn Baldwin 			 * just wait for the current invocation to
1163b36f4588SJohn Baldwin 			 * finish.
11642c1bb207SColin Percival 			 */
11655b999a6bSDavide Italiano 			while (cc->cc_exec_entity[direct].cc_curr == c) {
11666a0ce57dSAttilio Rao 				/*
11676a0ce57dSAttilio Rao 				 * Use direct calls to sleepqueue interface
11686a0ce57dSAttilio Rao 				 * instead of cv/msleep in order to avoid
11698d809d50SJeff Roberson 				 * a LOR between cc_lock and sleepqueue
11706a0ce57dSAttilio Rao 				 * chain spinlocks.  This piece of code
11716a0ce57dSAttilio Rao 				 * emulates a msleep_spin() call actually.
117267b158d8SJohn Baldwin 				 *
117367b158d8SJohn Baldwin 				 * If we already have the sleepqueue chain
117467b158d8SJohn Baldwin 				 * locked, then we can safely block.  If we
117567b158d8SJohn Baldwin 				 * don't already have it locked, however,
11768d809d50SJeff Roberson 				 * we have to drop the cc_lock to lock
117767b158d8SJohn Baldwin 				 * it.  This opens several races, so we
117867b158d8SJohn Baldwin 				 * restart at the beginning once we have
117967b158d8SJohn Baldwin 				 * both locks.  If nothing has changed, then
118067b158d8SJohn Baldwin 				 * we will end up back here with sq_locked
118167b158d8SJohn Baldwin 				 * set.
11826a0ce57dSAttilio Rao 				 */
118367b158d8SJohn Baldwin 				if (!sq_locked) {
11848d809d50SJeff Roberson 					CC_UNLOCK(cc);
11855b999a6bSDavide Italiano 					sleepq_lock(
11865b999a6bSDavide Italiano 					&cc->cc_exec_entity[direct].cc_waiting);
118767b158d8SJohn Baldwin 					sq_locked = 1;
11881283e9cdSAttilio Rao 					old_cc = cc;
118967b158d8SJohn Baldwin 					goto again;
11906a0ce57dSAttilio Rao 				}
11911283e9cdSAttilio Rao 
11921283e9cdSAttilio Rao 				/*
11931283e9cdSAttilio Rao 				 * Migration could be cancelled here, but
11941283e9cdSAttilio Rao 				 * as long as it is still not sure when it
11951283e9cdSAttilio Rao 				 * will be packed up, just let softclock()
11961283e9cdSAttilio Rao 				 * take care of it.
11971283e9cdSAttilio Rao 				 */
1198ac42a172SDavide Italiano 				cc->cc_exec_entity[direct].cc_waiting = true;
11996a0ce57dSAttilio Rao 				DROP_GIANT();
12008d809d50SJeff Roberson 				CC_UNLOCK(cc);
12015b999a6bSDavide Italiano 				sleepq_add(
12025b999a6bSDavide Italiano 				    &cc->cc_exec_entity[direct].cc_waiting,
12038d809d50SJeff Roberson 				    &cc->cc_lock.lock_object, "codrain",
12046a0ce57dSAttilio Rao 				    SLEEPQ_SLEEP, 0);
12055b999a6bSDavide Italiano 				sleepq_wait(
12065b999a6bSDavide Italiano 				    &cc->cc_exec_entity[direct].cc_waiting,
12075b999a6bSDavide Italiano 					     0);
120867b158d8SJohn Baldwin 				sq_locked = 0;
12091283e9cdSAttilio Rao 				old_cc = NULL;
12106a0ce57dSAttilio Rao 
12116a0ce57dSAttilio Rao 				/* Reacquire locks previously released. */
12126a0ce57dSAttilio Rao 				PICKUP_GIANT();
12138d809d50SJeff Roberson 				CC_LOCK(cc);
1214b36f4588SJohn Baldwin 			}
12155b999a6bSDavide Italiano 		} else if (use_lock &&
12165b999a6bSDavide Italiano 			    !cc->cc_exec_entity[direct].cc_cancel) {
1217b36f4588SJohn Baldwin 			/*
121864b9ee20SAttilio Rao 			 * The current callout is waiting for its
121964b9ee20SAttilio Rao 			 * lock which we hold.  Cancel the callout
1220b36f4588SJohn Baldwin 			 * and return.  After our caller drops the
122164b9ee20SAttilio Rao 			 * lock, the callout will be skipped in
1222b36f4588SJohn Baldwin 			 * softclock().
1223b36f4588SJohn Baldwin 			 */
1224ac42a172SDavide Italiano 			cc->cc_exec_entity[direct].cc_cancel = true;
122568a57ebfSGleb Smirnoff 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
122668a57ebfSGleb Smirnoff 			    c, c->c_func, c->c_arg);
12275b999a6bSDavide Italiano 			KASSERT(!cc_cce_migrating(cc, direct),
12281283e9cdSAttilio Rao 			    ("callout wrongly scheduled for migration"));
12298d809d50SJeff Roberson 			CC_UNLOCK(cc);
123067b158d8SJohn Baldwin 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
123198c926b2SIan Dowse 			return (1);
123257d07ca9SKonstantin Belousov 		} else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
123357d07ca9SKonstantin Belousov 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
123457d07ca9SKonstantin Belousov 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
123557d07ca9SKonstantin Belousov 			    c, c->c_func, c->c_arg);
123657d07ca9SKonstantin Belousov 			CC_UNLOCK(cc);
123757d07ca9SKonstantin Belousov 			return (1);
1238b36f4588SJohn Baldwin 		}
123968a57ebfSGleb Smirnoff 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
124068a57ebfSGleb Smirnoff 		    c, c->c_func, c->c_arg);
12418d809d50SJeff Roberson 		CC_UNLOCK(cc);
124267b158d8SJohn Baldwin 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1243a45982d2SJohn Baldwin 		return (0);
1244acc8326dSGarrett Wollman 	}
124567b158d8SJohn Baldwin 	if (sq_locked)
12465b999a6bSDavide Italiano 		sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
124767b158d8SJohn Baldwin 
12489b8b58e0SJonathan Lemon 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1249acc8326dSGarrett Wollman 
125068a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
125168a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
12525b999a6bSDavide Italiano 	if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
12535b999a6bSDavide Italiano 		if (cc->cc_exec_next_dir == c)
12545b999a6bSDavide Italiano 			cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
12555b999a6bSDavide Italiano 		LIST_REMOVE(c, c_links.le);
12565b999a6bSDavide Italiano 	} else
12575b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
12586098e7acSKonstantin Belousov 	callout_cc_del(c, cc);
125968a57ebfSGleb Smirnoff 
12608d809d50SJeff Roberson 	CC_UNLOCK(cc);
1261a45982d2SJohn Baldwin 	return (1);
1262acc8326dSGarrett Wollman }
1263acc8326dSGarrett Wollman 
1264acc8326dSGarrett Wollman void
1265e392e44cSDavide Italiano callout_init(struct callout *c, int mpsafe)
1266acc8326dSGarrett Wollman {
12677347e1c6SGarrett Wollman 	bzero(c, sizeof *c);
126898c926b2SIan Dowse 	if (mpsafe) {
126964b9ee20SAttilio Rao 		c->c_lock = NULL;
127098c926b2SIan Dowse 		c->c_flags = CALLOUT_RETURNUNLOCKED;
127198c926b2SIan Dowse 	} else {
127264b9ee20SAttilio Rao 		c->c_lock = &Giant.lock_object;
127398c926b2SIan Dowse 		c->c_flags = 0;
127498c926b2SIan Dowse 	}
12758d809d50SJeff Roberson 	c->c_cpu = timeout_cpu;
127698c926b2SIan Dowse }
127798c926b2SIan Dowse 
127898c926b2SIan Dowse void
1279e392e44cSDavide Italiano _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
128098c926b2SIan Dowse {
128198c926b2SIan Dowse 	bzero(c, sizeof *c);
128264b9ee20SAttilio Rao 	c->c_lock = lock;
128364b9ee20SAttilio Rao 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
128464b9ee20SAttilio Rao 	    ("callout_init_lock: bad flags %d", flags));
128564b9ee20SAttilio Rao 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
128664b9ee20SAttilio Rao 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
128713ddf72dSAttilio Rao 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
128813ddf72dSAttilio Rao 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
128964b9ee20SAttilio Rao 	    __func__));
129064b9ee20SAttilio Rao 	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
12918d809d50SJeff Roberson 	c->c_cpu = timeout_cpu;
1292acc8326dSGarrett Wollman }
1293acc8326dSGarrett Wollman 
1294e1d6dc65SNate Williams #ifdef APM_FIXUP_CALLTODO
1295e1d6dc65SNate Williams /*
1296e1d6dc65SNate Williams  * Adjust the kernel calltodo timeout list.  This routine is used after
1297e1d6dc65SNate Williams  * an APM resume to recalculate the calltodo timer list values with the
1298e1d6dc65SNate Williams  * number of hz's we have been sleeping.  The next hardclock() will detect
1299e1d6dc65SNate Williams  * that there are fired timers and run softclock() to execute them.
1300e1d6dc65SNate Williams  *
1301e1d6dc65SNate Williams  * Please note, I have not done an exhaustive analysis of what code this
1302e1d6dc65SNate Williams  * might break.  I am motivated to have my select()'s and alarm()'s that
1303e1d6dc65SNate Williams  * have expired during suspend firing upon resume so that the applications
1304e1d6dc65SNate Williams  * which set the timer can do the maintanence the timer was for as close
1305e1d6dc65SNate Williams  * as possible to the originally intended time.  Testing this code for a
1306e1d6dc65SNate Williams  * week showed that resuming from a suspend resulted in 22 to 25 timers
1307e1d6dc65SNate Williams  * firing, which seemed independant on whether the suspend was 2 hours or
1308e1d6dc65SNate Williams  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1309e1d6dc65SNate Williams  */
1310e1d6dc65SNate Williams void
1311e392e44cSDavide Italiano adjust_timeout_calltodo(struct timeval *time_change)
1312e1d6dc65SNate Williams {
1313e1d6dc65SNate Williams 	register struct callout *p;
1314e1d6dc65SNate Williams 	unsigned long delta_ticks;
1315e1d6dc65SNate Williams 
1316e1d6dc65SNate Williams 	/*
1317e1d6dc65SNate Williams 	 * How many ticks were we asleep?
1318c8b47828SBruce Evans 	 * (stolen from tvtohz()).
1319e1d6dc65SNate Williams 	 */
1320e1d6dc65SNate Williams 
1321e1d6dc65SNate Williams 	/* Don't do anything */
1322e1d6dc65SNate Williams 	if (time_change->tv_sec < 0)
1323e1d6dc65SNate Williams 		return;
1324e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
1325e1d6dc65SNate Williams 		delta_ticks = (time_change->tv_sec * 1000000 +
1326e1d6dc65SNate Williams 			       time_change->tv_usec + (tick - 1)) / tick + 1;
1327e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / hz)
1328e1d6dc65SNate Williams 		delta_ticks = time_change->tv_sec * hz +
1329e1d6dc65SNate Williams 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
1330e1d6dc65SNate Williams 	else
1331e1d6dc65SNate Williams 		delta_ticks = LONG_MAX;
1332e1d6dc65SNate Williams 
1333e1d6dc65SNate Williams 	if (delta_ticks > INT_MAX)
1334e1d6dc65SNate Williams 		delta_ticks = INT_MAX;
1335e1d6dc65SNate Williams 
1336e1d6dc65SNate Williams 	/*
1337e1d6dc65SNate Williams 	 * Now rip through the timer calltodo list looking for timers
1338e1d6dc65SNate Williams 	 * to expire.
1339e1d6dc65SNate Williams 	 */
1340e1d6dc65SNate Williams 
1341e1d6dc65SNate Williams 	/* don't collide with softclock() */
13428d809d50SJeff Roberson 	CC_LOCK(cc);
1343e1d6dc65SNate Williams 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1344e1d6dc65SNate Williams 		p->c_time -= delta_ticks;
1345e1d6dc65SNate Williams 
1346e1d6dc65SNate Williams 		/* Break if the timer had more time on it than delta_ticks */
1347e1d6dc65SNate Williams 		if (p->c_time > 0)
1348e1d6dc65SNate Williams 			break;
1349e1d6dc65SNate Williams 
1350e1d6dc65SNate Williams 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1351e1d6dc65SNate Williams 		delta_ticks = -p->c_time;
1352e1d6dc65SNate Williams 	}
13538d809d50SJeff Roberson 	CC_UNLOCK(cc);
1354e1d6dc65SNate Williams 
1355e1d6dc65SNate Williams 	return;
1356e1d6dc65SNate Williams }
1357e1d6dc65SNate Williams #endif /* APM_FIXUP_CALLTODO */
13585b999a6bSDavide Italiano 
13595b999a6bSDavide Italiano static int
13605b999a6bSDavide Italiano flssbt(sbintime_t sbt)
13615b999a6bSDavide Italiano {
13625b999a6bSDavide Italiano 
13635b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
13645b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
13655b999a6bSDavide Italiano 		return (flsl(sbt));
13665b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
13675b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
13685b999a6bSDavide Italiano 	return (flsl(sbt));
13695b999a6bSDavide Italiano }
13705b999a6bSDavide Italiano 
13715b999a6bSDavide Italiano /*
13725b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
13735b999a6bSDavide Italiano  */
13745b999a6bSDavide Italiano static int
13755b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
13765b999a6bSDavide Italiano {
13775b999a6bSDavide Italiano 	struct callout *tmp;
13785b999a6bSDavide Italiano 	struct callout_cpu *cc;
13795b999a6bSDavide Italiano 	struct callout_list *sc;
13805b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
13815b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
13825b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
13835b999a6bSDavide Italiano #ifdef SMP
13845b999a6bSDavide Italiano 	int cpu;
13855b999a6bSDavide Italiano #endif
13865b999a6bSDavide Italiano 
13875b999a6bSDavide Italiano 	val = 0;
13885b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
13895b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
13905b999a6bSDavide Italiano 		return (error);
13915b999a6bSDavide Italiano 	count = maxc = 0;
13925b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
13935b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
13945b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
13955b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
13965b999a6bSDavide Italiano 	now = sbinuptime();
13975b999a6bSDavide Italiano #ifdef SMP
13985b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
13995b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
14005b999a6bSDavide Italiano #else
14015b999a6bSDavide Italiano 		cc = CC_CPU(timeout_cpu);
14025b999a6bSDavide Italiano #endif
14035b999a6bSDavide Italiano 		CC_LOCK(cc);
14045b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
14055b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
14065b999a6bSDavide Italiano 			c = 0;
14075b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
14085b999a6bSDavide Italiano 				c++;
14095b999a6bSDavide Italiano 				t = tmp->c_time - now;
14105b999a6bSDavide Italiano 				if (t < 0)
14115b999a6bSDavide Italiano 					t = 0;
14125b999a6bSDavide Italiano 				st += t / SBT_1US;
14135b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
14145b999a6bSDavide Italiano 				if (t > maxt)
14155b999a6bSDavide Italiano 					maxt = t;
14165b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
14175b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
14185b999a6bSDavide Italiano 				ct[flssbt(t)]++;
14195b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
14205b999a6bSDavide Italiano 			}
14215b999a6bSDavide Italiano 			if (c > maxc)
14225b999a6bSDavide Italiano 				maxc = c;
14235b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
14245b999a6bSDavide Italiano 			count += c;
14255b999a6bSDavide Italiano 		}
14265b999a6bSDavide Italiano 		CC_UNLOCK(cc);
14275b999a6bSDavide Italiano #ifdef SMP
14285b999a6bSDavide Italiano 	}
14295b999a6bSDavide Italiano #endif
14305b999a6bSDavide Italiano 
14315b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
14325b999a6bSDavide Italiano 		tcum += ct[i];
14335b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14345b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
14355b999a6bSDavide Italiano 		pcum += cpr[i];
14365b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
14375b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
14385b999a6bSDavide Italiano 		c += ccpbk[i];
14395b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
14405b999a6bSDavide Italiano 
14415b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
14425b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
14435b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
14445b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
14455b999a6bSDavide Italiano 	    medc,
14465b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
14475b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
14485b999a6bSDavide Italiano 	    maxc);
14495b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14505b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
14515b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
14525b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
14535b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14545b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
14555b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
14565b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
14575b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
14585b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
14595b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
14605b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
14615b999a6bSDavide Italiano 			continue;
14625b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
14635b999a6bSDavide Italiano 		tcum += ct[i];
14645b999a6bSDavide Italiano 		pcum += cpr[i];
14655b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
14665b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
14675b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
14685b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
14695b999a6bSDavide Italiano 	}
14705b999a6bSDavide Italiano 	return (error);
14715b999a6bSDavide Italiano }
14725b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
14735b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
14745b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
14755b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
1476