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