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