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