xref: /openbsd/sys/kern/kern_timeout.c (revision 2ee1bbb5)
1 /*	$OpenBSD: kern_timeout.c,v 1.101 2025/01/13 03:21:10 mvs Exp $	*/
2 /*
3  * Copyright (c) 2001 Thomas Nordin <nordin@openbsd.org>
4  * Copyright (c) 2000-2001 Artur Grabowski <art@openbsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
17  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
19  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/kthread.h>
31 #include <sys/proc.h>
32 #include <sys/timeout.h>
33 #include <sys/mutex.h>
34 #include <sys/kernel.h>
35 #include <sys/queue.h>			/* _Q_INVALIDATE */
36 #include <sys/sysctl.h>
37 #include <sys/witness.h>
38 
39 #ifdef DDB
40 #include <machine/db_machdep.h>
41 #include <ddb/db_interface.h>
42 #include <ddb/db_sym.h>
43 #include <ddb/db_output.h>
44 #endif
45 
46 #include "kcov.h"
47 #if NKCOV > 0
48 #include <sys/kcov.h>
49 #endif
50 
51 /*
52  * Locks used to protect global variables in this file:
53  *
54  *	I	immutable after initialization
55  *	T	timeout_mutex
56  */
57 struct mutex timeout_mutex = MUTEX_INITIALIZER(IPL_HIGH);
58 
59 void *softclock_si;			/* [I] softclock() interrupt handle */
60 struct timeoutstat tostat;		/* [T] statistics and totals */
61 
62 /*
63  * Timeouts are kept in a hierarchical timing wheel. The to_time is the value
64  * of the global variable "ticks" when the timeout should be called. There are
65  * four levels with 256 buckets each.
66  */
67 #define WHEELCOUNT 4
68 #define WHEELSIZE 256
69 #define WHEELMASK 255
70 #define WHEELBITS 8
71 #define BUCKETS (WHEELCOUNT * WHEELSIZE)
72 
73 struct circq timeout_wheel[BUCKETS];	/* [T] Tick-based timeouts */
74 struct circq timeout_wheel_kc[BUCKETS];	/* [T] Clock-based timeouts */
75 struct circq timeout_new;		/* [T] New, unscheduled timeouts */
76 struct circq timeout_todo;		/* [T] Due or needs rescheduling */
77 struct circq timeout_proc;		/* [T] Due + needs process context */
78 #ifdef MULTIPROCESSOR
79 struct circq timeout_proc_mp;		/* [T] Process ctx + no kernel lock */
80 #endif
81 
82 time_t timeout_level_width[WHEELCOUNT];	/* [I] Wheel level width (seconds) */
83 struct timespec tick_ts;		/* [I] Length of a tick (1/hz secs) */
84 
85 struct kclock {
86 	struct timespec kc_lastscan;	/* [T] Clock time at last wheel scan */
87 	struct timespec kc_late;	/* [T] Late if due prior */
88 	struct timespec kc_offset;	/* [T] Offset from primary kclock */
89 } timeout_kclock[KCLOCK_MAX];
90 
91 #define MASKWHEEL(wheel, time) (((time) >> ((wheel)*WHEELBITS)) & WHEELMASK)
92 
93 #define BUCKET(rel, abs)						\
94     (timeout_wheel[							\
95 	((rel) <= (1 << (2*WHEELBITS)))					\
96 	    ? ((rel) <= (1 << WHEELBITS))				\
97 		? MASKWHEEL(0, (abs))					\
98 		: MASKWHEEL(1, (abs)) + WHEELSIZE			\
99 	    : ((rel) <= (1 << (3*WHEELBITS)))				\
100 		? MASKWHEEL(2, (abs)) + 2*WHEELSIZE			\
101 		: MASKWHEEL(3, (abs)) + 3*WHEELSIZE])
102 
103 #define MOVEBUCKET(wheel, time)						\
104     CIRCQ_CONCAT(&timeout_todo,						\
105         &timeout_wheel[MASKWHEEL((wheel), (time)) + (wheel)*WHEELSIZE])
106 
107 /*
108  * Circular queue definitions.
109  */
110 
111 #define CIRCQ_INIT(elem) do {			\
112 	(elem)->next = (elem);			\
113 	(elem)->prev = (elem);			\
114 } while (0)
115 
116 #define CIRCQ_INSERT_TAIL(list, elem) do {	\
117 	(elem)->prev = (list)->prev;		\
118 	(elem)->next = (list);			\
119 	(list)->prev->next = (elem);		\
120 	(list)->prev = (elem);			\
121 	tostat.tos_pending++;			\
122 } while (0)
123 
124 #define CIRCQ_CONCAT(fst, snd) do {		\
125 	if (!CIRCQ_EMPTY(snd)) {		\
126 		(fst)->prev->next = (snd)->next;\
127 		(snd)->next->prev = (fst)->prev;\
128 		(snd)->prev->next = (fst);      \
129 		(fst)->prev = (snd)->prev;      \
130 		CIRCQ_INIT(snd);		\
131 	}					\
132 } while (0)
133 
134 #define CIRCQ_REMOVE(elem) do {			\
135 	(elem)->next->prev = (elem)->prev;      \
136 	(elem)->prev->next = (elem)->next;      \
137 	_Q_INVALIDATE((elem)->prev);		\
138 	_Q_INVALIDATE((elem)->next);		\
139 	tostat.tos_pending--;			\
140 } while (0)
141 
142 #define CIRCQ_FIRST(elem) ((elem)->next)
143 
144 #define CIRCQ_EMPTY(elem) (CIRCQ_FIRST(elem) == (elem))
145 
146 #define CIRCQ_FOREACH(elem, list)		\
147 	for ((elem) = CIRCQ_FIRST(list);	\
148 	    (elem) != (list);			\
149 	    (elem) = CIRCQ_FIRST(elem))
150 
151 #ifdef WITNESS
152 struct lock_object timeout_sleeplock_obj = {
153 	.lo_name = "timeout",
154 	.lo_flags = LO_WITNESS | LO_INITIALIZED | LO_SLEEPABLE |
155 	    (LO_CLASS_RWLOCK << LO_CLASSSHIFT)
156 };
157 struct lock_object timeout_spinlock_obj = {
158 	.lo_name = "timeout",
159 	.lo_flags = LO_WITNESS | LO_INITIALIZED |
160 	    (LO_CLASS_MUTEX << LO_CLASSSHIFT)
161 };
162 struct lock_type timeout_sleeplock_type = {
163 	.lt_name = "timeout"
164 };
165 struct lock_type timeout_spinlock_type = {
166 	.lt_name = "timeout"
167 };
168 #define TIMEOUT_LOCK_OBJ(needsproc) \
169 	((needsproc) ? &timeout_sleeplock_obj : &timeout_spinlock_obj)
170 #endif
171 
172 void softclock(void *);
173 void softclock_create_thread(void *);
174 void softclock_process_kclock_timeout(struct timeout *, int);
175 void softclock_process_tick_timeout(struct timeout *, int);
176 void softclock_thread(void *);
177 #ifdef MULTIPROCESSOR
178 void softclock_thread_mp(void *);
179 #endif
180 void timeout_barrier_timeout(void *);
181 uint32_t timeout_bucket(const struct timeout *);
182 uint32_t timeout_maskwheel(uint32_t, const struct timespec *);
183 void timeout_run(struct timeout *);
184 
185 /*
186  * The first thing in a struct timeout is its struct circq, so we
187  * can get back from a pointer to the latter to a pointer to the
188  * whole timeout with just a cast.
189  */
190 static inline struct timeout *
timeout_from_circq(struct circq * p)191 timeout_from_circq(struct circq *p)
192 {
193 	return ((struct timeout *)(p));
194 }
195 
196 static inline void
timeout_sync_order(int needsproc)197 timeout_sync_order(int needsproc)
198 {
199 	WITNESS_CHECKORDER(TIMEOUT_LOCK_OBJ(needsproc), LOP_NEWORDER, NULL);
200 }
201 
202 static inline void
timeout_sync_enter(int needsproc)203 timeout_sync_enter(int needsproc)
204 {
205 	timeout_sync_order(needsproc);
206 	WITNESS_LOCK(TIMEOUT_LOCK_OBJ(needsproc), 0);
207 }
208 
209 static inline void
timeout_sync_leave(int needsproc)210 timeout_sync_leave(int needsproc)
211 {
212 	WITNESS_UNLOCK(TIMEOUT_LOCK_OBJ(needsproc), 0);
213 }
214 
215 /*
216  * Some of the "math" in here is a bit tricky.
217  *
218  * We have to beware of wrapping ints.
219  * We use the fact that any element added to the queue must be added with a
220  * positive time. That means that any element `to' on the queue cannot be
221  * scheduled to timeout further in time than INT_MAX, but to->to_time can
222  * be positive or negative so comparing it with anything is dangerous.
223  * The only way we can use the to->to_time value in any predictable way
224  * is when we calculate how far in the future `to' will timeout -
225  * "to->to_time - ticks". The result will always be positive for future
226  * timeouts and 0 or negative for due timeouts.
227  */
228 
229 void
timeout_startup(void)230 timeout_startup(void)
231 {
232 	int b, level;
233 
234 	CIRCQ_INIT(&timeout_new);
235 	CIRCQ_INIT(&timeout_todo);
236 	CIRCQ_INIT(&timeout_proc);
237 #ifdef MULTIPROCESSOR
238 	CIRCQ_INIT(&timeout_proc_mp);
239 #endif
240 	for (b = 0; b < nitems(timeout_wheel); b++)
241 		CIRCQ_INIT(&timeout_wheel[b]);
242 	for (b = 0; b < nitems(timeout_wheel_kc); b++)
243 		CIRCQ_INIT(&timeout_wheel_kc[b]);
244 
245 	for (level = 0; level < nitems(timeout_level_width); level++)
246 		timeout_level_width[level] = 2 << (level * WHEELBITS);
247 	NSEC_TO_TIMESPEC(tick_nsec, &tick_ts);
248 }
249 
250 void
timeout_proc_init(void)251 timeout_proc_init(void)
252 {
253 	softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
254 	if (softclock_si == NULL)
255 		panic("%s: unable to register softclock interrupt", __func__);
256 
257 	WITNESS_INIT(&timeout_sleeplock_obj, &timeout_sleeplock_type);
258 	WITNESS_INIT(&timeout_spinlock_obj, &timeout_spinlock_type);
259 
260 	kthread_create_deferred(softclock_create_thread, NULL);
261 }
262 
263 void
timeout_set(struct timeout * new,void (* fn)(void *),void * arg)264 timeout_set(struct timeout *new, void (*fn)(void *), void *arg)
265 {
266 	timeout_set_flags(new, fn, arg, KCLOCK_NONE, 0);
267 }
268 
269 void
timeout_set_flags(struct timeout * to,void (* fn)(void *),void * arg,int kclock,int flags)270 timeout_set_flags(struct timeout *to, void (*fn)(void *), void *arg, int kclock,
271     int flags)
272 {
273 	KASSERT(!ISSET(flags, ~(TIMEOUT_PROC | TIMEOUT_MPSAFE)));
274 	KASSERT(kclock >= KCLOCK_NONE && kclock < KCLOCK_MAX);
275 
276 	to->to_func = fn;
277 	to->to_arg = arg;
278 	to->to_kclock = kclock;
279 	to->to_flags = flags | TIMEOUT_INITIALIZED;
280 
281 	/* For now, only process context timeouts may be marked MP-safe. */
282 	if (ISSET(to->to_flags, TIMEOUT_MPSAFE))
283 		KASSERT(ISSET(to->to_flags, TIMEOUT_PROC));
284 }
285 
286 void
timeout_set_proc(struct timeout * new,void (* fn)(void *),void * arg)287 timeout_set_proc(struct timeout *new, void (*fn)(void *), void *arg)
288 {
289 	timeout_set_flags(new, fn, arg, KCLOCK_NONE, TIMEOUT_PROC);
290 }
291 
292 int
timeout_add(struct timeout * new,int to_ticks)293 timeout_add(struct timeout *new, int to_ticks)
294 {
295 	int old_time;
296 	int ret = 1;
297 
298 	KASSERT(ISSET(new->to_flags, TIMEOUT_INITIALIZED));
299 	KASSERT(new->to_kclock == KCLOCK_NONE);
300 	KASSERT(to_ticks >= 0);
301 
302 	mtx_enter(&timeout_mutex);
303 
304 	/* Initialize the time here, it won't change. */
305 	old_time = new->to_time;
306 	new->to_time = to_ticks + ticks;
307 	CLR(new->to_flags, TIMEOUT_TRIGGERED);
308 
309 	/*
310 	 * If this timeout already is scheduled and now is moved
311 	 * earlier, reschedule it now. Otherwise leave it in place
312 	 * and let it be rescheduled later.
313 	 */
314 	if (ISSET(new->to_flags, TIMEOUT_ONQUEUE)) {
315 		if (new->to_time - ticks < old_time - ticks) {
316 			CIRCQ_REMOVE(&new->to_list);
317 			CIRCQ_INSERT_TAIL(&timeout_new, &new->to_list);
318 		}
319 		tostat.tos_readded++;
320 		ret = 0;
321 	} else {
322 		SET(new->to_flags, TIMEOUT_ONQUEUE);
323 		CIRCQ_INSERT_TAIL(&timeout_new, &new->to_list);
324 	}
325 #if NKCOV > 0
326 	if (!kcov_cold)
327 		new->to_process = curproc->p_p;
328 #endif
329 	tostat.tos_added++;
330 	mtx_leave(&timeout_mutex);
331 
332 	return ret;
333 }
334 
335 static inline int
timeout_add_ticks(struct timeout * to,uint64_t to_ticks,int notzero)336 timeout_add_ticks(struct timeout *to, uint64_t to_ticks, int notzero)
337 {
338 	if (to_ticks > INT_MAX)
339 		to_ticks = INT_MAX;
340 	else if (to_ticks == 0 && notzero)
341 		to_ticks = 1;
342 
343 	return timeout_add(to, (int)to_ticks);
344 }
345 
346 int
timeout_add_tv(struct timeout * to,const struct timeval * tv)347 timeout_add_tv(struct timeout *to, const struct timeval *tv)
348 {
349 	uint64_t to_ticks;
350 
351 	to_ticks = (uint64_t)hz * tv->tv_sec + tv->tv_usec / tick;
352 
353 	return timeout_add_ticks(to, to_ticks, tv->tv_usec > 0);
354 }
355 
356 int
timeout_add_sec(struct timeout * to,int secs)357 timeout_add_sec(struct timeout *to, int secs)
358 {
359 	uint64_t to_ticks;
360 
361 	to_ticks = (uint64_t)hz * secs;
362 
363 	return timeout_add_ticks(to, to_ticks, 1);
364 }
365 
366 int
timeout_add_msec(struct timeout * to,uint64_t msecs)367 timeout_add_msec(struct timeout *to, uint64_t msecs)
368 {
369 	uint64_t to_ticks;
370 
371 	to_ticks = msecs * 1000 / tick;
372 
373 	return timeout_add_ticks(to, to_ticks, msecs > 0);
374 }
375 
376 int
timeout_add_usec(struct timeout * to,uint64_t usecs)377 timeout_add_usec(struct timeout *to, uint64_t usecs)
378 {
379 	uint64_t to_ticks;
380 
381 	to_ticks = usecs / tick;
382 
383 	return timeout_add_ticks(to, to_ticks, usecs > 0);
384 }
385 
386 int
timeout_add_nsec(struct timeout * to,uint64_t nsecs)387 timeout_add_nsec(struct timeout *to, uint64_t nsecs)
388 {
389 	uint64_t to_ticks;
390 
391 	to_ticks = nsecs / (tick * 1000);
392 
393 	return timeout_add_ticks(to, to_ticks, nsecs > 0);
394 }
395 
396 int
timeout_abs_ts(struct timeout * to,const struct timespec * abstime)397 timeout_abs_ts(struct timeout *to, const struct timespec *abstime)
398 {
399 	struct timespec old_abstime;
400 	int ret = 1;
401 
402 	mtx_enter(&timeout_mutex);
403 
404 	KASSERT(ISSET(to->to_flags, TIMEOUT_INITIALIZED));
405 	KASSERT(to->to_kclock == KCLOCK_UPTIME);
406 
407 	old_abstime = to->to_abstime;
408 	to->to_abstime = *abstime;
409 	CLR(to->to_flags, TIMEOUT_TRIGGERED);
410 
411 	if (ISSET(to->to_flags, TIMEOUT_ONQUEUE)) {
412 		if (timespeccmp(abstime, &old_abstime, <)) {
413 			CIRCQ_REMOVE(&to->to_list);
414 			CIRCQ_INSERT_TAIL(&timeout_new, &to->to_list);
415 		}
416 		tostat.tos_readded++;
417 		ret = 0;
418 	} else {
419 		SET(to->to_flags, TIMEOUT_ONQUEUE);
420 		CIRCQ_INSERT_TAIL(&timeout_new, &to->to_list);
421 	}
422 #if NKCOV > 0
423 	if (!kcov_cold)
424 		to->to_process = curproc->p_p;
425 #endif
426 	tostat.tos_added++;
427 
428 	mtx_leave(&timeout_mutex);
429 
430 	return ret;
431 }
432 
433 int
timeout_del(struct timeout * to)434 timeout_del(struct timeout *to)
435 {
436 	int ret = 0;
437 
438 	mtx_enter(&timeout_mutex);
439 	if (ISSET(to->to_flags, TIMEOUT_ONQUEUE)) {
440 		CIRCQ_REMOVE(&to->to_list);
441 		CLR(to->to_flags, TIMEOUT_ONQUEUE);
442 		tostat.tos_cancelled++;
443 		ret = 1;
444 	}
445 	CLR(to->to_flags, TIMEOUT_TRIGGERED);
446 	tostat.tos_deleted++;
447 	mtx_leave(&timeout_mutex);
448 
449 	return ret;
450 }
451 
452 int
timeout_del_barrier(struct timeout * to)453 timeout_del_barrier(struct timeout *to)
454 {
455 	int removed;
456 
457 	timeout_sync_order(ISSET(to->to_flags, TIMEOUT_PROC));
458 
459 	removed = timeout_del(to);
460 	timeout_barrier(to);
461 
462 	return removed;
463 }
464 
465 void
timeout_barrier(struct timeout * to)466 timeout_barrier(struct timeout *to)
467 {
468 	struct timeout barrier;
469 	struct cond c;
470 	int flags;
471 
472 	flags = to->to_flags & (TIMEOUT_PROC | TIMEOUT_MPSAFE);
473 	timeout_sync_order(ISSET(flags, TIMEOUT_PROC));
474 
475 	timeout_set_flags(&barrier, timeout_barrier_timeout, &c, KCLOCK_NONE,
476 	    flags);
477 	barrier.to_process = curproc->p_p;
478 	cond_init(&c);
479 
480 	mtx_enter(&timeout_mutex);
481 
482 	barrier.to_time = ticks;
483 	SET(barrier.to_flags, TIMEOUT_ONQUEUE);
484 	if (ISSET(flags, TIMEOUT_PROC)) {
485 #ifdef MULTIPROCESSOR
486 		if (ISSET(flags, TIMEOUT_MPSAFE))
487 			CIRCQ_INSERT_TAIL(&timeout_proc_mp, &barrier.to_list);
488 		else
489 #endif
490 			CIRCQ_INSERT_TAIL(&timeout_proc, &barrier.to_list);
491 	} else
492 		CIRCQ_INSERT_TAIL(&timeout_todo, &barrier.to_list);
493 
494 	mtx_leave(&timeout_mutex);
495 
496 	if (ISSET(flags, TIMEOUT_PROC)) {
497 #ifdef MULTIPROCESSOR
498 		if (ISSET(flags, TIMEOUT_MPSAFE))
499 			wakeup_one(&timeout_proc_mp);
500 		else
501 #endif
502 			wakeup_one(&timeout_proc);
503 	} else
504 		softintr_schedule(softclock_si);
505 
506 	cond_wait(&c, "tmobar");
507 }
508 
509 void
timeout_barrier_timeout(void * arg)510 timeout_barrier_timeout(void *arg)
511 {
512 	struct cond *c = arg;
513 
514 	cond_signal(c);
515 }
516 
517 uint32_t
timeout_bucket(const struct timeout * to)518 timeout_bucket(const struct timeout *to)
519 {
520 	struct timespec diff, shifted_abstime;
521 	struct kclock *kc;
522 	uint32_t level;
523 
524 	KASSERT(to->to_kclock == KCLOCK_UPTIME);
525 	kc = &timeout_kclock[to->to_kclock];
526 
527 	KASSERT(timespeccmp(&kc->kc_lastscan, &to->to_abstime, <));
528 	timespecsub(&to->to_abstime, &kc->kc_lastscan, &diff);
529 	for (level = 0; level < nitems(timeout_level_width) - 1; level++) {
530 		if (diff.tv_sec < timeout_level_width[level])
531 			break;
532 	}
533 	timespecadd(&to->to_abstime, &kc->kc_offset, &shifted_abstime);
534 	return level * WHEELSIZE + timeout_maskwheel(level, &shifted_abstime);
535 }
536 
537 /*
538  * Hash the absolute time into a bucket on a given level of the wheel.
539  *
540  * The complete hash is 32 bits.  The upper 25 bits are seconds, the
541  * lower 7 bits are nanoseconds.  tv_nsec is a positive value less
542  * than one billion so we need to divide it to isolate the desired
543  * bits.  We can't just shift it.
544  *
545  * The level is used to isolate an 8-bit portion of the hash.  The
546  * resulting number indicates which bucket the absolute time belongs
547  * in on the given level of the wheel.
548  */
549 uint32_t
timeout_maskwheel(uint32_t level,const struct timespec * abstime)550 timeout_maskwheel(uint32_t level, const struct timespec *abstime)
551 {
552 	uint32_t hi, lo;
553 
554  	hi = abstime->tv_sec << 7;
555 	lo = abstime->tv_nsec / 7812500;
556 
557 	return ((hi | lo) >> (level * WHEELBITS)) & WHEELMASK;
558 }
559 
560 /*
561  * This is called from hardclock() on the primary CPU at the start of
562  * every tick.
563  */
564 void
timeout_hardclock_update(void)565 timeout_hardclock_update(void)
566 {
567 	struct timespec elapsed, now;
568 	struct kclock *kc;
569 	struct timespec *lastscan = &timeout_kclock[KCLOCK_UPTIME].kc_lastscan;
570 	int b, done, first, i, last, level, need_softclock = 1, off;
571 
572 	mtx_enter(&timeout_mutex);
573 
574 	MOVEBUCKET(0, ticks);
575 	if (MASKWHEEL(0, ticks) == 0) {
576 		MOVEBUCKET(1, ticks);
577 		if (MASKWHEEL(1, ticks) == 0) {
578 			MOVEBUCKET(2, ticks);
579 			if (MASKWHEEL(2, ticks) == 0)
580 				MOVEBUCKET(3, ticks);
581 		}
582 	}
583 
584 	/*
585 	 * Dump the buckets that expired while we were away.
586 	 *
587 	 * If the elapsed time has exceeded a level's limit then we need
588 	 * to dump every bucket in the level.  We have necessarily completed
589 	 * a lap of that level, too, so we need to process buckets in the
590 	 * next level.
591 	 *
592 	 * Otherwise we need to compare indices: if the index of the first
593 	 * expired bucket is greater than that of the last then we have
594 	 * completed a lap of the level and need to process buckets in the
595 	 * next level.
596 	 */
597 	nanouptime(&now);
598 	timespecsub(&now, lastscan, &elapsed);
599 	for (level = 0; level < nitems(timeout_level_width); level++) {
600 		first = timeout_maskwheel(level, lastscan);
601 		if (elapsed.tv_sec >= timeout_level_width[level]) {
602 			last = (first == 0) ? WHEELSIZE - 1 : first - 1;
603 			done = 0;
604 		} else {
605 			last = timeout_maskwheel(level, &now);
606 			done = first <= last;
607 		}
608 		off = level * WHEELSIZE;
609 		for (b = first;; b = (b + 1) % WHEELSIZE) {
610 			CIRCQ_CONCAT(&timeout_todo, &timeout_wheel_kc[off + b]);
611 			if (b == last)
612 				break;
613 		}
614 		if (done)
615 			break;
616 	}
617 
618 	/*
619 	 * Update the cached state for each kclock.
620 	 */
621 	for (i = 0; i < nitems(timeout_kclock); i++) {
622 		kc = &timeout_kclock[i];
623 		timespecadd(&now, &kc->kc_offset, &kc->kc_lastscan);
624 		timespecsub(&kc->kc_lastscan, &tick_ts, &kc->kc_late);
625 	}
626 
627 	if (CIRCQ_EMPTY(&timeout_new) && CIRCQ_EMPTY(&timeout_todo))
628 		need_softclock = 0;
629 
630 	mtx_leave(&timeout_mutex);
631 
632 	if (need_softclock)
633 		softintr_schedule(softclock_si);
634 }
635 
636 void
timeout_run(struct timeout * to)637 timeout_run(struct timeout *to)
638 {
639 	void (*fn)(void *);
640 	void *arg;
641 	int needsproc;
642 
643 	MUTEX_ASSERT_LOCKED(&timeout_mutex);
644 
645 	CLR(to->to_flags, TIMEOUT_ONQUEUE);
646 	SET(to->to_flags, TIMEOUT_TRIGGERED);
647 
648 	fn = to->to_func;
649 	arg = to->to_arg;
650 	needsproc = ISSET(to->to_flags, TIMEOUT_PROC);
651 #if NKCOV > 0
652 	struct process *kcov_process = to->to_process;
653 #endif
654 
655 	mtx_leave(&timeout_mutex);
656 	timeout_sync_enter(needsproc);
657 #if NKCOV > 0
658 	kcov_remote_enter(KCOV_REMOTE_COMMON, kcov_process);
659 #endif
660 	fn(arg);
661 #if NKCOV > 0
662 	kcov_remote_leave(KCOV_REMOTE_COMMON, kcov_process);
663 #endif
664 	timeout_sync_leave(needsproc);
665 	mtx_enter(&timeout_mutex);
666 }
667 
668 void
softclock_process_kclock_timeout(struct timeout * to,int new)669 softclock_process_kclock_timeout(struct timeout *to, int new)
670 {
671 	struct kclock *kc = &timeout_kclock[to->to_kclock];
672 
673 	if (timespeccmp(&to->to_abstime, &kc->kc_lastscan, >)) {
674 		tostat.tos_scheduled++;
675 		if (!new)
676 			tostat.tos_rescheduled++;
677 		CIRCQ_INSERT_TAIL(&timeout_wheel_kc[timeout_bucket(to)],
678 		    &to->to_list);
679 		return;
680 	}
681 	if (!new && timespeccmp(&to->to_abstime, &kc->kc_late, <=))
682 		tostat.tos_late++;
683 	if (ISSET(to->to_flags, TIMEOUT_PROC)) {
684 #ifdef MULTIPROCESSOR
685 		if (ISSET(to->to_flags, TIMEOUT_MPSAFE))
686 			CIRCQ_INSERT_TAIL(&timeout_proc_mp, &to->to_list);
687 		else
688 #endif
689 			CIRCQ_INSERT_TAIL(&timeout_proc, &to->to_list);
690 		return;
691 	}
692 	timeout_run(to);
693 	tostat.tos_run_softclock++;
694 }
695 
696 void
softclock_process_tick_timeout(struct timeout * to,int new)697 softclock_process_tick_timeout(struct timeout *to, int new)
698 {
699 	int delta = to->to_time - ticks;
700 
701 	if (delta > 0) {
702 		tostat.tos_scheduled++;
703 		if (!new)
704 			tostat.tos_rescheduled++;
705 		CIRCQ_INSERT_TAIL(&BUCKET(delta, to->to_time), &to->to_list);
706 		return;
707 	}
708 	if (!new && delta < 0)
709 		tostat.tos_late++;
710 	if (ISSET(to->to_flags, TIMEOUT_PROC)) {
711 #ifdef MULTIPROCESSOR
712 		if (ISSET(to->to_flags, TIMEOUT_MPSAFE))
713 			CIRCQ_INSERT_TAIL(&timeout_proc_mp, &to->to_list);
714 		else
715 #endif
716 			CIRCQ_INSERT_TAIL(&timeout_proc, &to->to_list);
717 		return;
718 	}
719 	timeout_run(to);
720 	tostat.tos_run_softclock++;
721 }
722 
723 /*
724  * Timeouts are processed here instead of timeout_hardclock_update()
725  * to avoid doing any more work at IPL_CLOCK than absolutely necessary.
726  * Down here at IPL_SOFTCLOCK other interrupts can be serviced promptly
727  * so the system remains responsive even if there is a surge of timeouts.
728  */
729 void
softclock(void * arg)730 softclock(void *arg)
731 {
732 	struct timeout *first_new, *to;
733 	int needsproc, new;
734 #ifdef MULTIPROCESSOR
735 	int need_proc_mp;
736 #endif
737 
738 	first_new = NULL;
739 	new = 0;
740 
741 	mtx_enter(&timeout_mutex);
742 	if (!CIRCQ_EMPTY(&timeout_new))
743 		first_new = timeout_from_circq(CIRCQ_FIRST(&timeout_new));
744 	CIRCQ_CONCAT(&timeout_todo, &timeout_new);
745 	while (!CIRCQ_EMPTY(&timeout_todo)) {
746 		to = timeout_from_circq(CIRCQ_FIRST(&timeout_todo));
747 		CIRCQ_REMOVE(&to->to_list);
748 		if (to == first_new)
749 			new = 1;
750 		if (to->to_kclock == KCLOCK_NONE)
751 			softclock_process_tick_timeout(to, new);
752 		else if (to->to_kclock == KCLOCK_UPTIME)
753 			softclock_process_kclock_timeout(to, new);
754 		else {
755 			panic("%s: invalid to_clock: %d",
756 			    __func__, to->to_kclock);
757 		}
758 	}
759 	tostat.tos_softclocks++;
760 	needsproc = !CIRCQ_EMPTY(&timeout_proc);
761 #ifdef MULTIPROCESSOR
762 	need_proc_mp = !CIRCQ_EMPTY(&timeout_proc_mp);
763 #endif
764 	mtx_leave(&timeout_mutex);
765 
766 	if (needsproc)
767 		wakeup(&timeout_proc);
768 #ifdef MULTIPROCESSOR
769 	if (need_proc_mp)
770 		wakeup(&timeout_proc_mp);
771 #endif
772 }
773 
774 void
softclock_create_thread(void * arg)775 softclock_create_thread(void *arg)
776 {
777 	if (kthread_create(softclock_thread, NULL, NULL, "softclock"))
778 		panic("fork softclock");
779 #ifdef MULTIPROCESSOR
780 	if (kthread_create(softclock_thread_mp, NULL, NULL, "softclockmp"))
781 		panic("kthread_create softclock_thread_mp");
782 #endif
783 }
784 
785 void
softclock_thread(void * arg)786 softclock_thread(void *arg)
787 {
788 	CPU_INFO_ITERATOR cii;
789 	struct cpu_info *ci;
790 	struct timeout *to;
791 	int s;
792 
793 	KERNEL_ASSERT_LOCKED();
794 
795 	/* Be conservative for the moment */
796 	CPU_INFO_FOREACH(cii, ci) {
797 		if (CPU_IS_PRIMARY(ci))
798 			break;
799 	}
800 	KASSERT(ci != NULL);
801 	sched_peg_curproc(ci);
802 
803 	s = splsoftclock();
804 	mtx_enter(&timeout_mutex);
805 	for (;;) {
806 		while (!CIRCQ_EMPTY(&timeout_proc)) {
807 			to = timeout_from_circq(CIRCQ_FIRST(&timeout_proc));
808 			CIRCQ_REMOVE(&to->to_list);
809 			timeout_run(to);
810 			tostat.tos_run_thread++;
811 		}
812 		tostat.tos_thread_wakeups++;
813 		msleep_nsec(&timeout_proc, &timeout_mutex, PSWP, "tmoslp",
814 		    INFSLP);
815 	}
816 	splx(s);
817 }
818 
819 #ifdef MULTIPROCESSOR
820 void
softclock_thread_mp(void * arg)821 softclock_thread_mp(void *arg)
822 {
823 	struct timeout *to;
824 
825 	KERNEL_ASSERT_LOCKED();
826 	KERNEL_UNLOCK();
827 
828 	mtx_enter(&timeout_mutex);
829 	for (;;) {
830 		while (!CIRCQ_EMPTY(&timeout_proc_mp)) {
831 			to = timeout_from_circq(CIRCQ_FIRST(&timeout_proc_mp));
832 			CIRCQ_REMOVE(&to->to_list);
833 			timeout_run(to);
834 			tostat.tos_run_thread++;
835 		}
836 		tostat.tos_thread_wakeups++;
837 		msleep_nsec(&timeout_proc_mp, &timeout_mutex, PSWP, "tmoslp",
838 		    INFSLP);
839 	}
840 }
841 #endif /* MULTIPROCESSOR */
842 
843 #ifndef SMALL_KERNEL
844 void
timeout_adjust_ticks(int adj)845 timeout_adjust_ticks(int adj)
846 {
847 	struct timeout *to;
848 	struct circq *p;
849 	int new_ticks, b;
850 
851 	/* adjusting the monotonic clock backwards would be a Bad Thing */
852 	if (adj <= 0)
853 		return;
854 
855 	mtx_enter(&timeout_mutex);
856 	new_ticks = ticks + adj;
857 	for (b = 0; b < nitems(timeout_wheel); b++) {
858 		p = CIRCQ_FIRST(&timeout_wheel[b]);
859 		while (p != &timeout_wheel[b]) {
860 			to = timeout_from_circq(p);
861 			p = CIRCQ_FIRST(p);
862 
863 			/* when moving a timeout forward need to reinsert it */
864 			if (to->to_time - ticks < adj)
865 				to->to_time = new_ticks;
866 			CIRCQ_REMOVE(&to->to_list);
867 			CIRCQ_INSERT_TAIL(&timeout_todo, &to->to_list);
868 		}
869 	}
870 	ticks = new_ticks;
871 	mtx_leave(&timeout_mutex);
872 }
873 #endif
874 
875 int
timeout_sysctl(void * oldp,size_t * oldlenp,void * newp,size_t newlen)876 timeout_sysctl(void *oldp, size_t *oldlenp, void *newp, size_t newlen)
877 {
878 	struct timeoutstat status;
879 
880 	mtx_enter(&timeout_mutex);
881 	memcpy(&status, &tostat, sizeof(status));
882 	mtx_leave(&timeout_mutex);
883 
884 	return sysctl_rdstruct(oldp, oldlenp, newp, &status, sizeof(status));
885 }
886 
887 #ifdef DDB
888 const char *db_kclock(int);
889 void db_show_callout_bucket(struct circq *);
890 void db_show_timeout(struct timeout *, struct circq *);
891 const char *db_timespec(const struct timespec *);
892 
893 const char *
db_kclock(int kclock)894 db_kclock(int kclock)
895 {
896 	switch (kclock) {
897 	case KCLOCK_UPTIME:
898 		return "uptime";
899 	default:
900 		return "invalid";
901 	}
902 }
903 
904 const char *
db_timespec(const struct timespec * ts)905 db_timespec(const struct timespec *ts)
906 {
907 	static char buf[32];
908 	struct timespec tmp, zero;
909 
910 	if (ts->tv_sec >= 0) {
911 		snprintf(buf, sizeof(buf), "%lld.%09ld",
912 		    ts->tv_sec, ts->tv_nsec);
913 		return buf;
914 	}
915 
916 	timespecclear(&zero);
917 	timespecsub(&zero, ts, &tmp);
918 	snprintf(buf, sizeof(buf), "-%lld.%09ld", tmp.tv_sec, tmp.tv_nsec);
919 	return buf;
920 }
921 
922 void
db_show_callout_bucket(struct circq * bucket)923 db_show_callout_bucket(struct circq *bucket)
924 {
925 	struct circq *p;
926 
927 	CIRCQ_FOREACH(p, bucket)
928 		db_show_timeout(timeout_from_circq(p), bucket);
929 }
930 
931 void
db_show_timeout(struct timeout * to,struct circq * bucket)932 db_show_timeout(struct timeout *to, struct circq *bucket)
933 {
934 	struct timespec remaining;
935 	struct kclock *kc;
936 	char buf[8];
937 	db_expr_t offset;
938 	struct circq *wheel;
939 	const char *name, *where;
940 	int width = sizeof(long) * 2;
941 
942 	db_find_sym_and_offset((vaddr_t)to->to_func, &name, &offset);
943 	name = name ? name : "?";
944 	if (bucket == &timeout_new)
945 		where = "new";
946 	else if (bucket == &timeout_todo)
947 		where = "softint";
948 	else if (bucket == &timeout_proc)
949 		where = "thread";
950 #ifdef MULTIPROCESSOR
951 	else if (bucket == &timeout_proc_mp)
952 		where = "thread-mp";
953 #endif
954 	else {
955 		if (to->to_kclock == KCLOCK_UPTIME)
956 			wheel = timeout_wheel_kc;
957 		else if (to->to_kclock == KCLOCK_NONE)
958 			wheel = timeout_wheel;
959 		else
960 			goto invalid;
961 		snprintf(buf, sizeof(buf), "%3ld/%1ld",
962 		    (bucket - wheel) % WHEELSIZE,
963 		    (bucket - wheel) / WHEELSIZE);
964 		where = buf;
965 	}
966 	if (to->to_kclock == KCLOCK_UPTIME) {
967 		kc = &timeout_kclock[to->to_kclock];
968 		timespecsub(&to->to_abstime, &kc->kc_lastscan, &remaining);
969 		db_printf("%20s  %8s  %9s  0x%0*lx  %s\n",
970 		    db_timespec(&remaining), db_kclock(to->to_kclock), where,
971 		    width, (ulong)to->to_arg, name);
972 	} else if (to->to_kclock == KCLOCK_NONE) {
973 		db_printf("%20d  %8s  %9s  0x%0*lx  %s\n",
974 		    to->to_time - ticks, "ticks", where,
975 		    width, (ulong)to->to_arg, name);
976 	} else
977 		goto invalid;
978 	return;
979 
980  invalid:
981 	db_printf("%s: timeout 0x%p: invalid to_kclock: %d",
982 	    __func__, to, to->to_kclock);
983 }
984 
985 void
db_show_callout(db_expr_t addr,int haddr,db_expr_t count,char * modif)986 db_show_callout(db_expr_t addr, int haddr, db_expr_t count, char *modif)
987 {
988 	struct kclock *kc;
989 	int width = sizeof(long) * 2 + 2;
990 	int b, i;
991 
992 	db_printf("%20s  %8s\n", "lastscan", "clock");
993 	db_printf("%20d  %8s\n", ticks, "ticks");
994 	for (i = 0; i < nitems(timeout_kclock); i++) {
995 		kc = &timeout_kclock[i];
996 		db_printf("%20s  %8s\n",
997 		    db_timespec(&kc->kc_lastscan), db_kclock(i));
998 	}
999 	db_printf("\n");
1000 	db_printf("%20s  %8s  %9s  %*s  %s\n",
1001 	    "remaining", "clock", "wheel", width, "arg", "func");
1002 	db_show_callout_bucket(&timeout_new);
1003 	db_show_callout_bucket(&timeout_todo);
1004 	db_show_callout_bucket(&timeout_proc);
1005 #ifdef MULTIPROCESSOR
1006 	db_show_callout_bucket(&timeout_proc_mp);
1007 #endif
1008 	for (b = 0; b < nitems(timeout_wheel); b++)
1009 		db_show_callout_bucket(&timeout_wheel[b]);
1010 	for (b = 0; b < nitems(timeout_wheel_kc); b++)
1011 		db_show_callout_bucket(&timeout_wheel_kc[b]);
1012 }
1013 #endif
1014