]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/kern_timeout.c
MFC r245457:
[FreeBSD/stable/8.git] / sys / kern / kern_timeout.c
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      From: @(#)kern_clock.c  8.5 (Berkeley) 1/21/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_kdtrace.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/bus.h>
45 #include <sys/callout.h>
46 #include <sys/condvar.h>
47 #include <sys/interrupt.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/lock.h>
51 #include <sys/malloc.h>
52 #include <sys/mutex.h>
53 #include <sys/proc.h>
54 #include <sys/sdt.h>
55 #include <sys/sleepqueue.h>
56 #include <sys/sysctl.h>
57 #include <sys/smp.h>
58
59 #ifdef SMP
60 #include <machine/cpu.h>
61 #endif
62
63 SDT_PROVIDER_DEFINE(callout_execute);
64 SDT_PROBE_DEFINE(callout_execute, kernel, , callout_start, callout-start);
65 SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_start, 0,
66     "struct callout *");
67 SDT_PROBE_DEFINE(callout_execute, kernel, , callout_end, callout-end); 
68 SDT_PROBE_ARGTYPE(callout_execute, kernel, , callout_end, 0,
69     "struct callout *");
70
71 static int avg_depth;
72 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
73     "Average number of items examined per softclock call. Units = 1/1000");
74 static int avg_gcalls;
75 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
76     "Average number of Giant callouts made per softclock call. Units = 1/1000");
77 static int avg_lockcalls;
78 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
79     "Average number of lock callouts made per softclock call. Units = 1/1000");
80 static int avg_mpcalls;
81 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
82     "Average number of MP callouts made per softclock call. Units = 1/1000");
83 /*
84  * TODO:
85  *      allocate more timeout table slots when table overflows.
86  */
87 int callwheelsize, callwheelbits, callwheelmask;
88
89 /*
90  * The callout cpu migration entity represents informations necessary for
91  * describing the migrating callout to the new callout cpu.
92  * The cached informations are very important for deferring migration when
93  * the migrating callout is already running.
94  */
95 struct cc_mig_ent {
96 #ifdef SMP
97         void    (*ce_migration_func)(void *);
98         void    *ce_migration_arg;
99         int     ce_migration_cpu;
100         int     ce_migration_ticks;
101 #endif
102 };
103         
104 /*
105  * There is one struct callout_cpu per cpu, holding all relevant
106  * state for the callout processing thread on the individual CPU.
107  * In particular:
108  *      cc_ticks is incremented once per tick in callout_cpu().
109  *      It tracks the global 'ticks' but in a way that the individual
110  *      threads should not worry about races in the order in which
111  *      hardclock() and hardclock_cpu() run on the various CPUs.
112  *      cc_softclock is advanced in callout_cpu() to point to the
113  *      first entry in cc_callwheel that may need handling. In turn,
114  *      a softclock() is scheduled so it can serve the various entries i
115  *      such that cc_softclock <= i <= cc_ticks .
116  *      XXX maybe cc_softclock and cc_ticks should be volatile ?
117  *
118  *      cc_ticks is also used in callout_reset_cpu() to determine
119  *      when the callout should be served.
120  */
121 struct callout_cpu {
122         struct cc_mig_ent       cc_migrating_entity;
123         struct mtx              cc_lock;
124         struct callout          *cc_callout;
125         struct callout_tailq    *cc_callwheel;
126         struct callout_list     cc_callfree;
127         struct callout          *cc_next;
128         struct callout          *cc_curr;
129         void                    *cc_cookie;
130         int                     cc_ticks;
131         int                     cc_softticks;
132         int                     cc_cancel;
133         int                     cc_waiting;
134 };
135
136 #ifdef SMP
137 #define cc_migration_func       cc_migrating_entity.ce_migration_func
138 #define cc_migration_arg        cc_migrating_entity.ce_migration_arg
139 #define cc_migration_cpu        cc_migrating_entity.ce_migration_cpu
140 #define cc_migration_ticks      cc_migrating_entity.ce_migration_ticks
141
142 struct callout_cpu cc_cpu[MAXCPU];
143 #define CPUBLOCK        MAXCPU
144 #define CC_CPU(cpu)     (&cc_cpu[(cpu)])
145 #define CC_SELF()       CC_CPU(PCPU_GET(cpuid))
146 #else
147 struct callout_cpu cc_cpu;
148 #define CC_CPU(cpu)     &cc_cpu
149 #define CC_SELF()       &cc_cpu
150 #endif
151 #define CC_LOCK(cc)     mtx_lock_spin(&(cc)->cc_lock)
152 #define CC_UNLOCK(cc)   mtx_unlock_spin(&(cc)->cc_lock)
153 #define CC_LOCK_ASSERT(cc)      mtx_assert(&(cc)->cc_lock, MA_OWNED)
154
155 static int timeout_cpu;
156
157 MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
158
159 /**
160  * Locked by cc_lock:
161  *   cc_curr         - If a callout is in progress, it is curr_callout.
162  *                     If curr_callout is non-NULL, threads waiting in
163  *                     callout_drain() will be woken up as soon as the
164  *                     relevant callout completes.
165  *   cc_cancel       - Changing to 1 with both callout_lock and c_lock held
166  *                     guarantees that the current callout will not run.
167  *                     The softclock() function sets this to 0 before it
168  *                     drops callout_lock to acquire c_lock, and it calls
169  *                     the handler only if curr_cancelled is still 0 after
170  *                     c_lock is successfully acquired.
171  *   cc_waiting      - If a thread is waiting in callout_drain(), then
172  *                     callout_wait is nonzero.  Set only when
173  *                     curr_callout is non-NULL.
174  */
175
176 /*
177  * Resets the migration entity tied to a specific callout cpu.
178  */
179 static void
180 cc_cme_cleanup(struct callout_cpu *cc)
181 {
182
183 #ifdef SMP
184         cc->cc_migration_cpu = CPUBLOCK;
185         cc->cc_migration_ticks = 0;
186         cc->cc_migration_func = NULL;
187         cc->cc_migration_arg = NULL;
188 #endif
189 }
190
191 /*
192  * Checks if migration is requested by a specific callout cpu.
193  */
194 static int
195 cc_cme_migrating(struct callout_cpu *cc)
196 {
197
198 #ifdef SMP
199         return (cc->cc_migration_cpu != CPUBLOCK);
200 #else
201         return (0);
202 #endif
203 }
204
205 /*
206  * kern_timeout_callwheel_alloc() - kernel low level callwheel initialization 
207  *
208  *      This code is called very early in the kernel initialization sequence,
209  *      and may be called more then once.
210  */
211 caddr_t
212 kern_timeout_callwheel_alloc(caddr_t v)
213 {
214         struct callout_cpu *cc;
215
216         timeout_cpu = PCPU_GET(cpuid);
217         cc = CC_CPU(timeout_cpu);
218         /*
219          * Calculate callout wheel size
220          */
221         for (callwheelsize = 1, callwheelbits = 0;
222              callwheelsize < ncallout;
223              callwheelsize <<= 1, ++callwheelbits)
224                 ;
225         callwheelmask = callwheelsize - 1;
226
227         cc->cc_callout = (struct callout *)v;
228         v = (caddr_t)(cc->cc_callout + ncallout);
229         cc->cc_callwheel = (struct callout_tailq *)v;
230         v = (caddr_t)(cc->cc_callwheel + callwheelsize);
231         return(v);
232 }
233
234 static void
235 callout_cpu_init(struct callout_cpu *cc)
236 {
237         struct callout *c;
238         int i;
239
240         mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
241         SLIST_INIT(&cc->cc_callfree);
242         for (i = 0; i < callwheelsize; i++) {
243                 TAILQ_INIT(&cc->cc_callwheel[i]);
244         }
245         cc_cme_cleanup(cc);
246         if (cc->cc_callout == NULL)
247                 return;
248         for (i = 0; i < ncallout; i++) {
249                 c = &cc->cc_callout[i];
250                 callout_init(c, 0);
251                 c->c_flags = CALLOUT_LOCAL_ALLOC;
252                 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
253         }
254 }
255
256 #ifdef SMP
257 /*
258  * Switches the cpu tied to a specific callout.
259  * The function expects a locked incoming callout cpu and returns with
260  * locked outcoming callout cpu.
261  */
262 static struct callout_cpu *
263 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
264 {
265         struct callout_cpu *new_cc;
266
267         MPASS(c != NULL && cc != NULL);
268         CC_LOCK_ASSERT(cc);
269
270         /*
271          * Avoid interrupts and preemption firing after the callout cpu
272          * is blocked in order to avoid deadlocks as the new thread
273          * may be willing to acquire the callout cpu lock.
274          */
275         c->c_cpu = CPUBLOCK;
276         spinlock_enter();
277         CC_UNLOCK(cc);
278         new_cc = CC_CPU(new_cpu);
279         CC_LOCK(new_cc);
280         spinlock_exit();
281         c->c_cpu = new_cpu;
282         return (new_cc);
283 }
284 #endif
285
286 /*
287  * kern_timeout_callwheel_init() - initialize previously reserved callwheel
288  *                                 space.
289  *
290  *      This code is called just once, after the space reserved for the
291  *      callout wheel has been finalized.
292  */
293 void
294 kern_timeout_callwheel_init(void)
295 {
296         callout_cpu_init(CC_CPU(timeout_cpu));
297 }
298
299 /*
300  * Start standard softclock thread.
301  */
302 void    *softclock_ih;
303
304 static void
305 start_softclock(void *dummy)
306 {
307         struct callout_cpu *cc;
308 #ifdef SMP
309         int cpu;
310 #endif
311
312         cc = CC_CPU(timeout_cpu);
313         if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
314             INTR_MPSAFE, &softclock_ih))
315                 panic("died while creating standard software ithreads");
316         cc->cc_cookie = softclock_ih;
317 #ifdef SMP
318         CPU_FOREACH(cpu) {
319                 if (cpu == timeout_cpu)
320                         continue;
321                 cc = CC_CPU(cpu);
322                 if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
323                     INTR_MPSAFE, &cc->cc_cookie))
324                         panic("died while creating standard software ithreads");
325                 cc->cc_callout = NULL;  /* Only cpu0 handles timeout(). */
326                 cc->cc_callwheel = malloc(
327                     sizeof(struct callout_tailq) * callwheelsize, M_CALLOUT,
328                     M_WAITOK);
329                 callout_cpu_init(cc);
330         }
331 #endif
332 }
333
334 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
335
336 void
337 callout_tick(void)
338 {
339         struct callout_cpu *cc;
340         int need_softclock;
341         int bucket;
342
343         /*
344          * Process callouts at a very low cpu priority, so we don't keep the
345          * relatively high clock interrupt priority any longer than necessary.
346          */
347         need_softclock = 0;
348         cc = CC_SELF();
349         mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
350         cc->cc_ticks++;
351         for (; (cc->cc_softticks - cc->cc_ticks) <= 0; cc->cc_softticks++) {
352                 bucket = cc->cc_softticks & callwheelmask;
353                 if (!TAILQ_EMPTY(&cc->cc_callwheel[bucket])) {
354                         need_softclock = 1;
355                         break;
356                 }
357         }
358         mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
359         /*
360          * swi_sched acquires the thread lock, so we don't want to call it
361          * with cc_lock held; incorrect locking order.
362          */
363         if (need_softclock)
364                 swi_sched(cc->cc_cookie, 0);
365 }
366
367 static struct callout_cpu *
368 callout_lock(struct callout *c)
369 {
370         struct callout_cpu *cc;
371         int cpu;
372
373         for (;;) {
374                 cpu = c->c_cpu;
375 #ifdef SMP
376                 if (cpu == CPUBLOCK) {
377                         while (c->c_cpu == CPUBLOCK)
378                                 cpu_spinwait();
379                         continue;
380                 }
381 #endif
382                 cc = CC_CPU(cpu);
383                 CC_LOCK(cc);
384                 if (cpu == c->c_cpu)
385                         break;
386                 CC_UNLOCK(cc);
387         }
388         return (cc);
389 }
390
391 static void
392 callout_cc_add(struct callout *c, struct callout_cpu *cc, int to_ticks,
393     void (*func)(void *), void *arg, int cpu)
394 {
395
396         CC_LOCK_ASSERT(cc);
397
398         if (to_ticks <= 0)
399                 to_ticks = 1;
400         c->c_arg = arg;
401         c->c_flags |= (CALLOUT_ACTIVE | CALLOUT_PENDING);
402         c->c_func = func;
403         c->c_time = cc->cc_ticks + to_ticks;
404         TAILQ_INSERT_TAIL(&cc->cc_callwheel[c->c_time & callwheelmask],
405             c, c_links.tqe);
406 }
407
408 static void
409 callout_cc_del(struct callout *c, struct callout_cpu *cc)
410 {
411
412         if (cc->cc_next == c)
413                 cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
414         if (c->c_flags & CALLOUT_LOCAL_ALLOC) {
415                 c->c_func = NULL;
416                 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
417         }
418 }
419
420 static struct callout *
421 softclock_call_cc(struct callout *c, struct callout_cpu *cc, int *mpcalls,
422     int *lockcalls, int *gcalls)
423 {
424         void (*c_func)(void *);
425         void *c_arg;
426         struct lock_class *class;
427         struct lock_object *c_lock;
428         int c_flags, sharedlock;
429 #ifdef SMP
430         struct callout_cpu *new_cc;
431         void (*new_func)(void *);
432         void *new_arg;
433         int new_cpu, new_ticks;
434 #endif
435 #ifdef DIAGNOSTIC
436         struct bintime bt1, bt2;
437         struct timespec ts2;
438         static uint64_t maxdt = 36893488147419102LL;    /* 2 msec */
439         static timeout_t *lastfunc;
440 #endif
441
442         cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
443         class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
444         sharedlock = (c->c_flags & CALLOUT_SHAREDLOCK) ? 0 : 1;
445         c_lock = c->c_lock;
446         c_func = c->c_func;
447         c_arg = c->c_arg;
448         c_flags = c->c_flags;
449         if (c->c_flags & CALLOUT_LOCAL_ALLOC)
450                 c->c_flags = CALLOUT_LOCAL_ALLOC;
451         else
452                 c->c_flags &= ~CALLOUT_PENDING;
453         cc->cc_curr = c;
454         cc->cc_cancel = 0;
455         CC_UNLOCK(cc);
456         if (c_lock != NULL) {
457                 class->lc_lock(c_lock, sharedlock);
458                 /*
459                  * The callout may have been cancelled
460                  * while we switched locks.
461                  */
462                 if (cc->cc_cancel) {
463                         class->lc_unlock(c_lock);
464                         goto skip;
465                 }
466                 /* The callout cannot be stopped now. */
467                 cc->cc_cancel = 1;
468
469                 if (c_lock == &Giant.lock_object) {
470                         (*gcalls)++;
471                         CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
472                             c, c_func, c_arg);
473                 } else {
474                         (*lockcalls)++;
475                         CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
476                             c, c_func, c_arg);
477                 }
478         } else {
479                 (*mpcalls)++;
480                 CTR3(KTR_CALLOUT, "callout mpsafe %p func %p arg %p",
481                     c, c_func, c_arg);
482         }
483 #ifdef DIAGNOSTIC
484         binuptime(&bt1);
485 #endif
486         THREAD_NO_SLEEPING();
487         SDT_PROBE(callout_execute, kernel, , callout_start, c, 0, 0, 0, 0);
488         c_func(c_arg);
489         SDT_PROBE(callout_execute, kernel, , callout_end, c, 0, 0, 0, 0);
490         THREAD_SLEEPING_OK();
491 #ifdef DIAGNOSTIC
492         binuptime(&bt2);
493         bintime_sub(&bt2, &bt1);
494         if (bt2.frac > maxdt) {
495                 if (lastfunc != c_func || bt2.frac > maxdt * 2) {
496                         bintime2timespec(&bt2, &ts2);
497                         printf(
498                 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
499                             c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
500                 }
501                 maxdt = bt2.frac;
502                 lastfunc = c_func;
503         }
504 #endif
505         CTR1(KTR_CALLOUT, "callout %p finished", c);
506         if ((c_flags & CALLOUT_RETURNUNLOCKED) == 0)
507                 class->lc_unlock(c_lock);
508 skip:
509         CC_LOCK(cc);
510         /*
511          * If the current callout is locally allocated (from
512          * timeout(9)) then put it on the freelist.
513          *
514          * Note: we need to check the cached copy of c_flags because
515          * if it was not local, then it's not safe to deref the
516          * callout pointer.
517          */
518         if (c_flags & CALLOUT_LOCAL_ALLOC) {
519                 KASSERT(c->c_flags == CALLOUT_LOCAL_ALLOC,
520                     ("corrupted callout"));
521                 c->c_func = NULL;
522                 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
523         }
524         cc->cc_curr = NULL;
525         if (cc->cc_waiting) {
526                 /*
527                  * There is someone waiting for the
528                  * callout to complete.
529                  * If the callout was scheduled for
530                  * migration just cancel it.
531                  */
532                 if (cc_cme_migrating(cc))
533                         cc_cme_cleanup(cc);
534                 cc->cc_waiting = 0;
535                 CC_UNLOCK(cc);
536                 wakeup(&cc->cc_waiting);
537                 CC_LOCK(cc);
538         } else if (cc_cme_migrating(cc)) {
539 #ifdef SMP
540                 /*
541                  * If the callout was scheduled for
542                  * migration just perform it now.
543                  */
544                 new_cpu = cc->cc_migration_cpu;
545                 new_ticks = cc->cc_migration_ticks;
546                 new_func = cc->cc_migration_func;
547                 new_arg = cc->cc_migration_arg;
548                 cc_cme_cleanup(cc);
549
550                 /*
551                  * Handle deferred callout stops
552                  */
553                 if ((c->c_flags & CALLOUT_DFRMIGRATION) == 0) {
554                         CTR3(KTR_CALLOUT,
555                              "deferred cancelled %p func %p arg %p",
556                              c, new_func, new_arg);
557                         callout_cc_del(c, cc);
558                         goto nextc;
559                 }
560
561                 c->c_flags &= ~CALLOUT_DFRMIGRATION;
562
563                 /*
564                  * It should be assert here that the
565                  * callout is not destroyed but that
566                  * is not easy.
567                  */
568                 new_cc = callout_cpu_switch(c, cc, new_cpu);
569                 callout_cc_add(c, new_cc, new_ticks, new_func, new_arg,
570                     new_cpu);
571                 CC_UNLOCK(new_cc);
572                 CC_LOCK(cc);
573 #else
574                 panic("migration should not happen");
575 #endif
576         }
577 #ifdef SMP
578 nextc:
579 #endif
580         return (cc->cc_next);
581 }
582
583 /*
584  * The callout mechanism is based on the work of Adam M. Costello and 
585  * George Varghese, published in a technical report entitled "Redesigning
586  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
587  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
588  * used in this implementation was published by G. Varghese and T. Lauck in
589  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
590  * the Efficient Implementation of a Timer Facility" in the Proceedings of
591  * the 11th ACM Annual Symposium on Operating Systems Principles,
592  * Austin, Texas Nov 1987.
593  */
594
595 /*
596  * Software (low priority) clock interrupt.
597  * Run periodic events from timeout queue.
598  */
599 void
600 softclock(void *arg)
601 {
602         struct callout_cpu *cc;
603         struct callout *c;
604         struct callout_tailq *bucket;
605         int curticks;
606         int steps;      /* #steps since we last allowed interrupts */
607         int depth;
608         int mpcalls;
609         int lockcalls;
610         int gcalls;
611
612 #ifndef MAX_SOFTCLOCK_STEPS
613 #define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
614 #endif /* MAX_SOFTCLOCK_STEPS */
615
616         mpcalls = 0;
617         lockcalls = 0;
618         gcalls = 0;
619         depth = 0;
620         steps = 0;
621         cc = (struct callout_cpu *)arg;
622         CC_LOCK(cc);
623         while (cc->cc_softticks - 1 != cc->cc_ticks) {
624                 /*
625                  * cc_softticks may be modified by hard clock, so cache
626                  * it while we work on a given bucket.
627                  */
628                 curticks = cc->cc_softticks;
629                 cc->cc_softticks++;
630                 bucket = &cc->cc_callwheel[curticks & callwheelmask];
631                 c = TAILQ_FIRST(bucket);
632                 while (c != NULL) {
633                         depth++;
634                         if (c->c_time != curticks) {
635                                 c = TAILQ_NEXT(c, c_links.tqe);
636                                 ++steps;
637                                 if (steps >= MAX_SOFTCLOCK_STEPS) {
638                                         cc->cc_next = c;
639                                         /* Give interrupts a chance. */
640                                         CC_UNLOCK(cc);
641                                         ;       /* nothing */
642                                         CC_LOCK(cc);
643                                         c = cc->cc_next;
644                                         steps = 0;
645                                 }
646                         } else {
647                                 TAILQ_REMOVE(bucket, c, c_links.tqe);
648                                 c = softclock_call_cc(c, cc, &mpcalls,
649                                     &lockcalls, &gcalls);
650                                 steps = 0;
651                         }
652                 }
653         }
654         avg_depth += (depth * 1000 - avg_depth) >> 8;
655         avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
656         avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
657         avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
658         cc->cc_next = NULL;
659         CC_UNLOCK(cc);
660 }
661
662 /*
663  * timeout --
664  *      Execute a function after a specified length of time.
665  *
666  * untimeout --
667  *      Cancel previous timeout function call.
668  *
669  * callout_handle_init --
670  *      Initialize a handle so that using it with untimeout is benign.
671  *
672  *      See AT&T BCI Driver Reference Manual for specification.  This
673  *      implementation differs from that one in that although an 
674  *      identification value is returned from timeout, the original
675  *      arguments to timeout as well as the identifier are used to
676  *      identify entries for untimeout.
677  */
678 struct callout_handle
679 timeout(ftn, arg, to_ticks)
680         timeout_t *ftn;
681         void *arg;
682         int to_ticks;
683 {
684         struct callout_cpu *cc;
685         struct callout *new;
686         struct callout_handle handle;
687
688         cc = CC_CPU(timeout_cpu);
689         CC_LOCK(cc);
690         /* Fill in the next free callout structure. */
691         new = SLIST_FIRST(&cc->cc_callfree);
692         if (new == NULL)
693                 /* XXX Attempt to malloc first */
694                 panic("timeout table full");
695         SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
696         callout_reset(new, to_ticks, ftn, arg);
697         handle.callout = new;
698         CC_UNLOCK(cc);
699
700         return (handle);
701 }
702
703 void
704 untimeout(ftn, arg, handle)
705         timeout_t *ftn;
706         void *arg;
707         struct callout_handle handle;
708 {
709         struct callout_cpu *cc;
710
711         /*
712          * Check for a handle that was initialized
713          * by callout_handle_init, but never used
714          * for a real timeout.
715          */
716         if (handle.callout == NULL)
717                 return;
718
719         cc = callout_lock(handle.callout);
720         if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
721                 callout_stop(handle.callout);
722         CC_UNLOCK(cc);
723 }
724
725 void
726 callout_handle_init(struct callout_handle *handle)
727 {
728         handle->callout = NULL;
729 }
730
731 /*
732  * New interface; clients allocate their own callout structures.
733  *
734  * callout_reset() - establish or change a timeout
735  * callout_stop() - disestablish a timeout
736  * callout_init() - initialize a callout structure so that it can
737  *      safely be passed to callout_reset() and callout_stop()
738  *
739  * <sys/callout.h> defines three convenience macros:
740  *
741  * callout_active() - returns truth if callout has not been stopped,
742  *      drained, or deactivated since the last time the callout was
743  *      reset.
744  * callout_pending() - returns truth if callout is still waiting for timeout
745  * callout_deactivate() - marks the callout as having been serviced
746  */
747 int
748 callout_reset_on(struct callout *c, int to_ticks, void (*ftn)(void *),
749     void *arg, int cpu)
750 {
751         struct callout_cpu *cc;
752         int cancelled = 0;
753
754         /*
755          * Don't allow migration of pre-allocated callouts lest they
756          * become unbalanced.
757          */
758         if (c->c_flags & CALLOUT_LOCAL_ALLOC)
759                 cpu = c->c_cpu;
760         cc = callout_lock(c);
761         if (cc->cc_curr == c) {
762                 /*
763                  * We're being asked to reschedule a callout which is
764                  * currently in progress.  If there is a lock then we
765                  * can cancel the callout if it has not really started.
766                  */
767                 if (c->c_lock != NULL && !cc->cc_cancel)
768                         cancelled = cc->cc_cancel = 1;
769                 if (cc->cc_waiting) {
770                         /*
771                          * Someone has called callout_drain to kill this
772                          * callout.  Don't reschedule.
773                          */
774                         CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
775                             cancelled ? "cancelled" : "failed to cancel",
776                             c, c->c_func, c->c_arg);
777                         CC_UNLOCK(cc);
778                         return (cancelled);
779                 }
780         }
781         if (c->c_flags & CALLOUT_PENDING) {
782                 if (cc->cc_next == c) {
783                         cc->cc_next = TAILQ_NEXT(c, c_links.tqe);
784                 }
785                 TAILQ_REMOVE(&cc->cc_callwheel[c->c_time & callwheelmask], c,
786                     c_links.tqe);
787
788                 cancelled = 1;
789                 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
790         }
791
792 #ifdef SMP
793         /*
794          * If the callout must migrate try to perform it immediately.
795          * If the callout is currently running, just defer the migration
796          * to a more appropriate moment.
797          */
798         if (c->c_cpu != cpu) {
799                 if (cc->cc_curr == c) {
800                         cc->cc_migration_cpu = cpu;
801                         cc->cc_migration_ticks = to_ticks;
802                         cc->cc_migration_func = ftn;
803                         cc->cc_migration_arg = arg;
804                         c->c_flags |= CALLOUT_DFRMIGRATION;
805                         CTR5(KTR_CALLOUT,
806                     "migration of %p func %p arg %p in %d to %u deferred",
807                             c, c->c_func, c->c_arg, to_ticks, cpu);
808                         CC_UNLOCK(cc);
809                         return (cancelled);
810                 }
811                 cc = callout_cpu_switch(c, cc, cpu);
812         }
813 #endif
814
815         callout_cc_add(c, cc, to_ticks, ftn, arg, cpu);
816         CTR5(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d",
817             cancelled ? "re" : "", c, c->c_func, c->c_arg, to_ticks);
818         CC_UNLOCK(cc);
819
820         return (cancelled);
821 }
822
823 /*
824  * Common idioms that can be optimized in the future.
825  */
826 int
827 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
828 {
829         return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
830 }
831
832 int
833 callout_schedule(struct callout *c, int to_ticks)
834 {
835         return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
836 }
837
838 int
839 _callout_stop_safe(c, safe)
840         struct  callout *c;
841         int     safe;
842 {
843         struct callout_cpu *cc, *old_cc;
844         struct lock_class *class;
845         int use_lock, sq_locked;
846
847         /*
848          * Some old subsystems don't hold Giant while running a callout_stop(),
849          * so just discard this check for the moment.
850          */
851         if (!safe && c->c_lock != NULL) {
852                 if (c->c_lock == &Giant.lock_object)
853                         use_lock = mtx_owned(&Giant);
854                 else {
855                         use_lock = 1;
856                         class = LOCK_CLASS(c->c_lock);
857                         class->lc_assert(c->c_lock, LA_XLOCKED);
858                 }
859         } else
860                 use_lock = 0;
861
862         sq_locked = 0;
863         old_cc = NULL;
864 again:
865         cc = callout_lock(c);
866
867         /*
868          * If the callout was migrating while the callout cpu lock was
869          * dropped,  just drop the sleepqueue lock and check the states
870          * again.
871          */
872         if (sq_locked != 0 && cc != old_cc) {
873 #ifdef SMP
874                 CC_UNLOCK(cc);
875                 sleepq_release(&old_cc->cc_waiting);
876                 sq_locked = 0;
877                 old_cc = NULL;
878                 goto again;
879 #else
880                 panic("migration should not happen");
881 #endif
882         }
883
884         /*
885          * If the callout isn't pending, it's not on the queue, so
886          * don't attempt to remove it from the queue.  We can try to
887          * stop it by other means however.
888          */
889         if (!(c->c_flags & CALLOUT_PENDING)) {
890                 c->c_flags &= ~CALLOUT_ACTIVE;
891
892                 /*
893                  * If it wasn't on the queue and it isn't the current
894                  * callout, then we can't stop it, so just bail.
895                  */
896                 if (cc->cc_curr != c) {
897                         CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
898                             c, c->c_func, c->c_arg);
899                         CC_UNLOCK(cc);
900                         if (sq_locked)
901                                 sleepq_release(&cc->cc_waiting);
902                         return (0);
903                 }
904
905                 if (safe) {
906                         /*
907                          * The current callout is running (or just
908                          * about to run) and blocking is allowed, so
909                          * just wait for the current invocation to
910                          * finish.
911                          */
912                         while (cc->cc_curr == c) {
913
914                                 /*
915                                  * Use direct calls to sleepqueue interface
916                                  * instead of cv/msleep in order to avoid
917                                  * a LOR between cc_lock and sleepqueue
918                                  * chain spinlocks.  This piece of code
919                                  * emulates a msleep_spin() call actually.
920                                  *
921                                  * If we already have the sleepqueue chain
922                                  * locked, then we can safely block.  If we
923                                  * don't already have it locked, however,
924                                  * we have to drop the cc_lock to lock
925                                  * it.  This opens several races, so we
926                                  * restart at the beginning once we have
927                                  * both locks.  If nothing has changed, then
928                                  * we will end up back here with sq_locked
929                                  * set.
930                                  */
931                                 if (!sq_locked) {
932                                         CC_UNLOCK(cc);
933                                         sleepq_lock(&cc->cc_waiting);
934                                         sq_locked = 1;
935                                         old_cc = cc;
936                                         goto again;
937                                 }
938
939                                 /*
940                                  * Migration could be cancelled here, but
941                                  * as long as it is still not sure when it
942                                  * will be packed up, just let softclock()
943                                  * take care of it.
944                                  */
945                                 cc->cc_waiting = 1;
946                                 DROP_GIANT();
947                                 CC_UNLOCK(cc);
948                                 sleepq_add(&cc->cc_waiting,
949                                     &cc->cc_lock.lock_object, "codrain",
950                                     SLEEPQ_SLEEP, 0);
951                                 sleepq_wait(&cc->cc_waiting, 0);
952                                 sq_locked = 0;
953                                 old_cc = NULL;
954
955                                 /* Reacquire locks previously released. */
956                                 PICKUP_GIANT();
957                                 CC_LOCK(cc);
958                         }
959                 } else if (use_lock && !cc->cc_cancel) {
960                         /*
961                          * The current callout is waiting for its
962                          * lock which we hold.  Cancel the callout
963                          * and return.  After our caller drops the
964                          * lock, the callout will be skipped in
965                          * softclock().
966                          */
967                         cc->cc_cancel = 1;
968                         CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
969                             c, c->c_func, c->c_arg);
970                         KASSERT(!cc_cme_migrating(cc),
971                             ("callout wrongly scheduled for migration"));
972                         CC_UNLOCK(cc);
973                         KASSERT(!sq_locked, ("sleepqueue chain locked"));
974                         return (1);
975                 } else if ((c->c_flags & CALLOUT_DFRMIGRATION) != 0) {
976                         c->c_flags &= ~CALLOUT_DFRMIGRATION;
977                         CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
978                             c, c->c_func, c->c_arg);
979                         CC_UNLOCK(cc);
980                         return (1);
981                 }
982                 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
983                     c, c->c_func, c->c_arg);
984                 CC_UNLOCK(cc);
985                 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
986                 return (0);
987         }
988         if (sq_locked)
989                 sleepq_release(&cc->cc_waiting);
990
991         c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
992
993         CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
994             c, c->c_func, c->c_arg);
995         TAILQ_REMOVE(&cc->cc_callwheel[c->c_time & callwheelmask], c,
996             c_links.tqe);
997         callout_cc_del(c, cc);
998
999         CC_UNLOCK(cc);
1000         return (1);
1001 }
1002
1003 void
1004 callout_init(c, mpsafe)
1005         struct  callout *c;
1006         int mpsafe;
1007 {
1008         bzero(c, sizeof *c);
1009         if (mpsafe) {
1010                 c->c_lock = NULL;
1011                 c->c_flags = CALLOUT_RETURNUNLOCKED;
1012         } else {
1013                 c->c_lock = &Giant.lock_object;
1014                 c->c_flags = 0;
1015         }
1016         c->c_cpu = timeout_cpu;
1017 }
1018
1019 void
1020 _callout_init_lock(c, lock, flags)
1021         struct  callout *c;
1022         struct  lock_object *lock;
1023         int flags;
1024 {
1025         bzero(c, sizeof *c);
1026         c->c_lock = lock;
1027         KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1028             ("callout_init_lock: bad flags %d", flags));
1029         KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1030             ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1031         KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1032             (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1033             __func__));
1034         c->c_flags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1035         c->c_cpu = timeout_cpu;
1036 }
1037
1038 #ifdef APM_FIXUP_CALLTODO
1039 /* 
1040  * Adjust the kernel calltodo timeout list.  This routine is used after 
1041  * an APM resume to recalculate the calltodo timer list values with the 
1042  * number of hz's we have been sleeping.  The next hardclock() will detect 
1043  * that there are fired timers and run softclock() to execute them.
1044  *
1045  * Please note, I have not done an exhaustive analysis of what code this
1046  * might break.  I am motivated to have my select()'s and alarm()'s that
1047  * have expired during suspend firing upon resume so that the applications
1048  * which set the timer can do the maintanence the timer was for as close
1049  * as possible to the originally intended time.  Testing this code for a 
1050  * week showed that resuming from a suspend resulted in 22 to 25 timers 
1051  * firing, which seemed independant on whether the suspend was 2 hours or
1052  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1053  */
1054 void
1055 adjust_timeout_calltodo(time_change)
1056     struct timeval *time_change;
1057 {
1058         register struct callout *p;
1059         unsigned long delta_ticks;
1060
1061         /* 
1062          * How many ticks were we asleep?
1063          * (stolen from tvtohz()).
1064          */
1065
1066         /* Don't do anything */
1067         if (time_change->tv_sec < 0)
1068                 return;
1069         else if (time_change->tv_sec <= LONG_MAX / 1000000)
1070                 delta_ticks = (time_change->tv_sec * 1000000 +
1071                                time_change->tv_usec + (tick - 1)) / tick + 1;
1072         else if (time_change->tv_sec <= LONG_MAX / hz)
1073                 delta_ticks = time_change->tv_sec * hz +
1074                               (time_change->tv_usec + (tick - 1)) / tick + 1;
1075         else
1076                 delta_ticks = LONG_MAX;
1077
1078         if (delta_ticks > INT_MAX)
1079                 delta_ticks = INT_MAX;
1080
1081         /* 
1082          * Now rip through the timer calltodo list looking for timers
1083          * to expire.
1084          */
1085
1086         /* don't collide with softclock() */
1087         CC_LOCK(cc);
1088         for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1089                 p->c_time -= delta_ticks;
1090
1091                 /* Break if the timer had more time on it than delta_ticks */
1092                 if (p->c_time > 0)
1093                         break;
1094
1095                 /* take back the ticks the timer didn't use (p->c_time <= 0) */
1096                 delta_ticks = -p->c_time;
1097         }
1098         CC_UNLOCK(cc);
1099
1100         return;
1101 }
1102 #endif /* APM_FIXUP_CALLTODO */