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