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