xref: /dflybsd-src/sys/kern/kern_timeout.c (revision 441d34b2441f59fde86fa4ef2d5d5cb7a6bfcb11)
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 <sys/param.h>
103 #include <sys/systm.h>
104 #include <sys/callout.h>
105 #include <sys/kernel.h>
106 #include <sys/interrupt.h>
107 #include <sys/thread.h>
108 
109 #include <sys/thread2.h>
110 #include <sys/mplock2.h>
111 
112 #ifndef MAX_SOFTCLOCK_STEPS
113 #define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
114 #endif
115 
116 
117 struct softclock_pcpu {
118 	struct callout_tailq *callwheel;
119 	struct callout * volatile next;
120 	int softticks;		/* softticks index */
121 	int curticks;		/* per-cpu ticks counter */
122 	int isrunning;
123 	struct thread thread;
124 
125 };
126 
127 typedef struct softclock_pcpu *softclock_pcpu_t;
128 
129 /*
130  * TODO:
131  *	allocate more timeout table slots when table overflows.
132  */
133 static MALLOC_DEFINE(M_CALLOUT, "callout", "callout structures");
134 static int callwheelsize;
135 static int callwheelbits;
136 static int callwheelmask;
137 static struct softclock_pcpu softclock_pcpu_ary[MAXCPU];
138 
139 static void softclock_handler(void *arg);
140 
141 static void
142 swi_softclock_setup(void *arg)
143 {
144 	int cpu;
145 	int i;
146 
147 	/*
148 	 * Figure out how large a callwheel we need.  It must be a power of 2.
149 	 */
150 	callwheelsize = 1;
151 	callwheelbits = 0;
152 	while (callwheelsize < ncallout) {
153 		callwheelsize <<= 1;
154 		++callwheelbits;
155 	}
156 	callwheelmask = callwheelsize - 1;
157 
158 	/*
159 	 * Initialize per-cpu data structures.
160 	 */
161 	for (cpu = 0; cpu < ncpus; ++cpu) {
162 		softclock_pcpu_t sc;
163 
164 		sc = &softclock_pcpu_ary[cpu];
165 
166 		sc->callwheel = kmalloc(sizeof(*sc->callwheel) * callwheelsize,
167 					M_CALLOUT, M_WAITOK|M_ZERO);
168 		for (i = 0; i < callwheelsize; ++i)
169 			TAILQ_INIT(&sc->callwheel[i]);
170 
171 		/*
172 		 * Create a preemption-capable thread for each cpu to handle
173 		 * softclock timeouts on that cpu.  The preemption can only
174 		 * be blocked by a critical section.  The thread can itself
175 		 * be preempted by normal interrupts.
176 		 */
177 		lwkt_create(softclock_handler, sc, NULL,
178 			    &sc->thread, TDF_STOPREQ|TDF_INTTHREAD, cpu,
179 			    "softclock %d", cpu);
180 #if 0
181 		/*
182 		 * Do not make the thread preemptable until we clean up all
183 		 * the splsoftclock() calls in the system.  Since the threads
184 		 * are no longer operated as a software interrupt, the
185 		 * splsoftclock() calls will not have any effect on them.
186 		 */
187 		sc->thread.td_preemptable = lwkt_preempt;
188 #endif
189 	}
190 }
191 
192 /*
193  * Must occur after ncpus has been initialized.
194  */
195 SYSINIT(softclock_setup, SI_BOOT2_SOFTCLOCK, SI_ORDER_SECOND,
196 	swi_softclock_setup, NULL);
197 
198 /*
199  * This routine is called from the hardclock() (basically a FASTint/IPI) on
200  * each cpu in the system.  sc->curticks is this cpu's notion of the timebase.
201  * It IS NOT NECESSARILY SYNCHRONIZED WITH 'ticks'!  sc->softticks is where
202  * the callwheel is currently indexed.
203  *
204  * WARNING!  The MP lock is not necessarily held on call, nor can it be
205  * safely obtained.
206  *
207  * sc->softticks is adjusted by either this routine or our helper thread
208  * depending on whether the helper thread is running or not.
209  */
210 void
211 hardclock_softtick(globaldata_t gd)
212 {
213 	softclock_pcpu_t sc;
214 
215 	sc = &softclock_pcpu_ary[gd->gd_cpuid];
216 	++sc->curticks;
217 	if (sc->isrunning)
218 		return;
219 	if (sc->softticks == sc->curticks) {
220 		/*
221 		 * in sync, only wakeup the thread if there is something to
222 		 * do.
223 		 */
224 		if (TAILQ_FIRST(&sc->callwheel[sc->softticks & callwheelmask]))
225 		{
226 			sc->isrunning = 1;
227 			lwkt_schedule(&sc->thread);
228 		} else {
229 			++sc->softticks;
230 		}
231 	} else {
232 		/*
233 		 * out of sync, wakeup the thread unconditionally so it can
234 		 * catch up.
235 		 */
236 		sc->isrunning = 1;
237 		lwkt_schedule(&sc->thread);
238 	}
239 }
240 
241 /*
242  * This procedure is the main loop of our per-cpu helper thread.  The
243  * sc->isrunning flag prevents us from racing hardclock_softtick() and
244  * a critical section is sufficient to interlock sc->curticks and protect
245  * us from remote IPI's / list removal.
246  *
247  * The thread starts with the MP lock held and not in a critical section.
248  * The loop itself is MP safe while individual callbacks may or may not
249  * be, so we obtain or release the MP lock as appropriate.
250  */
251 static void
252 softclock_handler(void *arg)
253 {
254 	softclock_pcpu_t sc;
255 	struct callout *c;
256 	struct callout_tailq *bucket;
257 	void (*c_func)(void *);
258 	void *c_arg;
259 #ifdef SMP
260 	int mpsafe = 0;
261 #endif
262 
263 	lwkt_setpri_self(TDPRI_SOFT_NORM);
264 
265 	sc = arg;
266 	crit_enter();
267 loop:
268 	while (sc->softticks != (int)(sc->curticks + 1)) {
269 		bucket = &sc->callwheel[sc->softticks & callwheelmask];
270 
271 		for (c = TAILQ_FIRST(bucket); c; c = sc->next) {
272 			if (c->c_time != sc->softticks) {
273 				sc->next = TAILQ_NEXT(c, c_links.tqe);
274 				continue;
275 			}
276 #ifdef SMP
277 			if (c->c_flags & CALLOUT_MPSAFE) {
278 				if (mpsafe == 0) {
279 					mpsafe = 1;
280 					rel_mplock();
281 				}
282 			} else {
283 				/*
284 				 * The request might be removed while we
285 				 * are waiting to get the MP lock.  If it
286 				 * was removed sc->next will point to the
287 				 * next valid request or NULL, loop up.
288 				 */
289 				if (mpsafe) {
290 					mpsafe = 0;
291 					sc->next = c;
292 					get_mplock();
293 					if (c != sc->next)
294 						continue;
295 				}
296 			}
297 #endif
298 			sc->next = TAILQ_NEXT(c, c_links.tqe);
299 			TAILQ_REMOVE(bucket, c, c_links.tqe);
300 
301 			c_func = c->c_func;
302 			c_arg = c->c_arg;
303 			c->c_func = NULL;
304 			KKASSERT(c->c_flags & CALLOUT_DID_INIT);
305 			c->c_flags &= ~CALLOUT_PENDING;
306 			crit_exit();
307 			c_func(c_arg);
308 			crit_enter();
309 			/* NOTE: list may have changed */
310 		}
311 		++sc->softticks;
312 	}
313 	sc->isrunning = 0;
314 	lwkt_deschedule_self(&sc->thread);	/* == curthread */
315 	lwkt_switch();
316 	goto loop;
317 	/* NOT REACHED */
318 }
319 
320 /*
321  * New interface; clients allocate their own callout structures.
322  *
323  * callout_reset() - establish or change a timeout
324  * callout_stop() - disestablish a timeout
325  * callout_init() - initialize a callout structure so that it can
326  *			safely be passed to callout_reset() and callout_stop()
327  * callout_init_mp() - same but any installed functions must be MP safe.
328  *
329  * <sys/callout.h> defines three convenience macros:
330  *
331  * callout_active() - returns truth if callout has not been serviced
332  * callout_pending() - returns truth if callout is still waiting for timeout
333  * callout_deactivate() - marks the callout as having been serviced
334  */
335 
336 /*
337  * Start or restart a timeout.  Install the callout structure in the
338  * callwheel.  Callers may legally pass any value, even if 0 or negative,
339  * but since the sc->curticks index may have already been processed a
340  * minimum timeout of 1 tick will be enforced.
341  *
342  * The callout is installed on and will be processed on the current cpu's
343  * callout wheel.
344  *
345  * WARNING! This function may be called from any cpu but the caller must
346  * serialize callout_stop() and callout_reset() calls on the passed
347  * structure regardless of cpu.
348  */
349 void
350 callout_reset(struct callout *c, int to_ticks, void (*ftn)(void *),
351 		void *arg)
352 {
353 	softclock_pcpu_t sc;
354 	globaldata_t gd;
355 
356 #ifdef INVARIANTS
357         if ((c->c_flags & CALLOUT_DID_INIT) == 0) {
358 		callout_init(c);
359 		kprintf(
360 		    "callout_reset(%p) from %p: callout was not initialized\n",
361 		    c, ((int **)&c)[-1]);
362 		print_backtrace(-1);
363 	}
364 #endif
365 	gd = mycpu;
366 	sc = &softclock_pcpu_ary[gd->gd_cpuid];
367 	crit_enter_gd(gd);
368 
369 	if (c->c_flags & CALLOUT_PENDING)
370 		callout_stop(c);
371 
372 	if (to_ticks <= 0)
373 		to_ticks = 1;
374 
375 	c->c_arg = arg;
376 	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
377 	c->c_func = ftn;
378 	c->c_time = sc->curticks + to_ticks;
379 #ifdef SMP
380 	c->c_gd = gd;
381 #endif
382 
383 	TAILQ_INSERT_TAIL(&sc->callwheel[c->c_time & callwheelmask],
384 			  c, c_links.tqe);
385 	crit_exit_gd(gd);
386 }
387 
388 /*
389  * Stop a running timer.  WARNING!  If called on a cpu other then the one
390  * the callout was started on this function will liveloop on its IPI to
391  * the target cpu to process the request.  It is possible for the callout
392  * to execute in that case.
393  *
394  * WARNING! This function may be called from any cpu but the caller must
395  * serialize callout_stop() and callout_reset() calls on the passed
396  * structure regardless of cpu.
397  *
398  * WARNING! This routine may be called from an IPI
399  */
400 int
401 callout_stop(struct callout *c)
402 {
403 	globaldata_t gd = mycpu;
404 #ifdef SMP
405 	globaldata_t tgd;
406 #endif
407 	softclock_pcpu_t sc;
408 
409 #ifdef INVARIANTS
410         if ((c->c_flags & CALLOUT_DID_INIT) == 0) {
411 		callout_init(c);
412 		kprintf(
413 		    "callout_stop(%p) from %p: callout was not initialized\n",
414 		    c, ((int **)&c)[-1]);
415 		print_backtrace(-1);
416 	}
417 #endif
418 	crit_enter_gd(gd);
419 
420 	/*
421 	 * Don't attempt to delete a callout that's not on the queue.  The
422 	 * callout may not have a cpu assigned to it.  Callers do not have
423 	 * to be on the issuing cpu but must still serialize access to the
424 	 * callout structure.
425 	 *
426 	 * We are not cpu-localized here and cannot safely modify the
427 	 * flags field in the callout structure.  Note that most of the
428 	 * time CALLOUT_ACTIVE will be 0 if CALLOUT_PENDING is also 0.
429 	 *
430 	 * If we race another cpu's dispatch of this callout it is possible
431 	 * for CALLOUT_ACTIVE to be set with CALLOUT_PENDING unset.  This
432 	 * will cause us to fall through and synchronize with the other
433 	 * cpu.
434 	 */
435 	if ((c->c_flags & CALLOUT_PENDING) == 0) {
436 #ifdef SMP
437 		if ((c->c_flags & CALLOUT_ACTIVE) == 0) {
438 			crit_exit_gd(gd);
439 			return (0);
440 		}
441 		if (c->c_gd == NULL || c->c_gd == gd) {
442 			c->c_flags &= ~CALLOUT_ACTIVE;
443 			crit_exit_gd(gd);
444 			return (0);
445 		}
446 		/* fall-through to the cpu-localization code. */
447 #else
448 		c->c_flags &= ~CALLOUT_ACTIVE;
449 		crit_exit_gd(gd);
450 		return (0);
451 #endif
452 	}
453 #ifdef SMP
454 	if ((tgd = c->c_gd) != gd) {
455 		/*
456 		 * If the callout is owned by a different CPU we have to
457 		 * execute the function synchronously on the target cpu.
458 		 */
459 		int seq;
460 
461 		cpu_ccfence();	/* don't let tgd alias c_gd */
462 		seq = lwkt_send_ipiq(tgd, (void *)callout_stop, c);
463 		lwkt_wait_ipiq(tgd, seq);
464 	} else
465 #endif
466 	{
467 		/*
468 		 * If the callout is owned by the same CPU we can
469 		 * process it directly, but if we are racing our helper
470 		 * thread (sc->next), we have to adjust sc->next.  The
471 		 * race is interlocked by a critical section.
472 		 */
473 		sc = &softclock_pcpu_ary[gd->gd_cpuid];
474 
475 		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
476 		if (sc->next == c)
477 			sc->next = TAILQ_NEXT(c, c_links.tqe);
478 
479 		TAILQ_REMOVE(&sc->callwheel[c->c_time & callwheelmask],
480 				c, c_links.tqe);
481 		c->c_func = NULL;
482 	}
483 	crit_exit_gd(gd);
484 	return (1);
485 }
486 
487 /*
488  * Prepare a callout structure for use by callout_reset() and/or
489  * callout_stop().  The MP version of this routine requires that the callback
490  * function installed by callout_reset() be MP safe.
491  *
492  * The init functions can be called from any cpu and do not have to be
493  * called from the cpu that the timer will eventually run on.
494  */
495 void
496 callout_init(struct callout *c)
497 {
498 	bzero(c, sizeof *c);
499 	c->c_flags = CALLOUT_DID_INIT;
500 }
501 
502 void
503 callout_init_mp(struct callout *c)
504 {
505 	callout_init(c);
506 	c->c_flags |= CALLOUT_MPSAFE;
507 }
508 
509 /* What, are you joking?  This is nuts! -Matt */
510 #if 0
511 #ifdef APM_FIXUP_CALLTODO
512 /*
513  * Adjust the kernel calltodo timeout list.  This routine is used after
514  * an APM resume to recalculate the calltodo timer list values with the
515  * number of hz's we have been sleeping.  The next hardclock() will detect
516  * that there are fired timers and run softclock() to execute them.
517  *
518  * Please note, I have not done an exhaustive analysis of what code this
519  * might break.  I am motivated to have my select()'s and alarm()'s that
520  * have expired during suspend firing upon resume so that the applications
521  * which set the timer can do the maintanence the timer was for as close
522  * as possible to the originally intended time.  Testing this code for a
523  * week showed that resuming from a suspend resulted in 22 to 25 timers
524  * firing, which seemed independant on whether the suspend was 2 hours or
525  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
526  */
527 void
528 adjust_timeout_calltodo(struct timeval *time_change)
529 {
530 	struct callout *p;
531 	unsigned long delta_ticks;
532 
533 	/*
534 	 * How many ticks were we asleep?
535 	 * (stolen from tvtohz()).
536 	 */
537 
538 	/* Don't do anything */
539 	if (time_change->tv_sec < 0)
540 		return;
541 	else if (time_change->tv_sec <= LONG_MAX / 1000000)
542 		delta_ticks = (time_change->tv_sec * 1000000 +
543 			       time_change->tv_usec + (tick - 1)) / tick + 1;
544 	else if (time_change->tv_sec <= LONG_MAX / hz)
545 		delta_ticks = time_change->tv_sec * hz +
546 			      (time_change->tv_usec + (tick - 1)) / tick + 1;
547 	else
548 		delta_ticks = LONG_MAX;
549 
550 	if (delta_ticks > INT_MAX)
551 		delta_ticks = INT_MAX;
552 
553 	/*
554 	 * Now rip through the timer calltodo list looking for timers
555 	 * to expire.
556 	 */
557 
558 	/* don't collide with softclock() */
559 	crit_enter();
560 	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
561 		p->c_time -= delta_ticks;
562 
563 		/* Break if the timer had more time on it than delta_ticks */
564 		if (p->c_time > 0)
565 			break;
566 
567 		/* take back the ticks the timer didn't use (p->c_time <= 0) */
568 		delta_ticks = -p->c_time;
569 	}
570 	crit_exit();
571 
572 	return;
573 }
574 #endif /* APM_FIXUP_CALLTODO */
575 #endif
576 
577