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 hardclock() 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 #ifdef EARLY_AP_STARTUP
326 MPASS(mp_ncpus == 1 || smp_started);
328 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
330 #ifdef EARLY_AP_STARTUP
331 if ((et->et_flags & ET_FLAGS_PERCPU) == 0) {
333 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
336 state = DPCPU_ID_PTR(cpu, timerstate);
339 if (now >= state->nextevent) {
340 state->nextevent += SBT_1S;
351 /* Handle events for this time on this CPU. */
352 handleevents(now, 0);
355 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
360 state = DPCPU_ID_PTR(cpu, timerstate);
363 ipi_cpu(cpu, IPI_HARDCLOCK);
371 * Load new value into hardware timer.
374 loadtimer(sbintime_t now, int start)
376 struct pcpu_state *state;
382 if (timer->et_flags & ET_FLAGS_PERCPU) {
383 state = DPCPU_PTR(timerstate);
384 next = &state->nexttick;
390 * Try to start all periodic timers aligned
391 * to period to make events synchronous.
393 tmp = now % timerperiod;
394 new = timerperiod - tmp;
395 if (new < tmp) /* Left less then passed. */
397 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
398 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
399 (int)(new >> 32), (u_int)(new & 0xffffffff));
401 et_start(timer, new, timerperiod);
404 new = getnextevent();
406 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
407 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
410 et_start(timer, new - now, 0);
416 * Prepare event timer parameters after configuration changes.
423 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
425 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
427 singlemul = MIN(MAX(singlemul, 1), 20);
428 freq = hz * singlemul;
429 while (freq < (profiling ? profhz : stathz))
431 freq = round_freq(timer, freq);
432 timerperiod = SBT_1S / freq;
436 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
442 struct pcpu_state *state;
444 state = DPCPU_PTR(timerstate);
445 switch (atomic_load_acq_int(&state->action)) {
452 atomic_store_rel_int(&state->action, 0);
459 atomic_store_rel_int(&state->action, 0);
462 if (atomic_readandclear_int(&state->handle) && !busy) {
464 handleevents(now, 0);
471 * Reconfigure specified timer.
472 * For per-CPU timers use IPI to make other CPUs to reconfigure.
475 configtimer(int start)
477 sbintime_t now, next;
478 struct pcpu_state *state;
487 ET_HW_LOCK(DPCPU_PTR(timerstate));
489 /* Initialize time machine parameters. */
490 next = now + timerperiod;
495 #ifdef EARLY_AP_STARTUP
496 MPASS(mp_ncpus == 1 || smp_started);
499 state = DPCPU_ID_PTR(cpu, timerstate);
501 #ifndef EARLY_AP_STARTUP
502 if (!smp_started && cpu != CPU_FIRST())
503 state->nextevent = SBT_MAX;
506 state->nextevent = next;
508 state->nexttick = next;
510 state->nexttick = -1;
511 state->nexthard = next;
512 state->nextstat = next;
513 state->nextprof = next;
514 state->nextcall = next;
515 state->nextcallopt = next;
519 /* Start global timer or per-CPU timer of this CPU. */
523 /* Stop global timer or per-CPU timer of this CPU. */
526 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
528 #ifdef EARLY_AP_STARTUP
529 /* If timer is global we are done. */
530 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
532 /* If timer is global or there is no other CPUs yet - we are done. */
533 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
538 /* Set reconfigure flags for other CPUs. */
540 state = DPCPU_ID_PTR(cpu, timerstate);
541 atomic_store_rel_int(&state->action,
542 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
544 /* Broadcast reconfigure IPI. */
545 ipi_all_but_self(IPI_HARDCLOCK);
546 /* Wait for reconfiguration completed. */
552 state = DPCPU_ID_PTR(cpu, timerstate);
553 if (atomic_load_acq_int(&state->action))
561 * Calculate nearest frequency supported by hardware timer.
564 round_freq(struct eventtimer *et, int freq)
568 if (et->et_frequency != 0) {
569 div = lmax((et->et_frequency + freq / 2) / freq, 1);
570 if (et->et_flags & ET_FLAGS_POW2DIV)
571 div = 1 << (flsl(div + div / 2) - 1);
572 freq = (et->et_frequency + div / 2) / div;
574 if (et->et_min_period > SBT_1S)
575 panic("Event timer \"%s\" doesn't support sub-second periods!",
577 else if (et->et_min_period != 0)
578 freq = min(freq, SBT2FREQ(et->et_min_period));
579 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
580 freq = max(freq, SBT2FREQ(et->et_max_period));
585 * Configure and start event timers (BSP part).
588 cpu_initclocks_bsp(void)
590 struct pcpu_state *state;
593 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
595 state = DPCPU_ID_PTR(cpu, timerstate);
596 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
597 state->nextcall = SBT_MAX;
598 state->nextcallopt = SBT_MAX;
600 periodic = want_periodic;
601 /* Grab requested timer or the best of present. */
603 timer = et_find(timername, 0, 0);
604 if (timer == NULL && periodic) {
605 timer = et_find(NULL,
606 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
609 timer = et_find(NULL,
610 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
612 if (timer == NULL && !periodic) {
613 timer = et_find(NULL,
614 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
617 panic("No usable event timer found!");
618 et_init(timer, timercb, NULL, NULL);
620 /* Adapt to timer capabilities. */
621 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
623 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
625 if (timer->et_flags & ET_FLAGS_C3STOP)
626 cpu_disable_c3_sleep++;
629 * We honor the requested 'hz' value.
630 * We want to run stathz in the neighborhood of 128hz.
631 * We would like profhz to run as often as possible.
633 if (singlemul <= 0 || singlemul > 20) {
634 if (hz >= 1500 || (hz % 128) == 0)
642 base = round_freq(timer, hz * singlemul);
643 singlemul = max((base + hz / 2) / hz, 1);
644 hz = (base + singlemul / 2) / singlemul;
649 if (div >= singlemul && (div % singlemul) == 0)
654 while ((profhz + stathz) <= 128 * 64)
656 profhz = round_freq(timer, profhz);
658 hz = round_freq(timer, hz);
659 stathz = round_freq(timer, 127);
660 profhz = round_freq(timer, stathz * 64);
663 tick_sbt = SBT_1S / hz;
664 tick_bt = sbttobt(tick_sbt);
665 statperiod = SBT_1S / stathz;
666 profperiod = SBT_1S / profhz;
673 * Start per-CPU event timers on APs.
676 cpu_initclocks_ap(void)
679 struct pcpu_state *state;
682 state = DPCPU_PTR(timerstate);
686 hardclock_sync(curcpu);
690 td->td_intr_nesting_level++;
691 handleevents(state->now, 2);
692 td->td_intr_nesting_level--;
697 * Switch to profiling clock rates.
700 cpu_startprofclock(void)
704 if (profiling == 0) {
717 * Switch to regular clock rates.
720 cpu_stopprofclock(void)
724 if (profiling == 1) {
737 * Switch to idle mode (all ticks handled).
743 struct pcpu_state *state;
745 if (idletick || busy ||
746 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
747 #ifdef DEVICE_POLLING
748 || curcpu == CPU_FIRST()
752 state = DPCPU_PTR(timerstate);
757 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
758 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
759 t = getnextcpuevent(1);
762 state->nextevent = t;
766 return (MAX(t - now, 0));
770 * Switch to active mode (skip empty ticks).
773 cpu_activeclock(void)
776 struct pcpu_state *state;
779 state = DPCPU_PTR(timerstate);
780 if (state->idle == 0 || busy)
786 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
787 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
790 td->td_intr_nesting_level++;
791 handleevents(now, 1);
792 td->td_intr_nesting_level--;
797 * Change the frequency of the given timer. This changes et->et_frequency and
798 * if et is the active timer it reconfigures the timer on all CPUs. This is
799 * intended to be a private interface for the use of et_change_frequency() only.
802 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
808 et->et_frequency = newfreq;
811 et->et_frequency = newfreq;
816 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
818 struct pcpu_state *state;
820 /* Do not touch anything if somebody reconfiguring timers. */
823 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
824 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
825 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
826 state = DPCPU_ID_PTR(cpu, timerstate);
830 * If there is callout time already set earlier -- do nothing.
831 * This check may appear redundant because we check already in
832 * callout_process() but this double check guarantees we're safe
833 * with respect to race conditions between interrupts execution
836 state->nextcallopt = bt_opt;
837 if (bt >= state->nextcall)
839 state->nextcall = bt;
840 /* If there is some other event set earlier -- do nothing. */
841 if (bt >= state->nextevent)
843 state->nextevent = bt;
844 /* If timer is periodic -- there is nothing to reprogram. */
847 /* If timer is global or of the current CPU -- reprogram it. */
848 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
849 loadtimer(sbinuptime(), 0);
854 /* Otherwise make other CPU to reprogram it. */
858 ipi_cpu(cpu, IPI_HARDCLOCK);
863 * Report or change the active event timers hardware.
866 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
869 struct eventtimer *et;
874 snprintf(buf, sizeof(buf), "%s", et->et_name);
876 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
879 if (error != 0 || req->newptr == NULL ||
880 strcasecmp(buf, et->et_name) == 0) {
884 et = et_find(buf, 0, 0);
891 if (et->et_flags & ET_FLAGS_C3STOP)
892 cpu_disable_c3_sleep++;
893 if (timer->et_flags & ET_FLAGS_C3STOP)
894 cpu_disable_c3_sleep--;
895 periodic = want_periodic;
897 et_init(timer, timercb, NULL, NULL);
902 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
903 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
904 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
907 * Report or change the active event timer periodicity.
910 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
915 error = sysctl_handle_int(oidp, &val, 0, req);
916 if (error != 0 || req->newptr == NULL)
920 periodic = want_periodic = val;
925 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
926 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
927 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");
934 DB_SHOW_COMMAND(clocksource, db_show_clocksource)
936 struct pcpu_state *st;
940 st = DPCPU_ID_PTR(c, timerstate);
942 "CPU %2d: action %d handle %d ipi %d idle %d\n"
943 " now %#jx nevent %#jx (%jd)\n"
944 " ntick %#jx (%jd) nhard %#jx (%jd)\n"
945 " nstat %#jx (%jd) nprof %#jx (%jd)\n"
946 " ncall %#jx (%jd) ncallopt %#jx (%jd)\n",
947 c, st->action, st->handle, st->ipi, st->idle,
949 (uintmax_t)st->nextevent,
950 (uintmax_t)(st->nextevent - st->now) / tick_sbt,
951 (uintmax_t)st->nexttick,
952 (uintmax_t)(st->nexttick - st->now) / tick_sbt,
953 (uintmax_t)st->nexthard,
954 (uintmax_t)(st->nexthard - st->now) / tick_sbt,
955 (uintmax_t)st->nextstat,
956 (uintmax_t)(st->nextstat - st->now) / tick_sbt,
957 (uintmax_t)st->nextprof,
958 (uintmax_t)(st->nextprof - st->now) / tick_sbt,
959 (uintmax_t)st->nextcall,
960 (uintmax_t)(st->nextcall - st->now) / tick_sbt,
961 (uintmax_t)st->nextcallopt,
962 (uintmax_t)(st->nextcallopt - st->now) / tick_sbt);