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;
244 * Schedule binuptime of the next event on current CPU.
247 getnextcpuevent(int idle)
250 struct pcpu_state *state;
253 state = DPCPU_PTR(timerstate);
254 /* Handle hardclock() events, skipping some if CPU is idle. */
255 event = state->nexthard;
257 hardfreq = (u_int)hz / 2;
258 if (tc_min_ticktock_freq > 2
260 && curcpu == CPU_FIRST()
263 hardfreq = hz / tc_min_ticktock_freq;
265 event += tick_sbt * (hardfreq - 1);
267 /* Handle callout events. */
268 if (event > state->nextcall)
269 event = state->nextcall;
270 if (!idle) { /* If CPU is active - handle other types of events. */
271 if (event > state->nextstat)
272 event = state->nextstat;
273 if (profiling && event > state->nextprof)
274 event = state->nextprof;
277 if (event > state->nextcyc)
278 event = state->nextcyc;
284 * Schedule binuptime of the next event on all CPUs.
289 struct pcpu_state *state;
296 state = DPCPU_PTR(timerstate);
297 event = state->nextevent;
300 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
302 state = DPCPU_ID_PTR(cpu, timerstate);
303 if (event > state->nextevent) {
304 event = state->nextevent;
310 CTR4(KTR_SPARE2, "next at %d: next %d.%08x by %d",
311 curcpu, (int)(event >> 32), (u_int)(event & 0xffffffff), c);
315 /* Hardware timer callback function. */
317 timercb(struct eventtimer *et, void *arg)
321 struct pcpu_state *state;
326 /* Do not touch anything if somebody reconfiguring timers. */
329 /* Update present and next tick times. */
330 state = DPCPU_PTR(timerstate);
331 if (et->et_flags & ET_FLAGS_PERCPU) {
332 next = &state->nexttick;
337 *next = now + timerperiod;
339 *next = -1; /* Next tick is not scheduled yet. */
341 CTR3(KTR_SPARE2, "intr at %d: now %d.%08x",
342 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
345 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
347 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
349 state = DPCPU_ID_PTR(cpu, timerstate);
352 if (now >= state->nextevent) {
353 state->nextevent += SBT_1S;
364 /* Handle events for this time on this CPU. */
365 handleevents(now, 0);
368 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
373 state = DPCPU_ID_PTR(cpu, timerstate);
376 ipi_cpu(cpu, IPI_HARDCLOCK);
384 * Load new value into hardware timer.
387 loadtimer(sbintime_t now, int start)
389 struct pcpu_state *state;
395 if (timer->et_flags & ET_FLAGS_PERCPU) {
396 state = DPCPU_PTR(timerstate);
397 next = &state->nexttick;
403 * Try to start all periodic timers aligned
404 * to period to make events synchronous.
406 tmp = now % timerperiod;
407 new = timerperiod - tmp;
408 if (new < tmp) /* Left less then passed. */
410 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
411 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
412 (int)(new >> 32), (u_int)(new & 0xffffffff));
414 et_start(timer, new, timerperiod);
417 new = getnextevent();
419 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
420 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
423 et_start(timer, new - now, 0);
429 * Prepare event timer parameters after configuration changes.
436 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
438 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
440 singlemul = MIN(MAX(singlemul, 1), 20);
441 freq = hz * singlemul;
442 while (freq < (profiling ? profhz : stathz))
444 freq = round_freq(timer, freq);
445 timerperiod = SBT_1S / freq;
449 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
455 struct pcpu_state *state;
457 state = DPCPU_PTR(timerstate);
458 switch (atomic_load_acq_int(&state->action)) {
465 atomic_store_rel_int(&state->action, 0);
472 atomic_store_rel_int(&state->action, 0);
475 if (atomic_readandclear_int(&state->handle) && !busy) {
477 handleevents(now, 0);
484 * Reconfigure specified timer.
485 * For per-CPU timers use IPI to make other CPUs to reconfigure.
488 configtimer(int start)
490 sbintime_t now, next;
491 struct pcpu_state *state;
500 ET_HW_LOCK(DPCPU_PTR(timerstate));
502 /* Initialize time machine parameters. */
503 next = now + timerperiod;
509 state = DPCPU_ID_PTR(cpu, timerstate);
511 if (!smp_started && cpu != CPU_FIRST())
512 state->nextevent = INT64_MAX;
514 state->nextevent = next;
516 state->nexttick = next;
518 state->nexttick = -1;
519 state->nexthard = next;
520 state->nextstat = next;
521 state->nextprof = next;
522 state->nextcall = next;
523 state->nextcallopt = next;
527 /* Start global timer or per-CPU timer of this CPU. */
531 /* Stop global timer or per-CPU timer of this CPU. */
534 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
536 /* If timer is global or there is no other CPUs yet - we are done. */
537 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);
601 state->nextcyc = INT64_MAX;
603 state->nextcall = INT64_MAX;
604 state->nextcallopt = INT64_MAX;
606 periodic = want_periodic;
607 /* Grab requested timer or the best of present. */
609 timer = et_find(timername, 0, 0);
610 if (timer == NULL && periodic) {
611 timer = et_find(NULL,
612 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
615 timer = et_find(NULL,
616 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
618 if (timer == NULL && !periodic) {
619 timer = et_find(NULL,
620 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
623 panic("No usable event timer found!");
624 et_init(timer, timercb, NULL, NULL);
626 /* Adapt to timer capabilities. */
627 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
629 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
631 if (timer->et_flags & ET_FLAGS_C3STOP)
632 cpu_disable_deep_sleep++;
635 * We honor the requested 'hz' value.
636 * We want to run stathz in the neighborhood of 128hz.
637 * We would like profhz to run as often as possible.
639 if (singlemul <= 0 || singlemul > 20) {
640 if (hz >= 1500 || (hz % 128) == 0)
648 base = round_freq(timer, hz * singlemul);
649 singlemul = max((base + hz / 2) / hz, 1);
650 hz = (base + singlemul / 2) / singlemul;
655 if (div >= singlemul && (div % singlemul) == 0)
660 while ((profhz + stathz) <= 128 * 64)
662 profhz = round_freq(timer, profhz);
664 hz = round_freq(timer, hz);
665 stathz = round_freq(timer, 127);
666 profhz = round_freq(timer, stathz * 64);
669 tick_sbt = SBT_1S / hz;
670 tick_bt = sbttobt(tick_sbt);
671 statperiod = SBT_1S / stathz;
672 profperiod = SBT_1S / profhz;
679 * Start per-CPU event timers on APs.
682 cpu_initclocks_ap(void)
685 struct pcpu_state *state;
688 state = DPCPU_PTR(timerstate);
692 hardclock_sync(curcpu);
696 td->td_intr_nesting_level++;
697 handleevents(state->now, 2);
698 td->td_intr_nesting_level--;
703 * Switch to profiling clock rates.
706 cpu_startprofclock(void)
710 if (profiling == 0) {
723 * Switch to regular clock rates.
726 cpu_stopprofclock(void)
730 if (profiling == 1) {
743 * Switch to idle mode (all ticks handled).
749 struct pcpu_state *state;
751 if (idletick || busy ||
752 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
753 #ifdef DEVICE_POLLING
754 || curcpu == CPU_FIRST()
758 state = DPCPU_PTR(timerstate);
763 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
764 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
765 t = getnextcpuevent(1);
768 state->nextevent = t;
772 return (MAX(t - now, 0));
776 * Switch to active mode (skip empty ticks).
779 cpu_activeclock(void)
782 struct pcpu_state *state;
785 state = DPCPU_PTR(timerstate);
786 if (state->idle == 0 || busy)
792 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
793 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
796 td->td_intr_nesting_level++;
797 handleevents(now, 1);
798 td->td_intr_nesting_level--;
804 clocksource_cyc_set(const struct bintime *bt)
807 struct pcpu_state *state;
809 /* Do not touch anything if somebody reconfiguring timers. */
813 state = DPCPU_PTR(timerstate);
819 CTR5(KTR_SPARE2, "set_cyc at %d: now %d.%08x t %d.%08x",
820 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
821 (int)(t >> 32), (u_int)(t & 0xffffffff));
824 if (t == state->nextcyc)
827 if (t >= state->nextevent)
829 state->nextevent = t;
838 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
840 struct pcpu_state *state;
842 /* Do not touch anything if somebody reconfiguring timers. */
845 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
846 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
847 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
848 state = DPCPU_ID_PTR(cpu, timerstate);
852 * If there is callout time already set earlier -- do nothing.
853 * This check may appear redundant because we check already in
854 * callout_process() but this double check guarantees we're safe
855 * with respect to race conditions between interrupts execution
858 state->nextcallopt = bt_opt;
859 if (bt >= state->nextcall)
861 state->nextcall = bt;
862 /* If there is some other event set earlier -- do nothing. */
863 if (bt >= state->nextevent)
865 state->nextevent = bt;
866 /* If timer is periodic -- there is nothing to reprogram. */
869 /* If timer is global or of the current CPU -- reprogram it. */
870 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
871 loadtimer(sbinuptime(), 0);
876 /* Otherwise make other CPU to reprogram it. */
880 ipi_cpu(cpu, IPI_HARDCLOCK);
885 * Report or change the active event timers hardware.
888 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
891 struct eventtimer *et;
896 snprintf(buf, sizeof(buf), "%s", et->et_name);
898 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
901 if (error != 0 || req->newptr == NULL ||
902 strcasecmp(buf, et->et_name) == 0) {
906 et = et_find(buf, 0, 0);
913 if (et->et_flags & ET_FLAGS_C3STOP)
914 cpu_disable_deep_sleep++;
915 if (timer->et_flags & ET_FLAGS_C3STOP)
916 cpu_disable_deep_sleep--;
917 periodic = want_periodic;
919 et_init(timer, timercb, NULL, NULL);
924 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
925 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
926 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
929 * Report or change the active event timer periodicity.
932 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
937 error = sysctl_handle_int(oidp, &val, 0, req);
938 if (error != 0 || req->newptr == NULL)
942 periodic = want_periodic = val;
947 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
948 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
949 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");