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>
59 #include <sys/dtrace_bsd.h>
60 cyclic_clock_func_t cyclic_clock_func = NULL;
63 int cpu_can_deep_sleep = 0; /* C3 state is available. */
64 int cpu_disable_deep_sleep = 0; /* Timer dies in C3. */
66 static void setuptimer(void);
67 static void loadtimer(sbintime_t now, int first);
68 static int doconfigtimer(void);
69 static void configtimer(int start);
70 static int round_freq(struct eventtimer *et, int freq);
72 static sbintime_t getnextcpuevent(int idle);
73 static sbintime_t getnextevent(void);
74 static int handleevents(sbintime_t now, int fake);
76 static struct mtx et_hw_mtx;
78 #define ET_HW_LOCK(state) \
80 if (timer->et_flags & ET_FLAGS_PERCPU) \
81 mtx_lock_spin(&(state)->et_hw_mtx); \
83 mtx_lock_spin(&et_hw_mtx); \
86 #define ET_HW_UNLOCK(state) \
88 if (timer->et_flags & ET_FLAGS_PERCPU) \
89 mtx_unlock_spin(&(state)->et_hw_mtx); \
91 mtx_unlock_spin(&et_hw_mtx); \
94 static struct eventtimer *timer = NULL;
95 static sbintime_t timerperiod; /* Timer period for periodic mode. */
96 static sbintime_t statperiod; /* statclock() events period. */
97 static sbintime_t profperiod; /* profclock() events period. */
98 static sbintime_t nexttick; /* Next global timer tick time. */
99 static u_int busy = 1; /* Reconfiguration is in progress. */
100 static int profiling = 0; /* Profiling events enabled. */
102 static char timername[32]; /* Wanted timer. */
103 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
105 static int singlemul = 0; /* Multiplier for periodic mode. */
106 TUNABLE_INT("kern.eventtimer.singlemul", &singlemul);
107 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RW, &singlemul,
108 0, "Multiplier for periodic mode");
110 static u_int idletick = 0; /* Run periodic events when idle. */
111 TUNABLE_INT("kern.eventtimer.idletick", &idletick);
112 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RW, &idletick,
113 0, "Run periodic events when idle");
115 static int periodic = 0; /* Periodic or one-shot mode. */
116 static int want_periodic = 0; /* What mode to prefer. */
117 TUNABLE_INT("kern.eventtimer.periodic", &want_periodic);
120 struct mtx et_hw_mtx; /* Per-CPU timer mutex. */
121 u_int action; /* Reconfiguration requests. */
122 u_int handle; /* Immediate handle resuests. */
123 sbintime_t now; /* Last tick time. */
124 sbintime_t nextevent; /* Next scheduled event on this CPU. */
125 sbintime_t nexttick; /* Next timer tick time. */
126 sbintime_t nexthard; /* Next hardlock() event. */
127 sbintime_t nextstat; /* Next statclock() event. */
128 sbintime_t nextprof; /* Next profclock() event. */
129 sbintime_t nextcall; /* Next callout event. */
130 sbintime_t nextcallopt; /* Next optional callout event. */
132 sbintime_t nextcyc; /* Next OpenSolaris cyclics event. */
134 int ipi; /* This CPU needs IPI. */
135 int idle; /* This CPU is in idle mode. */
138 static DPCPU_DEFINE(struct pcpu_state, timerstate);
139 DPCPU_DEFINE(sbintime_t, hardclocktime);
142 * Timer broadcast IPI handler.
148 struct pcpu_state *state;
151 if (doconfigtimer() || busy)
152 return (FILTER_HANDLED);
153 state = DPCPU_PTR(timerstate);
155 CTR3(KTR_SPARE2, "ipi at %d: now %d.%08x",
156 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
157 done = handleevents(now, 0);
158 return (done ? FILTER_HANDLED : FILTER_STRAY);
162 * Handle all events for specified time on this CPU
165 handleevents(sbintime_t now, int fake)
168 struct trapframe *frame;
169 struct pcpu_state *state;
173 CTR3(KTR_SPARE2, "handle at %d: now %d.%08x",
174 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
180 frame = curthread->td_intr_frame;
181 usermode = TRAPF_USERMODE(frame);
184 state = DPCPU_PTR(timerstate);
187 while (now >= state->nexthard) {
188 state->nexthard += tick_sbt;
192 hct = DPCPU_PTR(hardclocktime);
193 *hct = state->nexthard - tick_sbt;
195 hardclock_cnt(runs, usermode);
200 while (now >= state->nextstat) {
201 state->nextstat += statperiod;
204 if (runs && fake < 2) {
205 statclock_cnt(runs, usermode);
210 while (now >= state->nextprof) {
211 state->nextprof += profperiod;
215 profclock_cnt(runs, usermode, TRAPF_PC(frame));
219 state->nextprof = state->nextstat;
220 if (now >= state->nextcallopt) {
221 state->nextcall = state->nextcallopt = INT64_MAX;
222 callout_process(now);
226 if (fake == 0 && now >= state->nextcyc && cyclic_clock_func != NULL) {
227 state->nextcyc = INT64_MAX;
228 (*cyclic_clock_func)(frame);
232 t = getnextcpuevent(0);
236 state->nextevent = t;
237 loadtimer(now, (fake == 2) &&
238 (timer->et_flags & ET_FLAGS_PERCPU));
245 * Schedule binuptime of the next event on current CPU.
248 getnextcpuevent(int idle)
251 struct pcpu_state *state;
254 state = DPCPU_PTR(timerstate);
255 /* Handle hardclock() events, skipping some if CPU is idle. */
256 event = state->nexthard;
258 hardfreq = (u_int)hz / 2;
259 if (tc_min_ticktock_freq > 2
261 && curcpu == CPU_FIRST()
264 hardfreq = hz / tc_min_ticktock_freq;
266 event += tick_sbt * (hardfreq - 1);
268 /* Handle callout events. */
269 if (event > state->nextcall)
270 event = state->nextcall;
271 if (!idle) { /* If CPU is active - handle other types of events. */
272 if (event > state->nextstat)
273 event = state->nextstat;
274 if (profiling && event > state->nextprof)
275 event = state->nextprof;
278 if (event > state->nextcyc)
279 event = state->nextcyc;
285 * Schedule binuptime of the next event on all CPUs.
290 struct pcpu_state *state;
297 state = DPCPU_PTR(timerstate);
298 event = state->nextevent;
301 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
303 state = DPCPU_ID_PTR(cpu, timerstate);
304 if (event > state->nextevent) {
305 event = state->nextevent;
311 CTR4(KTR_SPARE2, "next at %d: next %d.%08x by %d",
312 curcpu, (int)(event >> 32), (u_int)(event & 0xffffffff), c);
316 /* Hardware timer callback function. */
318 timercb(struct eventtimer *et, void *arg)
322 struct pcpu_state *state;
327 /* Do not touch anything if somebody reconfiguring timers. */
330 /* Update present and next tick times. */
331 state = DPCPU_PTR(timerstate);
332 if (et->et_flags & ET_FLAGS_PERCPU) {
333 next = &state->nexttick;
338 *next = now + timerperiod;
340 *next = -1; /* Next tick is not scheduled yet. */
342 CTR3(KTR_SPARE2, "intr at %d: now %d.%08x",
343 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
346 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
348 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
350 state = DPCPU_ID_PTR(cpu, timerstate);
353 if (now >= state->nextevent) {
354 state->nextevent += SBT_1S;
365 /* Handle events for this time on this CPU. */
366 handleevents(now, 0);
369 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
374 state = DPCPU_ID_PTR(cpu, timerstate);
377 ipi_cpu(cpu, IPI_HARDCLOCK);
385 * Load new value into hardware timer.
388 loadtimer(sbintime_t now, int start)
390 struct pcpu_state *state;
396 if (timer->et_flags & ET_FLAGS_PERCPU) {
397 state = DPCPU_PTR(timerstate);
398 next = &state->nexttick;
404 * Try to start all periodic timers aligned
405 * to period to make events synchronous.
407 tmp = now % timerperiod;
408 new = timerperiod - tmp;
409 if (new < tmp) /* Left less then passed. */
411 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
412 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
413 (int)(new >> 32), (u_int)(new & 0xffffffff));
415 et_start(timer, new, timerperiod);
418 new = getnextevent();
420 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
421 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
424 et_start(timer, new - now, 0);
430 * Prepare event timer parameters after configuration changes.
437 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
439 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
441 singlemul = MIN(MAX(singlemul, 1), 20);
442 freq = hz * singlemul;
443 while (freq < (profiling ? profhz : stathz))
445 freq = round_freq(timer, freq);
446 timerperiod = SBT_1S / freq;
450 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
456 struct pcpu_state *state;
458 state = DPCPU_PTR(timerstate);
459 switch (atomic_load_acq_int(&state->action)) {
466 atomic_store_rel_int(&state->action, 0);
473 atomic_store_rel_int(&state->action, 0);
476 if (atomic_readandclear_int(&state->handle) && !busy) {
478 handleevents(now, 0);
485 * Reconfigure specified timer.
486 * For per-CPU timers use IPI to make other CPUs to reconfigure.
489 configtimer(int start)
491 sbintime_t now, next;
492 struct pcpu_state *state;
501 ET_HW_LOCK(DPCPU_PTR(timerstate));
503 /* Initialize time machine parameters. */
504 next = now + timerperiod;
510 state = DPCPU_ID_PTR(cpu, timerstate);
512 if (!smp_started && cpu != CPU_FIRST())
513 state->nextevent = INT64_MAX;
515 state->nextevent = next;
517 state->nexttick = next;
519 state->nexttick = -1;
520 state->nexthard = next;
521 state->nextstat = next;
522 state->nextprof = next;
523 state->nextcall = next;
524 state->nextcallopt = next;
528 /* Start global timer or per-CPU timer of this CPU. */
532 /* Stop global timer or per-CPU timer of this CPU. */
535 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
537 /* If timer is global or there is no other CPUs yet - we are done. */
538 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
542 /* Set reconfigure flags for other CPUs. */
544 state = DPCPU_ID_PTR(cpu, timerstate);
545 atomic_store_rel_int(&state->action,
546 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
548 /* Broadcast reconfigure IPI. */
549 ipi_all_but_self(IPI_HARDCLOCK);
550 /* Wait for reconfiguration completed. */
556 state = DPCPU_ID_PTR(cpu, timerstate);
557 if (atomic_load_acq_int(&state->action))
565 * Calculate nearest frequency supported by hardware timer.
568 round_freq(struct eventtimer *et, int freq)
572 if (et->et_frequency != 0) {
573 div = lmax((et->et_frequency + freq / 2) / freq, 1);
574 if (et->et_flags & ET_FLAGS_POW2DIV)
575 div = 1 << (flsl(div + div / 2) - 1);
576 freq = (et->et_frequency + div / 2) / div;
578 if (et->et_min_period > SBT_1S)
579 panic("Event timer \"%s\" doesn't support sub-second periods!",
581 else if (et->et_min_period != 0)
582 freq = min(freq, SBT2FREQ(et->et_min_period));
583 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
584 freq = max(freq, SBT2FREQ(et->et_max_period));
589 * Configure and start event timers (BSP part).
592 cpu_initclocks_bsp(void)
594 struct pcpu_state *state;
597 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
599 state = DPCPU_ID_PTR(cpu, timerstate);
600 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
602 state->nextcyc = INT64_MAX;
604 state->nextcall = INT64_MAX;
605 state->nextcallopt = INT64_MAX;
607 periodic = want_periodic;
608 /* Grab requested timer or the best of present. */
610 timer = et_find(timername, 0, 0);
611 if (timer == NULL && periodic) {
612 timer = et_find(NULL,
613 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
616 timer = et_find(NULL,
617 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
619 if (timer == NULL && !periodic) {
620 timer = et_find(NULL,
621 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
624 panic("No usable event timer found!");
625 et_init(timer, timercb, NULL, NULL);
627 /* Adapt to timer capabilities. */
628 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
630 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
632 if (timer->et_flags & ET_FLAGS_C3STOP)
633 cpu_disable_deep_sleep++;
636 * We honor the requested 'hz' value.
637 * We want to run stathz in the neighborhood of 128hz.
638 * We would like profhz to run as often as possible.
640 if (singlemul <= 0 || singlemul > 20) {
641 if (hz >= 1500 || (hz % 128) == 0)
649 base = round_freq(timer, hz * singlemul);
650 singlemul = max((base + hz / 2) / hz, 1);
651 hz = (base + singlemul / 2) / singlemul;
656 if (div >= singlemul && (div % singlemul) == 0)
661 while ((profhz + stathz) <= 128 * 64)
663 profhz = round_freq(timer, profhz);
665 hz = round_freq(timer, hz);
666 stathz = round_freq(timer, 127);
667 profhz = round_freq(timer, stathz * 64);
670 tick_sbt = SBT_1S / hz;
671 tick_bt = sbttobt(tick_sbt);
672 statperiod = SBT_1S / stathz;
673 profperiod = SBT_1S / profhz;
680 * Start per-CPU event timers on APs.
683 cpu_initclocks_ap(void)
686 struct pcpu_state *state;
689 state = DPCPU_PTR(timerstate);
693 hardclock_sync(curcpu);
697 td->td_intr_nesting_level++;
698 handleevents(state->now, 2);
699 td->td_intr_nesting_level--;
704 * Switch to profiling clock rates.
707 cpu_startprofclock(void)
711 if (profiling == 0) {
724 * Switch to regular clock rates.
727 cpu_stopprofclock(void)
731 if (profiling == 1) {
744 * Switch to idle mode (all ticks handled).
750 struct pcpu_state *state;
752 if (idletick || busy ||
753 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
754 #ifdef DEVICE_POLLING
755 || curcpu == CPU_FIRST()
759 state = DPCPU_PTR(timerstate);
764 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
765 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
766 t = getnextcpuevent(1);
769 state->nextevent = t;
773 return (MAX(t - now, 0));
777 * Switch to active mode (skip empty ticks).
780 cpu_activeclock(void)
783 struct pcpu_state *state;
786 state = DPCPU_PTR(timerstate);
787 if (state->idle == 0 || busy)
793 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
794 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
797 td->td_intr_nesting_level++;
798 handleevents(now, 1);
799 td->td_intr_nesting_level--;
804 * Change the frequency of the given timer. This changes et->et_frequency and
805 * if et is the active timer it reconfigures the timer on all CPUs. This is
806 * intended to be a private interface for the use of et_change_frequency() only.
809 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
815 et->et_frequency = newfreq;
818 et->et_frequency = newfreq;
824 clocksource_cyc_set(const struct bintime *bt)
827 struct pcpu_state *state;
829 /* Do not touch anything if somebody reconfiguring timers. */
833 state = DPCPU_PTR(timerstate);
839 CTR5(KTR_SPARE2, "set_cyc at %d: now %d.%08x t %d.%08x",
840 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
841 (int)(t >> 32), (u_int)(t & 0xffffffff));
844 if (t == state->nextcyc)
847 if (t >= state->nextevent)
849 state->nextevent = t;
858 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
860 struct pcpu_state *state;
862 /* Do not touch anything if somebody reconfiguring timers. */
865 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
866 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
867 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
868 state = DPCPU_ID_PTR(cpu, timerstate);
872 * If there is callout time already set earlier -- do nothing.
873 * This check may appear redundant because we check already in
874 * callout_process() but this double check guarantees we're safe
875 * with respect to race conditions between interrupts execution
878 state->nextcallopt = bt_opt;
879 if (bt >= state->nextcall)
881 state->nextcall = bt;
882 /* If there is some other event set earlier -- do nothing. */
883 if (bt >= state->nextevent)
885 state->nextevent = bt;
886 /* If timer is periodic -- there is nothing to reprogram. */
889 /* If timer is global or of the current CPU -- reprogram it. */
890 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
891 loadtimer(sbinuptime(), 0);
896 /* Otherwise make other CPU to reprogram it. */
900 ipi_cpu(cpu, IPI_HARDCLOCK);
905 * Report or change the active event timers hardware.
908 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
911 struct eventtimer *et;
916 snprintf(buf, sizeof(buf), "%s", et->et_name);
918 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
921 if (error != 0 || req->newptr == NULL ||
922 strcasecmp(buf, et->et_name) == 0) {
926 et = et_find(buf, 0, 0);
933 if (et->et_flags & ET_FLAGS_C3STOP)
934 cpu_disable_deep_sleep++;
935 if (timer->et_flags & ET_FLAGS_C3STOP)
936 cpu_disable_deep_sleep--;
937 periodic = want_periodic;
939 et_init(timer, timercb, NULL, NULL);
944 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
945 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
946 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
949 * Report or change the active event timer periodicity.
952 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
957 error = sysctl_handle_int(oidp, &val, 0, req);
958 if (error != 0 || req->newptr == NULL)
962 periodic = want_periodic = val;
967 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
968 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
969 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");