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