2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2010-2013 Alexander Motin <mav@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer,
12 * without modification, immediately at the beginning of the file.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
33 * Common routines to manage event timers hardware.
36 #include "opt_device_polling.h"
38 #include <sys/param.h>
39 #include <sys/systm.h>
41 #include <sys/limits.h>
45 #include <sys/mutex.h>
47 #include <sys/kernel.h>
48 #include <sys/sched.h>
50 #include <sys/sysctl.h>
51 #include <sys/timeet.h>
52 #include <sys/timetc.h>
54 #include <machine/atomic.h>
55 #include <machine/clock.h>
56 #include <machine/cpu.h>
57 #include <machine/smp.h>
59 int cpu_disable_c2_sleep = 0; /* Timer dies in C2. */
60 int cpu_disable_c3_sleep = 0; /* Timer dies in C3. */
62 static void setuptimer(void);
63 static void loadtimer(sbintime_t now, int first);
64 static int doconfigtimer(void);
65 static void configtimer(int start);
66 static int round_freq(struct eventtimer *et, int freq);
69 static sbintime_t getnextcpuevent(struct pcpu_state *state, int idle);
70 static sbintime_t getnextevent(struct pcpu_state *state);
71 static int handleevents(sbintime_t now, int fake);
73 static struct mtx et_hw_mtx;
75 #define ET_HW_LOCK(state) \
77 if (timer->et_flags & ET_FLAGS_PERCPU) \
78 mtx_lock_spin(&(state)->et_hw_mtx); \
80 mtx_lock_spin(&et_hw_mtx); \
83 #define ET_HW_UNLOCK(state) \
85 if (timer->et_flags & ET_FLAGS_PERCPU) \
86 mtx_unlock_spin(&(state)->et_hw_mtx); \
88 mtx_unlock_spin(&et_hw_mtx); \
91 static struct eventtimer *timer = NULL;
92 static sbintime_t timerperiod; /* Timer period for periodic mode. */
93 static sbintime_t statperiod; /* statclock() events period. */
94 static sbintime_t profperiod; /* profclock() events period. */
95 static sbintime_t nexttick; /* Next global timer tick time. */
96 static u_int busy = 1; /* Reconfiguration is in progress. */
97 static int profiling; /* Profiling events enabled. */
99 static char timername[32]; /* Wanted timer. */
100 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
102 static int singlemul; /* Multiplier for periodic mode. */
103 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RWTUN, &singlemul,
104 0, "Multiplier for periodic mode");
106 static u_int idletick; /* Run periodic events when idle. */
107 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RWTUN, &idletick,
108 0, "Run periodic events when idle");
110 static int periodic; /* Periodic or one-shot mode. */
111 static int want_periodic; /* What mode to prefer. */
112 TUNABLE_INT("kern.eventtimer.periodic", &want_periodic);
115 struct mtx et_hw_mtx; /* Per-CPU timer mutex. */
116 u_int action; /* Reconfiguration requests. */
117 u_int handle; /* Immediate handle resuests. */
118 sbintime_t now; /* Last tick time. */
119 sbintime_t nextevent; /* Next scheduled event on this CPU. */
120 sbintime_t nexttick; /* Next timer tick time. */
121 sbintime_t nexthard; /* Next hardclock() event. */
122 sbintime_t nextstat; /* Next statclock() event. */
123 sbintime_t nextprof; /* Next profclock() event. */
124 sbintime_t nextcall; /* Next callout event. */
125 sbintime_t nextcallopt; /* Next optional callout event. */
126 int ipi; /* This CPU needs IPI. */
127 int idle; /* This CPU is in idle mode. */
130 DPCPU_DEFINE_STATIC(struct pcpu_state, timerstate);
131 DPCPU_DEFINE(sbintime_t, hardclocktime);
134 * Timer broadcast IPI handler.
140 struct pcpu_state *state;
143 if (doconfigtimer() || busy)
144 return (FILTER_HANDLED);
145 state = DPCPU_PTR(timerstate);
147 CTR3(KTR_SPARE2, "ipi at %d: now %d.%08x",
148 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
149 done = handleevents(now, 0);
150 return (done ? FILTER_HANDLED : FILTER_STRAY);
154 * Handle all events for specified time on this CPU
157 handleevents(sbintime_t now, int fake)
160 struct trapframe *frame;
161 struct pcpu_state *state;
165 CTR3(KTR_SPARE2, "handle at %d: now %d.%08x",
166 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
172 frame = curthread->td_intr_frame;
173 usermode = TRAPF_USERMODE(frame);
176 state = DPCPU_PTR(timerstate);
179 while (now >= state->nexthard) {
180 state->nexthard += tick_sbt;
184 hct = DPCPU_PTR(hardclocktime);
185 *hct = state->nexthard - tick_sbt;
187 hardclock(runs, usermode);
192 while (now >= state->nextstat) {
193 state->nextstat += statperiod;
196 if (runs && fake < 2) {
197 statclock(runs, usermode);
202 while (now >= state->nextprof) {
203 state->nextprof += profperiod;
207 profclock(runs, usermode, TRAPF_PC(frame));
211 state->nextprof = state->nextstat;
212 if (now >= state->nextcallopt || now >= state->nextcall) {
213 state->nextcall = state->nextcallopt = SBT_MAX;
214 callout_process(now);
218 t = getnextcpuevent(state, 0);
221 state->nextevent = t;
222 loadtimer(now, (fake == 2) &&
223 (timer->et_flags & ET_FLAGS_PERCPU));
230 * Schedule binuptime of the next event on current CPU.
233 getnextcpuevent(struct pcpu_state *state, int idle)
238 /* Handle hardclock() events, skipping some if CPU is idle. */
239 event = state->nexthard;
241 if (tc_min_ticktock_freq > 1
243 && curcpu == CPU_FIRST()
246 hardfreq = hz / tc_min_ticktock_freq;
250 event += tick_sbt * (hardfreq - 1);
252 /* Handle callout events. */
253 if (event > state->nextcall)
254 event = state->nextcall;
255 if (!idle) { /* If CPU is active - handle other types of events. */
256 if (event > state->nextstat)
257 event = state->nextstat;
258 if (profiling && event > state->nextprof)
259 event = state->nextprof;
265 * Schedule binuptime of the next event on all CPUs.
268 getnextevent(struct pcpu_state *state)
279 event = state->nextevent;
281 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
283 state = DPCPU_ID_PTR(cpu, timerstate);
284 if (event > state->nextevent) {
285 event = state->nextevent;
293 CTR4(KTR_SPARE2, "next at %d: next %d.%08x by %d",
294 curcpu, (int)(event >> 32), (u_int)(event & 0xffffffff), c);
298 /* Hardware timer callback function. */
300 timercb(struct eventtimer *et, void *arg)
304 struct pcpu_state *state;
309 /* Do not touch anything if somebody reconfiguring timers. */
312 /* Update present and next tick times. */
313 state = DPCPU_PTR(timerstate);
314 if (et->et_flags & ET_FLAGS_PERCPU) {
315 next = &state->nexttick;
320 *next = now + timerperiod;
322 *next = -1; /* Next tick is not scheduled yet. */
324 CTR3(KTR_SPARE2, "intr at %d: now %d.%08x",
325 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
328 #ifdef EARLY_AP_STARTUP
329 MPASS(mp_ncpus == 1 || smp_started);
331 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
333 #ifdef EARLY_AP_STARTUP
334 if ((et->et_flags & ET_FLAGS_PERCPU) == 0) {
336 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
339 state = DPCPU_ID_PTR(cpu, timerstate);
342 if (now >= state->nextevent) {
343 state->nextevent += SBT_1S;
354 /* Handle events for this time on this CPU. */
355 handleevents(now, 0);
358 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
363 state = DPCPU_ID_PTR(cpu, timerstate);
366 ipi_cpu(cpu, IPI_HARDCLOCK);
374 * Load new value into hardware timer.
377 loadtimer(sbintime_t now, int start)
379 struct pcpu_state *state;
385 state = DPCPU_PTR(timerstate);
386 if (timer->et_flags & ET_FLAGS_PERCPU)
387 next = &state->nexttick;
393 * Try to start all periodic timers aligned
394 * to period to make events synchronous.
396 tmp = now % timerperiod;
397 new = timerperiod - tmp;
398 if (new < tmp) /* Left less then passed. */
400 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
401 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
402 (int)(new >> 32), (u_int)(new & 0xffffffff));
404 et_start(timer, new, timerperiod);
407 new = getnextevent(state);
409 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
410 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
413 et_start(timer, new - now, 0);
419 * Prepare event timer parameters after configuration changes.
426 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
428 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
430 singlemul = MIN(MAX(singlemul, 1), 20);
431 freq = hz * singlemul;
432 while (freq < (profiling ? profhz : stathz))
434 freq = round_freq(timer, freq);
435 timerperiod = SBT_1S / freq;
439 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
445 struct pcpu_state *state;
447 state = DPCPU_PTR(timerstate);
448 switch (atomic_load_acq_int(&state->action)) {
455 atomic_store_rel_int(&state->action, 0);
462 atomic_store_rel_int(&state->action, 0);
465 if (atomic_readandclear_int(&state->handle) && !busy) {
467 handleevents(now, 0);
474 * Reconfigure specified timer.
475 * For per-CPU timers use IPI to make other CPUs to reconfigure.
478 configtimer(int start)
480 sbintime_t now, next;
481 struct pcpu_state *state;
490 ET_HW_LOCK(DPCPU_PTR(timerstate));
492 /* Initialize time machine parameters. */
493 next = now + timerperiod;
498 #ifdef EARLY_AP_STARTUP
499 MPASS(mp_ncpus == 1 || smp_started);
502 state = DPCPU_ID_PTR(cpu, timerstate);
504 #ifndef EARLY_AP_STARTUP
505 if (!smp_started && cpu != CPU_FIRST())
506 state->nextevent = SBT_MAX;
509 state->nextevent = next;
511 state->nexttick = next;
513 state->nexttick = -1;
514 state->nexthard = next;
515 state->nextstat = next;
516 state->nextprof = next;
517 state->nextcall = next;
518 state->nextcallopt = next;
522 /* Start global timer or per-CPU timer of this CPU. */
526 /* Stop global timer or per-CPU timer of this CPU. */
529 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
531 #ifdef EARLY_AP_STARTUP
532 /* If timer is global we are done. */
533 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
535 /* If timer is global or there is no other CPUs yet - we are done. */
536 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
541 /* Set reconfigure flags for other CPUs. */
543 state = DPCPU_ID_PTR(cpu, timerstate);
544 atomic_store_rel_int(&state->action,
545 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
547 /* Broadcast reconfigure IPI. */
548 ipi_all_but_self(IPI_HARDCLOCK);
549 /* Wait for reconfiguration completed. */
555 state = DPCPU_ID_PTR(cpu, timerstate);
556 if (atomic_load_acq_int(&state->action))
564 * Calculate nearest frequency supported by hardware timer.
567 round_freq(struct eventtimer *et, int freq)
571 if (et->et_frequency != 0) {
572 div = lmax((et->et_frequency + freq / 2) / freq, 1);
573 if (et->et_flags & ET_FLAGS_POW2DIV)
574 div = 1 << (flsl(div + div / 2) - 1);
575 freq = (et->et_frequency + div / 2) / div;
577 if (et->et_min_period > SBT_1S)
578 panic("Event timer \"%s\" doesn't support sub-second periods!",
580 else if (et->et_min_period != 0)
581 freq = min(freq, SBT2FREQ(et->et_min_period));
582 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
583 freq = max(freq, SBT2FREQ(et->et_max_period));
588 * Configure and start event timers (BSP part).
591 cpu_initclocks_bsp(void)
593 struct pcpu_state *state;
596 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
598 state = DPCPU_ID_PTR(cpu, timerstate);
599 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
600 state->nextcall = SBT_MAX;
601 state->nextcallopt = SBT_MAX;
603 periodic = want_periodic;
604 /* Grab requested timer or the best of present. */
606 timer = et_find(timername, 0, 0);
607 if (timer == NULL && periodic) {
608 timer = et_find(NULL,
609 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
612 timer = et_find(NULL,
613 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
615 if (timer == NULL && !periodic) {
616 timer = et_find(NULL,
617 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
620 panic("No usable event timer found!");
621 et_init(timer, timercb, NULL, NULL);
623 /* Adapt to timer capabilities. */
624 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
626 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
628 if (timer->et_flags & ET_FLAGS_C3STOP)
629 cpu_disable_c3_sleep++;
632 * We honor the requested 'hz' value.
633 * We want to run stathz in the neighborhood of 128hz.
634 * We would like profhz to run as often as possible.
636 if (singlemul <= 0 || singlemul > 20) {
637 if (hz >= 1500 || (hz % 128) == 0)
645 base = round_freq(timer, hz * singlemul);
646 singlemul = max((base + hz / 2) / hz, 1);
647 hz = (base + singlemul / 2) / singlemul;
652 if (div >= singlemul && (div % singlemul) == 0)
657 while ((profhz + stathz) <= 128 * 64)
659 profhz = round_freq(timer, profhz);
661 hz = round_freq(timer, hz);
662 stathz = round_freq(timer, 127);
663 profhz = round_freq(timer, stathz * 64);
666 tick_sbt = SBT_1S / hz;
667 tick_bt = sbttobt(tick_sbt);
668 statperiod = SBT_1S / stathz;
669 profperiod = SBT_1S / profhz;
676 * Start per-CPU event timers on APs.
679 cpu_initclocks_ap(void)
681 struct pcpu_state *state;
684 state = DPCPU_PTR(timerstate);
686 state->now = sbinuptime();
687 hardclock_sync(curcpu);
691 td->td_intr_nesting_level++;
692 handleevents(state->now, 2);
693 td->td_intr_nesting_level--;
714 * Switch to profiling clock rates.
717 cpu_startprofclock(void)
721 if (profiling == 0) {
734 * Switch to regular clock rates.
737 cpu_stopprofclock(void)
741 if (profiling == 1) {
754 * Switch to idle mode (all ticks handled).
760 struct pcpu_state *state;
762 if (idletick || busy ||
763 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
764 #ifdef DEVICE_POLLING
765 || curcpu == CPU_FIRST()
769 state = DPCPU_PTR(timerstate);
775 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
776 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
777 t = getnextcpuevent(state, 1);
779 state->nextevent = t;
783 return (MAX(t - now, 0));
787 * Switch to active mode (skip empty ticks).
790 cpu_activeclock(void)
793 struct pcpu_state *state;
796 state = DPCPU_PTR(timerstate);
797 if (atomic_load_int(&state->idle) == 0 || busy)
804 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
805 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
807 td->td_intr_nesting_level++;
808 handleevents(now, 1);
809 td->td_intr_nesting_level--;
814 * Change the frequency of the given timer. This changes et->et_frequency and
815 * if et is the active timer it reconfigures the timer on all CPUs. This is
816 * intended to be a private interface for the use of et_change_frequency() only.
819 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
825 et->et_frequency = newfreq;
828 et->et_frequency = newfreq;
833 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
835 struct pcpu_state *state;
837 /* Do not touch anything if somebody reconfiguring timers. */
840 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
841 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
842 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
844 KASSERT(!CPU_ABSENT(cpu), ("Absent CPU %d", cpu));
845 state = DPCPU_ID_PTR(cpu, timerstate);
849 * If there is callout time already set earlier -- do nothing.
850 * This check may appear redundant because we check already in
851 * callout_process() but this double check guarantees we're safe
852 * with respect to race conditions between interrupts execution
855 state->nextcallopt = bt_opt;
856 if (bt >= state->nextcall)
858 state->nextcall = bt;
859 /* If there is some other event set earlier -- do nothing. */
860 if (bt >= state->nextevent)
862 state->nextevent = bt;
863 /* If timer is periodic -- there is nothing to reprogram. */
866 /* If timer is global or of the current CPU -- reprogram it. */
867 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
868 loadtimer(sbinuptime(), 0);
873 /* Otherwise make other CPU to reprogram it. */
877 ipi_cpu(cpu, IPI_HARDCLOCK);
882 * Report or change the active event timers hardware.
885 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
888 struct eventtimer *et;
893 snprintf(buf, sizeof(buf), "%s", et->et_name);
895 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
898 if (error != 0 || req->newptr == NULL ||
899 strcasecmp(buf, et->et_name) == 0) {
903 et = et_find(buf, 0, 0);
910 if (et->et_flags & ET_FLAGS_C3STOP)
911 cpu_disable_c3_sleep++;
912 if (timer->et_flags & ET_FLAGS_C3STOP)
913 cpu_disable_c3_sleep--;
914 periodic = want_periodic;
916 et_init(timer, timercb, NULL, NULL);
921 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
922 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
923 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
926 * Report or change the active event timer periodicity.
929 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
934 error = sysctl_handle_int(oidp, &val, 0, req);
935 if (error != 0 || req->newptr == NULL)
939 periodic = want_periodic = val;
944 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
945 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
946 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");
953 DB_SHOW_COMMAND(clocksource, db_show_clocksource)
955 struct pcpu_state *st;
959 st = DPCPU_ID_PTR(c, timerstate);
961 "CPU %2d: action %d handle %d ipi %d idle %d\n"
962 " now %#jx nevent %#jx (%jd)\n"
963 " ntick %#jx (%jd) nhard %#jx (%jd)\n"
964 " nstat %#jx (%jd) nprof %#jx (%jd)\n"
965 " ncall %#jx (%jd) ncallopt %#jx (%jd)\n",
966 c, st->action, st->handle, st->ipi, st->idle,
968 (uintmax_t)st->nextevent,
969 (uintmax_t)(st->nextevent - st->now) / tick_sbt,
970 (uintmax_t)st->nexttick,
971 (uintmax_t)(st->nexttick - st->now) / tick_sbt,
972 (uintmax_t)st->nexthard,
973 (uintmax_t)(st->nexthard - st->now) / tick_sbt,
974 (uintmax_t)st->nextstat,
975 (uintmax_t)(st->nextstat - st->now) / tick_sbt,
976 (uintmax_t)st->nextprof,
977 (uintmax_t)(st->nextprof - st->now) / tick_sbt,
978 (uintmax_t)st->nextcall,
979 (uintmax_t)(st->nextcall - st->now) / tick_sbt,
980 (uintmax_t)st->nextcallopt,
981 (uintmax_t)(st->nextcallopt - st->now) / tick_sbt);