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