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