kern_timeout.c revision 248141
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 248141 2013-03-10 22:55:35Z 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.
261248141Sandre	 * XXX: Clip callout to result of previous function of maxusers
262248141Sandre	 * maximum 384.  This is still huge, but acceptable.
263248031Sandre	 */
264248031Sandre	ncallout = imin(16 + maxproc + maxfiles, 18508);
265248031Sandre	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
266248031Sandre
267248031Sandre	/*
268243853Salfred	 * Calculate callout wheel size, should be next power of two higher
269243853Salfred	 * than 'ncallout'.
27082127Sdillon	 */
271243853Salfred	callwheelsize = 1 << fls(ncallout);
27282127Sdillon	callwheelmask = callwheelsize - 1;
27382127Sdillon
274248032Sandre	/*
275248032Sandre	 * Only cpu0 handles timeout(9) and receives a preallocation.
276248032Sandre	 *
277248032Sandre	 * XXX: Once all timeout(9) consumers are converted this can
278248032Sandre	 * be removed.
279248032Sandre	 */
280248032Sandre	timeout_cpu = PCPU_GET(cpuid);
281248032Sandre	cc = CC_CPU(timeout_cpu);
282248032Sandre	cc->cc_callout = malloc(ncallout * sizeof(struct callout),
283248032Sandre	    M_CALLOUT, M_WAITOK);
284248032Sandre	callout_cpu_init(cc);
28582127Sdillon}
286248032SandreSYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
28782127Sdillon
288248032Sandre/*
289248032Sandre * Initialize the per-cpu callout structures.
290248032Sandre */
291177859Sjeffstatic void
292177859Sjeffcallout_cpu_init(struct callout_cpu *cc)
293177859Sjeff{
294177859Sjeff	struct callout *c;
295177859Sjeff	int i;
296177859Sjeff
297177859Sjeff	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
298177859Sjeff	SLIST_INIT(&cc->cc_callfree);
299248113Sdavide	cc->cc_callwheel = malloc(sizeof(struct callout_list) * callwheelsize,
300248032Sandre	    M_CALLOUT, M_WAITOK);
301247777Sdavide	for (i = 0; i < callwheelsize; i++)
302247777Sdavide		LIST_INIT(&cc->cc_callwheel[i]);
303247777Sdavide	TAILQ_INIT(&cc->cc_expireq);
304247777Sdavide	cc->cc_firstevent = INT64_MAX;
305247777Sdavide	for (i = 0; i < 2; i++)
306247777Sdavide		cc_cce_cleanup(cc, i);
307248032Sandre	if (cc->cc_callout == NULL)	/* Only cpu0 handles timeout(9) */
308177859Sjeff		return;
309177859Sjeff	for (i = 0; i < ncallout; i++) {
310177859Sjeff		c = &cc->cc_callout[i];
311177859Sjeff		callout_init(c, 0);
312177859Sjeff		c->c_flags = CALLOUT_LOCAL_ALLOC;
313177859Sjeff		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
314177859Sjeff	}
315177859Sjeff}
316177859Sjeff
317220456Sattilio#ifdef SMP
31882127Sdillon/*
319220456Sattilio * Switches the cpu tied to a specific callout.
320220456Sattilio * The function expects a locked incoming callout cpu and returns with
321220456Sattilio * locked outcoming callout cpu.
322220456Sattilio */
323220456Sattiliostatic struct callout_cpu *
324220456Sattiliocallout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
325220456Sattilio{
326220456Sattilio	struct callout_cpu *new_cc;
327220456Sattilio
328220456Sattilio	MPASS(c != NULL && cc != NULL);
329220456Sattilio	CC_LOCK_ASSERT(cc);
330220456Sattilio
331225057Sattilio	/*
332225057Sattilio	 * Avoid interrupts and preemption firing after the callout cpu
333225057Sattilio	 * is blocked in order to avoid deadlocks as the new thread
334225057Sattilio	 * may be willing to acquire the callout cpu lock.
335225057Sattilio	 */
336220456Sattilio	c->c_cpu = CPUBLOCK;
337225057Sattilio	spinlock_enter();
338220456Sattilio	CC_UNLOCK(cc);
339220456Sattilio	new_cc = CC_CPU(new_cpu);
340220456Sattilio	CC_LOCK(new_cc);
341225057Sattilio	spinlock_exit();
342220456Sattilio	c->c_cpu = new_cpu;
343220456Sattilio	return (new_cc);
344220456Sattilio}
345220456Sattilio#endif
346220456Sattilio
347220456Sattilio/*
348177859Sjeff * Start standard softclock thread.
349177859Sjeff */
350177859Sjeffstatic void
351177859Sjeffstart_softclock(void *dummy)
352177859Sjeff{
353177859Sjeff	struct callout_cpu *cc;
354177859Sjeff#ifdef SMP
355177859Sjeff	int cpu;
356177859Sjeff#endif
357177859Sjeff
358177859Sjeff	cc = CC_CPU(timeout_cpu);
359177859Sjeff	if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
360214746Sjhb	    INTR_MPSAFE, &cc->cc_cookie))
361177859Sjeff		panic("died while creating standard software ithreads");
362177859Sjeff#ifdef SMP
363209059Sjhb	CPU_FOREACH(cpu) {
364177859Sjeff		if (cpu == timeout_cpu)
365177859Sjeff			continue;
366177859Sjeff		cc = CC_CPU(cpu);
367248032Sandre		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(9). */
368248032Sandre		callout_cpu_init(cc);
369177859Sjeff		if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
370177859Sjeff		    INTR_MPSAFE, &cc->cc_cookie))
371177859Sjeff			panic("died while creating standard software ithreads");
37282127Sdillon	}
373177859Sjeff#endif
374177859Sjeff}
375177859SjeffSYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
376177859Sjeff
377247777Sdavide#define	CC_HASH_SHIFT	8
378247777Sdavide
379247777Sdavidestatic inline u_int
380247777Sdavidecallout_hash(sbintime_t sbt)
381247777Sdavide{
382247777Sdavide
383247777Sdavide	return (sbt >> (32 - CC_HASH_SHIFT));
384247777Sdavide}
385247777Sdavide
386247777Sdavidestatic inline u_int
387247777Sdavidecallout_get_bucket(sbintime_t sbt)
388247777Sdavide{
389247777Sdavide
390247777Sdavide	return (callout_hash(sbt) & callwheelmask);
391247777Sdavide}
392247777Sdavide
393177859Sjeffvoid
394247777Sdavidecallout_process(sbintime_t now)
395177859Sjeff{
396247777Sdavide	struct callout *tmp, *tmpn;
397177859Sjeff	struct callout_cpu *cc;
398247777Sdavide	struct callout_list *sc;
399247777Sdavide	sbintime_t first, last, max, tmp_max;
400247777Sdavide	uint32_t lookahead;
401247777Sdavide	u_int firstb, lastb, nowb;
402247777Sdavide#ifdef CALLOUT_PROFILING
403247777Sdavide	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
404247777Sdavide#endif
405177859Sjeff
406247777Sdavide	cc = CC_SELF();
407247777Sdavide	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
408247777Sdavide
409247777Sdavide	/* Compute the buckets of the last scan and present times. */
410247777Sdavide	firstb = callout_hash(cc->cc_lastscan);
411247777Sdavide	cc->cc_lastscan = now;
412247777Sdavide	nowb = callout_hash(now);
413247777Sdavide
414247777Sdavide	/* Compute the last bucket and minimum time of the bucket after it. */
415247777Sdavide	if (nowb == firstb)
416247777Sdavide		lookahead = (SBT_1S / 16);
417247777Sdavide	else if (nowb - firstb == 1)
418247777Sdavide		lookahead = (SBT_1S / 8);
419247777Sdavide	else
420247777Sdavide		lookahead = (SBT_1S / 2);
421247777Sdavide	first = last = now;
422247777Sdavide	first += (lookahead / 2);
423247777Sdavide	last += lookahead;
424247777Sdavide	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
425247777Sdavide	lastb = callout_hash(last) - 1;
426247777Sdavide	max = last;
427247777Sdavide
428177859Sjeff	/*
429247777Sdavide	 * Check if we wrapped around the entire wheel from the last scan.
430247777Sdavide	 * In case, we need to scan entirely the wheel for pending callouts.
431177859Sjeff	 */
432247777Sdavide	if (lastb - firstb >= callwheelsize) {
433247777Sdavide		lastb = firstb + callwheelsize - 1;
434247777Sdavide		if (nowb - firstb >= callwheelsize)
435247777Sdavide			nowb = lastb;
436247777Sdavide	}
437247777Sdavide
438247777Sdavide	/* Iterate callwheel from firstb to nowb and then up to lastb. */
439247777Sdavide	do {
440247777Sdavide		sc = &cc->cc_callwheel[firstb & callwheelmask];
441247777Sdavide		tmp = LIST_FIRST(sc);
442247777Sdavide		while (tmp != NULL) {
443247777Sdavide			/* Run the callout if present time within allowed. */
444247777Sdavide			if (tmp->c_time <= now) {
445247777Sdavide				/*
446247777Sdavide				 * Consumer told us the callout may be run
447247777Sdavide				 * directly from hardware interrupt context.
448247777Sdavide				 */
449247777Sdavide				if (tmp->c_flags & CALLOUT_DIRECT) {
450247777Sdavide#ifdef CALLOUT_PROFILING
451247777Sdavide					++depth_dir;
452247777Sdavide#endif
453247777Sdavide					cc->cc_exec_next_dir =
454247777Sdavide					    LIST_NEXT(tmp, c_links.le);
455247777Sdavide					cc->cc_bucket = firstb & callwheelmask;
456247777Sdavide					LIST_REMOVE(tmp, c_links.le);
457247777Sdavide					softclock_call_cc(tmp, cc,
458247777Sdavide#ifdef CALLOUT_PROFILING
459247777Sdavide					    &mpcalls_dir, &lockcalls_dir, NULL,
460247777Sdavide#endif
461247777Sdavide					    1);
462247777Sdavide					tmp = cc->cc_exec_next_dir;
463247777Sdavide				} else {
464247777Sdavide					tmpn = LIST_NEXT(tmp, c_links.le);
465247777Sdavide					LIST_REMOVE(tmp, c_links.le);
466247777Sdavide					TAILQ_INSERT_TAIL(&cc->cc_expireq,
467247777Sdavide					    tmp, c_links.tqe);
468247777Sdavide					tmp->c_flags |= CALLOUT_PROCESSED;
469247777Sdavide					tmp = tmpn;
470247777Sdavide				}
471247777Sdavide				continue;
472247777Sdavide			}
473247777Sdavide			/* Skip events from distant future. */
474247777Sdavide			if (tmp->c_time >= max)
475247777Sdavide				goto next;
476247777Sdavide			/*
477247777Sdavide			 * Event minimal time is bigger than present maximal
478247777Sdavide			 * time, so it cannot be aggregated.
479247777Sdavide			 */
480247777Sdavide			if (tmp->c_time > last) {
481247777Sdavide				lastb = nowb;
482247777Sdavide				goto next;
483247777Sdavide			}
484247777Sdavide			/* Update first and last time, respecting this event. */
485247777Sdavide			if (tmp->c_time < first)
486247777Sdavide				first = tmp->c_time;
487247777Sdavide			tmp_max = tmp->c_time + tmp->c_precision;
488247777Sdavide			if (tmp_max < last)
489247777Sdavide				last = tmp_max;
490247777Sdavidenext:
491247777Sdavide			tmp = LIST_NEXT(tmp, c_links.le);
492180608Sjeff		}
493247777Sdavide		/* Proceed with the next bucket. */
494247777Sdavide		firstb++;
495247777Sdavide		/*
496247777Sdavide		 * Stop if we looked after present time and found
497247777Sdavide		 * some event we can't execute at now.
498247777Sdavide		 * Stop if we looked far enough into the future.
499247777Sdavide		 */
500247777Sdavide	} while (((int)(firstb - lastb)) <= 0);
501247777Sdavide	cc->cc_firstevent = last;
502247777Sdavide#ifndef NO_EVENTTIMERS
503247777Sdavide	cpu_new_callout(curcpu, last, first);
504247777Sdavide#endif
505247777Sdavide#ifdef CALLOUT_PROFILING
506247777Sdavide	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
507247777Sdavide	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
508247777Sdavide	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
509247777Sdavide#endif
510177859Sjeff	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
511177859Sjeff	/*
512177859Sjeff	 * swi_sched acquires the thread lock, so we don't want to call it
513177859Sjeff	 * with cc_lock held; incorrect locking order.
514177859Sjeff	 */
515247777Sdavide	if (!TAILQ_EMPTY(&cc->cc_expireq))
516177859Sjeff		swi_sched(cc->cc_cookie, 0);
517177859Sjeff}
518177859Sjeff
519177859Sjeffstatic struct callout_cpu *
520177859Sjeffcallout_lock(struct callout *c)
521177859Sjeff{
522177859Sjeff	struct callout_cpu *cc;
523177859Sjeff	int cpu;
524177859Sjeff
525177859Sjeff	for (;;) {
526177859Sjeff		cpu = c->c_cpu;
527220456Sattilio#ifdef SMP
528220456Sattilio		if (cpu == CPUBLOCK) {
529220456Sattilio			while (c->c_cpu == CPUBLOCK)
530220456Sattilio				cpu_spinwait();
531220456Sattilio			continue;
532220456Sattilio		}
533220456Sattilio#endif
534177859Sjeff		cc = CC_CPU(cpu);
535177859Sjeff		CC_LOCK(cc);
536177859Sjeff		if (cpu == c->c_cpu)
537177859Sjeff			break;
538177859Sjeff		CC_UNLOCK(cc);
53982127Sdillon	}
540177859Sjeff	return (cc);
54182127Sdillon}
54282127Sdillon
543220456Sattiliostatic void
544247777Sdavidecallout_cc_add(struct callout *c, struct callout_cpu *cc,
545247777Sdavide    sbintime_t sbt, sbintime_t precision, void (*func)(void *),
546247777Sdavide    void *arg, int cpu, int flags)
547220456Sattilio{
548247777Sdavide	int bucket;
549220456Sattilio
550220456Sattilio	CC_LOCK_ASSERT(cc);
551247777Sdavide	if (sbt < cc->cc_lastscan)
552247777Sdavide		sbt = cc->cc_lastscan;
553220456Sattilio	c->c_arg = arg;
554220456Sattilio	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
555247777Sdavide	if (flags & C_DIRECT_EXEC)
556247777Sdavide		c->c_flags |= CALLOUT_DIRECT;
557247777Sdavide	c->c_flags &= ~CALLOUT_PROCESSED;
558220456Sattilio	c->c_func = func;
559247777Sdavide	c->c_time = sbt;
560247777Sdavide	c->c_precision = precision;
561247777Sdavide	bucket = callout_get_bucket(c->c_time);
562247777Sdavide	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
563247777Sdavide	    c, (int)(c->c_precision >> 32),
564247777Sdavide	    (u_int)(c->c_precision & 0xffffffff));
565247777Sdavide	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
566247777Sdavide	if (cc->cc_bucket == bucket)
567247777Sdavide		cc->cc_exec_next_dir = c;
568247777Sdavide#ifndef NO_EVENTTIMERS
569247777Sdavide	/*
570247777Sdavide	 * Inform the eventtimers(4) subsystem there's a new callout
571247777Sdavide	 * that has been inserted, but only if really required.
572247777Sdavide	 */
573247777Sdavide	sbt = c->c_time + c->c_precision;
574247777Sdavide	if (sbt < cc->cc_firstevent) {
575247777Sdavide		cc->cc_firstevent = sbt;
576247777Sdavide		cpu_new_callout(cpu, sbt, c->c_time);
577220456Sattilio	}
578247777Sdavide#endif
579220456Sattilio}
580220456Sattilio
581234981Skibstatic void
582234981Skibcallout_cc_del(struct callout *c, struct callout_cpu *cc)
583234981Skib{
584234981Skib
585243901Skib	if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
586243901Skib		return;
587243901Skib	c->c_func = NULL;
588243901Skib	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
589234981Skib}
590234981Skib
591243901Skibstatic void
592247777Sdavidesoftclock_call_cc(struct callout *c, struct callout_cpu *cc,
593247777Sdavide#ifdef CALLOUT_PROFILING
594247777Sdavide    int *mpcalls, int *lockcalls, int *gcalls,
595247777Sdavide#endif
596247777Sdavide    int direct)
597234981Skib{
598234981Skib	void (*c_func)(void *);
599234981Skib	void *c_arg;
600234981Skib	struct lock_class *class;
601234981Skib	struct lock_object *c_lock;
602234981Skib	int c_flags, sharedlock;
603234981Skib#ifdef SMP
604234981Skib	struct callout_cpu *new_cc;
605234981Skib	void (*new_func)(void *);
606234981Skib	void *new_arg;
607247777Sdavide	int flags, new_cpu;
608247777Sdavide	sbintime_t new_time;
609234981Skib#endif
610247777Sdavide#if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
611247793Sdavide	sbintime_t sbt1, sbt2;
612234981Skib	struct timespec ts2;
613247777Sdavide	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
614234981Skib	static timeout_t *lastfunc;
615234981Skib#endif
616234981Skib
617243901Skib	KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
618243901Skib	    (CALLOUT_PENDING | CALLOUT_ACTIVE),
619243901Skib	    ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
620234981Skib	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
621234981Skib	sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ? 0 : 1;
622234981Skib	c_lock = c->c_lock;
623234981Skib	c_func = c->c_func;
624234981Skib	c_arg = c->c_arg;
625234981Skib	c_flags = c->c_flags;
626234981Skib	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
627234981Skib		c->c_flags = CALLOUT_LOCAL_ALLOC;
628234981Skib	else
629234981Skib		c->c_flags &= ~CALLOUT_PENDING;
630247777Sdavide	cc->cc_exec_entity[direct].cc_curr = c;
631247818Sdavide	cc->cc_exec_entity[direct].cc_cancel = false;
632234981Skib	CC_UNLOCK(cc);
633234981Skib	if (c_lock != NULL) {
634234981Skib		class->lc_lock(c_lock, sharedlock);
635234981Skib		/*
636234981Skib		 * The callout may have been cancelled
637234981Skib		 * while we switched locks.
638234981Skib		 */
639247777Sdavide		if (cc->cc_exec_entity[direct].cc_cancel) {
640234981Skib			class->lc_unlock(c_lock);
641234981Skib			goto skip;
642234981Skib		}
643234981Skib		/* The callout cannot be stopped now. */
644247818Sdavide		cc->cc_exec_entity[direct].cc_cancel = true;
645234981Skib		if (c_lock == &Giant.lock_object) {
646247777Sdavide#ifdef CALLOUT_PROFILING
647234981Skib			(*gcalls)++;
648247777Sdavide#endif
649247777Sdavide			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
650234981Skib			    c, c_func, c_arg);
651234981Skib		} else {
652247777Sdavide#ifdef CALLOUT_PROFILING
653234981Skib			(*lockcalls)++;
654247777Sdavide#endif
655234981Skib			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
656234981Skib			    c, c_func, c_arg);
657234981Skib		}
658234981Skib	} else {
659247777Sdavide#ifdef CALLOUT_PROFILING
660234981Skib		(*mpcalls)++;
661247777Sdavide#endif
662247777Sdavide		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
663234981Skib		    c, c_func, c_arg);
664234981Skib	}
665247793Sdavide#if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
666247777Sdavide	sbt1 = sbinuptime();
667234981Skib#endif
668234981Skib	THREAD_NO_SLEEPING();
669234981Skib	SDT_PROBE(callout_execute, kernel, , callout_start, c, 0, 0, 0, 0);
670234981Skib	c_func(c_arg);
671234981Skib	SDT_PROBE(callout_execute, kernel, , callout_end, c, 0, 0, 0, 0);
672234981Skib	THREAD_SLEEPING_OK();
673247793Sdavide#if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
674247793Sdavide	sbt2 = sbinuptime();
675247793Sdavide	sbt2 -= sbt1;
676247793Sdavide	if (sbt2 > maxdt) {
677247793Sdavide		if (lastfunc != c_func || sbt2 > maxdt * 2) {
678247793Sdavide			ts2 = sbttots(sbt2);
679234981Skib			printf(
680234981Skib		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
681234981Skib			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
682234981Skib		}
683247793Sdavide		maxdt = sbt2;
684234981Skib		lastfunc = c_func;
685234981Skib	}
686234981Skib#endif
687234981Skib	CTR1(KTR_CALLOUT, "callout %p finished", c);
688234981Skib	if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
689234981Skib		class->lc_unlock(c_lock);
690234981Skibskip:
691234981Skib	CC_LOCK(cc);
692247777Sdavide	KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
693247777Sdavide	cc->cc_exec_entity[direct].cc_curr = NULL;
694247777Sdavide	if (cc->cc_exec_entity[direct].cc_waiting) {
695234981Skib		/*
696234981Skib		 * There is someone waiting for the
697234981Skib		 * callout to complete.
698234981Skib		 * If the callout was scheduled for
699234981Skib		 * migration just cancel it.
700234981Skib		 */
701247777Sdavide		if (cc_cce_migrating(cc, direct)) {
702247777Sdavide			cc_cce_cleanup(cc, direct);
703243912Sattilio
704243912Sattilio			/*
705243912Sattilio			 * It should be assert here that the callout is not
706243912Sattilio			 * destroyed but that is not easy.
707243912Sattilio			 */
708243901Skib			c->c_flags &= ~CALLOUT_DFRMIGRATION;
709243901Skib		}
710247818Sdavide		cc->cc_exec_entity[direct].cc_waiting = false;
711234981Skib		CC_UNLOCK(cc);
712247777Sdavide		wakeup(&cc->cc_exec_entity[direct].cc_waiting);
713234981Skib		CC_LOCK(cc);
714247777Sdavide	} else if (cc_cce_migrating(cc, direct)) {
715243912Sattilio		KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
716243901Skib		    ("Migrating legacy callout %p", c));
717234981Skib#ifdef SMP
718234981Skib		/*
719234981Skib		 * If the callout was scheduled for
720234981Skib		 * migration just perform it now.
721234981Skib		 */
722247777Sdavide		new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
723247777Sdavide		new_time = cc->cc_exec_entity[direct].ce_migration_time;
724247777Sdavide		new_func = cc->cc_exec_entity[direct].ce_migration_func;
725247777Sdavide		new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
726247777Sdavide		cc_cce_cleanup(cc, direct);
727234981Skib
728234981Skib		/*
729243912Sattilio		 * It should be assert here that the callout is not destroyed
730243912Sattilio		 * but that is not easy.
731243912Sattilio		 *
732243912Sattilio		 * As first thing, handle deferred callout stops.
733234981Skib		 */
734234981Skib		if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
735234981Skib			CTR3(KTR_CALLOUT,
736234981Skib			     "deferred cancelled %p func %p arg %p",
737234981Skib			     c, new_func, new_arg);
738234981Skib			callout_cc_del(c, cc);
739243901Skib			return;
740234981Skib		}
741234981Skib		c->c_flags &= ~CALLOUT_DFRMIGRATION;
742234981Skib
743234981Skib		new_cc = callout_cpu_switch(c, cc, new_cpu);
744247777Sdavide		flags = (direct) ? C_DIRECT_EXEC : 0;
745247777Sdavide		callout_cc_add(c, new_cc, new_time, c->c_precision, new_func,
746247777Sdavide		    new_arg, new_cpu, flags);
747234981Skib		CC_UNLOCK(new_cc);
748234981Skib		CC_LOCK(cc);
749234981Skib#else
750234981Skib		panic("migration should not happen");
751234981Skib#endif
752234981Skib	}
753243901Skib	/*
754243901Skib	 * If the current callout is locally allocated (from
755243901Skib	 * timeout(9)) then put it on the freelist.
756243901Skib	 *
757243901Skib	 * Note: we need to check the cached copy of c_flags because
758243901Skib	 * if it was not local, then it's not safe to deref the
759243901Skib	 * callout pointer.
760243901Skib	 */
761243901Skib	KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
762243901Skib	    c->c_flags == CALLOUT_LOCAL_ALLOC,
763243901Skib	    ("corrupted callout"));
764243912Sattilio	if (c_flags & CALLOUT_LOCAL_ALLOC)
765243912Sattilio		callout_cc_del(c, cc);
766234981Skib}
767234981Skib
76882127Sdillon/*
769247467Sdavide * The callout mechanism is based on the work of Adam M. Costello and
77029680Sgibbs * George Varghese, published in a technical report entitled "Redesigning
77129680Sgibbs * the BSD Callout and Timer Facilities" and modified slightly for inclusion
77229680Sgibbs * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
773128630Shmp * used in this implementation was published by G. Varghese and T. Lauck in
77429680Sgibbs * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
77529680Sgibbs * the Efficient Implementation of a Timer Facility" in the Proceedings of
77629680Sgibbs * the 11th ACM Annual Symposium on Operating Systems Principles,
77729680Sgibbs * Austin, Texas Nov 1987.
77829680Sgibbs */
77932388Sphk
78029680Sgibbs/*
7811541Srgrimes * Software (low priority) clock interrupt.
7821541Srgrimes * Run periodic events from timeout queue.
7831541Srgrimes */
7841541Srgrimesvoid
785177859Sjeffsoftclock(void *arg)
7861541Srgrimes{
787177859Sjeff	struct callout_cpu *cc;
788102936Sphk	struct callout *c;
789247777Sdavide#ifdef CALLOUT_PROFILING
790247777Sdavide	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
791247777Sdavide#endif
7921541Srgrimes
793177859Sjeff	cc = (struct callout_cpu *)arg;
794177859Sjeff	CC_LOCK(cc);
795247777Sdavide	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
796247777Sdavide		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
797247777Sdavide		softclock_call_cc(c, cc,
798247777Sdavide#ifdef CALLOUT_PROFILING
799247777Sdavide		    &mpcalls, &lockcalls, &gcalls,
800247777Sdavide#endif
801247777Sdavide		    0);
802247777Sdavide#ifdef CALLOUT_PROFILING
803247777Sdavide		++depth;
804247777Sdavide#endif
8051541Srgrimes	}
806247777Sdavide#ifdef CALLOUT_PROFILING
807115810Sphk	avg_depth += (depth * 1000 - avg_depth) >> 8;
808115810Sphk	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
809173760Sattilio	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
810115810Sphk	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
811247777Sdavide#endif
812177859Sjeff	CC_UNLOCK(cc);
8131541Srgrimes}
8141541Srgrimes
8151541Srgrimes/*
8161541Srgrimes * timeout --
8171541Srgrimes *	Execute a function after a specified length of time.
8181541Srgrimes *
8191541Srgrimes * untimeout --
8201541Srgrimes *	Cancel previous timeout function call.
8211541Srgrimes *
82229680Sgibbs * callout_handle_init --
82329680Sgibbs *	Initialize a handle so that using it with untimeout is benign.
82429680Sgibbs *
8251541Srgrimes *	See AT&T BCI Driver Reference Manual for specification.  This
826247698Smav *	implementation differs from that one in that although an
82729680Sgibbs *	identification value is returned from timeout, the original
82829680Sgibbs *	arguments to timeout as well as the identifier are used to
82929680Sgibbs *	identify entries for untimeout.
8301541Srgrimes */
83129680Sgibbsstruct callout_handle
83229680Sgibbstimeout(ftn, arg, to_ticks)
83333824Sbde	timeout_t *ftn;
8341541Srgrimes	void *arg;
83569147Sjlemon	int to_ticks;
8361541Srgrimes{
837177859Sjeff	struct callout_cpu *cc;
83829680Sgibbs	struct callout *new;
83929680Sgibbs	struct callout_handle handle;
8401541Srgrimes
841177859Sjeff	cc = CC_CPU(timeout_cpu);
842177859Sjeff	CC_LOCK(cc);
8431541Srgrimes	/* Fill in the next free callout structure. */
844177859Sjeff	new = SLIST_FIRST(&cc->cc_callfree);
84529680Sgibbs	if (new == NULL)
84629680Sgibbs		/* XXX Attempt to malloc first */
8471541Srgrimes		panic("timeout table full");
848177859Sjeff	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
84944510Swollman	callout_reset(new, to_ticks, ftn, arg);
850177859Sjeff	handle.callout = new;
851177859Sjeff	CC_UNLOCK(cc);
8521541Srgrimes
85329680Sgibbs	return (handle);
8541541Srgrimes}
8551541Srgrimes
8561541Srgrimesvoid
85729680Sgibbsuntimeout(ftn, arg, handle)
85833824Sbde	timeout_t *ftn;
8591541Srgrimes	void *arg;
86029680Sgibbs	struct callout_handle handle;
8611541Srgrimes{
862177859Sjeff	struct callout_cpu *cc;
8631541Srgrimes
86429680Sgibbs	/*
86529680Sgibbs	 * Check for a handle that was initialized
86629680Sgibbs	 * by callout_handle_init, but never used
86729680Sgibbs	 * for a real timeout.
86829680Sgibbs	 */
86929680Sgibbs	if (handle.callout == NULL)
87029680Sgibbs		return;
87129680Sgibbs
872177859Sjeff	cc = callout_lock(handle.callout);
87344510Swollman	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
87444510Swollman		callout_stop(handle.callout);
875177859Sjeff	CC_UNLOCK(cc);
8761541Srgrimes}
8771541Srgrimes
87824101Sbdevoid
87929680Sgibbscallout_handle_init(struct callout_handle *handle)
88029680Sgibbs{
88129680Sgibbs	handle->callout = NULL;
88229680Sgibbs}
88329680Sgibbs
88444510Swollman/*
88544510Swollman * New interface; clients allocate their own callout structures.
88644510Swollman *
88744510Swollman * callout_reset() - establish or change a timeout
88844510Swollman * callout_stop() - disestablish a timeout
88944510Swollman * callout_init() - initialize a callout structure so that it can
89044510Swollman *	safely be passed to callout_reset() and callout_stop()
89144510Swollman *
89250673Sjlemon * <sys/callout.h> defines three convenience macros:
89344510Swollman *
894140487Scperciva * callout_active() - returns truth if callout has not been stopped,
895140487Scperciva *	drained, or deactivated since the last time the callout was
896140487Scperciva *	reset.
89750673Sjlemon * callout_pending() - returns truth if callout is still waiting for timeout
89850673Sjlemon * callout_deactivate() - marks the callout as having been serviced
89944510Swollman */
900149879Sglebiusint
901247777Sdavidecallout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
902247777Sdavide    void (*ftn)(void *), void *arg, int cpu, int flags)
90344510Swollman{
904247777Sdavide	sbintime_t to_sbt, pr;
905177859Sjeff	struct callout_cpu *cc;
906247777Sdavide	int cancelled, direct;
90744510Swollman
908247777Sdavide	cancelled = 0;
909247777Sdavide	if (flags & C_ABSOLUTE) {
910247777Sdavide		to_sbt = sbt;
911247777Sdavide	} else {
912247777Sdavide		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
913247777Sdavide			sbt = tick_sbt;
914247777Sdavide		if ((flags & C_HARDCLOCK) ||
915247777Sdavide#ifdef NO_EVENTTIMERS
916247777Sdavide		    sbt >= sbt_timethreshold) {
917247777Sdavide			to_sbt = getsbinuptime();
918247777Sdavide
919247777Sdavide			/* Add safety belt for the case of hz > 1000. */
920247777Sdavide			to_sbt += tc_tick_sbt - tick_sbt;
921247777Sdavide#else
922247777Sdavide		    sbt >= sbt_tickthreshold) {
923247777Sdavide			/*
924247777Sdavide			 * Obtain the time of the last hardclock() call on
925247777Sdavide			 * this CPU directly from the kern_clocksource.c.
926247777Sdavide			 * This value is per-CPU, but it is equal for all
927247777Sdavide			 * active ones.
928247777Sdavide			 */
929247777Sdavide#ifdef __LP64__
930247777Sdavide			to_sbt = DPCPU_GET(hardclocktime);
931247777Sdavide#else
932247777Sdavide			spinlock_enter();
933247777Sdavide			to_sbt = DPCPU_GET(hardclocktime);
934247777Sdavide			spinlock_exit();
935247777Sdavide#endif
936247777Sdavide#endif
937247777Sdavide			if ((flags & C_HARDCLOCK) == 0)
938247777Sdavide				to_sbt += tick_sbt;
939247777Sdavide		} else
940247777Sdavide			to_sbt = sbinuptime();
941247777Sdavide		to_sbt += sbt;
942247777Sdavide		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
943247777Sdavide		    sbt >> C_PRELGET(flags));
944247777Sdavide		if (pr > precision)
945247777Sdavide			precision = pr;
946247777Sdavide	}
947177859Sjeff	/*
948177859Sjeff	 * Don't allow migration of pre-allocated callouts lest they
949177859Sjeff	 * become unbalanced.
950177859Sjeff	 */
951177859Sjeff	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
952177859Sjeff		cpu = c->c_cpu;
953247777Sdavide	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
954247777Sdavide	KASSERT(!direct || c->c_lock == NULL,
955247777Sdavide	    ("%s: direct callout %p has lock", __func__, c));
956177859Sjeff	cc = callout_lock(c);
957247777Sdavide	if (cc->cc_exec_entity[direct].cc_curr == c) {
958127969Scperciva		/*
959127969Scperciva		 * We're being asked to reschedule a callout which is
960173760Sattilio		 * currently in progress.  If there is a lock then we
961141428Siedowse		 * can cancel the callout if it has not really started.
962127969Scperciva		 */
963247777Sdavide		if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
964247818Sdavide			cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
965247777Sdavide		if (cc->cc_exec_entity[direct].cc_waiting) {
966141428Siedowse			/*
967141428Siedowse			 * Someone has called callout_drain to kill this
968141428Siedowse			 * callout.  Don't reschedule.
969141428Siedowse			 */
970163246Sglebius			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
971163246Sglebius			    cancelled ? "cancelled" : "failed to cancel",
972163246Sglebius			    c, c->c_func, c->c_arg);
973177859Sjeff			CC_UNLOCK(cc);
974149879Sglebius			return (cancelled);
975141428Siedowse		}
976128024Scperciva	}
977133190Scperciva	if (c->c_flags & CALLOUT_PENDING) {
978247777Sdavide		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
979247777Sdavide			if (cc->cc_exec_next_dir == c)
980247777Sdavide				cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
981247777Sdavide			LIST_REMOVE(c, c_links.le);
982247777Sdavide		} else
983247777Sdavide			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
984149879Sglebius		cancelled = 1;
985177859Sjeff		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
986133190Scperciva	}
987220456Sattilio
988220456Sattilio#ifdef SMP
98944510Swollman	/*
990220456Sattilio	 * If the callout must migrate try to perform it immediately.
991220456Sattilio	 * If the callout is currently running, just defer the migration
992220456Sattilio	 * to a more appropriate moment.
99344510Swollman	 */
994177859Sjeff	if (c->c_cpu != cpu) {
995247777Sdavide		if (cc->cc_exec_entity[direct].cc_curr == c) {
996247777Sdavide			cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
997247777Sdavide			cc->cc_exec_entity[direct].ce_migration_time
998247777Sdavide			    = to_sbt;
999247777Sdavide			cc->cc_exec_entity[direct].ce_migration_func = ftn;
1000247777Sdavide			cc->cc_exec_entity[direct].ce_migration_arg = arg;
1001234952Skib			c->c_flags |= CALLOUT_DFRMIGRATION;
1002247777Sdavide			CTR6(KTR_CALLOUT,
1003247777Sdavide		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1004247777Sdavide			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1005247777Sdavide			    (u_int)(to_sbt & 0xffffffff), cpu);
1006220456Sattilio			CC_UNLOCK(cc);
1007220456Sattilio			return (cancelled);
1008220456Sattilio		}
1009220456Sattilio		cc = callout_cpu_switch(c, cc, cpu);
1010177859Sjeff	}
1011220456Sattilio#endif
1012177859Sjeff
1013247777Sdavide	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1014247777Sdavide	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1015247777Sdavide	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1016247777Sdavide	    (u_int)(to_sbt & 0xffffffff));
1017177859Sjeff	CC_UNLOCK(cc);
1018149879Sglebius
1019149879Sglebius	return (cancelled);
102044510Swollman}
102144510Swollman
1022181191Ssam/*
1023181191Ssam * Common idioms that can be optimized in the future.
1024181191Ssam */
102581481Sjhbint
1026181191Ssamcallout_schedule_on(struct callout *c, int to_ticks, int cpu)
1027181191Ssam{
1028181191Ssam	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1029181191Ssam}
1030181191Ssam
1031181191Ssamint
1032181191Ssamcallout_schedule(struct callout *c, int to_ticks)
1033181191Ssam{
1034181191Ssam	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1035181191Ssam}
1036181191Ssam
1037181191Ssamint
1038127969Scperciva_callout_stop_safe(c, safe)
1039127969Scperciva	struct	callout *c;
1040127969Scperciva	int	safe;
1041127969Scperciva{
1042220456Sattilio	struct callout_cpu *cc, *old_cc;
1043173760Sattilio	struct lock_class *class;
1044247777Sdavide	int direct, sq_locked, use_lock;
1045127969Scperciva
1046173760Sattilio	/*
1047173760Sattilio	 * Some old subsystems don't hold Giant while running a callout_stop(),
1048173760Sattilio	 * so just discard this check for the moment.
1049173760Sattilio	 */
1050173760Sattilio	if (!safe && c->c_lock != NULL) {
1051173760Sattilio		if (c->c_lock == &Giant.lock_object)
1052173760Sattilio			use_lock = mtx_owned(&Giant);
1053173760Sattilio		else {
1054173760Sattilio			use_lock = 1;
1055173760Sattilio			class = LOCK_CLASS(c->c_lock);
1056173760Sattilio			class->lc_assert(c->c_lock, LA_XLOCKED);
1057173760Sattilio		}
1058173760Sattilio	} else
1059173760Sattilio		use_lock = 0;
1060247777Sdavide	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1061172025Sjhb	sq_locked = 0;
1062220456Sattilio	old_cc = NULL;
1063172025Sjhbagain:
1064177859Sjeff	cc = callout_lock(c);
1065220456Sattilio
106644510Swollman	/*
1067220456Sattilio	 * If the callout was migrating while the callout cpu lock was
1068220456Sattilio	 * dropped,  just drop the sleepqueue lock and check the states
1069220456Sattilio	 * again.
1070220456Sattilio	 */
1071220456Sattilio	if (sq_locked != 0 && cc != old_cc) {
1072220456Sattilio#ifdef SMP
1073220456Sattilio		CC_UNLOCK(cc);
1074247777Sdavide		sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
1075220456Sattilio		sq_locked = 0;
1076220456Sattilio		old_cc = NULL;
1077220456Sattilio		goto again;
1078220456Sattilio#else
1079220456Sattilio		panic("migration should not happen");
1080220456Sattilio#endif
1081220456Sattilio	}
1082220456Sattilio
1083220456Sattilio	/*
1084155957Sjhb	 * If the callout isn't pending, it's not on the queue, so
1085155957Sjhb	 * don't attempt to remove it from the queue.  We can try to
1086155957Sjhb	 * stop it by other means however.
108744510Swollman	 */
108844510Swollman	if (!(c->c_flags & CALLOUT_PENDING)) {
108950673Sjlemon		c->c_flags &= ~CALLOUT_ACTIVE;
1090155957Sjhb
1091155957Sjhb		/*
1092155957Sjhb		 * If it wasn't on the queue and it isn't the current
1093155957Sjhb		 * callout, then we can't stop it, so just bail.
1094155957Sjhb		 */
1095247777Sdavide		if (cc->cc_exec_entity[direct].cc_curr != c) {
1096163246Sglebius			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1097163246Sglebius			    c, c->c_func, c->c_arg);
1098177859Sjeff			CC_UNLOCK(cc);
1099172025Sjhb			if (sq_locked)
1100247777Sdavide				sleepq_release(
1101247777Sdavide				    &cc->cc_exec_entity[direct].cc_waiting);
1102141428Siedowse			return (0);
1103141428Siedowse		}
1104155957Sjhb
1105141428Siedowse		if (safe) {
1106127969Scperciva			/*
1107155957Sjhb			 * The current callout is running (or just
1108155957Sjhb			 * about to run) and blocking is allowed, so
1109155957Sjhb			 * just wait for the current invocation to
1110155957Sjhb			 * finish.
1111127969Scperciva			 */
1112247777Sdavide			while (cc->cc_exec_entity[direct].cc_curr == c) {
1113171053Sattilio				/*
1114171053Sattilio				 * Use direct calls to sleepqueue interface
1115171053Sattilio				 * instead of cv/msleep in order to avoid
1116177859Sjeff				 * a LOR between cc_lock and sleepqueue
1117171053Sattilio				 * chain spinlocks.  This piece of code
1118171053Sattilio				 * emulates a msleep_spin() call actually.
1119172025Sjhb				 *
1120172025Sjhb				 * If we already have the sleepqueue chain
1121172025Sjhb				 * locked, then we can safely block.  If we
1122172025Sjhb				 * don't already have it locked, however,
1123177859Sjeff				 * we have to drop the cc_lock to lock
1124172025Sjhb				 * it.  This opens several races, so we
1125172025Sjhb				 * restart at the beginning once we have
1126172025Sjhb				 * both locks.  If nothing has changed, then
1127172025Sjhb				 * we will end up back here with sq_locked
1128172025Sjhb				 * set.
1129171053Sattilio				 */
1130172025Sjhb				if (!sq_locked) {
1131177859Sjeff					CC_UNLOCK(cc);
1132247777Sdavide					sleepq_lock(
1133247777Sdavide					&cc->cc_exec_entity[direct].cc_waiting);
1134172025Sjhb					sq_locked = 1;
1135220456Sattilio					old_cc = cc;
1136172025Sjhb					goto again;
1137172025Sjhb				}
1138220456Sattilio
1139220456Sattilio				/*
1140220456Sattilio				 * Migration could be cancelled here, but
1141220456Sattilio				 * as long as it is still not sure when it
1142220456Sattilio				 * will be packed up, just let softclock()
1143220456Sattilio				 * take care of it.
1144220456Sattilio				 */
1145247818Sdavide				cc->cc_exec_entity[direct].cc_waiting = true;
1146171053Sattilio				DROP_GIANT();
1147177859Sjeff				CC_UNLOCK(cc);
1148247777Sdavide				sleepq_add(
1149247777Sdavide				    &cc->cc_exec_entity[direct].cc_waiting,
1150177859Sjeff				    &cc->cc_lock.lock_object, "codrain",
1151171053Sattilio				    SLEEPQ_SLEEP, 0);
1152247777Sdavide				sleepq_wait(
1153247777Sdavide				    &cc->cc_exec_entity[direct].cc_waiting,
1154247777Sdavide					     0);
1155172025Sjhb				sq_locked = 0;
1156220456Sattilio				old_cc = NULL;
1157171053Sattilio
1158171053Sattilio				/* Reacquire locks previously released. */
1159171053Sattilio				PICKUP_GIANT();
1160177859Sjeff				CC_LOCK(cc);
1161155957Sjhb			}
1162247777Sdavide		} else if (use_lock &&
1163247777Sdavide			    !cc->cc_exec_entity[direct].cc_cancel) {
1164155957Sjhb			/*
1165173760Sattilio			 * The current callout is waiting for its
1166173760Sattilio			 * lock which we hold.  Cancel the callout
1167155957Sjhb			 * and return.  After our caller drops the
1168173760Sattilio			 * lock, the callout will be skipped in
1169155957Sjhb			 * softclock().
1170155957Sjhb			 */
1171247818Sdavide			cc->cc_exec_entity[direct].cc_cancel = true;
1172163246Sglebius			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1173163246Sglebius			    c, c->c_func, c->c_arg);
1174247777Sdavide			KASSERT(!cc_cce_migrating(cc, direct),
1175220456Sattilio			    ("callout wrongly scheduled for migration"));
1176177859Sjeff			CC_UNLOCK(cc);
1177172025Sjhb			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1178141428Siedowse			return (1);
1179234952Skib		} else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
1180234952Skib			c->c_flags &= ~CALLOUT_DFRMIGRATION;
1181234952Skib			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1182234952Skib			    c, c->c_func, c->c_arg);
1183234952Skib			CC_UNLOCK(cc);
1184234952Skib			return (1);
1185155957Sjhb		}
1186163246Sglebius		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1187163246Sglebius		    c, c->c_func, c->c_arg);
1188177859Sjeff		CC_UNLOCK(cc);
1189172025Sjhb		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
119081481Sjhb		return (0);
119144510Swollman	}
1192172025Sjhb	if (sq_locked)
1193247777Sdavide		sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
1194172025Sjhb
119550673Sjlemon	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
119644510Swollman
1197234981Skib	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1198234981Skib	    c, c->c_func, c->c_arg);
1199247777Sdavide	if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1200247777Sdavide		if (cc->cc_exec_next_dir == c)
1201247777Sdavide			cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1202247777Sdavide		LIST_REMOVE(c, c_links.le);
1203247777Sdavide	} else
1204247777Sdavide		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1205234981Skib	callout_cc_del(c, cc);
120644510Swollman
1207177859Sjeff	CC_UNLOCK(cc);
120881481Sjhb	return (1);
120944510Swollman}
121044510Swollman
121144510Swollmanvoid
121269147Sjlemoncallout_init(c, mpsafe)
121344510Swollman	struct	callout *c;
121469147Sjlemon	int mpsafe;
121544510Swollman{
121644527Swollman	bzero(c, sizeof *c);
1217141428Siedowse	if (mpsafe) {
1218173760Sattilio		c->c_lock = NULL;
1219141428Siedowse		c->c_flags = CALLOUT_RETURNUNLOCKED;
1220141428Siedowse	} else {
1221173760Sattilio		c->c_lock = &Giant.lock_object;
1222141428Siedowse		c->c_flags = 0;
1223141428Siedowse	}
1224177859Sjeff	c->c_cpu = timeout_cpu;
122544510Swollman}
122644510Swollman
1227141428Siedowsevoid
1228173760Sattilio_callout_init_lock(c, lock, flags)
1229141428Siedowse	struct	callout *c;
1230173760Sattilio	struct	lock_object *lock;
1231141428Siedowse	int flags;
1232141428Siedowse{
1233141428Siedowse	bzero(c, sizeof *c);
1234173760Sattilio	c->c_lock = lock;
1235173760Sattilio	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1236173760Sattilio	    ("callout_init_lock: bad flags %d", flags));
1237173760Sattilio	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1238173760Sattilio	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1239176013Sattilio	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1240176013Sattilio	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1241173760Sattilio	    __func__));
1242173760Sattilio	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1243177859Sjeff	c->c_cpu = timeout_cpu;
1244141428Siedowse}
1245141428Siedowse
124631950Snate#ifdef APM_FIXUP_CALLTODO
124731950Snate/*
124831950Snate * Adjust the kernel calltodo timeout list.  This routine is used after
124931950Snate * an APM resume to recalculate the calltodo timer list values with the
125031950Snate * number of hz's we have been sleeping.  The next hardclock() will detect
125131950Snate * that there are fired timers and run softclock() to execute them.
125231950Snate *
125331950Snate * Please note, I have not done an exhaustive analysis of what code this
125431950Snate * might break.  I am motivated to have my select()'s and alarm()'s that
125531950Snate * have expired during suspend firing upon resume so that the applications
125631950Snate * which set the timer can do the maintanence the timer was for as close
125731950Snate * as possible to the originally intended time.  Testing this code for a
125831950Snate * week showed that resuming from a suspend resulted in 22 to 25 timers
125931950Snate * firing, which seemed independant on whether the suspend was 2 hours or
126031950Snate * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
126131950Snate */
126231950Snatevoid
126331950Snateadjust_timeout_calltodo(time_change)
126431950Snate    struct timeval *time_change;
126531950Snate{
126631950Snate	register struct callout *p;
126731950Snate	unsigned long delta_ticks;
126831950Snate
126931950Snate	/*
127031950Snate	 * How many ticks were we asleep?
127136127Sbde	 * (stolen from tvtohz()).
127231950Snate	 */
127331950Snate
127431950Snate	/* Don't do anything */
127531950Snate	if (time_change->tv_sec < 0)
127631950Snate		return;
127731950Snate	else if (time_change->tv_sec <= LONG_MAX / 1000000)
127831950Snate		delta_ticks = (time_change->tv_sec * 1000000 +
127931950Snate			       time_change->tv_usec + (tick - 1)) / tick + 1;
128031950Snate	else if (time_change->tv_sec <= LONG_MAX / hz)
128131950Snate		delta_ticks = time_change->tv_sec * hz +
128231950Snate			      (time_change->tv_usec + (tick - 1)) / tick + 1;
128331950Snate	else
128431950Snate		delta_ticks = LONG_MAX;
128531950Snate
128631950Snate	if (delta_ticks > INT_MAX)
128731950Snate		delta_ticks = INT_MAX;
128831950Snate
128931950Snate	/*
129031950Snate	 * Now rip through the timer calltodo list looking for timers
129131950Snate	 * to expire.
129231950Snate	 */
129331950Snate
129431950Snate	/* don't collide with softclock() */
1295177859Sjeff	CC_LOCK(cc);
129631950Snate	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
129731950Snate		p->c_time -= delta_ticks;
129831950Snate
129931950Snate		/* Break if the timer had more time on it than delta_ticks */
130031950Snate		if (p->c_time > 0)
130131950Snate			break;
130231950Snate
130331950Snate		/* take back the ticks the timer didn't use (p->c_time <= 0) */
130431950Snate		delta_ticks = -p->c_time;
130531950Snate	}
1306177859Sjeff	CC_UNLOCK(cc);
130731950Snate
130831950Snate	return;
130931950Snate}
131031950Snate#endif /* APM_FIXUP_CALLTODO */
1311247777Sdavide
1312247777Sdavidestatic int
1313247777Sdavideflssbt(sbintime_t sbt)
1314247777Sdavide{
1315247777Sdavide
1316247777Sdavide	sbt += (uint64_t)sbt >> 1;
1317247777Sdavide	if (sizeof(long) >= sizeof(sbintime_t))
1318247777Sdavide		return (flsl(sbt));
1319247777Sdavide	if (sbt >= SBT_1S)
1320247777Sdavide		return (flsl(((uint64_t)sbt) >> 32) + 32);
1321247777Sdavide	return (flsl(sbt));
1322247777Sdavide}
1323247777Sdavide
1324247777Sdavide/*
1325247777Sdavide * Dump immediate statistic snapshot of the scheduled callouts.
1326247777Sdavide */
1327247777Sdavidestatic int
1328247777Sdavidesysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1329247777Sdavide{
1330247777Sdavide	struct callout *tmp;
1331247777Sdavide	struct callout_cpu *cc;
1332247777Sdavide	struct callout_list *sc;
1333247777Sdavide	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1334247777Sdavide	int ct[64], cpr[64], ccpbk[32];
1335247777Sdavide	int error, val, i, count, tcum, pcum, maxc, c, medc;
1336247777Sdavide#ifdef SMP
1337247777Sdavide	int cpu;
1338247777Sdavide#endif
1339247777Sdavide
1340247777Sdavide	val = 0;
1341247777Sdavide	error = sysctl_handle_int(oidp, &val, 0, req);
1342247777Sdavide	if (error != 0 || req->newptr == NULL)
1343247777Sdavide		return (error);
1344247777Sdavide	count = maxc = 0;
1345247777Sdavide	st = spr = maxt = maxpr = 0;
1346247777Sdavide	bzero(ccpbk, sizeof(ccpbk));
1347247777Sdavide	bzero(ct, sizeof(ct));
1348247777Sdavide	bzero(cpr, sizeof(cpr));
1349247777Sdavide	now = sbinuptime();
1350247777Sdavide#ifdef SMP
1351247777Sdavide	CPU_FOREACH(cpu) {
1352247777Sdavide		cc = CC_CPU(cpu);
1353247777Sdavide#else
1354247777Sdavide		cc = CC_CPU(timeout_cpu);
1355247777Sdavide#endif
1356247777Sdavide		CC_LOCK(cc);
1357247777Sdavide		for (i = 0; i < callwheelsize; i++) {
1358247777Sdavide			sc = &cc->cc_callwheel[i];
1359247777Sdavide			c = 0;
1360247777Sdavide			LIST_FOREACH(tmp, sc, c_links.le) {
1361247777Sdavide				c++;
1362247777Sdavide				t = tmp->c_time - now;
1363247777Sdavide				if (t < 0)
1364247777Sdavide					t = 0;
1365247777Sdavide				st += t / SBT_1US;
1366247777Sdavide				spr += tmp->c_precision / SBT_1US;
1367247777Sdavide				if (t > maxt)
1368247777Sdavide					maxt = t;
1369247777Sdavide				if (tmp->c_precision > maxpr)
1370247777Sdavide					maxpr = tmp->c_precision;
1371247777Sdavide				ct[flssbt(t)]++;
1372247777Sdavide				cpr[flssbt(tmp->c_precision)]++;
1373247777Sdavide			}
1374247777Sdavide			if (c > maxc)
1375247777Sdavide				maxc = c;
1376247777Sdavide			ccpbk[fls(c + c / 2)]++;
1377247777Sdavide			count += c;
1378247777Sdavide		}
1379247777Sdavide		CC_UNLOCK(cc);
1380247777Sdavide#ifdef SMP
1381247777Sdavide	}
1382247777Sdavide#endif
1383247777Sdavide
1384247777Sdavide	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1385247777Sdavide		tcum += ct[i];
1386247777Sdavide	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1387247777Sdavide	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1388247777Sdavide		pcum += cpr[i];
1389247777Sdavide	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1390247777Sdavide	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1391247777Sdavide		c += ccpbk[i];
1392247777Sdavide	medc = (i >= 2) ? (1 << (i - 2)) : 0;
1393247777Sdavide
1394247777Sdavide	printf("Scheduled callouts statistic snapshot:\n");
1395247777Sdavide	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1396247777Sdavide	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1397247777Sdavide	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1398247777Sdavide	    medc,
1399247777Sdavide	    count / callwheelsize / mp_ncpus,
1400247777Sdavide	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1401247777Sdavide	    maxc);
1402247777Sdavide	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1403247777Sdavide	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1404247777Sdavide	    (st / count) / 1000000, (st / count) % 1000000,
1405247777Sdavide	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1406247777Sdavide	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1407247777Sdavide	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1408247777Sdavide	    (spr / count) / 1000000, (spr / count) % 1000000,
1409247777Sdavide	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1410247777Sdavide	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1411247777Sdavide	    "   prec\t   pcum\n");
1412247777Sdavide	for (i = 0, tcum = pcum = 0; i < 64; i++) {
1413247777Sdavide		if (ct[i] == 0 && cpr[i] == 0)
1414247777Sdavide			continue;
1415247777Sdavide		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1416247777Sdavide		tcum += ct[i];
1417247777Sdavide		pcum += cpr[i];
1418247777Sdavide		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1419247777Sdavide		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1420247777Sdavide		    i - 1 - (32 - CC_HASH_SHIFT),
1421247777Sdavide		    ct[i], tcum, cpr[i], pcum);
1422247777Sdavide	}
1423247777Sdavide	return (error);
1424247777Sdavide}
1425247777SdavideSYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1426247777Sdavide    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1427247777Sdavide    0, 0, sysctl_kern_callout_stat, "I",
1428247777Sdavide    "Dump immediate statistic snapshot of the scheduled callouts");
1429