2 * Copyright (c) 2010-2013 Alexander Motin <mav@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer,
10 * without modification, immediately at the beginning of the file.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
31 * Common routines to manage event timers hardware.
34 #include "opt_device_polling.h"
35 #include "opt_kdtrace.h"
37 #include <sys/param.h>
38 #include <sys/systm.h>
40 #include <sys/limits.h>
44 #include <sys/mutex.h>
46 #include <sys/kernel.h>
47 #include <sys/sched.h>
49 #include <sys/sysctl.h>
50 #include <sys/timeet.h>
51 #include <sys/timetc.h>
53 #include <machine/atomic.h>
54 #include <machine/clock.h>
55 #include <machine/cpu.h>
56 #include <machine/smp.h>
58 int cpu_deepest_sleep = 0; /* Deepest Cx state available. */
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);
68 static sbintime_t getnextcpuevent(int idle);
69 static sbintime_t getnextevent(void);
70 static int handleevents(sbintime_t now, int fake);
72 static struct mtx et_hw_mtx;
74 #define ET_HW_LOCK(state) \
76 if (timer->et_flags & ET_FLAGS_PERCPU) \
77 mtx_lock_spin(&(state)->et_hw_mtx); \
79 mtx_lock_spin(&et_hw_mtx); \
82 #define ET_HW_UNLOCK(state) \
84 if (timer->et_flags & ET_FLAGS_PERCPU) \
85 mtx_unlock_spin(&(state)->et_hw_mtx); \
87 mtx_unlock_spin(&et_hw_mtx); \
90 static struct eventtimer *timer = NULL;
91 static sbintime_t timerperiod; /* Timer period for periodic mode. */
92 static sbintime_t statperiod; /* statclock() events period. */
93 static sbintime_t profperiod; /* profclock() events period. */
94 static sbintime_t nexttick; /* Next global timer tick time. */
95 static u_int busy = 1; /* Reconfiguration is in progress. */
96 static int profiling = 0; /* Profiling events enabled. */
98 static char timername[32]; /* Wanted timer. */
99 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
101 static int singlemul = 0; /* Multiplier for periodic mode. */
102 TUNABLE_INT("kern.eventtimer.singlemul", &singlemul);
103 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RW, &singlemul,
104 0, "Multiplier for periodic mode");
106 static u_int idletick = 0; /* Run periodic events when idle. */
107 TUNABLE_INT("kern.eventtimer.idletick", &idletick);
108 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RW, &idletick,
109 0, "Run periodic events when idle");
111 static int periodic = 0; /* Periodic or one-shot mode. */
112 static int want_periodic = 0; /* What mode to prefer. */
113 TUNABLE_INT("kern.eventtimer.periodic", &want_periodic);
116 struct mtx et_hw_mtx; /* Per-CPU timer mutex. */
117 u_int action; /* Reconfiguration requests. */
118 u_int handle; /* Immediate handle resuests. */
119 sbintime_t now; /* Last tick time. */
120 sbintime_t nextevent; /* Next scheduled event on this CPU. */
121 sbintime_t nexttick; /* Next timer tick time. */
122 sbintime_t nexthard; /* Next hardlock() event. */
123 sbintime_t nextstat; /* Next statclock() event. */
124 sbintime_t nextprof; /* Next profclock() event. */
125 sbintime_t nextcall; /* Next callout event. */
126 sbintime_t nextcallopt; /* Next optional callout event. */
127 int ipi; /* This CPU needs IPI. */
128 int idle; /* This CPU is in idle mode. */
131 static DPCPU_DEFINE(struct pcpu_state, timerstate);
132 DPCPU_DEFINE(sbintime_t, hardclocktime);
135 * Timer broadcast IPI handler.
141 struct pcpu_state *state;
144 if (doconfigtimer() || busy)
145 return (FILTER_HANDLED);
146 state = DPCPU_PTR(timerstate);
148 CTR3(KTR_SPARE2, "ipi at %d: now %d.%08x",
149 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
150 done = handleevents(now, 0);
151 return (done ? FILTER_HANDLED : FILTER_STRAY);
155 * Handle all events for specified time on this CPU
158 handleevents(sbintime_t now, int fake)
161 struct trapframe *frame;
162 struct pcpu_state *state;
166 CTR3(KTR_SPARE2, "handle at %d: now %d.%08x",
167 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
173 frame = curthread->td_intr_frame;
174 usermode = TRAPF_USERMODE(frame);
177 state = DPCPU_PTR(timerstate);
180 while (now >= state->nexthard) {
181 state->nexthard += tick_sbt;
185 hct = DPCPU_PTR(hardclocktime);
186 *hct = state->nexthard - tick_sbt;
188 hardclock_cnt(runs, usermode);
193 while (now >= state->nextstat) {
194 state->nextstat += statperiod;
197 if (runs && fake < 2) {
198 statclock_cnt(runs, usermode);
203 while (now >= state->nextprof) {
204 state->nextprof += profperiod;
208 profclock_cnt(runs, usermode, TRAPF_PC(frame));
212 state->nextprof = state->nextstat;
213 if (now >= state->nextcallopt || now >= state->nextcall) {
214 state->nextcall = state->nextcallopt = SBT_MAX;
215 callout_process(now);
218 t = getnextcpuevent(0);
222 state->nextevent = t;
223 loadtimer(now, (fake == 2) &&
224 (timer->et_flags & ET_FLAGS_PERCPU));
231 * Schedule binuptime of the next event on current CPU.
234 getnextcpuevent(int idle)
237 struct pcpu_state *state;
240 state = DPCPU_PTR(timerstate);
241 /* Handle hardclock() events, skipping some if CPU is idle. */
242 event = state->nexthard;
244 hardfreq = (u_int)hz / 2;
245 if (tc_min_ticktock_freq > 2
247 && curcpu == CPU_FIRST()
250 hardfreq = hz / tc_min_ticktock_freq;
252 event += tick_sbt * (hardfreq - 1);
254 /* Handle callout events. */
255 if (event > state->nextcall)
256 event = state->nextcall;
257 if (!idle) { /* If CPU is active - handle other types of events. */
258 if (event > state->nextstat)
259 event = state->nextstat;
260 if (profiling && event > state->nextprof)
261 event = state->nextprof;
267 * Schedule binuptime of the next event on all CPUs.
272 struct pcpu_state *state;
279 state = DPCPU_PTR(timerstate);
280 event = state->nextevent;
283 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
285 state = DPCPU_ID_PTR(cpu, timerstate);
286 if (event > state->nextevent) {
287 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 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
330 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
332 state = DPCPU_ID_PTR(cpu, timerstate);
335 if (now >= state->nextevent) {
336 state->nextevent += SBT_1S;
347 /* Handle events for this time on this CPU. */
348 handleevents(now, 0);
351 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
356 state = DPCPU_ID_PTR(cpu, timerstate);
359 ipi_cpu(cpu, IPI_HARDCLOCK);
367 * Load new value into hardware timer.
370 loadtimer(sbintime_t now, int start)
372 struct pcpu_state *state;
378 if (timer->et_flags & ET_FLAGS_PERCPU) {
379 state = DPCPU_PTR(timerstate);
380 next = &state->nexttick;
386 * Try to start all periodic timers aligned
387 * to period to make events synchronous.
389 tmp = now % timerperiod;
390 new = timerperiod - tmp;
391 if (new < tmp) /* Left less then passed. */
393 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
394 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
395 (int)(new >> 32), (u_int)(new & 0xffffffff));
397 et_start(timer, new, timerperiod);
400 new = getnextevent();
402 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
403 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
406 et_start(timer, new - now, 0);
412 * Prepare event timer parameters after configuration changes.
419 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
421 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
423 singlemul = MIN(MAX(singlemul, 1), 20);
424 freq = hz * singlemul;
425 while (freq < (profiling ? profhz : stathz))
427 freq = round_freq(timer, freq);
428 timerperiod = SBT_1S / freq;
432 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
438 struct pcpu_state *state;
440 state = DPCPU_PTR(timerstate);
441 switch (atomic_load_acq_int(&state->action)) {
448 atomic_store_rel_int(&state->action, 0);
455 atomic_store_rel_int(&state->action, 0);
458 if (atomic_readandclear_int(&state->handle) && !busy) {
460 handleevents(now, 0);
467 * Reconfigure specified timer.
468 * For per-CPU timers use IPI to make other CPUs to reconfigure.
471 configtimer(int start)
473 sbintime_t now, next;
474 struct pcpu_state *state;
483 ET_HW_LOCK(DPCPU_PTR(timerstate));
485 /* Initialize time machine parameters. */
486 next = now + timerperiod;
492 state = DPCPU_ID_PTR(cpu, timerstate);
494 if (!smp_started && cpu != CPU_FIRST())
495 state->nextevent = SBT_MAX;
497 state->nextevent = next;
499 state->nexttick = next;
501 state->nexttick = -1;
502 state->nexthard = next;
503 state->nextstat = next;
504 state->nextprof = next;
505 state->nextcall = next;
506 state->nextcallopt = next;
510 /* Start global timer or per-CPU timer of this CPU. */
514 /* Stop global timer or per-CPU timer of this CPU. */
517 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
519 /* If timer is global or there is no other CPUs yet - we are done. */
520 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
524 /* Set reconfigure flags for other CPUs. */
526 state = DPCPU_ID_PTR(cpu, timerstate);
527 atomic_store_rel_int(&state->action,
528 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
530 /* Broadcast reconfigure IPI. */
531 ipi_all_but_self(IPI_HARDCLOCK);
532 /* Wait for reconfiguration completed. */
538 state = DPCPU_ID_PTR(cpu, timerstate);
539 if (atomic_load_acq_int(&state->action))
547 * Calculate nearest frequency supported by hardware timer.
550 round_freq(struct eventtimer *et, int freq)
554 if (et->et_frequency != 0) {
555 div = lmax((et->et_frequency + freq / 2) / freq, 1);
556 if (et->et_flags & ET_FLAGS_POW2DIV)
557 div = 1 << (flsl(div + div / 2) - 1);
558 freq = (et->et_frequency + div / 2) / div;
560 if (et->et_min_period > SBT_1S)
561 panic("Event timer \"%s\" doesn't support sub-second periods!",
563 else if (et->et_min_period != 0)
564 freq = min(freq, SBT2FREQ(et->et_min_period));
565 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
566 freq = max(freq, SBT2FREQ(et->et_max_period));
571 * Configure and start event timers (BSP part).
574 cpu_initclocks_bsp(void)
576 struct pcpu_state *state;
579 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
581 state = DPCPU_ID_PTR(cpu, timerstate);
582 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
583 state->nextcall = SBT_MAX;
584 state->nextcallopt = SBT_MAX;
586 periodic = want_periodic;
587 /* Grab requested timer or the best of present. */
589 timer = et_find(timername, 0, 0);
590 if (timer == NULL && periodic) {
591 timer = et_find(NULL,
592 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
595 timer = et_find(NULL,
596 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
598 if (timer == NULL && !periodic) {
599 timer = et_find(NULL,
600 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
603 panic("No usable event timer found!");
604 et_init(timer, timercb, NULL, NULL);
606 /* Adapt to timer capabilities. */
607 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
609 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
611 if (timer->et_flags & ET_FLAGS_C3STOP)
612 cpu_disable_c3_sleep++;
615 * We honor the requested 'hz' value.
616 * We want to run stathz in the neighborhood of 128hz.
617 * We would like profhz to run as often as possible.
619 if (singlemul <= 0 || singlemul > 20) {
620 if (hz >= 1500 || (hz % 128) == 0)
628 base = round_freq(timer, hz * singlemul);
629 singlemul = max((base + hz / 2) / hz, 1);
630 hz = (base + singlemul / 2) / singlemul;
635 if (div >= singlemul && (div % singlemul) == 0)
640 while ((profhz + stathz) <= 128 * 64)
642 profhz = round_freq(timer, profhz);
644 hz = round_freq(timer, hz);
645 stathz = round_freq(timer, 127);
646 profhz = round_freq(timer, stathz * 64);
649 tick_sbt = SBT_1S / hz;
650 tick_bt = sbttobt(tick_sbt);
651 statperiod = SBT_1S / stathz;
652 profperiod = SBT_1S / profhz;
659 * Start per-CPU event timers on APs.
662 cpu_initclocks_ap(void)
665 struct pcpu_state *state;
668 state = DPCPU_PTR(timerstate);
672 hardclock_sync(curcpu);
676 td->td_intr_nesting_level++;
677 handleevents(state->now, 2);
678 td->td_intr_nesting_level--;
683 * Switch to profiling clock rates.
686 cpu_startprofclock(void)
690 if (profiling == 0) {
703 * Switch to regular clock rates.
706 cpu_stopprofclock(void)
710 if (profiling == 1) {
723 * Switch to idle mode (all ticks handled).
729 struct pcpu_state *state;
731 if (idletick || busy ||
732 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
733 #ifdef DEVICE_POLLING
734 || curcpu == CPU_FIRST()
738 state = DPCPU_PTR(timerstate);
743 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
744 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
745 t = getnextcpuevent(1);
748 state->nextevent = t;
752 return (MAX(t - now, 0));
756 * Switch to active mode (skip empty ticks).
759 cpu_activeclock(void)
762 struct pcpu_state *state;
765 state = DPCPU_PTR(timerstate);
766 if (state->idle == 0 || busy)
772 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
773 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
776 td->td_intr_nesting_level++;
777 handleevents(now, 1);
778 td->td_intr_nesting_level--;
783 * Change the frequency of the given timer. This changes et->et_frequency and
784 * if et is the active timer it reconfigures the timer on all CPUs. This is
785 * intended to be a private interface for the use of et_change_frequency() only.
788 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
794 et->et_frequency = newfreq;
797 et->et_frequency = newfreq;
802 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
804 struct pcpu_state *state;
806 /* Do not touch anything if somebody reconfiguring timers. */
809 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
810 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
811 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
812 state = DPCPU_ID_PTR(cpu, timerstate);
816 * If there is callout time already set earlier -- do nothing.
817 * This check may appear redundant because we check already in
818 * callout_process() but this double check guarantees we're safe
819 * with respect to race conditions between interrupts execution
822 state->nextcallopt = bt_opt;
823 if (bt >= state->nextcall)
825 state->nextcall = bt;
826 /* If there is some other event set earlier -- do nothing. */
827 if (bt >= state->nextevent)
829 state->nextevent = bt;
830 /* If timer is periodic -- there is nothing to reprogram. */
833 /* If timer is global or of the current CPU -- reprogram it. */
834 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
835 loadtimer(sbinuptime(), 0);
840 /* Otherwise make other CPU to reprogram it. */
844 ipi_cpu(cpu, IPI_HARDCLOCK);
849 * Report or change the active event timers hardware.
852 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
855 struct eventtimer *et;
860 snprintf(buf, sizeof(buf), "%s", et->et_name);
862 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
865 if (error != 0 || req->newptr == NULL ||
866 strcasecmp(buf, et->et_name) == 0) {
870 et = et_find(buf, 0, 0);
877 if (et->et_flags & ET_FLAGS_C3STOP)
878 cpu_disable_c3_sleep++;
879 if (timer->et_flags & ET_FLAGS_C3STOP)
880 cpu_disable_c3_sleep--;
881 periodic = want_periodic;
883 et_init(timer, timercb, NULL, NULL);
888 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
889 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
890 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
893 * Report or change the active event timer periodicity.
896 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
901 error = sysctl_handle_int(oidp, &val, 0, req);
902 if (error != 0 || req->newptr == NULL)
906 periodic = want_periodic = val;
911 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
912 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
913 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");
920 DB_SHOW_COMMAND(clocksource, db_show_clocksource)
922 struct pcpu_state *st;
926 st = DPCPU_ID_PTR(c, timerstate);
928 "CPU %2d: action %d handle %d ipi %d idle %d\n"
929 " now %#jx nevent %#jx (%jd)\n"
930 " ntick %#jx (%jd) nhard %#jx (%jd)\n"
931 " nstat %#jx (%jd) nprof %#jx (%jd)\n"
932 " ncall %#jx (%jd) ncallopt %#jx (%jd)\n",
933 c, st->action, st->handle, st->ipi, st->idle,
935 (uintmax_t)st->nextevent,
936 (uintmax_t)(st->nextevent - st->now) / tick_sbt,
937 (uintmax_t)st->nexttick,
938 (uintmax_t)(st->nexttick - st->now) / tick_sbt,
939 (uintmax_t)st->nexthard,
940 (uintmax_t)(st->nexthard - st->now) / tick_sbt,
941 (uintmax_t)st->nextstat,
942 (uintmax_t)(st->nextstat - st->now) / tick_sbt,
943 (uintmax_t)st->nextprof,
944 (uintmax_t)(st->nextprof - st->now) / tick_sbt,
945 (uintmax_t)st->nextcall,
946 (uintmax_t)(st->nextcall - st->now) / tick_sbt,
947 (uintmax_t)st->nextcallopt,
948 (uintmax_t)(st->nextcallopt - st->now) / tick_sbt);