xref: /freebsd/sys/kern/kern_timeout.c (revision 037637812d953f28f3348b548ccb71225b3aaaaf)
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"
4191dd9aaeSRobert Watson #include "opt_kdtrace.h"
425b999a6bSDavide Italiano #if defined(__arm__)
435b999a6bSDavide Italiano #include "opt_timer.h"
445b999a6bSDavide Italiano #endif
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>
508d809d50SJeff Roberson #include <sys/interrupt.h>
51df8bae1dSRodney W. Grimes #include <sys/kernel.h>
52ff7ec58aSRobert Watson #include <sys/ktr.h>
53f34fa851SJohn Baldwin #include <sys/lock.h>
548d809d50SJeff Roberson #include <sys/malloc.h>
55cb799bfeSJohn Baldwin #include <sys/mutex.h>
5621f9e816SJohn Baldwin #include <sys/proc.h>
5791dd9aaeSRobert Watson #include <sys/sdt.h>
586a0ce57dSAttilio Rao #include <sys/sleepqueue.h>
5922ee8c4fSPoul-Henning Kamp #include <sys/sysctl.h>
608d809d50SJeff Roberson #include <sys/smp.h>
61df8bae1dSRodney W. Grimes 
621283e9cdSAttilio Rao #ifdef SMP
631283e9cdSAttilio Rao #include <machine/cpu.h>
641283e9cdSAttilio Rao #endif
651283e9cdSAttilio Rao 
665b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
675b999a6bSDavide Italiano DPCPU_DECLARE(sbintime_t, hardclocktime);
685b999a6bSDavide Italiano #endif
695b999a6bSDavide Italiano 
7091dd9aaeSRobert Watson SDT_PROVIDER_DEFINE(callout_execute);
7179856499SRui Paulo SDT_PROBE_DEFINE(callout_execute, kernel, , callout_start, callout-start);
7291dd9aaeSRobert Watson SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_start, 0,
7391dd9aaeSRobert Watson     "struct callout *");
7479856499SRui Paulo SDT_PROBE_DEFINE(callout_execute, kernel, , callout_end, callout-end);
7591dd9aaeSRobert Watson SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_end, 0,
7691dd9aaeSRobert Watson     "struct callout *");
7791dd9aaeSRobert Watson 
785b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7922ee8c4fSPoul-Henning Kamp static int avg_depth;
8022ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
8122ee8c4fSPoul-Henning Kamp     "Average number of items examined per softclock call. Units = 1/1000");
8222ee8c4fSPoul-Henning Kamp static int avg_gcalls;
8322ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
8422ee8c4fSPoul-Henning Kamp     "Average number of Giant callouts made per softclock call. Units = 1/1000");
8564b9ee20SAttilio Rao static int avg_lockcalls;
8664b9ee20SAttilio Rao SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
8764b9ee20SAttilio Rao     "Average number of lock callouts made per softclock call. Units = 1/1000");
8822ee8c4fSPoul-Henning Kamp static int avg_mpcalls;
8922ee8c4fSPoul-Henning Kamp SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
9022ee8c4fSPoul-Henning Kamp     "Average number of MP callouts made per softclock call. Units = 1/1000");
915b999a6bSDavide Italiano static int avg_depth_dir;
925b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
935b999a6bSDavide Italiano     "Average number of direct callouts examined per callout_process call. "
945b999a6bSDavide Italiano     "Units = 1/1000");
955b999a6bSDavide Italiano static int avg_lockcalls_dir;
965b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
975b999a6bSDavide Italiano     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
985b999a6bSDavide Italiano     "callout_process call. Units = 1/1000");
995b999a6bSDavide Italiano static int avg_mpcalls_dir;
1005b999a6bSDavide Italiano SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
1015b999a6bSDavide Italiano     0, "Average number of MP direct callouts made per callout_process call. "
1025b999a6bSDavide Italiano     "Units = 1/1000");
1035b999a6bSDavide Italiano #endif
10415b7a470SPoul-Henning Kamp /*
10515b7a470SPoul-Henning Kamp  * TODO:
10615b7a470SPoul-Henning Kamp  *	allocate more timeout table slots when table overflows.
10715b7a470SPoul-Henning Kamp  */
1083f555c45SDavide Italiano u_int callwheelsize, callwheelmask;
109f23b4c91SGarrett Wollman 
11020c510f8SLuigi Rizzo /*
1115b999a6bSDavide Italiano  * The callout cpu exec entities represent informations necessary for
1125b999a6bSDavide Italiano  * describing the state of callouts currently running on the CPU and the ones
1135b999a6bSDavide Italiano  * necessary for migrating callouts to the new callout cpu. In particular,
1145b999a6bSDavide Italiano  * the first entry of the array cc_exec_entity holds informations for callout
1155b999a6bSDavide Italiano  * running in SWI thread context, while the second one holds informations
1165b999a6bSDavide Italiano  * for callout running directly from hardware interrupt context.
1171283e9cdSAttilio Rao  * The cached informations are very important for deferring migration when
1181283e9cdSAttilio Rao  * the migrating callout is already running.
1191283e9cdSAttilio Rao  */
1205b999a6bSDavide Italiano struct cc_exec {
1215b999a6bSDavide Italiano 	struct callout		*cc_next;
1225b999a6bSDavide Italiano 	struct callout		*cc_curr;
1231283e9cdSAttilio Rao #ifdef SMP
1241283e9cdSAttilio Rao 	void			(*ce_migration_func)(void *);
1251283e9cdSAttilio Rao 	void			*ce_migration_arg;
1261283e9cdSAttilio Rao 	int			ce_migration_cpu;
1275b999a6bSDavide Italiano 	sbintime_t		ce_migration_time;
1281283e9cdSAttilio Rao #endif
1295b999a6bSDavide Italiano 	boolean_t		cc_cancel;
1305b999a6bSDavide Italiano 	boolean_t		cc_waiting;
1311283e9cdSAttilio Rao };
1321283e9cdSAttilio Rao 
1331283e9cdSAttilio Rao /*
13420c510f8SLuigi Rizzo  * There is one struct callout_cpu per cpu, holding all relevant
13520c510f8SLuigi Rizzo  * state for the callout processing thread on the individual CPU.
13620c510f8SLuigi Rizzo  */
1378d809d50SJeff Roberson struct callout_cpu {
1384ceaf45dSAttilio Rao 	struct mtx_padalign	cc_lock;
1395b999a6bSDavide Italiano 	struct cc_exec 		cc_exec_entity[2];
1408d809d50SJeff Roberson 	struct callout		*cc_callout;
1415b999a6bSDavide Italiano 	struct callout_list	*cc_callwheel;
1425b999a6bSDavide Italiano 	struct callout_tailq	cc_expireq;
1435b999a6bSDavide Italiano 	struct callout_slist	cc_callfree;
1445b999a6bSDavide Italiano 	sbintime_t		cc_firstevent;
1455b999a6bSDavide Italiano 	sbintime_t		cc_lastscan;
1468d809d50SJeff Roberson 	void			*cc_cookie;
1475b999a6bSDavide Italiano 	u_int			cc_bucket;
1488d809d50SJeff Roberson };
1498d809d50SJeff Roberson 
1505b999a6bSDavide Italiano #define	cc_exec_curr		cc_exec_entity[0].cc_curr
1515b999a6bSDavide Italiano #define	cc_exec_next		cc_exec_entity[0].cc_next
1525b999a6bSDavide Italiano #define	cc_exec_cancel		cc_exec_entity[0].cc_cancel
1535b999a6bSDavide Italiano #define	cc_exec_waiting		cc_exec_entity[0].cc_waiting
1545b999a6bSDavide Italiano #define	cc_exec_curr_dir	cc_exec_entity[1].cc_curr
1555b999a6bSDavide Italiano #define	cc_exec_next_dir	cc_exec_entity[1].cc_next
1565b999a6bSDavide Italiano #define	cc_exec_cancel_dir	cc_exec_entity[1].cc_cancel
1575b999a6bSDavide Italiano #define	cc_exec_waiting_dir	cc_exec_entity[1].cc_waiting
1585b999a6bSDavide Italiano 
1598d809d50SJeff Roberson #ifdef SMP
1605b999a6bSDavide Italiano #define	cc_migration_func	cc_exec_entity[0].ce_migration_func
1615b999a6bSDavide Italiano #define	cc_migration_arg	cc_exec_entity[0].ce_migration_arg
1625b999a6bSDavide Italiano #define	cc_migration_cpu	cc_exec_entity[0].ce_migration_cpu
1635b999a6bSDavide Italiano #define	cc_migration_time	cc_exec_entity[0].ce_migration_time
1645b999a6bSDavide Italiano #define	cc_migration_func_dir	cc_exec_entity[1].ce_migration_func
1655b999a6bSDavide Italiano #define	cc_migration_arg_dir	cc_exec_entity[1].ce_migration_arg
1665b999a6bSDavide Italiano #define	cc_migration_cpu_dir	cc_exec_entity[1].ce_migration_cpu
1675b999a6bSDavide Italiano #define	cc_migration_time_dir	cc_exec_entity[1].ce_migration_time
1681283e9cdSAttilio Rao 
1698d809d50SJeff Roberson struct callout_cpu cc_cpu[MAXCPU];
1701283e9cdSAttilio Rao #define	CPUBLOCK	MAXCPU
1718d809d50SJeff Roberson #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
1728d809d50SJeff Roberson #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
1738d809d50SJeff Roberson #else
1748d809d50SJeff Roberson struct callout_cpu cc_cpu;
1758d809d50SJeff Roberson #define	CC_CPU(cpu)	&cc_cpu
1768d809d50SJeff Roberson #define	CC_SELF()	&cc_cpu
1778d809d50SJeff Roberson #endif
1788d809d50SJeff Roberson #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
1798d809d50SJeff Roberson #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
1801283e9cdSAttilio Rao #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
1818d809d50SJeff Roberson 
1828d809d50SJeff Roberson static int timeout_cpu;
1835b999a6bSDavide Italiano 
1845b999a6bSDavide Italiano static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
1855b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
1865b999a6bSDavide Italiano 		    int *mpcalls, int *lockcalls, int *gcalls,
1875b999a6bSDavide Italiano #endif
1885b999a6bSDavide Italiano 		    int direct);
1898d809d50SJeff Roberson 
190d745c852SEd Schouten static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
19149a74476SColin Percival 
192e9dec2c4SColin Percival /**
1938d809d50SJeff Roberson  * Locked by cc_lock:
1945b999a6bSDavide Italiano  *   cc_curr         - If a callout is in progress, it is cc_curr.
1955b999a6bSDavide Italiano  *                     If cc_curr is non-NULL, threads waiting in
196b36f4588SJohn Baldwin  *                     callout_drain() will be woken up as soon as the
1972c1bb207SColin Percival  *                     relevant callout completes.
1985b999a6bSDavide Italiano  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
19998c926b2SIan Dowse  *                     guarantees that the current callout will not run.
20098c926b2SIan Dowse  *                     The softclock() function sets this to 0 before it
20164b9ee20SAttilio Rao  *                     drops callout_lock to acquire c_lock, and it calls
202b36f4588SJohn Baldwin  *                     the handler only if curr_cancelled is still 0 after
2035b999a6bSDavide Italiano  *                     cc_lock is successfully acquired.
2048d809d50SJeff Roberson  *   cc_waiting      - If a thread is waiting in callout_drain(), then
205b36f4588SJohn Baldwin  *                     callout_wait is nonzero.  Set only when
2065b999a6bSDavide Italiano  *                     cc_curr is non-NULL.
2072c1bb207SColin Percival  */
208df8bae1dSRodney W. Grimes 
209df8bae1dSRodney W. Grimes /*
2105b999a6bSDavide Italiano  * Resets the execution entity tied to a specific callout cpu.
2111283e9cdSAttilio Rao  */
2121283e9cdSAttilio Rao static void
2135b999a6bSDavide Italiano cc_cce_cleanup(struct callout_cpu *cc, int direct)
2141283e9cdSAttilio Rao {
2151283e9cdSAttilio Rao 
2165b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_curr = NULL;
2175b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_next = NULL;
2185b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_cancel = FALSE;
2195b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_waiting = FALSE;
2201283e9cdSAttilio Rao #ifdef SMP
2215b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_cpu = CPUBLOCK;
2225b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_time = 0;
2235b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_func = NULL;
2245b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].ce_migration_arg = NULL;
2251283e9cdSAttilio Rao #endif
2261283e9cdSAttilio Rao }
2271283e9cdSAttilio Rao 
2281283e9cdSAttilio Rao /*
2291283e9cdSAttilio Rao  * Checks if migration is requested by a specific callout cpu.
2301283e9cdSAttilio Rao  */
2311283e9cdSAttilio Rao static int
2325b999a6bSDavide Italiano cc_cce_migrating(struct callout_cpu *cc, int direct)
2331283e9cdSAttilio Rao {
2341283e9cdSAttilio Rao 
2351283e9cdSAttilio Rao #ifdef SMP
2365b999a6bSDavide Italiano 	return (cc->cc_exec_entity[direct].ce_migration_cpu != CPUBLOCK);
2371283e9cdSAttilio Rao #else
2381283e9cdSAttilio Rao 	return (0);
2391283e9cdSAttilio Rao #endif
2401283e9cdSAttilio Rao }
2411283e9cdSAttilio Rao 
2421283e9cdSAttilio Rao /*
243219d632cSMatthew Dillon  * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization
244219d632cSMatthew Dillon  *
245219d632cSMatthew Dillon  *	This code is called very early in the kernel initialization sequence,
246219d632cSMatthew Dillon  *	and may be called more then once.
247219d632cSMatthew Dillon  */
248219d632cSMatthew Dillon caddr_t
249219d632cSMatthew Dillon kern_timeout_callwheel_alloc(caddr_t v)
250219d632cSMatthew Dillon {
2518d809d50SJeff Roberson 	struct callout_cpu *cc;
2528d809d50SJeff Roberson 
2538d809d50SJeff Roberson 	timeout_cpu = PCPU_GET(cpuid);
2548d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
255219d632cSMatthew Dillon 	/*
256922314f0SAlfred Perlstein 	 * Calculate callout wheel size, should be next power of two higher
257922314f0SAlfred Perlstein 	 * than 'ncallout'.
258219d632cSMatthew Dillon 	 */
259922314f0SAlfred Perlstein 	callwheelsize = 1 << fls(ncallout);
260219d632cSMatthew Dillon 	callwheelmask = callwheelsize - 1;
261219d632cSMatthew Dillon 
2628d809d50SJeff Roberson 	cc->cc_callout = (struct callout *)v;
2638d809d50SJeff Roberson 	v = (caddr_t)(cc->cc_callout + ncallout);
2645b999a6bSDavide Italiano 	cc->cc_callwheel = (struct callout_list *)v;
2658d809d50SJeff Roberson 	v = (caddr_t)(cc->cc_callwheel + callwheelsize);
266219d632cSMatthew Dillon 	return(v);
267219d632cSMatthew Dillon }
268219d632cSMatthew Dillon 
2698d809d50SJeff Roberson static void
2708d809d50SJeff Roberson callout_cpu_init(struct callout_cpu *cc)
2718d809d50SJeff Roberson {
2728d809d50SJeff Roberson 	struct callout *c;
2738d809d50SJeff Roberson 	int i;
2748d809d50SJeff Roberson 
2758d809d50SJeff Roberson 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
2768d809d50SJeff Roberson 	SLIST_INIT(&cc->cc_callfree);
2775b999a6bSDavide Italiano 	for (i = 0; i < callwheelsize; i++)
2785b999a6bSDavide Italiano 		LIST_INIT(&cc->cc_callwheel[i]);
2795b999a6bSDavide Italiano 	TAILQ_INIT(&cc->cc_expireq);
2805b999a6bSDavide Italiano 	cc->cc_firstevent = INT64_MAX;
2815b999a6bSDavide Italiano 	for (i = 0; i < 2; i++)
2825b999a6bSDavide Italiano 		cc_cce_cleanup(cc, i);
2838d809d50SJeff Roberson 	if (cc->cc_callout == NULL)
2848d809d50SJeff Roberson 		return;
2858d809d50SJeff Roberson 	for (i = 0; i < ncallout; i++) {
2868d809d50SJeff Roberson 		c = &cc->cc_callout[i];
2878d809d50SJeff Roberson 		callout_init(c, 0);
2888d809d50SJeff Roberson 		c->c_flags = CALLOUT_LOCAL_ALLOC;
2898d809d50SJeff Roberson 		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
2908d809d50SJeff Roberson 	}
2918d809d50SJeff Roberson }
2928d809d50SJeff Roberson 
2931283e9cdSAttilio Rao #ifdef SMP
2941283e9cdSAttilio Rao /*
2951283e9cdSAttilio Rao  * Switches the cpu tied to a specific callout.
2961283e9cdSAttilio Rao  * The function expects a locked incoming callout cpu and returns with
2971283e9cdSAttilio Rao  * locked outcoming callout cpu.
2981283e9cdSAttilio Rao  */
2991283e9cdSAttilio Rao static struct callout_cpu *
3001283e9cdSAttilio Rao callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
3011283e9cdSAttilio Rao {
3021283e9cdSAttilio Rao 	struct callout_cpu *new_cc;
3031283e9cdSAttilio Rao 
3041283e9cdSAttilio Rao 	MPASS(c != NULL && cc != NULL);
3051283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
3061283e9cdSAttilio Rao 
307e75baa28SAttilio Rao 	/*
308e75baa28SAttilio Rao 	 * Avoid interrupts and preemption firing after the callout cpu
309e75baa28SAttilio Rao 	 * is blocked in order to avoid deadlocks as the new thread
310e75baa28SAttilio Rao 	 * may be willing to acquire the callout cpu lock.
311e75baa28SAttilio Rao 	 */
3121283e9cdSAttilio Rao 	c->c_cpu = CPUBLOCK;
313e75baa28SAttilio Rao 	spinlock_enter();
3141283e9cdSAttilio Rao 	CC_UNLOCK(cc);
3151283e9cdSAttilio Rao 	new_cc = CC_CPU(new_cpu);
3161283e9cdSAttilio Rao 	CC_LOCK(new_cc);
317e75baa28SAttilio Rao 	spinlock_exit();
3181283e9cdSAttilio Rao 	c->c_cpu = new_cpu;
3191283e9cdSAttilio Rao 	return (new_cc);
3201283e9cdSAttilio Rao }
3211283e9cdSAttilio Rao #endif
3221283e9cdSAttilio Rao 
323219d632cSMatthew Dillon /*
324219d632cSMatthew Dillon  * kern_timeout_callwheel_init() - initialize previously reserved callwheel
325219d632cSMatthew Dillon  *				   space.
326219d632cSMatthew Dillon  *
327219d632cSMatthew Dillon  *	This code is called just once, after the space reserved for the
328219d632cSMatthew Dillon  *	callout wheel has been finalized.
329219d632cSMatthew Dillon  */
330219d632cSMatthew Dillon void
331219d632cSMatthew Dillon kern_timeout_callwheel_init(void)
332219d632cSMatthew Dillon {
3338d809d50SJeff Roberson 	callout_cpu_init(CC_CPU(timeout_cpu));
3348d809d50SJeff Roberson }
335219d632cSMatthew Dillon 
3368d809d50SJeff Roberson /*
3378d809d50SJeff Roberson  * Start standard softclock thread.
3388d809d50SJeff Roberson  */
3398d809d50SJeff Roberson static void
3408d809d50SJeff Roberson start_softclock(void *dummy)
3418d809d50SJeff Roberson {
3428d809d50SJeff Roberson 	struct callout_cpu *cc;
3438d809d50SJeff Roberson #ifdef SMP
3448d809d50SJeff Roberson 	int cpu;
3458d809d50SJeff Roberson #endif
3468d809d50SJeff Roberson 
3478d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
3488d809d50SJeff Roberson 	if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
3493350df48SJohn Baldwin 	    INTR_MPSAFE, &cc->cc_cookie))
3508d809d50SJeff Roberson 		panic("died while creating standard software ithreads");
3518d809d50SJeff Roberson #ifdef SMP
3523aa6d94eSJohn Baldwin 	CPU_FOREACH(cpu) {
3538d809d50SJeff Roberson 		if (cpu == timeout_cpu)
3548d809d50SJeff Roberson 			continue;
3558d809d50SJeff Roberson 		cc = CC_CPU(cpu);
3568d809d50SJeff Roberson 		if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
3578d809d50SJeff Roberson 		    INTR_MPSAFE, &cc->cc_cookie))
3588d809d50SJeff Roberson 			panic("died while creating standard software ithreads");
3598d809d50SJeff Roberson 		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(). */
3608d809d50SJeff Roberson 		cc->cc_callwheel = malloc(
3615b999a6bSDavide Italiano 		    sizeof(struct callout_list) * callwheelsize, M_CALLOUT,
3628d809d50SJeff Roberson 		    M_WAITOK);
3638d809d50SJeff Roberson 		callout_cpu_init(cc);
364219d632cSMatthew Dillon 	}
3658d809d50SJeff Roberson #endif
366219d632cSMatthew Dillon }
3678d809d50SJeff Roberson 
3688d809d50SJeff Roberson SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
3698d809d50SJeff Roberson 
3705b999a6bSDavide Italiano #define	CC_HASH_SHIFT	8
3718d809d50SJeff Roberson 
3725b999a6bSDavide Italiano static inline u_int
3735b999a6bSDavide Italiano callout_hash(sbintime_t sbt)
3745b999a6bSDavide Italiano {
3755b999a6bSDavide Italiano 
3765b999a6bSDavide Italiano 	return (sbt >> (32 - CC_HASH_SHIFT));
3775b999a6bSDavide Italiano }
3785b999a6bSDavide Italiano 
3795b999a6bSDavide Italiano static inline u_int
3805b999a6bSDavide Italiano callout_get_bucket(sbintime_t sbt)
3815b999a6bSDavide Italiano {
3825b999a6bSDavide Italiano 
3835b999a6bSDavide Italiano 	return (callout_hash(sbt) & callwheelmask);
3845b999a6bSDavide Italiano }
3855b999a6bSDavide Italiano 
3865b999a6bSDavide Italiano void
3875b999a6bSDavide Italiano callout_process(sbintime_t now)
3885b999a6bSDavide Italiano {
3895b999a6bSDavide Italiano 	struct callout *tmp, *tmpn;
3905b999a6bSDavide Italiano 	struct callout_cpu *cc;
3915b999a6bSDavide Italiano 	struct callout_list *sc;
3925b999a6bSDavide Italiano 	sbintime_t first, last, max, tmp_max;
3935b999a6bSDavide Italiano 	uint32_t lookahead;
3945b999a6bSDavide Italiano 	u_int firstb, lastb, nowb;
3955b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
3965b999a6bSDavide Italiano 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
3975b999a6bSDavide Italiano #endif
3985b999a6bSDavide Italiano 
3998d809d50SJeff Roberson 	cc = CC_SELF();
4008d809d50SJeff Roberson 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
4015b999a6bSDavide Italiano 
4025b999a6bSDavide Italiano 	/* Compute the buckets of the last scan and present times. */
4035b999a6bSDavide Italiano 	firstb = callout_hash(cc->cc_lastscan);
4045b999a6bSDavide Italiano 	cc->cc_lastscan = now;
4055b999a6bSDavide Italiano 	nowb = callout_hash(now);
4065b999a6bSDavide Italiano 
4075b999a6bSDavide Italiano 	/* Compute the last bucket and minimum time of the bucket after it. */
4085b999a6bSDavide Italiano 	if (nowb == firstb)
4095b999a6bSDavide Italiano 		lookahead = (SBT_1S / 16);
4105b999a6bSDavide Italiano 	else if (nowb - firstb == 1)
4115b999a6bSDavide Italiano 		lookahead = (SBT_1S / 8);
4125b999a6bSDavide Italiano 	else
4135b999a6bSDavide Italiano 		lookahead = (SBT_1S / 2);
4145b999a6bSDavide Italiano 	first = last = now;
4155b999a6bSDavide Italiano 	first += (lookahead / 2);
4165b999a6bSDavide Italiano 	last += lookahead;
4175b999a6bSDavide Italiano 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
4185b999a6bSDavide Italiano 	lastb = callout_hash(last) - 1;
4195b999a6bSDavide Italiano 	max = last;
4205b999a6bSDavide Italiano 
4215b999a6bSDavide Italiano 	/*
4225b999a6bSDavide Italiano 	 * Check if we wrapped around the entire wheel from the last scan.
4235b999a6bSDavide Italiano 	 * In case, we need to scan entirely the wheel for pending callouts.
4245b999a6bSDavide Italiano 	 */
4255b999a6bSDavide Italiano 	if (lastb - firstb >= callwheelsize) {
4265b999a6bSDavide Italiano 		lastb = firstb + callwheelsize - 1;
4275b999a6bSDavide Italiano 		if (nowb - firstb >= callwheelsize)
4285b999a6bSDavide Italiano 			nowb = lastb;
4299fc51b0bSJeff Roberson 	}
4305b999a6bSDavide Italiano 
4315b999a6bSDavide Italiano 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
4325b999a6bSDavide Italiano 	do {
4335b999a6bSDavide Italiano 		sc = &cc->cc_callwheel[firstb & callwheelmask];
4345b999a6bSDavide Italiano 		tmp = LIST_FIRST(sc);
4355b999a6bSDavide Italiano 		while (tmp != NULL) {
4365b999a6bSDavide Italiano 			/* Run the callout if present time within allowed. */
4375b999a6bSDavide Italiano 			if (tmp->c_time <= now) {
4385b999a6bSDavide Italiano 				/*
4395b999a6bSDavide Italiano 				 * Consumer told us the callout may be run
4405b999a6bSDavide Italiano 				 * directly from hardware interrupt context.
4415b999a6bSDavide Italiano 				 */
4425b999a6bSDavide Italiano 				if (tmp->c_flags & CALLOUT_DIRECT) {
4435b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4445b999a6bSDavide Italiano 					++depth_dir;
4455b999a6bSDavide Italiano #endif
4465b999a6bSDavide Italiano 					cc->cc_exec_next_dir =
4475b999a6bSDavide Italiano 					    LIST_NEXT(tmp, c_links.le);
4485b999a6bSDavide Italiano 					cc->cc_bucket = firstb & callwheelmask;
4495b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4505b999a6bSDavide Italiano 					softclock_call_cc(tmp, cc,
4515b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4525b999a6bSDavide Italiano 					    &mpcalls_dir, &lockcalls_dir, NULL,
4535b999a6bSDavide Italiano #endif
4545b999a6bSDavide Italiano 					    1);
4555b999a6bSDavide Italiano 					tmp = cc->cc_exec_next_dir;
4565b999a6bSDavide Italiano 				} else {
4575b999a6bSDavide Italiano 					tmpn = LIST_NEXT(tmp, c_links.le);
4585b999a6bSDavide Italiano 					LIST_REMOVE(tmp, c_links.le);
4595b999a6bSDavide Italiano 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
4605b999a6bSDavide Italiano 					    tmp, c_links.tqe);
4615b999a6bSDavide Italiano 					tmp->c_flags |= CALLOUT_PROCESSED;
4625b999a6bSDavide Italiano 					tmp = tmpn;
4639fc51b0bSJeff Roberson 				}
4645b999a6bSDavide Italiano 				continue;
4655b999a6bSDavide Italiano 			}
4665b999a6bSDavide Italiano 			/* Skip events from distant future. */
4675b999a6bSDavide Italiano 			if (tmp->c_time >= max)
4685b999a6bSDavide Italiano 				goto next;
4695b999a6bSDavide Italiano 			/*
4705b999a6bSDavide Italiano 			 * Event minimal time is bigger than present maximal
4715b999a6bSDavide Italiano 			 * time, so it cannot be aggregated.
4725b999a6bSDavide Italiano 			 */
4735b999a6bSDavide Italiano 			if (tmp->c_time > last) {
4745b999a6bSDavide Italiano 				lastb = nowb;
4755b999a6bSDavide Italiano 				goto next;
4765b999a6bSDavide Italiano 			}
4775b999a6bSDavide Italiano 			/* Update first and last time, respecting this event. */
4785b999a6bSDavide Italiano 			if (tmp->c_time < first)
4795b999a6bSDavide Italiano 				first = tmp->c_time;
4805b999a6bSDavide Italiano 			tmp_max = tmp->c_time + tmp->c_precision;
4815b999a6bSDavide Italiano 			if (tmp_max < last)
4825b999a6bSDavide Italiano 				last = tmp_max;
4835b999a6bSDavide Italiano next:
4845b999a6bSDavide Italiano 			tmp = LIST_NEXT(tmp, c_links.le);
4855b999a6bSDavide Italiano 		}
4865b999a6bSDavide Italiano 		/* Proceed with the next bucket. */
4875b999a6bSDavide Italiano 		firstb++;
4885b999a6bSDavide Italiano 		/*
4895b999a6bSDavide Italiano 		 * Stop if we looked after present time and found
4905b999a6bSDavide Italiano 		 * some event we can't execute at now.
4915b999a6bSDavide Italiano 		 * Stop if we looked far enough into the future.
4925b999a6bSDavide Italiano 		 */
4935b999a6bSDavide Italiano 	} while (((int)(firstb - lastb)) <= 0);
4945b999a6bSDavide Italiano 	cc->cc_firstevent = last;
4955b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
4965b999a6bSDavide Italiano 	cpu_new_callout(curcpu, last, first);
4975b999a6bSDavide Italiano #endif
4985b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
4995b999a6bSDavide Italiano 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
5005b999a6bSDavide Italiano 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
5015b999a6bSDavide Italiano 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
5025b999a6bSDavide Italiano #endif
5038d809d50SJeff Roberson 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
5048d809d50SJeff Roberson 	/*
5058d809d50SJeff Roberson 	 * swi_sched acquires the thread lock, so we don't want to call it
5068d809d50SJeff Roberson 	 * with cc_lock held; incorrect locking order.
5078d809d50SJeff Roberson 	 */
5085b999a6bSDavide Italiano 	if (!TAILQ_EMPTY(&cc->cc_expireq))
5098d809d50SJeff Roberson 		swi_sched(cc->cc_cookie, 0);
5108d809d50SJeff Roberson }
5118d809d50SJeff Roberson 
5128d809d50SJeff Roberson static struct callout_cpu *
5138d809d50SJeff Roberson callout_lock(struct callout *c)
5148d809d50SJeff Roberson {
5158d809d50SJeff Roberson 	struct callout_cpu *cc;
5168d809d50SJeff Roberson 	int cpu;
5178d809d50SJeff Roberson 
5188d809d50SJeff Roberson 	for (;;) {
5198d809d50SJeff Roberson 		cpu = c->c_cpu;
5201283e9cdSAttilio Rao #ifdef SMP
5211283e9cdSAttilio Rao 		if (cpu == CPUBLOCK) {
5221283e9cdSAttilio Rao 			while (c->c_cpu == CPUBLOCK)
5231283e9cdSAttilio Rao 				cpu_spinwait();
5241283e9cdSAttilio Rao 			continue;
5251283e9cdSAttilio Rao 		}
5261283e9cdSAttilio Rao #endif
5278d809d50SJeff Roberson 		cc = CC_CPU(cpu);
5288d809d50SJeff Roberson 		CC_LOCK(cc);
5298d809d50SJeff Roberson 		if (cpu == c->c_cpu)
5308d809d50SJeff Roberson 			break;
5318d809d50SJeff Roberson 		CC_UNLOCK(cc);
5328d809d50SJeff Roberson 	}
5338d809d50SJeff Roberson 	return (cc);
534219d632cSMatthew Dillon }
535219d632cSMatthew Dillon 
5361283e9cdSAttilio Rao static void
5375b999a6bSDavide Italiano callout_cc_add(struct callout *c, struct callout_cpu *cc,
5385b999a6bSDavide Italiano     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
5395b999a6bSDavide Italiano     void *arg, int cpu, int flags)
5401283e9cdSAttilio Rao {
5415b999a6bSDavide Italiano 	int bucket;
5421283e9cdSAttilio Rao 
5431283e9cdSAttilio Rao 	CC_LOCK_ASSERT(cc);
5445b999a6bSDavide Italiano 	if (sbt < cc->cc_lastscan)
5455b999a6bSDavide Italiano 		sbt = cc->cc_lastscan;
5461283e9cdSAttilio Rao 	c->c_arg = arg;
5471283e9cdSAttilio Rao 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
5485b999a6bSDavide Italiano 	if (flags & C_DIRECT_EXEC)
5495b999a6bSDavide Italiano 		c->c_flags |= CALLOUT_DIRECT;
5505b999a6bSDavide Italiano 	c->c_flags &= ~CALLOUT_PROCESSED;
5511283e9cdSAttilio Rao 	c->c_func = func;
5525b999a6bSDavide Italiano 	c->c_time = sbt;
5535b999a6bSDavide Italiano 	c->c_precision = precision;
5545b999a6bSDavide Italiano 	bucket = callout_get_bucket(c->c_time);
5555b999a6bSDavide Italiano 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
5565b999a6bSDavide Italiano 	    c, (int)(c->c_precision >> 32),
5575b999a6bSDavide Italiano 	    (u_int)(c->c_precision & 0xffffffff));
5585b999a6bSDavide Italiano 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
5595b999a6bSDavide Italiano 	if (cc->cc_bucket == bucket)
5605b999a6bSDavide Italiano 		cc->cc_exec_next_dir = c;
5615b999a6bSDavide Italiano #ifndef NO_EVENTTIMERS
5625b999a6bSDavide Italiano 	/*
5635b999a6bSDavide Italiano 	 * Inform the eventtimers(4) subsystem there's a new callout
5645b999a6bSDavide Italiano 	 * that has been inserted, but only if really required.
5655b999a6bSDavide Italiano 	 */
5665b999a6bSDavide Italiano 	sbt = c->c_time + c->c_precision;
5675b999a6bSDavide Italiano 	if (sbt < cc->cc_firstevent) {
5685b999a6bSDavide Italiano 		cc->cc_firstevent = sbt;
5695b999a6bSDavide Italiano 		cpu_new_callout(cpu, sbt, c->c_time);
5701283e9cdSAttilio Rao 	}
5715b999a6bSDavide Italiano #endif
5721283e9cdSAttilio Rao }
5731283e9cdSAttilio Rao 
5746098e7acSKonstantin Belousov static void
5756098e7acSKonstantin Belousov callout_cc_del(struct callout *c, struct callout_cpu *cc)
5766098e7acSKonstantin Belousov {
5776098e7acSKonstantin Belousov 
578eb8a7186SKonstantin Belousov 	if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
579eb8a7186SKonstantin Belousov 		return;
5806098e7acSKonstantin Belousov 	c->c_func = NULL;
5816098e7acSKonstantin Belousov 	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
5826098e7acSKonstantin Belousov }
5836098e7acSKonstantin Belousov 
584eb8a7186SKonstantin Belousov static void
5855b999a6bSDavide Italiano softclock_call_cc(struct callout *c, struct callout_cpu *cc,
5865b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
5875b999a6bSDavide Italiano     int *mpcalls, int *lockcalls, int *gcalls,
5885b999a6bSDavide Italiano #endif
5895b999a6bSDavide Italiano     int direct)
5906098e7acSKonstantin Belousov {
5916098e7acSKonstantin Belousov 	void (*c_func)(void *);
5926098e7acSKonstantin Belousov 	void *c_arg;
5936098e7acSKonstantin Belousov 	struct lock_class *class;
5946098e7acSKonstantin Belousov 	struct lock_object *c_lock;
5956098e7acSKonstantin Belousov 	int c_flags, sharedlock;
5966098e7acSKonstantin Belousov #ifdef SMP
5976098e7acSKonstantin Belousov 	struct callout_cpu *new_cc;
5986098e7acSKonstantin Belousov 	void (*new_func)(void *);
5996098e7acSKonstantin Belousov 	void *new_arg;
6005b999a6bSDavide Italiano 	int flags, new_cpu;
6015b999a6bSDavide Italiano 	sbintime_t new_time;
6026098e7acSKonstantin Belousov #endif
6035b999a6bSDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
604*03763781SDavide Italiano 	sbintime_t sbt1, sbt2;
6056098e7acSKonstantin Belousov 	struct timespec ts2;
6065b999a6bSDavide Italiano 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
6076098e7acSKonstantin Belousov 	static timeout_t *lastfunc;
6086098e7acSKonstantin Belousov #endif
6096098e7acSKonstantin Belousov 
610eb8a7186SKonstantin Belousov 	KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
611eb8a7186SKonstantin Belousov 	    (CALLOUT_PENDING | CALLOUT_ACTIVE),
612eb8a7186SKonstantin Belousov 	    ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
6136098e7acSKonstantin Belousov 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
6146098e7acSKonstantin Belousov 	sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ? 0 : 1;
6156098e7acSKonstantin Belousov 	c_lock = c->c_lock;
6166098e7acSKonstantin Belousov 	c_func = c->c_func;
6176098e7acSKonstantin Belousov 	c_arg = c->c_arg;
6186098e7acSKonstantin Belousov 	c_flags = c->c_flags;
6196098e7acSKonstantin Belousov 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
6206098e7acSKonstantin Belousov 		c->c_flags = CALLOUT_LOCAL_ALLOC;
6216098e7acSKonstantin Belousov 	else
6226098e7acSKonstantin Belousov 		c->c_flags &= ~CALLOUT_PENDING;
6235b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_curr = c;
6245b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_cancel = FALSE;
6256098e7acSKonstantin Belousov 	CC_UNLOCK(cc);
6266098e7acSKonstantin Belousov 	if (c_lock != NULL) {
6276098e7acSKonstantin Belousov 		class->lc_lock(c_lock, sharedlock);
6286098e7acSKonstantin Belousov 		/*
6296098e7acSKonstantin Belousov 		 * The callout may have been cancelled
6306098e7acSKonstantin Belousov 		 * while we switched locks.
6316098e7acSKonstantin Belousov 		 */
6325b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_cancel) {
6336098e7acSKonstantin Belousov 			class->lc_unlock(c_lock);
6346098e7acSKonstantin Belousov 			goto skip;
6356098e7acSKonstantin Belousov 		}
6366098e7acSKonstantin Belousov 		/* The callout cannot be stopped now. */
6375b999a6bSDavide Italiano 		cc->cc_exec_entity[direct].cc_cancel = TRUE;
6386098e7acSKonstantin Belousov 		if (c_lock == &Giant.lock_object) {
6395b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6406098e7acSKonstantin Belousov 			(*gcalls)++;
6415b999a6bSDavide Italiano #endif
6425b999a6bSDavide Italiano 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
6436098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6446098e7acSKonstantin Belousov 		} else {
6455b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6466098e7acSKonstantin Belousov 			(*lockcalls)++;
6475b999a6bSDavide Italiano #endif
6486098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
6496098e7acSKonstantin Belousov 			    c, c_func, c_arg);
6506098e7acSKonstantin Belousov 		}
6516098e7acSKonstantin Belousov 	} else {
6525b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
6536098e7acSKonstantin Belousov 		(*mpcalls)++;
6545b999a6bSDavide Italiano #endif
6555b999a6bSDavide Italiano 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
6566098e7acSKonstantin Belousov 		    c, c_func, c_arg);
6576098e7acSKonstantin Belousov 	}
658*03763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
6595b999a6bSDavide Italiano 	sbt1 = sbinuptime();
6606098e7acSKonstantin Belousov #endif
6616098e7acSKonstantin Belousov 	THREAD_NO_SLEEPING();
6626098e7acSKonstantin Belousov 	SDT_PROBE(callout_execute, kernel, , callout_start, c, 0, 0, 0, 0);
6636098e7acSKonstantin Belousov 	c_func(c_arg);
6646098e7acSKonstantin Belousov 	SDT_PROBE(callout_execute, kernel, , callout_end, c, 0, 0, 0, 0);
6656098e7acSKonstantin Belousov 	THREAD_SLEEPING_OK();
666*03763781SDavide Italiano #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
667*03763781SDavide Italiano 	sbt2 = sbinuptime();
668*03763781SDavide Italiano 	sbt2 -= sbt1;
669*03763781SDavide Italiano 	if (sbt2 > maxdt) {
670*03763781SDavide Italiano 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
671*03763781SDavide Italiano 			ts2 = sbttots(sbt2);
6726098e7acSKonstantin Belousov 			printf(
6736098e7acSKonstantin Belousov 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
6746098e7acSKonstantin Belousov 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
6756098e7acSKonstantin Belousov 		}
676*03763781SDavide Italiano 		maxdt = sbt2;
6776098e7acSKonstantin Belousov 		lastfunc = c_func;
6786098e7acSKonstantin Belousov 	}
6796098e7acSKonstantin Belousov #endif
6806098e7acSKonstantin Belousov 	CTR1(KTR_CALLOUT, "callout %p finished", c);
6816098e7acSKonstantin Belousov 	if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
6826098e7acSKonstantin Belousov 		class->lc_unlock(c_lock);
6836098e7acSKonstantin Belousov skip:
6846098e7acSKonstantin Belousov 	CC_LOCK(cc);
6855b999a6bSDavide Italiano 	KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
6865b999a6bSDavide Italiano 	cc->cc_exec_entity[direct].cc_curr = NULL;
6875b999a6bSDavide Italiano 	if (cc->cc_exec_entity[direct].cc_waiting) {
6886098e7acSKonstantin Belousov 		/*
6896098e7acSKonstantin Belousov 		 * There is someone waiting for the
6906098e7acSKonstantin Belousov 		 * callout to complete.
6916098e7acSKonstantin Belousov 		 * If the callout was scheduled for
6926098e7acSKonstantin Belousov 		 * migration just cancel it.
6936098e7acSKonstantin Belousov 		 */
6945b999a6bSDavide Italiano 		if (cc_cce_migrating(cc, direct)) {
6955b999a6bSDavide Italiano 			cc_cce_cleanup(cc, direct);
696bdf9120cSAttilio Rao 
697bdf9120cSAttilio Rao 			/*
698bdf9120cSAttilio Rao 			 * It should be assert here that the callout is not
699bdf9120cSAttilio Rao 			 * destroyed but that is not easy.
700bdf9120cSAttilio Rao 			 */
701eb8a7186SKonstantin Belousov 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
702eb8a7186SKonstantin Belousov 		}
7035b999a6bSDavide Italiano 		cc->cc_exec_entity[direct].cc_waiting = FALSE;
7046098e7acSKonstantin Belousov 		CC_UNLOCK(cc);
7055b999a6bSDavide Italiano 		wakeup(&cc->cc_exec_entity[direct].cc_waiting);
7066098e7acSKonstantin Belousov 		CC_LOCK(cc);
7075b999a6bSDavide Italiano 	} else if (cc_cce_migrating(cc, direct)) {
708bdf9120cSAttilio Rao 		KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
709eb8a7186SKonstantin Belousov 		    ("Migrating legacy callout %p", c));
7106098e7acSKonstantin Belousov #ifdef SMP
7116098e7acSKonstantin Belousov 		/*
7126098e7acSKonstantin Belousov 		 * If the callout was scheduled for
7136098e7acSKonstantin Belousov 		 * migration just perform it now.
7146098e7acSKonstantin Belousov 		 */
7155b999a6bSDavide Italiano 		new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
7165b999a6bSDavide Italiano 		new_time = cc->cc_exec_entity[direct].ce_migration_time;
7175b999a6bSDavide Italiano 		new_func = cc->cc_exec_entity[direct].ce_migration_func;
7185b999a6bSDavide Italiano 		new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
7195b999a6bSDavide Italiano 		cc_cce_cleanup(cc, direct);
7206098e7acSKonstantin Belousov 
7216098e7acSKonstantin Belousov 		/*
722bdf9120cSAttilio Rao 		 * It should be assert here that the callout is not destroyed
723bdf9120cSAttilio Rao 		 * but that is not easy.
724bdf9120cSAttilio Rao 		 *
725bdf9120cSAttilio Rao 		 * As first thing, handle deferred callout stops.
7266098e7acSKonstantin Belousov 		 */
7276098e7acSKonstantin Belousov 		if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
7286098e7acSKonstantin Belousov 			CTR3(KTR_CALLOUT,
7296098e7acSKonstantin Belousov 			     "deferred cancelled %p func %p arg %p",
7306098e7acSKonstantin Belousov 			     c, new_func, new_arg);
7316098e7acSKonstantin Belousov 			callout_cc_del(c, cc);
732eb8a7186SKonstantin Belousov 			return;
7336098e7acSKonstantin Belousov 		}
7346098e7acSKonstantin Belousov 		c->c_flags &= ~CALLOUT_DFRMIGRATION;
7356098e7acSKonstantin Belousov 
7366098e7acSKonstantin Belousov 		new_cc = callout_cpu_switch(c, cc, new_cpu);
7375b999a6bSDavide Italiano 		flags = (direct) ? C_DIRECT_EXEC : 0;
7385b999a6bSDavide Italiano 		callout_cc_add(c, new_cc, new_time, c->c_precision, new_func,
7395b999a6bSDavide Italiano 		    new_arg, new_cpu, flags);
7406098e7acSKonstantin Belousov 		CC_UNLOCK(new_cc);
7416098e7acSKonstantin Belousov 		CC_LOCK(cc);
7426098e7acSKonstantin Belousov #else
7436098e7acSKonstantin Belousov 		panic("migration should not happen");
7446098e7acSKonstantin Belousov #endif
7456098e7acSKonstantin Belousov 	}
746eb8a7186SKonstantin Belousov 	/*
747eb8a7186SKonstantin Belousov 	 * If the current callout is locally allocated (from
748eb8a7186SKonstantin Belousov 	 * timeout(9)) then put it on the freelist.
749eb8a7186SKonstantin Belousov 	 *
750eb8a7186SKonstantin Belousov 	 * Note: we need to check the cached copy of c_flags because
751eb8a7186SKonstantin Belousov 	 * if it was not local, then it's not safe to deref the
752eb8a7186SKonstantin Belousov 	 * callout pointer.
753eb8a7186SKonstantin Belousov 	 */
754eb8a7186SKonstantin Belousov 	KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
755eb8a7186SKonstantin Belousov 	    c->c_flags == CALLOUT_LOCAL_ALLOC,
756eb8a7186SKonstantin Belousov 	    ("corrupted callout"));
757bdf9120cSAttilio Rao 	if (c_flags & CALLOUT_LOCAL_ALLOC)
758eb8a7186SKonstantin Belousov 		callout_cc_del(c, cc);
7596098e7acSKonstantin Belousov }
7606098e7acSKonstantin Belousov 
761219d632cSMatthew Dillon /*
762ab36c067SJustin T. Gibbs  * The callout mechanism is based on the work of Adam M. Costello and
763ab36c067SJustin T. Gibbs  * George Varghese, published in a technical report entitled "Redesigning
764ab36c067SJustin T. Gibbs  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
765ab36c067SJustin T. Gibbs  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
766024035e8SHiten Pandya  * used in this implementation was published by G. Varghese and T. Lauck in
767ab36c067SJustin T. Gibbs  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
768ab36c067SJustin T. Gibbs  * the Efficient Implementation of a Timer Facility" in the Proceedings of
769ab36c067SJustin T. Gibbs  * the 11th ACM Annual Symposium on Operating Systems Principles,
770ab36c067SJustin T. Gibbs  * Austin, Texas Nov 1987.
771ab36c067SJustin T. Gibbs  */
772a50ec505SPoul-Henning Kamp 
773ab36c067SJustin T. Gibbs /*
774df8bae1dSRodney W. Grimes  * Software (low priority) clock interrupt.
775df8bae1dSRodney W. Grimes  * Run periodic events from timeout queue.
776df8bae1dSRodney W. Grimes  */
777df8bae1dSRodney W. Grimes void
7788d809d50SJeff Roberson softclock(void *arg)
779df8bae1dSRodney W. Grimes {
7808d809d50SJeff Roberson 	struct callout_cpu *cc;
781b336df68SPoul-Henning Kamp 	struct callout *c;
7825b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7835b999a6bSDavide Italiano 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
7845b999a6bSDavide Italiano #endif
785df8bae1dSRodney W. Grimes 
7868d809d50SJeff Roberson 	cc = (struct callout_cpu *)arg;
7878d809d50SJeff Roberson 	CC_LOCK(cc);
7885b999a6bSDavide Italiano 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
7895b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
7905b999a6bSDavide Italiano 		softclock_call_cc(c, cc,
7915b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7925b999a6bSDavide Italiano 		    &mpcalls, &lockcalls, &gcalls,
7935b999a6bSDavide Italiano #endif
7945b999a6bSDavide Italiano 		    0);
7955b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
7965b999a6bSDavide Italiano 		++depth;
7975b999a6bSDavide Italiano #endif
798df8bae1dSRodney W. Grimes 	}
7995b999a6bSDavide Italiano #ifdef CALLOUT_PROFILING
80022ee8c4fSPoul-Henning Kamp 	avg_depth += (depth * 1000 - avg_depth) >> 8;
80122ee8c4fSPoul-Henning Kamp 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
80264b9ee20SAttilio Rao 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
80322ee8c4fSPoul-Henning Kamp 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
8045b999a6bSDavide Italiano #endif
8058d809d50SJeff Roberson 	CC_UNLOCK(cc);
806df8bae1dSRodney W. Grimes }
807df8bae1dSRodney W. Grimes 
808df8bae1dSRodney W. Grimes /*
809df8bae1dSRodney W. Grimes  * timeout --
810df8bae1dSRodney W. Grimes  *	Execute a function after a specified length of time.
811df8bae1dSRodney W. Grimes  *
812df8bae1dSRodney W. Grimes  * untimeout --
813df8bae1dSRodney W. Grimes  *	Cancel previous timeout function call.
814df8bae1dSRodney W. Grimes  *
815ab36c067SJustin T. Gibbs  * callout_handle_init --
816ab36c067SJustin T. Gibbs  *	Initialize a handle so that using it with untimeout is benign.
817ab36c067SJustin T. Gibbs  *
818df8bae1dSRodney W. Grimes  *	See AT&T BCI Driver Reference Manual for specification.  This
819ab36c067SJustin T. Gibbs  *	implementation differs from that one in that although an
820ab36c067SJustin T. Gibbs  *	identification value is returned from timeout, the original
821ab36c067SJustin T. Gibbs  *	arguments to timeout as well as the identifier are used to
822ab36c067SJustin T. Gibbs  *	identify entries for untimeout.
823df8bae1dSRodney W. Grimes  */
824ab36c067SJustin T. Gibbs struct callout_handle
825ab36c067SJustin T. Gibbs timeout(ftn, arg, to_ticks)
8268f03c6f1SBruce Evans 	timeout_t *ftn;
827df8bae1dSRodney W. Grimes 	void *arg;
828e82ac18eSJonathan Lemon 	int to_ticks;
829df8bae1dSRodney W. Grimes {
8308d809d50SJeff Roberson 	struct callout_cpu *cc;
831ab36c067SJustin T. Gibbs 	struct callout *new;
832ab36c067SJustin T. Gibbs 	struct callout_handle handle;
833df8bae1dSRodney W. Grimes 
8348d809d50SJeff Roberson 	cc = CC_CPU(timeout_cpu);
8358d809d50SJeff Roberson 	CC_LOCK(cc);
836df8bae1dSRodney W. Grimes 	/* Fill in the next free callout structure. */
8378d809d50SJeff Roberson 	new = SLIST_FIRST(&cc->cc_callfree);
838ab36c067SJustin T. Gibbs 	if (new == NULL)
839ab36c067SJustin T. Gibbs 		/* XXX Attempt to malloc first */
840df8bae1dSRodney W. Grimes 		panic("timeout table full");
8418d809d50SJeff Roberson 	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
842acc8326dSGarrett Wollman 	callout_reset(new, to_ticks, ftn, arg);
843ab36c067SJustin T. Gibbs 	handle.callout = new;
8448d809d50SJeff Roberson 	CC_UNLOCK(cc);
8458d809d50SJeff Roberson 
846ab36c067SJustin T. Gibbs 	return (handle);
847df8bae1dSRodney W. Grimes }
848df8bae1dSRodney W. Grimes 
849df8bae1dSRodney W. Grimes void
850ab36c067SJustin T. Gibbs untimeout(ftn, arg, handle)
8518f03c6f1SBruce Evans 	timeout_t *ftn;
852df8bae1dSRodney W. Grimes 	void *arg;
853ab36c067SJustin T. Gibbs 	struct callout_handle handle;
854df8bae1dSRodney W. Grimes {
8558d809d50SJeff Roberson 	struct callout_cpu *cc;
856df8bae1dSRodney W. Grimes 
857ab36c067SJustin T. Gibbs 	/*
858ab36c067SJustin T. Gibbs 	 * Check for a handle that was initialized
859ab36c067SJustin T. Gibbs 	 * by callout_handle_init, but never used
860ab36c067SJustin T. Gibbs 	 * for a real timeout.
861ab36c067SJustin T. Gibbs 	 */
862ab36c067SJustin T. Gibbs 	if (handle.callout == NULL)
863ab36c067SJustin T. Gibbs 		return;
864df8bae1dSRodney W. Grimes 
8658d809d50SJeff Roberson 	cc = callout_lock(handle.callout);
866acc8326dSGarrett Wollman 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
867acc8326dSGarrett Wollman 		callout_stop(handle.callout);
8688d809d50SJeff Roberson 	CC_UNLOCK(cc);
869df8bae1dSRodney W. Grimes }
870df8bae1dSRodney W. Grimes 
8713c816944SBruce Evans void
872ab36c067SJustin T. Gibbs callout_handle_init(struct callout_handle *handle)
873ab36c067SJustin T. Gibbs {
874ab36c067SJustin T. Gibbs 	handle->callout = NULL;
875ab36c067SJustin T. Gibbs }
876ab36c067SJustin T. Gibbs 
877acc8326dSGarrett Wollman /*
878acc8326dSGarrett Wollman  * New interface; clients allocate their own callout structures.
879acc8326dSGarrett Wollman  *
880acc8326dSGarrett Wollman  * callout_reset() - establish or change a timeout
881acc8326dSGarrett Wollman  * callout_stop() - disestablish a timeout
882acc8326dSGarrett Wollman  * callout_init() - initialize a callout structure so that it can
883acc8326dSGarrett Wollman  *	safely be passed to callout_reset() and callout_stop()
884acc8326dSGarrett Wollman  *
8859b8b58e0SJonathan Lemon  * <sys/callout.h> defines three convenience macros:
886acc8326dSGarrett Wollman  *
88786fd19deSColin Percival  * callout_active() - returns truth if callout has not been stopped,
88886fd19deSColin Percival  *	drained, or deactivated since the last time the callout was
88986fd19deSColin Percival  *	reset.
8909b8b58e0SJonathan Lemon  * callout_pending() - returns truth if callout is still waiting for timeout
8919b8b58e0SJonathan Lemon  * callout_deactivate() - marks the callout as having been serviced
892acc8326dSGarrett Wollman  */
893d04304d1SGleb Smirnoff int
8945b999a6bSDavide Italiano callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
8955b999a6bSDavide Italiano     void (*ftn)(void *), void *arg, int cpu, int flags)
896acc8326dSGarrett Wollman {
8975b999a6bSDavide Italiano 	sbintime_t to_sbt, pr;
8988d809d50SJeff Roberson 	struct callout_cpu *cc;
8995b999a6bSDavide Italiano 	int cancelled, direct;
900acc8326dSGarrett Wollman 
9015b999a6bSDavide Italiano 	cancelled = 0;
9025b999a6bSDavide Italiano 	if (flags & C_ABSOLUTE) {
9035b999a6bSDavide Italiano 		to_sbt = sbt;
9045b999a6bSDavide Italiano 	} else {
9055b999a6bSDavide Italiano 		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
9065b999a6bSDavide Italiano 			sbt = tick_sbt;
9075b999a6bSDavide Italiano 		if ((flags & C_HARDCLOCK) ||
9085b999a6bSDavide Italiano #ifdef NO_EVENTTIMERS
9095b999a6bSDavide Italiano 		    sbt >= sbt_timethreshold) {
9105b999a6bSDavide Italiano 			to_sbt = getsbinuptime();
9115b999a6bSDavide Italiano 
9125b999a6bSDavide Italiano 			/* Add safety belt for the case of hz > 1000. */
9135b999a6bSDavide Italiano 			to_sbt += tc_tick_sbt - tick_sbt;
9145b999a6bSDavide Italiano #else
9155b999a6bSDavide Italiano 		    sbt >= sbt_tickthreshold) {
9165b999a6bSDavide Italiano 			/*
9175b999a6bSDavide Italiano 			 * Obtain the time of the last hardclock() call on
9185b999a6bSDavide Italiano 			 * this CPU directly from the kern_clocksource.c.
9195b999a6bSDavide Italiano 			 * This value is per-CPU, but it is equal for all
9205b999a6bSDavide Italiano 			 * active ones.
9215b999a6bSDavide Italiano 			 */
9225b999a6bSDavide Italiano #ifdef __LP64__
9235b999a6bSDavide Italiano 			to_sbt = DPCPU_GET(hardclocktime);
9245b999a6bSDavide Italiano #else
9255b999a6bSDavide Italiano 			spinlock_enter();
9265b999a6bSDavide Italiano 			to_sbt = DPCPU_GET(hardclocktime);
9275b999a6bSDavide Italiano 			spinlock_exit();
9285b999a6bSDavide Italiano #endif
9295b999a6bSDavide Italiano #endif
9305b999a6bSDavide Italiano 			if ((flags & C_HARDCLOCK) == 0)
9315b999a6bSDavide Italiano 				to_sbt += tick_sbt;
9325b999a6bSDavide Italiano 		} else
9335b999a6bSDavide Italiano 			to_sbt = sbinuptime();
9345b999a6bSDavide Italiano 		to_sbt += sbt;
9355b999a6bSDavide Italiano 		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
9365b999a6bSDavide Italiano 		    sbt >> C_PRELGET(flags));
9375b999a6bSDavide Italiano 		if (pr > precision)
9385b999a6bSDavide Italiano 			precision = pr;
9395b999a6bSDavide Italiano 	}
9408d809d50SJeff Roberson 	/*
9418d809d50SJeff Roberson 	 * Don't allow migration of pre-allocated callouts lest they
9428d809d50SJeff Roberson 	 * become unbalanced.
9438d809d50SJeff Roberson 	 */
9448d809d50SJeff Roberson 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
9458d809d50SJeff Roberson 		cpu = c->c_cpu;
9465b999a6bSDavide Italiano 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
9475b999a6bSDavide Italiano 	KASSERT(!direct || c->c_lock == NULL,
9485b999a6bSDavide Italiano 	    ("%s: direct callout %p has lock", __func__, c));
9498d809d50SJeff Roberson 	cc = callout_lock(c);
9505b999a6bSDavide Italiano 	if (cc->cc_exec_entity[direct].cc_curr == c) {
9512c1bb207SColin Percival 		/*
9522c1bb207SColin Percival 		 * We're being asked to reschedule a callout which is
95364b9ee20SAttilio Rao 		 * currently in progress.  If there is a lock then we
95498c926b2SIan Dowse 		 * can cancel the callout if it has not really started.
95598c926b2SIan Dowse 		 */
9565b999a6bSDavide Italiano 		if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
9575b999a6bSDavide Italiano 			cancelled = cc->cc_exec_entity[direct].cc_cancel = TRUE;
9585b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_waiting) {
95998c926b2SIan Dowse 			/*
96098c926b2SIan Dowse 			 * Someone has called callout_drain to kill this
96198c926b2SIan Dowse 			 * callout.  Don't reschedule.
9622c1bb207SColin Percival 			 */
96368a57ebfSGleb Smirnoff 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
96468a57ebfSGleb Smirnoff 			    cancelled ? "cancelled" : "failed to cancel",
96568a57ebfSGleb Smirnoff 			    c, c->c_func, c->c_arg);
9668d809d50SJeff Roberson 			CC_UNLOCK(cc);
967d04304d1SGleb Smirnoff 			return (cancelled);
96849a74476SColin Percival 		}
96998c926b2SIan Dowse 	}
9700413bacdSColin Percival 	if (c->c_flags & CALLOUT_PENDING) {
9715b999a6bSDavide Italiano 		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
9725b999a6bSDavide Italiano 			if (cc->cc_exec_next_dir == c)
9735b999a6bSDavide Italiano 				cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
9745b999a6bSDavide Italiano 			LIST_REMOVE(c, c_links.le);
9755b999a6bSDavide Italiano 		} else
9765b999a6bSDavide Italiano 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
977d04304d1SGleb Smirnoff 		cancelled = 1;
9788d809d50SJeff Roberson 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
9798d809d50SJeff Roberson 	}
9801283e9cdSAttilio Rao 
9811283e9cdSAttilio Rao #ifdef SMP
9820413bacdSColin Percival 	/*
9831283e9cdSAttilio Rao 	 * If the callout must migrate try to perform it immediately.
9841283e9cdSAttilio Rao 	 * If the callout is currently running, just defer the migration
9851283e9cdSAttilio Rao 	 * to a more appropriate moment.
9860413bacdSColin Percival 	 */
9878d809d50SJeff Roberson 	if (c->c_cpu != cpu) {
9885b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_curr == c) {
9895b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
9905b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_time
9915b999a6bSDavide Italiano 			    = to_sbt;
9925b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_func = ftn;
9935b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].ce_migration_arg = arg;
99457d07ca9SKonstantin Belousov 			c->c_flags |= CALLOUT_DFRMIGRATION;
9955b999a6bSDavide Italiano 			CTR6(KTR_CALLOUT,
9965b999a6bSDavide Italiano 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
9975b999a6bSDavide Italiano 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
9985b999a6bSDavide Italiano 			    (u_int)(to_sbt & 0xffffffff), cpu);
99908e4ac8aSAttilio Rao 			CC_UNLOCK(cc);
10001283e9cdSAttilio Rao 			return (cancelled);
1001a157e425SAlexander Motin 		}
10021283e9cdSAttilio Rao 		cc = callout_cpu_switch(c, cc, cpu);
100308e4ac8aSAttilio Rao 	}
10041283e9cdSAttilio Rao #endif
10051283e9cdSAttilio Rao 
10065b999a6bSDavide Italiano 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
10075b999a6bSDavide Italiano 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
10085b999a6bSDavide Italiano 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
10095b999a6bSDavide Italiano 	    (u_int)(to_sbt & 0xffffffff));
10108d809d50SJeff Roberson 	CC_UNLOCK(cc);
1011d04304d1SGleb Smirnoff 
1012d04304d1SGleb Smirnoff 	return (cancelled);
1013acc8326dSGarrett Wollman }
1014acc8326dSGarrett Wollman 
10156e0186d5SSam Leffler /*
10166e0186d5SSam Leffler  * Common idioms that can be optimized in the future.
10176e0186d5SSam Leffler  */
10186e0186d5SSam Leffler int
10196e0186d5SSam Leffler callout_schedule_on(struct callout *c, int to_ticks, int cpu)
10206e0186d5SSam Leffler {
10216e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
10226e0186d5SSam Leffler }
10236e0186d5SSam Leffler 
10246e0186d5SSam Leffler int
10256e0186d5SSam Leffler callout_schedule(struct callout *c, int to_ticks)
10266e0186d5SSam Leffler {
10276e0186d5SSam Leffler 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
10286e0186d5SSam Leffler }
10296e0186d5SSam Leffler 
10302c1bb207SColin Percival int
10312c1bb207SColin Percival _callout_stop_safe(c, safe)
10322c1bb207SColin Percival 	struct	callout *c;
10332c1bb207SColin Percival 	int	safe;
10342c1bb207SColin Percival {
10351283e9cdSAttilio Rao 	struct callout_cpu *cc, *old_cc;
103664b9ee20SAttilio Rao 	struct lock_class *class;
10375b999a6bSDavide Italiano 	int direct, sq_locked, use_lock;
103898c926b2SIan Dowse 
103964b9ee20SAttilio Rao 	/*
104064b9ee20SAttilio Rao 	 * Some old subsystems don't hold Giant while running a callout_stop(),
104164b9ee20SAttilio Rao 	 * so just discard this check for the moment.
104264b9ee20SAttilio Rao 	 */
104364b9ee20SAttilio Rao 	if (!safe && c->c_lock != NULL) {
104464b9ee20SAttilio Rao 		if (c->c_lock == &Giant.lock_object)
104564b9ee20SAttilio Rao 			use_lock = mtx_owned(&Giant);
104664b9ee20SAttilio Rao 		else {
104764b9ee20SAttilio Rao 			use_lock = 1;
104864b9ee20SAttilio Rao 			class = LOCK_CLASS(c->c_lock);
104964b9ee20SAttilio Rao 			class->lc_assert(c->c_lock, LA_XLOCKED);
105098c926b2SIan Dowse 		}
105164b9ee20SAttilio Rao 	} else
105264b9ee20SAttilio Rao 		use_lock = 0;
10535b999a6bSDavide Italiano 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
105467b158d8SJohn Baldwin 	sq_locked = 0;
10551283e9cdSAttilio Rao 	old_cc = NULL;
105667b158d8SJohn Baldwin again:
10578d809d50SJeff Roberson 	cc = callout_lock(c);
10581283e9cdSAttilio Rao 
10591283e9cdSAttilio Rao 	/*
10601283e9cdSAttilio Rao 	 * If the callout was migrating while the callout cpu lock was
10611283e9cdSAttilio Rao 	 * dropped,  just drop the sleepqueue lock and check the states
10621283e9cdSAttilio Rao 	 * again.
10631283e9cdSAttilio Rao 	 */
10641283e9cdSAttilio Rao 	if (sq_locked != 0 && cc != old_cc) {
10651283e9cdSAttilio Rao #ifdef SMP
10661283e9cdSAttilio Rao 		CC_UNLOCK(cc);
10675b999a6bSDavide Italiano 		sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
10681283e9cdSAttilio Rao 		sq_locked = 0;
10691283e9cdSAttilio Rao 		old_cc = NULL;
10701283e9cdSAttilio Rao 		goto again;
10711283e9cdSAttilio Rao #else
10721283e9cdSAttilio Rao 		panic("migration should not happen");
10731283e9cdSAttilio Rao #endif
10741283e9cdSAttilio Rao 	}
10751283e9cdSAttilio Rao 
1076acc8326dSGarrett Wollman 	/*
1077b36f4588SJohn Baldwin 	 * If the callout isn't pending, it's not on the queue, so
1078b36f4588SJohn Baldwin 	 * don't attempt to remove it from the queue.  We can try to
1079b36f4588SJohn Baldwin 	 * stop it by other means however.
1080acc8326dSGarrett Wollman 	 */
1081acc8326dSGarrett Wollman 	if (!(c->c_flags & CALLOUT_PENDING)) {
10829b8b58e0SJonathan Lemon 		c->c_flags &= ~CALLOUT_ACTIVE;
1083b36f4588SJohn Baldwin 
1084b36f4588SJohn Baldwin 		/*
1085b36f4588SJohn Baldwin 		 * If it wasn't on the queue and it isn't the current
1086b36f4588SJohn Baldwin 		 * callout, then we can't stop it, so just bail.
1087b36f4588SJohn Baldwin 		 */
10885b999a6bSDavide Italiano 		if (cc->cc_exec_entity[direct].cc_curr != c) {
108968a57ebfSGleb Smirnoff 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
109068a57ebfSGleb Smirnoff 			    c, c->c_func, c->c_arg);
10918d809d50SJeff Roberson 			CC_UNLOCK(cc);
109267b158d8SJohn Baldwin 			if (sq_locked)
10935b999a6bSDavide Italiano 				sleepq_release(
10945b999a6bSDavide Italiano 				    &cc->cc_exec_entity[direct].cc_waiting);
109598c926b2SIan Dowse 			return (0);
109698c926b2SIan Dowse 		}
1097b36f4588SJohn Baldwin 
109898c926b2SIan Dowse 		if (safe) {
10992c1bb207SColin Percival 			/*
1100b36f4588SJohn Baldwin 			 * The current callout is running (or just
1101b36f4588SJohn Baldwin 			 * about to run) and blocking is allowed, so
1102b36f4588SJohn Baldwin 			 * just wait for the current invocation to
1103b36f4588SJohn Baldwin 			 * finish.
11042c1bb207SColin Percival 			 */
11055b999a6bSDavide Italiano 			while (cc->cc_exec_entity[direct].cc_curr == c) {
11066a0ce57dSAttilio Rao 				/*
11076a0ce57dSAttilio Rao 				 * Use direct calls to sleepqueue interface
11086a0ce57dSAttilio Rao 				 * instead of cv/msleep in order to avoid
11098d809d50SJeff Roberson 				 * a LOR between cc_lock and sleepqueue
11106a0ce57dSAttilio Rao 				 * chain spinlocks.  This piece of code
11116a0ce57dSAttilio Rao 				 * emulates a msleep_spin() call actually.
111267b158d8SJohn Baldwin 				 *
111367b158d8SJohn Baldwin 				 * If we already have the sleepqueue chain
111467b158d8SJohn Baldwin 				 * locked, then we can safely block.  If we
111567b158d8SJohn Baldwin 				 * don't already have it locked, however,
11168d809d50SJeff Roberson 				 * we have to drop the cc_lock to lock
111767b158d8SJohn Baldwin 				 * it.  This opens several races, so we
111867b158d8SJohn Baldwin 				 * restart at the beginning once we have
111967b158d8SJohn Baldwin 				 * both locks.  If nothing has changed, then
112067b158d8SJohn Baldwin 				 * we will end up back here with sq_locked
112167b158d8SJohn Baldwin 				 * set.
11226a0ce57dSAttilio Rao 				 */
112367b158d8SJohn Baldwin 				if (!sq_locked) {
11248d809d50SJeff Roberson 					CC_UNLOCK(cc);
11255b999a6bSDavide Italiano 					sleepq_lock(
11265b999a6bSDavide Italiano 					&cc->cc_exec_entity[direct].cc_waiting);
112767b158d8SJohn Baldwin 					sq_locked = 1;
11281283e9cdSAttilio Rao 					old_cc = cc;
112967b158d8SJohn Baldwin 					goto again;
11306a0ce57dSAttilio Rao 				}
11311283e9cdSAttilio Rao 
11321283e9cdSAttilio Rao 				/*
11331283e9cdSAttilio Rao 				 * Migration could be cancelled here, but
11341283e9cdSAttilio Rao 				 * as long as it is still not sure when it
11351283e9cdSAttilio Rao 				 * will be packed up, just let softclock()
11361283e9cdSAttilio Rao 				 * take care of it.
11371283e9cdSAttilio Rao 				 */
11385b999a6bSDavide Italiano 				cc->cc_exec_entity[direct].cc_waiting = TRUE;
11396a0ce57dSAttilio Rao 				DROP_GIANT();
11408d809d50SJeff Roberson 				CC_UNLOCK(cc);
11415b999a6bSDavide Italiano 				sleepq_add(
11425b999a6bSDavide Italiano 				    &cc->cc_exec_entity[direct].cc_waiting,
11438d809d50SJeff Roberson 				    &cc->cc_lock.lock_object, "codrain",
11446a0ce57dSAttilio Rao 				    SLEEPQ_SLEEP, 0);
11455b999a6bSDavide Italiano 				sleepq_wait(
11465b999a6bSDavide Italiano 				    &cc->cc_exec_entity[direct].cc_waiting,
11475b999a6bSDavide Italiano 					     0);
114867b158d8SJohn Baldwin 				sq_locked = 0;
11491283e9cdSAttilio Rao 				old_cc = NULL;
11506a0ce57dSAttilio Rao 
11516a0ce57dSAttilio Rao 				/* Reacquire locks previously released. */
11526a0ce57dSAttilio Rao 				PICKUP_GIANT();
11538d809d50SJeff Roberson 				CC_LOCK(cc);
1154b36f4588SJohn Baldwin 			}
11555b999a6bSDavide Italiano 		} else if (use_lock &&
11565b999a6bSDavide Italiano 			    !cc->cc_exec_entity[direct].cc_cancel) {
1157b36f4588SJohn Baldwin 			/*
115864b9ee20SAttilio Rao 			 * The current callout is waiting for its
115964b9ee20SAttilio Rao 			 * lock which we hold.  Cancel the callout
1160b36f4588SJohn Baldwin 			 * and return.  After our caller drops the
116164b9ee20SAttilio Rao 			 * lock, the callout will be skipped in
1162b36f4588SJohn Baldwin 			 * softclock().
1163b36f4588SJohn Baldwin 			 */
11645b999a6bSDavide Italiano 			cc->cc_exec_entity[direct].cc_cancel = TRUE;
116568a57ebfSGleb Smirnoff 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
116668a57ebfSGleb Smirnoff 			    c, c->c_func, c->c_arg);
11675b999a6bSDavide Italiano 			KASSERT(!cc_cce_migrating(cc, direct),
11681283e9cdSAttilio Rao 			    ("callout wrongly scheduled for migration"));
11698d809d50SJeff Roberson 			CC_UNLOCK(cc);
117067b158d8SJohn Baldwin 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
117198c926b2SIan Dowse 			return (1);
117257d07ca9SKonstantin Belousov 		} else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
117357d07ca9SKonstantin Belousov 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
117457d07ca9SKonstantin Belousov 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
117557d07ca9SKonstantin Belousov 			    c, c->c_func, c->c_arg);
117657d07ca9SKonstantin Belousov 			CC_UNLOCK(cc);
117757d07ca9SKonstantin Belousov 			return (1);
1178b36f4588SJohn Baldwin 		}
117968a57ebfSGleb Smirnoff 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
118068a57ebfSGleb Smirnoff 		    c, c->c_func, c->c_arg);
11818d809d50SJeff Roberson 		CC_UNLOCK(cc);
118267b158d8SJohn Baldwin 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1183a45982d2SJohn Baldwin 		return (0);
1184acc8326dSGarrett Wollman 	}
118567b158d8SJohn Baldwin 	if (sq_locked)
11865b999a6bSDavide Italiano 		sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
118767b158d8SJohn Baldwin 
11889b8b58e0SJonathan Lemon 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1189acc8326dSGarrett Wollman 
119068a57ebfSGleb Smirnoff 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
119168a57ebfSGleb Smirnoff 	    c, c->c_func, c->c_arg);
11925b999a6bSDavide Italiano 	if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
11935b999a6bSDavide Italiano 		if (cc->cc_exec_next_dir == c)
11945b999a6bSDavide Italiano 			cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
11955b999a6bSDavide Italiano 		LIST_REMOVE(c, c_links.le);
11965b999a6bSDavide Italiano 	} else
11975b999a6bSDavide Italiano 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
11986098e7acSKonstantin Belousov 	callout_cc_del(c, cc);
119968a57ebfSGleb Smirnoff 
12008d809d50SJeff Roberson 	CC_UNLOCK(cc);
1201a45982d2SJohn Baldwin 	return (1);
1202acc8326dSGarrett Wollman }
1203acc8326dSGarrett Wollman 
1204acc8326dSGarrett Wollman void
1205e82ac18eSJonathan Lemon callout_init(c, mpsafe)
1206acc8326dSGarrett Wollman 	struct	callout *c;
1207e82ac18eSJonathan Lemon 	int mpsafe;
1208acc8326dSGarrett Wollman {
12097347e1c6SGarrett Wollman 	bzero(c, sizeof *c);
121098c926b2SIan Dowse 	if (mpsafe) {
121164b9ee20SAttilio Rao 		c->c_lock = NULL;
121298c926b2SIan Dowse 		c->c_flags = CALLOUT_RETURNUNLOCKED;
121398c926b2SIan Dowse 	} else {
121464b9ee20SAttilio Rao 		c->c_lock = &Giant.lock_object;
121598c926b2SIan Dowse 		c->c_flags = 0;
121698c926b2SIan Dowse 	}
12178d809d50SJeff Roberson 	c->c_cpu = timeout_cpu;
121898c926b2SIan Dowse }
121998c926b2SIan Dowse 
122098c926b2SIan Dowse void
122164b9ee20SAttilio Rao _callout_init_lock(c, lock, flags)
122298c926b2SIan Dowse 	struct	callout *c;
122364b9ee20SAttilio Rao 	struct	lock_object *lock;
122498c926b2SIan Dowse 	int flags;
122598c926b2SIan Dowse {
122698c926b2SIan Dowse 	bzero(c, sizeof *c);
122764b9ee20SAttilio Rao 	c->c_lock = lock;
122864b9ee20SAttilio Rao 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
122964b9ee20SAttilio Rao 	    ("callout_init_lock: bad flags %d", flags));
123064b9ee20SAttilio Rao 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
123164b9ee20SAttilio Rao 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
123213ddf72dSAttilio Rao 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
123313ddf72dSAttilio Rao 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
123464b9ee20SAttilio Rao 	    __func__));
123564b9ee20SAttilio Rao 	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
12368d809d50SJeff Roberson 	c->c_cpu = timeout_cpu;
1237acc8326dSGarrett Wollman }
1238acc8326dSGarrett Wollman 
1239e1d6dc65SNate Williams #ifdef APM_FIXUP_CALLTODO
1240e1d6dc65SNate Williams /*
1241e1d6dc65SNate Williams  * Adjust the kernel calltodo timeout list.  This routine is used after
1242e1d6dc65SNate Williams  * an APM resume to recalculate the calltodo timer list values with the
1243e1d6dc65SNate Williams  * number of hz's we have been sleeping.  The next hardclock() will detect
1244e1d6dc65SNate Williams  * that there are fired timers and run softclock() to execute them.
1245e1d6dc65SNate Williams  *
1246e1d6dc65SNate Williams  * Please note, I have not done an exhaustive analysis of what code this
1247e1d6dc65SNate Williams  * might break.  I am motivated to have my select()'s and alarm()'s that
1248e1d6dc65SNate Williams  * have expired during suspend firing upon resume so that the applications
1249e1d6dc65SNate Williams  * which set the timer can do the maintanence the timer was for as close
1250e1d6dc65SNate Williams  * as possible to the originally intended time.  Testing this code for a
1251e1d6dc65SNate Williams  * week showed that resuming from a suspend resulted in 22 to 25 timers
1252e1d6dc65SNate Williams  * firing, which seemed independant on whether the suspend was 2 hours or
1253e1d6dc65SNate Williams  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1254e1d6dc65SNate Williams  */
1255e1d6dc65SNate Williams void
1256e1d6dc65SNate Williams adjust_timeout_calltodo(time_change)
1257e1d6dc65SNate Williams     struct timeval *time_change;
1258e1d6dc65SNate Williams {
1259e1d6dc65SNate Williams 	register struct callout *p;
1260e1d6dc65SNate Williams 	unsigned long delta_ticks;
1261e1d6dc65SNate Williams 
1262e1d6dc65SNate Williams 	/*
1263e1d6dc65SNate Williams 	 * How many ticks were we asleep?
1264c8b47828SBruce Evans 	 * (stolen from tvtohz()).
1265e1d6dc65SNate Williams 	 */
1266e1d6dc65SNate Williams 
1267e1d6dc65SNate Williams 	/* Don't do anything */
1268e1d6dc65SNate Williams 	if (time_change->tv_sec < 0)
1269e1d6dc65SNate Williams 		return;
1270e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
1271e1d6dc65SNate Williams 		delta_ticks = (time_change->tv_sec * 1000000 +
1272e1d6dc65SNate Williams 			       time_change->tv_usec + (tick - 1)) / tick + 1;
1273e1d6dc65SNate Williams 	else if (time_change->tv_sec <= LONG_MAX / hz)
1274e1d6dc65SNate Williams 		delta_ticks = time_change->tv_sec * hz +
1275e1d6dc65SNate Williams 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
1276e1d6dc65SNate Williams 	else
1277e1d6dc65SNate Williams 		delta_ticks = LONG_MAX;
1278e1d6dc65SNate Williams 
1279e1d6dc65SNate Williams 	if (delta_ticks > INT_MAX)
1280e1d6dc65SNate Williams 		delta_ticks = INT_MAX;
1281e1d6dc65SNate Williams 
1282e1d6dc65SNate Williams 	/*
1283e1d6dc65SNate Williams 	 * Now rip through the timer calltodo list looking for timers
1284e1d6dc65SNate Williams 	 * to expire.
1285e1d6dc65SNate Williams 	 */
1286e1d6dc65SNate Williams 
1287e1d6dc65SNate Williams 	/* don't collide with softclock() */
12888d809d50SJeff Roberson 	CC_LOCK(cc);
1289e1d6dc65SNate Williams 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1290e1d6dc65SNate Williams 		p->c_time -= delta_ticks;
1291e1d6dc65SNate Williams 
1292e1d6dc65SNate Williams 		/* Break if the timer had more time on it than delta_ticks */
1293e1d6dc65SNate Williams 		if (p->c_time > 0)
1294e1d6dc65SNate Williams 			break;
1295e1d6dc65SNate Williams 
1296e1d6dc65SNate Williams 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1297e1d6dc65SNate Williams 		delta_ticks = -p->c_time;
1298e1d6dc65SNate Williams 	}
12998d809d50SJeff Roberson 	CC_UNLOCK(cc);
1300e1d6dc65SNate Williams 
1301e1d6dc65SNate Williams 	return;
1302e1d6dc65SNate Williams }
1303e1d6dc65SNate Williams #endif /* APM_FIXUP_CALLTODO */
13045b999a6bSDavide Italiano 
13055b999a6bSDavide Italiano static int
13065b999a6bSDavide Italiano flssbt(sbintime_t sbt)
13075b999a6bSDavide Italiano {
13085b999a6bSDavide Italiano 
13095b999a6bSDavide Italiano 	sbt += (uint64_t)sbt >> 1;
13105b999a6bSDavide Italiano 	if (sizeof(long) >= sizeof(sbintime_t))
13115b999a6bSDavide Italiano 		return (flsl(sbt));
13125b999a6bSDavide Italiano 	if (sbt >= SBT_1S)
13135b999a6bSDavide Italiano 		return (flsl(((uint64_t)sbt) >> 32) + 32);
13145b999a6bSDavide Italiano 	return (flsl(sbt));
13155b999a6bSDavide Italiano }
13165b999a6bSDavide Italiano 
13175b999a6bSDavide Italiano /*
13185b999a6bSDavide Italiano  * Dump immediate statistic snapshot of the scheduled callouts.
13195b999a6bSDavide Italiano  */
13205b999a6bSDavide Italiano static int
13215b999a6bSDavide Italiano sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
13225b999a6bSDavide Italiano {
13235b999a6bSDavide Italiano 	struct callout *tmp;
13245b999a6bSDavide Italiano 	struct callout_cpu *cc;
13255b999a6bSDavide Italiano 	struct callout_list *sc;
13265b999a6bSDavide Italiano 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
13275b999a6bSDavide Italiano 	int ct[64], cpr[64], ccpbk[32];
13285b999a6bSDavide Italiano 	int error, val, i, count, tcum, pcum, maxc, c, medc;
13295b999a6bSDavide Italiano #ifdef SMP
13305b999a6bSDavide Italiano 	int cpu;
13315b999a6bSDavide Italiano #endif
13325b999a6bSDavide Italiano 
13335b999a6bSDavide Italiano 	val = 0;
13345b999a6bSDavide Italiano 	error = sysctl_handle_int(oidp, &val, 0, req);
13355b999a6bSDavide Italiano 	if (error != 0 || req->newptr == NULL)
13365b999a6bSDavide Italiano 		return (error);
13375b999a6bSDavide Italiano 	count = maxc = 0;
13385b999a6bSDavide Italiano 	st = spr = maxt = maxpr = 0;
13395b999a6bSDavide Italiano 	bzero(ccpbk, sizeof(ccpbk));
13405b999a6bSDavide Italiano 	bzero(ct, sizeof(ct));
13415b999a6bSDavide Italiano 	bzero(cpr, sizeof(cpr));
13425b999a6bSDavide Italiano 	now = sbinuptime();
13435b999a6bSDavide Italiano #ifdef SMP
13445b999a6bSDavide Italiano 	CPU_FOREACH(cpu) {
13455b999a6bSDavide Italiano 		cc = CC_CPU(cpu);
13465b999a6bSDavide Italiano #else
13475b999a6bSDavide Italiano 		cc = CC_CPU(timeout_cpu);
13485b999a6bSDavide Italiano #endif
13495b999a6bSDavide Italiano 		CC_LOCK(cc);
13505b999a6bSDavide Italiano 		for (i = 0; i < callwheelsize; i++) {
13515b999a6bSDavide Italiano 			sc = &cc->cc_callwheel[i];
13525b999a6bSDavide Italiano 			c = 0;
13535b999a6bSDavide Italiano 			LIST_FOREACH(tmp, sc, c_links.le) {
13545b999a6bSDavide Italiano 				c++;
13555b999a6bSDavide Italiano 				t = tmp->c_time - now;
13565b999a6bSDavide Italiano 				if (t < 0)
13575b999a6bSDavide Italiano 					t = 0;
13585b999a6bSDavide Italiano 				st += t / SBT_1US;
13595b999a6bSDavide Italiano 				spr += tmp->c_precision / SBT_1US;
13605b999a6bSDavide Italiano 				if (t > maxt)
13615b999a6bSDavide Italiano 					maxt = t;
13625b999a6bSDavide Italiano 				if (tmp->c_precision > maxpr)
13635b999a6bSDavide Italiano 					maxpr = tmp->c_precision;
13645b999a6bSDavide Italiano 				ct[flssbt(t)]++;
13655b999a6bSDavide Italiano 				cpr[flssbt(tmp->c_precision)]++;
13665b999a6bSDavide Italiano 			}
13675b999a6bSDavide Italiano 			if (c > maxc)
13685b999a6bSDavide Italiano 				maxc = c;
13695b999a6bSDavide Italiano 			ccpbk[fls(c + c / 2)]++;
13705b999a6bSDavide Italiano 			count += c;
13715b999a6bSDavide Italiano 		}
13725b999a6bSDavide Italiano 		CC_UNLOCK(cc);
13735b999a6bSDavide Italiano #ifdef SMP
13745b999a6bSDavide Italiano 	}
13755b999a6bSDavide Italiano #endif
13765b999a6bSDavide Italiano 
13775b999a6bSDavide Italiano 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
13785b999a6bSDavide Italiano 		tcum += ct[i];
13795b999a6bSDavide Italiano 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
13805b999a6bSDavide Italiano 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
13815b999a6bSDavide Italiano 		pcum += cpr[i];
13825b999a6bSDavide Italiano 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
13835b999a6bSDavide Italiano 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
13845b999a6bSDavide Italiano 		c += ccpbk[i];
13855b999a6bSDavide Italiano 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
13865b999a6bSDavide Italiano 
13875b999a6bSDavide Italiano 	printf("Scheduled callouts statistic snapshot:\n");
13885b999a6bSDavide Italiano 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
13895b999a6bSDavide Italiano 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
13905b999a6bSDavide Italiano 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
13915b999a6bSDavide Italiano 	    medc,
13925b999a6bSDavide Italiano 	    count / callwheelsize / mp_ncpus,
13935b999a6bSDavide Italiano 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
13945b999a6bSDavide Italiano 	    maxc);
13955b999a6bSDavide Italiano 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
13965b999a6bSDavide Italiano 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
13975b999a6bSDavide Italiano 	    (st / count) / 1000000, (st / count) % 1000000,
13985b999a6bSDavide Italiano 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
13995b999a6bSDavide Italiano 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
14005b999a6bSDavide Italiano 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
14015b999a6bSDavide Italiano 	    (spr / count) / 1000000, (spr / count) % 1000000,
14025b999a6bSDavide Italiano 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
14035b999a6bSDavide Italiano 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
14045b999a6bSDavide Italiano 	    "   prec\t   pcum\n");
14055b999a6bSDavide Italiano 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
14065b999a6bSDavide Italiano 		if (ct[i] == 0 && cpr[i] == 0)
14075b999a6bSDavide Italiano 			continue;
14085b999a6bSDavide Italiano 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
14095b999a6bSDavide Italiano 		tcum += ct[i];
14105b999a6bSDavide Italiano 		pcum += cpr[i];
14115b999a6bSDavide Italiano 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
14125b999a6bSDavide Italiano 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
14135b999a6bSDavide Italiano 		    i - 1 - (32 - CC_HASH_SHIFT),
14145b999a6bSDavide Italiano 		    ct[i], tcum, cpr[i], pcum);
14155b999a6bSDavide Italiano 	}
14165b999a6bSDavide Italiano 	return (error);
14175b999a6bSDavide Italiano }
14185b999a6bSDavide Italiano SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
14195b999a6bSDavide Italiano     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
14205b999a6bSDavide Italiano     0, 0, sysctl_kern_callout_stat, "I",
14215b999a6bSDavide Italiano     "Dump immediate statistic snapshot of the scheduled callouts");
1422