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