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