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