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