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