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