kern_timeout.c revision 248032
11541Srgrimes/*-
21541Srgrimes * Copyright (c) 1982, 1986, 1991, 1993
31541Srgrimes *	The Regents of the University of California.  All rights reserved.
41541Srgrimes * (c) UNIX System Laboratories, Inc.
51541Srgrimes * All or some portions of this file are derived from material licensed
61541Srgrimes * to the University of California by American Telephone and Telegraph
71541Srgrimes * Co. or Unix System Laboratories, Inc. and are reproduced herein with
81541Srgrimes * the permission of UNIX System Laboratories, Inc.
91541Srgrimes *
101541Srgrimes * Redistribution and use in source and binary forms, with or without
111541Srgrimes * modification, are permitted provided that the following conditions
121541Srgrimes * are met:
131541Srgrimes * 1. Redistributions of source code must retain the above copyright
141541Srgrimes *    notice, this list of conditions and the following disclaimer.
151541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
161541Srgrimes *    notice, this list of conditions and the following disclaimer in the
171541Srgrimes *    documentation and/or other materials provided with the distribution.
181541Srgrimes * 4. Neither the name of the University nor the names of its contributors
191541Srgrimes *    may be used to endorse or promote products derived from this software
201541Srgrimes *    without specific prior written permission.
211541Srgrimes *
221541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
231541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
241541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
251541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
261541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
271541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
281541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
291541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
301541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
311541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
321541Srgrimes * SUCH DAMAGE.
331541Srgrimes *
3444510Swollman *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
351541Srgrimes */
361541Srgrimes
37116182Sobrien#include <sys/cdefs.h>
38116182Sobrien__FBSDID("$FreeBSD: head/sys/kern/kern_timeout.c 248032 2013-03-08 10:37:17Z andre $");
39116182Sobrien
40247777Sdavide#include "opt_callout_profiling.h"
41187664Srwatson#include "opt_kdtrace.h"
42247777Sdavide#if defined(__arm__)
43247777Sdavide#include "opt_timer.h"
44247777Sdavide#endif
45187664Srwatson
461541Srgrimes#include <sys/param.h>
471541Srgrimes#include <sys/systm.h>
48177859Sjeff#include <sys/bus.h>
4933392Sphk#include <sys/callout.h>
50248031Sandre#include <sys/file.h>
51177859Sjeff#include <sys/interrupt.h>
521541Srgrimes#include <sys/kernel.h>
53133229Srwatson#include <sys/ktr.h>
5474914Sjhb#include <sys/lock.h>
55177859Sjeff#include <sys/malloc.h>
5668840Sjhb#include <sys/mutex.h>
57150188Sjhb#include <sys/proc.h>
58187664Srwatson#include <sys/sdt.h>
59171053Sattilio#include <sys/sleepqueue.h>
60115810Sphk#include <sys/sysctl.h>
61177859Sjeff#include <sys/smp.h>
621541Srgrimes
63220456Sattilio#ifdef SMP
64220456Sattilio#include <machine/cpu.h>
65220456Sattilio#endif
66220456Sattilio
67247777Sdavide#ifndef NO_EVENTTIMERS
68247777SdavideDPCPU_DECLARE(sbintime_t, hardclocktime);
69247777Sdavide#endif
70247777Sdavide
71187664SrwatsonSDT_PROVIDER_DEFINE(callout_execute);
72211616SrpauloSDT_PROBE_DEFINE(callout_execute, kernel, , callout_start, callout-start);
73187664SrwatsonSDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_start, 0,
74187664Srwatson    "struct callout *");
75211616SrpauloSDT_PROBE_DEFINE(callout_execute, kernel, , callout_end, callout-end);
76187664SrwatsonSDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_end, 0,
77187664Srwatson    "struct callout *");
78187664Srwatson
79247777Sdavide#ifdef CALLOUT_PROFILING
80115810Sphkstatic int avg_depth;
81115810SphkSYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
82115810Sphk    "Average number of items examined per softclock call. Units = 1/1000");
83115810Sphkstatic int avg_gcalls;
84115810SphkSYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
85115810Sphk    "Average number of Giant callouts made per softclock call. Units = 1/1000");
86173760Sattiliostatic int avg_lockcalls;
87173760SattilioSYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
88173760Sattilio    "Average number of lock callouts made per softclock call. Units = 1/1000");
89115810Sphkstatic int avg_mpcalls;
90115810SphkSYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
91115810Sphk    "Average number of MP callouts made per softclock call. Units = 1/1000");
92247777Sdavidestatic int avg_depth_dir;
93247777SdavideSYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
94247777Sdavide    "Average number of direct callouts examined per callout_process call. "
95247777Sdavide    "Units = 1/1000");
96247777Sdavidestatic int avg_lockcalls_dir;
97247777SdavideSYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
98247777Sdavide    &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
99247777Sdavide    "callout_process call. Units = 1/1000");
100247777Sdavidestatic int avg_mpcalls_dir;
101247777SdavideSYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
102247777Sdavide    0, "Average number of MP direct callouts made per callout_process call. "
103247777Sdavide    "Units = 1/1000");
104247777Sdavide#endif
105248031Sandre
106248031Sandrestatic int ncallout;
107248031SandreSYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN, &ncallout, 0,
108248031Sandre    "Number of entries in callwheel and size of timeout() preallocation");
109248031Sandre
11033392Sphk/*
11133392Sphk * TODO:
11233392Sphk *	allocate more timeout table slots when table overflows.
11333392Sphk */
114247715Sdavideu_int callwheelsize, callwheelmask;
1152112Swollman
116200510Sluigi/*
117247777Sdavide * The callout cpu exec entities represent informations necessary for
118247777Sdavide * describing the state of callouts currently running on the CPU and the ones
119247777Sdavide * necessary for migrating callouts to the new callout cpu. In particular,
120247777Sdavide * the first entry of the array cc_exec_entity holds informations for callout
121247777Sdavide * running in SWI thread context, while the second one holds informations
122247777Sdavide * for callout running directly from hardware interrupt context.
123220456Sattilio * The cached informations are very important for deferring migration when
124220456Sattilio * the migrating callout is already running.
125220456Sattilio */
126247777Sdavidestruct cc_exec {
127247777Sdavide	struct callout		*cc_next;
128247777Sdavide	struct callout		*cc_curr;
129220456Sattilio#ifdef SMP
130247777Sdavide	void			(*ce_migration_func)(void *);
131247777Sdavide	void			*ce_migration_arg;
132247777Sdavide	int			ce_migration_cpu;
133247777Sdavide	sbintime_t		ce_migration_time;
134220456Sattilio#endif
135247813Sdavide	bool			cc_cancel;
136247813Sdavide	bool			cc_waiting;
137220456Sattilio};
138247467Sdavide
139220456Sattilio/*
140200510Sluigi * There is one struct callout_cpu per cpu, holding all relevant
141200510Sluigi * state for the callout processing thread on the individual CPU.
142200510Sluigi */
143177859Sjeffstruct callout_cpu {
144242402Sattilio	struct mtx_padalign	cc_lock;
145247777Sdavide	struct cc_exec 		cc_exec_entity[2];
146177859Sjeff	struct callout		*cc_callout;
147247777Sdavide	struct callout_list	*cc_callwheel;
148247777Sdavide	struct callout_tailq	cc_expireq;
149247777Sdavide	struct callout_slist	cc_callfree;
150247777Sdavide	sbintime_t		cc_firstevent;
151247777Sdavide	sbintime_t		cc_lastscan;
152177859Sjeff	void			*cc_cookie;
153247777Sdavide	u_int			cc_bucket;
154177859Sjeff};
155128024Scperciva
156247777Sdavide#define	cc_exec_curr		cc_exec_entity[0].cc_curr
157247777Sdavide#define	cc_exec_next		cc_exec_entity[0].cc_next
158247777Sdavide#define	cc_exec_cancel		cc_exec_entity[0].cc_cancel
159247777Sdavide#define	cc_exec_waiting		cc_exec_entity[0].cc_waiting
160247777Sdavide#define	cc_exec_curr_dir	cc_exec_entity[1].cc_curr
161247777Sdavide#define	cc_exec_next_dir	cc_exec_entity[1].cc_next
162247777Sdavide#define	cc_exec_cancel_dir	cc_exec_entity[1].cc_cancel
163247777Sdavide#define	cc_exec_waiting_dir	cc_exec_entity[1].cc_waiting
164247777Sdavide
165177859Sjeff#ifdef SMP
166247777Sdavide#define	cc_migration_func	cc_exec_entity[0].ce_migration_func
167247777Sdavide#define	cc_migration_arg	cc_exec_entity[0].ce_migration_arg
168247777Sdavide#define	cc_migration_cpu	cc_exec_entity[0].ce_migration_cpu
169247777Sdavide#define	cc_migration_time	cc_exec_entity[0].ce_migration_time
170247777Sdavide#define	cc_migration_func_dir	cc_exec_entity[1].ce_migration_func
171247777Sdavide#define	cc_migration_arg_dir	cc_exec_entity[1].ce_migration_arg
172247777Sdavide#define	cc_migration_cpu_dir	cc_exec_entity[1].ce_migration_cpu
173247777Sdavide#define	cc_migration_time_dir	cc_exec_entity[1].ce_migration_time
174220456Sattilio
175177859Sjeffstruct callout_cpu cc_cpu[MAXCPU];
176220456Sattilio#define	CPUBLOCK	MAXCPU
177177859Sjeff#define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
178177859Sjeff#define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
179177859Sjeff#else
180177859Sjeffstruct callout_cpu cc_cpu;
181177859Sjeff#define	CC_CPU(cpu)	&cc_cpu
182177859Sjeff#define	CC_SELF()	&cc_cpu
183177859Sjeff#endif
184177859Sjeff#define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
185177859Sjeff#define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
186220456Sattilio#define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
187177859Sjeff
188177859Sjeffstatic int timeout_cpu;
189177859Sjeff
190248032Sandrestatic void	callout_cpu_init(struct callout_cpu *cc);
191247777Sdavidestatic void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
192247777Sdavide#ifdef CALLOUT_PROFILING
193247777Sdavide		    int *mpcalls, int *lockcalls, int *gcalls,
194247777Sdavide#endif
195247777Sdavide		    int direct);
196247777Sdavide
197227293Sedstatic MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
198177859Sjeff
199139831Scperciva/**
200177859Sjeff * Locked by cc_lock:
201247777Sdavide *   cc_curr         - If a callout is in progress, it is cc_curr.
202247777Sdavide *                     If cc_curr is non-NULL, threads waiting in
203177859Sjeff *                     callout_drain() will be woken up as soon as the
204127969Scperciva *                     relevant callout completes.
205247777Sdavide *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
206141428Siedowse *                     guarantees that the current callout will not run.
207141428Siedowse *                     The softclock() function sets this to 0 before it
208173760Sattilio *                     drops callout_lock to acquire c_lock, and it calls
209155957Sjhb *                     the handler only if curr_cancelled is still 0 after
210247777Sdavide *                     cc_lock is successfully acquired.
211177859Sjeff *   cc_waiting      - If a thread is waiting in callout_drain(), then
212155957Sjhb *                     callout_wait is nonzero.  Set only when
213247777Sdavide *                     cc_curr is non-NULL.
214127969Scperciva */
215128024Scperciva
2161541Srgrimes/*
217247777Sdavide * Resets the execution entity tied to a specific callout cpu.
218220456Sattilio */
219220456Sattiliostatic void
220247777Sdavidecc_cce_cleanup(struct callout_cpu *cc, int direct)
221220456Sattilio{
222220456Sattilio
223247777Sdavide	cc->cc_exec_entity[direct].cc_curr = NULL;
224247777Sdavide	cc->cc_exec_entity[direct].cc_next = NULL;
225247818Sdavide	cc->cc_exec_entity[direct].cc_cancel = false;
226247818Sdavide	cc->cc_exec_entity[direct].cc_waiting = false;
227220456Sattilio#ifdef SMP
228247777Sdavide	cc->cc_exec_entity[direct].ce_migration_cpu = CPUBLOCK;
229247777Sdavide	cc->cc_exec_entity[direct].ce_migration_time = 0;
230247777Sdavide	cc->cc_exec_entity[direct].ce_migration_func = NULL;
231247777Sdavide	cc->cc_exec_entity[direct].ce_migration_arg = NULL;
232220456Sattilio#endif
233220456Sattilio}
234220456Sattilio
235220456Sattilio/*
236220456Sattilio * Checks if migration is requested by a specific callout cpu.
237220456Sattilio */
238220456Sattiliostatic int
239247777Sdavidecc_cce_migrating(struct callout_cpu *cc, int direct)
240220456Sattilio{
241220456Sattilio
242220456Sattilio#ifdef SMP
243247777Sdavide	return (cc->cc_exec_entity[direct].ce_migration_cpu != CPUBLOCK);
244220456Sattilio#else
245220456Sattilio	return (0);
246220456Sattilio#endif
247220456Sattilio}
248220456Sattilio
249220456Sattilio/*
250248032Sandre * Kernel low level callwheel initialization
251248032Sandre * called on cpu0 during kernel startup.
25282127Sdillon */
253248032Sandrestatic void
254248032Sandrecallout_callwheel_init(void *dummy)
25582127Sdillon{
256177859Sjeff	struct callout_cpu *cc;
257177859Sjeff
25882127Sdillon	/*
259248031Sandre	 * Calculate the size of the callout wheel and the preallocated
260248031Sandre	 * timeout() structures.
261248031Sandre	 */
262248031Sandre	ncallout = imin(16 + maxproc + maxfiles, 18508);
263248031Sandre	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
264248031Sandre
265248031Sandre	/*
266243853Salfred	 * Calculate callout wheel size, should be next power of two higher
267243853Salfred	 * than 'ncallout'.
26882127Sdillon	 */
269243853Salfred	callwheelsize = 1 << fls(ncallout);
27082127Sdillon	callwheelmask = callwheelsize - 1;
27182127Sdillon
272248032Sandre	/*
273248032Sandre	 * Only cpu0 handles timeout(9) and receives a preallocation.
274248032Sandre	 *
275248032Sandre	 * XXX: Once all timeout(9) consumers are converted this can
276248032Sandre	 * be removed.
277248032Sandre	 */
278248032Sandre	timeout_cpu = PCPU_GET(cpuid);
279248032Sandre	cc = CC_CPU(timeout_cpu);
280248032Sandre	cc->cc_callout = malloc(ncallout * sizeof(struct callout),
281248032Sandre	    M_CALLOUT, M_WAITOK);
282248032Sandre	callout_cpu_init(cc);
28382127Sdillon}
284248032SandreSYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
28582127Sdillon
286248032Sandre/*
287248032Sandre * Initialize the per-cpu callout structures.
288248032Sandre */
289177859Sjeffstatic void
290177859Sjeffcallout_cpu_init(struct callout_cpu *cc)
291177859Sjeff{
292177859Sjeff	struct callout *c;
293177859Sjeff	int i;
294177859Sjeff
295177859Sjeff	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
296177859Sjeff	SLIST_INIT(&cc->cc_callfree);
297248032Sandre	cc->cc_callwheel = malloc(sizeof(struct callout_tailq) * callwheelsize,
298248032Sandre	    M_CALLOUT, M_WAITOK);
299247777Sdavide	for (i = 0; i < callwheelsize; i++)
300247777Sdavide		LIST_INIT(&cc->cc_callwheel[i]);
301247777Sdavide	TAILQ_INIT(&cc->cc_expireq);
302247777Sdavide	cc->cc_firstevent = INT64_MAX;
303247777Sdavide	for (i = 0; i < 2; i++)
304247777Sdavide		cc_cce_cleanup(cc, i);
305248032Sandre	if (cc->cc_callout == NULL)	/* Only cpu0 handles timeout(9) */
306177859Sjeff		return;
307177859Sjeff	for (i = 0; i < ncallout; i++) {
308177859Sjeff		c = &cc->cc_callout[i];
309177859Sjeff		callout_init(c, 0);
310177859Sjeff		c->c_flags = CALLOUT_LOCAL_ALLOC;
311177859Sjeff		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
312177859Sjeff	}
313177859Sjeff}
314177859Sjeff
315220456Sattilio#ifdef SMP
31682127Sdillon/*
317220456Sattilio * Switches the cpu tied to a specific callout.
318220456Sattilio * The function expects a locked incoming callout cpu and returns with
319220456Sattilio * locked outcoming callout cpu.
320220456Sattilio */
321220456Sattiliostatic struct callout_cpu *
322220456Sattiliocallout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
323220456Sattilio{
324220456Sattilio	struct callout_cpu *new_cc;
325220456Sattilio
326220456Sattilio	MPASS(c != NULL && cc != NULL);
327220456Sattilio	CC_LOCK_ASSERT(cc);
328220456Sattilio
329225057Sattilio	/*
330225057Sattilio	 * Avoid interrupts and preemption firing after the callout cpu
331225057Sattilio	 * is blocked in order to avoid deadlocks as the new thread
332225057Sattilio	 * may be willing to acquire the callout cpu lock.
333225057Sattilio	 */
334220456Sattilio	c->c_cpu = CPUBLOCK;
335225057Sattilio	spinlock_enter();
336220456Sattilio	CC_UNLOCK(cc);
337220456Sattilio	new_cc = CC_CPU(new_cpu);
338220456Sattilio	CC_LOCK(new_cc);
339225057Sattilio	spinlock_exit();
340220456Sattilio	c->c_cpu = new_cpu;
341220456Sattilio	return (new_cc);
342220456Sattilio}
343220456Sattilio#endif
344220456Sattilio
345220456Sattilio/*
346177859Sjeff * Start standard softclock thread.
347177859Sjeff */
348177859Sjeffstatic void
349177859Sjeffstart_softclock(void *dummy)
350177859Sjeff{
351177859Sjeff	struct callout_cpu *cc;
352177859Sjeff#ifdef SMP
353177859Sjeff	int cpu;
354177859Sjeff#endif
355177859Sjeff
356177859Sjeff	cc = CC_CPU(timeout_cpu);
357177859Sjeff	if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
358214746Sjhb	    INTR_MPSAFE, &cc->cc_cookie))
359177859Sjeff		panic("died while creating standard software ithreads");
360177859Sjeff#ifdef SMP
361209059Sjhb	CPU_FOREACH(cpu) {
362177859Sjeff		if (cpu == timeout_cpu)
363177859Sjeff			continue;
364177859Sjeff		cc = CC_CPU(cpu);
365248032Sandre		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(9). */
366248032Sandre		callout_cpu_init(cc);
367177859Sjeff		if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
368177859Sjeff		    INTR_MPSAFE, &cc->cc_cookie))
369177859Sjeff			panic("died while creating standard software ithreads");
37082127Sdillon	}
371177859Sjeff#endif
372177859Sjeff}
373177859SjeffSYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
374177859Sjeff
375247777Sdavide#define	CC_HASH_SHIFT	8
376247777Sdavide
377247777Sdavidestatic inline u_int
378247777Sdavidecallout_hash(sbintime_t sbt)
379247777Sdavide{
380247777Sdavide
381247777Sdavide	return (sbt >> (32 - CC_HASH_SHIFT));
382247777Sdavide}
383247777Sdavide
384247777Sdavidestatic inline u_int
385247777Sdavidecallout_get_bucket(sbintime_t sbt)
386247777Sdavide{
387247777Sdavide
388247777Sdavide	return (callout_hash(sbt) & callwheelmask);
389247777Sdavide}
390247777Sdavide
391177859Sjeffvoid
392247777Sdavidecallout_process(sbintime_t now)
393177859Sjeff{
394247777Sdavide	struct callout *tmp, *tmpn;
395177859Sjeff	struct callout_cpu *cc;
396247777Sdavide	struct callout_list *sc;
397247777Sdavide	sbintime_t first, last, max, tmp_max;
398247777Sdavide	uint32_t lookahead;
399247777Sdavide	u_int firstb, lastb, nowb;
400247777Sdavide#ifdef CALLOUT_PROFILING
401247777Sdavide	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
402247777Sdavide#endif
403177859Sjeff
404247777Sdavide	cc = CC_SELF();
405247777Sdavide	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
406247777Sdavide
407247777Sdavide	/* Compute the buckets of the last scan and present times. */
408247777Sdavide	firstb = callout_hash(cc->cc_lastscan);
409247777Sdavide	cc->cc_lastscan = now;
410247777Sdavide	nowb = callout_hash(now);
411247777Sdavide
412247777Sdavide	/* Compute the last bucket and minimum time of the bucket after it. */
413247777Sdavide	if (nowb == firstb)
414247777Sdavide		lookahead = (SBT_1S / 16);
415247777Sdavide	else if (nowb - firstb == 1)
416247777Sdavide		lookahead = (SBT_1S / 8);
417247777Sdavide	else
418247777Sdavide		lookahead = (SBT_1S / 2);
419247777Sdavide	first = last = now;
420247777Sdavide	first += (lookahead / 2);
421247777Sdavide	last += lookahead;
422247777Sdavide	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
423247777Sdavide	lastb = callout_hash(last) - 1;
424247777Sdavide	max = last;
425247777Sdavide
426177859Sjeff	/*
427247777Sdavide	 * Check if we wrapped around the entire wheel from the last scan.
428247777Sdavide	 * In case, we need to scan entirely the wheel for pending callouts.
429177859Sjeff	 */
430247777Sdavide	if (lastb - firstb >= callwheelsize) {
431247777Sdavide		lastb = firstb + callwheelsize - 1;
432247777Sdavide		if (nowb - firstb >= callwheelsize)
433247777Sdavide			nowb = lastb;
434247777Sdavide	}
435247777Sdavide
436247777Sdavide	/* Iterate callwheel from firstb to nowb and then up to lastb. */
437247777Sdavide	do {
438247777Sdavide		sc = &cc->cc_callwheel[firstb & callwheelmask];
439247777Sdavide		tmp = LIST_FIRST(sc);
440247777Sdavide		while (tmp != NULL) {
441247777Sdavide			/* Run the callout if present time within allowed. */
442247777Sdavide			if (tmp->c_time <= now) {
443247777Sdavide				/*
444247777Sdavide				 * Consumer told us the callout may be run
445247777Sdavide				 * directly from hardware interrupt context.
446247777Sdavide				 */
447247777Sdavide				if (tmp->c_flags & CALLOUT_DIRECT) {
448247777Sdavide#ifdef CALLOUT_PROFILING
449247777Sdavide					++depth_dir;
450247777Sdavide#endif
451247777Sdavide					cc->cc_exec_next_dir =
452247777Sdavide					    LIST_NEXT(tmp, c_links.le);
453247777Sdavide					cc->cc_bucket = firstb & callwheelmask;
454247777Sdavide					LIST_REMOVE(tmp, c_links.le);
455247777Sdavide					softclock_call_cc(tmp, cc,
456247777Sdavide#ifdef CALLOUT_PROFILING
457247777Sdavide					    &mpcalls_dir, &lockcalls_dir, NULL,
458247777Sdavide#endif
459247777Sdavide					    1);
460247777Sdavide					tmp = cc->cc_exec_next_dir;
461247777Sdavide				} else {
462247777Sdavide					tmpn = LIST_NEXT(tmp, c_links.le);
463247777Sdavide					LIST_REMOVE(tmp, c_links.le);
464247777Sdavide					TAILQ_INSERT_TAIL(&cc->cc_expireq,
465247777Sdavide					    tmp, c_links.tqe);
466247777Sdavide					tmp->c_flags |= CALLOUT_PROCESSED;
467247777Sdavide					tmp = tmpn;
468247777Sdavide				}
469247777Sdavide				continue;
470247777Sdavide			}
471247777Sdavide			/* Skip events from distant future. */
472247777Sdavide			if (tmp->c_time >= max)
473247777Sdavide				goto next;
474247777Sdavide			/*
475247777Sdavide			 * Event minimal time is bigger than present maximal
476247777Sdavide			 * time, so it cannot be aggregated.
477247777Sdavide			 */
478247777Sdavide			if (tmp->c_time > last) {
479247777Sdavide				lastb = nowb;
480247777Sdavide				goto next;
481247777Sdavide			}
482247777Sdavide			/* Update first and last time, respecting this event. */
483247777Sdavide			if (tmp->c_time < first)
484247777Sdavide				first = tmp->c_time;
485247777Sdavide			tmp_max = tmp->c_time + tmp->c_precision;
486247777Sdavide			if (tmp_max < last)
487247777Sdavide				last = tmp_max;
488247777Sdavidenext:
489247777Sdavide			tmp = LIST_NEXT(tmp, c_links.le);
490180608Sjeff		}
491247777Sdavide		/* Proceed with the next bucket. */
492247777Sdavide		firstb++;
493247777Sdavide		/*
494247777Sdavide		 * Stop if we looked after present time and found
495247777Sdavide		 * some event we can't execute at now.
496247777Sdavide		 * Stop if we looked far enough into the future.
497247777Sdavide		 */
498247777Sdavide	} while (((int)(firstb - lastb)) <= 0);
499247777Sdavide	cc->cc_firstevent = last;
500247777Sdavide#ifndef NO_EVENTTIMERS
501247777Sdavide	cpu_new_callout(curcpu, last, first);
502247777Sdavide#endif
503247777Sdavide#ifdef CALLOUT_PROFILING
504247777Sdavide	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
505247777Sdavide	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
506247777Sdavide	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
507247777Sdavide#endif
508177859Sjeff	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
509177859Sjeff	/*
510177859Sjeff	 * swi_sched acquires the thread lock, so we don't want to call it
511177859Sjeff	 * with cc_lock held; incorrect locking order.
512177859Sjeff	 */
513247777Sdavide	if (!TAILQ_EMPTY(&cc->cc_expireq))
514177859Sjeff		swi_sched(cc->cc_cookie, 0);
515177859Sjeff}
516177859Sjeff
517177859Sjeffstatic struct callout_cpu *
518177859Sjeffcallout_lock(struct callout *c)
519177859Sjeff{
520177859Sjeff	struct callout_cpu *cc;
521177859Sjeff	int cpu;
522177859Sjeff
523177859Sjeff	for (;;) {
524177859Sjeff		cpu = c->c_cpu;
525220456Sattilio#ifdef SMP
526220456Sattilio		if (cpu == CPUBLOCK) {
527220456Sattilio			while (c->c_cpu == CPUBLOCK)
528220456Sattilio				cpu_spinwait();
529220456Sattilio			continue;
530220456Sattilio		}
531220456Sattilio#endif
532177859Sjeff		cc = CC_CPU(cpu);
533177859Sjeff		CC_LOCK(cc);
534177859Sjeff		if (cpu == c->c_cpu)
535177859Sjeff			break;
536177859Sjeff		CC_UNLOCK(cc);
53782127Sdillon	}
538177859Sjeff	return (cc);
53982127Sdillon}
54082127Sdillon
541220456Sattiliostatic void
542247777Sdavidecallout_cc_add(struct callout *c, struct callout_cpu *cc,
543247777Sdavide    sbintime_t sbt, sbintime_t precision, void (*func)(void *),
544247777Sdavide    void *arg, int cpu, int flags)
545220456Sattilio{
546247777Sdavide	int bucket;
547220456Sattilio
548220456Sattilio	CC_LOCK_ASSERT(cc);
549247777Sdavide	if (sbt < cc->cc_lastscan)
550247777Sdavide		sbt = cc->cc_lastscan;
551220456Sattilio	c->c_arg = arg;
552220456Sattilio	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
553247777Sdavide	if (flags & C_DIRECT_EXEC)
554247777Sdavide		c->c_flags |= CALLOUT_DIRECT;
555247777Sdavide	c->c_flags &= ~CALLOUT_PROCESSED;
556220456Sattilio	c->c_func = func;
557247777Sdavide	c->c_time = sbt;
558247777Sdavide	c->c_precision = precision;
559247777Sdavide	bucket = callout_get_bucket(c->c_time);
560247777Sdavide	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
561247777Sdavide	    c, (int)(c->c_precision >> 32),
562247777Sdavide	    (u_int)(c->c_precision & 0xffffffff));
563247777Sdavide	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
564247777Sdavide	if (cc->cc_bucket == bucket)
565247777Sdavide		cc->cc_exec_next_dir = c;
566247777Sdavide#ifndef NO_EVENTTIMERS
567247777Sdavide	/*
568247777Sdavide	 * Inform the eventtimers(4) subsystem there's a new callout
569247777Sdavide	 * that has been inserted, but only if really required.
570247777Sdavide	 */
571247777Sdavide	sbt = c->c_time + c->c_precision;
572247777Sdavide	if (sbt < cc->cc_firstevent) {
573247777Sdavide		cc->cc_firstevent = sbt;
574247777Sdavide		cpu_new_callout(cpu, sbt, c->c_time);
575220456Sattilio	}
576247777Sdavide#endif
577220456Sattilio}
578220456Sattilio
579234981Skibstatic void
580234981Skibcallout_cc_del(struct callout *c, struct callout_cpu *cc)
581234981Skib{
582234981Skib
583243901Skib	if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
584243901Skib		return;
585243901Skib	c->c_func = NULL;
586243901Skib	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
587234981Skib}
588234981Skib
589243901Skibstatic void
590247777Sdavidesoftclock_call_cc(struct callout *c, struct callout_cpu *cc,
591247777Sdavide#ifdef CALLOUT_PROFILING
592247777Sdavide    int *mpcalls, int *lockcalls, int *gcalls,
593247777Sdavide#endif
594247777Sdavide    int direct)
595234981Skib{
596234981Skib	void (*c_func)(void *);
597234981Skib	void *c_arg;
598234981Skib	struct lock_class *class;
599234981Skib	struct lock_object *c_lock;
600234981Skib	int c_flags, sharedlock;
601234981Skib#ifdef SMP
602234981Skib	struct callout_cpu *new_cc;
603234981Skib	void (*new_func)(void *);
604234981Skib	void *new_arg;
605247777Sdavide	int flags, new_cpu;
606247777Sdavide	sbintime_t new_time;
607234981Skib#endif
608247777Sdavide#if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
609247793Sdavide	sbintime_t sbt1, sbt2;
610234981Skib	struct timespec ts2;
611247777Sdavide	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
612234981Skib	static timeout_t *lastfunc;
613234981Skib#endif
614234981Skib
615243901Skib	KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
616243901Skib	    (CALLOUT_PENDING | CALLOUT_ACTIVE),
617243901Skib	    ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
618234981Skib	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
619234981Skib	sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ? 0 : 1;
620234981Skib	c_lock = c->c_lock;
621234981Skib	c_func = c->c_func;
622234981Skib	c_arg = c->c_arg;
623234981Skib	c_flags = c->c_flags;
624234981Skib	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
625234981Skib		c->c_flags = CALLOUT_LOCAL_ALLOC;
626234981Skib	else
627234981Skib		c->c_flags &= ~CALLOUT_PENDING;
628247777Sdavide	cc->cc_exec_entity[direct].cc_curr = c;
629247818Sdavide	cc->cc_exec_entity[direct].cc_cancel = false;
630234981Skib	CC_UNLOCK(cc);
631234981Skib	if (c_lock != NULL) {
632234981Skib		class->lc_lock(c_lock, sharedlock);
633234981Skib		/*
634234981Skib		 * The callout may have been cancelled
635234981Skib		 * while we switched locks.
636234981Skib		 */
637247777Sdavide		if (cc->cc_exec_entity[direct].cc_cancel) {
638234981Skib			class->lc_unlock(c_lock);
639234981Skib			goto skip;
640234981Skib		}
641234981Skib		/* The callout cannot be stopped now. */
642247818Sdavide		cc->cc_exec_entity[direct].cc_cancel = true;
643234981Skib		if (c_lock == &Giant.lock_object) {
644247777Sdavide#ifdef CALLOUT_PROFILING
645234981Skib			(*gcalls)++;
646247777Sdavide#endif
647247777Sdavide			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
648234981Skib			    c, c_func, c_arg);
649234981Skib		} else {
650247777Sdavide#ifdef CALLOUT_PROFILING
651234981Skib			(*lockcalls)++;
652247777Sdavide#endif
653234981Skib			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
654234981Skib			    c, c_func, c_arg);
655234981Skib		}
656234981Skib	} else {
657247777Sdavide#ifdef CALLOUT_PROFILING
658234981Skib		(*mpcalls)++;
659247777Sdavide#endif
660247777Sdavide		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
661234981Skib		    c, c_func, c_arg);
662234981Skib	}
663247793Sdavide#if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
664247777Sdavide	sbt1 = sbinuptime();
665234981Skib#endif
666234981Skib	THREAD_NO_SLEEPING();
667234981Skib	SDT_PROBE(callout_execute, kernel, , callout_start, c, 0, 0, 0, 0);
668234981Skib	c_func(c_arg);
669234981Skib	SDT_PROBE(callout_execute, kernel, , callout_end, c, 0, 0, 0, 0);
670234981Skib	THREAD_SLEEPING_OK();
671247793Sdavide#if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
672247793Sdavide	sbt2 = sbinuptime();
673247793Sdavide	sbt2 -= sbt1;
674247793Sdavide	if (sbt2 > maxdt) {
675247793Sdavide		if (lastfunc != c_func || sbt2 > maxdt * 2) {
676247793Sdavide			ts2 = sbttots(sbt2);
677234981Skib			printf(
678234981Skib		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
679234981Skib			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
680234981Skib		}
681247793Sdavide		maxdt = sbt2;
682234981Skib		lastfunc = c_func;
683234981Skib	}
684234981Skib#endif
685234981Skib	CTR1(KTR_CALLOUT, "callout %p finished", c);
686234981Skib	if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
687234981Skib		class->lc_unlock(c_lock);
688234981Skibskip:
689234981Skib	CC_LOCK(cc);
690247777Sdavide	KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
691247777Sdavide	cc->cc_exec_entity[direct].cc_curr = NULL;
692247777Sdavide	if (cc->cc_exec_entity[direct].cc_waiting) {
693234981Skib		/*
694234981Skib		 * There is someone waiting for the
695234981Skib		 * callout to complete.
696234981Skib		 * If the callout was scheduled for
697234981Skib		 * migration just cancel it.
698234981Skib		 */
699247777Sdavide		if (cc_cce_migrating(cc, direct)) {
700247777Sdavide			cc_cce_cleanup(cc, direct);
701243912Sattilio
702243912Sattilio			/*
703243912Sattilio			 * It should be assert here that the callout is not
704243912Sattilio			 * destroyed but that is not easy.
705243912Sattilio			 */
706243901Skib			c->c_flags &= ~CALLOUT_DFRMIGRATION;
707243901Skib		}
708247818Sdavide		cc->cc_exec_entity[direct].cc_waiting = false;
709234981Skib		CC_UNLOCK(cc);
710247777Sdavide		wakeup(&cc->cc_exec_entity[direct].cc_waiting);
711234981Skib		CC_LOCK(cc);
712247777Sdavide	} else if (cc_cce_migrating(cc, direct)) {
713243912Sattilio		KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
714243901Skib		    ("Migrating legacy callout %p", c));
715234981Skib#ifdef SMP
716234981Skib		/*
717234981Skib		 * If the callout was scheduled for
718234981Skib		 * migration just perform it now.
719234981Skib		 */
720247777Sdavide		new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
721247777Sdavide		new_time = cc->cc_exec_entity[direct].ce_migration_time;
722247777Sdavide		new_func = cc->cc_exec_entity[direct].ce_migration_func;
723247777Sdavide		new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
724247777Sdavide		cc_cce_cleanup(cc, direct);
725234981Skib
726234981Skib		/*
727243912Sattilio		 * It should be assert here that the callout is not destroyed
728243912Sattilio		 * but that is not easy.
729243912Sattilio		 *
730243912Sattilio		 * As first thing, handle deferred callout stops.
731234981Skib		 */
732234981Skib		if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
733234981Skib			CTR3(KTR_CALLOUT,
734234981Skib			     "deferred cancelled %p func %p arg %p",
735234981Skib			     c, new_func, new_arg);
736234981Skib			callout_cc_del(c, cc);
737243901Skib			return;
738234981Skib		}
739234981Skib		c->c_flags &= ~CALLOUT_DFRMIGRATION;
740234981Skib
741234981Skib		new_cc = callout_cpu_switch(c, cc, new_cpu);
742247777Sdavide		flags = (direct) ? C_DIRECT_EXEC : 0;
743247777Sdavide		callout_cc_add(c, new_cc, new_time, c->c_precision, new_func,
744247777Sdavide		    new_arg, new_cpu, flags);
745234981Skib		CC_UNLOCK(new_cc);
746234981Skib		CC_LOCK(cc);
747234981Skib#else
748234981Skib		panic("migration should not happen");
749234981Skib#endif
750234981Skib	}
751243901Skib	/*
752243901Skib	 * If the current callout is locally allocated (from
753243901Skib	 * timeout(9)) then put it on the freelist.
754243901Skib	 *
755243901Skib	 * Note: we need to check the cached copy of c_flags because
756243901Skib	 * if it was not local, then it's not safe to deref the
757243901Skib	 * callout pointer.
758243901Skib	 */
759243901Skib	KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
760243901Skib	    c->c_flags == CALLOUT_LOCAL_ALLOC,
761243901Skib	    ("corrupted callout"));
762243912Sattilio	if (c_flags & CALLOUT_LOCAL_ALLOC)
763243912Sattilio		callout_cc_del(c, cc);
764234981Skib}
765234981Skib
76682127Sdillon/*
767247467Sdavide * The callout mechanism is based on the work of Adam M. Costello and
76829680Sgibbs * George Varghese, published in a technical report entitled "Redesigning
76929680Sgibbs * the BSD Callout and Timer Facilities" and modified slightly for inclusion
77029680Sgibbs * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
771128630Shmp * used in this implementation was published by G. Varghese and T. Lauck in
77229680Sgibbs * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
77329680Sgibbs * the Efficient Implementation of a Timer Facility" in the Proceedings of
77429680Sgibbs * the 11th ACM Annual Symposium on Operating Systems Principles,
77529680Sgibbs * Austin, Texas Nov 1987.
77629680Sgibbs */
77732388Sphk
77829680Sgibbs/*
7791541Srgrimes * Software (low priority) clock interrupt.
7801541Srgrimes * Run periodic events from timeout queue.
7811541Srgrimes */
7821541Srgrimesvoid
783177859Sjeffsoftclock(void *arg)
7841541Srgrimes{
785177859Sjeff	struct callout_cpu *cc;
786102936Sphk	struct callout *c;
787247777Sdavide#ifdef CALLOUT_PROFILING
788247777Sdavide	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
789247777Sdavide#endif
7901541Srgrimes
791177859Sjeff	cc = (struct callout_cpu *)arg;
792177859Sjeff	CC_LOCK(cc);
793247777Sdavide	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
794247777Sdavide		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
795247777Sdavide		softclock_call_cc(c, cc,
796247777Sdavide#ifdef CALLOUT_PROFILING
797247777Sdavide		    &mpcalls, &lockcalls, &gcalls,
798247777Sdavide#endif
799247777Sdavide		    0);
800247777Sdavide#ifdef CALLOUT_PROFILING
801247777Sdavide		++depth;
802247777Sdavide#endif
8031541Srgrimes	}
804247777Sdavide#ifdef CALLOUT_PROFILING
805115810Sphk	avg_depth += (depth * 1000 - avg_depth) >> 8;
806115810Sphk	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
807173760Sattilio	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
808115810Sphk	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
809247777Sdavide#endif
810177859Sjeff	CC_UNLOCK(cc);
8111541Srgrimes}
8121541Srgrimes
8131541Srgrimes/*
8141541Srgrimes * timeout --
8151541Srgrimes *	Execute a function after a specified length of time.
8161541Srgrimes *
8171541Srgrimes * untimeout --
8181541Srgrimes *	Cancel previous timeout function call.
8191541Srgrimes *
82029680Sgibbs * callout_handle_init --
82129680Sgibbs *	Initialize a handle so that using it with untimeout is benign.
82229680Sgibbs *
8231541Srgrimes *	See AT&T BCI Driver Reference Manual for specification.  This
824247698Smav *	implementation differs from that one in that although an
82529680Sgibbs *	identification value is returned from timeout, the original
82629680Sgibbs *	arguments to timeout as well as the identifier are used to
82729680Sgibbs *	identify entries for untimeout.
8281541Srgrimes */
82929680Sgibbsstruct callout_handle
83029680Sgibbstimeout(ftn, arg, to_ticks)
83133824Sbde	timeout_t *ftn;
8321541Srgrimes	void *arg;
83369147Sjlemon	int to_ticks;
8341541Srgrimes{
835177859Sjeff	struct callout_cpu *cc;
83629680Sgibbs	struct callout *new;
83729680Sgibbs	struct callout_handle handle;
8381541Srgrimes
839177859Sjeff	cc = CC_CPU(timeout_cpu);
840177859Sjeff	CC_LOCK(cc);
8411541Srgrimes	/* Fill in the next free callout structure. */
842177859Sjeff	new = SLIST_FIRST(&cc->cc_callfree);
84329680Sgibbs	if (new == NULL)
84429680Sgibbs		/* XXX Attempt to malloc first */
8451541Srgrimes		panic("timeout table full");
846177859Sjeff	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
84744510Swollman	callout_reset(new, to_ticks, ftn, arg);
848177859Sjeff	handle.callout = new;
849177859Sjeff	CC_UNLOCK(cc);
8501541Srgrimes
85129680Sgibbs	return (handle);
8521541Srgrimes}
8531541Srgrimes
8541541Srgrimesvoid
85529680Sgibbsuntimeout(ftn, arg, handle)
85633824Sbde	timeout_t *ftn;
8571541Srgrimes	void *arg;
85829680Sgibbs	struct callout_handle handle;
8591541Srgrimes{
860177859Sjeff	struct callout_cpu *cc;
8611541Srgrimes
86229680Sgibbs	/*
86329680Sgibbs	 * Check for a handle that was initialized
86429680Sgibbs	 * by callout_handle_init, but never used
86529680Sgibbs	 * for a real timeout.
86629680Sgibbs	 */
86729680Sgibbs	if (handle.callout == NULL)
86829680Sgibbs		return;
86929680Sgibbs
870177859Sjeff	cc = callout_lock(handle.callout);
87144510Swollman	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
87244510Swollman		callout_stop(handle.callout);
873177859Sjeff	CC_UNLOCK(cc);
8741541Srgrimes}
8751541Srgrimes
87624101Sbdevoid
87729680Sgibbscallout_handle_init(struct callout_handle *handle)
87829680Sgibbs{
87929680Sgibbs	handle->callout = NULL;
88029680Sgibbs}
88129680Sgibbs
88244510Swollman/*
88344510Swollman * New interface; clients allocate their own callout structures.
88444510Swollman *
88544510Swollman * callout_reset() - establish or change a timeout
88644510Swollman * callout_stop() - disestablish a timeout
88744510Swollman * callout_init() - initialize a callout structure so that it can
88844510Swollman *	safely be passed to callout_reset() and callout_stop()
88944510Swollman *
89050673Sjlemon * <sys/callout.h> defines three convenience macros:
89144510Swollman *
892140487Scperciva * callout_active() - returns truth if callout has not been stopped,
893140487Scperciva *	drained, or deactivated since the last time the callout was
894140487Scperciva *	reset.
89550673Sjlemon * callout_pending() - returns truth if callout is still waiting for timeout
89650673Sjlemon * callout_deactivate() - marks the callout as having been serviced
89744510Swollman */
898149879Sglebiusint
899247777Sdavidecallout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
900247777Sdavide    void (*ftn)(void *), void *arg, int cpu, int flags)
90144510Swollman{
902247777Sdavide	sbintime_t to_sbt, pr;
903177859Sjeff	struct callout_cpu *cc;
904247777Sdavide	int cancelled, direct;
90544510Swollman
906247777Sdavide	cancelled = 0;
907247777Sdavide	if (flags & C_ABSOLUTE) {
908247777Sdavide		to_sbt = sbt;
909247777Sdavide	} else {
910247777Sdavide		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
911247777Sdavide			sbt = tick_sbt;
912247777Sdavide		if ((flags & C_HARDCLOCK) ||
913247777Sdavide#ifdef NO_EVENTTIMERS
914247777Sdavide		    sbt >= sbt_timethreshold) {
915247777Sdavide			to_sbt = getsbinuptime();
916247777Sdavide
917247777Sdavide			/* Add safety belt for the case of hz > 1000. */
918247777Sdavide			to_sbt += tc_tick_sbt - tick_sbt;
919247777Sdavide#else
920247777Sdavide		    sbt >= sbt_tickthreshold) {
921247777Sdavide			/*
922247777Sdavide			 * Obtain the time of the last hardclock() call on
923247777Sdavide			 * this CPU directly from the kern_clocksource.c.
924247777Sdavide			 * This value is per-CPU, but it is equal for all
925247777Sdavide			 * active ones.
926247777Sdavide			 */
927247777Sdavide#ifdef __LP64__
928247777Sdavide			to_sbt = DPCPU_GET(hardclocktime);
929247777Sdavide#else
930247777Sdavide			spinlock_enter();
931247777Sdavide			to_sbt = DPCPU_GET(hardclocktime);
932247777Sdavide			spinlock_exit();
933247777Sdavide#endif
934247777Sdavide#endif
935247777Sdavide			if ((flags & C_HARDCLOCK) == 0)
936247777Sdavide				to_sbt += tick_sbt;
937247777Sdavide		} else
938247777Sdavide			to_sbt = sbinuptime();
939247777Sdavide		to_sbt += sbt;
940247777Sdavide		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
941247777Sdavide		    sbt >> C_PRELGET(flags));
942247777Sdavide		if (pr > precision)
943247777Sdavide			precision = pr;
944247777Sdavide	}
945177859Sjeff	/*
946177859Sjeff	 * Don't allow migration of pre-allocated callouts lest they
947177859Sjeff	 * become unbalanced.
948177859Sjeff	 */
949177859Sjeff	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
950177859Sjeff		cpu = c->c_cpu;
951247777Sdavide	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
952247777Sdavide	KASSERT(!direct || c->c_lock == NULL,
953247777Sdavide	    ("%s: direct callout %p has lock", __func__, c));
954177859Sjeff	cc = callout_lock(c);
955247777Sdavide	if (cc->cc_exec_entity[direct].cc_curr == c) {
956127969Scperciva		/*
957127969Scperciva		 * We're being asked to reschedule a callout which is
958173760Sattilio		 * currently in progress.  If there is a lock then we
959141428Siedowse		 * can cancel the callout if it has not really started.
960127969Scperciva		 */
961247777Sdavide		if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
962247818Sdavide			cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
963247777Sdavide		if (cc->cc_exec_entity[direct].cc_waiting) {
964141428Siedowse			/*
965141428Siedowse			 * Someone has called callout_drain to kill this
966141428Siedowse			 * callout.  Don't reschedule.
967141428Siedowse			 */
968163246Sglebius			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
969163246Sglebius			    cancelled ? "cancelled" : "failed to cancel",
970163246Sglebius			    c, c->c_func, c->c_arg);
971177859Sjeff			CC_UNLOCK(cc);
972149879Sglebius			return (cancelled);
973141428Siedowse		}
974128024Scperciva	}
975133190Scperciva	if (c->c_flags & CALLOUT_PENDING) {
976247777Sdavide		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
977247777Sdavide			if (cc->cc_exec_next_dir == c)
978247777Sdavide				cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
979247777Sdavide			LIST_REMOVE(c, c_links.le);
980247777Sdavide		} else
981247777Sdavide			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
982149879Sglebius		cancelled = 1;
983177859Sjeff		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
984133190Scperciva	}
985220456Sattilio
986220456Sattilio#ifdef SMP
98744510Swollman	/*
988220456Sattilio	 * If the callout must migrate try to perform it immediately.
989220456Sattilio	 * If the callout is currently running, just defer the migration
990220456Sattilio	 * to a more appropriate moment.
99144510Swollman	 */
992177859Sjeff	if (c->c_cpu != cpu) {
993247777Sdavide		if (cc->cc_exec_entity[direct].cc_curr == c) {
994247777Sdavide			cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
995247777Sdavide			cc->cc_exec_entity[direct].ce_migration_time
996247777Sdavide			    = to_sbt;
997247777Sdavide			cc->cc_exec_entity[direct].ce_migration_func = ftn;
998247777Sdavide			cc->cc_exec_entity[direct].ce_migration_arg = arg;
999234952Skib			c->c_flags |= CALLOUT_DFRMIGRATION;
1000247777Sdavide			CTR6(KTR_CALLOUT,
1001247777Sdavide		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1002247777Sdavide			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1003247777Sdavide			    (u_int)(to_sbt & 0xffffffff), cpu);
1004220456Sattilio			CC_UNLOCK(cc);
1005220456Sattilio			return (cancelled);
1006220456Sattilio		}
1007220456Sattilio		cc = callout_cpu_switch(c, cc, cpu);
1008177859Sjeff	}
1009220456Sattilio#endif
1010177859Sjeff
1011247777Sdavide	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1012247777Sdavide	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1013247777Sdavide	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1014247777Sdavide	    (u_int)(to_sbt & 0xffffffff));
1015177859Sjeff	CC_UNLOCK(cc);
1016149879Sglebius
1017149879Sglebius	return (cancelled);
101844510Swollman}
101944510Swollman
1020181191Ssam/*
1021181191Ssam * Common idioms that can be optimized in the future.
1022181191Ssam */
102381481Sjhbint
1024181191Ssamcallout_schedule_on(struct callout *c, int to_ticks, int cpu)
1025181191Ssam{
1026181191Ssam	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1027181191Ssam}
1028181191Ssam
1029181191Ssamint
1030181191Ssamcallout_schedule(struct callout *c, int to_ticks)
1031181191Ssam{
1032181191Ssam	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1033181191Ssam}
1034181191Ssam
1035181191Ssamint
1036127969Scperciva_callout_stop_safe(c, safe)
1037127969Scperciva	struct	callout *c;
1038127969Scperciva	int	safe;
1039127969Scperciva{
1040220456Sattilio	struct callout_cpu *cc, *old_cc;
1041173760Sattilio	struct lock_class *class;
1042247777Sdavide	int direct, sq_locked, use_lock;
1043127969Scperciva
1044173760Sattilio	/*
1045173760Sattilio	 * Some old subsystems don't hold Giant while running a callout_stop(),
1046173760Sattilio	 * so just discard this check for the moment.
1047173760Sattilio	 */
1048173760Sattilio	if (!safe && c->c_lock != NULL) {
1049173760Sattilio		if (c->c_lock == &Giant.lock_object)
1050173760Sattilio			use_lock = mtx_owned(&Giant);
1051173760Sattilio		else {
1052173760Sattilio			use_lock = 1;
1053173760Sattilio			class = LOCK_CLASS(c->c_lock);
1054173760Sattilio			class->lc_assert(c->c_lock, LA_XLOCKED);
1055173760Sattilio		}
1056173760Sattilio	} else
1057173760Sattilio		use_lock = 0;
1058247777Sdavide	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1059172025Sjhb	sq_locked = 0;
1060220456Sattilio	old_cc = NULL;
1061172025Sjhbagain:
1062177859Sjeff	cc = callout_lock(c);
1063220456Sattilio
106444510Swollman	/*
1065220456Sattilio	 * If the callout was migrating while the callout cpu lock was
1066220456Sattilio	 * dropped,  just drop the sleepqueue lock and check the states
1067220456Sattilio	 * again.
1068220456Sattilio	 */
1069220456Sattilio	if (sq_locked != 0 && cc != old_cc) {
1070220456Sattilio#ifdef SMP
1071220456Sattilio		CC_UNLOCK(cc);
1072247777Sdavide		sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
1073220456Sattilio		sq_locked = 0;
1074220456Sattilio		old_cc = NULL;
1075220456Sattilio		goto again;
1076220456Sattilio#else
1077220456Sattilio		panic("migration should not happen");
1078220456Sattilio#endif
1079220456Sattilio	}
1080220456Sattilio
1081220456Sattilio	/*
1082155957Sjhb	 * If the callout isn't pending, it's not on the queue, so
1083155957Sjhb	 * don't attempt to remove it from the queue.  We can try to
1084155957Sjhb	 * stop it by other means however.
108544510Swollman	 */
108644510Swollman	if (!(c->c_flags & CALLOUT_PENDING)) {
108750673Sjlemon		c->c_flags &= ~CALLOUT_ACTIVE;
1088155957Sjhb
1089155957Sjhb		/*
1090155957Sjhb		 * If it wasn't on the queue and it isn't the current
1091155957Sjhb		 * callout, then we can't stop it, so just bail.
1092155957Sjhb		 */
1093247777Sdavide		if (cc->cc_exec_entity[direct].cc_curr != c) {
1094163246Sglebius			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1095163246Sglebius			    c, c->c_func, c->c_arg);
1096177859Sjeff			CC_UNLOCK(cc);
1097172025Sjhb			if (sq_locked)
1098247777Sdavide				sleepq_release(
1099247777Sdavide				    &cc->cc_exec_entity[direct].cc_waiting);
1100141428Siedowse			return (0);
1101141428Siedowse		}
1102155957Sjhb
1103141428Siedowse		if (safe) {
1104127969Scperciva			/*
1105155957Sjhb			 * The current callout is running (or just
1106155957Sjhb			 * about to run) and blocking is allowed, so
1107155957Sjhb			 * just wait for the current invocation to
1108155957Sjhb			 * finish.
1109127969Scperciva			 */
1110247777Sdavide			while (cc->cc_exec_entity[direct].cc_curr == c) {
1111171053Sattilio				/*
1112171053Sattilio				 * Use direct calls to sleepqueue interface
1113171053Sattilio				 * instead of cv/msleep in order to avoid
1114177859Sjeff				 * a LOR between cc_lock and sleepqueue
1115171053Sattilio				 * chain spinlocks.  This piece of code
1116171053Sattilio				 * emulates a msleep_spin() call actually.
1117172025Sjhb				 *
1118172025Sjhb				 * If we already have the sleepqueue chain
1119172025Sjhb				 * locked, then we can safely block.  If we
1120172025Sjhb				 * don't already have it locked, however,
1121177859Sjeff				 * we have to drop the cc_lock to lock
1122172025Sjhb				 * it.  This opens several races, so we
1123172025Sjhb				 * restart at the beginning once we have
1124172025Sjhb				 * both locks.  If nothing has changed, then
1125172025Sjhb				 * we will end up back here with sq_locked
1126172025Sjhb				 * set.
1127171053Sattilio				 */
1128172025Sjhb				if (!sq_locked) {
1129177859Sjeff					CC_UNLOCK(cc);
1130247777Sdavide					sleepq_lock(
1131247777Sdavide					&cc->cc_exec_entity[direct].cc_waiting);
1132172025Sjhb					sq_locked = 1;
1133220456Sattilio					old_cc = cc;
1134172025Sjhb					goto again;
1135172025Sjhb				}
1136220456Sattilio
1137220456Sattilio				/*
1138220456Sattilio				 * Migration could be cancelled here, but
1139220456Sattilio				 * as long as it is still not sure when it
1140220456Sattilio				 * will be packed up, just let softclock()
1141220456Sattilio				 * take care of it.
1142220456Sattilio				 */
1143247818Sdavide				cc->cc_exec_entity[direct].cc_waiting = true;
1144171053Sattilio				DROP_GIANT();
1145177859Sjeff				CC_UNLOCK(cc);
1146247777Sdavide				sleepq_add(
1147247777Sdavide				    &cc->cc_exec_entity[direct].cc_waiting,
1148177859Sjeff				    &cc->cc_lock.lock_object, "codrain",
1149171053Sattilio				    SLEEPQ_SLEEP, 0);
1150247777Sdavide				sleepq_wait(
1151247777Sdavide				    &cc->cc_exec_entity[direct].cc_waiting,
1152247777Sdavide					     0);
1153172025Sjhb				sq_locked = 0;
1154220456Sattilio				old_cc = NULL;
1155171053Sattilio
1156171053Sattilio				/* Reacquire locks previously released. */
1157171053Sattilio				PICKUP_GIANT();
1158177859Sjeff				CC_LOCK(cc);
1159155957Sjhb			}
1160247777Sdavide		} else if (use_lock &&
1161247777Sdavide			    !cc->cc_exec_entity[direct].cc_cancel) {
1162155957Sjhb			/*
1163173760Sattilio			 * The current callout is waiting for its
1164173760Sattilio			 * lock which we hold.  Cancel the callout
1165155957Sjhb			 * and return.  After our caller drops the
1166173760Sattilio			 * lock, the callout will be skipped in
1167155957Sjhb			 * softclock().
1168155957Sjhb			 */
1169247818Sdavide			cc->cc_exec_entity[direct].cc_cancel = true;
1170163246Sglebius			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1171163246Sglebius			    c, c->c_func, c->c_arg);
1172247777Sdavide			KASSERT(!cc_cce_migrating(cc, direct),
1173220456Sattilio			    ("callout wrongly scheduled for migration"));
1174177859Sjeff			CC_UNLOCK(cc);
1175172025Sjhb			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1176141428Siedowse			return (1);
1177234952Skib		} else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
1178234952Skib			c->c_flags &= ~CALLOUT_DFRMIGRATION;
1179234952Skib			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1180234952Skib			    c, c->c_func, c->c_arg);
1181234952Skib			CC_UNLOCK(cc);
1182234952Skib			return (1);
1183155957Sjhb		}
1184163246Sglebius		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1185163246Sglebius		    c, c->c_func, c->c_arg);
1186177859Sjeff		CC_UNLOCK(cc);
1187172025Sjhb		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
118881481Sjhb		return (0);
118944510Swollman	}
1190172025Sjhb	if (sq_locked)
1191247777Sdavide		sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
1192172025Sjhb
119350673Sjlemon	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
119444510Swollman
1195234981Skib	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1196234981Skib	    c, c->c_func, c->c_arg);
1197247777Sdavide	if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1198247777Sdavide		if (cc->cc_exec_next_dir == c)
1199247777Sdavide			cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1200247777Sdavide		LIST_REMOVE(c, c_links.le);
1201247777Sdavide	} else
1202247777Sdavide		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1203234981Skib	callout_cc_del(c, cc);
120444510Swollman
1205177859Sjeff	CC_UNLOCK(cc);
120681481Sjhb	return (1);
120744510Swollman}
120844510Swollman
120944510Swollmanvoid
121069147Sjlemoncallout_init(c, mpsafe)
121144510Swollman	struct	callout *c;
121269147Sjlemon	int mpsafe;
121344510Swollman{
121444527Swollman	bzero(c, sizeof *c);
1215141428Siedowse	if (mpsafe) {
1216173760Sattilio		c->c_lock = NULL;
1217141428Siedowse		c->c_flags = CALLOUT_RETURNUNLOCKED;
1218141428Siedowse	} else {
1219173760Sattilio		c->c_lock = &Giant.lock_object;
1220141428Siedowse		c->c_flags = 0;
1221141428Siedowse	}
1222177859Sjeff	c->c_cpu = timeout_cpu;
122344510Swollman}
122444510Swollman
1225141428Siedowsevoid
1226173760Sattilio_callout_init_lock(c, lock, flags)
1227141428Siedowse	struct	callout *c;
1228173760Sattilio	struct	lock_object *lock;
1229141428Siedowse	int flags;
1230141428Siedowse{
1231141428Siedowse	bzero(c, sizeof *c);
1232173760Sattilio	c->c_lock = lock;
1233173760Sattilio	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1234173760Sattilio	    ("callout_init_lock: bad flags %d", flags));
1235173760Sattilio	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1236173760Sattilio	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1237176013Sattilio	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1238176013Sattilio	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1239173760Sattilio	    __func__));
1240173760Sattilio	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1241177859Sjeff	c->c_cpu = timeout_cpu;
1242141428Siedowse}
1243141428Siedowse
124431950Snate#ifdef APM_FIXUP_CALLTODO
124531950Snate/*
124631950Snate * Adjust the kernel calltodo timeout list.  This routine is used after
124731950Snate * an APM resume to recalculate the calltodo timer list values with the
124831950Snate * number of hz's we have been sleeping.  The next hardclock() will detect
124931950Snate * that there are fired timers and run softclock() to execute them.
125031950Snate *
125131950Snate * Please note, I have not done an exhaustive analysis of what code this
125231950Snate * might break.  I am motivated to have my select()'s and alarm()'s that
125331950Snate * have expired during suspend firing upon resume so that the applications
125431950Snate * which set the timer can do the maintanence the timer was for as close
125531950Snate * as possible to the originally intended time.  Testing this code for a
125631950Snate * week showed that resuming from a suspend resulted in 22 to 25 timers
125731950Snate * firing, which seemed independant on whether the suspend was 2 hours or
125831950Snate * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
125931950Snate */
126031950Snatevoid
126131950Snateadjust_timeout_calltodo(time_change)
126231950Snate    struct timeval *time_change;
126331950Snate{
126431950Snate	register struct callout *p;
126531950Snate	unsigned long delta_ticks;
126631950Snate
126731950Snate	/*
126831950Snate	 * How many ticks were we asleep?
126936127Sbde	 * (stolen from tvtohz()).
127031950Snate	 */
127131950Snate
127231950Snate	/* Don't do anything */
127331950Snate	if (time_change->tv_sec < 0)
127431950Snate		return;
127531950Snate	else if (time_change->tv_sec <= LONG_MAX / 1000000)
127631950Snate		delta_ticks = (time_change->tv_sec * 1000000 +
127731950Snate			       time_change->tv_usec + (tick - 1)) / tick + 1;
127831950Snate	else if (time_change->tv_sec <= LONG_MAX / hz)
127931950Snate		delta_ticks = time_change->tv_sec * hz +
128031950Snate			      (time_change->tv_usec + (tick - 1)) / tick + 1;
128131950Snate	else
128231950Snate		delta_ticks = LONG_MAX;
128331950Snate
128431950Snate	if (delta_ticks > INT_MAX)
128531950Snate		delta_ticks = INT_MAX;
128631950Snate
128731950Snate	/*
128831950Snate	 * Now rip through the timer calltodo list looking for timers
128931950Snate	 * to expire.
129031950Snate	 */
129131950Snate
129231950Snate	/* don't collide with softclock() */
1293177859Sjeff	CC_LOCK(cc);
129431950Snate	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
129531950Snate		p->c_time -= delta_ticks;
129631950Snate
129731950Snate		/* Break if the timer had more time on it than delta_ticks */
129831950Snate		if (p->c_time > 0)
129931950Snate			break;
130031950Snate
130131950Snate		/* take back the ticks the timer didn't use (p->c_time <= 0) */
130231950Snate		delta_ticks = -p->c_time;
130331950Snate	}
1304177859Sjeff	CC_UNLOCK(cc);
130531950Snate
130631950Snate	return;
130731950Snate}
130831950Snate#endif /* APM_FIXUP_CALLTODO */
1309247777Sdavide
1310247777Sdavidestatic int
1311247777Sdavideflssbt(sbintime_t sbt)
1312247777Sdavide{
1313247777Sdavide
1314247777Sdavide	sbt += (uint64_t)sbt >> 1;
1315247777Sdavide	if (sizeof(long) >= sizeof(sbintime_t))
1316247777Sdavide		return (flsl(sbt));
1317247777Sdavide	if (sbt >= SBT_1S)
1318247777Sdavide		return (flsl(((uint64_t)sbt) >> 32) + 32);
1319247777Sdavide	return (flsl(sbt));
1320247777Sdavide}
1321247777Sdavide
1322247777Sdavide/*
1323247777Sdavide * Dump immediate statistic snapshot of the scheduled callouts.
1324247777Sdavide */
1325247777Sdavidestatic int
1326247777Sdavidesysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1327247777Sdavide{
1328247777Sdavide	struct callout *tmp;
1329247777Sdavide	struct callout_cpu *cc;
1330247777Sdavide	struct callout_list *sc;
1331247777Sdavide	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1332247777Sdavide	int ct[64], cpr[64], ccpbk[32];
1333247777Sdavide	int error, val, i, count, tcum, pcum, maxc, c, medc;
1334247777Sdavide#ifdef SMP
1335247777Sdavide	int cpu;
1336247777Sdavide#endif
1337247777Sdavide
1338247777Sdavide	val = 0;
1339247777Sdavide	error = sysctl_handle_int(oidp, &val, 0, req);
1340247777Sdavide	if (error != 0 || req->newptr == NULL)
1341247777Sdavide		return (error);
1342247777Sdavide	count = maxc = 0;
1343247777Sdavide	st = spr = maxt = maxpr = 0;
1344247777Sdavide	bzero(ccpbk, sizeof(ccpbk));
1345247777Sdavide	bzero(ct, sizeof(ct));
1346247777Sdavide	bzero(cpr, sizeof(cpr));
1347247777Sdavide	now = sbinuptime();
1348247777Sdavide#ifdef SMP
1349247777Sdavide	CPU_FOREACH(cpu) {
1350247777Sdavide		cc = CC_CPU(cpu);
1351247777Sdavide#else
1352247777Sdavide		cc = CC_CPU(timeout_cpu);
1353247777Sdavide#endif
1354247777Sdavide		CC_LOCK(cc);
1355247777Sdavide		for (i = 0; i < callwheelsize; i++) {
1356247777Sdavide			sc = &cc->cc_callwheel[i];
1357247777Sdavide			c = 0;
1358247777Sdavide			LIST_FOREACH(tmp, sc, c_links.le) {
1359247777Sdavide				c++;
1360247777Sdavide				t = tmp->c_time - now;
1361247777Sdavide				if (t < 0)
1362247777Sdavide					t = 0;
1363247777Sdavide				st += t / SBT_1US;
1364247777Sdavide				spr += tmp->c_precision / SBT_1US;
1365247777Sdavide				if (t > maxt)
1366247777Sdavide					maxt = t;
1367247777Sdavide				if (tmp->c_precision > maxpr)
1368247777Sdavide					maxpr = tmp->c_precision;
1369247777Sdavide				ct[flssbt(t)]++;
1370247777Sdavide				cpr[flssbt(tmp->c_precision)]++;
1371247777Sdavide			}
1372247777Sdavide			if (c > maxc)
1373247777Sdavide				maxc = c;
1374247777Sdavide			ccpbk[fls(c + c / 2)]++;
1375247777Sdavide			count += c;
1376247777Sdavide		}
1377247777Sdavide		CC_UNLOCK(cc);
1378247777Sdavide#ifdef SMP
1379247777Sdavide	}
1380247777Sdavide#endif
1381247777Sdavide
1382247777Sdavide	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1383247777Sdavide		tcum += ct[i];
1384247777Sdavide	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1385247777Sdavide	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1386247777Sdavide		pcum += cpr[i];
1387247777Sdavide	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1388247777Sdavide	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1389247777Sdavide		c += ccpbk[i];
1390247777Sdavide	medc = (i >= 2) ? (1 << (i - 2)) : 0;
1391247777Sdavide
1392247777Sdavide	printf("Scheduled callouts statistic snapshot:\n");
1393247777Sdavide	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1394247777Sdavide	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1395247777Sdavide	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1396247777Sdavide	    medc,
1397247777Sdavide	    count / callwheelsize / mp_ncpus,
1398247777Sdavide	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1399247777Sdavide	    maxc);
1400247777Sdavide	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1401247777Sdavide	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1402247777Sdavide	    (st / count) / 1000000, (st / count) % 1000000,
1403247777Sdavide	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1404247777Sdavide	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1405247777Sdavide	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1406247777Sdavide	    (spr / count) / 1000000, (spr / count) % 1000000,
1407247777Sdavide	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1408247777Sdavide	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1409247777Sdavide	    "   prec\t   pcum\n");
1410247777Sdavide	for (i = 0, tcum = pcum = 0; i < 64; i++) {
1411247777Sdavide		if (ct[i] == 0 && cpr[i] == 0)
1412247777Sdavide			continue;
1413247777Sdavide		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1414247777Sdavide		tcum += ct[i];
1415247777Sdavide		pcum += cpr[i];
1416247777Sdavide		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1417247777Sdavide		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1418247777Sdavide		    i - 1 - (32 - CC_HASH_SHIFT),
1419247777Sdavide		    ct[i], tcum, cpr[i], pcum);
1420247777Sdavide	}
1421247777Sdavide	return (error);
1422247777Sdavide}
1423247777SdavideSYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1424247777Sdavide    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1425247777Sdavide    0, 0, sysctl_kern_callout_stat, "I",
1426247777Sdavide    "Dump immediate statistic snapshot of the scheduled callouts");
1427