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