2 * Copyright (c) 2010-2012 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>
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>
58 #include <sys/dtrace_bsd.h>
59 cyclic_clock_func_t cyclic_clock_func = NULL;
62 int cpu_deepest_sleep = 0; /* Deepest Cx state available. */
63 int cpu_disable_c2_sleep = 0; /* Timer dies in C2. */
64 int cpu_disable_c3_sleep = 0; /* Timer dies in C3. */
66 static void setuptimer(void);
67 static void loadtimer(struct bintime *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 void getnextcpuevent(struct bintime *event, int idle);
73 static void getnextevent(struct bintime *event);
74 static int handleevents(struct bintime *now, int fake);
76 static void cpu_new_callout(int cpu, int ticks);
79 static struct mtx et_hw_mtx;
81 #define ET_HW_LOCK(state) \
83 if (timer->et_flags & ET_FLAGS_PERCPU) \
84 mtx_lock_spin(&(state)->et_hw_mtx); \
86 mtx_lock_spin(&et_hw_mtx); \
89 #define ET_HW_UNLOCK(state) \
91 if (timer->et_flags & ET_FLAGS_PERCPU) \
92 mtx_unlock_spin(&(state)->et_hw_mtx); \
94 mtx_unlock_spin(&et_hw_mtx); \
97 static struct eventtimer *timer = NULL;
98 static struct bintime timerperiod; /* Timer period for periodic mode. */
99 static struct bintime hardperiod; /* hardclock() events period. */
100 static struct bintime statperiod; /* statclock() events period. */
101 static struct bintime profperiod; /* profclock() events period. */
102 static struct bintime nexttick; /* Next global timer tick time. */
103 static struct bintime nexthard; /* Next global hardlock() event. */
104 static u_int busy = 0; /* Reconfiguration is in progress. */
105 static int profiling = 0; /* Profiling events enabled. */
107 static char timername[32]; /* Wanted timer. */
108 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
110 static int singlemul = 0; /* Multiplier for periodic mode. */
111 TUNABLE_INT("kern.eventtimer.singlemul", &singlemul);
112 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RW, &singlemul,
113 0, "Multiplier for periodic mode");
115 static u_int idletick = 0; /* Run periodic events when idle. */
116 TUNABLE_INT("kern.eventtimer.idletick", &idletick);
117 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RW, &idletick,
118 0, "Run periodic events when idle");
120 static u_int activetick = 1; /* Run all periodic events when active. */
121 TUNABLE_INT("kern.eventtimer.activetick", &activetick);
122 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, activetick, CTLFLAG_RW, &activetick,
123 0, "Run all periodic events when active");
125 static int periodic = 0; /* Periodic or one-shot mode. */
126 static int want_periodic = 0; /* What mode to prefer. */
127 TUNABLE_INT("kern.eventtimer.periodic", &want_periodic);
130 struct mtx et_hw_mtx; /* Per-CPU timer mutex. */
131 u_int action; /* Reconfiguration requests. */
132 u_int handle; /* Immediate handle resuests. */
133 struct bintime now; /* Last tick time. */
134 struct bintime nextevent; /* Next scheduled event on this CPU. */
135 struct bintime nexttick; /* Next timer tick time. */
136 struct bintime nexthard; /* Next hardlock() event. */
137 struct bintime nextstat; /* Next statclock() event. */
138 struct bintime nextprof; /* Next profclock() event. */
140 struct bintime nextcyc; /* Next OpenSolaris cyclics event. */
142 int ipi; /* This CPU needs IPI. */
143 int idle; /* This CPU is in idle mode. */
146 static DPCPU_DEFINE(struct pcpu_state, timerstate);
148 #define FREQ2BT(freq, bt) \
151 (bt)->frac = ((uint64_t)0x8000000000000000 / (freq)) << 1; \
153 #define BT2FREQ(bt) \
154 (((uint64_t)0x8000000000000000 + ((bt)->frac >> 2)) / \
158 * Timer broadcast IPI handler.
164 struct pcpu_state *state;
167 if (doconfigtimer() || busy)
168 return (FILTER_HANDLED);
169 state = DPCPU_PTR(timerstate);
171 CTR4(KTR_SPARE2, "ipi at %d: now %d.%08x%08x",
172 curcpu, now.sec, (unsigned int)(now.frac >> 32),
173 (unsigned int)(now.frac & 0xffffffff));
174 done = handleevents(&now, 0);
175 return (done ? FILTER_HANDLED : FILTER_STRAY);
179 * Handle all events for specified time on this CPU
182 handleevents(struct bintime *now, int fake)
185 struct trapframe *frame;
186 struct pcpu_state *state;
191 CTR4(KTR_SPARE2, "handle at %d: now %d.%08x%08x",
192 curcpu, now->sec, (unsigned int)(now->frac >> 32),
193 (unsigned int)(now->frac & 0xffffffff));
200 frame = curthread->td_intr_frame;
201 usermode = TRAPF_USERMODE(frame);
202 pc = TRAPF_PC(frame);
205 state = DPCPU_PTR(timerstate);
208 while (bintime_cmp(now, &state->nexthard, >=)) {
209 bintime_add(&state->nexthard, &hardperiod);
212 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 &&
213 bintime_cmp(&state->nexthard, &nexthard, >))
214 nexthard = state->nexthard;
215 if (runs && fake < 2) {
216 hardclock_cnt(runs, usermode);
220 while (bintime_cmp(now, &state->nextstat, >=)) {
221 bintime_add(&state->nextstat, &statperiod);
224 if (runs && fake < 2) {
225 statclock_cnt(runs, usermode);
230 while (bintime_cmp(now, &state->nextprof, >=)) {
231 bintime_add(&state->nextprof, &profperiod);
235 profclock_cnt(runs, usermode, pc);
239 state->nextprof = state->nextstat;
242 if (fake == 0 && cyclic_clock_func != NULL &&
243 state->nextcyc.sec != -1 &&
244 bintime_cmp(now, &state->nextcyc, >=)) {
245 state->nextcyc.sec = -1;
246 (*cyclic_clock_func)(frame);
250 getnextcpuevent(&t, 0);
252 state->nextevent = t;
258 state->nextevent = t;
266 * Schedule binuptime of the next event on current CPU.
269 getnextcpuevent(struct bintime *event, int idle)
272 struct pcpu_state *state;
275 state = DPCPU_PTR(timerstate);
276 /* Handle hardclock() events. */
277 *event = state->nexthard;
278 if (idle || (!activetick && !profiling &&
279 (timer->et_flags & ET_FLAGS_PERCPU) == 0)) {
280 skip = idle ? 4 : (stathz / 2);
281 if (curcpu == CPU_FIRST() && tc_min_ticktock_freq > skip)
282 skip = tc_min_ticktock_freq;
283 skip = callout_tickstofirst(hz / skip) - 1;
284 CTR2(KTR_SPARE2, "skip at %d: %d", curcpu, skip);
286 bintime_mul(&tmp, skip);
287 bintime_add(event, &tmp);
289 if (!idle) { /* If CPU is active - handle other types of events. */
290 if (bintime_cmp(event, &state->nextstat, >))
291 *event = state->nextstat;
292 if (profiling && bintime_cmp(event, &state->nextprof, >))
293 *event = state->nextprof;
296 if (state->nextcyc.sec != -1 && bintime_cmp(event, &state->nextcyc, >))
297 *event = state->nextcyc;
302 * Schedule binuptime of the next event on all CPUs.
305 getnextevent(struct bintime *event)
307 struct pcpu_state *state;
313 state = DPCPU_PTR(timerstate);
314 *event = state->nextevent;
316 nonidle = !state->idle;
317 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
322 state = DPCPU_ID_PTR(cpu, timerstate);
323 nonidle += !state->idle;
324 if (bintime_cmp(event, &state->nextevent, >)) {
325 *event = state->nextevent;
330 if (nonidle != 0 && bintime_cmp(event, &nexthard, >))
333 CTR5(KTR_SPARE2, "next at %d: next %d.%08x%08x by %d",
334 curcpu, event->sec, (unsigned int)(event->frac >> 32),
335 (unsigned int)(event->frac & 0xffffffff), c);
338 /* Hardware timer callback function. */
340 timercb(struct eventtimer *et, void *arg)
343 struct bintime *next;
344 struct pcpu_state *state;
349 /* Do not touch anything if somebody reconfiguring timers. */
352 /* Update present and next tick times. */
353 state = DPCPU_PTR(timerstate);
354 if (et->et_flags & ET_FLAGS_PERCPU) {
355 next = &state->nexttick;
359 now = *next; /* Ex-next tick time becomes present time. */
360 bintime_add(next, &timerperiod); /* Next tick in 1 period. */
362 binuptime(&now); /* Get present time from hardware. */
363 next->sec = -1; /* Next tick is not scheduled yet. */
366 CTR4(KTR_SPARE2, "intr at %d: now %d.%08x%08x",
367 curcpu, now.sec, (unsigned int)(now.frac >> 32),
368 (unsigned int)(now.frac & 0xffffffff));
371 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
373 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
375 state = DPCPU_ID_PTR(cpu, timerstate);
378 if (bintime_cmp(&now, &state->nextevent, >=)) {
379 state->nextevent.sec++;
390 /* Handle events for this time on this CPU. */
391 handleevents(&now, 0);
394 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
399 state = DPCPU_ID_PTR(cpu, timerstate);
402 ipi_cpu(cpu, IPI_HARDCLOCK);
410 * Load new value into hardware timer.
413 loadtimer(struct bintime *now, int start)
415 struct pcpu_state *state;
417 struct bintime *next;
421 if (timer->et_flags & ET_FLAGS_PERCPU) {
422 state = DPCPU_PTR(timerstate);
423 next = &state->nexttick;
429 * Try to start all periodic timers aligned
430 * to period to make events synchronous.
432 tmp = ((uint64_t)now->sec << 36) + (now->frac >> 28);
433 tmp = (tmp % (timerperiod.frac >> 28)) << 28;
435 new.frac = timerperiod.frac - tmp;
436 if (new.frac < tmp) /* Left less then passed. */
437 bintime_add(&new, &timerperiod);
438 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
439 curcpu, now->sec, (unsigned int)(now->frac >> 32),
440 new.sec, (unsigned int)(new.frac >> 32));
442 bintime_add(next, now);
443 et_start(timer, &new, &timerperiod);
447 eq = bintime_cmp(&new, next, ==);
448 CTR5(KTR_SPARE2, "load at %d: next %d.%08x%08x eq %d",
449 curcpu, new.sec, (unsigned int)(new.frac >> 32),
450 (unsigned int)(new.frac & 0xffffffff),
454 bintime_sub(&new, now);
455 et_start(timer, &new, NULL);
461 * Prepare event timer parameters after configuration changes.
468 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
470 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
472 singlemul = MIN(MAX(singlemul, 1), 20);
473 freq = hz * singlemul;
474 while (freq < (profiling ? profhz : stathz))
476 freq = round_freq(timer, freq);
477 FREQ2BT(freq, &timerperiod);
481 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
487 struct pcpu_state *state;
489 state = DPCPU_PTR(timerstate);
490 switch (atomic_load_acq_int(&state->action)) {
497 atomic_store_rel_int(&state->action, 0);
504 atomic_store_rel_int(&state->action, 0);
507 if (atomic_readandclear_int(&state->handle) && !busy) {
509 handleevents(&now, 0);
516 * Reconfigure specified timer.
517 * For per-CPU timers use IPI to make other CPUs to reconfigure.
520 configtimer(int start)
522 struct bintime now, next;
523 struct pcpu_state *state;
531 ET_HW_LOCK(DPCPU_PTR(timerstate));
533 /* Initialize time machine parameters. */
535 bintime_add(&next, &timerperiod);
541 state = DPCPU_ID_PTR(cpu, timerstate);
543 state->nextevent = next;
545 state->nexttick = next;
547 state->nexttick.sec = -1;
548 state->nexthard = next;
549 state->nextstat = next;
550 state->nextprof = next;
554 /* Start global timer or per-CPU timer of this CPU. */
558 /* Stop global timer or per-CPU timer of this CPU. */
561 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
563 /* If timer is global or there is no other CPUs yet - we are done. */
564 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
568 /* Set reconfigure flags for other CPUs. */
570 state = DPCPU_ID_PTR(cpu, timerstate);
571 atomic_store_rel_int(&state->action,
572 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
574 /* Broadcast reconfigure IPI. */
575 ipi_all_but_self(IPI_HARDCLOCK);
576 /* Wait for reconfiguration completed. */
582 state = DPCPU_ID_PTR(cpu, timerstate);
583 if (atomic_load_acq_int(&state->action))
591 * Calculate nearest frequency supported by hardware timer.
594 round_freq(struct eventtimer *et, int freq)
598 if (et->et_frequency != 0) {
599 div = lmax((et->et_frequency + freq / 2) / freq, 1);
600 if (et->et_flags & ET_FLAGS_POW2DIV)
601 div = 1 << (flsl(div + div / 2) - 1);
602 freq = (et->et_frequency + div / 2) / div;
604 if (et->et_min_period.sec > 0)
606 else if (et->et_min_period.frac != 0)
607 freq = min(freq, BT2FREQ(&et->et_min_period));
608 if (et->et_max_period.sec == 0 && et->et_max_period.frac != 0)
609 freq = max(freq, BT2FREQ(&et->et_max_period));
614 * Configure and start event timers (BSP part).
617 cpu_initclocks_bsp(void)
619 struct pcpu_state *state;
622 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
624 state = DPCPU_ID_PTR(cpu, timerstate);
625 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
627 state->nextcyc.sec = -1;
631 callout_new_inserted = cpu_new_callout;
633 periodic = want_periodic;
634 /* Grab requested timer or the best of present. */
636 timer = et_find(timername, 0, 0);
637 if (timer == NULL && periodic) {
638 timer = et_find(NULL,
639 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
642 timer = et_find(NULL,
643 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
645 if (timer == NULL && !periodic) {
646 timer = et_find(NULL,
647 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
650 panic("No usable event timer found!");
651 et_init(timer, timercb, NULL, NULL);
653 /* Adapt to timer capabilities. */
654 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
656 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
658 if (timer->et_flags & ET_FLAGS_C3STOP)
659 cpu_disable_c3_sleep++;
662 * We honor the requested 'hz' value.
663 * We want to run stathz in the neighborhood of 128hz.
664 * We would like profhz to run as often as possible.
666 if (singlemul <= 0 || singlemul > 20) {
667 if (hz >= 1500 || (hz % 128) == 0)
675 base = round_freq(timer, hz * singlemul);
676 singlemul = max((base + hz / 2) / hz, 1);
677 hz = (base + singlemul / 2) / singlemul;
682 if (div >= singlemul && (div % singlemul) == 0)
687 while ((profhz + stathz) <= 128 * 64)
689 profhz = round_freq(timer, profhz);
691 hz = round_freq(timer, hz);
692 stathz = round_freq(timer, 127);
693 profhz = round_freq(timer, stathz * 64);
696 FREQ2BT(hz, &hardperiod);
697 FREQ2BT(stathz, &statperiod);
698 FREQ2BT(profhz, &profperiod);
705 * Start per-CPU event timers on APs.
708 cpu_initclocks_ap(void)
711 struct pcpu_state *state;
713 state = DPCPU_PTR(timerstate);
716 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 && periodic) {
717 state->now = nexttick;
718 bintime_sub(&state->now, &timerperiod);
721 hardclock_sync(curcpu);
722 handleevents(&state->now, 2);
723 if (timer->et_flags & ET_FLAGS_PERCPU)
729 * Switch to profiling clock rates.
732 cpu_startprofclock(void)
736 if (profiling == 0) {
749 * Switch to regular clock rates.
752 cpu_stopprofclock(void)
756 if (profiling == 1) {
769 * Switch to idle mode (all ticks handled).
774 struct bintime now, t;
775 struct pcpu_state *state;
777 if (idletick || busy ||
778 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
779 #ifdef DEVICE_POLLING
780 || curcpu == CPU_FIRST()
784 state = DPCPU_PTR(timerstate);
789 CTR4(KTR_SPARE2, "idle at %d: now %d.%08x%08x",
790 curcpu, now.sec, (unsigned int)(now.frac >> 32),
791 (unsigned int)(now.frac & 0xffffffff));
792 getnextcpuevent(&t, 1);
795 state->nextevent = t;
802 * Switch to active mode (skip empty ticks).
805 cpu_activeclock(void)
808 struct pcpu_state *state;
811 state = DPCPU_PTR(timerstate);
812 if (state->idle == 0 || busy)
818 CTR4(KTR_SPARE2, "active at %d: now %d.%08x%08x",
819 curcpu, now.sec, (unsigned int)(now.frac >> 32),
820 (unsigned int)(now.frac & 0xffffffff));
823 td->td_intr_nesting_level++;
824 handleevents(&now, 1);
825 td->td_intr_nesting_level--;
831 clocksource_cyc_set(const struct bintime *t)
834 struct pcpu_state *state;
836 state = DPCPU_PTR(timerstate);
842 CTR4(KTR_SPARE2, "set_cyc at %d: now %d.%08x%08x",
843 curcpu, now.sec, (unsigned int)(now.frac >> 32),
844 (unsigned int)(now.frac & 0xffffffff));
845 CTR4(KTR_SPARE2, "set_cyc at %d: t %d.%08x%08x",
846 curcpu, t->sec, (unsigned int)(t->frac >> 32),
847 (unsigned int)(t->frac & 0xffffffff));
850 if (bintime_cmp(t, &state->nextcyc, ==)) {
855 if (bintime_cmp(&state->nextcyc, &state->nextevent, >=)) {
859 state->nextevent = state->nextcyc;
868 cpu_new_callout(int cpu, int ticks)
871 struct pcpu_state *state;
873 CTR3(KTR_SPARE2, "new co at %d: on %d in %d",
875 state = DPCPU_ID_PTR(cpu, timerstate);
877 if (state->idle == 0 || busy) {
882 * If timer is periodic - just update next event time for target CPU.
883 * If timer is global - there is chance it is already programmed.
885 if (periodic || (timer->et_flags & ET_FLAGS_PERCPU) == 0) {
887 bintime_mul(&tmp, ticks - 1);
888 bintime_add(&tmp, &state->nexthard);
889 if (bintime_cmp(&tmp, &state->nextevent, <))
890 state->nextevent = tmp;
892 bintime_cmp(&state->nextevent, &nexttick, >=)) {
898 * Otherwise we have to wake that CPU up, as we can't get present
899 * bintime to reprogram global timer from here. If timer is per-CPU,
900 * we by definition can't do it from here.
903 if (timer->et_flags & ET_FLAGS_PERCPU) {
905 ipi_cpu(cpu, IPI_HARDCLOCK);
907 if (!cpu_idle_wakeup(cpu))
908 ipi_cpu(cpu, IPI_AST);
914 * Report or change the active event timers hardware.
917 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
920 struct eventtimer *et;
925 snprintf(buf, sizeof(buf), "%s", et->et_name);
927 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
930 if (error != 0 || req->newptr == NULL ||
931 strcasecmp(buf, et->et_name) == 0) {
935 et = et_find(buf, 0, 0);
942 if (et->et_flags & ET_FLAGS_C3STOP)
943 cpu_disable_c3_sleep++;
944 if (timer->et_flags & ET_FLAGS_C3STOP)
945 cpu_disable_c3_sleep--;
946 periodic = want_periodic;
948 et_init(timer, timercb, NULL, NULL);
953 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
954 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
955 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
958 * Report or change the active event timer periodicity.
961 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
966 error = sysctl_handle_int(oidp, &val, 0, req);
967 if (error != 0 || req->newptr == NULL)
971 periodic = want_periodic = val;
976 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
977 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
978 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");