xref: /freebsd/sys/kern/kern_timeout.c (revision 864c53ead899f7838cd2e1cca3b485a4a82f5cdc)
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(timeout_t *ftn, void *arg, int to_ticks)
877 {
878 	struct callout_cpu *cc;
879 	struct callout *new;
880 	struct callout_handle handle;
881 
882 	cc = CC_CPU(timeout_cpu);
883 	CC_LOCK(cc);
884 	/* Fill in the next free callout structure. */
885 	new = SLIST_FIRST(&cc->cc_callfree);
886 	if (new == NULL)
887 		/* XXX Attempt to malloc first */
888 		panic("timeout table full");
889 	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
890 	callout_reset(new, to_ticks, ftn, arg);
891 	handle.callout = new;
892 	CC_UNLOCK(cc);
893 
894 	return (handle);
895 }
896 
897 void
898 untimeout(timeout_t *ftn, void *arg, struct callout_handle handle)
899 {
900 	struct callout_cpu *cc;
901 
902 	/*
903 	 * Check for a handle that was initialized
904 	 * by callout_handle_init, but never used
905 	 * for a real timeout.
906 	 */
907 	if (handle.callout == NULL)
908 		return;
909 
910 	cc = callout_lock(handle.callout);
911 	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
912 		callout_stop(handle.callout);
913 	CC_UNLOCK(cc);
914 }
915 
916 void
917 callout_handle_init(struct callout_handle *handle)
918 {
919 	handle->callout = NULL;
920 }
921 
922 /*
923  * New interface; clients allocate their own callout structures.
924  *
925  * callout_reset() - establish or change a timeout
926  * callout_stop() - disestablish a timeout
927  * callout_init() - initialize a callout structure so that it can
928  *	safely be passed to callout_reset() and callout_stop()
929  *
930  * <sys/callout.h> defines three convenience macros:
931  *
932  * callout_active() - returns truth if callout has not been stopped,
933  *	drained, or deactivated since the last time the callout was
934  *	reset.
935  * callout_pending() - returns truth if callout is still waiting for timeout
936  * callout_deactivate() - marks the callout as having been serviced
937  */
938 int
939 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
940     void (*ftn)(void *), void *arg, int cpu, int flags)
941 {
942 	sbintime_t to_sbt, pr;
943 	struct callout_cpu *cc;
944 	int cancelled, direct;
945 
946 	cancelled = 0;
947 	if (flags & C_ABSOLUTE) {
948 		to_sbt = sbt;
949 	} else {
950 		if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
951 			sbt = tick_sbt;
952 		if ((flags & C_HARDCLOCK) ||
953 #ifdef NO_EVENTTIMERS
954 		    sbt >= sbt_timethreshold) {
955 			to_sbt = getsbinuptime();
956 
957 			/* Add safety belt for the case of hz > 1000. */
958 			to_sbt += tc_tick_sbt - tick_sbt;
959 #else
960 		    sbt >= sbt_tickthreshold) {
961 			/*
962 			 * Obtain the time of the last hardclock() call on
963 			 * this CPU directly from the kern_clocksource.c.
964 			 * This value is per-CPU, but it is equal for all
965 			 * active ones.
966 			 */
967 #ifdef __LP64__
968 			to_sbt = DPCPU_GET(hardclocktime);
969 #else
970 			spinlock_enter();
971 			to_sbt = DPCPU_GET(hardclocktime);
972 			spinlock_exit();
973 #endif
974 #endif
975 			if ((flags & C_HARDCLOCK) == 0)
976 				to_sbt += tick_sbt;
977 		} else
978 			to_sbt = sbinuptime();
979 		if (SBT_MAX - to_sbt < sbt)
980 			to_sbt = SBT_MAX;
981 		else
982 			to_sbt += sbt;
983 		pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
984 		    sbt >> C_PRELGET(flags));
985 		if (pr > precision)
986 			precision = pr;
987 	}
988 	/*
989 	 * Don't allow migration of pre-allocated callouts lest they
990 	 * become unbalanced.
991 	 */
992 	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
993 		cpu = c->c_cpu;
994 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
995 	KASSERT(!direct || c->c_lock == NULL,
996 	    ("%s: direct callout %p has lock", __func__, c));
997 	cc = callout_lock(c);
998 	if (cc->cc_exec_entity[direct].cc_curr == c) {
999 		/*
1000 		 * We're being asked to reschedule a callout which is
1001 		 * currently in progress.  If there is a lock then we
1002 		 * can cancel the callout if it has not really started.
1003 		 */
1004 		if (c->c_lock != NULL && !cc->cc_exec_entity[direct].cc_cancel)
1005 			cancelled = cc->cc_exec_entity[direct].cc_cancel = true;
1006 		if (cc->cc_exec_entity[direct].cc_waiting) {
1007 			/*
1008 			 * Someone has called callout_drain to kill this
1009 			 * callout.  Don't reschedule.
1010 			 */
1011 			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1012 			    cancelled ? "cancelled" : "failed to cancel",
1013 			    c, c->c_func, c->c_arg);
1014 			CC_UNLOCK(cc);
1015 			return (cancelled);
1016 		}
1017 	}
1018 	if (c->c_flags & CALLOUT_PENDING) {
1019 		if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1020 			if (cc->cc_exec_next_dir == c)
1021 				cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1022 			LIST_REMOVE(c, c_links.le);
1023 		} else
1024 			TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1025 		cancelled = 1;
1026 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1027 	}
1028 
1029 #ifdef SMP
1030 	/*
1031 	 * If the callout must migrate try to perform it immediately.
1032 	 * If the callout is currently running, just defer the migration
1033 	 * to a more appropriate moment.
1034 	 */
1035 	if (c->c_cpu != cpu) {
1036 		if (cc->cc_exec_entity[direct].cc_curr == c) {
1037 			cc->cc_exec_entity[direct].ce_migration_cpu = cpu;
1038 			cc->cc_exec_entity[direct].ce_migration_time
1039 			    = to_sbt;
1040 			cc->cc_exec_entity[direct].ce_migration_prec
1041 			    = precision;
1042 			cc->cc_exec_entity[direct].ce_migration_func = ftn;
1043 			cc->cc_exec_entity[direct].ce_migration_arg = arg;
1044 			c->c_flags |= CALLOUT_DFRMIGRATION;
1045 			CTR6(KTR_CALLOUT,
1046 		    "migration of %p func %p arg %p in %d.%08x to %u deferred",
1047 			    c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1048 			    (u_int)(to_sbt & 0xffffffff), cpu);
1049 			CC_UNLOCK(cc);
1050 			return (cancelled);
1051 		}
1052 		cc = callout_cpu_switch(c, cc, cpu);
1053 	}
1054 #endif
1055 
1056 	callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1057 	CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1058 	    cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1059 	    (u_int)(to_sbt & 0xffffffff));
1060 	CC_UNLOCK(cc);
1061 
1062 	return (cancelled);
1063 }
1064 
1065 /*
1066  * Common idioms that can be optimized in the future.
1067  */
1068 int
1069 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1070 {
1071 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1072 }
1073 
1074 int
1075 callout_schedule(struct callout *c, int to_ticks)
1076 {
1077 	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1078 }
1079 
1080 int
1081 _callout_stop_safe(struct callout *c, int safe)
1082 {
1083 	struct callout_cpu *cc, *old_cc;
1084 	struct lock_class *class;
1085 	int direct, sq_locked, use_lock;
1086 
1087 	/*
1088 	 * Some old subsystems don't hold Giant while running a callout_stop(),
1089 	 * so just discard this check for the moment.
1090 	 */
1091 	if (!safe && c->c_lock != NULL) {
1092 		if (c->c_lock == &Giant.lock_object)
1093 			use_lock = mtx_owned(&Giant);
1094 		else {
1095 			use_lock = 1;
1096 			class = LOCK_CLASS(c->c_lock);
1097 			class->lc_assert(c->c_lock, LA_XLOCKED);
1098 		}
1099 	} else
1100 		use_lock = 0;
1101 	direct = (c->c_flags & CALLOUT_DIRECT) != 0;
1102 	sq_locked = 0;
1103 	old_cc = NULL;
1104 again:
1105 	cc = callout_lock(c);
1106 
1107 	/*
1108 	 * If the callout was migrating while the callout cpu lock was
1109 	 * dropped,  just drop the sleepqueue lock and check the states
1110 	 * again.
1111 	 */
1112 	if (sq_locked != 0 && cc != old_cc) {
1113 #ifdef SMP
1114 		CC_UNLOCK(cc);
1115 		sleepq_release(&old_cc->cc_exec_entity[direct].cc_waiting);
1116 		sq_locked = 0;
1117 		old_cc = NULL;
1118 		goto again;
1119 #else
1120 		panic("migration should not happen");
1121 #endif
1122 	}
1123 
1124 	/*
1125 	 * If the callout isn't pending, it's not on the queue, so
1126 	 * don't attempt to remove it from the queue.  We can try to
1127 	 * stop it by other means however.
1128 	 */
1129 	if (!(c->c_flags & CALLOUT_PENDING)) {
1130 		c->c_flags &= ~CALLOUT_ACTIVE;
1131 
1132 		/*
1133 		 * If it wasn't on the queue and it isn't the current
1134 		 * callout, then we can't stop it, so just bail.
1135 		 */
1136 		if (cc->cc_exec_entity[direct].cc_curr != c) {
1137 			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1138 			    c, c->c_func, c->c_arg);
1139 			CC_UNLOCK(cc);
1140 			if (sq_locked)
1141 				sleepq_release(
1142 				    &cc->cc_exec_entity[direct].cc_waiting);
1143 			return (0);
1144 		}
1145 
1146 		if (safe) {
1147 			/*
1148 			 * The current callout is running (or just
1149 			 * about to run) and blocking is allowed, so
1150 			 * just wait for the current invocation to
1151 			 * finish.
1152 			 */
1153 			while (cc->cc_exec_entity[direct].cc_curr == c) {
1154 				/*
1155 				 * Use direct calls to sleepqueue interface
1156 				 * instead of cv/msleep in order to avoid
1157 				 * a LOR between cc_lock and sleepqueue
1158 				 * chain spinlocks.  This piece of code
1159 				 * emulates a msleep_spin() call actually.
1160 				 *
1161 				 * If we already have the sleepqueue chain
1162 				 * locked, then we can safely block.  If we
1163 				 * don't already have it locked, however,
1164 				 * we have to drop the cc_lock to lock
1165 				 * it.  This opens several races, so we
1166 				 * restart at the beginning once we have
1167 				 * both locks.  If nothing has changed, then
1168 				 * we will end up back here with sq_locked
1169 				 * set.
1170 				 */
1171 				if (!sq_locked) {
1172 					CC_UNLOCK(cc);
1173 					sleepq_lock(
1174 					&cc->cc_exec_entity[direct].cc_waiting);
1175 					sq_locked = 1;
1176 					old_cc = cc;
1177 					goto again;
1178 				}
1179 
1180 				/*
1181 				 * Migration could be cancelled here, but
1182 				 * as long as it is still not sure when it
1183 				 * will be packed up, just let softclock()
1184 				 * take care of it.
1185 				 */
1186 				cc->cc_exec_entity[direct].cc_waiting = true;
1187 				DROP_GIANT();
1188 				CC_UNLOCK(cc);
1189 				sleepq_add(
1190 				    &cc->cc_exec_entity[direct].cc_waiting,
1191 				    &cc->cc_lock.lock_object, "codrain",
1192 				    SLEEPQ_SLEEP, 0);
1193 				sleepq_wait(
1194 				    &cc->cc_exec_entity[direct].cc_waiting,
1195 					     0);
1196 				sq_locked = 0;
1197 				old_cc = NULL;
1198 
1199 				/* Reacquire locks previously released. */
1200 				PICKUP_GIANT();
1201 				CC_LOCK(cc);
1202 			}
1203 		} else if (use_lock &&
1204 			    !cc->cc_exec_entity[direct].cc_cancel) {
1205 			/*
1206 			 * The current callout is waiting for its
1207 			 * lock which we hold.  Cancel the callout
1208 			 * and return.  After our caller drops the
1209 			 * lock, the callout will be skipped in
1210 			 * softclock().
1211 			 */
1212 			cc->cc_exec_entity[direct].cc_cancel = true;
1213 			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1214 			    c, c->c_func, c->c_arg);
1215 			KASSERT(!cc_cce_migrating(cc, direct),
1216 			    ("callout wrongly scheduled for migration"));
1217 			CC_UNLOCK(cc);
1218 			KASSERT(!sq_locked, ("sleepqueue chain locked"));
1219 			return (1);
1220 		} else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
1221 			c->c_flags &= ~CALLOUT_DFRMIGRATION;
1222 			CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1223 			    c, c->c_func, c->c_arg);
1224 			CC_UNLOCK(cc);
1225 			return (1);
1226 		}
1227 		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1228 		    c, c->c_func, c->c_arg);
1229 		CC_UNLOCK(cc);
1230 		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1231 		return (0);
1232 	}
1233 	if (sq_locked)
1234 		sleepq_release(&cc->cc_exec_entity[direct].cc_waiting);
1235 
1236 	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1237 
1238 	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1239 	    c, c->c_func, c->c_arg);
1240 	if ((c->c_flags & CALLOUT_PROCESSED) == 0) {
1241 		if (cc->cc_exec_next_dir == c)
1242 			cc->cc_exec_next_dir = LIST_NEXT(c, c_links.le);
1243 		LIST_REMOVE(c, c_links.le);
1244 	} else
1245 		TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1246 	callout_cc_del(c, cc);
1247 
1248 	CC_UNLOCK(cc);
1249 	return (1);
1250 }
1251 
1252 void
1253 callout_init(struct callout *c, int mpsafe)
1254 {
1255 	bzero(c, sizeof *c);
1256 	if (mpsafe) {
1257 		c->c_lock = NULL;
1258 		c->c_flags = CALLOUT_RETURNUNLOCKED;
1259 	} else {
1260 		c->c_lock = &Giant.lock_object;
1261 		c->c_flags = 0;
1262 	}
1263 	c->c_cpu = timeout_cpu;
1264 }
1265 
1266 void
1267 _callout_init_lock(struct callout *c, struct lock_object *lock, int flags)
1268 {
1269 	bzero(c, sizeof *c);
1270 	c->c_lock = lock;
1271 	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1272 	    ("callout_init_lock: bad flags %d", flags));
1273 	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1274 	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1275 	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1276 	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1277 	    __func__));
1278 	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1279 	c->c_cpu = timeout_cpu;
1280 }
1281 
1282 #ifdef APM_FIXUP_CALLTODO
1283 /*
1284  * Adjust the kernel calltodo timeout list.  This routine is used after
1285  * an APM resume to recalculate the calltodo timer list values with the
1286  * number of hz's we have been sleeping.  The next hardclock() will detect
1287  * that there are fired timers and run softclock() to execute them.
1288  *
1289  * Please note, I have not done an exhaustive analysis of what code this
1290  * might break.  I am motivated to have my select()'s and alarm()'s that
1291  * have expired during suspend firing upon resume so that the applications
1292  * which set the timer can do the maintanence the timer was for as close
1293  * as possible to the originally intended time.  Testing this code for a
1294  * week showed that resuming from a suspend resulted in 22 to 25 timers
1295  * firing, which seemed independant on whether the suspend was 2 hours or
1296  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1297  */
1298 void
1299 adjust_timeout_calltodo(struct timeval *time_change)
1300 {
1301 	register struct callout *p;
1302 	unsigned long delta_ticks;
1303 
1304 	/*
1305 	 * How many ticks were we asleep?
1306 	 * (stolen from tvtohz()).
1307 	 */
1308 
1309 	/* Don't do anything */
1310 	if (time_change->tv_sec < 0)
1311 		return;
1312 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
1313 		delta_ticks = (time_change->tv_sec * 1000000 +
1314 			       time_change->tv_usec + (tick - 1)) / tick + 1;
1315 	else if (time_change->tv_sec <= LONG_MAX / hz)
1316 		delta_ticks = time_change->tv_sec * hz +
1317 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
1318 	else
1319 		delta_ticks = LONG_MAX;
1320 
1321 	if (delta_ticks > INT_MAX)
1322 		delta_ticks = INT_MAX;
1323 
1324 	/*
1325 	 * Now rip through the timer calltodo list looking for timers
1326 	 * to expire.
1327 	 */
1328 
1329 	/* don't collide with softclock() */
1330 	CC_LOCK(cc);
1331 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1332 		p->c_time -= delta_ticks;
1333 
1334 		/* Break if the timer had more time on it than delta_ticks */
1335 		if (p->c_time > 0)
1336 			break;
1337 
1338 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
1339 		delta_ticks = -p->c_time;
1340 	}
1341 	CC_UNLOCK(cc);
1342 
1343 	return;
1344 }
1345 #endif /* APM_FIXUP_CALLTODO */
1346 
1347 static int
1348 flssbt(sbintime_t sbt)
1349 {
1350 
1351 	sbt += (uint64_t)sbt >> 1;
1352 	if (sizeof(long) >= sizeof(sbintime_t))
1353 		return (flsl(sbt));
1354 	if (sbt >= SBT_1S)
1355 		return (flsl(((uint64_t)sbt) >> 32) + 32);
1356 	return (flsl(sbt));
1357 }
1358 
1359 /*
1360  * Dump immediate statistic snapshot of the scheduled callouts.
1361  */
1362 static int
1363 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1364 {
1365 	struct callout *tmp;
1366 	struct callout_cpu *cc;
1367 	struct callout_list *sc;
1368 	sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1369 	int ct[64], cpr[64], ccpbk[32];
1370 	int error, val, i, count, tcum, pcum, maxc, c, medc;
1371 #ifdef SMP
1372 	int cpu;
1373 #endif
1374 
1375 	val = 0;
1376 	error = sysctl_handle_int(oidp, &val, 0, req);
1377 	if (error != 0 || req->newptr == NULL)
1378 		return (error);
1379 	count = maxc = 0;
1380 	st = spr = maxt = maxpr = 0;
1381 	bzero(ccpbk, sizeof(ccpbk));
1382 	bzero(ct, sizeof(ct));
1383 	bzero(cpr, sizeof(cpr));
1384 	now = sbinuptime();
1385 #ifdef SMP
1386 	CPU_FOREACH(cpu) {
1387 		cc = CC_CPU(cpu);
1388 #else
1389 		cc = CC_CPU(timeout_cpu);
1390 #endif
1391 		CC_LOCK(cc);
1392 		for (i = 0; i < callwheelsize; i++) {
1393 			sc = &cc->cc_callwheel[i];
1394 			c = 0;
1395 			LIST_FOREACH(tmp, sc, c_links.le) {
1396 				c++;
1397 				t = tmp->c_time - now;
1398 				if (t < 0)
1399 					t = 0;
1400 				st += t / SBT_1US;
1401 				spr += tmp->c_precision / SBT_1US;
1402 				if (t > maxt)
1403 					maxt = t;
1404 				if (tmp->c_precision > maxpr)
1405 					maxpr = tmp->c_precision;
1406 				ct[flssbt(t)]++;
1407 				cpr[flssbt(tmp->c_precision)]++;
1408 			}
1409 			if (c > maxc)
1410 				maxc = c;
1411 			ccpbk[fls(c + c / 2)]++;
1412 			count += c;
1413 		}
1414 		CC_UNLOCK(cc);
1415 #ifdef SMP
1416 	}
1417 #endif
1418 
1419 	for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1420 		tcum += ct[i];
1421 	medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1422 	for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1423 		pcum += cpr[i];
1424 	medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1425 	for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1426 		c += ccpbk[i];
1427 	medc = (i >= 2) ? (1 << (i - 2)) : 0;
1428 
1429 	printf("Scheduled callouts statistic snapshot:\n");
1430 	printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1431 	    count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1432 	printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1433 	    medc,
1434 	    count / callwheelsize / mp_ncpus,
1435 	    (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1436 	    maxc);
1437 	printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1438 	    medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1439 	    (st / count) / 1000000, (st / count) % 1000000,
1440 	    maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1441 	printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1442 	    medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1443 	    (spr / count) / 1000000, (spr / count) % 1000000,
1444 	    maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1445 	printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1446 	    "   prec\t   pcum\n");
1447 	for (i = 0, tcum = pcum = 0; i < 64; i++) {
1448 		if (ct[i] == 0 && cpr[i] == 0)
1449 			continue;
1450 		t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1451 		tcum += ct[i];
1452 		pcum += cpr[i];
1453 		printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1454 		    t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1455 		    i - 1 - (32 - CC_HASH_SHIFT),
1456 		    ct[i], tcum, cpr[i], pcum);
1457 	}
1458 	return (error);
1459 }
1460 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1461     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1462     0, 0, sysctl_kern_callout_stat, "I",
1463     "Dump immediate statistic snapshot of the scheduled callouts");
1464