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