kern_timeout.c revision 184385
1327952Sdim/*-
2226586Sdim * Copyright (c) 1982, 1986, 1991, 1993
3353358Sdim *	The Regents of the University of California.  All rights reserved.
4353358Sdim * (c) UNIX System Laboratories, Inc.
5353358Sdim * All or some portions of this file are derived from material licensed
6226586Sdim * to the University of California by American Telephone and Telegraph
7226586Sdim * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8226586Sdim * the permission of UNIX System Laboratories, Inc.
9341825Sdim *
10226586Sdim * Redistribution and use in source and binary forms, with or without
11226586Sdim * modification, are permitted provided that the following conditions
12226586Sdim * are met:
13327952Sdim * 1. Redistributions of source code must retain the above copyright
14280031Sdim *    notice, this list of conditions and the following disclaimer.
15280031Sdim * 2. Redistributions in binary form must reproduce the above copyright
16226586Sdim *    notice, this list of conditions and the following disclaimer in the
17327952Sdim *    documentation and/or other materials provided with the distribution.
18234353Sdim * 4. Neither the name of the University nor the names of its contributors
19226586Sdim *    may be used to endorse or promote products derived from this software
20234353Sdim *    without specific prior written permission.
21249423Sdim *
22327952Sdim * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23327952Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24226586Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25226586Sdim * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26226586Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27276479Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28226586Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29249423Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30341825Sdim * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31234353Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32327952Sdim * SUCH DAMAGE.
33249423Sdim *
34341825Sdim *	From: @(#)kern_clock.c	8.5 (Berkeley) 1/21/94
35249423Sdim */
36314564Sdim
37314564Sdim#include <sys/cdefs.h>
38314564Sdim__FBSDID("$FreeBSD: head/sys/kern/kern_timeout.c 184385 2008-10-28 03:26:25Z peter $");
39314564Sdim
40327952Sdim#include <sys/param.h>
41314564Sdim#include <sys/systm.h>
42314564Sdim#include <sys/bus.h>
43314564Sdim#include <sys/callout.h>
44314564Sdim#include <sys/condvar.h>
45327952Sdim#include <sys/interrupt.h>
46314564Sdim#include <sys/kernel.h>
47360784Sdim#include <sys/ktr.h>
48360784Sdim#include <sys/lock.h>
49360784Sdim#include <sys/malloc.h>
50360784Sdim#include <sys/mutex.h>
51314564Sdim#include <sys/proc.h>
52314564Sdim#include <sys/sleepqueue.h>
53249423Sdim#include <sys/sysctl.h>
54327952Sdim#include <sys/smp.h>
55314564Sdim
56314564Sdimstatic int avg_depth;
57249423SdimSYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
58249423Sdim    "Average number of items examined per softclock call. Units = 1/1000");
59249423Sdimstatic int avg_gcalls;
60360784SdimSYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
61360784Sdim    "Average number of Giant callouts made per softclock call. Units = 1/1000");
62360784Sdimstatic int avg_lockcalls;
63360784SdimSYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
64341825Sdim    "Average number of lock callouts made per softclock call. Units = 1/1000");
65249423Sdimstatic int avg_mpcalls;
66249423SdimSYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
67249423Sdim    "Average number of MP callouts made per softclock call. Units = 1/1000");
68314564Sdim/*
69314564Sdim * TODO:
70341825Sdim *	allocate more timeout table slots when table overflows.
71314564Sdim */
72314564Sdimint callwheelsize, callwheelbits, callwheelmask;
73249423Sdim
74249423Sdimstruct callout_cpu {
75341825Sdim	struct mtx		cc_lock;
76226586Sdim	struct callout		*cc_callout;
77226586Sdim	struct callout_tailq	*cc_callwheel;
78226586Sdim	struct callout_list	cc_callfree;
79226586Sdim	struct callout		*cc_next;
80226586Sdim	struct callout		*cc_curr;
81276479Sdim	void			*cc_cookie;
82276479Sdim	int 			cc_softticks;
83327952Sdim	int			cc_cancel;
84226586Sdim	int			cc_waiting;
85327952Sdim};
86327952Sdim
87261991Sdim#ifdef SMP
88226586Sdimstruct callout_cpu cc_cpu[MAXCPU];
89341825Sdim#define	CC_CPU(cpu)	(&cc_cpu[(cpu)])
90341825Sdim#define	CC_SELF()	CC_CPU(PCPU_GET(cpuid))
91276479Sdim#else
92276479Sdimstruct callout_cpu cc_cpu;
93276479Sdim#define	CC_CPU(cpu)	&cc_cpu
94327952Sdim#define	CC_SELF()	&cc_cpu
95341825Sdim#endif
96276479Sdim#define	CC_LOCK(cc)	mtx_lock_spin(&(cc)->cc_lock)
97276479Sdim#define	CC_UNLOCK(cc)	mtx_unlock_spin(&(cc)->cc_lock)
98276479Sdim
99341825Sdimstatic int timeout_cpu;
100341825Sdim
101226586SdimMALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
102341825Sdim
103360784Sdim/**
104360784Sdim * Locked by cc_lock:
105226586Sdim *   cc_curr         - If a callout is in progress, it is curr_callout.
106226586Sdim *                     If curr_callout is non-NULL, threads waiting in
107226586Sdim *                     callout_drain() will be woken up as soon as the
108234353Sdim *                     relevant callout completes.
109234353Sdim *   cc_cancel       - Changing to 1 with both callout_lock and c_lock held
110341825Sdim *                     guarantees that the current callout will not run.
111234353Sdim *                     The softclock() function sets this to 0 before it
112234353Sdim *                     drops callout_lock to acquire c_lock, and it calls
113234353Sdim *                     the handler only if curr_cancelled is still 0 after
114234353Sdim *                     c_lock is successfully acquired.
115234353Sdim *   cc_waiting      - If a thread is waiting in callout_drain(), then
116234353Sdim *                     callout_wait is nonzero.  Set only when
117234353Sdim *                     curr_callout is non-NULL.
118341825Sdim */
119234353Sdim
120249423Sdim/*
121249423Sdim * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization
122249423Sdim *
123249423Sdim *	This code is called very early in the kernel initialization sequence,
124249423Sdim *	and may be called more then once.
125360784Sdim */
126360784Sdimcaddr_t
127360784Sdimkern_timeout_callwheel_alloc(caddr_t v)
128321369Sdim{
129360784Sdim	struct callout_cpu *cc;
130360784Sdim
131321369Sdim	timeout_cpu = PCPU_GET(cpuid);
132360784Sdim	cc = CC_CPU(timeout_cpu);
133360784Sdim	/*
134321369Sdim	 * Calculate callout wheel size
135341825Sdim	 */
136249423Sdim	for (callwheelsize = 1, callwheelbits = 0;
137249423Sdim	     callwheelsize < ncallout;
138288943Sdim	     callwheelsize <<= 1, ++callwheelbits)
139261991Sdim		;
140341825Sdim	callwheelmask = callwheelsize - 1;
141276479Sdim
142276479Sdim	cc->cc_callout = (struct callout *)v;
143276479Sdim	v = (caddr_t)(cc->cc_callout + ncallout);
144276479Sdim	cc->cc_callwheel = (struct callout_tailq *)v;
145276479Sdim	v = (caddr_t)(cc->cc_callwheel + callwheelsize);
146276479Sdim	return(v);
147276479Sdim}
148276479Sdim
149276479Sdimstatic void
150276479Sdimcallout_cpu_init(struct callout_cpu *cc)
151276479Sdim{
152276479Sdim	struct callout *c;
153276479Sdim	int i;
154276479Sdim
155276479Sdim	mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
156276479Sdim	SLIST_INIT(&cc->cc_callfree);
157276479Sdim	for (i = 0; i < callwheelsize; i++) {
158276479Sdim		TAILQ_INIT(&cc->cc_callwheel[i]);
159276479Sdim	}
160327952Sdim	if (cc->cc_callout == NULL)
161226586Sdim		return;
162321369Sdim	for (i = 0; i < ncallout; i++) {
163360784Sdim		c = &cc->cc_callout[i];
164321369Sdim		callout_init(c, 0);
165321369Sdim		c->c_flags = CALLOUT_LOCAL_ALLOC;
166321369Sdim		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
167321369Sdim	}
168321369Sdim}
169327952Sdim
170321369Sdim/*
171321369Sdim * kern_timeout_callwheel_init() - initialize previously reserved callwheel
172360784Sdim *				   space.
173360784Sdim *
174321369Sdim *	This code is called just once, after the space reserved for the
175321369Sdim *	callout wheel has been finalized.
176321369Sdim */
177321369Sdimvoid
178321369Sdimkern_timeout_callwheel_init(void)
179321369Sdim{
180321369Sdim	callout_cpu_init(CC_CPU(timeout_cpu));
181327952Sdim}
182321369Sdim
183321369Sdim/*
184327952Sdim * Start standard softclock thread.
185321369Sdim */
186321369Sdimvoid    *softclock_ih;
187341825Sdim
188327952Sdimstatic void
189226586Sdimstart_softclock(void *dummy)
190327952Sdim{
191	struct callout_cpu *cc;
192#ifdef SMP
193	int cpu;
194#endif
195
196	cc = CC_CPU(timeout_cpu);
197	if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
198	    INTR_MPSAFE, &softclock_ih))
199		panic("died while creating standard software ithreads");
200	cc->cc_cookie = softclock_ih;
201#ifdef SMP
202	for (cpu = 0; cpu <= mp_maxid; cpu++) {
203		if (cpu == timeout_cpu)
204			continue;
205		if (CPU_ABSENT(cpu))
206			continue;
207		cc = CC_CPU(cpu);
208		if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
209		    INTR_MPSAFE, &cc->cc_cookie))
210			panic("died while creating standard software ithreads");
211		cc->cc_callout = NULL;	/* Only cpu0 handles timeout(). */
212		cc->cc_callwheel = malloc(
213		    sizeof(struct callout_tailq) * callwheelsize, M_CALLOUT,
214		    M_WAITOK);
215		callout_cpu_init(cc);
216	}
217#endif
218}
219
220SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
221
222void
223callout_tick(void)
224{
225	struct callout_cpu *cc;
226	int need_softclock;
227	int bucket;
228
229	/*
230	 * Process callouts at a very low cpu priority, so we don't keep the
231	 * relatively high clock interrupt priority any longer than necessary.
232	 */
233	need_softclock = 0;
234	cc = CC_SELF();
235	mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
236	for (; (cc->cc_softticks - ticks) < 0; cc->cc_softticks++) {
237		bucket = cc->cc_softticks & callwheelmask;
238		if (!TAILQ_EMPTY(&cc->cc_callwheel[bucket])) {
239			need_softclock = 1;
240			break;
241		}
242	}
243	mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
244	/*
245	 * swi_sched acquires the thread lock, so we don't want to call it
246	 * with cc_lock held; incorrect locking order.
247	 */
248	if (need_softclock)
249		swi_sched(cc->cc_cookie, 0);
250}
251
252static struct callout_cpu *
253callout_lock(struct callout *c)
254{
255	struct callout_cpu *cc;
256	int cpu;
257
258	for (;;) {
259		cpu = c->c_cpu;
260		cc = CC_CPU(cpu);
261		CC_LOCK(cc);
262		if (cpu == c->c_cpu)
263			break;
264		CC_UNLOCK(cc);
265	}
266	return (cc);
267}
268
269/*
270 * The callout mechanism is based on the work of Adam M. Costello and
271 * George Varghese, published in a technical report entitled "Redesigning
272 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
273 * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
274 * used in this implementation was published by G. Varghese and T. Lauck in
275 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
276 * the Efficient Implementation of a Timer Facility" in the Proceedings of
277 * the 11th ACM Annual Symposium on Operating Systems Principles,
278 * Austin, Texas Nov 1987.
279 */
280
281/*
282 * Software (low priority) clock interrupt.
283 * Run periodic events from timeout queue.
284 */
285void
286softclock(void *arg)
287{
288	struct callout_cpu *cc;
289	struct callout *c;
290	struct callout_tailq *bucket;
291	int curticks;
292	int steps;	/* #steps since we last allowed interrupts */
293	int depth;
294	int mpcalls;
295	int lockcalls;
296	int gcalls;
297#ifdef DIAGNOSTIC
298	struct bintime bt1, bt2;
299	struct timespec ts2;
300	static uint64_t maxdt = 36893488147419102LL;	/* 2 msec */
301	static timeout_t *lastfunc;
302#endif
303
304#ifndef MAX_SOFTCLOCK_STEPS
305#define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
306#endif /* MAX_SOFTCLOCK_STEPS */
307
308	mpcalls = 0;
309	lockcalls = 0;
310	gcalls = 0;
311	depth = 0;
312	steps = 0;
313	cc = (struct callout_cpu *)arg;
314	CC_LOCK(cc);
315	while (cc->cc_softticks != ticks) {
316		/*
317		 * cc_softticks may be modified by hard clock, so cache
318		 * it while we work on a given bucket.
319		 */
320		curticks = cc->cc_softticks;
321		cc->cc_softticks++;
322		bucket = &cc->cc_callwheel[curticks & callwheelmask];
323		c = TAILQ_FIRST(bucket);
324		while (c) {
325			depth++;
326			if (c->c_time != curticks) {
327				c = TAILQ_NEXT(c, c_links.tqe);
328				++steps;
329				if (steps >= MAX_SOFTCLOCK_STEPS) {
330					cc->cc_next = c;
331					/* Give interrupts a chance. */
332					CC_UNLOCK(cc);
333					;	/* nothing */
334					CC_LOCK(cc);
335					c = cc->cc_next;
336					steps = 0;
337				}
338			} else {
339				void (*c_func)(void *);
340				void *c_arg;
341				struct lock_class *class;
342				struct lock_object *c_lock;
343				int c_flags, sharedlock;
344
345				cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
346				TAILQ_REMOVE(bucket, c, c_links.tqe);
347				class = (c->c_lock != NULL) ?
348				    LOCK_CLASS(c->c_lock) : NULL;
349				sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ?
350				    0 : 1;
351				c_lock = c->c_lock;
352				c_func = c->c_func;
353				c_arg = c->c_arg;
354				c_flags = c->c_flags;
355				if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
356					c->c_flags = CALLOUT_LOCAL_ALLOC;
357				} else {
358					c->c_flags =
359					    (c->c_flags & ~CALLOUT_PENDING);
360				}
361				cc->cc_curr = c;
362				cc->cc_cancel = 0;
363				CC_UNLOCK(cc);
364				if (c_lock != NULL) {
365					class->lc_lock(c_lock, sharedlock);
366					/*
367					 * The callout may have been cancelled
368					 * while we switched locks.
369					 */
370					if (cc->cc_cancel) {
371						class->lc_unlock(c_lock);
372						goto skip;
373					}
374					/* The callout cannot be stopped now. */
375					cc->cc_cancel = 1;
376
377					if (c_lock == &Giant.lock_object) {
378						gcalls++;
379						CTR3(KTR_CALLOUT,
380						    "callout %p func %p arg %p",
381						    c, c_func, c_arg);
382					} else {
383						lockcalls++;
384						CTR3(KTR_CALLOUT, "callout lock"
385						    " %p func %p arg %p",
386						    c, c_func, c_arg);
387					}
388				} else {
389					mpcalls++;
390					CTR3(KTR_CALLOUT,
391					    "callout mpsafe %p func %p arg %p",
392					    c, c_func, c_arg);
393				}
394#ifdef DIAGNOSTIC
395				binuptime(&bt1);
396#endif
397				THREAD_NO_SLEEPING();
398				c_func(c_arg);
399				THREAD_SLEEPING_OK();
400#ifdef DIAGNOSTIC
401				binuptime(&bt2);
402				bintime_sub(&bt2, &bt1);
403				if (bt2.frac > maxdt) {
404					if (lastfunc != c_func ||
405					    bt2.frac > maxdt * 2) {
406						bintime2timespec(&bt2, &ts2);
407						printf(
408			"Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
409						    c_func, c_arg,
410						    (intmax_t)ts2.tv_sec,
411						    ts2.tv_nsec);
412					}
413					maxdt = bt2.frac;
414					lastfunc = c_func;
415				}
416#endif
417				if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
418					class->lc_unlock(c_lock);
419			skip:
420				CC_LOCK(cc);
421				/*
422				 * If the current callout is locally
423				 * allocated (from timeout(9))
424				 * then put it on the freelist.
425				 *
426				 * Note: we need to check the cached
427				 * copy of c_flags because if it was not
428				 * local, then it's not safe to deref the
429				 * callout pointer.
430				 */
431				if (c_flags & CALLOUT_LOCAL_ALLOC) {
432					KASSERT(c->c_flags ==
433					    CALLOUT_LOCAL_ALLOC,
434					    ("corrupted callout"));
435					c->c_func = NULL;
436					SLIST_INSERT_HEAD(&cc->cc_callfree, c,
437					    c_links.sle);
438				}
439				cc->cc_curr = NULL;
440				if (cc->cc_waiting) {
441					/*
442					 * There is someone waiting
443					 * for the callout to complete.
444					 */
445					cc->cc_waiting = 0;
446					CC_UNLOCK(cc);
447					wakeup(&cc->cc_waiting);
448					CC_LOCK(cc);
449				}
450				steps = 0;
451				c = cc->cc_next;
452			}
453		}
454	}
455	avg_depth += (depth * 1000 - avg_depth) >> 8;
456	avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
457	avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
458	avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
459	cc->cc_next = NULL;
460	CC_UNLOCK(cc);
461}
462
463/*
464 * timeout --
465 *	Execute a function after a specified length of time.
466 *
467 * untimeout --
468 *	Cancel previous timeout function call.
469 *
470 * callout_handle_init --
471 *	Initialize a handle so that using it with untimeout is benign.
472 *
473 *	See AT&T BCI Driver Reference Manual for specification.  This
474 *	implementation differs from that one in that although an
475 *	identification value is returned from timeout, the original
476 *	arguments to timeout as well as the identifier are used to
477 *	identify entries for untimeout.
478 */
479struct callout_handle
480timeout(ftn, arg, to_ticks)
481	timeout_t *ftn;
482	void *arg;
483	int to_ticks;
484{
485	struct callout_cpu *cc;
486	struct callout *new;
487	struct callout_handle handle;
488
489	cc = CC_CPU(timeout_cpu);
490	CC_LOCK(cc);
491	/* Fill in the next free callout structure. */
492	new = SLIST_FIRST(&cc->cc_callfree);
493	if (new == NULL)
494		/* XXX Attempt to malloc first */
495		panic("timeout table full");
496	SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
497	callout_reset(new, to_ticks, ftn, arg);
498	handle.callout = new;
499	CC_UNLOCK(cc);
500
501	return (handle);
502}
503
504void
505untimeout(ftn, arg, handle)
506	timeout_t *ftn;
507	void *arg;
508	struct callout_handle handle;
509{
510	struct callout_cpu *cc;
511
512	/*
513	 * Check for a handle that was initialized
514	 * by callout_handle_init, but never used
515	 * for a real timeout.
516	 */
517	if (handle.callout == NULL)
518		return;
519
520	cc = callout_lock(handle.callout);
521	if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
522		callout_stop(handle.callout);
523	CC_UNLOCK(cc);
524}
525
526void
527callout_handle_init(struct callout_handle *handle)
528{
529	handle->callout = NULL;
530}
531
532/*
533 * New interface; clients allocate their own callout structures.
534 *
535 * callout_reset() - establish or change a timeout
536 * callout_stop() - disestablish a timeout
537 * callout_init() - initialize a callout structure so that it can
538 *	safely be passed to callout_reset() and callout_stop()
539 *
540 * <sys/callout.h> defines three convenience macros:
541 *
542 * callout_active() - returns truth if callout has not been stopped,
543 *	drained, or deactivated since the last time the callout was
544 *	reset.
545 * callout_pending() - returns truth if callout is still waiting for timeout
546 * callout_deactivate() - marks the callout as having been serviced
547 */
548int
549callout_reset_on(struct callout *c, int to_ticks, void (*ftn)(void *),
550    void *arg, int cpu)
551{
552	struct callout_cpu *cc;
553	int cancelled = 0;
554
555	/*
556	 * Don't allow migration of pre-allocated callouts lest they
557	 * become unbalanced.
558	 */
559	if (c->c_flags & CALLOUT_LOCAL_ALLOC)
560		cpu = c->c_cpu;
561retry:
562	cc = callout_lock(c);
563	if (cc->cc_curr == c) {
564		/*
565		 * We're being asked to reschedule a callout which is
566		 * currently in progress.  If there is a lock then we
567		 * can cancel the callout if it has not really started.
568		 */
569		if (c->c_lock != NULL && !cc->cc_cancel)
570			cancelled = cc->cc_cancel = 1;
571		if (cc->cc_waiting) {
572			/*
573			 * Someone has called callout_drain to kill this
574			 * callout.  Don't reschedule.
575			 */
576			CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
577			    cancelled ? "cancelled" : "failed to cancel",
578			    c, c->c_func, c->c_arg);
579			CC_UNLOCK(cc);
580			return (cancelled);
581		}
582	}
583	if (c->c_flags & CALLOUT_PENDING) {
584		if (cc->cc_next == c) {
585			cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
586		}
587		TAILQ_REMOVE(&cc->cc_callwheel[c->c_time & callwheelmask], c,
588		    c_links.tqe);
589
590		cancelled = 1;
591		c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
592	}
593	/*
594	 * If the lock must migrate we have to check the state again as
595	 * we can't hold both the new and old locks simultaneously.
596	 */
597	if (c->c_cpu != cpu) {
598		c->c_cpu = cpu;
599		CC_UNLOCK(cc);
600		goto retry;
601	}
602
603	if (to_ticks <= 0)
604		to_ticks = 1;
605
606	c->c_arg = arg;
607	c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
608	c->c_func = ftn;
609	c->c_time = ticks + to_ticks;
610	TAILQ_INSERT_TAIL(&cc->cc_callwheel[c->c_time & callwheelmask],
611			  c, c_links.tqe);
612	CTR5(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d",
613	    cancelled ? "re" : "", c, c->c_func, c->c_arg, to_ticks);
614	CC_UNLOCK(cc);
615
616	return (cancelled);
617}
618
619/*
620 * Common idioms that can be optimized in the future.
621 */
622int
623callout_schedule_on(struct callout *c, int to_ticks, int cpu)
624{
625	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
626}
627
628int
629callout_schedule(struct callout *c, int to_ticks)
630{
631	return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
632}
633
634int
635_callout_stop_safe(c, safe)
636	struct	callout *c;
637	int	safe;
638{
639	struct callout_cpu *cc;
640	struct lock_class *class;
641	int use_lock, sq_locked;
642
643	/*
644	 * Some old subsystems don't hold Giant while running a callout_stop(),
645	 * so just discard this check for the moment.
646	 */
647	if (!safe && c->c_lock != NULL) {
648		if (c->c_lock == &Giant.lock_object)
649			use_lock = mtx_owned(&Giant);
650		else {
651			use_lock = 1;
652			class = LOCK_CLASS(c->c_lock);
653			class->lc_assert(c->c_lock, LA_XLOCKED);
654		}
655	} else
656		use_lock = 0;
657
658	sq_locked = 0;
659again:
660	cc = callout_lock(c);
661	/*
662	 * If the callout isn't pending, it's not on the queue, so
663	 * don't attempt to remove it from the queue.  We can try to
664	 * stop it by other means however.
665	 */
666	if (!(c->c_flags & CALLOUT_PENDING)) {
667		c->c_flags &= ~CALLOUT_ACTIVE;
668
669		/*
670		 * If it wasn't on the queue and it isn't the current
671		 * callout, then we can't stop it, so just bail.
672		 */
673		if (cc->cc_curr != c) {
674			CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
675			    c, c->c_func, c->c_arg);
676			CC_UNLOCK(cc);
677			if (sq_locked)
678				sleepq_release(&cc->cc_waiting);
679			return (0);
680		}
681
682		if (safe) {
683			/*
684			 * The current callout is running (or just
685			 * about to run) and blocking is allowed, so
686			 * just wait for the current invocation to
687			 * finish.
688			 */
689			while (cc->cc_curr == c) {
690
691				/*
692				 * Use direct calls to sleepqueue interface
693				 * instead of cv/msleep in order to avoid
694				 * a LOR between cc_lock and sleepqueue
695				 * chain spinlocks.  This piece of code
696				 * emulates a msleep_spin() call actually.
697				 *
698				 * If we already have the sleepqueue chain
699				 * locked, then we can safely block.  If we
700				 * don't already have it locked, however,
701				 * we have to drop the cc_lock to lock
702				 * it.  This opens several races, so we
703				 * restart at the beginning once we have
704				 * both locks.  If nothing has changed, then
705				 * we will end up back here with sq_locked
706				 * set.
707				 */
708				if (!sq_locked) {
709					CC_UNLOCK(cc);
710					sleepq_lock(&cc->cc_waiting);
711					sq_locked = 1;
712					goto again;
713				}
714				cc->cc_waiting = 1;
715				DROP_GIANT();
716				CC_UNLOCK(cc);
717				sleepq_add(&cc->cc_waiting,
718				    &cc->cc_lock.lock_object, "codrain",
719				    SLEEPQ_SLEEP, 0);
720				sleepq_wait(&cc->cc_waiting, 0);
721				sq_locked = 0;
722
723				/* Reacquire locks previously released. */
724				PICKUP_GIANT();
725				CC_LOCK(cc);
726			}
727		} else if (use_lock && !cc->cc_cancel) {
728			/*
729			 * The current callout is waiting for its
730			 * lock which we hold.  Cancel the callout
731			 * and return.  After our caller drops the
732			 * lock, the callout will be skipped in
733			 * softclock().
734			 */
735			cc->cc_cancel = 1;
736			CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
737			    c, c->c_func, c->c_arg);
738			CC_UNLOCK(cc);
739			KASSERT(!sq_locked, ("sleepqueue chain locked"));
740			return (1);
741		}
742		CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
743		    c, c->c_func, c->c_arg);
744		CC_UNLOCK(cc);
745		KASSERT(!sq_locked, ("sleepqueue chain still locked"));
746		return (0);
747	}
748	if (sq_locked)
749		sleepq_release(&cc->cc_waiting);
750
751	c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
752
753	if (cc->cc_next == c) {
754		cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
755	}
756	TAILQ_REMOVE(&cc->cc_callwheel[c->c_time & callwheelmask], c,
757	    c_links.tqe);
758
759	CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
760	    c, c->c_func, c->c_arg);
761
762	if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
763		c->c_func = NULL;
764		SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
765	}
766	CC_UNLOCK(cc);
767	return (1);
768}
769
770void
771callout_init(c, mpsafe)
772	struct	callout *c;
773	int mpsafe;
774{
775	bzero(c, sizeof *c);
776	if (mpsafe) {
777		c->c_lock = NULL;
778		c->c_flags = CALLOUT_RETURNUNLOCKED;
779	} else {
780		c->c_lock = &Giant.lock_object;
781		c->c_flags = 0;
782	}
783	c->c_cpu = timeout_cpu;
784}
785
786void
787_callout_init_lock(c, lock, flags)
788	struct	callout *c;
789	struct	lock_object *lock;
790	int flags;
791{
792	bzero(c, sizeof *c);
793	c->c_lock = lock;
794	KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
795	    ("callout_init_lock: bad flags %d", flags));
796	KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
797	    ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
798	KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
799	    (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
800	    __func__));
801	c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
802	c->c_cpu = timeout_cpu;
803}
804
805#ifdef APM_FIXUP_CALLTODO
806/*
807 * Adjust the kernel calltodo timeout list.  This routine is used after
808 * an APM resume to recalculate the calltodo timer list values with the
809 * number of hz's we have been sleeping.  The next hardclock() will detect
810 * that there are fired timers and run softclock() to execute them.
811 *
812 * Please note, I have not done an exhaustive analysis of what code this
813 * might break.  I am motivated to have my select()'s and alarm()'s that
814 * have expired during suspend firing upon resume so that the applications
815 * which set the timer can do the maintanence the timer was for as close
816 * as possible to the originally intended time.  Testing this code for a
817 * week showed that resuming from a suspend resulted in 22 to 25 timers
818 * firing, which seemed independant on whether the suspend was 2 hours or
819 * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
820 */
821void
822adjust_timeout_calltodo(time_change)
823    struct timeval *time_change;
824{
825	register struct callout *p;
826	unsigned long delta_ticks;
827
828	/*
829	 * How many ticks were we asleep?
830	 * (stolen from tvtohz()).
831	 */
832
833	/* Don't do anything */
834	if (time_change->tv_sec < 0)
835		return;
836	else if (time_change->tv_sec <= LONG_MAX / 1000000)
837		delta_ticks = (time_change->tv_sec * 1000000 +
838			       time_change->tv_usec + (tick - 1)) / tick + 1;
839	else if (time_change->tv_sec <= LONG_MAX / hz)
840		delta_ticks = time_change->tv_sec * hz +
841			      (time_change->tv_usec + (tick - 1)) / tick + 1;
842	else
843		delta_ticks = LONG_MAX;
844
845	if (delta_ticks > INT_MAX)
846		delta_ticks = INT_MAX;
847
848	/*
849	 * Now rip through the timer calltodo list looking for timers
850	 * to expire.
851	 */
852
853	/* don't collide with softclock() */
854	CC_LOCK(cc);
855	for (p = calltodo.c_next; p != NULL; p = p->c_next) {
856		p->c_time -= delta_ticks;
857
858		/* Break if the timer had more time on it than delta_ticks */
859		if (p->c_time > 0)
860			break;
861
862		/* take back the ticks the timer didn't use (p->c_time <= 0) */
863		delta_ticks = -p->c_time;
864	}
865	CC_UNLOCK(cc);
866
867	return;
868}
869#endif /* APM_FIXUP_CALLTODO */
870