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"
36 #include <sys/param.h>
37 #include <sys/systm.h>
39 #include <sys/limits.h>
43 #include <sys/mutex.h>
45 #include <sys/kernel.h>
46 #include <sys/sched.h>
48 #include <sys/sysctl.h>
49 #include <sys/timeet.h>
50 #include <sys/timetc.h>
52 #include <machine/atomic.h>
53 #include <machine/clock.h>
54 #include <machine/cpu.h>
55 #include <machine/smp.h>
57 int cpu_deepest_sleep = 0; /* Deepest Cx state available. */
58 int cpu_disable_c2_sleep = 0; /* Timer dies in C2. */
59 int cpu_disable_c3_sleep = 0; /* Timer dies in C3. */
61 static void setuptimer(void);
62 static void loadtimer(sbintime_t now, int first);
63 static int doconfigtimer(void);
64 static void configtimer(int start);
65 static int round_freq(struct eventtimer *et, int freq);
67 static sbintime_t getnextcpuevent(int idle);
68 static sbintime_t getnextevent(void);
69 static int handleevents(sbintime_t now, int fake);
71 static struct mtx et_hw_mtx;
73 #define ET_HW_LOCK(state) \
75 if (timer->et_flags & ET_FLAGS_PERCPU) \
76 mtx_lock_spin(&(state)->et_hw_mtx); \
78 mtx_lock_spin(&et_hw_mtx); \
81 #define ET_HW_UNLOCK(state) \
83 if (timer->et_flags & ET_FLAGS_PERCPU) \
84 mtx_unlock_spin(&(state)->et_hw_mtx); \
86 mtx_unlock_spin(&et_hw_mtx); \
89 static struct eventtimer *timer = NULL;
90 static sbintime_t timerperiod; /* Timer period for periodic mode. */
91 static sbintime_t statperiod; /* statclock() events period. */
92 static sbintime_t profperiod; /* profclock() events period. */
93 static sbintime_t nexttick; /* Next global timer tick time. */
94 static u_int busy = 1; /* Reconfiguration is in progress. */
95 static int profiling; /* Profiling events enabled. */
97 static char timername[32]; /* Wanted timer. */
98 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
100 static int singlemul; /* Multiplier for periodic mode. */
101 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RWTUN, &singlemul,
102 0, "Multiplier for periodic mode");
104 static u_int idletick; /* Run periodic events when idle. */
105 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RWTUN, &idletick,
106 0, "Run periodic events when idle");
108 static int periodic; /* Periodic or one-shot mode. */
109 static int want_periodic; /* What mode to prefer. */
110 TUNABLE_INT("kern.eventtimer.periodic", &want_periodic);
113 struct mtx et_hw_mtx; /* Per-CPU timer mutex. */
114 u_int action; /* Reconfiguration requests. */
115 u_int handle; /* Immediate handle resuests. */
116 sbintime_t now; /* Last tick time. */
117 sbintime_t nextevent; /* Next scheduled event on this CPU. */
118 sbintime_t nexttick; /* Next timer tick time. */
119 sbintime_t nexthard; /* Next hardlock() event. */
120 sbintime_t nextstat; /* Next statclock() event. */
121 sbintime_t nextprof; /* Next profclock() event. */
122 sbintime_t nextcall; /* Next callout event. */
123 sbintime_t nextcallopt; /* Next optional callout event. */
124 int ipi; /* This CPU needs IPI. */
125 int idle; /* This CPU is in idle mode. */
128 static DPCPU_DEFINE(struct pcpu_state, timerstate);
129 DPCPU_DEFINE(sbintime_t, hardclocktime);
132 * Timer broadcast IPI handler.
138 struct pcpu_state *state;
141 if (doconfigtimer() || busy)
142 return (FILTER_HANDLED);
143 state = DPCPU_PTR(timerstate);
145 CTR3(KTR_SPARE2, "ipi at %d: now %d.%08x",
146 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
147 done = handleevents(now, 0);
148 return (done ? FILTER_HANDLED : FILTER_STRAY);
152 * Handle all events for specified time on this CPU
155 handleevents(sbintime_t now, int fake)
158 struct trapframe *frame;
159 struct pcpu_state *state;
163 CTR3(KTR_SPARE2, "handle at %d: now %d.%08x",
164 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
170 frame = curthread->td_intr_frame;
171 usermode = TRAPF_USERMODE(frame);
174 state = DPCPU_PTR(timerstate);
177 while (now >= state->nexthard) {
178 state->nexthard += tick_sbt;
182 hct = DPCPU_PTR(hardclocktime);
183 *hct = state->nexthard - tick_sbt;
185 hardclock_cnt(runs, usermode);
190 while (now >= state->nextstat) {
191 state->nextstat += statperiod;
194 if (runs && fake < 2) {
195 statclock_cnt(runs, usermode);
200 while (now >= state->nextprof) {
201 state->nextprof += profperiod;
205 profclock_cnt(runs, usermode, TRAPF_PC(frame));
209 state->nextprof = state->nextstat;
210 if (now >= state->nextcallopt) {
211 state->nextcall = state->nextcallopt = SBT_MAX;
212 callout_process(now);
215 t = getnextcpuevent(0);
219 state->nextevent = t;
220 loadtimer(now, (fake == 2) &&
221 (timer->et_flags & ET_FLAGS_PERCPU));
228 * Schedule binuptime of the next event on current CPU.
231 getnextcpuevent(int idle)
234 struct pcpu_state *state;
237 state = DPCPU_PTR(timerstate);
238 /* Handle hardclock() events, skipping some if CPU is idle. */
239 event = state->nexthard;
241 hardfreq = (u_int)hz / 2;
242 if (tc_min_ticktock_freq > 2
244 && curcpu == CPU_FIRST()
247 hardfreq = hz / tc_min_ticktock_freq;
249 event += tick_sbt * (hardfreq - 1);
251 /* Handle callout events. */
252 if (event > state->nextcall)
253 event = state->nextcall;
254 if (!idle) { /* If CPU is active - handle other types of events. */
255 if (event > state->nextstat)
256 event = state->nextstat;
257 if (profiling && event > state->nextprof)
258 event = state->nextprof;
264 * Schedule binuptime of the next event on all CPUs.
269 struct pcpu_state *state;
276 state = DPCPU_PTR(timerstate);
277 event = state->nextevent;
280 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
282 state = DPCPU_ID_PTR(cpu, timerstate);
283 if (event > state->nextevent) {
284 event = state->nextevent;
290 CTR4(KTR_SPARE2, "next at %d: next %d.%08x by %d",
291 curcpu, (int)(event >> 32), (u_int)(event & 0xffffffff), c);
295 /* Hardware timer callback function. */
297 timercb(struct eventtimer *et, void *arg)
301 struct pcpu_state *state;
306 /* Do not touch anything if somebody reconfiguring timers. */
309 /* Update present and next tick times. */
310 state = DPCPU_PTR(timerstate);
311 if (et->et_flags & ET_FLAGS_PERCPU) {
312 next = &state->nexttick;
317 *next = now + timerperiod;
319 *next = -1; /* Next tick is not scheduled yet. */
321 CTR3(KTR_SPARE2, "intr at %d: now %d.%08x",
322 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
325 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
327 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
329 state = DPCPU_ID_PTR(cpu, timerstate);
332 if (now >= state->nextevent) {
333 state->nextevent += SBT_1S;
344 /* Handle events for this time on this CPU. */
345 handleevents(now, 0);
348 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
353 state = DPCPU_ID_PTR(cpu, timerstate);
356 ipi_cpu(cpu, IPI_HARDCLOCK);
364 * Load new value into hardware timer.
367 loadtimer(sbintime_t now, int start)
369 struct pcpu_state *state;
375 if (timer->et_flags & ET_FLAGS_PERCPU) {
376 state = DPCPU_PTR(timerstate);
377 next = &state->nexttick;
383 * Try to start all periodic timers aligned
384 * to period to make events synchronous.
386 tmp = now % timerperiod;
387 new = timerperiod - tmp;
388 if (new < tmp) /* Left less then passed. */
390 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
391 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
392 (int)(new >> 32), (u_int)(new & 0xffffffff));
394 et_start(timer, new, timerperiod);
397 new = getnextevent();
399 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
400 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
403 et_start(timer, new - now, 0);
409 * Prepare event timer parameters after configuration changes.
416 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
418 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
420 singlemul = MIN(MAX(singlemul, 1), 20);
421 freq = hz * singlemul;
422 while (freq < (profiling ? profhz : stathz))
424 freq = round_freq(timer, freq);
425 timerperiod = SBT_1S / freq;
429 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
435 struct pcpu_state *state;
437 state = DPCPU_PTR(timerstate);
438 switch (atomic_load_acq_int(&state->action)) {
445 atomic_store_rel_int(&state->action, 0);
452 atomic_store_rel_int(&state->action, 0);
455 if (atomic_readandclear_int(&state->handle) && !busy) {
457 handleevents(now, 0);
464 * Reconfigure specified timer.
465 * For per-CPU timers use IPI to make other CPUs to reconfigure.
468 configtimer(int start)
470 sbintime_t now, next;
471 struct pcpu_state *state;
480 ET_HW_LOCK(DPCPU_PTR(timerstate));
482 /* Initialize time machine parameters. */
483 next = now + timerperiod;
489 state = DPCPU_ID_PTR(cpu, timerstate);
491 if (!smp_started && cpu != CPU_FIRST())
492 state->nextevent = SBT_MAX;
494 state->nextevent = next;
496 state->nexttick = next;
498 state->nexttick = -1;
499 state->nexthard = next;
500 state->nextstat = next;
501 state->nextprof = next;
502 state->nextcall = next;
503 state->nextcallopt = next;
507 /* Start global timer or per-CPU timer of this CPU. */
511 /* Stop global timer or per-CPU timer of this CPU. */
514 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
516 /* If timer is global or there is no other CPUs yet - we are done. */
517 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
521 /* Set reconfigure flags for other CPUs. */
523 state = DPCPU_ID_PTR(cpu, timerstate);
524 atomic_store_rel_int(&state->action,
525 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
527 /* Broadcast reconfigure IPI. */
528 ipi_all_but_self(IPI_HARDCLOCK);
529 /* Wait for reconfiguration completed. */
535 state = DPCPU_ID_PTR(cpu, timerstate);
536 if (atomic_load_acq_int(&state->action))
544 * Calculate nearest frequency supported by hardware timer.
547 round_freq(struct eventtimer *et, int freq)
551 if (et->et_frequency != 0) {
552 div = lmax((et->et_frequency + freq / 2) / freq, 1);
553 if (et->et_flags & ET_FLAGS_POW2DIV)
554 div = 1 << (flsl(div + div / 2) - 1);
555 freq = (et->et_frequency + div / 2) / div;
557 if (et->et_min_period > SBT_1S)
558 panic("Event timer \"%s\" doesn't support sub-second periods!",
560 else if (et->et_min_period != 0)
561 freq = min(freq, SBT2FREQ(et->et_min_period));
562 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
563 freq = max(freq, SBT2FREQ(et->et_max_period));
568 * Configure and start event timers (BSP part).
571 cpu_initclocks_bsp(void)
573 struct pcpu_state *state;
576 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
578 state = DPCPU_ID_PTR(cpu, timerstate);
579 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
580 state->nextcall = SBT_MAX;
581 state->nextcallopt = SBT_MAX;
583 periodic = want_periodic;
584 /* Grab requested timer or the best of present. */
586 timer = et_find(timername, 0, 0);
587 if (timer == NULL && periodic) {
588 timer = et_find(NULL,
589 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
592 timer = et_find(NULL,
593 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
595 if (timer == NULL && !periodic) {
596 timer = et_find(NULL,
597 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
600 panic("No usable event timer found!");
601 et_init(timer, timercb, NULL, NULL);
603 /* Adapt to timer capabilities. */
604 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
606 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
608 if (timer->et_flags & ET_FLAGS_C3STOP)
609 cpu_disable_c3_sleep++;
612 * We honor the requested 'hz' value.
613 * We want to run stathz in the neighborhood of 128hz.
614 * We would like profhz to run as often as possible.
616 if (singlemul <= 0 || singlemul > 20) {
617 if (hz >= 1500 || (hz % 128) == 0)
625 base = round_freq(timer, hz * singlemul);
626 singlemul = max((base + hz / 2) / hz, 1);
627 hz = (base + singlemul / 2) / singlemul;
632 if (div >= singlemul && (div % singlemul) == 0)
637 while ((profhz + stathz) <= 128 * 64)
639 profhz = round_freq(timer, profhz);
641 hz = round_freq(timer, hz);
642 stathz = round_freq(timer, 127);
643 profhz = round_freq(timer, stathz * 64);
646 tick_sbt = SBT_1S / hz;
647 tick_bt = sbttobt(tick_sbt);
648 statperiod = SBT_1S / stathz;
649 profperiod = SBT_1S / profhz;
656 * Start per-CPU event timers on APs.
659 cpu_initclocks_ap(void)
662 struct pcpu_state *state;
665 state = DPCPU_PTR(timerstate);
669 hardclock_sync(curcpu);
673 td->td_intr_nesting_level++;
674 handleevents(state->now, 2);
675 td->td_intr_nesting_level--;
680 * Switch to profiling clock rates.
683 cpu_startprofclock(void)
687 if (profiling == 0) {
700 * Switch to regular clock rates.
703 cpu_stopprofclock(void)
707 if (profiling == 1) {
720 * Switch to idle mode (all ticks handled).
726 struct pcpu_state *state;
728 if (idletick || busy ||
729 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
730 #ifdef DEVICE_POLLING
731 || curcpu == CPU_FIRST()
735 state = DPCPU_PTR(timerstate);
740 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
741 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
742 t = getnextcpuevent(1);
745 state->nextevent = t;
749 return (MAX(t - now, 0));
753 * Switch to active mode (skip empty ticks).
756 cpu_activeclock(void)
759 struct pcpu_state *state;
762 state = DPCPU_PTR(timerstate);
763 if (state->idle == 0 || busy)
769 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
770 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
773 td->td_intr_nesting_level++;
774 handleevents(now, 1);
775 td->td_intr_nesting_level--;
780 * Change the frequency of the given timer. This changes et->et_frequency and
781 * if et is the active timer it reconfigures the timer on all CPUs. This is
782 * intended to be a private interface for the use of et_change_frequency() only.
785 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
791 et->et_frequency = newfreq;
794 et->et_frequency = newfreq;
799 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
801 struct pcpu_state *state;
803 /* Do not touch anything if somebody reconfiguring timers. */
806 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
807 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
808 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
809 state = DPCPU_ID_PTR(cpu, timerstate);
813 * If there is callout time already set earlier -- do nothing.
814 * This check may appear redundant because we check already in
815 * callout_process() but this double check guarantees we're safe
816 * with respect to race conditions between interrupts execution
819 state->nextcallopt = bt_opt;
820 if (bt >= state->nextcall)
822 state->nextcall = bt;
823 /* If there is some other event set earlier -- do nothing. */
824 if (bt >= state->nextevent)
826 state->nextevent = bt;
827 /* If timer is periodic -- there is nothing to reprogram. */
830 /* If timer is global or of the current CPU -- reprogram it. */
831 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
832 loadtimer(sbinuptime(), 0);
837 /* Otherwise make other CPU to reprogram it. */
841 ipi_cpu(cpu, IPI_HARDCLOCK);
846 * Report or change the active event timers hardware.
849 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
852 struct eventtimer *et;
857 snprintf(buf, sizeof(buf), "%s", et->et_name);
859 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
862 if (error != 0 || req->newptr == NULL ||
863 strcasecmp(buf, et->et_name) == 0) {
867 et = et_find(buf, 0, 0);
874 if (et->et_flags & ET_FLAGS_C3STOP)
875 cpu_disable_c3_sleep++;
876 if (timer->et_flags & ET_FLAGS_C3STOP)
877 cpu_disable_c3_sleep--;
878 periodic = want_periodic;
880 et_init(timer, timercb, NULL, NULL);
885 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
886 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
887 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
890 * Report or change the active event timer periodicity.
893 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
898 error = sysctl_handle_int(oidp, &val, 0, req);
899 if (error != 0 || req->newptr == NULL)
903 periodic = want_periodic = val;
908 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
909 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
910 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");
917 DB_SHOW_COMMAND(clocksource, db_show_clocksource)
919 struct pcpu_state *st;
923 st = DPCPU_ID_PTR(c, timerstate);
925 "CPU %2d: action %d handle %d ipi %d idle %d\n"
926 " now %#jx nevent %#jx (%jd)\n"
927 " ntick %#jx (%jd) nhard %#jx (%jd)\n"
928 " nstat %#jx (%jd) nprof %#jx (%jd)\n"
929 " ncall %#jx (%jd) ncallopt %#jx (%jd)\n",
930 c, st->action, st->handle, st->ipi, st->idle,
932 (uintmax_t)st->nextevent,
933 (uintmax_t)(st->nextevent - st->now) / tick_sbt,
934 (uintmax_t)st->nexttick,
935 (uintmax_t)(st->nexttick - st->now) / tick_sbt,
936 (uintmax_t)st->nexthard,
937 (uintmax_t)(st->nexthard - st->now) / tick_sbt,
938 (uintmax_t)st->nextstat,
939 (uintmax_t)(st->nextstat - st->now) / tick_sbt,
940 (uintmax_t)st->nextprof,
941 (uintmax_t)(st->nextprof - st->now) / tick_sbt,
942 (uintmax_t)st->nextcall,
943 (uintmax_t)(st->nextcall - st->now) / tick_sbt,
944 (uintmax_t)st->nextcallopt,
945 (uintmax_t)(st->nextcallopt - st->now) / tick_sbt);