Home | History | Annotate | Line # | Download | only in kern
kern_timeout.c revision 1.17.20.4
      1 /*	$NetBSD: kern_timeout.c,v 1.17.20.4 2007/01/19 00:38:00 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003, 2006 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.
      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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 2001 Thomas Nordin <nordin (at) openbsd.org>
     41  * Copyright (c) 2000-2001 Artur Grabowski <art (at) openbsd.org>
     42  * All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  *
     48  * 1. Redistributions of source code must retain the above copyright
     49  *    notice, this list of conditions and the following disclaimer.
     50  * 2. Redistributions in binary form must reproduce the above copyright
     51  *    notice, this list of conditions and the following disclaimer in the
     52  *    documentation and/or other materials provided with the distribution.
     53  * 3. The name of the author may not be used to endorse or promote products
     54  *    derived from this software without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
     57  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
     58  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
     59  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     60  * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     61  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     62  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     63  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     64  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     65  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 __KERNEL_RCSID(0, "$NetBSD: kern_timeout.c,v 1.17.20.4 2007/01/19 00:38:00 yamt Exp $");
     70 
     71 /*
     72  * Adapted from OpenBSD: kern_timeout.c,v 1.15 2002/12/08 04:21:07 art Exp,
     73  * modified to match NetBSD's pre-existing callout API.
     74  */
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/kernel.h>
     79 #include <sys/lock.h>
     80 #include <sys/callout.h>
     81 #include <sys/mutex.h>
     82 
     83 #ifdef DDB
     84 #include <machine/db_machdep.h>
     85 #include <ddb/db_interface.h>
     86 #include <ddb/db_access.h>
     87 #include <ddb/db_sym.h>
     88 #include <ddb/db_output.h>
     89 #endif
     90 
     91 /*
     92  * Timeouts are kept in a hierarchical timing wheel. The c_time is the value
     93  * of the global variable "hardclock_ticks" when the timeout should be called.
     94  * There are four levels with 256 buckets each. See 'Scheme 7' in
     95  * "Hashed and Hierarchical Timing Wheels: Efficient Data Structures for
     96  * Implementing a Timer Facility" by George Varghese and Tony Lauck.
     97  */
     98 #define BUCKETS 1024
     99 #define WHEELSIZE 256
    100 #define WHEELMASK 255
    101 #define WHEELBITS 8
    102 
    103 static struct callout_circq timeout_wheel[BUCKETS];	/* Queues of timeouts */
    104 static struct callout_circq timeout_todo;		/* Worklist */
    105 
    106 #define MASKWHEEL(wheel, time) (((time) >> ((wheel)*WHEELBITS)) & WHEELMASK)
    107 
    108 #define BUCKET(rel, abs)						\
    109     (((rel) <= (1 << (2*WHEELBITS)))					\
    110     	? ((rel) <= (1 << WHEELBITS))					\
    111             ? &timeout_wheel[MASKWHEEL(0, (abs))]			\
    112             : &timeout_wheel[MASKWHEEL(1, (abs)) + WHEELSIZE]		\
    113         : ((rel) <= (1 << (3*WHEELBITS)))				\
    114             ? &timeout_wheel[MASKWHEEL(2, (abs)) + 2*WHEELSIZE]		\
    115             : &timeout_wheel[MASKWHEEL(3, (abs)) + 3*WHEELSIZE])
    116 
    117 #define MOVEBUCKET(wheel, time)						\
    118     CIRCQ_APPEND(&timeout_todo,						\
    119         &timeout_wheel[MASKWHEEL((wheel), (time)) + (wheel)*WHEELSIZE])
    120 
    121 /*
    122  * All wheels are locked with the same lock (which must also block out all
    123  * interrupts).
    124  */
    125 kmutex_t callout_mutex;
    126 
    127 /*
    128  * Circular queue definitions.
    129  */
    130 
    131 #define CIRCQ_INIT(list)						\
    132 do {									\
    133         (list)->cq_next_l = (list);					\
    134         (list)->cq_prev_l = (list);					\
    135 } while (/*CONSTCOND*/0)
    136 
    137 #define CIRCQ_INSERT(elem, list)					\
    138 do {									\
    139         (elem)->cq_prev_e = (list)->cq_prev_e;				\
    140         (elem)->cq_next_l = (list);					\
    141         (list)->cq_prev_l->cq_next_l = (elem);				\
    142         (list)->cq_prev_l = (elem);					\
    143 } while (/*CONSTCOND*/0)
    144 
    145 #define CIRCQ_APPEND(fst, snd)						\
    146 do {									\
    147         if (!CIRCQ_EMPTY(snd)) {					\
    148                 (fst)->cq_prev_l->cq_next_l = (snd)->cq_next_l;		\
    149                 (snd)->cq_next_l->cq_prev_l = (fst)->cq_prev_l;		\
    150                 (snd)->cq_prev_l->cq_next_l = (fst);			\
    151                 (fst)->cq_prev_l = (snd)->cq_prev_l;			\
    152                 CIRCQ_INIT(snd);					\
    153         }								\
    154 } while (/*CONSTCOND*/0)
    155 
    156 #define CIRCQ_REMOVE(elem)						\
    157 do {									\
    158         (elem)->cq_next_l->cq_prev_e = (elem)->cq_prev_e;		\
    159         (elem)->cq_prev_l->cq_next_e = (elem)->cq_next_e;		\
    160 } while (/*CONSTCOND*/0)
    161 
    162 #define CIRCQ_FIRST(list)	((list)->cq_next_e)
    163 #define CIRCQ_NEXT(elem)	((elem)->cq_next_e)
    164 #define CIRCQ_LAST(elem,list)	((elem)->cq_next_l == (list))
    165 #define CIRCQ_EMPTY(list)	((list)->cq_next_l == (list))
    166 
    167 /*
    168  * Some of the "math" in here is a bit tricky.
    169  *
    170  * We have to beware of wrapping ints.
    171  * We use the fact that any element added to the queue must be added with a
    172  * positive time. That means that any element `to' on the queue cannot be
    173  * scheduled to timeout further in time than INT_MAX, but c->c_time can
    174  * be positive or negative so comparing it with anything is dangerous.
    175  * The only way we can use the c->c_time value in any predictable way
    176  * is when we calculate how far in the future `to' will timeout -
    177  * "c->c_time - hardclock_ticks". The result will always be positive for
    178  * future timeouts and 0 or negative for due timeouts.
    179  */
    180 
    181 #ifdef CALLOUT_EVENT_COUNTERS
    182 static struct evcnt callout_ev_late;
    183 #endif
    184 
    185 /*
    186  * callout_barrier:
    187  *
    188  *	If the callout is running on another CPU, busy wait until it
    189  *	completes.
    190  */
    191 static inline void
    192 callout_barrier(struct callout *c)
    193 {
    194 #ifdef MULTIPROCESSOR
    195 	struct cpu_info *ci;
    196 
    197 	LOCK_ASSERT(mutex_owned(&callout_mutex));
    198 
    199 	/*
    200 	 * The callout may have already been dispatched to run on the
    201 	 * current CPU.  It's possible for us to arrive here before it
    202 	 * actually runs because the SPL is dropped from IPL_SCHED in
    203 	 * softclock(), and IPL_SOFTCLOCK is low priority. We can't deal
    204 	 * with that race easily, so for now the caller must deal with
    205 	 * it.
    206 	 */
    207 	while ((ci = c->c_oncpu) != NULL && ci != curcpu() &&
    208 	    ci->ci_data.cpu_callout == c) {
    209 		smutex_exit(&callout_mutex);
    210 		while (ci->ci_data.cpu_callout == c)
    211 			;
    212 		smutex_enter(&callout_mutex);
    213 	}
    214 	c->c_oncpu = NULL;
    215 #endif
    216 }
    217 
    218 /*
    219  * callout_startup:
    220  *
    221  *	Initialize the callout facility, called at system startup time.
    222  */
    223 void
    224 callout_startup(void)
    225 {
    226 	int b;
    227 
    228 	CIRCQ_INIT(&timeout_todo);
    229 	for (b = 0; b < BUCKETS; b++)
    230 		CIRCQ_INIT(&timeout_wheel[b]);
    231 	mutex_init(&callout_mutex, MUTEX_SPIN, IPL_SCHED);
    232 
    233 #ifdef CALLOUT_EVENT_COUNTERS
    234 	evcnt_attach_dynamic(&callout_ev_late, EVCNT_TYPE_MISC,
    235 	    NULL, "callout", "late");
    236 #endif
    237 }
    238 
    239 /*
    240  * callout_init:
    241  *
    242  *	Initialize a callout structure.
    243  */
    244 void
    245 callout_init(struct callout *c)
    246 {
    247 
    248 	memset(c, 0, sizeof(*c));
    249 }
    250 
    251 /*
    252  * callout_reset:
    253  *
    254  *	Reset a callout structure with a new function and argument, and
    255  *	schedule it to run.
    256  */
    257 void
    258 callout_reset(struct callout *c, int to_ticks, void (*func)(void *), void *arg)
    259 {
    260 	int old_time;
    261 
    262 	KASSERT(to_ticks >= 0);
    263 
    264 	smutex_enter(&callout_mutex);
    265 
    266 	callout_barrier(c);
    267 
    268 	/* Initialize the time here, it won't change. */
    269 	old_time = c->c_time;
    270 	c->c_time = to_ticks + hardclock_ticks;
    271 	c->c_flags &= ~(CALLOUT_FIRED|CALLOUT_INVOKING);
    272 
    273 	c->c_func = func;
    274 	c->c_arg = arg;
    275 
    276 	/*
    277 	 * If this timeout is already scheduled and now is moved
    278 	 * earlier, reschedule it now. Otherwise leave it in place
    279 	 * and let it be rescheduled later.
    280 	 */
    281 	if (callout_pending(c)) {
    282 		if (c->c_time - old_time < 0) {
    283 			CIRCQ_REMOVE(&c->c_list);
    284 			CIRCQ_INSERT(&c->c_list, &timeout_todo);
    285 		}
    286 	} else {
    287 		c->c_flags |= CALLOUT_PENDING;
    288 		CIRCQ_INSERT(&c->c_list, &timeout_todo);
    289 	}
    290 
    291 	smutex_exit(&callout_mutex);
    292 }
    293 
    294 /*
    295  * callout_schedule:
    296  *
    297  *	Schedule a callout to run.  The function and argument must
    298  *	already be set in the callout structure.
    299  */
    300 void
    301 callout_schedule(struct callout *c, int to_ticks)
    302 {
    303 	int old_time;
    304 
    305 	KASSERT(to_ticks >= 0);
    306 
    307 	smutex_enter(&callout_mutex);
    308 
    309 	callout_barrier(c);
    310 
    311 	/* Initialize the time here, it won't change. */
    312 	old_time = c->c_time;
    313 	c->c_time = to_ticks + hardclock_ticks;
    314 	c->c_flags &= ~(CALLOUT_FIRED|CALLOUT_INVOKING);
    315 
    316 	/*
    317 	 * If this timeout is already scheduled and now is moved
    318 	 * earlier, reschedule it now. Otherwise leave it in place
    319 	 * and let it be rescheduled later.
    320 	 */
    321 	if (callout_pending(c)) {
    322 		if (c->c_time - old_time < 0) {
    323 			CIRCQ_REMOVE(&c->c_list);
    324 			CIRCQ_INSERT(&c->c_list, &timeout_todo);
    325 		}
    326 	} else {
    327 		c->c_flags |= CALLOUT_PENDING;
    328 		CIRCQ_INSERT(&c->c_list, &timeout_todo);
    329 	}
    330 
    331 	smutex_exit(&callout_mutex);
    332 }
    333 
    334 /*
    335  * callout_stop:
    336  *
    337  *	Cancel a pending callout.
    338  */
    339 void
    340 callout_stop(struct callout *c)
    341 {
    342 
    343 	smutex_enter(&callout_mutex);
    344 
    345 	callout_barrier(c);
    346 
    347 	if (callout_pending(c))
    348 		CIRCQ_REMOVE(&c->c_list);
    349 
    350 	c->c_flags &= ~(CALLOUT_PENDING|CALLOUT_FIRED);
    351 
    352 	smutex_exit(&callout_mutex);
    353 }
    354 
    355 /*
    356  * This is called from hardclock() once every tick.
    357  * We return !0 if we need to schedule a softclock.
    358  */
    359 int
    360 callout_hardclock(void)
    361 {
    362 	int needsoftclock;
    363 
    364 	smutex_enter(&callout_mutex);
    365 
    366 	MOVEBUCKET(0, hardclock_ticks);
    367 	if (MASKWHEEL(0, hardclock_ticks) == 0) {
    368 		MOVEBUCKET(1, hardclock_ticks);
    369 		if (MASKWHEEL(1, hardclock_ticks) == 0) {
    370 			MOVEBUCKET(2, hardclock_ticks);
    371 			if (MASKWHEEL(2, hardclock_ticks) == 0)
    372 				MOVEBUCKET(3, hardclock_ticks);
    373 		}
    374 	}
    375 
    376 	needsoftclock = !CIRCQ_EMPTY(&timeout_todo);
    377 	smutex_exit(&callout_mutex);
    378 
    379 	return needsoftclock;
    380 }
    381 
    382 /* ARGSUSED */
    383 void
    384 softclock(void *v)
    385 {
    386 	struct cpu_info *ci;
    387 	struct callout *c;
    388 	void (*func)(void *);
    389 	void *arg;
    390 
    391 	ci = curcpu();
    392 
    393 	smutex_enter(&callout_mutex);
    394 
    395 	while (!CIRCQ_EMPTY(&timeout_todo)) {
    396 		c = CIRCQ_FIRST(&timeout_todo);
    397 		CIRCQ_REMOVE(&c->c_list);
    398 
    399 		/* If due run it, otherwise insert it into the right bucket. */
    400 		if (c->c_time - hardclock_ticks > 0) {
    401 			CIRCQ_INSERT(&c->c_list,
    402 			    BUCKET((c->c_time - hardclock_ticks), c->c_time));
    403 		} else {
    404 #ifdef CALLOUT_EVENT_COUNTERS
    405 			if (c->c_time - hardclock_ticks < 0)
    406 				callout_ev_late.ev_count++;
    407 #endif
    408 			c->c_flags = (c->c_flags & ~CALLOUT_PENDING) |
    409 			    (CALLOUT_FIRED|CALLOUT_INVOKING);
    410 
    411 			func = c->c_func;
    412 			arg = c->c_arg;
    413 
    414 #ifdef MULTIPROCESSOR
    415 			c->c_oncpu = ci;
    416 			ci->ci_data.cpu_callout = c;
    417 #endif
    418 			smutex_exit(&callout_mutex);
    419 			(*func)(arg);
    420 			smutex_enter(&callout_mutex);
    421 #ifdef MULTIPROCESSOR
    422 			ci->ci_data.cpu_callout = NULL;
    423 			/*
    424 			 * we can't touch 'c' here because it might be
    425 			 * freed already.
    426 			 */
    427 #endif
    428 		}
    429 	}
    430 
    431 	smutex_exit(&callout_mutex);
    432 }
    433 
    434 #ifdef DDB
    435 static void
    436 db_show_callout_bucket(struct callout_circq *bucket)
    437 {
    438 	struct callout *c;
    439 	db_expr_t offset;
    440 	const char *name;
    441 	static char question[] = "?";
    442 
    443 	if (CIRCQ_EMPTY(bucket))
    444 		return;
    445 
    446 	for (c = CIRCQ_FIRST(bucket); /*nothing*/; c = CIRCQ_NEXT(&c->c_list)) {
    447 		db_find_sym_and_offset((db_addr_t)(intptr_t)c->c_func, &name,
    448 		    &offset);
    449 		name = name ? name : question;
    450 #ifdef _LP64
    451 #define	POINTER_WIDTH	"%16lx"
    452 #else
    453 #define	POINTER_WIDTH	"%8lx"
    454 #endif
    455 		db_printf("%9d %2d/%-4d " POINTER_WIDTH "  %s\n",
    456 		    c->c_time - hardclock_ticks,
    457 		    (int)((bucket - timeout_wheel) / WHEELSIZE),
    458 		    (int)(bucket - timeout_wheel), (u_long) c->c_arg, name);
    459 
    460 		if (CIRCQ_LAST(&c->c_list, bucket))
    461 			break;
    462 	}
    463 }
    464 
    465 void
    466 db_show_callout(db_expr_t addr, int haddr, db_expr_t count, const char *modif)
    467 {
    468 	int b;
    469 
    470 	db_printf("hardclock_ticks now: %d\n", hardclock_ticks);
    471 #ifdef _LP64
    472 	db_printf("    ticks  wheel               arg  func\n");
    473 #else
    474 	db_printf("    ticks  wheel       arg  func\n");
    475 #endif
    476 
    477 	/*
    478 	 * Don't lock the callwheel; all the other CPUs are paused
    479 	 * anyhow, and we might be called in a circumstance where
    480 	 * some other CPU was paused while holding the lock.
    481 	 */
    482 
    483 	db_show_callout_bucket(&timeout_todo);
    484 	for (b = 0; b < BUCKETS; b++)
    485 		db_show_callout_bucket(&timeout_wheel[b]);
    486 }
    487 #endif /* DDB */
    488