xref: /freebsd/sys/kern/kern_timeout.c (revision 4ec234c813eed05c166859bba82c882e40826eb9)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_callout_profiling.h"
41 #if defined(__arm__)
42 #include "opt_timer.h"
43 #endif
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/bus.h>
48 #include <sys/callout.h>
49 #include <sys/file.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/ktr.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mutex.h>
56 #include <sys/proc.h>
57 #include <sys/sdt.h>
58 #include <sys/sleepqueue.h>
59 #include <sys/sysctl.h>
60 #include <sys/smp.h>
61 
62 #ifdef SMP
63 #include <machine/cpu.h>
64 #endif
65 
66 #ifndef NO_EVENTTIMERS
67 DPCPU_DECLARE(sbintime_t, hardclocktime);
68 #endif
69 
70 SDT_PROVIDER_DEFINE(callout_execute);
71 SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__start,
72     "struct callout *");
73 SDT_PROBE_DEFINE1(callout_execute, kernel, , callout__end,
74     "struct callout *");
75 
76 #ifdef CALLOUT_PROFILING
77 static int avg_depth;
78 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
79     "Average number of items examined per softclock call. Units = 1/1000");
80 static int avg_gcalls;
81 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
82     "Average number of Giant callouts made per softclock call. Units = 1/1000");
83 static int avg_lockcalls;
84 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
85     "Average number of lock callouts made per softclock call. Units = 1/1000");
86 static int avg_mpcalls;
87 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
88     "Average number of MP callouts made per softclock call. Units = 1/1000");
89 static int avg_depth_dir;
90 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
91     "Average number of direct callouts examined per callout_process call. "
92     "Units = 1/1000");
93 static int avg_lockcalls_dir;
94 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
95     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
96     "callout_process call. Units = 1/1000");
97 static int avg_mpcalls_dir;
98 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
99     0, "Average number of MP direct callouts made per callout_process call. "
100     "Units = 1/1000");
101 #endif
102 
103 static int ncallout;
104 SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN, &ncallout, 0,
105     "Number of entries in callwheel and size of timeout() preallocation");
106 
107 /*
108  * TODO:
109  *	allocate more timeout table slots when table overflows.
110  */
111 u_int callwheelsize, callwheelmask;
112 
113 /*
114  * The callout cpu exec entities represent informations necessary for
115  * describing the state of callouts currently running on the CPU and the ones
116  * necessary for migrating callouts to the new callout cpu. In particular,
117  * the first entry of the array cc_exec_entity holds informations for callout
118  * running in SWI thread context, while the second one holds informations
119  * for callout running directly from hardware interrupt context.
120  * The cached informations are very important for deferring migration when
121  * the migrating callout is already running.
122  */
123 struct cc_exec {
124 	struct callout		*cc_next;
125 	struct callout		*cc_curr;
126 #ifdef SMP
127 	void			(*ce_migration_func)(void *);
128 	void			*ce_migration_arg;
129 	int			ce_migration_cpu;
130 	sbintime_t		ce_migration_time;
131 	sbintime_t		ce_migration_prec;
132 #endif
133 	bool			cc_cancel;
134 	bool			cc_waiting;
135 };
136 
137 /*
138  * There is one struct callout_cpu per cpu, holding all relevant
139  * state for the callout processing thread on the individual CPU.
140  */
141 struct callout_cpu {
142 	struct mtx_padalign	cc_lock;
143 	struct cc_exec 		cc_exec_entity[2];
144 	struct callout		*cc_callout;
145 	struct callout_list	*cc_callwheel;
146 	struct callout_tailq	cc_expireq;
147 	struct callout_slist	cc_callfree;
148 	sbintime_t		cc_firstevent;
149 	sbintime_t		cc_lastscan;
150 	void			*cc_cookie;
151 	u_int			cc_bucket;
152 };
153 
154 #define	cc_exec_curr		cc_exec_entity[0].cc_curr
155 #define	cc_exec_next		cc_exec_entity[0].cc_next
156 #define	cc_exec_cancel		cc_exec_entity[0].cc_cancel
157 #define	cc_exec_waiting		cc_exec_entity[0].cc_waiting
158 #define	cc_exec_curr_dir	cc_exec_entity[1].cc_curr
159 #define	cc_exec_next_dir	cc_exec_entity[1].cc_next
160 #define	cc_exec_cancel_dir	cc_exec_entity[1].cc_cancel
161 #define	cc_exec_waiting_dir	cc_exec_entity[1].cc_waiting
162 
163 #ifdef SMP
164 #define	cc_migration_func	cc_exec_entity[0].ce_migration_func
165 #define	cc_migration_arg	cc_exec_entity[0].ce_migration_arg
166 #define	cc_migration_cpu	cc_exec_entity[0].ce_migration_cpu
167 #define	cc_migration_time	cc_exec_entity[0].ce_migration_time
168 #define	cc_migration_prec	cc_exec_entity[0].ce_migration_prec
169 #define	cc_migration_func_dir	cc_exec_entity[1].ce_migration_func
170 #define	cc_migration_arg_dir	cc_exec_entity[1].ce_migration_arg
171 #define	cc_migration_cpu_dir	cc_exec_entity[1].ce_migration_cpu
172 #define	cc_migration_time_dir	cc_exec_entity[1].ce_migration_time
173 #define	cc_migration_prec_dir	cc_exec_entity[1].ce_migration_prec
174 
175 struct callout_cpu cc_cpu[MAXCPU];
176 #define	CPUBLOCK	MAXCPU
177 #define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
178 #define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
179 #else
180 struct callout_cpu cc_cpu;
181 #define	CC_CPU(cpu)	&cc_cpu
182 #define	CC_SELF()	&cc_cpu
183 #endif
184 #define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
185 #define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
186 #define	CC_LOCK_ASSERT(cc)	mtx_assert(&(cc)->cc_lock, MA_OWNED)
187 
188 static int timeout_cpu;
189 
190 static void	callout_cpu_init(struct callout_cpu *cc);
191 static void	softclock_call_cc(struct callout *c, struct callout_cpu *cc,
192 #ifdef CALLOUT_PROFILING
193 		    int *mpcalls, int *lockcalls, int *gcalls,
194 #endif
195 		    int direct);
196 
197 static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
198 
199 /**
200  * Locked by cc_lock:
201  *   cc_curr         - If a callout is in progress, it is cc_curr.
202  *                     If cc_curr is non-NULL, threads waiting in
203  *                     callout_drain() will be woken up as soon as the
204  *                     relevant callout completes.
205  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
206  *                     guarantees that the current callout will not run.
207  *                     The softclock() function sets this to 0 before it
208  *                     drops callout_lock to acquire c_lock, and it calls
209  *                     the handler only if curr_cancelled is still 0 after
210  *                     cc_lock is successfully acquired.
211  *   cc_waiting      - If a thread is waiting in callout_drain(), then
212  *                     callout_wait is nonzero.  Set only when
213  *                     cc_curr is non-NULL.
214  */
215 
216 /*
217  * Resets the execution entity tied to a specific callout cpu.
218  */
219 static void
220 cc_cce_cleanup(struct callout_cpu *cc, int direct)
221 {
222 
223 	cc->cc_exec_entity[direct].cc_curr = NULL;
224 	cc->cc_exec_entity[direct].cc_next = NULL;
225 	cc->cc_exec_entity[direct].cc_cancel = false;
226 	cc->cc_exec_entity[direct].cc_waiting = false;
227 #ifdef SMP
228 	cc->cc_exec_entity[direct].ce_migration_cpu = CPUBLOCK;
229 	cc->cc_exec_entity[direct].ce_migration_time = 0;
230 	cc->cc_exec_entity[direct].ce_migration_prec = 0;
231 	cc->cc_exec_entity[direct].ce_migration_func = NULL;
232 	cc->cc_exec_entity[direct].ce_migration_arg = NULL;
233 #endif
234 }
235 
236 /*
237  * Checks if migration is requested by a specific callout cpu.
238  */
239 static int
240 cc_cce_migrating(struct callout_cpu *cc, int direct)
241 {
242 
243 #ifdef SMP
244 	return (cc->cc_exec_entity[direct].ce_migration_cpu != CPUBLOCK);
245 #else
246 	return (0);
247 #endif
248 }
249 
250 /*
251  * Kernel low level callwheel initialization
252  * called on cpu0 during kernel startup.
253  */
254 static void
255 callout_callwheel_init(void *dummy)
256 {
257 	struct callout_cpu *cc;
258 
259 	/*
260 	 * Calculate the size of the callout wheel and the preallocated
261 	 * timeout() structures.
262 	 * XXX: Clip callout to result of previous function of maxusers
263 	 * maximum 384.  This is still huge, but acceptable.
264 	 */
265 	ncallout = imin(16 + maxproc + maxfiles, 18508);
266 	TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
267 
268 	/*
269 	 * Calculate callout wheel size, should be next power of two higher
270 	 * than 'ncallout'.
271 	 */
272 	callwheelsize = 1 << fls(ncallout);
273 	callwheelmask = callwheelsize - 1;
274 
275 	/*
276 	 * Only cpu0 handles timeout(9) and receives a preallocation.
277 	 *
278 	 * XXX: Once all timeout(9) consumers are converted this can
279 	 * be removed.
280 	 */
281 	timeout_cpu = PCPU_GET(cpuid);
282 	cc = CC_CPU(timeout_cpu);
283 	cc->cc_callout = malloc(ncallout * sizeof(struct callout),
284 	    M_CALLOUT, M_WAITOK);
285 	callout_cpu_init(cc);
286 }
287 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
288 
289 /*
290  * Initialize the per-cpu callout structures.
291  */
292 static void
293 callout_cpu_init(struct callout_cpu *cc)
294 {
295 	struct callout *c;
296 	int i;
297 
298 	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
299 	SLIST_INIT(&cc->cc_callfree);
300 	cc->cc_callwheel = malloc(sizeof(struct callout_list) * callwheelsize,
301 	    M_CALLOUT, M_WAITOK);
302 	for (i = 0; i < callwheelsize; i++)
303 		LIST_INIT(&cc->cc_callwheel[i]);
304 	TAILQ_INIT(&cc->cc_expireq);
305 	cc->cc_firstevent = INT64_MAX;
306 	for (i = 0; i < 2; i++)
307 		cc_cce_cleanup(cc, i);
308 	if (cc->cc_callout == NULL)	/* Only cpu0 handles timeout(9) */
309 		return;
310 	for (i = 0; i < ncallout; i++) {
311 		c = &cc->cc_callout[i];
312 		callout_init(c, 0);
313 		c->c_flags = CALLOUT_LOCAL_ALLOC;
314 		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
315 	}
316 }
317 
318 #ifdef SMP
319 /*
320  * Switches the cpu tied to a specific callout.
321  * The function expects a locked incoming callout cpu and returns with
322  * locked outcoming callout cpu.
323  */
324 static struct callout_cpu *
325 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
326 {
327 	struct callout_cpu *new_cc;
328 
329 	MPASS(c != NULL && cc != NULL);
330 	CC_LOCK_ASSERT(cc);
331 
332 	/*
333 	 * Avoid interrupts and preemption firing after the callout cpu
334 	 * is blocked in order to avoid deadlocks as the new thread
335 	 * may be willing to acquire the callout cpu lock.
336 	 */
337 	c->c_cpu = CPUBLOCK;
338 	spinlock_enter();
339 	CC_UNLOCK(cc);
340 	new_cc = CC_CPU(new_cpu);
341 	CC_LOCK(new_cc);
342 	spinlock_exit();
343 	c->c_cpu = new_cpu;
344 	return (new_cc);
345 }
346 #endif
347 
348 /*
349  * Start standard softclock thread.
350  */
351 static void
352 start_softclock(void *dummy)
353 {
354 	struct callout_cpu *cc;
355 #ifdef SMP
356 	int cpu;
357 #endif
358 
359 	cc = CC_CPU(timeout_cpu);
360 	if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
361 	    INTR_MPSAFE, &cc->cc_cookie))
362 		panic("died while creating standard software ithreads");
363 #ifdef SMP
364 	CPU_FOREACH(cpu) {
365 		if (cpu == timeout_cpu)
366 			continue;
367 		cc = CC_CPU(cpu);
368 		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(9). */
369 		callout_cpu_init(cc);
370 		if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
371 		    INTR_MPSAFE, &cc->cc_cookie))
372 			panic("died while creating standard software ithreads");
373 	}
374 #endif
375 }
376 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
377 
378 #define	CC_HASH_SHIFT	8
379 
380 static inline u_int
381 callout_hash(sbintime_t sbt)
382 {
383 
384 	return (sbt >> (32 - CC_HASH_SHIFT));
385 }
386 
387 static inline u_int
388 callout_get_bucket(sbintime_t sbt)
389 {
390 
391 	return (callout_hash(sbt) & callwheelmask);
392 }
393 
394 void
395 callout_process(sbintime_t now)
396 {
397 	struct callout *tmp, *tmpn;
398 	struct callout_cpu *cc;
399 	struct callout_list *sc;
400 	sbintime_t first, last, max, tmp_max;
401 	uint32_t lookahead;
402 	u_int firstb, lastb, nowb;
403 #ifdef CALLOUT_PROFILING
404 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
405 #endif
406 
407 	cc = CC_SELF();
408 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
409 
410 	/* Compute the buckets of the last scan and present times. */
411 	firstb = callout_hash(cc->cc_lastscan);
412 	cc->cc_lastscan = now;
413 	nowb = callout_hash(now);
414 
415 	/* Compute the last bucket and minimum time of the bucket after it. */
416 	if (nowb == firstb)
417 		lookahead = (SBT_1S / 16);
418 	else if (nowb - firstb == 1)
419 		lookahead = (SBT_1S / 8);
420 	else
421 		lookahead = (SBT_1S / 2);
422 	first = last = now;
423 	first += (lookahead / 2);
424 	last += lookahead;
425 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
426 	lastb = callout_hash(last) - 1;
427 	max = last;
428 
429 	/*
430 	 * Check if we wrapped around the entire wheel from the last scan.
431 	 * In case, we need to scan entirely the wheel for pending callouts.
432 	 */
433 	if (lastb - firstb >= callwheelsize) {
434 		lastb = firstb + callwheelsize - 1;
435 		if (nowb - firstb >= callwheelsize)
436 			nowb = lastb;
437 	}
438 
439 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
440 	do {
441 		sc = &cc->cc_callwheel[firstb & callwheelmask];
442 		tmp = LIST_FIRST(sc);
443 		while (tmp != NULL) {
444 			/* Run the callout if present time within allowed. */
445 			if (tmp->c_time <= now) {
446 				/*
447 				 * Consumer told us the callout may be run
448 				 * directly from hardware interrupt context.
449 				 */
450 				if (tmp->c_flags & CALLOUT_DIRECT) {
451 #ifdef CALLOUT_PROFILING
452 					++depth_dir;
453 #endif
454 					cc->cc_exec_next_dir =
455 					    LIST_NEXT(tmp, c_links.le);
456 					cc->cc_bucket = firstb & callwheelmask;
457 					LIST_REMOVE(tmp, c_links.le);
458 					softclock_call_cc(tmp, cc,
459 #ifdef CALLOUT_PROFILING
460 					    &mpcalls_dir, &lockcalls_dir, NULL,
461 #endif
462 					    1);
463 					tmp = cc->cc_exec_next_dir;
464 				} else {
465 					tmpn = LIST_NEXT(tmp, c_links.le);
466 					LIST_REMOVE(tmp, c_links.le);
467 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
468 					    tmp, c_links.tqe);
469 					tmp->c_flags |= CALLOUT_PROCESSED;
470 					tmp = tmpn;
471 				}
472 				continue;
473 			}
474 			/* Skip events from distant future. */
475 			if (tmp->c_time >= max)
476 				goto next;
477 			/*
478 			 * Event minimal time is bigger than present maximal
479 			 * time, so it cannot be aggregated.
480 			 */
481 			if (tmp->c_time > last) {
482 				lastb = nowb;
483 				goto next;
484 			}
485 			/* Update first and last time, respecting this event. */
486 			if (tmp->c_time < first)
487 				first = tmp->c_time;
488 			tmp_max = tmp->c_time + tmp->c_precision;
489 			if (tmp_max < last)
490 				last = tmp_max;
491 next:
492 			tmp = LIST_NEXT(tmp, c_links.le);
493 		}
494 		/* Proceed with the next bucket. */
495 		firstb++;
496 		/*
497 		 * Stop if we looked after present time and found
498 		 * some event we can't execute at now.
499 		 * Stop if we looked far enough into the future.
500 		 */
501 	} while (((int)(firstb - lastb)) <= 0);
502 	cc->cc_firstevent = last;
503 #ifndef NO_EVENTTIMERS
504 	cpu_new_callout(curcpu, last, first);
505 #endif
506 #ifdef CALLOUT_PROFILING
507 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
508 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
509 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
510 #endif
511 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
512 	/*
513 	 * swi_sched acquires the thread lock, so we don't want to call it
514 	 * with cc_lock held; incorrect locking order.
515 	 */
516 	if (!TAILQ_EMPTY(&cc->cc_expireq))
517 		swi_sched(cc->cc_cookie, 0);
518 }
519 
520 static struct callout_cpu *
521 callout_lock(struct callout *c)
522 {
523 	struct callout_cpu *cc;
524 	int cpu;
525 
526 	for (;;) {
527 		cpu = c->c_cpu;
528 #ifdef SMP
529 		if (cpu == CPUBLOCK) {
530 			while (c->c_cpu == CPUBLOCK)
531 				cpu_spinwait();
532 			continue;
533 		}
534 #endif
535 		cc = CC_CPU(cpu);
536 		CC_LOCK(cc);
537 		if (cpu == c->c_cpu)
538 			break;
539 		CC_UNLOCK(cc);
540 	}
541 	return (cc);
542 }
543 
544 static void
545 callout_cc_add(struct callout *c, struct callout_cpu *cc,
546     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
547     void *arg, int cpu, int flags)
548 {
549 	int bucket;
550 
551 	CC_LOCK_ASSERT(cc);
552 	if (sbt < cc->cc_lastscan)
553 		sbt = cc->cc_lastscan;
554 	c->c_arg = arg;
555 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
556 	if (flags & C_DIRECT_EXEC)
557 		c->c_flags |= CALLOUT_DIRECT;
558 	c->c_flags &= ~CALLOUT_PROCESSED;
559 	c->c_func = func;
560 	c->c_time = sbt;
561 	c->c_precision = precision;
562 	bucket = callout_get_bucket(c->c_time);
563 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
564 	    c, (int)(c->c_precision >> 32),
565 	    (u_int)(c->c_precision & 0xffffffff));
566 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
567 	if (cc->cc_bucket == bucket)
568 		cc->cc_exec_next_dir = c;
569 #ifndef NO_EVENTTIMERS
570 	/*
571 	 * Inform the eventtimers(4) subsystem there's a new callout
572 	 * that has been inserted, but only if really required.
573 	 */
574 	if (INT64_MAX - c->c_time < c->c_precision)
575 		c->c_precision = INT64_MAX - c->c_time;
576 	sbt = c->c_time + c->c_precision;
577 	if (sbt < cc->cc_firstevent) {
578 		cc->cc_firstevent = sbt;
579 		cpu_new_callout(cpu, sbt, c->c_time);
580 	}
581 #endif
582 }
583 
584 static void
585 callout_cc_del(struct callout *c, struct callout_cpu *cc)
586 {
587 
588 	if ((c->c_flags & CALLOUT_LOCAL_ALLOC) == 0)
589 		return;
590 	c->c_func = NULL;
591 	SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
592 }
593 
594 static void
595 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
596 #ifdef CALLOUT_PROFILING
597     int *mpcalls, int *lockcalls, int *gcalls,
598 #endif
599     int direct)
600 {
601 	struct rm_priotracker tracker;
602 	void (*c_func)(void *);
603 	void *c_arg;
604 	struct lock_class *class;
605 	struct lock_object *c_lock;
606 	uintptr_t lock_status;
607 	int c_flags;
608 #ifdef SMP
609 	struct callout_cpu *new_cc;
610 	void (*new_func)(void *);
611 	void *new_arg;
612 	int flags, new_cpu;
613 	sbintime_t new_prec, new_time;
614 #endif
615 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
616 	sbintime_t sbt1, sbt2;
617 	struct timespec ts2;
618 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
619 	static timeout_t *lastfunc;
620 #endif
621 
622 	KASSERT((c->c_flags & (CALLOUT_PENDING | CALLOUT_ACTIVE)) ==
623 	    (CALLOUT_PENDING | CALLOUT_ACTIVE),
624 	    ("softclock_call_cc: pend|act %p %x", c, c->c_flags));
625 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
626 	lock_status = 0;
627 	if (c->c_flags & CALLOUT_SHAREDLOCK) {
628 		if (class == &lock_class_rm)
629 			lock_status = (uintptr_t)&tracker;
630 		else
631 			lock_status = 1;
632 	}
633 	c_lock = c->c_lock;
634 	c_func = c->c_func;
635 	c_arg = c->c_arg;
636 	c_flags = c->c_flags;
637 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
638 		c->c_flags = CALLOUT_LOCAL_ALLOC;
639 	else
640 		c->c_flags &= ~CALLOUT_PENDING;
641 	cc->cc_exec_entity[direct].cc_curr = c;
642 	cc->cc_exec_entity[direct].cc_cancel = false;
643 	CC_UNLOCK(cc);
644 	if (c_lock != NULL) {
645 		class->lc_lock(c_lock, lock_status);
646 		/*
647 		 * The callout may have been cancelled
648 		 * while we switched locks.
649 		 */
650 		if (cc->cc_exec_entity[direct].cc_cancel) {
651 			class->lc_unlock(c_lock);
652 			goto skip;
653 		}
654 		/* The callout cannot be stopped now. */
655 		cc->cc_exec_entity[direct].cc_cancel = true;
656 		if (c_lock == &Giant.lock_object) {
657 #ifdef CALLOUT_PROFILING
658 			(*gcalls)++;
659 #endif
660 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
661 			    c, c_func, c_arg);
662 		} else {
663 #ifdef CALLOUT_PROFILING
664 			(*lockcalls)++;
665 #endif
666 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
667 			    c, c_func, c_arg);
668 		}
669 	} else {
670 #ifdef CALLOUT_PROFILING
671 		(*mpcalls)++;
672 #endif
673 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
674 		    c, c_func, c_arg);
675 	}
676 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
677 	sbt1 = sbinuptime();
678 #endif
679 	THREAD_NO_SLEEPING();
680 	SDT_PROBE(callout_execute, kernel, , callout__start, c, 0, 0, 0, 0);
681 	c_func(c_arg);
682 	SDT_PROBE(callout_execute, kernel, , callout__end, c, 0, 0, 0, 0);
683 	THREAD_SLEEPING_OK();
684 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
685 	sbt2 = sbinuptime();
686 	sbt2 -= sbt1;
687 	if (sbt2 > maxdt) {
688 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
689 			ts2 = sbttots(sbt2);
690 			printf(
691 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
692 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
693 		}
694 		maxdt = sbt2;
695 		lastfunc = c_func;
696 	}
697 #endif
698 	CTR1(KTR_CALLOUT, "callout %p finished", c);
699 	if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
700 		class->lc_unlock(c_lock);
701 skip:
702 	CC_LOCK(cc);
703 	KASSERT(cc->cc_exec_entity[direct].cc_curr == c, ("mishandled cc_curr"));
704 	cc->cc_exec_entity[direct].cc_curr = NULL;
705 	if (cc->cc_exec_entity[direct].cc_waiting) {
706 		/*
707 		 * There is someone waiting for the
708 		 * callout to complete.
709 		 * If the callout was scheduled for
710 		 * migration just cancel it.
711 		 */
712 		if (cc_cce_migrating(cc, direct)) {
713 			cc_cce_cleanup(cc, direct);
714 
715 			/*
716 			 * It should be assert here that the callout is not
717 			 * destroyed but that is not easy.
718 			 */
719 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
720 		}
721 		cc->cc_exec_entity[direct].cc_waiting = false;
722 		CC_UNLOCK(cc);
723 		wakeup(&cc->cc_exec_entity[direct].cc_waiting);
724 		CC_LOCK(cc);
725 	} else if (cc_cce_migrating(cc, direct)) {
726 		KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0,
727 		    ("Migrating legacy callout %p", c));
728 #ifdef SMP
729 		/*
730 		 * If the callout was scheduled for
731 		 * migration just perform it now.
732 		 */
733 		new_cpu = cc->cc_exec_entity[direct].ce_migration_cpu;
734 		new_time = cc->cc_exec_entity[direct].ce_migration_time;
735 		new_prec = cc->cc_exec_entity[direct].ce_migration_prec;
736 		new_func = cc->cc_exec_entity[direct].ce_migration_func;
737 		new_arg = cc->cc_exec_entity[direct].ce_migration_arg;
738 		cc_cce_cleanup(cc, direct);
739 
740 		/*
741 		 * It should be assert here that the callout is not destroyed
742 		 * but that is not easy.
743 		 *
744 		 * As first thing, handle deferred callout stops.
745 		 */
746 		if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
747 			CTR3(KTR_CALLOUT,
748 			     "deferred cancelled %p func %p arg %p",
749 			     c, new_func, new_arg);
750 			callout_cc_del(c, cc);
751 			return;
752 		}
753 		c->c_flags &= ~CALLOUT_DFRMIGRATION;
754 
755 		new_cc = callout_cpu_switch(c, cc, new_cpu);
756 		flags = (direct) ? C_DIRECT_EXEC : 0;
757 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
758 		    new_arg, new_cpu, flags);
759 		CC_UNLOCK(new_cc);
760 		CC_LOCK(cc);
761 #else
762 		panic("migration should not happen");
763 #endif
764 	}
765 	/*
766 	 * If the current callout is locally allocated (from
767 	 * timeout(9)) then put it on the freelist.
768 	 *
769 	 * Note: we need to check the cached copy of c_flags because
770 	 * if it was not local, then it's not safe to deref the
771 	 * callout pointer.
772 	 */
773 	KASSERT((c_flags & CALLOUT_LOCAL_ALLOC) == 0 ||
774 	    c->c_flags == CALLOUT_LOCAL_ALLOC,
775 	    ("corrupted callout"));
776 	if (c_flags & CALLOUT_LOCAL_ALLOC)
777 		callout_cc_del(c, cc);
778 }
779 
780 /*
781  * The callout mechanism is based on the work of Adam M. Costello and
782  * George Varghese, published in a technical report entitled "Redesigning
783  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
784  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
785  * used in this implementation was published by G. Varghese and T. Lauck in
786  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
787  * the Efficient Implementation of a Timer Facility" in the Proceedings of
788  * the 11th ACM Annual Symposium on Operating Systems Principles,
789  * Austin, Texas Nov 1987.
790  */
791 
792 /*
793  * Software (low priority) clock interrupt.
794  * Run periodic events from timeout queue.
795  */
796 void
797 softclock(void *arg)
798 {
799 	struct callout_cpu *cc;
800 	struct callout *c;
801 #ifdef CALLOUT_PROFILING
802 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
803 #endif
804 
805 	cc = (struct callout_cpu *)arg;
806 	CC_LOCK(cc);
807 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
808 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
809 		softclock_call_cc(c, cc,
810 #ifdef CALLOUT_PROFILING
811 		    &mpcalls, &lockcalls, &gcalls,
812 #endif
813 		    0);
814 #ifdef CALLOUT_PROFILING
815 		++depth;
816 #endif
817 	}
818 #ifdef CALLOUT_PROFILING
819 	avg_depth += (depth * 1000 - avg_depth) >> 8;
820 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
821 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
822 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
823 #endif
824 	CC_UNLOCK(cc);
825 }
826 
827 /*
828  * timeout --
829  *	Execute a function after a specified length of time.
830  *
831  * untimeout --
832  *	Cancel previous timeout function call.
833  *
834  * callout_handle_init --
835  *	Initialize a handle so that using it with untimeout is benign.
836  *
837  *	See AT&T BCI Driver Reference Manual for specification.  This
838  *	implementation differs from that one in that although an
839  *	identification value is returned from timeout, the original
840  *	arguments to timeout as well as the identifier are used to
841  *	identify entries for untimeout.
842  */
843 struct callout_handle
844 timeout(ftn, arg, to_ticks)
845 	timeout_t *ftn;
846 	void *arg;
847 	int to_ticks;
848 {
849 	struct callout_cpu *cc;
850 	struct callout *new;
851 	struct callout_handle handle;
852 
853 	cc = CC_CPU(timeout_cpu);
854 	CC_LOCK(cc);
855 	/* Fill in the next free callout structure. */
856 	new = SLIST_FIRST(&cc->cc_callfree);
857 	if (new == NULL)
858 		/* XXX Attempt to malloc first */
859 		panic("timeout table full");
860 	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
861 	callout_reset(new, to_ticks, ftn, arg);
862 	handle.callout = new;
863 	CC_UNLOCK(cc);
864 
865 	return (handle);
866 }
867 
868 void
869 untimeout(ftn, arg, handle)
870 	timeout_t *ftn;
871 	void *arg;
872 	struct callout_handle handle;
873 {
874 	struct callout_cpu *cc;
875 
876 	/*
877 	 * Check for a handle that was initialized
878 	 * by callout_handle_init, but never used
879 	 * for a real timeout.
880 	 */
881 	if (handle.callout == NULL)
882 		return;
883 
884 	cc = callout_lock(handle.callout);
885 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
886 		callout_stop(handle.callout);
887 	CC_UNLOCK(cc);
888 }
889 
890 void
891 callout_handle_init(struct callout_handle *handle)
892 {
893 	handle->callout = NULL;
894 }
895 
896 /*
897  * New interface; clients allocate their own callout structures.
898  *
899  * callout_reset() - establish or change a timeout
900  * callout_stop() - disestablish a timeout
901  * callout_init() - initialize a callout structure so that it can
902  *	safely be passed to callout_reset() and callout_stop()
903  *
904  * <sys/callout.h> defines three convenience macros:
905  *
906  * callout_active() - returns truth if callout has not been stopped,
907  *	drained, or deactivated since the last time the callout was
908  *	reset.
909  * callout_pending() - returns truth if callout is still waiting for timeout
910  * callout_deactivate() - marks the callout as having been serviced
911  */
912 int
913 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
914     void (*ftn)(void *), void *arg, int cpu, int flags)
915 {
916 	sbintime_t to_sbt, pr;
917 	struct callout_cpu *cc;
918 	int cancelled, direct;
919 
920 	cancelled = 0;
921 	if (flags & C_ABSOLUTE) {
922 		to_sbt = sbt;
923 	} else {
924 		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
925 			sbt = tick_sbt;
926 		if ((flags & C_HARDCLOCK) ||
927 #ifdef NO_EVENTTIMERS
928 		    sbt >= sbt_timethreshold) {
929 			to_sbt = getsbinuptime();
930 
931 			/* Add safety belt for the case of hz > 1000. */
932 			to_sbt += tc_tick_sbt - tick_sbt;
933 #else
934 		    sbt >= sbt_tickthreshold) {
935 			/*
936 			 * Obtain the time of the last hardclock() call on
937 			 * this CPU directly from the kern_clocksource.c.
938 			 * This value is per-CPU, but it is equal for all
939 			 * active ones.
940 			 */
941 #ifdef __LP64__
942 			to_sbt = DPCPU_GET(hardclocktime);
943 #else
944 			spinlock_enter();
945 			to_sbt = DPCPU_GET(hardclocktime);
946 			spinlock_exit();
947 #endif
948 #endif
949 			if ((flags & C_HARDCLOCK) == 0)
950 				to_sbt += tick_sbt;
951 		} else
952 			to_sbt = sbinuptime();
953 		if (INT64_MAX - to_sbt < sbt)
954 			to_sbt = INT64_MAX;
955 		else
956 			to_sbt += sbt;
957 		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
958 		    sbt >> C_PRELGET(flags));
959 		if (pr > precision)
960 			precision = pr;
961 	}
962 	/*
963 	 * Don't allow migration of pre-allocated callouts lest they
964 	 * become unbalanced.
965 	 */
966 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
967 		cpu = c->c_cpu;
968 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
969 	KASSERT(!direct || c->c_lock == NULL,
970 	    ("%s: direct callout %p has lock", __func__, c));
971 	cc = callout_lock(c);
972 	if (cc->cc_exec_entity[direct].cc_curr == c) {
973 		/*
974 		 * We're being asked to reschedule a callout which is
975 		 * currently in progress.  If there is a lock then we
976 		 * can cancel the callout if it has not really started.
977 		 */
978 		if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
979 			cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
980 		if (cc->cc_exec_entity[direct].cc_waiting) {
981 			/*
982 			 * Someone has called callout_drain to kill this
983 			 * callout.  Don't reschedule.
984 			 */
985 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
986 			    cancelled ? "cancelled" : "failed to cancel",
987 			    c, c->c_func, c->c_arg);
988 			CC_UNLOCK(cc);
989 			return (cancelled);
990 		}
991 	}
992 	if (c->c_flags & CALLOUT_PENDING) {
993 		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
994 			if (cc->cc_exec_next_dir == c)
995 				cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
996 			LIST_REMOVE(c, c_links.le);
997 		} else
998 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
999 		cancelled = 1;
1000 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1001 	}
1002 
1003 #ifdef SMP
1004 	/*
1005 	 * If the callout must migrate try to perform it immediately.
1006 	 * If the callout is currently running, just defer the migration
1007 	 * to a more appropriate moment.
1008 	 */
1009 	if (c->c_cpu != cpu) {
1010 		if (cc->cc_exec_entity[direct].cc_curr == c) {
1011 			cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
1012 			cc->cc_exec_entity[direct].ce_migration_time
1013 			    = to_sbt;
1014 			cc->cc_exec_entity[direct].ce_migration_prec
1015 			    = precision;
1016 			cc->cc_exec_entity[direct].ce_migration_func = ftn;
1017 			cc->cc_exec_entity[direct].ce_migration_arg = arg;
1018 			c->c_flags |= CALLOUT_DFRMIGRATION;
1019 			CTR6(KTR_CALLOUT,
1020 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1021 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1022 			    (u_int)(to_sbt & 0xffffffff), cpu);
1023 			CC_UNLOCK(cc);
1024 			return (cancelled);
1025 		}
1026 		cc = callout_cpu_switch(c, cc, cpu);
1027 	}
1028 #endif
1029 
1030 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1031 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1032 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1033 	    (u_int)(to_sbt & 0xffffffff));
1034 	CC_UNLOCK(cc);
1035 
1036 	return (cancelled);
1037 }
1038 
1039 /*
1040  * Common idioms that can be optimized in the future.
1041  */
1042 int
1043 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1044 {
1045 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1046 }
1047 
1048 int
1049 callout_schedule(struct callout *c, int to_ticks)
1050 {
1051 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1052 }
1053 
1054 int
1055 _callout_stop_safe(c, safe)
1056 	struct	callout *c;
1057 	int	safe;
1058 {
1059 	struct callout_cpu *cc, *old_cc;
1060 	struct lock_class *class;
1061 	int direct, sq_locked, use_lock;
1062 
1063 	/*
1064 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1065 	 * so just discard this check for the moment.
1066 	 */
1067 	if (!safe && c->c_lock != NULL) {
1068 		if (c->c_lock == &Giant.lock_object)
1069 			use_lock = mtx_owned(&Giant);
1070 		else {
1071 			use_lock = 1;
1072 			class = LOCK_CLASS(c->c_lock);
1073 			class->lc_assert(c->c_lock, LA_XLOCKED);
1074 		}
1075 	} else
1076 		use_lock = 0;
1077 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1078 	sq_locked = 0;
1079 	old_cc = NULL;
1080 again:
1081 	cc = callout_lock(c);
1082 
1083 	/*
1084 	 * If the callout was migrating while the callout cpu lock was
1085 	 * dropped,  just drop the sleepqueue lock and check the states
1086 	 * again.
1087 	 */
1088 	if (sq_locked != 0 && cc != old_cc) {
1089 #ifdef SMP
1090 		CC_UNLOCK(cc);
1091 		sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
1092 		sq_locked = 0;
1093 		old_cc = NULL;
1094 		goto again;
1095 #else
1096 		panic("migration should not happen");
1097 #endif
1098 	}
1099 
1100 	/*
1101 	 * If the callout isn't pending, it's not on the queue, so
1102 	 * don't attempt to remove it from the queue.  We can try to
1103 	 * stop it by other means however.
1104 	 */
1105 	if (!(c->c_flags & CALLOUT_PENDING)) {
1106 		c->c_flags &= ~CALLOUT_ACTIVE;
1107 
1108 		/*
1109 		 * If it wasn't on the queue and it isn't the current
1110 		 * callout, then we can't stop it, so just bail.
1111 		 */
1112 		if (cc->cc_exec_entity[direct].cc_curr != c) {
1113 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1114 			    c, c->c_func, c->c_arg);
1115 			CC_UNLOCK(cc);
1116 			if (sq_locked)
1117 				sleepq_release(
1118 				    &cc->cc_exec_entity[direct].cc_waiting);
1119 			return (0);
1120 		}
1121 
1122 		if (safe) {
1123 			/*
1124 			 * The current callout is running (or just
1125 			 * about to run) and blocking is allowed, so
1126 			 * just wait for the current invocation to
1127 			 * finish.
1128 			 */
1129 			while (cc->cc_exec_entity[direct].cc_curr == c) {
1130 				/*
1131 				 * Use direct calls to sleepqueue interface
1132 				 * instead of cv/msleep in order to avoid
1133 				 * a LOR between cc_lock and sleepqueue
1134 				 * chain spinlocks.  This piece of code
1135 				 * emulates a msleep_spin() call actually.
1136 				 *
1137 				 * If we already have the sleepqueue chain
1138 				 * locked, then we can safely block.  If we
1139 				 * don't already have it locked, however,
1140 				 * we have to drop the cc_lock to lock
1141 				 * it.  This opens several races, so we
1142 				 * restart at the beginning once we have
1143 				 * both locks.  If nothing has changed, then
1144 				 * we will end up back here with sq_locked
1145 				 * set.
1146 				 */
1147 				if (!sq_locked) {
1148 					CC_UNLOCK(cc);
1149 					sleepq_lock(
1150 					&cc->cc_exec_entity[direct].cc_waiting);
1151 					sq_locked = 1;
1152 					old_cc = cc;
1153 					goto again;
1154 				}
1155 
1156 				/*
1157 				 * Migration could be cancelled here, but
1158 				 * as long as it is still not sure when it
1159 				 * will be packed up, just let softclock()
1160 				 * take care of it.
1161 				 */
1162 				cc->cc_exec_entity[direct].cc_waiting = true;
1163 				DROP_GIANT();
1164 				CC_UNLOCK(cc);
1165 				sleepq_add(
1166 				    &cc->cc_exec_entity[direct].cc_waiting,
1167 				    &cc->cc_lock.lock_object, "codrain",
1168 				    SLEEPQ_SLEEP, 0);
1169 				sleepq_wait(
1170 				    &cc->cc_exec_entity[direct].cc_waiting,
1171 					     0);
1172 				sq_locked = 0;
1173 				old_cc = NULL;
1174 
1175 				/* Reacquire locks previously released. */
1176 				PICKUP_GIANT();
1177 				CC_LOCK(cc);
1178 			}
1179 		} else if (use_lock &&
1180 			    !cc->cc_exec_entity[direct].cc_cancel) {
1181 			/*
1182 			 * The current callout is waiting for its
1183 			 * lock which we hold.  Cancel the callout
1184 			 * and return.  After our caller drops the
1185 			 * lock, the callout will be skipped in
1186 			 * softclock().
1187 			 */
1188 			cc->cc_exec_entity[direct].cc_cancel = true;
1189 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1190 			    c, c->c_func, c->c_arg);
1191 			KASSERT(!cc_cce_migrating(cc, direct),
1192 			    ("callout wrongly scheduled for migration"));
1193 			CC_UNLOCK(cc);
1194 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1195 			return (1);
1196 		} else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
1197 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
1198 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1199 			    c, c->c_func, c->c_arg);
1200 			CC_UNLOCK(cc);
1201 			return (1);
1202 		}
1203 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1204 		    c, c->c_func, c->c_arg);
1205 		CC_UNLOCK(cc);
1206 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1207 		return (0);
1208 	}
1209 	if (sq_locked)
1210 		sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
1211 
1212 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1213 
1214 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1215 	    c, c->c_func, c->c_arg);
1216 	if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1217 		if (cc->cc_exec_next_dir == c)
1218 			cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1219 		LIST_REMOVE(c, c_links.le);
1220 	} else
1221 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1222 	callout_cc_del(c, cc);
1223 
1224 	CC_UNLOCK(cc);
1225 	return (1);
1226 }
1227 
1228 void
1229 callout_init(c, mpsafe)
1230 	struct	callout *c;
1231 	int mpsafe;
1232 {
1233 	bzero(c, sizeof *c);
1234 	if (mpsafe) {
1235 		c->c_lock = NULL;
1236 		c->c_flags = CALLOUT_RETURNUNLOCKED;
1237 	} else {
1238 		c->c_lock = &Giant.lock_object;
1239 		c->c_flags = 0;
1240 	}
1241 	c->c_cpu = timeout_cpu;
1242 }
1243 
1244 void
1245 _callout_init_lock(c, lock, flags)
1246 	struct	callout *c;
1247 	struct	lock_object *lock;
1248 	int flags;
1249 {
1250 	bzero(c, sizeof *c);
1251 	c->c_lock = lock;
1252 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1253 	    ("callout_init_lock: bad flags %d", flags));
1254 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1255 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1256 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1257 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1258 	    __func__));
1259 	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1260 	c->c_cpu = timeout_cpu;
1261 }
1262 
1263 #ifdef APM_FIXUP_CALLTODO
1264 /*
1265  * Adjust the kernel calltodo timeout list.  This routine is used after
1266  * an APM resume to recalculate the calltodo timer list values with the
1267  * number of hz's we have been sleeping.  The next hardclock() will detect
1268  * that there are fired timers and run softclock() to execute them.
1269  *
1270  * Please note, I have not done an exhaustive analysis of what code this
1271  * might break.  I am motivated to have my select()'s and alarm()'s that
1272  * have expired during suspend firing upon resume so that the applications
1273  * which set the timer can do the maintanence the timer was for as close
1274  * as possible to the originally intended time.  Testing this code for a
1275  * week showed that resuming from a suspend resulted in 22 to 25 timers
1276  * firing, which seemed independant on whether the suspend was 2 hours or
1277  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1278  */
1279 void
1280 adjust_timeout_calltodo(time_change)
1281     struct timeval *time_change;
1282 {
1283 	register struct callout *p;
1284 	unsigned long delta_ticks;
1285 
1286 	/*
1287 	 * How many ticks were we asleep?
1288 	 * (stolen from tvtohz()).
1289 	 */
1290 
1291 	/* Don't do anything */
1292 	if (time_change->tv_sec < 0)
1293 		return;
1294 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
1295 		delta_ticks = (time_change->tv_sec * 1000000 +
1296 			       time_change->tv_usec + (tick - 1)) / tick + 1;
1297 	else if (time_change->tv_sec <= LONG_MAX / hz)
1298 		delta_ticks = time_change->tv_sec * hz +
1299 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
1300 	else
1301 		delta_ticks = LONG_MAX;
1302 
1303 	if (delta_ticks > INT_MAX)
1304 		delta_ticks = INT_MAX;
1305 
1306 	/*
1307 	 * Now rip through the timer calltodo list looking for timers
1308 	 * to expire.
1309 	 */
1310 
1311 	/* don't collide with softclock() */
1312 	CC_LOCK(cc);
1313 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1314 		p->c_time -= delta_ticks;
1315 
1316 		/* Break if the timer had more time on it than delta_ticks */
1317 		if (p->c_time > 0)
1318 			break;
1319 
1320 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1321 		delta_ticks = -p->c_time;
1322 	}
1323 	CC_UNLOCK(cc);
1324 
1325 	return;
1326 }
1327 #endif /* APM_FIXUP_CALLTODO */
1328 
1329 static int
1330 flssbt(sbintime_t sbt)
1331 {
1332 
1333 	sbt += (uint64_t)sbt >> 1;
1334 	if (sizeof(long) >= sizeof(sbintime_t))
1335 		return (flsl(sbt));
1336 	if (sbt >= SBT_1S)
1337 		return (flsl(((uint64_t)sbt) >> 32) + 32);
1338 	return (flsl(sbt));
1339 }
1340 
1341 /*
1342  * Dump immediate statistic snapshot of the scheduled callouts.
1343  */
1344 static int
1345 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1346 {
1347 	struct callout *tmp;
1348 	struct callout_cpu *cc;
1349 	struct callout_list *sc;
1350 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1351 	int ct[64], cpr[64], ccpbk[32];
1352 	int error, val, i, count, tcum, pcum, maxc, c, medc;
1353 #ifdef SMP
1354 	int cpu;
1355 #endif
1356 
1357 	val = 0;
1358 	error = sysctl_handle_int(oidp, &val, 0, req);
1359 	if (error != 0 || req->newptr == NULL)
1360 		return (error);
1361 	count = maxc = 0;
1362 	st = spr = maxt = maxpr = 0;
1363 	bzero(ccpbk, sizeof(ccpbk));
1364 	bzero(ct, sizeof(ct));
1365 	bzero(cpr, sizeof(cpr));
1366 	now = sbinuptime();
1367 #ifdef SMP
1368 	CPU_FOREACH(cpu) {
1369 		cc = CC_CPU(cpu);
1370 #else
1371 		cc = CC_CPU(timeout_cpu);
1372 #endif
1373 		CC_LOCK(cc);
1374 		for (i = 0; i < callwheelsize; i++) {
1375 			sc = &cc->cc_callwheel[i];
1376 			c = 0;
1377 			LIST_FOREACH(tmp, sc, c_links.le) {
1378 				c++;
1379 				t = tmp->c_time - now;
1380 				if (t < 0)
1381 					t = 0;
1382 				st += t / SBT_1US;
1383 				spr += tmp->c_precision / SBT_1US;
1384 				if (t > maxt)
1385 					maxt = t;
1386 				if (tmp->c_precision > maxpr)
1387 					maxpr = tmp->c_precision;
1388 				ct[flssbt(t)]++;
1389 				cpr[flssbt(tmp->c_precision)]++;
1390 			}
1391 			if (c > maxc)
1392 				maxc = c;
1393 			ccpbk[fls(c + c / 2)]++;
1394 			count += c;
1395 		}
1396 		CC_UNLOCK(cc);
1397 #ifdef SMP
1398 	}
1399 #endif
1400 
1401 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1402 		tcum += ct[i];
1403 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1404 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1405 		pcum += cpr[i];
1406 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1407 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1408 		c += ccpbk[i];
1409 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
1410 
1411 	printf("Scheduled callouts statistic snapshot:\n");
1412 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1413 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1414 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1415 	    medc,
1416 	    count / callwheelsize / mp_ncpus,
1417 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1418 	    maxc);
1419 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1420 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1421 	    (st / count) / 1000000, (st / count) % 1000000,
1422 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1423 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1424 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1425 	    (spr / count) / 1000000, (spr / count) % 1000000,
1426 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1427 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1428 	    "   prec\t   pcum\n");
1429 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
1430 		if (ct[i] == 0 && cpr[i] == 0)
1431 			continue;
1432 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1433 		tcum += ct[i];
1434 		pcum += cpr[i];
1435 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1436 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1437 		    i - 1 - (32 - CC_HASH_SHIFT),
1438 		    ct[i], tcum, cpr[i], pcum);
1439 	}
1440 	return (error);
1441 }
1442 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1443     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1444     0, 0, sysctl_kern_callout_stat, "I",
1445     "Dump immediate statistic snapshot of the scheduled callouts");
1446