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