xref: /freebsd/sys/kern/kern_timeout.c (revision a3557ef0)
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 #if defined(__arm__)
45 #include "opt_timer.h"
46 #endif
47 #include "opt_rss.h"
48 
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/bus.h>
52 #include <sys/callout.h>
53 #include <sys/domainset.h>
54 #include <sys/file.h>
55 #include <sys/interrupt.h>
56 #include <sys/kernel.h>
57 #include <sys/ktr.h>
58 #include <sys/lock.h>
59 #include <sys/malloc.h>
60 #include <sys/mutex.h>
61 #include <sys/proc.h>
62 #include <sys/sdt.h>
63 #include <sys/sleepqueue.h>
64 #include <sys/sysctl.h>
65 #include <sys/smp.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 #ifndef NO_EVENTTIMERS
78 DPCPU_DECLARE(sbintime_t, hardclocktime);
79 #endif
80 
81 SDT_PROVIDER_DEFINE(callout_execute);
82 SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
83 SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
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 	void			*cc_cookie;
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 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 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() 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 | MTX_RECURSE);
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 callout_cpu *cc;
378 	char name[MAXCOMLEN];
379 	int cpu;
380 	bool pin_swi;
381 	struct intr_event *ie;
382 
383 	CPU_FOREACH(cpu) {
384 		cc = CC_CPU(cpu);
385 		snprintf(name, sizeof(name), "clock (%d)", cpu);
386 		ie = NULL;
387 		if (swi_add(&ie, name, softclock, cc, SWI_CLOCK,
388 		    INTR_MPSAFE, &cc->cc_cookie))
389 			panic("died while creating standard software ithreads");
390 		if (cpu == cc_default_cpu)
391 			pin_swi = pin_default_swi;
392 		else
393 			pin_swi = pin_pcpu_swi;
394 		if (pin_swi && (intr_event_bind(ie, cpu) != 0)) {
395 			printf("%s: %s clock couldn't be pinned to cpu %d\n",
396 			    __func__,
397 			    cpu == cc_default_cpu ? "default" : "per-cpu",
398 			    cpu);
399 		}
400 	}
401 }
402 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
403 
404 #define	CC_HASH_SHIFT	8
405 
406 static inline u_int
407 callout_hash(sbintime_t sbt)
408 {
409 
410 	return (sbt >> (32 - CC_HASH_SHIFT));
411 }
412 
413 static inline u_int
414 callout_get_bucket(sbintime_t sbt)
415 {
416 
417 	return (callout_hash(sbt) & callwheelmask);
418 }
419 
420 void
421 callout_process(sbintime_t now)
422 {
423 	struct callout *tmp, *tmpn;
424 	struct callout_cpu *cc;
425 	struct callout_list *sc;
426 	sbintime_t first, last, max, tmp_max;
427 	uint32_t lookahead;
428 	u_int firstb, lastb, nowb;
429 #ifdef CALLOUT_PROFILING
430 	int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
431 #endif
432 
433 	cc = CC_SELF();
434 	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
435 
436 	/* Compute the buckets of the last scan and present times. */
437 	firstb = callout_hash(cc->cc_lastscan);
438 	cc->cc_lastscan = now;
439 	nowb = callout_hash(now);
440 
441 	/* Compute the last bucket and minimum time of the bucket after it. */
442 	if (nowb == firstb)
443 		lookahead = (SBT_1S / 16);
444 	else if (nowb - firstb == 1)
445 		lookahead = (SBT_1S / 8);
446 	else
447 		lookahead = (SBT_1S / 2);
448 	first = last = now;
449 	first += (lookahead / 2);
450 	last += lookahead;
451 	last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
452 	lastb = callout_hash(last) - 1;
453 	max = last;
454 
455 	/*
456 	 * Check if we wrapped around the entire wheel from the last scan.
457 	 * In case, we need to scan entirely the wheel for pending callouts.
458 	 */
459 	if (lastb - firstb >= callwheelsize) {
460 		lastb = firstb + callwheelsize - 1;
461 		if (nowb - firstb >= callwheelsize)
462 			nowb = lastb;
463 	}
464 
465 	/* Iterate callwheel from firstb to nowb and then up to lastb. */
466 	do {
467 		sc = &cc->cc_callwheel[firstb & callwheelmask];
468 		tmp = LIST_FIRST(sc);
469 		while (tmp != NULL) {
470 			/* Run the callout if present time within allowed. */
471 			if (tmp->c_time <= now) {
472 				/*
473 				 * Consumer told us the callout may be run
474 				 * directly from hardware interrupt context.
475 				 */
476 				if (tmp->c_iflags & CALLOUT_DIRECT) {
477 #ifdef CALLOUT_PROFILING
478 					++depth_dir;
479 #endif
480 					cc_exec_next(cc) =
481 					    LIST_NEXT(tmp, c_links.le);
482 					cc->cc_bucket = firstb & callwheelmask;
483 					LIST_REMOVE(tmp, c_links.le);
484 					softclock_call_cc(tmp, cc,
485 #ifdef CALLOUT_PROFILING
486 					    &mpcalls_dir, &lockcalls_dir, NULL,
487 #endif
488 					    1);
489 					tmp = cc_exec_next(cc);
490 					cc_exec_next(cc) = NULL;
491 				} else {
492 					tmpn = LIST_NEXT(tmp, c_links.le);
493 					LIST_REMOVE(tmp, c_links.le);
494 					TAILQ_INSERT_TAIL(&cc->cc_expireq,
495 					    tmp, c_links.tqe);
496 					tmp->c_iflags |= CALLOUT_PROCESSED;
497 					tmp = tmpn;
498 				}
499 				continue;
500 			}
501 			/* Skip events from distant future. */
502 			if (tmp->c_time >= max)
503 				goto next;
504 			/*
505 			 * Event minimal time is bigger than present maximal
506 			 * time, so it cannot be aggregated.
507 			 */
508 			if (tmp->c_time > last) {
509 				lastb = nowb;
510 				goto next;
511 			}
512 			/* Update first and last time, respecting this event. */
513 			if (tmp->c_time < first)
514 				first = tmp->c_time;
515 			tmp_max = tmp->c_time + tmp->c_precision;
516 			if (tmp_max < last)
517 				last = tmp_max;
518 next:
519 			tmp = LIST_NEXT(tmp, c_links.le);
520 		}
521 		/* Proceed with the next bucket. */
522 		firstb++;
523 		/*
524 		 * Stop if we looked after present time and found
525 		 * some event we can't execute at now.
526 		 * Stop if we looked far enough into the future.
527 		 */
528 	} while (((int)(firstb - lastb)) <= 0);
529 	cc->cc_firstevent = last;
530 #ifndef NO_EVENTTIMERS
531 	cpu_new_callout(curcpu, last, first);
532 #endif
533 #ifdef CALLOUT_PROFILING
534 	avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
535 	avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
536 	avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
537 #endif
538 	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
539 	/*
540 	 * swi_sched acquires the thread lock, so we don't want to call it
541 	 * with cc_lock held; incorrect locking order.
542 	 */
543 	if (!TAILQ_EMPTY(&cc->cc_expireq))
544 		swi_sched(cc->cc_cookie, 0);
545 }
546 
547 static struct callout_cpu *
548 callout_lock(struct callout *c)
549 {
550 	struct callout_cpu *cc;
551 	int cpu;
552 
553 	for (;;) {
554 		cpu = c->c_cpu;
555 #ifdef SMP
556 		if (cpu == CPUBLOCK) {
557 			while (c->c_cpu == CPUBLOCK)
558 				cpu_spinwait();
559 			continue;
560 		}
561 #endif
562 		cc = CC_CPU(cpu);
563 		CC_LOCK(cc);
564 		if (cpu == c->c_cpu)
565 			break;
566 		CC_UNLOCK(cc);
567 	}
568 	return (cc);
569 }
570 
571 static void
572 callout_cc_add(struct callout *c, struct callout_cpu *cc,
573     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
574     void *arg, int cpu, int flags)
575 {
576 	int bucket;
577 
578 	CC_LOCK_ASSERT(cc);
579 	if (sbt < cc->cc_lastscan)
580 		sbt = cc->cc_lastscan;
581 	c->c_arg = arg;
582 	c->c_iflags |= CALLOUT_PENDING;
583 	c->c_iflags &= ~CALLOUT_PROCESSED;
584 	c->c_flags |= CALLOUT_ACTIVE;
585 	if (flags & C_DIRECT_EXEC)
586 		c->c_iflags |= CALLOUT_DIRECT;
587 	c->c_func = func;
588 	c->c_time = sbt;
589 	c->c_precision = precision;
590 	bucket = callout_get_bucket(c->c_time);
591 	CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
592 	    c, (int)(c->c_precision >> 32),
593 	    (u_int)(c->c_precision & 0xffffffff));
594 	LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
595 	if (cc->cc_bucket == bucket)
596 		cc_exec_next(cc) = c;
597 #ifndef NO_EVENTTIMERS
598 	/*
599 	 * Inform the eventtimers(4) subsystem there's a new callout
600 	 * that has been inserted, but only if really required.
601 	 */
602 	if (SBT_MAX - c->c_time < c->c_precision)
603 		c->c_precision = SBT_MAX - c->c_time;
604 	sbt = c->c_time + c->c_precision;
605 	if (sbt < cc->cc_firstevent) {
606 		cc->cc_firstevent = sbt;
607 		cpu_new_callout(cpu, sbt, c->c_time);
608 	}
609 #endif
610 }
611 
612 static void
613 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
614 #ifdef CALLOUT_PROFILING
615     int *mpcalls, int *lockcalls, int *gcalls,
616 #endif
617     int direct)
618 {
619 	struct rm_priotracker tracker;
620 	callout_func_t *c_func, *drain;
621 	void *c_arg;
622 	struct lock_class *class;
623 	struct lock_object *c_lock;
624 	uintptr_t lock_status;
625 	int c_iflags;
626 #ifdef SMP
627 	struct callout_cpu *new_cc;
628 	callout_func_t *new_func;
629 	void *new_arg;
630 	int flags, new_cpu;
631 	sbintime_t new_prec, new_time;
632 #endif
633 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
634 	sbintime_t sbt1, sbt2;
635 	struct timespec ts2;
636 	static sbintime_t maxdt = 2 * SBT_1MS;	/* 2 msec */
637 	static callout_func_t *lastfunc;
638 #endif
639 
640 	KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
641 	    ("softclock_call_cc: pend %p %x", c, c->c_iflags));
642 	KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
643 	    ("softclock_call_cc: act %p %x", c, c->c_flags));
644 	class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
645 	lock_status = 0;
646 	if (c->c_flags & CALLOUT_SHAREDLOCK) {
647 		if (class == &lock_class_rm)
648 			lock_status = (uintptr_t)&tracker;
649 		else
650 			lock_status = 1;
651 	}
652 	c_lock = c->c_lock;
653 	c_func = c->c_func;
654 	c_arg = c->c_arg;
655 	c_iflags = c->c_iflags;
656 	c->c_iflags &= ~CALLOUT_PENDING;
657 
658 	cc_exec_curr(cc, direct) = c;
659 	cc_exec_last_func(cc, direct) = c_func;
660 	cc_exec_last_arg(cc, direct) = c_arg;
661 	cc_exec_cancel(cc, direct) = false;
662 	cc_exec_drain(cc, direct) = NULL;
663 	CC_UNLOCK(cc);
664 	if (c_lock != NULL) {
665 		class->lc_lock(c_lock, lock_status);
666 		/*
667 		 * The callout may have been cancelled
668 		 * while we switched locks.
669 		 */
670 		if (cc_exec_cancel(cc, direct)) {
671 			class->lc_unlock(c_lock);
672 			goto skip;
673 		}
674 		/* The callout cannot be stopped now. */
675 		cc_exec_cancel(cc, direct) = true;
676 		if (c_lock == &Giant.lock_object) {
677 #ifdef CALLOUT_PROFILING
678 			(*gcalls)++;
679 #endif
680 			CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
681 			    c, c_func, c_arg);
682 		} else {
683 #ifdef CALLOUT_PROFILING
684 			(*lockcalls)++;
685 #endif
686 			CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
687 			    c, c_func, c_arg);
688 		}
689 	} else {
690 #ifdef CALLOUT_PROFILING
691 		(*mpcalls)++;
692 #endif
693 		CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
694 		    c, c_func, c_arg);
695 	}
696 	KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
697 	    "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
698 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
699 	sbt1 = sbinuptime();
700 #endif
701 	THREAD_NO_SLEEPING();
702 	SDT_PROBE1(callout_execute, , , callout__start, c);
703 	c_func(c_arg);
704 	SDT_PROBE1(callout_execute, , , callout__end, c);
705 	THREAD_SLEEPING_OK();
706 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
707 	sbt2 = sbinuptime();
708 	sbt2 -= sbt1;
709 	if (sbt2 > maxdt) {
710 		if (lastfunc != c_func || sbt2 > maxdt * 2) {
711 			ts2 = sbttots(sbt2);
712 			printf(
713 		"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
714 			    c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
715 		}
716 		maxdt = sbt2;
717 		lastfunc = c_func;
718 	}
719 #endif
720 	KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
721 	CTR1(KTR_CALLOUT, "callout %p finished", c);
722 	if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
723 		class->lc_unlock(c_lock);
724 skip:
725 	CC_LOCK(cc);
726 	KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
727 	cc_exec_curr(cc, direct) = NULL;
728 	if (cc_exec_drain(cc, direct)) {
729 		drain = cc_exec_drain(cc, direct);
730 		cc_exec_drain(cc, direct) = NULL;
731 		CC_UNLOCK(cc);
732 		drain(c_arg);
733 		CC_LOCK(cc);
734 	}
735 	if (cc_exec_waiting(cc, direct)) {
736 		/*
737 		 * There is someone waiting for the
738 		 * callout to complete.
739 		 * If the callout was scheduled for
740 		 * migration just cancel it.
741 		 */
742 		if (cc_cce_migrating(cc, direct)) {
743 			cc_cce_cleanup(cc, direct);
744 
745 			/*
746 			 * It should be assert here that the callout is not
747 			 * destroyed but that is not easy.
748 			 */
749 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
750 		}
751 		cc_exec_waiting(cc, direct) = false;
752 		CC_UNLOCK(cc);
753 		wakeup(&cc_exec_waiting(cc, direct));
754 		CC_LOCK(cc);
755 	} else if (cc_cce_migrating(cc, direct)) {
756 #ifdef SMP
757 		/*
758 		 * If the callout was scheduled for
759 		 * migration just perform it now.
760 		 */
761 		new_cpu = cc_migration_cpu(cc, direct);
762 		new_time = cc_migration_time(cc, direct);
763 		new_prec = cc_migration_prec(cc, direct);
764 		new_func = cc_migration_func(cc, direct);
765 		new_arg = cc_migration_arg(cc, direct);
766 		cc_cce_cleanup(cc, direct);
767 
768 		/*
769 		 * It should be assert here that the callout is not destroyed
770 		 * but that is not easy.
771 		 *
772 		 * As first thing, handle deferred callout stops.
773 		 */
774 		if (!callout_migrating(c)) {
775 			CTR3(KTR_CALLOUT,
776 			     "deferred cancelled %p func %p arg %p",
777 			     c, new_func, new_arg);
778 			return;
779 		}
780 		c->c_iflags &= ~CALLOUT_DFRMIGRATION;
781 
782 		new_cc = callout_cpu_switch(c, cc, new_cpu);
783 		flags = (direct) ? C_DIRECT_EXEC : 0;
784 		callout_cc_add(c, new_cc, new_time, new_prec, new_func,
785 		    new_arg, new_cpu, flags);
786 		CC_UNLOCK(new_cc);
787 		CC_LOCK(cc);
788 #else
789 		panic("migration should not happen");
790 #endif
791 	}
792 }
793 
794 /*
795  * The callout mechanism is based on the work of Adam M. Costello and
796  * George Varghese, published in a technical report entitled "Redesigning
797  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
798  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
799  * used in this implementation was published by G. Varghese and T. Lauck in
800  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
801  * the Efficient Implementation of a Timer Facility" in the Proceedings of
802  * the 11th ACM Annual Symposium on Operating Systems Principles,
803  * Austin, Texas Nov 1987.
804  */
805 
806 /*
807  * Software (low priority) clock interrupt.
808  * Run periodic events from timeout queue.
809  */
810 void
811 softclock(void *arg)
812 {
813 	struct callout_cpu *cc;
814 	struct callout *c;
815 #ifdef CALLOUT_PROFILING
816 	int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
817 #endif
818 
819 	cc = (struct callout_cpu *)arg;
820 	CC_LOCK(cc);
821 	while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
822 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
823 		softclock_call_cc(c, cc,
824 #ifdef CALLOUT_PROFILING
825 		    &mpcalls, &lockcalls, &gcalls,
826 #endif
827 		    0);
828 #ifdef CALLOUT_PROFILING
829 		++depth;
830 #endif
831 	}
832 #ifdef CALLOUT_PROFILING
833 	avg_depth += (depth * 1000 - avg_depth) >> 8;
834 	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
835 	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
836 	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
837 #endif
838 	CC_UNLOCK(cc);
839 }
840 
841 void
842 callout_when(sbintime_t sbt, sbintime_t precision, int flags,
843     sbintime_t *res, sbintime_t *prec_res)
844 {
845 	sbintime_t to_sbt, to_pr;
846 
847 	if ((flags & (C_ABSOLUTE | C_PRECALC)) != 0) {
848 		*res = sbt;
849 		*prec_res = precision;
850 		return;
851 	}
852 	if ((flags & C_HARDCLOCK) != 0 && sbt < tick_sbt)
853 		sbt = tick_sbt;
854 	if ((flags & C_HARDCLOCK) != 0 ||
855 #ifdef NO_EVENTTIMERS
856 	    sbt >= sbt_timethreshold) {
857 		to_sbt = getsbinuptime();
858 
859 		/* Add safety belt for the case of hz > 1000. */
860 		to_sbt += tc_tick_sbt - tick_sbt;
861 #else
862 	    sbt >= sbt_tickthreshold) {
863 		/*
864 		 * Obtain the time of the last hardclock() call on
865 		 * this CPU directly from the kern_clocksource.c.
866 		 * This value is per-CPU, but it is equal for all
867 		 * active ones.
868 		 */
869 #ifdef __LP64__
870 		to_sbt = DPCPU_GET(hardclocktime);
871 #else
872 		spinlock_enter();
873 		to_sbt = DPCPU_GET(hardclocktime);
874 		spinlock_exit();
875 #endif
876 #endif
877 		if (cold && to_sbt == 0)
878 			to_sbt = sbinuptime();
879 		if ((flags & C_HARDCLOCK) == 0)
880 			to_sbt += tick_sbt;
881 	} else
882 		to_sbt = sbinuptime();
883 	if (SBT_MAX - to_sbt < sbt)
884 		to_sbt = SBT_MAX;
885 	else
886 		to_sbt += sbt;
887 	*res = to_sbt;
888 	to_pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
889 	    sbt >> C_PRELGET(flags));
890 	*prec_res = to_pr > precision ? to_pr : precision;
891 }
892 
893 /*
894  * New interface; clients allocate their own callout structures.
895  *
896  * callout_reset() - establish or change a timeout
897  * callout_stop() - disestablish a timeout
898  * callout_init() - initialize a callout structure so that it can
899  *	safely be passed to callout_reset() and callout_stop()
900  *
901  * <sys/callout.h> defines three convenience macros:
902  *
903  * callout_active() - returns truth if callout has not been stopped,
904  *	drained, or deactivated since the last time the callout was
905  *	reset.
906  * callout_pending() - returns truth if callout is still waiting for timeout
907  * callout_deactivate() - marks the callout as having been serviced
908  */
909 int
910 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t prec,
911     callout_func_t *ftn, void *arg, int cpu, int flags)
912 {
913 	sbintime_t to_sbt, precision;
914 	struct callout_cpu *cc;
915 	int cancelled, direct;
916 	int ignore_cpu=0;
917 
918 	cancelled = 0;
919 	if (cpu == -1) {
920 		ignore_cpu = 1;
921 	} else if ((cpu >= MAXCPU) ||
922 		   ((CC_CPU(cpu))->cc_inited == 0)) {
923 		/* Invalid CPU spec */
924 		panic("Invalid CPU in callout %d", cpu);
925 	}
926 	callout_when(sbt, prec, flags, &to_sbt, &precision);
927 
928 	/*
929 	 * This flag used to be added by callout_cc_add, but the
930 	 * first time you call this we could end up with the
931 	 * wrong direct flag if we don't do it before we add.
932 	 */
933 	if (flags & C_DIRECT_EXEC) {
934 		direct = 1;
935 	} else {
936 		direct = 0;
937 	}
938 	KASSERT(!direct || c->c_lock == NULL,
939 	    ("%s: direct callout %p has lock", __func__, c));
940 	cc = callout_lock(c);
941 	/*
942 	 * Don't allow migration if the user does not care.
943 	 */
944 	if (ignore_cpu) {
945 		cpu = c->c_cpu;
946 	}
947 
948 	if (cc_exec_curr(cc, direct) == c) {
949 		/*
950 		 * We're being asked to reschedule a callout which is
951 		 * currently in progress.  If there is a lock then we
952 		 * can cancel the callout if it has not really started.
953 		 */
954 		if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
955 			cancelled = cc_exec_cancel(cc, direct) = true;
956 		if (cc_exec_waiting(cc, direct) || cc_exec_drain(cc, direct)) {
957 			/*
958 			 * Someone has called callout_drain to kill this
959 			 * callout.  Don't reschedule.
960 			 */
961 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
962 			    cancelled ? "cancelled" : "failed to cancel",
963 			    c, c->c_func, c->c_arg);
964 			CC_UNLOCK(cc);
965 			return (cancelled);
966 		}
967 #ifdef SMP
968 		if (callout_migrating(c)) {
969 			/*
970 			 * This only occurs when a second callout_reset_sbt_on
971 			 * is made after a previous one moved it into
972 			 * deferred migration (below). Note we do *not* change
973 			 * the prev_cpu even though the previous target may
974 			 * be different.
975 			 */
976 			cc_migration_cpu(cc, direct) = cpu;
977 			cc_migration_time(cc, direct) = to_sbt;
978 			cc_migration_prec(cc, direct) = precision;
979 			cc_migration_func(cc, direct) = ftn;
980 			cc_migration_arg(cc, direct) = arg;
981 			cancelled = 1;
982 			CC_UNLOCK(cc);
983 			return (cancelled);
984 		}
985 #endif
986 	}
987 	if (c->c_iflags & CALLOUT_PENDING) {
988 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
989 			if (cc_exec_next(cc) == c)
990 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
991 			LIST_REMOVE(c, c_links.le);
992 		} else {
993 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
994 		}
995 		cancelled = 1;
996 		c->c_iflags &= ~ CALLOUT_PENDING;
997 		c->c_flags &= ~ CALLOUT_ACTIVE;
998 	}
999 
1000 #ifdef SMP
1001 	/*
1002 	 * If the callout must migrate try to perform it immediately.
1003 	 * If the callout is currently running, just defer the migration
1004 	 * to a more appropriate moment.
1005 	 */
1006 	if (c->c_cpu != cpu) {
1007 		if (cc_exec_curr(cc, direct) == c) {
1008 			/*
1009 			 * Pending will have been removed since we are
1010 			 * actually executing the callout on another
1011 			 * CPU. That callout should be waiting on the
1012 			 * lock the caller holds. If we set both
1013 			 * active/and/pending after we return and the
1014 			 * lock on the executing callout proceeds, it
1015 			 * will then see pending is true and return.
1016 			 * At the return from the actual callout execution
1017 			 * the migration will occur in softclock_call_cc
1018 			 * and this new callout will be placed on the
1019 			 * new CPU via a call to callout_cpu_switch() which
1020 			 * will get the lock on the right CPU followed
1021 			 * by a call callout_cc_add() which will add it there.
1022 			 * (see above in softclock_call_cc()).
1023 			 */
1024 			cc_migration_cpu(cc, direct) = cpu;
1025 			cc_migration_time(cc, direct) = to_sbt;
1026 			cc_migration_prec(cc, direct) = precision;
1027 			cc_migration_func(cc, direct) = ftn;
1028 			cc_migration_arg(cc, direct) = arg;
1029 			c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
1030 			c->c_flags |= CALLOUT_ACTIVE;
1031 			CTR6(KTR_CALLOUT,
1032 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1033 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1034 			    (u_int)(to_sbt & 0xffffffff), cpu);
1035 			CC_UNLOCK(cc);
1036 			return (cancelled);
1037 		}
1038 		cc = callout_cpu_switch(c, cc, cpu);
1039 	}
1040 #endif
1041 
1042 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1043 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1044 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1045 	    (u_int)(to_sbt & 0xffffffff));
1046 	CC_UNLOCK(cc);
1047 
1048 	return (cancelled);
1049 }
1050 
1051 /*
1052  * Common idioms that can be optimized in the future.
1053  */
1054 int
1055 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1056 {
1057 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1058 }
1059 
1060 int
1061 callout_schedule(struct callout *c, int to_ticks)
1062 {
1063 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1064 }
1065 
1066 int
1067 _callout_stop_safe(struct callout *c, int flags, callout_func_t *drain)
1068 {
1069 	struct callout_cpu *cc, *old_cc;
1070 	struct lock_class *class;
1071 	int direct, sq_locked, use_lock;
1072 	int cancelled, not_on_a_list;
1073 
1074 	if ((flags & CS_DRAIN) != 0)
1075 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, c->c_lock,
1076 		    "calling %s", __func__);
1077 
1078 	/*
1079 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1080 	 * so just discard this check for the moment.
1081 	 */
1082 	if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1083 		if (c->c_lock == &Giant.lock_object)
1084 			use_lock = mtx_owned(&Giant);
1085 		else {
1086 			use_lock = 1;
1087 			class = LOCK_CLASS(c->c_lock);
1088 			class->lc_assert(c->c_lock, LA_XLOCKED);
1089 		}
1090 	} else
1091 		use_lock = 0;
1092 	if (c->c_iflags & CALLOUT_DIRECT) {
1093 		direct = 1;
1094 	} else {
1095 		direct = 0;
1096 	}
1097 	sq_locked = 0;
1098 	old_cc = NULL;
1099 again:
1100 	cc = callout_lock(c);
1101 
1102 	if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
1103 	    (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
1104 	    ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1105 		/*
1106 		 * Special case where this slipped in while we
1107 		 * were migrating *as* the callout is about to
1108 		 * execute. The caller probably holds the lock
1109 		 * the callout wants.
1110 		 *
1111 		 * Get rid of the migration first. Then set
1112 		 * the flag that tells this code *not* to
1113 		 * try to remove it from any lists (its not
1114 		 * on one yet). When the callout wheel runs,
1115 		 * it will ignore this callout.
1116 		 */
1117 		c->c_iflags &= ~CALLOUT_PENDING;
1118 		c->c_flags &= ~CALLOUT_ACTIVE;
1119 		not_on_a_list = 1;
1120 	} else {
1121 		not_on_a_list = 0;
1122 	}
1123 
1124 	/*
1125 	 * If the callout was migrating while the callout cpu lock was
1126 	 * dropped,  just drop the sleepqueue lock and check the states
1127 	 * again.
1128 	 */
1129 	if (sq_locked != 0 && cc != old_cc) {
1130 #ifdef SMP
1131 		CC_UNLOCK(cc);
1132 		sleepq_release(&cc_exec_waiting(old_cc, direct));
1133 		sq_locked = 0;
1134 		old_cc = NULL;
1135 		goto again;
1136 #else
1137 		panic("migration should not happen");
1138 #endif
1139 	}
1140 
1141 	/*
1142 	 * If the callout is running, try to stop it or drain it.
1143 	 */
1144 	if (cc_exec_curr(cc, direct) == c) {
1145 		/*
1146 		 * Succeed we to stop it or not, we must clear the
1147 		 * active flag - this is what API users expect.  If we're
1148 		 * draining and the callout is currently executing, first wait
1149 		 * until it finishes.
1150 		 */
1151 		if ((flags & CS_DRAIN) == 0)
1152 			c->c_flags &= ~CALLOUT_ACTIVE;
1153 
1154 		if ((flags & CS_DRAIN) != 0) {
1155 			/*
1156 			 * The current callout is running (or just
1157 			 * about to run) and blocking is allowed, so
1158 			 * just wait for the current invocation to
1159 			 * finish.
1160 			 */
1161 			while (cc_exec_curr(cc, direct) == c) {
1162 				/*
1163 				 * Use direct calls to sleepqueue interface
1164 				 * instead of cv/msleep in order to avoid
1165 				 * a LOR between cc_lock and sleepqueue
1166 				 * chain spinlocks.  This piece of code
1167 				 * emulates a msleep_spin() call actually.
1168 				 *
1169 				 * If we already have the sleepqueue chain
1170 				 * locked, then we can safely block.  If we
1171 				 * don't already have it locked, however,
1172 				 * we have to drop the cc_lock to lock
1173 				 * it.  This opens several races, so we
1174 				 * restart at the beginning once we have
1175 				 * both locks.  If nothing has changed, then
1176 				 * we will end up back here with sq_locked
1177 				 * set.
1178 				 */
1179 				if (!sq_locked) {
1180 					CC_UNLOCK(cc);
1181 					sleepq_lock(
1182 					    &cc_exec_waiting(cc, direct));
1183 					sq_locked = 1;
1184 					old_cc = cc;
1185 					goto again;
1186 				}
1187 
1188 				/*
1189 				 * Migration could be cancelled here, but
1190 				 * as long as it is still not sure when it
1191 				 * will be packed up, just let softclock()
1192 				 * take care of it.
1193 				 */
1194 				cc_exec_waiting(cc, direct) = true;
1195 				DROP_GIANT();
1196 				CC_UNLOCK(cc);
1197 				sleepq_add(
1198 				    &cc_exec_waiting(cc, direct),
1199 				    &cc->cc_lock.lock_object, "codrain",
1200 				    SLEEPQ_SLEEP, 0);
1201 				sleepq_wait(
1202 				    &cc_exec_waiting(cc, direct),
1203 					     0);
1204 				sq_locked = 0;
1205 				old_cc = NULL;
1206 
1207 				/* Reacquire locks previously released. */
1208 				PICKUP_GIANT();
1209 				CC_LOCK(cc);
1210 			}
1211 			c->c_flags &= ~CALLOUT_ACTIVE;
1212 		} else if (use_lock &&
1213 			   !cc_exec_cancel(cc, direct) && (drain == NULL)) {
1214 
1215 			/*
1216 			 * The current callout is waiting for its
1217 			 * lock which we hold.  Cancel the callout
1218 			 * and return.  After our caller drops the
1219 			 * lock, the callout will be skipped in
1220 			 * softclock(). This *only* works with a
1221 			 * callout_stop() *not* callout_drain() or
1222 			 * callout_async_drain().
1223 			 */
1224 			cc_exec_cancel(cc, direct) = true;
1225 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1226 			    c, c->c_func, c->c_arg);
1227 			KASSERT(!cc_cce_migrating(cc, direct),
1228 			    ("callout wrongly scheduled for migration"));
1229 			if (callout_migrating(c)) {
1230 				c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1231 #ifdef SMP
1232 				cc_migration_cpu(cc, direct) = CPUBLOCK;
1233 				cc_migration_time(cc, direct) = 0;
1234 				cc_migration_prec(cc, direct) = 0;
1235 				cc_migration_func(cc, direct) = NULL;
1236 				cc_migration_arg(cc, direct) = NULL;
1237 #endif
1238 			}
1239 			CC_UNLOCK(cc);
1240 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1241 			return (1);
1242 		} else if (callout_migrating(c)) {
1243 			/*
1244 			 * The callout is currently being serviced
1245 			 * and the "next" callout is scheduled at
1246 			 * its completion with a migration. We remove
1247 			 * the migration flag so it *won't* get rescheduled,
1248 			 * but we can't stop the one thats running so
1249 			 * we return 0.
1250 			 */
1251 			c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1252 #ifdef SMP
1253 			/*
1254 			 * We can't call cc_cce_cleanup here since
1255 			 * if we do it will remove .ce_curr and
1256 			 * its still running. This will prevent a
1257 			 * reschedule of the callout when the
1258 			 * execution completes.
1259 			 */
1260 			cc_migration_cpu(cc, direct) = CPUBLOCK;
1261 			cc_migration_time(cc, direct) = 0;
1262 			cc_migration_prec(cc, direct) = 0;
1263 			cc_migration_func(cc, direct) = NULL;
1264 			cc_migration_arg(cc, direct) = NULL;
1265 #endif
1266 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1267 			    c, c->c_func, c->c_arg);
1268  			if (drain) {
1269 				cc_exec_drain(cc, direct) = drain;
1270 			}
1271 			CC_UNLOCK(cc);
1272 			return ((flags & CS_EXECUTING) != 0);
1273 		}
1274 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1275 		    c, c->c_func, c->c_arg);
1276 		if (drain) {
1277 			cc_exec_drain(cc, direct) = drain;
1278 		}
1279 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1280 		cancelled = ((flags & CS_EXECUTING) != 0);
1281 	} else
1282 		cancelled = 1;
1283 
1284 	if (sq_locked)
1285 		sleepq_release(&cc_exec_waiting(cc, direct));
1286 
1287 	if ((c->c_iflags & CALLOUT_PENDING) == 0) {
1288 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1289 		    c, c->c_func, c->c_arg);
1290 		/*
1291 		 * For not scheduled and not executing callout return
1292 		 * negative value.
1293 		 */
1294 		if (cc_exec_curr(cc, direct) != c)
1295 			cancelled = -1;
1296 		CC_UNLOCK(cc);
1297 		return (cancelled);
1298 	}
1299 
1300 	c->c_iflags &= ~CALLOUT_PENDING;
1301 	c->c_flags &= ~CALLOUT_ACTIVE;
1302 
1303 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1304 	    c, c->c_func, c->c_arg);
1305 	if (not_on_a_list == 0) {
1306 		if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1307 			if (cc_exec_next(cc) == c)
1308 				cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1309 			LIST_REMOVE(c, c_links.le);
1310 		} else {
1311 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1312 		}
1313 	}
1314 	CC_UNLOCK(cc);
1315 	return (cancelled);
1316 }
1317 
1318 void
1319 callout_init(struct callout *c, int mpsafe)
1320 {
1321 	bzero(c, sizeof *c);
1322 	if (mpsafe) {
1323 		c->c_lock = NULL;
1324 		c->c_iflags = CALLOUT_RETURNUNLOCKED;
1325 	} else {
1326 		c->c_lock = &Giant.lock_object;
1327 		c->c_iflags = 0;
1328 	}
1329 	c->c_cpu = cc_default_cpu;
1330 }
1331 
1332 void
1333 _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
1334 {
1335 	bzero(c, sizeof *c);
1336 	c->c_lock = lock;
1337 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1338 	    ("callout_init_lock: bad flags %d", flags));
1339 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1340 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1341 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1342 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1343 	    __func__));
1344 	c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1345 	c->c_cpu = cc_default_cpu;
1346 }
1347 
1348 #ifdef APM_FIXUP_CALLTODO
1349 /*
1350  * Adjust the kernel calltodo timeout list.  This routine is used after
1351  * an APM resume to recalculate the calltodo timer list values with the
1352  * number of hz's we have been sleeping.  The next hardclock() will detect
1353  * that there are fired timers and run softclock() to execute them.
1354  *
1355  * Please note, I have not done an exhaustive analysis of what code this
1356  * might break.  I am motivated to have my select()'s and alarm()'s that
1357  * have expired during suspend firing upon resume so that the applications
1358  * which set the timer can do the maintanence the timer was for as close
1359  * as possible to the originally intended time.  Testing this code for a
1360  * week showed that resuming from a suspend resulted in 22 to 25 timers
1361  * firing, which seemed independent on whether the suspend was 2 hours or
1362  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1363  */
1364 void
1365 adjust_timeout_calltodo(struct timeval *time_change)
1366 {
1367 	struct callout *p;
1368 	unsigned long delta_ticks;
1369 
1370 	/*
1371 	 * How many ticks were we asleep?
1372 	 * (stolen from tvtohz()).
1373 	 */
1374 
1375 	/* Don't do anything */
1376 	if (time_change->tv_sec < 0)
1377 		return;
1378 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
1379 		delta_ticks = howmany(time_change->tv_sec * 1000000 +
1380 		    time_change->tv_usec, tick) + 1;
1381 	else if (time_change->tv_sec <= LONG_MAX / hz)
1382 		delta_ticks = time_change->tv_sec * hz +
1383 		    howmany(time_change->tv_usec, tick) + 1;
1384 	else
1385 		delta_ticks = LONG_MAX;
1386 
1387 	if (delta_ticks > INT_MAX)
1388 		delta_ticks = INT_MAX;
1389 
1390 	/*
1391 	 * Now rip through the timer calltodo list looking for timers
1392 	 * to expire.
1393 	 */
1394 
1395 	/* don't collide with softclock() */
1396 	CC_LOCK(cc);
1397 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1398 		p->c_time -= delta_ticks;
1399 
1400 		/* Break if the timer had more time on it than delta_ticks */
1401 		if (p->c_time > 0)
1402 			break;
1403 
1404 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1405 		delta_ticks = -p->c_time;
1406 	}
1407 	CC_UNLOCK(cc);
1408 
1409 	return;
1410 }
1411 #endif /* APM_FIXUP_CALLTODO */
1412 
1413 static int
1414 flssbt(sbintime_t sbt)
1415 {
1416 
1417 	sbt += (uint64_t)sbt >> 1;
1418 	if (sizeof(long) >= sizeof(sbintime_t))
1419 		return (flsl(sbt));
1420 	if (sbt >= SBT_1S)
1421 		return (flsl(((uint64_t)sbt) >> 32) + 32);
1422 	return (flsl(sbt));
1423 }
1424 
1425 /*
1426  * Dump immediate statistic snapshot of the scheduled callouts.
1427  */
1428 static int
1429 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1430 {
1431 	struct callout *tmp;
1432 	struct callout_cpu *cc;
1433 	struct callout_list *sc;
1434 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1435 	int ct[64], cpr[64], ccpbk[32];
1436 	int error, val, i, count, tcum, pcum, maxc, c, medc;
1437 	int cpu;
1438 
1439 	val = 0;
1440 	error = sysctl_handle_int(oidp, &val, 0, req);
1441 	if (error != 0 || req->newptr == NULL)
1442 		return (error);
1443 	count = maxc = 0;
1444 	st = spr = maxt = maxpr = 0;
1445 	bzero(ccpbk, sizeof(ccpbk));
1446 	bzero(ct, sizeof(ct));
1447 	bzero(cpr, sizeof(cpr));
1448 	now = sbinuptime();
1449 	CPU_FOREACH(cpu) {
1450 		cc = CC_CPU(cpu);
1451 		CC_LOCK(cc);
1452 		for (i = 0; i < callwheelsize; i++) {
1453 			sc = &cc->cc_callwheel[i];
1454 			c = 0;
1455 			LIST_FOREACH(tmp, sc, c_links.le) {
1456 				c++;
1457 				t = tmp->c_time - now;
1458 				if (t < 0)
1459 					t = 0;
1460 				st += t / SBT_1US;
1461 				spr += tmp->c_precision / SBT_1US;
1462 				if (t > maxt)
1463 					maxt = t;
1464 				if (tmp->c_precision > maxpr)
1465 					maxpr = tmp->c_precision;
1466 				ct[flssbt(t)]++;
1467 				cpr[flssbt(tmp->c_precision)]++;
1468 			}
1469 			if (c > maxc)
1470 				maxc = c;
1471 			ccpbk[fls(c + c / 2)]++;
1472 			count += c;
1473 		}
1474 		CC_UNLOCK(cc);
1475 	}
1476 
1477 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1478 		tcum += ct[i];
1479 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1480 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1481 		pcum += cpr[i];
1482 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1483 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1484 		c += ccpbk[i];
1485 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
1486 
1487 	printf("Scheduled callouts statistic snapshot:\n");
1488 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1489 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1490 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1491 	    medc,
1492 	    count / callwheelsize / mp_ncpus,
1493 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1494 	    maxc);
1495 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1496 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1497 	    (st / count) / 1000000, (st / count) % 1000000,
1498 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1499 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1500 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1501 	    (spr / count) / 1000000, (spr / count) % 1000000,
1502 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1503 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1504 	    "   prec\t   pcum\n");
1505 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
1506 		if (ct[i] == 0 && cpr[i] == 0)
1507 			continue;
1508 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1509 		tcum += ct[i];
1510 		pcum += cpr[i];
1511 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1512 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1513 		    i - 1 - (32 - CC_HASH_SHIFT),
1514 		    ct[i], tcum, cpr[i], pcum);
1515 	}
1516 	return (error);
1517 }
1518 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1519     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1520     0, 0, sysctl_kern_callout_stat, "I",
1521     "Dump immediate statistic snapshot of the scheduled callouts");
1522 
1523 #ifdef DDB
1524 static void
1525 _show_callout(struct callout *c)
1526 {
1527 
1528 	db_printf("callout %p\n", c);
1529 #define	C_DB_PRINTF(f, e)	db_printf("   %s = " f "\n", #e, c->e);
1530 	db_printf("   &c_links = %p\n", &(c->c_links));
1531 	C_DB_PRINTF("%" PRId64,	c_time);
1532 	C_DB_PRINTF("%" PRId64,	c_precision);
1533 	C_DB_PRINTF("%p",	c_arg);
1534 	C_DB_PRINTF("%p",	c_func);
1535 	C_DB_PRINTF("%p",	c_lock);
1536 	C_DB_PRINTF("%#x",	c_flags);
1537 	C_DB_PRINTF("%#x",	c_iflags);
1538 	C_DB_PRINTF("%d",	c_cpu);
1539 #undef	C_DB_PRINTF
1540 }
1541 
1542 DB_SHOW_COMMAND(callout, db_show_callout)
1543 {
1544 
1545 	if (!have_addr) {
1546 		db_printf("usage: show callout <struct callout *>\n");
1547 		return;
1548 	}
1549 
1550 	_show_callout((struct callout *)addr);
1551 }
1552 
1553 static void
1554 _show_last_callout(int cpu, int direct, const char *dirstr)
1555 {
1556 	struct callout_cpu *cc;
1557 	void *func, *arg;
1558 
1559 	cc = CC_CPU(cpu);
1560 	func = cc_exec_last_func(cc, direct);
1561 	arg = cc_exec_last_arg(cc, direct);
1562 	db_printf("cpu %d last%s callout function: %p ", cpu, dirstr, func);
1563 	db_printsym((db_expr_t)func, DB_STGY_ANY);
1564 	db_printf("\ncpu %d last%s callout argument: %p\n", cpu, dirstr, arg);
1565 }
1566 
1567 DB_SHOW_COMMAND(callout_last, db_show_callout_last)
1568 {
1569 	int cpu, last;
1570 
1571 	if (have_addr) {
1572 		if (addr < 0 || addr > mp_maxid || CPU_ABSENT(addr)) {
1573 			db_printf("no such cpu: %d\n", (int)addr);
1574 			return;
1575 		}
1576 		cpu = last = addr;
1577 	} else {
1578 		cpu = 0;
1579 		last = mp_maxid;
1580 	}
1581 
1582 	while (cpu <= last) {
1583 		if (!CPU_ABSENT(cpu)) {
1584 			_show_last_callout(cpu, 0, "");
1585 			_show_last_callout(cpu, 1, " direct");
1586 		}
1587 		cpu++;
1588 	}
1589 }
1590 #endif /* DDB */
1591