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