xref: /netbsd-src/sys/kern/kern_timeout.c (revision 0e552da7216834a96e91ad098e59272b41087480)
1 /*	$NetBSD: kern_timeout.c,v 1.61 2020/04/19 20:35:29 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 2003, 2006, 2007, 2008, 2009, 2019 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe, and by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c) 2001 Thomas Nordin <nordin@openbsd.org>
34  * Copyright (c) 2000-2001 Artur Grabowski <art@openbsd.org>
35  * All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  *
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. The name of the author may not be used to endorse or promote products
47  *    derived from this software without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
50  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
51  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
52  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
53  * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
54  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
55  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
56  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
57  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
58  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60 
61 #include <sys/cdefs.h>
62 __KERNEL_RCSID(0, "$NetBSD: kern_timeout.c,v 1.61 2020/04/19 20:35:29 ad Exp $");
63 
64 /*
65  * Timeouts are kept in a hierarchical timing wheel.  The c_time is the
66  * value of c_cpu->cc_ticks when the timeout should be called.  There are
67  * four levels with 256 buckets each. See 'Scheme 7' in "Hashed and
68  * Hierarchical Timing Wheels: Efficient Data Structures for Implementing
69  * a Timer Facility" by George Varghese and Tony Lauck.
70  *
71  * Some of the "math" in here is a bit tricky.  We have to beware of
72  * wrapping ints.
73  *
74  * We use the fact that any element added to the queue must be added with
75  * a positive time.  That means that any element `to' on the queue cannot
76  * be scheduled to timeout further in time than INT_MAX, but c->c_time can
77  * be positive or negative so comparing it with anything is dangerous.
78  * The only way we can use the c->c_time value in any predictable way is
79  * when we calculate how far in the future `to' will timeout - "c->c_time
80  * - c->c_cpu->cc_ticks".  The result will always be positive for future
81  * timeouts and 0 or negative for due timeouts.
82  */
83 
84 #define	_CALLOUT_PRIVATE
85 
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/kernel.h>
89 #include <sys/callout.h>
90 #include <sys/lwp.h>
91 #include <sys/mutex.h>
92 #include <sys/proc.h>
93 #include <sys/sleepq.h>
94 #include <sys/syncobj.h>
95 #include <sys/evcnt.h>
96 #include <sys/intr.h>
97 #include <sys/cpu.h>
98 #include <sys/kmem.h>
99 
100 #ifdef DDB
101 #include <machine/db_machdep.h>
102 #include <ddb/db_interface.h>
103 #include <ddb/db_access.h>
104 #include <ddb/db_cpu.h>
105 #include <ddb/db_sym.h>
106 #include <ddb/db_output.h>
107 #endif
108 
109 #define BUCKETS		1024
110 #define WHEELSIZE	256
111 #define WHEELMASK	255
112 #define WHEELBITS	8
113 
114 #define MASKWHEEL(wheel, time) (((time) >> ((wheel)*WHEELBITS)) & WHEELMASK)
115 
116 #define BUCKET(cc, rel, abs)						\
117     (((rel) <= (1 << (2*WHEELBITS)))					\
118     	? ((rel) <= (1 << WHEELBITS))					\
119             ? &(cc)->cc_wheel[MASKWHEEL(0, (abs))]			\
120             : &(cc)->cc_wheel[MASKWHEEL(1, (abs)) + WHEELSIZE]		\
121         : ((rel) <= (1 << (3*WHEELBITS)))				\
122             ? &(cc)->cc_wheel[MASKWHEEL(2, (abs)) + 2*WHEELSIZE]	\
123             : &(cc)->cc_wheel[MASKWHEEL(3, (abs)) + 3*WHEELSIZE])
124 
125 #define MOVEBUCKET(cc, wheel, time)					\
126     CIRCQ_APPEND(&(cc)->cc_todo,					\
127         &(cc)->cc_wheel[MASKWHEEL((wheel), (time)) + (wheel)*WHEELSIZE])
128 
129 /*
130  * Circular queue definitions.
131  */
132 
133 #define CIRCQ_INIT(list)						\
134 do {									\
135         (list)->cq_next_l = (list);					\
136         (list)->cq_prev_l = (list);					\
137 } while (/*CONSTCOND*/0)
138 
139 #define CIRCQ_INSERT(elem, list)					\
140 do {									\
141         (elem)->cq_prev_e = (list)->cq_prev_e;				\
142         (elem)->cq_next_l = (list);					\
143         (list)->cq_prev_l->cq_next_l = (elem);				\
144         (list)->cq_prev_l = (elem);					\
145 } while (/*CONSTCOND*/0)
146 
147 #define CIRCQ_APPEND(fst, snd)						\
148 do {									\
149         if (!CIRCQ_EMPTY(snd)) {					\
150                 (fst)->cq_prev_l->cq_next_l = (snd)->cq_next_l;		\
151                 (snd)->cq_next_l->cq_prev_l = (fst)->cq_prev_l;		\
152                 (snd)->cq_prev_l->cq_next_l = (fst);			\
153                 (fst)->cq_prev_l = (snd)->cq_prev_l;			\
154                 CIRCQ_INIT(snd);					\
155         }								\
156 } while (/*CONSTCOND*/0)
157 
158 #define CIRCQ_REMOVE(elem)						\
159 do {									\
160         (elem)->cq_next_l->cq_prev_e = (elem)->cq_prev_e;		\
161         (elem)->cq_prev_l->cq_next_e = (elem)->cq_next_e;		\
162 } while (/*CONSTCOND*/0)
163 
164 #define CIRCQ_FIRST(list)	((list)->cq_next_e)
165 #define CIRCQ_NEXT(elem)	((elem)->cq_next_e)
166 #define CIRCQ_LAST(elem,list)	((elem)->cq_next_l == (list))
167 #define CIRCQ_EMPTY(list)	((list)->cq_next_l == (list))
168 
169 struct callout_cpu {
170 	kmutex_t	*cc_lock;
171 	sleepq_t	cc_sleepq;
172 	u_int		cc_nwait;
173 	u_int		cc_ticks;
174 	lwp_t		*cc_lwp;
175 	callout_impl_t	*cc_active;
176 	callout_impl_t	*cc_cancel;
177 	struct evcnt	cc_ev_late;
178 	struct evcnt	cc_ev_block;
179 	struct callout_circq cc_todo;		/* Worklist */
180 	struct callout_circq cc_wheel[BUCKETS];	/* Queues of timeouts */
181 	char		cc_name1[12];
182 	char		cc_name2[12];
183 };
184 
185 #ifndef CRASH
186 
187 static void	callout_softclock(void *);
188 static void	callout_wait(callout_impl_t *, void *, kmutex_t *);
189 
190 static struct callout_cpu callout_cpu0 __cacheline_aligned;
191 static void *callout_sih __read_mostly;
192 
193 static inline kmutex_t *
194 callout_lock(callout_impl_t *c)
195 {
196 	struct callout_cpu *cc;
197 	kmutex_t *lock;
198 
199 	for (;;) {
200 		cc = c->c_cpu;
201 		lock = cc->cc_lock;
202 		mutex_spin_enter(lock);
203 		if (__predict_true(cc == c->c_cpu))
204 			return lock;
205 		mutex_spin_exit(lock);
206 	}
207 }
208 
209 /*
210  * callout_startup:
211  *
212  *	Initialize the callout facility, called at system startup time.
213  *	Do just enough to allow callouts to be safely registered.
214  */
215 void
216 callout_startup(void)
217 {
218 	struct callout_cpu *cc;
219 	int b;
220 
221 	KASSERT(curcpu()->ci_data.cpu_callout == NULL);
222 
223 	cc = &callout_cpu0;
224 	cc->cc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
225 	CIRCQ_INIT(&cc->cc_todo);
226 	for (b = 0; b < BUCKETS; b++)
227 		CIRCQ_INIT(&cc->cc_wheel[b]);
228 	curcpu()->ci_data.cpu_callout = cc;
229 }
230 
231 /*
232  * callout_init_cpu:
233  *
234  *	Per-CPU initialization.
235  */
236 CTASSERT(sizeof(callout_impl_t) <= sizeof(callout_t));
237 
238 void
239 callout_init_cpu(struct cpu_info *ci)
240 {
241 	struct callout_cpu *cc;
242 	int b;
243 
244 	if ((cc = ci->ci_data.cpu_callout) == NULL) {
245 		cc = kmem_zalloc(sizeof(*cc), KM_SLEEP);
246 		cc->cc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_SCHED);
247 		CIRCQ_INIT(&cc->cc_todo);
248 		for (b = 0; b < BUCKETS; b++)
249 			CIRCQ_INIT(&cc->cc_wheel[b]);
250 	} else {
251 		/* Boot CPU, one time only. */
252 		callout_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
253 		    callout_softclock, NULL);
254 		if (callout_sih == NULL)
255 			panic("callout_init_cpu (2)");
256 	}
257 
258 	sleepq_init(&cc->cc_sleepq);
259 
260 	snprintf(cc->cc_name1, sizeof(cc->cc_name1), "late/%u",
261 	    cpu_index(ci));
262 	evcnt_attach_dynamic(&cc->cc_ev_late, EVCNT_TYPE_MISC,
263 	    NULL, "callout", cc->cc_name1);
264 
265 	snprintf(cc->cc_name2, sizeof(cc->cc_name2), "wait/%u",
266 	    cpu_index(ci));
267 	evcnt_attach_dynamic(&cc->cc_ev_block, EVCNT_TYPE_MISC,
268 	    NULL, "callout", cc->cc_name2);
269 
270 	ci->ci_data.cpu_callout = cc;
271 }
272 
273 /*
274  * callout_init:
275  *
276  *	Initialize a callout structure.  This must be quick, so we fill
277  *	only the minimum number of fields.
278  */
279 void
280 callout_init(callout_t *cs, u_int flags)
281 {
282 	callout_impl_t *c = (callout_impl_t *)cs;
283 	struct callout_cpu *cc;
284 
285 	KASSERT((flags & ~CALLOUT_FLAGMASK) == 0);
286 
287 	cc = curcpu()->ci_data.cpu_callout;
288 	c->c_func = NULL;
289 	c->c_magic = CALLOUT_MAGIC;
290 	if (__predict_true((flags & CALLOUT_MPSAFE) != 0 && cc != NULL)) {
291 		c->c_flags = flags;
292 		c->c_cpu = cc;
293 		return;
294 	}
295 	c->c_flags = flags | CALLOUT_BOUND;
296 	c->c_cpu = &callout_cpu0;
297 }
298 
299 /*
300  * callout_destroy:
301  *
302  *	Destroy a callout structure.  The callout must be stopped.
303  */
304 void
305 callout_destroy(callout_t *cs)
306 {
307 	callout_impl_t *c = (callout_impl_t *)cs;
308 
309 	KASSERTMSG(c->c_magic == CALLOUT_MAGIC,
310 	    "callout %p: c_magic (%#x) != CALLOUT_MAGIC (%#x)",
311 	    c, c->c_magic, CALLOUT_MAGIC);
312 	/*
313 	 * It's not necessary to lock in order to see the correct value
314 	 * of c->c_flags.  If the callout could potentially have been
315 	 * running, the current thread should have stopped it.
316 	 */
317 	KASSERTMSG((c->c_flags & CALLOUT_PENDING) == 0,
318 	    "pending callout %p: c_func (%p) c_flags (%#x) destroyed from %p",
319 	    c, c->c_func, c->c_flags, __builtin_return_address(0));
320 	KASSERTMSG(c->c_cpu->cc_lwp == curlwp || c->c_cpu->cc_active != c,
321 	    "running callout %p: c_func (%p) c_flags (%#x) destroyed from %p",
322 	    c, c->c_func, c->c_flags, __builtin_return_address(0));
323 	c->c_magic = 0;
324 }
325 
326 /*
327  * callout_schedule_locked:
328  *
329  *	Schedule a callout to run.  The function and argument must
330  *	already be set in the callout structure.  Must be called with
331  *	callout_lock.
332  */
333 static void
334 callout_schedule_locked(callout_impl_t *c, kmutex_t *lock, int to_ticks)
335 {
336 	struct callout_cpu *cc, *occ;
337 	int old_time;
338 
339 	KASSERT(to_ticks >= 0);
340 	KASSERT(c->c_func != NULL);
341 
342 	/* Initialize the time here, it won't change. */
343 	occ = c->c_cpu;
344 	c->c_flags &= ~(CALLOUT_FIRED | CALLOUT_INVOKING);
345 
346 	/*
347 	 * If this timeout is already scheduled and now is moved
348 	 * earlier, reschedule it now.  Otherwise leave it in place
349 	 * and let it be rescheduled later.
350 	 */
351 	if ((c->c_flags & CALLOUT_PENDING) != 0) {
352 		/* Leave on existing CPU. */
353 		old_time = c->c_time;
354 		c->c_time = to_ticks + occ->cc_ticks;
355 		if (c->c_time - old_time < 0) {
356 			CIRCQ_REMOVE(&c->c_list);
357 			CIRCQ_INSERT(&c->c_list, &occ->cc_todo);
358 		}
359 		mutex_spin_exit(lock);
360 		return;
361 	}
362 
363 	cc = curcpu()->ci_data.cpu_callout;
364 	if ((c->c_flags & CALLOUT_BOUND) != 0 || cc == occ ||
365 	    !mutex_tryenter(cc->cc_lock)) {
366 		/* Leave on existing CPU. */
367 		c->c_time = to_ticks + occ->cc_ticks;
368 		c->c_flags |= CALLOUT_PENDING;
369 		CIRCQ_INSERT(&c->c_list, &occ->cc_todo);
370 	} else {
371 		/* Move to this CPU. */
372 		c->c_cpu = cc;
373 		c->c_time = to_ticks + cc->cc_ticks;
374 		c->c_flags |= CALLOUT_PENDING;
375 		CIRCQ_INSERT(&c->c_list, &cc->cc_todo);
376 		mutex_spin_exit(cc->cc_lock);
377 	}
378 	mutex_spin_exit(lock);
379 }
380 
381 /*
382  * callout_reset:
383  *
384  *	Reset a callout structure with a new function and argument, and
385  *	schedule it to run.
386  */
387 void
388 callout_reset(callout_t *cs, int to_ticks, void (*func)(void *), void *arg)
389 {
390 	callout_impl_t *c = (callout_impl_t *)cs;
391 	kmutex_t *lock;
392 
393 	KASSERT(c->c_magic == CALLOUT_MAGIC);
394 	KASSERT(func != NULL);
395 
396 	lock = callout_lock(c);
397 	c->c_func = func;
398 	c->c_arg = arg;
399 	callout_schedule_locked(c, lock, to_ticks);
400 }
401 
402 /*
403  * callout_schedule:
404  *
405  *	Schedule a callout to run.  The function and argument must
406  *	already be set in the callout structure.
407  */
408 void
409 callout_schedule(callout_t *cs, int to_ticks)
410 {
411 	callout_impl_t *c = (callout_impl_t *)cs;
412 	kmutex_t *lock;
413 
414 	KASSERT(c->c_magic == CALLOUT_MAGIC);
415 
416 	lock = callout_lock(c);
417 	callout_schedule_locked(c, lock, to_ticks);
418 }
419 
420 /*
421  * callout_stop:
422  *
423  *	Try to cancel a pending callout.  It may be too late: the callout
424  *	could be running on another CPU.  If called from interrupt context,
425  *	the callout could already be in progress at a lower priority.
426  */
427 bool
428 callout_stop(callout_t *cs)
429 {
430 	callout_impl_t *c = (callout_impl_t *)cs;
431 	struct callout_cpu *cc;
432 	kmutex_t *lock;
433 	bool expired;
434 
435 	KASSERT(c->c_magic == CALLOUT_MAGIC);
436 
437 	lock = callout_lock(c);
438 
439 	if ((c->c_flags & CALLOUT_PENDING) != 0)
440 		CIRCQ_REMOVE(&c->c_list);
441 	expired = ((c->c_flags & CALLOUT_FIRED) != 0);
442 	c->c_flags &= ~(CALLOUT_PENDING|CALLOUT_FIRED);
443 
444 	cc = c->c_cpu;
445 	if (cc->cc_active == c) {
446 		/*
447 		 * This is for non-MPSAFE callouts only.  To synchronize
448 		 * effectively we must be called with kernel_lock held.
449 		 * It's also taken in callout_softclock.
450 		 */
451 		cc->cc_cancel = c;
452 	}
453 
454 	mutex_spin_exit(lock);
455 
456 	return expired;
457 }
458 
459 /*
460  * callout_halt:
461  *
462  *	Cancel a pending callout.  If in-flight, block until it completes.
463  *	May not be called from a hard interrupt handler.  If the callout
464  * 	can take locks, the caller of callout_halt() must not hold any of
465  *	those locks, otherwise the two could deadlock.  If 'interlock' is
466  *	non-NULL and we must wait for the callout to complete, it will be
467  *	released and re-acquired before returning.
468  */
469 bool
470 callout_halt(callout_t *cs, void *interlock)
471 {
472 	callout_impl_t *c = (callout_impl_t *)cs;
473 	kmutex_t *lock;
474 	int flags;
475 
476 	KASSERT(c->c_magic == CALLOUT_MAGIC);
477 	KASSERT(!cpu_intr_p());
478 	KASSERT(interlock == NULL || mutex_owned(interlock));
479 
480 	/* Fast path. */
481 	lock = callout_lock(c);
482 	flags = c->c_flags;
483 	if ((flags & CALLOUT_PENDING) != 0)
484 		CIRCQ_REMOVE(&c->c_list);
485 	c->c_flags = flags & ~(CALLOUT_PENDING|CALLOUT_FIRED);
486 	if (__predict_false(flags & CALLOUT_FIRED)) {
487 		callout_wait(c, interlock, lock);
488 		return true;
489 	}
490 	mutex_spin_exit(lock);
491 	return false;
492 }
493 
494 /*
495  * callout_wait:
496  *
497  *	Slow path for callout_halt().  Deliberately marked __noinline to
498  *	prevent unneeded overhead in the caller.
499  */
500 static void __noinline
501 callout_wait(callout_impl_t *c, void *interlock, kmutex_t *lock)
502 {
503 	struct callout_cpu *cc;
504 	struct lwp *l;
505 	kmutex_t *relock;
506 
507 	l = curlwp;
508 	relock = NULL;
509 	for (;;) {
510 		/*
511 		 * At this point we know the callout is not pending, but it
512 		 * could be running on a CPU somewhere.  That can be curcpu
513 		 * in a few cases:
514 		 *
515 		 * - curlwp is a higher priority soft interrupt
516 		 * - the callout blocked on a lock and is currently asleep
517 		 * - the callout itself has called callout_halt() (nice!)
518 		 */
519 		cc = c->c_cpu;
520 		if (__predict_true(cc->cc_active != c || cc->cc_lwp == l))
521 			break;
522 
523 		/* It's running - need to wait for it to complete. */
524 		if (interlock != NULL) {
525 			/*
526 			 * Avoid potential scheduler lock order problems by
527 			 * dropping the interlock without the callout lock
528 			 * held; then retry.
529 			 */
530 			mutex_spin_exit(lock);
531 			mutex_exit(interlock);
532 			relock = interlock;
533 			interlock = NULL;
534 		} else {
535 			/* XXX Better to do priority inheritance. */
536 			KASSERT(l->l_wchan == NULL);
537 			cc->cc_nwait++;
538 			cc->cc_ev_block.ev_count++;
539 			l->l_kpriority = true;
540 			sleepq_enter(&cc->cc_sleepq, l, cc->cc_lock);
541 			sleepq_enqueue(&cc->cc_sleepq, cc, "callout",
542 			    &sleep_syncobj, false);
543 			sleepq_block(0, false);
544 		}
545 
546 		/*
547 		 * Re-lock the callout and check the state of play again.
548 		 * It's a common design pattern for callouts to re-schedule
549 		 * themselves so put a stop to it again if needed.
550 		 */
551 		lock = callout_lock(c);
552 		if ((c->c_flags & CALLOUT_PENDING) != 0)
553 			CIRCQ_REMOVE(&c->c_list);
554 		c->c_flags &= ~(CALLOUT_PENDING|CALLOUT_FIRED);
555 	}
556 
557 	mutex_spin_exit(lock);
558 	if (__predict_false(relock != NULL))
559 		mutex_enter(relock);
560 }
561 
562 #ifdef notyet
563 /*
564  * callout_bind:
565  *
566  *	Bind a callout so that it will only execute on one CPU.
567  *	The callout must be stopped, and must be MPSAFE.
568  *
569  *	XXX Disabled for now until it is decided how to handle
570  *	offlined CPUs.  We may want weak+strong binding.
571  */
572 void
573 callout_bind(callout_t *cs, struct cpu_info *ci)
574 {
575 	callout_impl_t *c = (callout_impl_t *)cs;
576 	struct callout_cpu *cc;
577 	kmutex_t *lock;
578 
579 	KASSERT((c->c_flags & CALLOUT_PENDING) == 0);
580 	KASSERT(c->c_cpu->cc_active != c);
581 	KASSERT(c->c_magic == CALLOUT_MAGIC);
582 	KASSERT((c->c_flags & CALLOUT_MPSAFE) != 0);
583 
584 	lock = callout_lock(c);
585 	cc = ci->ci_data.cpu_callout;
586 	c->c_flags |= CALLOUT_BOUND;
587 	if (c->c_cpu != cc) {
588 		/*
589 		 * Assigning c_cpu effectively unlocks the callout
590 		 * structure, as we don't hold the new CPU's lock.
591 		 * Issue memory barrier to prevent accesses being
592 		 * reordered.
593 		 */
594 		membar_exit();
595 		c->c_cpu = cc;
596 	}
597 	mutex_spin_exit(lock);
598 }
599 #endif
600 
601 void
602 callout_setfunc(callout_t *cs, void (*func)(void *), void *arg)
603 {
604 	callout_impl_t *c = (callout_impl_t *)cs;
605 	kmutex_t *lock;
606 
607 	KASSERT(c->c_magic == CALLOUT_MAGIC);
608 	KASSERT(func != NULL);
609 
610 	lock = callout_lock(c);
611 	c->c_func = func;
612 	c->c_arg = arg;
613 	mutex_spin_exit(lock);
614 }
615 
616 bool
617 callout_expired(callout_t *cs)
618 {
619 	callout_impl_t *c = (callout_impl_t *)cs;
620 	kmutex_t *lock;
621 	bool rv;
622 
623 	KASSERT(c->c_magic == CALLOUT_MAGIC);
624 
625 	lock = callout_lock(c);
626 	rv = ((c->c_flags & CALLOUT_FIRED) != 0);
627 	mutex_spin_exit(lock);
628 
629 	return rv;
630 }
631 
632 bool
633 callout_active(callout_t *cs)
634 {
635 	callout_impl_t *c = (callout_impl_t *)cs;
636 	kmutex_t *lock;
637 	bool rv;
638 
639 	KASSERT(c->c_magic == CALLOUT_MAGIC);
640 
641 	lock = callout_lock(c);
642 	rv = ((c->c_flags & (CALLOUT_PENDING|CALLOUT_FIRED)) != 0);
643 	mutex_spin_exit(lock);
644 
645 	return rv;
646 }
647 
648 bool
649 callout_pending(callout_t *cs)
650 {
651 	callout_impl_t *c = (callout_impl_t *)cs;
652 	kmutex_t *lock;
653 	bool rv;
654 
655 	KASSERT(c->c_magic == CALLOUT_MAGIC);
656 
657 	lock = callout_lock(c);
658 	rv = ((c->c_flags & CALLOUT_PENDING) != 0);
659 	mutex_spin_exit(lock);
660 
661 	return rv;
662 }
663 
664 bool
665 callout_invoking(callout_t *cs)
666 {
667 	callout_impl_t *c = (callout_impl_t *)cs;
668 	kmutex_t *lock;
669 	bool rv;
670 
671 	KASSERT(c->c_magic == CALLOUT_MAGIC);
672 
673 	lock = callout_lock(c);
674 	rv = ((c->c_flags & CALLOUT_INVOKING) != 0);
675 	mutex_spin_exit(lock);
676 
677 	return rv;
678 }
679 
680 void
681 callout_ack(callout_t *cs)
682 {
683 	callout_impl_t *c = (callout_impl_t *)cs;
684 	kmutex_t *lock;
685 
686 	KASSERT(c->c_magic == CALLOUT_MAGIC);
687 
688 	lock = callout_lock(c);
689 	c->c_flags &= ~CALLOUT_INVOKING;
690 	mutex_spin_exit(lock);
691 }
692 
693 /*
694  * callout_hardclock:
695  *
696  *	Called from hardclock() once every tick.  We schedule a soft
697  *	interrupt if there is work to be done.
698  */
699 void
700 callout_hardclock(void)
701 {
702 	struct callout_cpu *cc;
703 	int needsoftclock, ticks;
704 
705 	cc = curcpu()->ci_data.cpu_callout;
706 	mutex_spin_enter(cc->cc_lock);
707 
708 	ticks = ++cc->cc_ticks;
709 
710 	MOVEBUCKET(cc, 0, ticks);
711 	if (MASKWHEEL(0, ticks) == 0) {
712 		MOVEBUCKET(cc, 1, ticks);
713 		if (MASKWHEEL(1, ticks) == 0) {
714 			MOVEBUCKET(cc, 2, ticks);
715 			if (MASKWHEEL(2, ticks) == 0)
716 				MOVEBUCKET(cc, 3, ticks);
717 		}
718 	}
719 
720 	needsoftclock = !CIRCQ_EMPTY(&cc->cc_todo);
721 	mutex_spin_exit(cc->cc_lock);
722 
723 	if (needsoftclock)
724 		softint_schedule(callout_sih);
725 }
726 
727 /*
728  * callout_softclock:
729  *
730  *	Soft interrupt handler, scheduled above if there is work to
731  * 	be done.  Callouts are made in soft interrupt context.
732  */
733 static void
734 callout_softclock(void *v)
735 {
736 	callout_impl_t *c;
737 	struct callout_cpu *cc;
738 	void (*func)(void *);
739 	void *arg;
740 	int mpsafe, count, ticks, delta;
741 	lwp_t *l;
742 
743 	l = curlwp;
744 	KASSERT(l->l_cpu == curcpu());
745 	cc = l->l_cpu->ci_data.cpu_callout;
746 
747 	mutex_spin_enter(cc->cc_lock);
748 	cc->cc_lwp = l;
749 	while (!CIRCQ_EMPTY(&cc->cc_todo)) {
750 		c = CIRCQ_FIRST(&cc->cc_todo);
751 		KASSERT(c->c_magic == CALLOUT_MAGIC);
752 		KASSERT(c->c_func != NULL);
753 		KASSERT(c->c_cpu == cc);
754 		KASSERT((c->c_flags & CALLOUT_PENDING) != 0);
755 		KASSERT((c->c_flags & CALLOUT_FIRED) == 0);
756 		CIRCQ_REMOVE(&c->c_list);
757 
758 		/* If due run it, otherwise insert it into the right bucket. */
759 		ticks = cc->cc_ticks;
760 		delta = (int)((unsigned)c->c_time - (unsigned)ticks);
761 		if (delta > 0) {
762 			CIRCQ_INSERT(&c->c_list, BUCKET(cc, delta, c->c_time));
763 			continue;
764 		}
765 		if (delta < 0)
766 			cc->cc_ev_late.ev_count++;
767 
768 		c->c_flags = (c->c_flags & ~CALLOUT_PENDING) |
769 		    (CALLOUT_FIRED | CALLOUT_INVOKING);
770 		mpsafe = (c->c_flags & CALLOUT_MPSAFE);
771 		func = c->c_func;
772 		arg = c->c_arg;
773 		cc->cc_active = c;
774 
775 		mutex_spin_exit(cc->cc_lock);
776 		KASSERT(func != NULL);
777 		if (__predict_false(!mpsafe)) {
778 			KERNEL_LOCK(1, NULL);
779 			(*func)(arg);
780 			KERNEL_UNLOCK_ONE(NULL);
781 		} else
782 			(*func)(arg);
783 		mutex_spin_enter(cc->cc_lock);
784 
785 		/*
786 		 * We can't touch 'c' here because it might be
787 		 * freed already.  If LWPs waiting for callout
788 		 * to complete, awaken them.
789 		 */
790 		cc->cc_active = NULL;
791 		if ((count = cc->cc_nwait) != 0) {
792 			cc->cc_nwait = 0;
793 			/* sleepq_wake() drops the lock. */
794 			sleepq_wake(&cc->cc_sleepq, cc, count, cc->cc_lock);
795 			mutex_spin_enter(cc->cc_lock);
796 		}
797 	}
798 	cc->cc_lwp = NULL;
799 	mutex_spin_exit(cc->cc_lock);
800 }
801 #endif
802 
803 #ifdef DDB
804 static void
805 db_show_callout_bucket(struct callout_cpu *cc, struct callout_circq *kbucket,
806     struct callout_circq *bucket)
807 {
808 	callout_impl_t *c, ci;
809 	db_expr_t offset;
810 	const char *name;
811 	static char question[] = "?";
812 	int b;
813 
814 	if (CIRCQ_LAST(bucket, kbucket))
815 		return;
816 
817 	for (c = CIRCQ_FIRST(bucket); /*nothing*/; c = CIRCQ_NEXT(&c->c_list)) {
818 		db_read_bytes((db_addr_t)c, sizeof(ci), (char *)&ci);
819 		c = &ci;
820 		db_find_sym_and_offset((db_addr_t)(intptr_t)c->c_func, &name,
821 		    &offset);
822 		name = name ? name : question;
823 		b = (bucket - cc->cc_wheel);
824 		if (b < 0)
825 			b = -WHEELSIZE;
826 		db_printf("%9d %2d/%-4d %16lx  %s\n",
827 		    c->c_time - cc->cc_ticks, b / WHEELSIZE, b,
828 		    (u_long)c->c_arg, name);
829 		if (CIRCQ_LAST(&c->c_list, kbucket))
830 			break;
831 	}
832 }
833 
834 void
835 db_show_callout(db_expr_t addr, bool haddr, db_expr_t count, const char *modif)
836 {
837 	struct callout_cpu *cc, ccb;
838 	struct cpu_info *ci, cib;
839 	int b;
840 
841 #ifndef CRASH
842 	db_printf("hardclock_ticks now: %d\n", getticks());
843 #endif
844 	db_printf("    ticks  wheel               arg  func\n");
845 
846 	/*
847 	 * Don't lock the callwheel; all the other CPUs are paused
848 	 * anyhow, and we might be called in a circumstance where
849 	 * some other CPU was paused while holding the lock.
850 	 */
851 	for (ci = db_cpu_first(); ci != NULL; ci = db_cpu_next(ci)) {
852 		db_read_bytes((db_addr_t)ci, sizeof(cib), (char *)&cib);
853 		cc = cib.ci_data.cpu_callout;
854 		db_read_bytes((db_addr_t)cc, sizeof(ccb), (char *)&ccb);
855 		db_show_callout_bucket(&ccb, &cc->cc_todo, &ccb.cc_todo);
856 	}
857 	for (b = 0; b < BUCKETS; b++) {
858 		for (ci = db_cpu_first(); ci != NULL; ci = db_cpu_next(ci)) {
859 			db_read_bytes((db_addr_t)ci, sizeof(cib), (char *)&cib);
860 			cc = cib.ci_data.cpu_callout;
861 			db_read_bytes((db_addr_t)cc, sizeof(ccb), (char *)&ccb);
862 			db_show_callout_bucket(&ccb, &cc->cc_wheel[b],
863 			    &ccb.cc_wheel[b]);
864 		}
865 	}
866 }
867 #endif /* DDB */
868