]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_timeout.c
MFC r303702:
[FreeBSD/stable/10.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_callout_profiling.h"
41 #include "opt_kdtrace.h"
42 #if defined(__arm__)
43 #include "opt_timer.h"
44 #endif
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/bus.h>
49 #include <sys/callout.h>
50 #include <sys/file.h>
51 #include <sys/interrupt.h>
52 #include <sys/kernel.h>
53 #include <sys/ktr.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/mutex.h>
57 #include <sys/proc.h>
58 #include <sys/sdt.h>
59 #include <sys/sleepqueue.h>
60 #include <sys/sysctl.h>
61 #include <sys/smp.h>
62
63 #ifdef SMP
64 #include <machine/cpu.h>
65 #endif
66
67 #ifndef NO_EVENTTIMERS
68 DPCPU_DECLARE(sbintime_t, hardclocktime);
69 #endif
70
71 SDT_PROVIDER_DEFINE(callout_execute);
72 SDT_PROBE_DEFINE1(callout_execute, , , callout__start, "struct callout *");
73 SDT_PROBE_DEFINE1(callout_execute, , , callout__end, "struct callout *");
74
75 #ifdef CALLOUT_PROFILING
76 static int avg_depth;
77 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth, CTLFLAG_RD, &avg_depth, 0,
78     "Average number of items examined per softclock call. Units = 1/1000");
79 static int avg_gcalls;
80 SYSCTL_INT(_debug, OID_AUTO, to_avg_gcalls, CTLFLAG_RD, &avg_gcalls, 0,
81     "Average number of Giant callouts made per softclock call. Units = 1/1000");
82 static int avg_lockcalls;
83 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls, CTLFLAG_RD, &avg_lockcalls, 0,
84     "Average number of lock callouts made per softclock call. Units = 1/1000");
85 static int avg_mpcalls;
86 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls, CTLFLAG_RD, &avg_mpcalls, 0,
87     "Average number of MP callouts made per softclock call. Units = 1/1000");
88 static int avg_depth_dir;
89 SYSCTL_INT(_debug, OID_AUTO, to_avg_depth_dir, CTLFLAG_RD, &avg_depth_dir, 0,
90     "Average number of direct callouts examined per callout_process call. "
91     "Units = 1/1000");
92 static int avg_lockcalls_dir;
93 SYSCTL_INT(_debug, OID_AUTO, to_avg_lockcalls_dir, CTLFLAG_RD,
94     &avg_lockcalls_dir, 0, "Average number of lock direct callouts made per "
95     "callout_process call. Units = 1/1000");
96 static int avg_mpcalls_dir;
97 SYSCTL_INT(_debug, OID_AUTO, to_avg_mpcalls_dir, CTLFLAG_RD, &avg_mpcalls_dir,
98     0, "Average number of MP direct callouts made per callout_process call. "
99     "Units = 1/1000");
100 #endif
101
102 static int ncallout;
103 SYSCTL_INT(_kern, OID_AUTO, ncallout, CTLFLAG_RDTUN, &ncallout, 0,
104     "Number of entries in callwheel and size of timeout() preallocation");
105
106 /*
107  * TODO:
108  *      allocate more timeout table slots when table overflows.
109  */
110 u_int callwheelsize, callwheelmask;
111
112 /*
113  * The callout cpu exec entities represent informations necessary for
114  * describing the state of callouts currently running on the CPU and the ones
115  * necessary for migrating callouts to the new callout cpu. In particular,
116  * the first entry of the array cc_exec_entity holds informations for callout
117  * running in SWI thread context, while the second one holds informations
118  * for callout running directly from hardware interrupt context.
119  * The cached informations are very important for deferring migration when
120  * the migrating callout is already running.
121  */
122 struct cc_exec {
123         struct callout          *cc_curr;
124 #ifdef SMP
125         void                    (*ce_migration_func)(void *);
126         void                    *ce_migration_arg;
127         int                     ce_migration_cpu;
128         sbintime_t              ce_migration_time;
129         sbintime_t              ce_migration_prec;
130 #endif
131         bool                    cc_cancel;
132         bool                    cc_waiting;
133 };
134
135 /*
136  * There is one struct callout_cpu per cpu, holding all relevant
137  * state for the callout processing thread on the individual CPU.
138  */
139 struct callout_cpu {
140         struct mtx_padalign     cc_lock;
141         struct cc_exec          cc_exec_entity[2];
142         struct callout          *cc_next;
143         struct callout          *cc_callout;
144         struct callout_list     *cc_callwheel;
145         struct callout_tailq    cc_expireq;
146         struct callout_slist    cc_callfree;
147         sbintime_t              cc_firstevent;
148         sbintime_t              cc_lastscan;
149         void                    *cc_cookie;
150         u_int                   cc_bucket;
151         u_int                   cc_inited;
152         char                    cc_ktr_event_name[20];
153 };
154
155 #define callout_migrating(c)    ((c)->c_iflags & CALLOUT_DFRMIGRATION)
156
157 #define cc_exec_curr(cc, dir)           cc->cc_exec_entity[dir].cc_curr
158 #define cc_exec_next(cc)                cc->cc_next
159 #define cc_exec_cancel(cc, dir)         cc->cc_exec_entity[dir].cc_cancel
160 #define cc_exec_waiting(cc, dir)        cc->cc_exec_entity[dir].cc_waiting
161 #ifdef SMP
162 #define cc_migration_func(cc, dir)      cc->cc_exec_entity[dir].ce_migration_func
163 #define cc_migration_arg(cc, dir)       cc->cc_exec_entity[dir].ce_migration_arg
164 #define cc_migration_cpu(cc, dir)       cc->cc_exec_entity[dir].ce_migration_cpu
165 #define cc_migration_time(cc, dir)      cc->cc_exec_entity[dir].ce_migration_time
166 #define cc_migration_prec(cc, dir)      cc->cc_exec_entity[dir].ce_migration_prec
167
168 struct callout_cpu cc_cpu[MAXCPU];
169 #define CPUBLOCK        MAXCPU
170 #define CC_CPU(cpu)     (&cc_cpu[(cpu)])
171 #define CC_SELF()       CC_CPU(PCPU_GET(cpuid))
172 #else
173 struct callout_cpu cc_cpu;
174 #define CC_CPU(cpu)     &cc_cpu
175 #define CC_SELF()       &cc_cpu
176 #endif
177 #define CC_LOCK(cc)     mtx_lock_spin(&(cc)->cc_lock)
178 #define CC_UNLOCK(cc)   mtx_unlock_spin(&(cc)->cc_lock)
179 #define CC_LOCK_ASSERT(cc)      mtx_assert(&(cc)->cc_lock, MA_OWNED)
180
181 static int timeout_cpu;
182
183 static void     callout_cpu_init(struct callout_cpu *cc, int cpu);
184 static void     softclock_call_cc(struct callout *c, struct callout_cpu *cc,
185 #ifdef CALLOUT_PROFILING
186                     int *mpcalls, int *lockcalls, int *gcalls,
187 #endif
188                     int direct);
189
190 static MALLOC_DEFINE(M_CALLOUT, "callout", "Callout datastructures");
191
192 /**
193  * Locked by cc_lock:
194  *   cc_curr         - If a callout is in progress, it is cc_curr.
195  *                     If cc_curr is non-NULL, threads waiting in
196  *                     callout_drain() will be woken up as soon as the
197  *                     relevant callout completes.
198  *   cc_cancel       - Changing to 1 with both callout_lock and cc_lock held
199  *                     guarantees that the current callout will not run.
200  *                     The softclock() function sets this to 0 before it
201  *                     drops callout_lock to acquire c_lock, and it calls
202  *                     the handler only if curr_cancelled is still 0 after
203  *                     cc_lock is successfully acquired.
204  *   cc_waiting      - If a thread is waiting in callout_drain(), then
205  *                     callout_wait is nonzero.  Set only when
206  *                     cc_curr is non-NULL.
207  */
208
209 /*
210  * Resets the execution entity tied to a specific callout cpu.
211  */
212 static void
213 cc_cce_cleanup(struct callout_cpu *cc, int direct)
214 {
215
216         cc_exec_curr(cc, direct) = NULL;
217         cc_exec_cancel(cc, direct) = false;
218         cc_exec_waiting(cc, direct) = false;
219 #ifdef SMP
220         cc_migration_cpu(cc, direct) = CPUBLOCK;
221         cc_migration_time(cc, direct) = 0;
222         cc_migration_prec(cc, direct) = 0;
223         cc_migration_func(cc, direct) = NULL;
224         cc_migration_arg(cc, direct) = NULL;
225 #endif
226 }
227
228 /*
229  * Checks if migration is requested by a specific callout cpu.
230  */
231 static int
232 cc_cce_migrating(struct callout_cpu *cc, int direct)
233 {
234
235 #ifdef SMP
236         return (cc_migration_cpu(cc, direct) != CPUBLOCK);
237 #else
238         return (0);
239 #endif
240 }
241
242 /*
243  * Kernel low level callwheel initialization
244  * called on cpu0 during kernel startup.
245  */
246 static void
247 callout_callwheel_init(void *dummy)
248 {
249         struct callout_cpu *cc;
250
251         /*
252          * Calculate the size of the callout wheel and the preallocated
253          * timeout() structures.
254          * XXX: Clip callout to result of previous function of maxusers
255          * maximum 384.  This is still huge, but acceptable.
256          */
257         memset(CC_CPU(0), 0, sizeof(cc_cpu));
258         ncallout = imin(16 + maxproc + maxfiles, 18508);
259         TUNABLE_INT_FETCH("kern.ncallout", &ncallout);
260
261         /*
262          * Calculate callout wheel size, should be next power of two higher
263          * than 'ncallout'.
264          */
265         callwheelsize = 1 << fls(ncallout);
266         callwheelmask = callwheelsize - 1;
267
268         /*
269          * Only cpu0 handles timeout(9) and receives a preallocation.
270          *
271          * XXX: Once all timeout(9) consumers are converted this can
272          * be removed.
273          */
274         timeout_cpu = PCPU_GET(cpuid);
275         cc = CC_CPU(timeout_cpu);
276         cc->cc_callout = malloc(ncallout * sizeof(struct callout),
277             M_CALLOUT, M_WAITOK);
278         callout_cpu_init(cc, timeout_cpu);
279 }
280 SYSINIT(callwheel_init, SI_SUB_CPU, SI_ORDER_ANY, callout_callwheel_init, NULL);
281
282 /*
283  * Initialize the per-cpu callout structures.
284  */
285 static void
286 callout_cpu_init(struct callout_cpu *cc, int cpu)
287 {
288         struct callout *c;
289         int i;
290
291         mtx_init(&cc->cc_lock, "callout", NULL, MTX_SPIN | MTX_RECURSE);
292         SLIST_INIT(&cc->cc_callfree);
293         cc->cc_inited = 1;
294         cc->cc_callwheel = malloc(sizeof(struct callout_list) * callwheelsize,
295             M_CALLOUT, M_WAITOK);
296         for (i = 0; i < callwheelsize; i++)
297                 LIST_INIT(&cc->cc_callwheel[i]);
298         TAILQ_INIT(&cc->cc_expireq);
299         cc->cc_firstevent = INT64_MAX;
300         for (i = 0; i < 2; i++)
301                 cc_cce_cleanup(cc, i);
302         snprintf(cc->cc_ktr_event_name, sizeof(cc->cc_ktr_event_name),
303             "callwheel cpu %d", cpu);
304         if (cc->cc_callout == NULL)     /* Only cpu0 handles timeout(9) */
305                 return;
306         for (i = 0; i < ncallout; i++) {
307                 c = &cc->cc_callout[i];
308                 callout_init(c, 0);
309                 c->c_iflags = CALLOUT_LOCAL_ALLOC;
310                 SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
311         }
312 }
313
314 #ifdef SMP
315 /*
316  * Switches the cpu tied to a specific callout.
317  * The function expects a locked incoming callout cpu and returns with
318  * locked outcoming callout cpu.
319  */
320 static struct callout_cpu *
321 callout_cpu_switch(struct callout *c, struct callout_cpu *cc, int new_cpu)
322 {
323         struct callout_cpu *new_cc;
324
325         MPASS(c != NULL && cc != NULL);
326         CC_LOCK_ASSERT(cc);
327
328         /*
329          * Avoid interrupts and preemption firing after the callout cpu
330          * is blocked in order to avoid deadlocks as the new thread
331          * may be willing to acquire the callout cpu lock.
332          */
333         c->c_cpu = CPUBLOCK;
334         spinlock_enter();
335         CC_UNLOCK(cc);
336         new_cc = CC_CPU(new_cpu);
337         CC_LOCK(new_cc);
338         spinlock_exit();
339         c->c_cpu = new_cpu;
340         return (new_cc);
341 }
342 #endif
343
344 /*
345  * Start standard softclock thread.
346  */
347 static void
348 start_softclock(void *dummy)
349 {
350         struct callout_cpu *cc;
351 #ifdef SMP
352         int cpu;
353 #endif
354
355         cc = CC_CPU(timeout_cpu);
356         if (swi_add(&clk_intr_event, "clock", softclock, cc, SWI_CLOCK,
357             INTR_MPSAFE, &cc->cc_cookie))
358                 panic("died while creating standard software ithreads");
359 #ifdef SMP
360         CPU_FOREACH(cpu) {
361                 if (cpu == timeout_cpu)
362                         continue;
363                 cc = CC_CPU(cpu);
364                 cc->cc_callout = NULL;  /* Only cpu0 handles timeout(9). */
365                 callout_cpu_init(cc, cpu);
366                 if (swi_add(NULL, "clock", softclock, cc, SWI_CLOCK,
367                     INTR_MPSAFE, &cc->cc_cookie))
368                         panic("died while creating standard software ithreads");
369         }
370 #endif
371 }
372 SYSINIT(start_softclock, SI_SUB_SOFTINTR, SI_ORDER_FIRST, start_softclock, NULL);
373
374 #define CC_HASH_SHIFT   8
375
376 static inline u_int
377 callout_hash(sbintime_t sbt)
378 {
379
380         return (sbt >> (32 - CC_HASH_SHIFT));
381 }
382
383 static inline u_int
384 callout_get_bucket(sbintime_t sbt)
385 {
386
387         return (callout_hash(sbt) & callwheelmask);
388 }
389
390 void
391 callout_process(sbintime_t now)
392 {
393         struct callout *tmp, *tmpn;
394         struct callout_cpu *cc;
395         struct callout_list *sc;
396         sbintime_t first, last, max, tmp_max;
397         uint32_t lookahead;
398         u_int firstb, lastb, nowb;
399 #ifdef CALLOUT_PROFILING
400         int depth_dir = 0, mpcalls_dir = 0, lockcalls_dir = 0;
401 #endif
402
403         cc = CC_SELF();
404         mtx_lock_spin_flags(&cc->cc_lock, MTX_QUIET);
405
406         /* Compute the buckets of the last scan and present times. */
407         firstb = callout_hash(cc->cc_lastscan);
408         cc->cc_lastscan = now;
409         nowb = callout_hash(now);
410
411         /* Compute the last bucket and minimum time of the bucket after it. */
412         if (nowb == firstb)
413                 lookahead = (SBT_1S / 16);
414         else if (nowb - firstb == 1)
415                 lookahead = (SBT_1S / 8);
416         else
417                 lookahead = (SBT_1S / 2);
418         first = last = now;
419         first += (lookahead / 2);
420         last += lookahead;
421         last &= (0xffffffffffffffffLLU << (32 - CC_HASH_SHIFT));
422         lastb = callout_hash(last) - 1;
423         max = last;
424
425         /*
426          * Check if we wrapped around the entire wheel from the last scan.
427          * In case, we need to scan entirely the wheel for pending callouts.
428          */
429         if (lastb - firstb >= callwheelsize) {
430                 lastb = firstb + callwheelsize - 1;
431                 if (nowb - firstb >= callwheelsize)
432                         nowb = lastb;
433         }
434
435         /* Iterate callwheel from firstb to nowb and then up to lastb. */
436         do {
437                 sc = &cc->cc_callwheel[firstb & callwheelmask];
438                 tmp = LIST_FIRST(sc);
439                 while (tmp != NULL) {
440                         /* Run the callout if present time within allowed. */
441                         if (tmp->c_time <= now) {
442                                 /*
443                                  * Consumer told us the callout may be run
444                                  * directly from hardware interrupt context.
445                                  */
446                                 if (tmp->c_iflags & CALLOUT_DIRECT) {
447 #ifdef CALLOUT_PROFILING
448                                         ++depth_dir;
449 #endif
450                                         cc_exec_next(cc) =
451                                             LIST_NEXT(tmp, c_links.le);
452                                         cc->cc_bucket = firstb & callwheelmask;
453                                         LIST_REMOVE(tmp, c_links.le);
454                                         softclock_call_cc(tmp, cc,
455 #ifdef CALLOUT_PROFILING
456                                             &mpcalls_dir, &lockcalls_dir, NULL,
457 #endif
458                                             1);
459                                         tmp = cc_exec_next(cc);
460                                         cc_exec_next(cc) = NULL;
461                                 } else {
462                                         tmpn = LIST_NEXT(tmp, c_links.le);
463                                         LIST_REMOVE(tmp, c_links.le);
464                                         TAILQ_INSERT_TAIL(&cc->cc_expireq,
465                                             tmp, c_links.tqe);
466                                         tmp->c_iflags |= CALLOUT_PROCESSED;
467                                         tmp = tmpn;
468                                 }
469                                 continue;
470                         }
471                         /* Skip events from distant future. */
472                         if (tmp->c_time >= max)
473                                 goto next;
474                         /*
475                          * Event minimal time is bigger than present maximal
476                          * time, so it cannot be aggregated.
477                          */
478                         if (tmp->c_time > last) {
479                                 lastb = nowb;
480                                 goto next;
481                         }
482                         /* Update first and last time, respecting this event. */
483                         if (tmp->c_time < first)
484                                 first = tmp->c_time;
485                         tmp_max = tmp->c_time + tmp->c_precision;
486                         if (tmp_max < last)
487                                 last = tmp_max;
488 next:
489                         tmp = LIST_NEXT(tmp, c_links.le);
490                 }
491                 /* Proceed with the next bucket. */
492                 firstb++;
493                 /*
494                  * Stop if we looked after present time and found
495                  * some event we can't execute at now.
496                  * Stop if we looked far enough into the future.
497                  */
498         } while (((int)(firstb - lastb)) <= 0);
499         cc->cc_firstevent = last;
500 #ifndef NO_EVENTTIMERS
501         cpu_new_callout(curcpu, last, first);
502 #endif
503 #ifdef CALLOUT_PROFILING
504         avg_depth_dir += (depth_dir * 1000 - avg_depth_dir) >> 8;
505         avg_mpcalls_dir += (mpcalls_dir * 1000 - avg_mpcalls_dir) >> 8;
506         avg_lockcalls_dir += (lockcalls_dir * 1000 - avg_lockcalls_dir) >> 8;
507 #endif
508         mtx_unlock_spin_flags(&cc->cc_lock, MTX_QUIET);
509         /*
510          * swi_sched acquires the thread lock, so we don't want to call it
511          * with cc_lock held; incorrect locking order.
512          */
513         if (!TAILQ_EMPTY(&cc->cc_expireq))
514                 swi_sched(cc->cc_cookie, 0);
515 }
516
517 static struct callout_cpu *
518 callout_lock(struct callout *c)
519 {
520         struct callout_cpu *cc;
521         int cpu;
522
523         for (;;) {
524                 cpu = c->c_cpu;
525 #ifdef SMP
526                 if (cpu == CPUBLOCK) {
527                         while (c->c_cpu == CPUBLOCK)
528                                 cpu_spinwait();
529                         continue;
530                 }
531 #endif
532                 cc = CC_CPU(cpu);
533                 CC_LOCK(cc);
534                 if (cpu == c->c_cpu)
535                         break;
536                 CC_UNLOCK(cc);
537         }
538         return (cc);
539 }
540
541 static void
542 callout_cc_add(struct callout *c, struct callout_cpu *cc,
543     sbintime_t sbt, sbintime_t precision, void (*func)(void *),
544     void *arg, int cpu, int flags)
545 {
546         int bucket;
547
548         CC_LOCK_ASSERT(cc);
549         if (sbt < cc->cc_lastscan)
550                 sbt = cc->cc_lastscan;
551         c->c_arg = arg;
552         c->c_iflags |= CALLOUT_PENDING;
553         c->c_iflags &= ~CALLOUT_PROCESSED;
554         c->c_flags |= CALLOUT_ACTIVE;
555         if (flags & C_DIRECT_EXEC)
556                 c->c_iflags |= CALLOUT_DIRECT;
557         c->c_func = func;
558         c->c_time = sbt;
559         c->c_precision = precision;
560         bucket = callout_get_bucket(c->c_time);
561         CTR3(KTR_CALLOUT, "precision set for %p: %d.%08x",
562             c, (int)(c->c_precision >> 32),
563             (u_int)(c->c_precision & 0xffffffff));
564         LIST_INSERT_HEAD(&cc->cc_callwheel[bucket], c, c_links.le);
565         if (cc->cc_bucket == bucket)
566                 cc_exec_next(cc) = c;
567 #ifndef NO_EVENTTIMERS
568         /*
569          * Inform the eventtimers(4) subsystem there's a new callout
570          * that has been inserted, but only if really required.
571          */
572         if (INT64_MAX - c->c_time < c->c_precision)
573                 c->c_precision = INT64_MAX - c->c_time;
574         sbt = c->c_time + c->c_precision;
575         if (sbt < cc->cc_firstevent) {
576                 cc->cc_firstevent = sbt;
577                 cpu_new_callout(cpu, sbt, c->c_time);
578         }
579 #endif
580 }
581
582 static void
583 callout_cc_del(struct callout *c, struct callout_cpu *cc)
584 {
585
586         if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) == 0)
587                 return;
588         c->c_func = NULL;
589         SLIST_INSERT_HEAD(&cc->cc_callfree, c, c_links.sle);
590 }
591
592 static void
593 softclock_call_cc(struct callout *c, struct callout_cpu *cc,
594 #ifdef CALLOUT_PROFILING
595     int *mpcalls, int *lockcalls, int *gcalls,
596 #endif
597     int direct)
598 {
599         struct rm_priotracker tracker;
600         void (*c_func)(void *);
601         void *c_arg;
602         struct lock_class *class;
603         struct lock_object *c_lock;
604         uintptr_t lock_status;
605         int c_iflags;
606 #ifdef SMP
607         struct callout_cpu *new_cc;
608         void (*new_func)(void *);
609         void *new_arg;
610         int flags, new_cpu;
611         sbintime_t new_prec, new_time;
612 #endif
613 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING) 
614         sbintime_t sbt1, sbt2;
615         struct timespec ts2;
616         static sbintime_t maxdt = 2 * SBT_1MS;  /* 2 msec */
617         static timeout_t *lastfunc;
618 #endif
619
620         KASSERT((c->c_iflags & CALLOUT_PENDING) == CALLOUT_PENDING,
621             ("softclock_call_cc: pend %p %x", c, c->c_iflags));
622         KASSERT((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE,
623             ("softclock_call_cc: act %p %x", c, c->c_flags));
624         class = (c->c_lock != NULL) ? LOCK_CLASS(c->c_lock) : NULL;
625         lock_status = 0;
626         if (c->c_flags & CALLOUT_SHAREDLOCK) {
627                 if (class == &lock_class_rm)
628                         lock_status = (uintptr_t)&tracker;
629                 else
630                         lock_status = 1;
631         }
632         c_lock = c->c_lock;
633         c_func = c->c_func;
634         c_arg = c->c_arg;
635         c_iflags = c->c_iflags;
636         if (c->c_iflags & CALLOUT_LOCAL_ALLOC)
637                 c->c_iflags = CALLOUT_LOCAL_ALLOC;
638         else
639                 c->c_iflags &= ~CALLOUT_PENDING;
640         
641         cc_exec_curr(cc, direct) = c;
642         cc_exec_cancel(cc, direct) = false;
643         CC_UNLOCK(cc);
644         if (c_lock != NULL) {
645                 class->lc_lock(c_lock, lock_status);
646                 /*
647                  * The callout may have been cancelled
648                  * while we switched locks.
649                  */
650                 if (cc_exec_cancel(cc, direct)) {
651                         class->lc_unlock(c_lock);
652                         goto skip;
653                 }
654                 /* The callout cannot be stopped now. */
655                 cc_exec_cancel(cc, direct) = true;
656                 if (c_lock == &Giant.lock_object) {
657 #ifdef CALLOUT_PROFILING
658                         (*gcalls)++;
659 #endif
660                         CTR3(KTR_CALLOUT, "callout giant %p func %p arg %p",
661                             c, c_func, c_arg);
662                 } else {
663 #ifdef CALLOUT_PROFILING
664                         (*lockcalls)++;
665 #endif
666                         CTR3(KTR_CALLOUT, "callout lock %p func %p arg %p",
667                             c, c_func, c_arg);
668                 }
669         } else {
670 #ifdef CALLOUT_PROFILING
671                 (*mpcalls)++;
672 #endif
673                 CTR3(KTR_CALLOUT, "callout %p func %p arg %p",
674                     c, c_func, c_arg);
675         }
676         KTR_STATE3(KTR_SCHED, "callout", cc->cc_ktr_event_name, "running",
677             "func:%p", c_func, "arg:%p", c_arg, "direct:%d", direct);
678 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
679         sbt1 = sbinuptime();
680 #endif
681         THREAD_NO_SLEEPING();
682         SDT_PROBE1(callout_execute, , , callout__start, c);
683         c_func(c_arg);
684         SDT_PROBE1(callout_execute, , , callout__end, c);
685         THREAD_SLEEPING_OK();
686 #if defined(DIAGNOSTIC) || defined(CALLOUT_PROFILING)
687         sbt2 = sbinuptime();
688         sbt2 -= sbt1;
689         if (sbt2 > maxdt) {
690                 if (lastfunc != c_func || sbt2 > maxdt * 2) {
691                         ts2 = sbttots(sbt2);
692                         printf(
693                 "Expensive timeout(9) function: %p(%p) %jd.%09ld s\n",
694                             c_func, c_arg, (intmax_t)ts2.tv_sec, ts2.tv_nsec);
695                 }
696                 maxdt = sbt2;
697                 lastfunc = c_func;
698         }
699 #endif
700         KTR_STATE0(KTR_SCHED, "callout", cc->cc_ktr_event_name, "idle");
701         CTR1(KTR_CALLOUT, "callout %p finished", c);
702         if ((c_iflags & CALLOUT_RETURNUNLOCKED) == 0)
703                 class->lc_unlock(c_lock);
704 skip:
705         CC_LOCK(cc);
706         KASSERT(cc_exec_curr(cc, direct) == c, ("mishandled cc_curr"));
707         cc_exec_curr(cc, direct) = NULL;
708         if (cc_exec_waiting(cc, direct)) {
709                 /*
710                  * There is someone waiting for the
711                  * callout to complete.
712                  * If the callout was scheduled for
713                  * migration just cancel it.
714                  */
715                 if (cc_cce_migrating(cc, direct)) {
716                         cc_cce_cleanup(cc, direct);
717
718                         /*
719                          * It should be assert here that the callout is not
720                          * destroyed but that is not easy.
721                          */
722                         c->c_iflags &= ~CALLOUT_DFRMIGRATION;
723                 }
724                 cc_exec_waiting(cc, direct) = false;
725                 CC_UNLOCK(cc);
726                 wakeup(&cc_exec_waiting(cc, direct));
727                 CC_LOCK(cc);
728         } else if (cc_cce_migrating(cc, direct)) {
729                 KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0,
730                     ("Migrating legacy callout %p", c));
731 #ifdef SMP
732                 /*
733                  * If the callout was scheduled for
734                  * migration just perform it now.
735                  */
736                 new_cpu = cc_migration_cpu(cc, direct);
737                 new_time = cc_migration_time(cc, direct);
738                 new_prec = cc_migration_prec(cc, direct);
739                 new_func = cc_migration_func(cc, direct);
740                 new_arg = cc_migration_arg(cc, direct);
741                 cc_cce_cleanup(cc, direct);
742
743                 /*
744                  * It should be assert here that the callout is not destroyed
745                  * but that is not easy.
746                  *
747                  * As first thing, handle deferred callout stops.
748                  */
749                 if (!callout_migrating(c)) {
750                         CTR3(KTR_CALLOUT,
751                              "deferred cancelled %p func %p arg %p",
752                              c, new_func, new_arg);
753                         callout_cc_del(c, cc);
754                         return;
755                 }
756                 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
757
758                 new_cc = callout_cpu_switch(c, cc, new_cpu);
759                 flags = (direct) ? C_DIRECT_EXEC : 0;
760                 callout_cc_add(c, new_cc, new_time, new_prec, new_func,
761                     new_arg, new_cpu, flags);
762                 CC_UNLOCK(new_cc);
763                 CC_LOCK(cc);
764 #else
765                 panic("migration should not happen");
766 #endif
767         }
768         /*
769          * If the current callout is locally allocated (from
770          * timeout(9)) then put it on the freelist.
771          *
772          * Note: we need to check the cached copy of c_iflags because
773          * if it was not local, then it's not safe to deref the
774          * callout pointer.
775          */
776         KASSERT((c_iflags & CALLOUT_LOCAL_ALLOC) == 0 ||
777             c->c_iflags == CALLOUT_LOCAL_ALLOC,
778             ("corrupted callout"));
779         if (c_iflags & CALLOUT_LOCAL_ALLOC)
780                 callout_cc_del(c, cc);
781 }
782
783 /*
784  * The callout mechanism is based on the work of Adam M. Costello and
785  * George Varghese, published in a technical report entitled "Redesigning
786  * the BSD Callout and Timer Facilities" and modified slightly for inclusion
787  * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
788  * used in this implementation was published by G. Varghese and T. Lauck in
789  * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
790  * the Efficient Implementation of a Timer Facility" in the Proceedings of
791  * the 11th ACM Annual Symposium on Operating Systems Principles,
792  * Austin, Texas Nov 1987.
793  */
794
795 /*
796  * Software (low priority) clock interrupt.
797  * Run periodic events from timeout queue.
798  */
799 void
800 softclock(void *arg)
801 {
802         struct callout_cpu *cc;
803         struct callout *c;
804 #ifdef CALLOUT_PROFILING
805         int depth = 0, gcalls = 0, lockcalls = 0, mpcalls = 0;
806 #endif
807
808         cc = (struct callout_cpu *)arg;
809         CC_LOCK(cc);
810         while ((c = TAILQ_FIRST(&cc->cc_expireq)) != NULL) {
811                 TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
812                 softclock_call_cc(c, cc,
813 #ifdef CALLOUT_PROFILING
814                     &mpcalls, &lockcalls, &gcalls,
815 #endif
816                     0);
817 #ifdef CALLOUT_PROFILING
818                 ++depth;
819 #endif
820         }
821 #ifdef CALLOUT_PROFILING
822         avg_depth += (depth * 1000 - avg_depth) >> 8;
823         avg_mpcalls += (mpcalls * 1000 - avg_mpcalls) >> 8;
824         avg_lockcalls += (lockcalls * 1000 - avg_lockcalls) >> 8;
825         avg_gcalls += (gcalls * 1000 - avg_gcalls) >> 8;
826 #endif
827         CC_UNLOCK(cc);
828 }
829
830 /*
831  * timeout --
832  *      Execute a function after a specified length of time.
833  *
834  * untimeout --
835  *      Cancel previous timeout function call.
836  *
837  * callout_handle_init --
838  *      Initialize a handle so that using it with untimeout is benign.
839  *
840  *      See AT&T BCI Driver Reference Manual for specification.  This
841  *      implementation differs from that one in that although an
842  *      identification value is returned from timeout, the original
843  *      arguments to timeout as well as the identifier are used to
844  *      identify entries for untimeout.
845  */
846 struct callout_handle
847 timeout(ftn, arg, to_ticks)
848         timeout_t *ftn;
849         void *arg;
850         int to_ticks;
851 {
852         struct callout_cpu *cc;
853         struct callout *new;
854         struct callout_handle handle;
855
856         cc = CC_CPU(timeout_cpu);
857         CC_LOCK(cc);
858         /* Fill in the next free callout structure. */
859         new = SLIST_FIRST(&cc->cc_callfree);
860         if (new == NULL)
861                 /* XXX Attempt to malloc first */
862                 panic("timeout table full");
863         SLIST_REMOVE_HEAD(&cc->cc_callfree, c_links.sle);
864         callout_reset(new, to_ticks, ftn, arg);
865         handle.callout = new;
866         CC_UNLOCK(cc);
867
868         return (handle);
869 }
870
871 void
872 untimeout(ftn, arg, handle)
873         timeout_t *ftn;
874         void *arg;
875         struct callout_handle handle;
876 {
877         struct callout_cpu *cc;
878
879         /*
880          * Check for a handle that was initialized
881          * by callout_handle_init, but never used
882          * for a real timeout.
883          */
884         if (handle.callout == NULL)
885                 return;
886
887         cc = callout_lock(handle.callout);
888         if (handle.callout->c_func == ftn && handle.callout->c_arg == arg)
889                 callout_stop(handle.callout);
890         CC_UNLOCK(cc);
891 }
892
893 void
894 callout_handle_init(struct callout_handle *handle)
895 {
896         handle->callout = NULL;
897 }
898
899 /*
900  * New interface; clients allocate their own callout structures.
901  *
902  * callout_reset() - establish or change a timeout
903  * callout_stop() - disestablish a timeout
904  * callout_init() - initialize a callout structure so that it can
905  *      safely be passed to callout_reset() and callout_stop()
906  *
907  * <sys/callout.h> defines three convenience macros:
908  *
909  * callout_active() - returns truth if callout has not been stopped,
910  *      drained, or deactivated since the last time the callout was
911  *      reset.
912  * callout_pending() - returns truth if callout is still waiting for timeout
913  * callout_deactivate() - marks the callout as having been serviced
914  */
915 int
916 callout_reset_sbt_on(struct callout *c, sbintime_t sbt, sbintime_t precision,
917     void (*ftn)(void *), void *arg, int cpu, int flags)
918 {
919         sbintime_t to_sbt, pr;
920         struct callout_cpu *cc;
921         int cancelled, direct;
922         int ignore_cpu=0;
923
924         cancelled = 0;
925         if (cpu == -1) {
926                 ignore_cpu = 1;
927         } else if ((cpu >= MAXCPU) ||
928                    ((CC_CPU(cpu))->cc_inited == 0)) {
929                 /* Invalid CPU spec */
930                 panic("Invalid CPU in callout %d", cpu);
931         }
932         if (flags & C_ABSOLUTE) {
933                 to_sbt = sbt;
934         } else {
935                 if ((flags & C_HARDCLOCK) && (sbt < tick_sbt))
936                         sbt = tick_sbt;
937                 if ((flags & C_HARDCLOCK) ||
938 #ifdef NO_EVENTTIMERS
939                     sbt >= sbt_timethreshold) {
940                         to_sbt = getsbinuptime();
941
942                         /* Add safety belt for the case of hz > 1000. */
943                         to_sbt += tc_tick_sbt - tick_sbt;
944 #else
945                     sbt >= sbt_tickthreshold) {
946                         /*
947                          * Obtain the time of the last hardclock() call on
948                          * this CPU directly from the kern_clocksource.c.
949                          * This value is per-CPU, but it is equal for all
950                          * active ones.
951                          */
952 #ifdef __LP64__
953                         to_sbt = DPCPU_GET(hardclocktime);
954 #else
955                         spinlock_enter();
956                         to_sbt = DPCPU_GET(hardclocktime);
957                         spinlock_exit();
958 #endif
959 #endif
960                         if ((flags & C_HARDCLOCK) == 0)
961                                 to_sbt += tick_sbt;
962                 } else
963                         to_sbt = sbinuptime();
964                 if (INT64_MAX - to_sbt < sbt)
965                         to_sbt = INT64_MAX;
966                 else
967                         to_sbt += sbt;
968                 pr = ((C_PRELGET(flags) < 0) ? sbt >> tc_precexp :
969                     sbt >> C_PRELGET(flags));
970                 if (pr > precision)
971                         precision = pr;
972         }
973         /* 
974          * This flag used to be added by callout_cc_add, but the
975          * first time you call this we could end up with the
976          * wrong direct flag if we don't do it before we add.
977          */
978         if (flags & C_DIRECT_EXEC) {
979                 direct = 1;
980         } else {
981                 direct = 0;
982         }
983         KASSERT(!direct || c->c_lock == NULL,
984             ("%s: direct callout %p has lock", __func__, c));
985         cc = callout_lock(c);
986         /*
987          * Don't allow migration of pre-allocated callouts lest they
988          * become unbalanced or handle the case where the user does
989          * not care. 
990          */
991         if ((c->c_iflags & CALLOUT_LOCAL_ALLOC) ||
992             ignore_cpu) {
993                 cpu = c->c_cpu;
994         }
995
996         if (cc_exec_curr(cc, direct) == c) {
997                 /*
998                  * We're being asked to reschedule a callout which is
999                  * currently in progress.  If there is a lock then we
1000                  * can cancel the callout if it has not really started.
1001                  */
1002                 if (c->c_lock != NULL && !cc_exec_cancel(cc, direct))
1003                         cancelled = cc_exec_cancel(cc, direct) = true;
1004                 if (cc_exec_waiting(cc, direct)) {
1005                         /*
1006                          * Someone has called callout_drain to kill this
1007                          * callout.  Don't reschedule.
1008                          */
1009                         CTR4(KTR_CALLOUT, "%s %p func %p arg %p",
1010                             cancelled ? "cancelled" : "failed to cancel",
1011                             c, c->c_func, c->c_arg);
1012                         CC_UNLOCK(cc);
1013                         return (cancelled);
1014                 }
1015 #ifdef SMP
1016                 if (callout_migrating(c)) {
1017                         /* 
1018                          * This only occurs when a second callout_reset_sbt_on
1019                          * is made after a previous one moved it into
1020                          * deferred migration (below). Note we do *not* change
1021                          * the prev_cpu even though the previous target may
1022                          * be different.
1023                          */
1024                         cc_migration_cpu(cc, direct) = cpu;
1025                         cc_migration_time(cc, direct) = to_sbt;
1026                         cc_migration_prec(cc, direct) = precision;
1027                         cc_migration_func(cc, direct) = ftn;
1028                         cc_migration_arg(cc, direct) = arg;
1029                         cancelled = 1;
1030                         CC_UNLOCK(cc);
1031                         return (cancelled);
1032                 }
1033 #endif
1034         }
1035         if (c->c_iflags & CALLOUT_PENDING) {
1036                 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1037                         if (cc_exec_next(cc) == c)
1038                                 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1039                         LIST_REMOVE(c, c_links.le);
1040                 } else {
1041                         TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1042                 }
1043                 cancelled = 1;
1044                 c->c_iflags &= ~ CALLOUT_PENDING;
1045                 c->c_flags &= ~ CALLOUT_ACTIVE;
1046         }
1047
1048 #ifdef SMP
1049         /*
1050          * If the callout must migrate try to perform it immediately.
1051          * If the callout is currently running, just defer the migration
1052          * to a more appropriate moment.
1053          */
1054         if (c->c_cpu != cpu) {
1055                 if (cc_exec_curr(cc, direct) == c) {
1056                         /* 
1057                          * Pending will have been removed since we are
1058                          * actually executing the callout on another
1059                          * CPU. That callout should be waiting on the
1060                          * lock the caller holds. If we set both
1061                          * active/and/pending after we return and the
1062                          * lock on the executing callout proceeds, it
1063                          * will then see pending is true and return.
1064                          * At the return from the actual callout execution
1065                          * the migration will occur in softclock_call_cc
1066                          * and this new callout will be placed on the 
1067                          * new CPU via a call to callout_cpu_switch() which
1068                          * will get the lock on the right CPU followed
1069                          * by a call callout_cc_add() which will add it there.
1070                          * (see above in softclock_call_cc()).
1071                          */
1072                         cc_migration_cpu(cc, direct) = cpu;
1073                         cc_migration_time(cc, direct) = to_sbt;
1074                         cc_migration_prec(cc, direct) = precision;
1075                         cc_migration_func(cc, direct) = ftn;
1076                         cc_migration_arg(cc, direct) = arg;
1077                         c->c_iflags |= (CALLOUT_DFRMIGRATION | CALLOUT_PENDING);
1078                         c->c_flags |= CALLOUT_ACTIVE;
1079                         CTR6(KTR_CALLOUT,
1080                     "migration of %p func %p arg %p in %d.%08x to %u deferred",
1081                             c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1082                             (u_int)(to_sbt & 0xffffffff), cpu);
1083                         CC_UNLOCK(cc);
1084                         return (cancelled);
1085                 }
1086                 cc = callout_cpu_switch(c, cc, cpu);
1087         }
1088 #endif
1089
1090         callout_cc_add(c, cc, to_sbt, precision, ftn, arg, cpu, flags);
1091         CTR6(KTR_CALLOUT, "%sscheduled %p func %p arg %p in %d.%08x",
1092             cancelled ? "re" : "", c, c->c_func, c->c_arg, (int)(to_sbt >> 32),
1093             (u_int)(to_sbt & 0xffffffff));
1094         CC_UNLOCK(cc);
1095
1096         return (cancelled);
1097 }
1098
1099 /*
1100  * Common idioms that can be optimized in the future.
1101  */
1102 int
1103 callout_schedule_on(struct callout *c, int to_ticks, int cpu)
1104 {
1105         return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, cpu);
1106 }
1107
1108 int
1109 callout_schedule(struct callout *c, int to_ticks)
1110 {
1111         return callout_reset_on(c, to_ticks, c->c_func, c->c_arg, c->c_cpu);
1112 }
1113
1114 int
1115 _callout_stop_safe(c, flags)
1116         struct  callout *c;
1117         int     flags;
1118 {
1119         struct callout_cpu *cc, *old_cc;
1120         struct lock_class *class;
1121         int direct, sq_locked, use_lock;
1122         int not_on_a_list;
1123
1124         /*
1125          * Some old subsystems don't hold Giant while running a callout_stop(),
1126          * so just discard this check for the moment.
1127          */
1128         if ((flags & CS_DRAIN) == 0 && c->c_lock != NULL) {
1129                 if (c->c_lock == &Giant.lock_object)
1130                         use_lock = mtx_owned(&Giant);
1131                 else {
1132                         use_lock = 1;
1133                         class = LOCK_CLASS(c->c_lock);
1134                         class->lc_assert(c->c_lock, LA_XLOCKED);
1135                 }
1136         } else
1137                 use_lock = 0;
1138         if (c->c_iflags & CALLOUT_DIRECT) {
1139                 direct = 1;
1140         } else {
1141                 direct = 0;
1142         }
1143         sq_locked = 0;
1144         old_cc = NULL;
1145 again:
1146         cc = callout_lock(c);
1147
1148         if ((c->c_iflags & (CALLOUT_DFRMIGRATION | CALLOUT_PENDING)) ==
1149             (CALLOUT_DFRMIGRATION | CALLOUT_PENDING) &&
1150             ((c->c_flags & CALLOUT_ACTIVE) == CALLOUT_ACTIVE)) {
1151                 /*
1152                  * Special case where this slipped in while we
1153                  * were migrating *as* the callout is about to
1154                  * execute. The caller probably holds the lock
1155                  * the callout wants.
1156                  *
1157                  * Get rid of the migration first. Then set
1158                  * the flag that tells this code *not* to
1159                  * try to remove it from any lists (its not
1160                  * on one yet). When the callout wheel runs,
1161                  * it will ignore this callout.
1162                  */
1163                 c->c_iflags &= ~CALLOUT_PENDING;
1164                 c->c_flags &= ~CALLOUT_ACTIVE;
1165                 not_on_a_list = 1;
1166         } else {
1167                 not_on_a_list = 0;
1168         }
1169
1170         /*
1171          * If the callout was migrating while the callout cpu lock was
1172          * dropped,  just drop the sleepqueue lock and check the states
1173          * again.
1174          */
1175         if (sq_locked != 0 && cc != old_cc) {
1176 #ifdef SMP
1177                 CC_UNLOCK(cc);
1178                 sleepq_release(&cc_exec_waiting(old_cc, direct));
1179                 sq_locked = 0;
1180                 old_cc = NULL;
1181                 goto again;
1182 #else
1183                 panic("migration should not happen");
1184 #endif
1185         }
1186
1187         /*
1188          * If the callout isn't pending, it's not on the queue, so
1189          * don't attempt to remove it from the queue.  We can try to
1190          * stop it by other means however.
1191          */
1192         if (!(c->c_iflags & CALLOUT_PENDING)) {
1193                 c->c_flags &= ~CALLOUT_ACTIVE;
1194
1195                 /*
1196                  * If it wasn't on the queue and it isn't the current
1197                  * callout, then we can't stop it, so just bail.
1198                  */
1199                 if (cc_exec_curr(cc, direct) != c) {
1200                         CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1201                             c, c->c_func, c->c_arg);
1202                         CC_UNLOCK(cc);
1203                         if (sq_locked)
1204                                 sleepq_release(&cc_exec_waiting(cc, direct));
1205                         return (0);
1206                 }
1207
1208                 if ((flags & CS_DRAIN) != 0) {
1209                         /*
1210                          * The current callout is running (or just
1211                          * about to run) and blocking is allowed, so
1212                          * just wait for the current invocation to
1213                          * finish.
1214                          */
1215                         while (cc_exec_curr(cc, direct) == c) {
1216                                 /*
1217                                  * Use direct calls to sleepqueue interface
1218                                  * instead of cv/msleep in order to avoid
1219                                  * a LOR between cc_lock and sleepqueue
1220                                  * chain spinlocks.  This piece of code
1221                                  * emulates a msleep_spin() call actually.
1222                                  *
1223                                  * If we already have the sleepqueue chain
1224                                  * locked, then we can safely block.  If we
1225                                  * don't already have it locked, however,
1226                                  * we have to drop the cc_lock to lock
1227                                  * it.  This opens several races, so we
1228                                  * restart at the beginning once we have
1229                                  * both locks.  If nothing has changed, then
1230                                  * we will end up back here with sq_locked
1231                                  * set.
1232                                  */
1233                                 if (!sq_locked) {
1234                                         CC_UNLOCK(cc);
1235                                         sleepq_lock(
1236                                             &cc_exec_waiting(cc, direct));
1237                                         sq_locked = 1;
1238                                         old_cc = cc;
1239                                         goto again;
1240                                 }
1241
1242                                 /*
1243                                  * Migration could be cancelled here, but
1244                                  * as long as it is still not sure when it
1245                                  * will be packed up, just let softclock()
1246                                  * take care of it.
1247                                  */
1248                                 cc_exec_waiting(cc, direct) = true;
1249                                 DROP_GIANT();
1250                                 CC_UNLOCK(cc);
1251                                 sleepq_add(
1252                                     &cc_exec_waiting(cc, direct),
1253                                     &cc->cc_lock.lock_object, "codrain",
1254                                     SLEEPQ_SLEEP, 0);
1255                                 sleepq_wait(
1256                                     &cc_exec_waiting(cc, direct),
1257                                              0);
1258                                 sq_locked = 0;
1259                                 old_cc = NULL;
1260
1261                                 /* Reacquire locks previously released. */
1262                                 PICKUP_GIANT();
1263                                 CC_LOCK(cc);
1264                         }
1265                 } else if (use_lock &&
1266                            !cc_exec_cancel(cc, direct)) {
1267                         
1268                         /*
1269                          * The current callout is waiting for its
1270                          * lock which we hold.  Cancel the callout
1271                          * and return.  After our caller drops the
1272                          * lock, the callout will be skipped in
1273                          * softclock().
1274                          */
1275                         cc_exec_cancel(cc, direct) = true;
1276                         CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1277                             c, c->c_func, c->c_arg);
1278                         KASSERT(!cc_cce_migrating(cc, direct),
1279                             ("callout wrongly scheduled for migration"));
1280                         if (callout_migrating(c)) {
1281                                 c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1282 #ifdef SMP
1283                                 cc_migration_cpu(cc, direct) = CPUBLOCK;
1284                                 cc_migration_time(cc, direct) = 0;
1285                                 cc_migration_prec(cc, direct) = 0;
1286                                 cc_migration_func(cc, direct) = NULL;
1287                                 cc_migration_arg(cc, direct) = NULL;
1288 #endif
1289                         }
1290                         CC_UNLOCK(cc);
1291                         KASSERT(!sq_locked, ("sleepqueue chain locked"));
1292                         return (1);
1293                 } else if (callout_migrating(c)) {
1294                         /*
1295                          * The callout is currently being serviced
1296                          * and the "next" callout is scheduled at
1297                          * its completion with a migration. We remove
1298                          * the migration flag so it *won't* get rescheduled,
1299                          * but we can't stop the one thats running so
1300                          * we return 0.
1301                          */
1302                         c->c_iflags &= ~CALLOUT_DFRMIGRATION;
1303 #ifdef SMP
1304                         /* 
1305                          * We can't call cc_cce_cleanup here since
1306                          * if we do it will remove .ce_curr and
1307                          * its still running. This will prevent a
1308                          * reschedule of the callout when the 
1309                          * execution completes.
1310                          */
1311                         cc_migration_cpu(cc, direct) = CPUBLOCK;
1312                         cc_migration_time(cc, direct) = 0;
1313                         cc_migration_prec(cc, direct) = 0;
1314                         cc_migration_func(cc, direct) = NULL;
1315                         cc_migration_arg(cc, direct) = NULL;
1316 #endif
1317                         CTR3(KTR_CALLOUT, "postponing stop %p func %p arg %p",
1318                             c, c->c_func, c->c_arg);
1319                         CC_UNLOCK(cc);
1320                         return ((flags & CS_MIGRBLOCK) != 0);
1321                 }
1322                 CTR3(KTR_CALLOUT, "failed to stop %p func %p arg %p",
1323                     c, c->c_func, c->c_arg);
1324                 CC_UNLOCK(cc);
1325                 KASSERT(!sq_locked, ("sleepqueue chain still locked"));
1326                 return (0);
1327         }
1328         if (sq_locked)
1329                 sleepq_release(&cc_exec_waiting(cc, direct));
1330
1331         c->c_iflags &= ~CALLOUT_PENDING;
1332         c->c_flags &= ~CALLOUT_ACTIVE;
1333
1334         CTR3(KTR_CALLOUT, "cancelled %p func %p arg %p",
1335             c, c->c_func, c->c_arg);
1336         if (not_on_a_list == 0) {
1337                 if ((c->c_iflags & CALLOUT_PROCESSED) == 0) {
1338                         if (cc_exec_next(cc) == c)
1339                                 cc_exec_next(cc) = LIST_NEXT(c, c_links.le);
1340                         LIST_REMOVE(c, c_links.le);
1341                 } else {
1342                         TAILQ_REMOVE(&cc->cc_expireq, c, c_links.tqe);
1343                 }
1344         }
1345         callout_cc_del(c, cc);
1346         CC_UNLOCK(cc);
1347         return (1);
1348 }
1349
1350 void
1351 callout_init(c, mpsafe)
1352         struct  callout *c;
1353         int mpsafe;
1354 {
1355         bzero(c, sizeof *c);
1356         if (mpsafe) {
1357                 c->c_lock = NULL;
1358                 c->c_iflags = CALLOUT_RETURNUNLOCKED;
1359         } else {
1360                 c->c_lock = &Giant.lock_object;
1361                 c->c_iflags = 0;
1362         }
1363         c->c_cpu = timeout_cpu;
1364 }
1365
1366 void
1367 _callout_init_lock(c, lock, flags)
1368         struct  callout *c;
1369         struct  lock_object *lock;
1370         int flags;
1371 {
1372         bzero(c, sizeof *c);
1373         c->c_lock = lock;
1374         KASSERT((flags & ~(CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK)) == 0,
1375             ("callout_init_lock: bad flags %d", flags));
1376         KASSERT(lock != NULL || (flags & CALLOUT_RETURNUNLOCKED) == 0,
1377             ("callout_init_lock: CALLOUT_RETURNUNLOCKED with no lock"));
1378         KASSERT(lock == NULL || !(LOCK_CLASS(lock)->lc_flags &
1379             (LC_SPINLOCK | LC_SLEEPABLE)), ("%s: invalid lock class",
1380             __func__));
1381         c->c_iflags = flags & (CALLOUT_RETURNUNLOCKED | CALLOUT_SHAREDLOCK);
1382         c->c_cpu = timeout_cpu;
1383 }
1384
1385 #ifdef APM_FIXUP_CALLTODO
1386 /* 
1387  * Adjust the kernel calltodo timeout list.  This routine is used after 
1388  * an APM resume to recalculate the calltodo timer list values with the 
1389  * number of hz's we have been sleeping.  The next hardclock() will detect 
1390  * that there are fired timers and run softclock() to execute them.
1391  *
1392  * Please note, I have not done an exhaustive analysis of what code this
1393  * might break.  I am motivated to have my select()'s and alarm()'s that
1394  * have expired during suspend firing upon resume so that the applications
1395  * which set the timer can do the maintanence the timer was for as close
1396  * as possible to the originally intended time.  Testing this code for a 
1397  * week showed that resuming from a suspend resulted in 22 to 25 timers 
1398  * firing, which seemed independent on whether the suspend was 2 hours or
1399  * 2 days.  Your milage may vary.   - Ken Key <key@cs.utk.edu>
1400  */
1401 void
1402 adjust_timeout_calltodo(time_change)
1403     struct timeval *time_change;
1404 {
1405         register struct callout *p;
1406         unsigned long delta_ticks;
1407
1408         /* 
1409          * How many ticks were we asleep?
1410          * (stolen from tvtohz()).
1411          */
1412
1413         /* Don't do anything */
1414         if (time_change->tv_sec < 0)
1415                 return;
1416         else if (time_change->tv_sec <= LONG_MAX / 1000000)
1417                 delta_ticks = (time_change->tv_sec * 1000000 +
1418                                time_change->tv_usec + (tick - 1)) / tick + 1;
1419         else if (time_change->tv_sec <= LONG_MAX / hz)
1420                 delta_ticks = time_change->tv_sec * hz +
1421                               (time_change->tv_usec + (tick - 1)) / tick + 1;
1422         else
1423                 delta_ticks = LONG_MAX;
1424
1425         if (delta_ticks > INT_MAX)
1426                 delta_ticks = INT_MAX;
1427
1428         /* 
1429          * Now rip through the timer calltodo list looking for timers
1430          * to expire.
1431          */
1432
1433         /* don't collide with softclock() */
1434         CC_LOCK(cc);
1435         for (p = calltodo.c_next; p != NULL; p = p->c_next) {
1436                 p->c_time -= delta_ticks;
1437
1438                 /* Break if the timer had more time on it than delta_ticks */
1439                 if (p->c_time > 0)
1440                         break;
1441
1442                 /* take back the ticks the timer didn't use (p->c_time <= 0) */
1443                 delta_ticks = -p->c_time;
1444         }
1445         CC_UNLOCK(cc);
1446
1447         return;
1448 }
1449 #endif /* APM_FIXUP_CALLTODO */
1450
1451 static int
1452 flssbt(sbintime_t sbt)
1453 {
1454
1455         sbt += (uint64_t)sbt >> 1;
1456         if (sizeof(long) >= sizeof(sbintime_t))
1457                 return (flsl(sbt));
1458         if (sbt >= SBT_1S)
1459                 return (flsl(((uint64_t)sbt) >> 32) + 32);
1460         return (flsl(sbt));
1461 }
1462
1463 /*
1464  * Dump immediate statistic snapshot of the scheduled callouts.
1465  */
1466 static int
1467 sysctl_kern_callout_stat(SYSCTL_HANDLER_ARGS)
1468 {
1469         struct callout *tmp;
1470         struct callout_cpu *cc;
1471         struct callout_list *sc;
1472         sbintime_t maxpr, maxt, medpr, medt, now, spr, st, t;
1473         int ct[64], cpr[64], ccpbk[32];
1474         int error, val, i, count, tcum, pcum, maxc, c, medc;
1475 #ifdef SMP
1476         int cpu;
1477 #endif
1478
1479         val = 0;
1480         error = sysctl_handle_int(oidp, &val, 0, req);
1481         if (error != 0 || req->newptr == NULL)
1482                 return (error);
1483         count = maxc = 0;
1484         st = spr = maxt = maxpr = 0;
1485         bzero(ccpbk, sizeof(ccpbk));
1486         bzero(ct, sizeof(ct));
1487         bzero(cpr, sizeof(cpr));
1488         now = sbinuptime();
1489 #ifdef SMP
1490         CPU_FOREACH(cpu) {
1491                 cc = CC_CPU(cpu);
1492 #else
1493                 cc = CC_CPU(timeout_cpu);
1494 #endif
1495                 CC_LOCK(cc);
1496                 for (i = 0; i < callwheelsize; i++) {
1497                         sc = &cc->cc_callwheel[i];
1498                         c = 0;
1499                         LIST_FOREACH(tmp, sc, c_links.le) {
1500                                 c++;
1501                                 t = tmp->c_time - now;
1502                                 if (t < 0)
1503                                         t = 0;
1504                                 st += t / SBT_1US;
1505                                 spr += tmp->c_precision / SBT_1US;
1506                                 if (t > maxt)
1507                                         maxt = t;
1508                                 if (tmp->c_precision > maxpr)
1509                                         maxpr = tmp->c_precision;
1510                                 ct[flssbt(t)]++;
1511                                 cpr[flssbt(tmp->c_precision)]++;
1512                         }
1513                         if (c > maxc)
1514                                 maxc = c;
1515                         ccpbk[fls(c + c / 2)]++;
1516                         count += c;
1517                 }
1518                 CC_UNLOCK(cc);
1519 #ifdef SMP
1520         }
1521 #endif
1522
1523         for (i = 0, tcum = 0; i < 64 && tcum < count / 2; i++)
1524                 tcum += ct[i];
1525         medt = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1526         for (i = 0, pcum = 0; i < 64 && pcum < count / 2; i++)
1527                 pcum += cpr[i];
1528         medpr = (i >= 2) ? (((sbintime_t)1) << (i - 2)) : 0;
1529         for (i = 0, c = 0; i < 32 && c < count / 2; i++)
1530                 c += ccpbk[i];
1531         medc = (i >= 2) ? (1 << (i - 2)) : 0;
1532
1533         printf("Scheduled callouts statistic snapshot:\n");
1534         printf("  Callouts: %6d  Buckets: %6d*%-3d  Bucket size: 0.%06ds\n",
1535             count, callwheelsize, mp_ncpus, 1000000 >> CC_HASH_SHIFT);
1536         printf("  C/Bk: med %5d         avg %6d.%06jd  max %6d\n",
1537             medc,
1538             count / callwheelsize / mp_ncpus,
1539             (uint64_t)count * 1000000 / callwheelsize / mp_ncpus % 1000000,
1540             maxc);
1541         printf("  Time: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1542             medt / SBT_1S, (medt & 0xffffffff) * 1000000 >> 32,
1543             (st / count) / 1000000, (st / count) % 1000000,
1544             maxt / SBT_1S, (maxt & 0xffffffff) * 1000000 >> 32);
1545         printf("  Prec: med %5jd.%06jds avg %6jd.%06jds max %6jd.%06jds\n",
1546             medpr / SBT_1S, (medpr & 0xffffffff) * 1000000 >> 32,
1547             (spr / count) / 1000000, (spr / count) % 1000000,
1548             maxpr / SBT_1S, (maxpr & 0xffffffff) * 1000000 >> 32);
1549         printf("  Distribution:       \tbuckets\t   time\t   tcum\t"
1550             "   prec\t   pcum\n");
1551         for (i = 0, tcum = pcum = 0; i < 64; i++) {
1552                 if (ct[i] == 0 && cpr[i] == 0)
1553                         continue;
1554                 t = (i != 0) ? (((sbintime_t)1) << (i - 1)) : 0;
1555                 tcum += ct[i];
1556                 pcum += cpr[i];
1557                 printf("  %10jd.%06jds\t 2**%d\t%7d\t%7d\t%7d\t%7d\n",
1558                     t / SBT_1S, (t & 0xffffffff) * 1000000 >> 32,
1559                     i - 1 - (32 - CC_HASH_SHIFT),
1560                     ct[i], tcum, cpr[i], pcum);
1561         }
1562         return (error);
1563 }
1564 SYSCTL_PROC(_kern, OID_AUTO, callout_stat,
1565     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1566     0, 0, sysctl_kern_callout_stat, "I",
1567     "Dump immediate statistic snapshot of the scheduled callouts");