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