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