xref: /dragonfly/sys/kern/kern_timeout.c (revision 6b5c5d0d)
1 /*
2  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
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. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  * (c) UNIX System Laboratories, Inc.
38  * All or some portions of this file are derived from material licensed
39  * to the University of California by American Telephone and Telegraph
40  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
41  * the permission of UNIX System Laboratories, Inc.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *	This product includes software developed by the University of
54  *	California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  *
71  *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
72  * $FreeBSD: src/sys/kern/kern_timeout.c,v 1.59.2.1 2001/11/13 18:24:52 archie Exp $
73  * $DragonFly: src/sys/kern/kern_timeout.c,v 1.27 2007/11/14 18:27:52 swildner Exp $
74  */
75 /*
76  * DRAGONFLY BGL STATUS
77  *
78  *	All the API functions should be MP safe.
79  *
80  *	The callback functions will be flagged as being MP safe if the
81  *	timeout structure is initialized with callout_init_mp() instead of
82  *	callout_init().
83  *
84  *	The helper threads cannot be made preempt-capable until after we
85  *	clean up all the uses of splsoftclock() and related interlocks (which
86  *	require the related functions to be MP safe as well).
87  */
88 /*
89  * The callout mechanism is based on the work of Adam M. Costello and
90  * George Varghese, published in a technical report entitled "Redesigning
91  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
92  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
93  * used in this implementation was published by G. Varghese and T. Lauck in
94  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
95  * the Efficient Implementation of a Timer Facility" in the Proceedings of
96  * the 11th ACM Annual Symposium on Operating Systems Principles,
97  * Austin, Texas Nov 1987.
98  *
99  * The per-cpu augmentation was done by Matthew Dillon.
100  */
101 
102 #include "opt_ddb.h"
103 
104 #include <sys/param.h>
105 #include <sys/systm.h>
106 #include <sys/callout.h>
107 #include <sys/kernel.h>
108 #include <sys/interrupt.h>
109 #include <sys/thread.h>
110 #include <sys/thread2.h>
111 #include <ddb/ddb.h>
112 
113 #ifndef MAX_SOFTCLOCK_STEPS
114 #define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
115 #endif
116 
117 
118 struct softclock_pcpu {
119 	struct callout_tailq *callwheel;
120 	struct callout * volatile next;
121 	int softticks;		/* softticks index */
122 	int curticks;		/* per-cpu ticks counter */
123 	int isrunning;
124 	struct thread thread;
125 
126 };
127 
128 typedef struct softclock_pcpu *softclock_pcpu_t;
129 
130 /*
131  * TODO:
132  *	allocate more timeout table slots when table overflows.
133  */
134 static MALLOC_DEFINE(M_CALLOUT, "callout", "callout structures");
135 static int callwheelsize;
136 static int callwheelbits;
137 static int callwheelmask;
138 static struct softclock_pcpu softclock_pcpu_ary[MAXCPU];
139 
140 static void softclock_handler(void *arg);
141 
142 static void
143 swi_softclock_setup(void *arg)
144 {
145 	int cpu;
146 	int i;
147 
148 	/*
149 	 * Figure out how large a callwheel we need.  It must be a power of 2.
150 	 */
151 	callwheelsize = 1;
152 	callwheelbits = 0;
153 	while (callwheelsize < ncallout) {
154 		callwheelsize <<= 1;
155 		++callwheelbits;
156 	}
157 	callwheelmask = callwheelsize - 1;
158 
159 	/*
160 	 * Initialize per-cpu data structures.
161 	 */
162 	for (cpu = 0; cpu < ncpus; ++cpu) {
163 		softclock_pcpu_t sc;
164 
165 		sc = &softclock_pcpu_ary[cpu];
166 
167 		sc->callwheel = kmalloc(sizeof(*sc->callwheel) * callwheelsize,
168 					M_CALLOUT, M_WAITOK|M_ZERO);
169 		for (i = 0; i < callwheelsize; ++i)
170 			TAILQ_INIT(&sc->callwheel[i]);
171 
172 		/*
173 		 * Create a preemption-capable thread for each cpu to handle
174 		 * softclock timeouts on that cpu.  The preemption can only
175 		 * be blocked by a critical section.  The thread can itself
176 		 * be preempted by normal interrupts.
177 		 */
178 		lwkt_create(softclock_handler, sc, NULL,
179 			    &sc->thread, TDF_STOPREQ|TDF_INTTHREAD, cpu,
180 			    "softclock %d", cpu);
181 #if 0
182 		/*
183 		 * Do not make the thread preemptable until we clean up all
184 		 * the splsoftclock() calls in the system.  Since the threads
185 		 * are no longer operated as a software interrupt, the
186 		 * splsoftclock() calls will not have any effect on them.
187 		 */
188 		sc->thread.td_preemptable = lwkt_preempt;
189 #endif
190 	}
191 }
192 
193 /*
194  * Must occur after ncpus has been initialized.
195  */
196 SYSINIT(softclock_setup, SI_BOOT2_SOFTCLOCK, SI_ORDER_SECOND,
197 	swi_softclock_setup, NULL);
198 
199 /*
200  * This routine is called from the hardclock() (basically a FASTint/IPI) on
201  * each cpu in the system.  sc->curticks is this cpu's notion of the timebase.
202  * It IS NOT NECESSARILY SYNCHRONIZED WITH 'ticks'!  sc->softticks is where
203  * the callwheel is currently indexed.
204  *
205  * WARNING!  The MP lock is not necessarily held on call, nor can it be
206  * safely obtained.
207  *
208  * sc->softticks is adjusted by either this routine or our helper thread
209  * depending on whether the helper thread is running or not.
210  */
211 void
212 hardclock_softtick(globaldata_t gd)
213 {
214 	softclock_pcpu_t sc;
215 
216 	sc = &softclock_pcpu_ary[gd->gd_cpuid];
217 	++sc->curticks;
218 	if (sc->isrunning)
219 		return;
220 	if (sc->softticks == sc->curticks) {
221 		/*
222 		 * in sync, only wakeup the thread if there is something to
223 		 * do.
224 		 */
225 		if (TAILQ_FIRST(&sc->callwheel[sc->softticks & callwheelmask]))
226 		{
227 			sc->isrunning = 1;
228 			lwkt_schedule(&sc->thread);
229 		} else {
230 			++sc->softticks;
231 		}
232 	} else {
233 		/*
234 		 * out of sync, wakeup the thread unconditionally so it can
235 		 * catch up.
236 		 */
237 		sc->isrunning = 1;
238 		lwkt_schedule(&sc->thread);
239 	}
240 }
241 
242 /*
243  * This procedure is the main loop of our per-cpu helper thread.  The
244  * sc->isrunning flag prevents us from racing hardclock_softtick() and
245  * a critical section is sufficient to interlock sc->curticks and protect
246  * us from remote IPI's / list removal.
247  *
248  * The thread starts with the MP lock held and not in a critical section.
249  * The loop itself is MP safe while individual callbacks may or may not
250  * be, so we obtain or release the MP lock as appropriate.
251  */
252 static void
253 softclock_handler(void *arg)
254 {
255 	softclock_pcpu_t sc;
256 	struct callout *c;
257 	struct callout_tailq *bucket;
258 	void (*c_func)(void *);
259 	void *c_arg;
260 #ifdef SMP
261 	int mpsafe = 0;
262 #endif
263 
264 	lwkt_setpri_self(TDPRI_SOFT_NORM);
265 
266 	sc = arg;
267 	crit_enter();
268 loop:
269 	while (sc->softticks != (int)(sc->curticks + 1)) {
270 		bucket = &sc->callwheel[sc->softticks & callwheelmask];
271 
272 		for (c = TAILQ_FIRST(bucket); c; c = sc->next) {
273 			if (c->c_time != sc->softticks) {
274 				sc->next = TAILQ_NEXT(c, c_links.tqe);
275 				continue;
276 			}
277 #ifdef SMP
278 			if (c->c_flags & CALLOUT_MPSAFE) {
279 				if (mpsafe == 0) {
280 					mpsafe = 1;
281 					rel_mplock();
282 				}
283 			} else {
284 				/*
285 				 * The request might be removed while we
286 				 * are waiting to get the MP lock.  If it
287 				 * was removed sc->next will point to the
288 				 * next valid request or NULL, loop up.
289 				 */
290 				if (mpsafe) {
291 					mpsafe = 0;
292 					sc->next = c;
293 					get_mplock();
294 					if (c != sc->next)
295 						continue;
296 				}
297 			}
298 #endif
299 			sc->next = TAILQ_NEXT(c, c_links.tqe);
300 			TAILQ_REMOVE(bucket, c, c_links.tqe);
301 
302 			c_func = c->c_func;
303 			c_arg = c->c_arg;
304 			c->c_func = NULL;
305 			KKASSERT(c->c_flags & CALLOUT_DID_INIT);
306 			c->c_flags &= ~CALLOUT_PENDING;
307 			crit_exit();
308 			c_func(c_arg);
309 			crit_enter();
310 			/* NOTE: list may have changed */
311 		}
312 		++sc->softticks;
313 	}
314 	sc->isrunning = 0;
315 	lwkt_deschedule_self(&sc->thread);	/* == curthread */
316 	lwkt_switch();
317 	goto loop;
318 	/* NOT REACHED */
319 }
320 
321 /*
322  * New interface; clients allocate their own callout structures.
323  *
324  * callout_reset() - establish or change a timeout
325  * callout_stop() - disestablish a timeout
326  * callout_init() - initialize a callout structure so that it can
327  *			safely be passed to callout_reset() and callout_stop()
328  * callout_init_mp() - same but any installed functions must be MP safe.
329  *
330  * <sys/callout.h> defines three convenience macros:
331  *
332  * callout_active() - returns truth if callout has not been serviced
333  * callout_pending() - returns truth if callout is still waiting for timeout
334  * callout_deactivate() - marks the callout as having been serviced
335  */
336 
337 /*
338  * Start or restart a timeout.  Install the callout structure in the
339  * callwheel.  Callers may legally pass any value, even if 0 or negative,
340  * but since the sc->curticks index may have already been processed a
341  * minimum timeout of 1 tick will be enforced.
342  *
343  * The callout is installed on and will be processed on the current cpu's
344  * callout wheel.
345  *
346  * WARNING! This function may be called from any cpu but the caller must
347  * serialize callout_stop() and callout_reset() calls on the passed
348  * structure regardless of cpu.
349  */
350 void
351 callout_reset(struct callout *c, int to_ticks, void (*ftn)(void *),
352 		void *arg)
353 {
354 	softclock_pcpu_t sc;
355 	globaldata_t gd;
356 
357 #ifdef INVARIANTS
358         if ((c->c_flags & CALLOUT_DID_INIT) == 0) {
359 		callout_init(c);
360 		kprintf(
361 		    "callout_reset(%p) from %p: callout was not initialized\n",
362 		    c, ((int **)&c)[-1]);
363 #ifdef DDB
364 		db_print_backtrace();
365 #endif
366 	}
367 #endif
368 	gd = mycpu;
369 	sc = &softclock_pcpu_ary[gd->gd_cpuid];
370 	crit_enter_gd(gd);
371 
372 	if (c->c_flags & CALLOUT_PENDING)
373 		callout_stop(c);
374 
375 	if (to_ticks <= 0)
376 		to_ticks = 1;
377 
378 	c->c_arg = arg;
379 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
380 	c->c_func = ftn;
381 	c->c_time = sc->curticks + to_ticks;
382 #ifdef SMP
383 	c->c_gd = gd;
384 #endif
385 
386 	TAILQ_INSERT_TAIL(&sc->callwheel[c->c_time & callwheelmask],
387 			  c, c_links.tqe);
388 	crit_exit_gd(gd);
389 }
390 
391 /*
392  * Stop a running timer.  WARNING!  If called on a cpu other then the one
393  * the callout was started on this function will liveloop on its IPI to
394  * the target cpu to process the request.  It is possible for the callout
395  * to execute in that case.
396  *
397  * WARNING! This function may be called from any cpu but the caller must
398  * serialize callout_stop() and callout_reset() calls on the passed
399  * structure regardless of cpu.
400  *
401  * WARNING! This routine may be called from an IPI
402  */
403 int
404 callout_stop(struct callout *c)
405 {
406 	globaldata_t gd = mycpu;
407 #ifdef SMP
408 	globaldata_t tgd;
409 #endif
410 	softclock_pcpu_t sc;
411 
412 #ifdef INVARIANTS
413         if ((c->c_flags & CALLOUT_DID_INIT) == 0) {
414 		callout_init(c);
415 		kprintf(
416 		    "callout_stop(%p) from %p: callout was not initialized\n",
417 		    c, ((int **)&c)[-1]);
418 #ifdef DDB
419 		db_print_backtrace();
420 #endif
421 	}
422 #endif
423 	crit_enter_gd(gd);
424 
425 	/*
426 	 * Don't attempt to delete a callout that's not on the queue.  The
427 	 * callout may not have a cpu assigned to it.  Callers do not have
428 	 * to be on the issuing cpu but must still serialize access to the
429 	 * callout structure.
430 	 *
431 	 * We are not cpu-localized here and cannot safely modify the
432 	 * flags field in the callout structure.  Note that most of the
433 	 * time CALLOUT_ACTIVE will be 0 if CALLOUT_PENDING is also 0.
434 	 *
435 	 * If we race another cpu's dispatch of this callout it is possible
436 	 * for CALLOUT_ACTIVE to be set with CALLOUT_PENDING unset.  This
437 	 * will cause us to fall through and synchronize with the other
438 	 * cpu.
439 	 */
440 	if ((c->c_flags & CALLOUT_PENDING) == 0) {
441 #ifdef SMP
442 		if ((c->c_flags & CALLOUT_ACTIVE) == 0) {
443 			crit_exit_gd(gd);
444 			return (0);
445 		}
446 		if (c->c_gd == NULL || c->c_gd == gd) {
447 			c->c_flags &= ~CALLOUT_ACTIVE;
448 			crit_exit_gd(gd);
449 			return (0);
450 		}
451 		/* fall-through to the cpu-localization code. */
452 #else
453 		c->c_flags &= ~CALLOUT_ACTIVE;
454 		crit_exit_gd(gd);
455 		return (0);
456 #endif
457 	}
458 #ifdef SMP
459 	if ((tgd = c->c_gd) != gd) {
460 		/*
461 		 * If the callout is owned by a different CPU we have to
462 		 * execute the function synchronously on the target cpu.
463 		 */
464 		int seq;
465 
466 		cpu_ccfence();	/* don't let tgd alias c_gd */
467 		seq = lwkt_send_ipiq(tgd, (void *)callout_stop, c);
468 		lwkt_wait_ipiq(tgd, seq);
469 	} else
470 #endif
471 	{
472 		/*
473 		 * If the callout is owned by the same CPU we can
474 		 * process it directly, but if we are racing our helper
475 		 * thread (sc->next), we have to adjust sc->next.  The
476 		 * race is interlocked by a critical section.
477 		 */
478 		sc = &softclock_pcpu_ary[gd->gd_cpuid];
479 
480 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
481 		if (sc->next == c)
482 			sc->next = TAILQ_NEXT(c, c_links.tqe);
483 
484 		TAILQ_REMOVE(&sc->callwheel[c->c_time & callwheelmask],
485 				c, c_links.tqe);
486 		c->c_func = NULL;
487 	}
488 	crit_exit_gd(gd);
489 	return (1);
490 }
491 
492 /*
493  * Prepare a callout structure for use by callout_reset() and/or
494  * callout_stop().  The MP version of this routine requires that the callback
495  * function installed by callout_reset() be MP safe.
496  */
497 void
498 callout_init(struct callout *c)
499 {
500 	bzero(c, sizeof *c);
501 	c->c_flags = CALLOUT_DID_INIT;
502 }
503 
504 void
505 callout_init_mp(struct callout *c)
506 {
507 	callout_init(c);
508 	c->c_flags |= CALLOUT_MPSAFE;
509 }
510 
511 /* What, are you joking?  This is nuts! -Matt */
512 #if 0
513 #ifdef APM_FIXUP_CALLTODO
514 /*
515  * Adjust the kernel calltodo timeout list.  This routine is used after
516  * an APM resume to recalculate the calltodo timer list values with the
517  * number of hz's we have been sleeping.  The next hardclock() will detect
518  * that there are fired timers and run softclock() to execute them.
519  *
520  * Please note, I have not done an exhaustive analysis of what code this
521  * might break.  I am motivated to have my select()'s and alarm()'s that
522  * have expired during suspend firing upon resume so that the applications
523  * which set the timer can do the maintanence the timer was for as close
524  * as possible to the originally intended time.  Testing this code for a
525  * week showed that resuming from a suspend resulted in 22 to 25 timers
526  * firing, which seemed independant on whether the suspend was 2 hours or
527  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
528  */
529 void
530 adjust_timeout_calltodo(struct timeval *time_change)
531 {
532 	struct callout *p;
533 	unsigned long delta_ticks;
534 
535 	/*
536 	 * How many ticks were we asleep?
537 	 * (stolen from tvtohz()).
538 	 */
539 
540 	/* Don't do anything */
541 	if (time_change->tv_sec < 0)
542 		return;
543 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
544 		delta_ticks = (time_change->tv_sec * 1000000 +
545 			       time_change->tv_usec + (tick - 1)) / tick + 1;
546 	else if (time_change->tv_sec <= LONG_MAX / hz)
547 		delta_ticks = time_change->tv_sec * hz +
548 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
549 	else
550 		delta_ticks = LONG_MAX;
551 
552 	if (delta_ticks > INT_MAX)
553 		delta_ticks = INT_MAX;
554 
555 	/*
556 	 * Now rip through the timer calltodo list looking for timers
557 	 * to expire.
558 	 */
559 
560 	/* don't collide with softclock() */
561 	crit_enter();
562 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
563 		p->c_time -= delta_ticks;
564 
565 		/* Break if the timer had more time on it than delta_ticks */
566 		if (p->c_time > 0)
567 			break;
568 
569 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
570 		delta_ticks = -p->c_time;
571 	}
572 	crit_exit();
573 
574 	return;
575 }
576 #endif /* APM_FIXUP_CALLTODO */
577 #endif
578 
579