xref: /freebsd/sys/kern/kern_timeout.c (revision c4fde87a3236b500246d4fce76dbca2a3d64f73a)
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 	sbintime_t prec;
638 	int c_iflags;
639 #ifdef SMP
640 	struct callout_cpu *new_cc;
641 	callout_func_t *new_func;
642 	void *new_arg;
643 	int flags, new_cpu;
644 	sbintime_t new_prec, new_time;
645 #endif
646 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
647 	sbintime_t sbt1, sbt2;
648 	struct timespec ts2;
649 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
650 	static callout_func_t *lastfunc;
651 #endif
652 
653 	CC_LOCK_ASSERT(cc);
654 	KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
655 	    ("softclock_call_cc: pend %p %x", c, c->c_iflags));
656 	KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
657 	    ("softclock_call_cc: act %p %x", c, c->c_flags));
658 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
659 	lock_status = 0;
660 	if (c->c_iflags & CALLOUT_SHAREDLOCK) {
661 		if (class == &lock_class_rm)
662 			lock_status = (uintptr_t)&tracker;
663 		else
664 			lock_status = 1;
665 	}
666 	c_lock = c->c_lock;
667 	c_func = c->c_func;
668 	c_arg = c->c_arg;
669 	c_iflags = c->c_iflags;
670 	c->c_iflags &= ~CALLOUT_PENDING;
671 
672 	cc_exec_curr(cc, direct) = c;
673 	cc_exec_last_func(cc, direct) = c_func;
674 	cc_exec_last_arg(cc, direct) = c_arg;
675 	cc_exec_cancel(cc, direct) = false;
676 	if (c_lock != NULL) {
677 		if (c_iflags & CALLOUT_TRYLOCK) {
678 			if (__predict_false(class->lc_trylock(c_lock,
679 			    lock_status) == 0)) {
680 				/*
681 				 * Retry after half of the precision, but not
682 				 * sooner than a tick from the current time.
683 				 * Every failure halves the precision, so the
684 				 * retry delay would otherwise shrink to zero.
685 				 * Immediate retries can starve a
686 				 * lower-priority lock owner on the same CPU,
687 				 * preventing it from running to release the
688 				 * lock.
689 				 *
690 				 * Use the current time because cc_lastscan may
691 				 * be stale by the time the lock is attempted.
692 				 * Keep the precision at least a tick as well,
693 				 * so that the retries of many contended
694 				 * callouts can share a timer interrupt.
695 				 */
696 				cc_exec_curr(cc, direct) = NULL;
697 				prec = qmax(c->c_precision / 2, tick_sbt);
698 				callout_cc_add(c, cc, sbinuptime() + prec,
699 				    prec, c_func, c_arg,
700 				    (direct) ? C_DIRECT_EXEC : 0);
701 				return;
702 			}
703 			CC_UNLOCK(cc);
704 		} else {
705 			CC_UNLOCK(cc);
706 			class->lc_lock(c_lock, lock_status);
707 			/*
708 			 * The callout may have been cancelled
709 			 * while we switched locks.
710 			 */
711 			if (cc_exec_cancel(cc, direct)) {
712 				class->lc_unlock(c_lock);
713 				goto skip;
714 			}
715 		}
716 		/* The callout cannot be stopped now. */
717 		cc_exec_cancel(cc, direct) = true;
718 		if (c_lock == &Giant.lock_object) {
719 #ifdef CALLOUT_PROFILING
720 			(*gcalls)++;
721 #endif
722 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
723 			    c, c_func, c_arg);
724 		} else {
725 #ifdef CALLOUT_PROFILING
726 			(*lockcalls)++;
727 #endif
728 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
729 			    c, c_func, c_arg);
730 		}
731 	} else {
732 		CC_UNLOCK(cc);
733 #ifdef CALLOUT_PROFILING
734 		(*mpcalls)++;
735 #endif
736 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
737 		    c, c_func, c_arg);
738 	}
739 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
740 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
741 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
742 	sbt1 = sbinuptime();
743 #endif
744 	THREAD_NO_SLEEPING();
745 	SDT_PROBE1(callout_execute, , , callout__start, c);
746 	c_func(c_arg);
747 	SDT_PROBE1(callout_execute, , , callout__end, c);
748 	THREAD_SLEEPING_OK();
749 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
750 	sbt2 = sbinuptime();
751 	sbt2 -= sbt1;
752 	if (sbt2 > maxdt) {
753 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
754 			ts2 = sbttots(sbt2);
755 			printf(
756 		"Expensive callout(9) function: %p(%p) %jd.%09ld s\n",
757 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
758 		}
759 		maxdt = sbt2;
760 		lastfunc = c_func;
761 	}
762 #endif
763 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
764 	CTR1(KTR_CALLOUT, "callout %p finished", c);
765 	if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
766 		class->lc_unlock(c_lock);
767 skip:
768 	CC_LOCK(cc);
769 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
770 	cc_exec_curr(cc, direct) = NULL;
771 	if (cc_exec_waiting(cc, direct)) {
772 		/*
773 		 * There is someone waiting for the
774 		 * callout to complete.
775 		 * If the callout was scheduled for
776 		 * migration just cancel it.
777 		 */
778 		if (cc_cce_migrating(cc, direct)) {
779 			cc_cce_cleanup(cc, direct);
780 
781 			/*
782 			 * It should be assert here that the callout is not
783 			 * destroyed but that is not easy.
784 			 */
785 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
786 		}
787 		cc_exec_waiting(cc, direct) = false;
788 		CC_UNLOCK(cc);
789 		wakeup(&cc_exec_waiting(cc, direct));
790 		CC_LOCK(cc);
791 	} else if (cc_cce_migrating(cc, direct)) {
792 #ifdef SMP
793 		/*
794 		 * If the callout was scheduled for
795 		 * migration just perform it now.
796 		 */
797 		new_cpu = cc_migration_cpu(cc, direct);
798 		new_time = cc_migration_time(cc, direct);
799 		new_prec = cc_migration_prec(cc, direct);
800 		new_func = cc_migration_func(cc, direct);
801 		new_arg = cc_migration_arg(cc, direct);
802 		cc_cce_cleanup(cc, direct);
803 
804 		/*
805 		 * It should be assert here that the callout is not destroyed
806 		 * but that is not easy.
807 		 *
808 		 * As first thing, handle deferred callout stops.
809 		 */
810 		if (!callout_migrating(c)) {
811 			CTR3(KTR_CALLOUT,
812 			     "deferred cancelled %p func %p arg %p",
813 			     c, new_func, new_arg);
814 			return;
815 		}
816 		c->c_iflags &= ~CALLOUT_DFRMIGRATION;
817 
818 		new_cc = callout_cpu_switch(c, cc, new_cpu);
819 		flags = (direct) ? C_DIRECT_EXEC : 0;
820 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
821 		    new_arg, flags);
822 		CC_UNLOCK(new_cc);
823 		CC_LOCK(cc);
824 #else
825 		panic("migration should not happen");
826 #endif
827 	}
828 }
829 
830 /*
831  * The callout mechanism is based on the work of Adam M. Costello and
832  * George Varghese, published in a technical report entitled "Redesigning
833  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
834  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
835  * used in this implementation was published by G. Varghese and T. Lauck in
836  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
837  * the Efficient Implementation of a Timer Facility" in the Proceedings of
838  * the 11th ACM Annual Symposium on Operating Systems Principles,
839  * Austin, Texas Nov 1987.
840  */
841 
842 /*
843  * Software (low priority) clock interrupt thread handler.
844  * Run periodic events from timeout queue.
845  */
846 static void
847 softclock_thread(void *arg)
848 {
849 	struct thread *td = curthread;
850 	struct callout_cpu *cc;
851 	struct callout *c;
852 #ifdef CALLOUT_PROFILING
853 	int depth, gcalls, lockcalls, mpcalls;
854 #endif
855 
856 	cc = (struct callout_cpu *)arg;
857 	CC_LOCK(cc);
858 	for (;;) {
859 		while (TAILQ_EMPTY(&cc->cc_expireq)) {
860 			/*
861 			 * Use CC_LOCK(cc) as the thread_lock while
862 			 * idle.
863 			 */
864 			thread_lock(td);
865 			thread_lock_set(td, (struct mtx *)&cc->cc_lock);
866 			TD_SET_IWAIT(td);
867 			mi_switch(SW_VOL | SWT_IWAIT);
868 
869 			/* mi_switch() drops thread_lock(). */
870 			CC_LOCK(cc);
871 		}
872 
873 #ifdef CALLOUT_PROFILING
874 		depth = gcalls = lockcalls = mpcalls = 0;
875 #endif
876 		while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
877 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
878 			softclock_call_cc(c, cc,
879 #ifdef CALLOUT_PROFILING
880 			    &mpcalls, &lockcalls, &gcalls,
881 #endif
882 			    0);
883 #ifdef CALLOUT_PROFILING
884 			++depth;
885 #endif
886 		}
887 #ifdef CALLOUT_PROFILING
888 		avg_depth += (depth * 1000 - avg_depth) >> 8;
889 		avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
890 		avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
891 		avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
892 #endif
893 	}
894 }
895 
896 void
897 callout_when(sbintime_t sbt, sbintime_t precision, int flags,
898     sbintime_t *res, sbintime_t *prec_res)
899 {
900 	sbintime_t to_sbt, to_pr;
901 
902 	if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
903 		*res = sbt;
904 		*prec_res = precision;
905 		return;
906 	}
907 	if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
908 		sbt = tick_sbt;
909 	if ((flags & C_HARDCLOCK) != 0 || sbt >= sbt_tickthreshold) {
910 		/*
911 		 * Obtain the time of the last hardclock() call on
912 		 * this CPU directly from the kern_clocksource.c.
913 		 * This value is per-CPU, but it is equal for all
914 		 * active ones.
915 		 */
916 #ifdef __LP64__
917 		to_sbt = DPCPU_GET(hardclocktime);
918 #else
919 		spinlock_enter();
920 		to_sbt = DPCPU_GET(hardclocktime);
921 		spinlock_exit();
922 #endif
923 		if (cold && to_sbt == 0)
924 			to_sbt = sbinuptime();
925 		if ((flags & C_HARDCLOCK) == 0)
926 			to_sbt += tick_sbt;
927 	} else
928 		to_sbt = sbinuptime();
929 	if (SBT_MAX - to_sbt < sbt)
930 		to_sbt = SBT_MAX;
931 	else
932 		to_sbt += sbt;
933 	*res = to_sbt;
934 	to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
935 	    sbt >> C_PRELGET(flags));
936 	*prec_res = to_pr > precision ? to_pr : precision;
937 }
938 
939 /*
940  * New interface; clients allocate their own callout structures.
941  *
942  * callout_reset() - establish or change a timeout
943  * callout_stop() - disestablish a timeout
944  * callout_init() - initialize a callout structure so that it can
945  *	safely be passed to callout_reset() and callout_stop()
946  *
947  * <sys/callout.h> defines three convenience macros:
948  *
949  * callout_active() - returns truth if callout has not been stopped,
950  *	drained, or deactivated since the last time the callout was
951  *	reset.
952  * callout_pending() - returns truth if callout is still waiting for timeout
953  * callout_deactivate() - marks the callout as having been serviced
954  */
955 int
956 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
957     callout_func_t *ftn, void *arg, int cpu, int flags)
958 {
959 	sbintime_t to_sbt, precision;
960 	struct callout_cpu *cc;
961 	int cancelled, direct;
962 
963 	cancelled = 0;
964 	callout_when(sbt, prec, flags, &to_sbt, &precision);
965 
966 	/*
967 	 * This flag used to be added by callout_cc_add, but the
968 	 * first time you call this we could end up with the
969 	 * wrong direct flag if we don't do it before we add.
970 	 */
971 	if (flags & C_DIRECT_EXEC) {
972 		direct = 1;
973 	} else {
974 		direct = 0;
975 	}
976 	KASSERT(!direct || c->c_lock == NULL ||
977 	    (LOCK_CLASS(c->c_lock)->lc_flags & LC_SPINLOCK),
978 	    ("%s: direct callout %p has non-spin lock", __func__, c));
979 
980 	cc = callout_lock(c);
981 	if (cpu == -1)
982 		cpu = c->c_cpu;
983 	KASSERT(cpu >= 0 && cpu <= mp_maxid && !CPU_ABSENT(cpu),
984 	    ("%s: invalid cpu %d", __func__, cpu));
985 
986 	if (cc_exec_curr(cc, direct) == c) {
987 		/*
988 		 * We're being asked to reschedule a callout which is
989 		 * currently in progress.  If there is a lock then we
990 		 * can cancel the callout if it has not really started.
991 		 */
992 		if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
993 			cancelled = cc_exec_cancel(cc, direct) = true;
994 		if (cc_exec_waiting(cc, direct)) {
995 			/*
996 			 * Someone has called callout_drain to kill this
997 			 * callout.  Don't reschedule.
998 			 */
999 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1000 			    cancelled ? "cancelled" : "failed to cancel",
1001 			    c, c->c_func, c->c_arg);
1002 			CC_UNLOCK(cc);
1003 			return (cancelled);
1004 		}
1005 #ifdef SMP
1006 		if (callout_migrating(c)) {
1007 			/*
1008 			 * This only occurs when a second callout_reset_sbt_on
1009 			 * is made after a previous one moved it into
1010 			 * deferred migration (below). Note we do *not* change
1011 			 * the prev_cpu even though the previous target may
1012 			 * be different.
1013 			 */
1014 			cc_migration_cpu(cc, direct) = cpu;
1015 			cc_migration_time(cc, direct) = to_sbt;
1016 			cc_migration_prec(cc, direct) = precision;
1017 			cc_migration_func(cc, direct) = ftn;
1018 			cc_migration_arg(cc, direct) = arg;
1019 			cancelled = 1;
1020 			CC_UNLOCK(cc);
1021 			return (cancelled);
1022 		}
1023 #endif
1024 	}
1025 	if (c->c_iflags & CALLOUT_PENDING) {
1026 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1027 			if (cc_exec_next(cc) == c)
1028 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1029 			LIST_REMOVE(c, c_links.le);
1030 		} else {
1031 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1032 		}
1033 		cancelled = 1;
1034 		c->c_iflags &= ~ CALLOUT_PENDING;
1035 		c->c_flags &= ~ CALLOUT_ACTIVE;
1036 	}
1037 
1038 #ifdef SMP
1039 	/*
1040 	 * If the callout must migrate try to perform it immediately.
1041 	 * If the callout is currently running, just defer the migration
1042 	 * to a more appropriate moment.
1043 	 */
1044 	if (c->c_cpu != cpu) {
1045 		if (cc_exec_curr(cc, direct) == c) {
1046 			/*
1047 			 * Pending will have been removed since we are
1048 			 * actually executing the callout on another
1049 			 * CPU. That callout should be waiting on the
1050 			 * lock the caller holds. If we set both
1051 			 * active/and/pending after we return and the
1052 			 * lock on the executing callout proceeds, it
1053 			 * will then see pending is true and return.
1054 			 * At the return from the actual callout execution
1055 			 * the migration will occur in softclock_call_cc
1056 			 * and this new callout will be placed on the
1057 			 * new CPU via a call to callout_cpu_switch() which
1058 			 * will get the lock on the right CPU followed
1059 			 * by a call callout_cc_add() which will add it there.
1060 			 * (see above in softclock_call_cc()).
1061 			 */
1062 			cc_migration_cpu(cc, direct) = cpu;
1063 			cc_migration_time(cc, direct) = to_sbt;
1064 			cc_migration_prec(cc, direct) = precision;
1065 			cc_migration_func(cc, direct) = ftn;
1066 			cc_migration_arg(cc, direct) = arg;
1067 			c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
1068 			c->c_flags |= CALLOUT_ACTIVE;
1069 			CTR6(KTR_CALLOUT,
1070 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1071 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1072 			    (u_int)(to_sbt & 0xffffffff), cpu);
1073 			CC_UNLOCK(cc);
1074 			return (cancelled);
1075 		}
1076 		cc = callout_cpu_switch(c, cc, cpu);
1077 	}
1078 #endif
1079 
1080 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, flags);
1081 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1082 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1083 	    (u_int)(to_sbt & 0xffffffff));
1084 	CC_UNLOCK(cc);
1085 
1086 	return (cancelled);
1087 }
1088 
1089 /*
1090  * Common idioms that can be optimized in the future.
1091  */
1092 int
1093 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1094 {
1095 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1096 }
1097 
1098 int
1099 callout_schedule(struct callout *c, int to_ticks)
1100 {
1101 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1102 }
1103 
1104 int
1105 _callout_stop_safe(struct callout *c, int flags)
1106 {
1107 	struct callout_cpu *cc, *old_cc;
1108 	struct lock_class *class;
1109 	int direct, sq_locked, use_lock;
1110 	int cancelled, not_on_a_list;
1111 
1112 	if ((flags & CS_DRAIN) != 0)
1113 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
1114 		    "calling %s", __func__);
1115 
1116 	/*
1117 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1118 	 * so just discard this check for the moment.
1119 	 */
1120 	if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1121 		if (c->c_lock == &Giant.lock_object)
1122 			use_lock = mtx_owned(&Giant);
1123 		else {
1124 			use_lock = 1;
1125 			class = LOCK_CLASS(c->c_lock);
1126 			class->lc_assert(c->c_lock, LA_XLOCKED);
1127 		}
1128 	} else
1129 		use_lock = 0;
1130 	if (c->c_iflags & CALLOUT_DIRECT) {
1131 		direct = 1;
1132 	} else {
1133 		direct = 0;
1134 	}
1135 	sq_locked = 0;
1136 	old_cc = NULL;
1137 again:
1138 	cc = callout_lock(c);
1139 
1140 	if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
1141 	    (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
1142 	    ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1143 		/*
1144 		 * Special case where this slipped in while we
1145 		 * were migrating *as* the callout is about to
1146 		 * execute. The caller probably holds the lock
1147 		 * the callout wants.
1148 		 *
1149 		 * Get rid of the migration first. Then set
1150 		 * the flag that tells this code *not* to
1151 		 * try to remove it from any lists (its not
1152 		 * on one yet). When the callout wheel runs,
1153 		 * it will ignore this callout.
1154 		 */
1155 		c->c_iflags &= ~CALLOUT_PENDING;
1156 		c->c_flags &= ~CALLOUT_ACTIVE;
1157 		not_on_a_list = 1;
1158 	} else {
1159 		not_on_a_list = 0;
1160 	}
1161 
1162 	/*
1163 	 * If the callout was migrating while the callout cpu lock was
1164 	 * dropped,  just drop the sleepqueue lock and check the states
1165 	 * again.
1166 	 */
1167 	if (sq_locked != 0 && cc != old_cc) {
1168 #ifdef SMP
1169 		CC_UNLOCK(cc);
1170 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1171 		sq_locked = 0;
1172 		old_cc = NULL;
1173 		goto again;
1174 #else
1175 		panic("migration should not happen");
1176 #endif
1177 	}
1178 
1179 	/*
1180 	 * If the callout is running, try to stop it or drain it.
1181 	 */
1182 	if (cc_exec_curr(cc, direct) == c) {
1183 		/*
1184 		 * Succeed we to stop it or not, we must clear the
1185 		 * active flag - this is what API users expect.  If we're
1186 		 * draining and the callout is currently executing, first wait
1187 		 * until it finishes.
1188 		 */
1189 		if ((flags & CS_DRAIN) == 0)
1190 			c->c_flags &= ~CALLOUT_ACTIVE;
1191 
1192 		if ((flags & CS_DRAIN) != 0) {
1193 			/*
1194 			 * The current callout is running (or just
1195 			 * about to run) and blocking is allowed, so
1196 			 * just wait for the current invocation to
1197 			 * finish.
1198 			 */
1199 			if (cc_exec_curr(cc, direct) == c) {
1200 				/*
1201 				 * Use direct calls to sleepqueue interface
1202 				 * instead of cv/msleep in order to avoid
1203 				 * a LOR between cc_lock and sleepqueue
1204 				 * chain spinlocks.  This piece of code
1205 				 * emulates a msleep_spin() call actually.
1206 				 *
1207 				 * If we already have the sleepqueue chain
1208 				 * locked, then we can safely block.  If we
1209 				 * don't already have it locked, however,
1210 				 * we have to drop the cc_lock to lock
1211 				 * it.  This opens several races, so we
1212 				 * restart at the beginning once we have
1213 				 * both locks.  If nothing has changed, then
1214 				 * we will end up back here with sq_locked
1215 				 * set.
1216 				 */
1217 				if (!sq_locked) {
1218 					CC_UNLOCK(cc);
1219 					sleepq_lock(
1220 					    &cc_exec_waiting(cc, direct));
1221 					sq_locked = 1;
1222 					old_cc = cc;
1223 					goto again;
1224 				}
1225 
1226 				/*
1227 				 * Migration could be cancelled here, but
1228 				 * as long as it is still not sure when it
1229 				 * will be packed up, just let softclock()
1230 				 * take care of it.
1231 				 */
1232 				cc_exec_waiting(cc, direct) = true;
1233 				DROP_GIANT();
1234 				CC_UNLOCK(cc);
1235 				sleepq_add(
1236 				    &cc_exec_waiting(cc, direct),
1237 				    &cc->cc_lock.lock_object, "codrain",
1238 				    SLEEPQ_SLEEP, 0);
1239 				sleepq_wait(
1240 				    &cc_exec_waiting(cc, direct),
1241 					     0);
1242 				sq_locked = 0;
1243 				old_cc = NULL;
1244 
1245 				/* Reacquire locks previously released. */
1246 				PICKUP_GIANT();
1247 				goto again;
1248 			}
1249 			c->c_flags &= ~CALLOUT_ACTIVE;
1250 		} else if (use_lock && !cc_exec_cancel(cc, direct)) {
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* with callout_drain().
1259 			 */
1260 			cc_exec_cancel(cc, direct) = true;
1261 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1262 			    c, c->c_func, c->c_arg);
1263 			KASSERT(!cc_cce_migrating(cc, direct),
1264 			    ("callout wrongly scheduled for migration"));
1265 			if (callout_migrating(c)) {
1266 				c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1267 #ifdef SMP
1268 				cc_migration_cpu(cc, direct) = CPUBLOCK;
1269 				cc_migration_time(cc, direct) = 0;
1270 				cc_migration_prec(cc, direct) = 0;
1271 				cc_migration_func(cc, direct) = NULL;
1272 				cc_migration_arg(cc, direct) = NULL;
1273 #endif
1274 			}
1275 			CC_UNLOCK(cc);
1276 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1277 			return (1);
1278 		} else if (callout_migrating(c)) {
1279 			/*
1280 			 * The callout is currently being serviced
1281 			 * and the "next" callout is scheduled at
1282 			 * its completion with a migration. We remove
1283 			 * the migration flag so it *won't* get rescheduled,
1284 			 * but we can't stop the one thats running so
1285 			 * we return 0.
1286 			 */
1287 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1288 #ifdef SMP
1289 			/*
1290 			 * We can't call cc_cce_cleanup here since
1291 			 * if we do it will remove .ce_curr and
1292 			 * its still running. This will prevent a
1293 			 * reschedule of the callout when the
1294 			 * execution completes.
1295 			 */
1296 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1297 			cc_migration_time(cc, direct) = 0;
1298 			cc_migration_prec(cc, direct) = 0;
1299 			cc_migration_func(cc, direct) = NULL;
1300 			cc_migration_arg(cc, direct) = NULL;
1301 #endif
1302 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1303 			    c, c->c_func, c->c_arg);
1304 			CC_UNLOCK(cc);
1305 			return (0);
1306 		} else {
1307 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1308 			    c, c->c_func, c->c_arg);
1309 		}
1310 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1311 		cancelled = 0;
1312 	} else
1313 		cancelled = 1;
1314 
1315 	if (sq_locked)
1316 		sleepq_release(&cc_exec_waiting(cc, direct));
1317 
1318 	if ((c->c_iflags & CALLOUT_PENDING) == 0) {
1319 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1320 		    c, c->c_func, c->c_arg);
1321 		/*
1322 		 * For not scheduled and not executing callout return
1323 		 * negative value.
1324 		 */
1325 		if (cc_exec_curr(cc, direct) != c)
1326 			cancelled = -1;
1327 		CC_UNLOCK(cc);
1328 		return (cancelled);
1329 	}
1330 
1331 	c->c_iflags &= ~CALLOUT_PENDING;
1332 	c->c_flags &= ~CALLOUT_ACTIVE;
1333 
1334 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1335 	    c, c->c_func, c->c_arg);
1336 	if (not_on_a_list == 0) {
1337 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1338 			if (cc_exec_next(cc) == c)
1339 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1340 			LIST_REMOVE(c, c_links.le);
1341 		} else {
1342 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1343 		}
1344 	}
1345 	CC_UNLOCK(cc);
1346 	return (cancelled);
1347 }
1348 
1349 void
1350 callout_init(struct callout *c, int mpsafe)
1351 {
1352 	bzero(c, sizeof *c);
1353 	if (mpsafe) {
1354 		c->c_lock = NULL;
1355 		c->c_iflags = CALLOUT_RETURNUNLOCKED;
1356 	} else {
1357 		c->c_lock = &Giant.lock_object;
1358 		c->c_iflags = 0;
1359 	}
1360 	c->c_cpu = cc_default_cpu;
1361 }
1362 
1363 void
1364 _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
1365 {
1366 	KASSERT(lock != NULL, ("%s: no lock", __func__));
1367 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK |
1368 	    CALLOUT_TRYLOCK)) == 0,
1369 	    ("%s: bad flags %d", __func__, flags));
1370 	KASSERT(!(LOCK_CLASS(lock)->lc_flags & LC_SLEEPABLE),
1371 	    ("%s: callout %p has sleepable lock", __func__, c));
1372 	KASSERT(!(flags & CALLOUT_TRYLOCK) ||
1373 	    (LOCK_CLASS(lock)->lc_trylock != NULL),
1374 	    ("%s: CALLOUT_TRYLOCK requested for %s",
1375 	    __func__, LOCK_CLASS(lock)->lc_name));
1376 
1377 	*c = (struct callout ){
1378 		.c_lock = lock,
1379 		.c_iflags = flags,
1380 		.c_cpu = cc_default_cpu,
1381 	};
1382 }
1383 
1384 static int
1385 flssbt(sbintime_t sbt)
1386 {
1387 
1388 	sbt += (uint64_t)sbt >> 1;
1389 	if (sizeof(long) >= sizeof(sbintime_t))
1390 		return (flsl(sbt));
1391 	if (sbt >= SBT_1S)
1392 		return (flsl(((uint64_t)sbt) >> 32) + 32);
1393 	return (flsl(sbt));
1394 }
1395 
1396 /*
1397  * Dump immediate statistic snapshot of the scheduled callouts.
1398  */
1399 static int
1400 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1401 {
1402 	struct callout *tmp;
1403 	struct callout_cpu *cc;
1404 	struct callout_list *sc;
1405 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1406 	int ct[64], cpr[64], ccpbk[32];
1407 	int error, val, i, count, tcum, pcum, maxc, c, medc;
1408 	int cpu;
1409 
1410 	val = 0;
1411 	error = sysctl_handle_int(oidp, &val, 0, req);
1412 	if (error != 0 || req->newptr == NULL)
1413 		return (error);
1414 	count = maxc = 0;
1415 	st = spr = maxt = maxpr = 0;
1416 	bzero(ccpbk, sizeof(ccpbk));
1417 	bzero(ct, sizeof(ct));
1418 	bzero(cpr, sizeof(cpr));
1419 	now = sbinuptime();
1420 	CPU_FOREACH(cpu) {
1421 		cc = CC_CPU(cpu);
1422 		CC_LOCK(cc);
1423 		for (i = 0; i < callwheelsize; i++) {
1424 			sc = &cc->cc_callwheel[i];
1425 			c = 0;
1426 			LIST_FOREACH(tmp, sc, c_links.le) {
1427 				c++;
1428 				t = tmp->c_time - now;
1429 				if (t < 0)
1430 					t = 0;
1431 				st += t / SBT_1US;
1432 				spr += tmp->c_precision / SBT_1US;
1433 				if (t > maxt)
1434 					maxt = t;
1435 				if (tmp->c_precision > maxpr)
1436 					maxpr = tmp->c_precision;
1437 				ct[flssbt(t)]++;
1438 				cpr[flssbt(tmp->c_precision)]++;
1439 			}
1440 			if (c > maxc)
1441 				maxc = c;
1442 			ccpbk[fls(c + c / 2)]++;
1443 			count += c;
1444 		}
1445 		CC_UNLOCK(cc);
1446 	}
1447 
1448 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1449 		tcum += ct[i];
1450 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1451 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1452 		pcum += cpr[i];
1453 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1454 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1455 		c += ccpbk[i];
1456 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
1457 
1458 	printf("Scheduled callouts statistic snapshot:\n");
1459 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1460 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1461 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1462 	    medc,
1463 	    count / callwheelsize / mp_ncpus,
1464 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1465 	    maxc);
1466 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1467 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1468 	    (st / count) / 1000000, (st / count) % 1000000,
1469 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1470 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1471 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1472 	    (spr / count) / 1000000, (spr / count) % 1000000,
1473 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1474 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1475 	    "   prec\t   pcum\n");
1476 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
1477 		if (ct[i] == 0 && cpr[i] == 0)
1478 			continue;
1479 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1480 		tcum += ct[i];
1481 		pcum += cpr[i];
1482 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1483 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1484 		    i - 1 - (32 - CC_HASH_SHIFT),
1485 		    ct[i], tcum, cpr[i], pcum);
1486 	}
1487 	return (error);
1488 }
1489 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1490     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1491     0, 0, sysctl_kern_callout_stat, "I",
1492     "Dump immediate statistic snapshot of the scheduled callouts");
1493 
1494 #ifdef DDB
1495 static void
1496 _show_callout(struct callout *c)
1497 {
1498 
1499 	db_printf("callout %p\n", c);
1500 #define	C_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, c->e);
1501 	db_printf("   &c_links = %p\n", &(c->c_links));
1502 	C_DB_PRINTF("%" PRId64,	c_time);
1503 	C_DB_PRINTF("%" PRId64,	c_precision);
1504 	C_DB_PRINTF("%p",	c_arg);
1505 	db_printf("   %s = %p (", "c_func", c->c_func);
1506 	db_printsym((db_addr_t)c->c_func, DB_STGY_ANY);
1507 	db_printf(")\n");
1508 	C_DB_PRINTF("%p",	c_lock);
1509 	C_DB_PRINTF("%#x",	c_flags);
1510 	C_DB_PRINTF("%#x",	c_iflags);
1511 	C_DB_PRINTF("%d",	c_cpu);
1512 #undef	C_DB_PRINTF
1513 }
1514 
1515 DB_SHOW_COMMAND(callout, db_show_callout)
1516 {
1517 
1518 	if (!have_addr) {
1519 		db_printf("usage: show callout <struct callout *>\n");
1520 		return;
1521 	}
1522 
1523 	_show_callout((struct callout *)addr);
1524 }
1525 
1526 static void
1527 _show_last_callout(int cpu, int direct, const char *dirstr)
1528 {
1529 	struct callout_cpu *cc;
1530 	void *func, *arg;
1531 
1532 	cc = CC_CPU(cpu);
1533 	func = cc_exec_last_func(cc, direct);
1534 	arg = cc_exec_last_arg(cc, direct);
1535 	db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
1536 	db_printsym((db_expr_t)func, DB_STGY_ANY);
1537 	db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
1538 }
1539 
1540 DB_SHOW_COMMAND_FLAGS(callout_last, db_show_callout_last, DB_CMD_MEMSAFE)
1541 {
1542 	int cpu, last;
1543 
1544 	if (have_addr) {
1545 		if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
1546 			db_printf("no such cpu: %d\n", (int)addr);
1547 			return;
1548 		}
1549 		cpu = last = addr;
1550 	} else {
1551 		cpu = 0;
1552 		last = mp_maxid;
1553 	}
1554 
1555 	while (cpu <= last) {
1556 		if (!CPU_ABSENT(cpu)) {
1557 			_show_last_callout(cpu, 0, "");
1558 			_show_last_callout(cpu, 1, " direct");
1559 		}
1560 		cpu++;
1561 	}
1562 }
1563 #endif /* DDB */
1564