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