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_disable_c2_sleep = 0; /* Timer dies in C2. */
58 int cpu_disable_c3_sleep = 0; /* Timer dies in C3. */
60 static void setuptimer(void);
61 static void loadtimer(sbintime_t now, int first);
62 static int doconfigtimer(void);
63 static void configtimer(int start);
64 static int round_freq(struct eventtimer *et, int freq);
66 static sbintime_t getnextcpuevent(int idle);
67 static sbintime_t getnextevent(void);
68 static int handleevents(sbintime_t now, int fake);
70 static struct mtx et_hw_mtx;
72 #define ET_HW_LOCK(state) \
74 if (timer->et_flags & ET_FLAGS_PERCPU) \
75 mtx_lock_spin(&(state)->et_hw_mtx); \
77 mtx_lock_spin(&et_hw_mtx); \
80 #define ET_HW_UNLOCK(state) \
82 if (timer->et_flags & ET_FLAGS_PERCPU) \
83 mtx_unlock_spin(&(state)->et_hw_mtx); \
85 mtx_unlock_spin(&et_hw_mtx); \
88 static struct eventtimer *timer = NULL;
89 static sbintime_t timerperiod; /* Timer period for periodic mode. */
90 static sbintime_t statperiod; /* statclock() events period. */
91 static sbintime_t profperiod; /* profclock() events period. */
92 static sbintime_t nexttick; /* Next global timer tick time. */
93 static u_int busy = 1; /* Reconfiguration is in progress. */
94 static int profiling; /* Profiling events enabled. */
96 static char timername[32]; /* Wanted timer. */
97 TUNABLE_STR("kern.eventtimer.timer", timername, sizeof(timername));
99 static int singlemul; /* Multiplier for periodic mode. */
100 SYSCTL_INT(_kern_eventtimer, OID_AUTO, singlemul, CTLFLAG_RWTUN, &singlemul,
101 0, "Multiplier for periodic mode");
103 static u_int idletick; /* Run periodic events when idle. */
104 SYSCTL_UINT(_kern_eventtimer, OID_AUTO, idletick, CTLFLAG_RWTUN, &idletick,
105 0, "Run periodic events when idle");
107 static int periodic; /* Periodic or one-shot mode. */
108 static int want_periodic; /* What mode to prefer. */
109 TUNABLE_INT("kern.eventtimer.periodic", &want_periodic);
112 struct mtx et_hw_mtx; /* Per-CPU timer mutex. */
113 u_int action; /* Reconfiguration requests. */
114 u_int handle; /* Immediate handle resuests. */
115 sbintime_t now; /* Last tick time. */
116 sbintime_t nextevent; /* Next scheduled event on this CPU. */
117 sbintime_t nexttick; /* Next timer tick time. */
118 sbintime_t nexthard; /* Next hardclock() event. */
119 sbintime_t nextstat; /* Next statclock() event. */
120 sbintime_t nextprof; /* Next profclock() event. */
121 sbintime_t nextcall; /* Next callout event. */
122 sbintime_t nextcallopt; /* Next optional callout event. */
123 int ipi; /* This CPU needs IPI. */
124 int idle; /* This CPU is in idle mode. */
127 static DPCPU_DEFINE(struct pcpu_state, timerstate);
128 DPCPU_DEFINE(sbintime_t, hardclocktime);
131 * Timer broadcast IPI handler.
137 struct pcpu_state *state;
140 if (doconfigtimer() || busy)
141 return (FILTER_HANDLED);
142 state = DPCPU_PTR(timerstate);
144 CTR3(KTR_SPARE2, "ipi at %d: now %d.%08x",
145 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
146 done = handleevents(now, 0);
147 return (done ? FILTER_HANDLED : FILTER_STRAY);
151 * Handle all events for specified time on this CPU
154 handleevents(sbintime_t now, int fake)
157 struct trapframe *frame;
158 struct pcpu_state *state;
162 CTR3(KTR_SPARE2, "handle at %d: now %d.%08x",
163 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
169 frame = curthread->td_intr_frame;
170 usermode = TRAPF_USERMODE(frame);
173 state = DPCPU_PTR(timerstate);
176 while (now >= state->nexthard) {
177 state->nexthard += tick_sbt;
181 hct = DPCPU_PTR(hardclocktime);
182 *hct = state->nexthard - tick_sbt;
184 hardclock_cnt(runs, usermode);
189 while (now >= state->nextstat) {
190 state->nextstat += statperiod;
193 if (runs && fake < 2) {
194 statclock_cnt(runs, usermode);
199 while (now >= state->nextprof) {
200 state->nextprof += profperiod;
204 profclock_cnt(runs, usermode, TRAPF_PC(frame));
208 state->nextprof = state->nextstat;
209 if (now >= state->nextcallopt || now >= state->nextcall) {
210 state->nextcall = state->nextcallopt = SBT_MAX;
211 callout_process(now);
214 t = getnextcpuevent(0);
218 state->nextevent = t;
219 loadtimer(now, (fake == 2) &&
220 (timer->et_flags & ET_FLAGS_PERCPU));
227 * Schedule binuptime of the next event on current CPU.
230 getnextcpuevent(int idle)
233 struct pcpu_state *state;
236 state = DPCPU_PTR(timerstate);
237 /* Handle hardclock() events, skipping some if CPU is idle. */
238 event = state->nexthard;
240 hardfreq = (u_int)hz / 2;
241 if (tc_min_ticktock_freq > 2
243 && curcpu == CPU_FIRST()
246 hardfreq = hz / tc_min_ticktock_freq;
248 event += tick_sbt * (hardfreq - 1);
250 /* Handle callout events. */
251 if (event > state->nextcall)
252 event = state->nextcall;
253 if (!idle) { /* If CPU is active - handle other types of events. */
254 if (event > state->nextstat)
255 event = state->nextstat;
256 if (profiling && event > state->nextprof)
257 event = state->nextprof;
263 * Schedule binuptime of the next event on all CPUs.
268 struct pcpu_state *state;
275 state = DPCPU_PTR(timerstate);
276 event = state->nextevent;
279 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
281 state = DPCPU_ID_PTR(cpu, timerstate);
282 if (event > state->nextevent) {
283 event = state->nextevent;
289 CTR4(KTR_SPARE2, "next at %d: next %d.%08x by %d",
290 curcpu, (int)(event >> 32), (u_int)(event & 0xffffffff), c);
294 /* Hardware timer callback function. */
296 timercb(struct eventtimer *et, void *arg)
300 struct pcpu_state *state;
305 /* Do not touch anything if somebody reconfiguring timers. */
308 /* Update present and next tick times. */
309 state = DPCPU_PTR(timerstate);
310 if (et->et_flags & ET_FLAGS_PERCPU) {
311 next = &state->nexttick;
316 *next = now + timerperiod;
318 *next = -1; /* Next tick is not scheduled yet. */
320 CTR3(KTR_SPARE2, "intr at %d: now %d.%08x",
321 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
324 #ifdef EARLY_AP_STARTUP
325 MPASS(mp_ncpus == 1 || smp_started);
327 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
329 #ifdef EARLY_AP_STARTUP
330 if ((et->et_flags & ET_FLAGS_PERCPU) == 0) {
332 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
335 state = DPCPU_ID_PTR(cpu, timerstate);
338 if (now >= state->nextevent) {
339 state->nextevent += SBT_1S;
350 /* Handle events for this time on this CPU. */
351 handleevents(now, 0);
354 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
359 state = DPCPU_ID_PTR(cpu, timerstate);
362 ipi_cpu(cpu, IPI_HARDCLOCK);
370 * Load new value into hardware timer.
373 loadtimer(sbintime_t now, int start)
375 struct pcpu_state *state;
381 if (timer->et_flags & ET_FLAGS_PERCPU) {
382 state = DPCPU_PTR(timerstate);
383 next = &state->nexttick;
389 * Try to start all periodic timers aligned
390 * to period to make events synchronous.
392 tmp = now % timerperiod;
393 new = timerperiod - tmp;
394 if (new < tmp) /* Left less then passed. */
396 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
397 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
398 (int)(new >> 32), (u_int)(new & 0xffffffff));
400 et_start(timer, new, timerperiod);
403 new = getnextevent();
405 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
406 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
409 et_start(timer, new - now, 0);
415 * Prepare event timer parameters after configuration changes.
422 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
424 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
426 singlemul = MIN(MAX(singlemul, 1), 20);
427 freq = hz * singlemul;
428 while (freq < (profiling ? profhz : stathz))
430 freq = round_freq(timer, freq);
431 timerperiod = SBT_1S / freq;
435 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
441 struct pcpu_state *state;
443 state = DPCPU_PTR(timerstate);
444 switch (atomic_load_acq_int(&state->action)) {
451 atomic_store_rel_int(&state->action, 0);
458 atomic_store_rel_int(&state->action, 0);
461 if (atomic_readandclear_int(&state->handle) && !busy) {
463 handleevents(now, 0);
470 * Reconfigure specified timer.
471 * For per-CPU timers use IPI to make other CPUs to reconfigure.
474 configtimer(int start)
476 sbintime_t now, next;
477 struct pcpu_state *state;
486 ET_HW_LOCK(DPCPU_PTR(timerstate));
488 /* Initialize time machine parameters. */
489 next = now + timerperiod;
494 #ifdef EARLY_AP_STARTUP
495 MPASS(mp_ncpus == 1 || smp_started);
498 state = DPCPU_ID_PTR(cpu, timerstate);
500 #ifndef EARLY_AP_STARTUP
501 if (!smp_started && cpu != CPU_FIRST())
502 state->nextevent = SBT_MAX;
505 state->nextevent = next;
507 state->nexttick = next;
509 state->nexttick = -1;
510 state->nexthard = next;
511 state->nextstat = next;
512 state->nextprof = next;
513 state->nextcall = next;
514 state->nextcallopt = next;
518 /* Start global timer or per-CPU timer of this CPU. */
522 /* Stop global timer or per-CPU timer of this CPU. */
525 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
527 #ifdef EARLY_AP_STARTUP
528 /* If timer is global we are done. */
529 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0) {
531 /* If timer is global or there is no other CPUs yet - we are done. */
532 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
537 /* Set reconfigure flags for other CPUs. */
539 state = DPCPU_ID_PTR(cpu, timerstate);
540 atomic_store_rel_int(&state->action,
541 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
543 /* Broadcast reconfigure IPI. */
544 ipi_all_but_self(IPI_HARDCLOCK);
545 /* Wait for reconfiguration completed. */
551 state = DPCPU_ID_PTR(cpu, timerstate);
552 if (atomic_load_acq_int(&state->action))
560 * Calculate nearest frequency supported by hardware timer.
563 round_freq(struct eventtimer *et, int freq)
567 if (et->et_frequency != 0) {
568 div = lmax((et->et_frequency + freq / 2) / freq, 1);
569 if (et->et_flags & ET_FLAGS_POW2DIV)
570 div = 1 << (flsl(div + div / 2) - 1);
571 freq = (et->et_frequency + div / 2) / div;
573 if (et->et_min_period > SBT_1S)
574 panic("Event timer \"%s\" doesn't support sub-second periods!",
576 else if (et->et_min_period != 0)
577 freq = min(freq, SBT2FREQ(et->et_min_period));
578 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
579 freq = max(freq, SBT2FREQ(et->et_max_period));
584 * Configure and start event timers (BSP part).
587 cpu_initclocks_bsp(void)
589 struct pcpu_state *state;
592 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
594 state = DPCPU_ID_PTR(cpu, timerstate);
595 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
596 state->nextcall = SBT_MAX;
597 state->nextcallopt = SBT_MAX;
599 periodic = want_periodic;
600 /* Grab requested timer or the best of present. */
602 timer = et_find(timername, 0, 0);
603 if (timer == NULL && periodic) {
604 timer = et_find(NULL,
605 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
608 timer = et_find(NULL,
609 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
611 if (timer == NULL && !periodic) {
612 timer = et_find(NULL,
613 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
616 panic("No usable event timer found!");
617 et_init(timer, timercb, NULL, NULL);
619 /* Adapt to timer capabilities. */
620 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
622 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
624 if (timer->et_flags & ET_FLAGS_C3STOP)
625 cpu_disable_c3_sleep++;
628 * We honor the requested 'hz' value.
629 * We want to run stathz in the neighborhood of 128hz.
630 * We would like profhz to run as often as possible.
632 if (singlemul <= 0 || singlemul > 20) {
633 if (hz >= 1500 || (hz % 128) == 0)
641 base = round_freq(timer, hz * singlemul);
642 singlemul = max((base + hz / 2) / hz, 1);
643 hz = (base + singlemul / 2) / singlemul;
648 if (div >= singlemul && (div % singlemul) == 0)
653 while ((profhz + stathz) <= 128 * 64)
655 profhz = round_freq(timer, profhz);
657 hz = round_freq(timer, hz);
658 stathz = round_freq(timer, 127);
659 profhz = round_freq(timer, stathz * 64);
662 tick_sbt = SBT_1S / hz;
663 tick_bt = sbttobt(tick_sbt);
664 statperiod = SBT_1S / stathz;
665 profperiod = SBT_1S / profhz;
672 * Start per-CPU event timers on APs.
675 cpu_initclocks_ap(void)
678 struct pcpu_state *state;
681 state = DPCPU_PTR(timerstate);
685 hardclock_sync(curcpu);
689 td->td_intr_nesting_level++;
690 handleevents(state->now, 2);
691 td->td_intr_nesting_level--;
696 * Switch to profiling clock rates.
699 cpu_startprofclock(void)
703 if (profiling == 0) {
716 * Switch to regular clock rates.
719 cpu_stopprofclock(void)
723 if (profiling == 1) {
736 * Switch to idle mode (all ticks handled).
742 struct pcpu_state *state;
744 if (idletick || busy ||
745 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
746 #ifdef DEVICE_POLLING
747 || curcpu == CPU_FIRST()
751 state = DPCPU_PTR(timerstate);
756 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
757 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
758 t = getnextcpuevent(1);
761 state->nextevent = t;
765 return (MAX(t - now, 0));
769 * Switch to active mode (skip empty ticks).
772 cpu_activeclock(void)
775 struct pcpu_state *state;
778 state = DPCPU_PTR(timerstate);
779 if (state->idle == 0 || busy)
785 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
786 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
789 td->td_intr_nesting_level++;
790 handleevents(now, 1);
791 td->td_intr_nesting_level--;
796 * Change the frequency of the given timer. This changes et->et_frequency and
797 * if et is the active timer it reconfigures the timer on all CPUs. This is
798 * intended to be a private interface for the use of et_change_frequency() only.
801 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
807 et->et_frequency = newfreq;
810 et->et_frequency = newfreq;
815 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
817 struct pcpu_state *state;
819 /* Do not touch anything if somebody reconfiguring timers. */
822 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
823 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
824 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
825 state = DPCPU_ID_PTR(cpu, timerstate);
829 * If there is callout time already set earlier -- do nothing.
830 * This check may appear redundant because we check already in
831 * callout_process() but this double check guarantees we're safe
832 * with respect to race conditions between interrupts execution
835 state->nextcallopt = bt_opt;
836 if (bt >= state->nextcall)
838 state->nextcall = bt;
839 /* If there is some other event set earlier -- do nothing. */
840 if (bt >= state->nextevent)
842 state->nextevent = bt;
843 /* If timer is periodic -- there is nothing to reprogram. */
846 /* If timer is global or of the current CPU -- reprogram it. */
847 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
848 loadtimer(sbinuptime(), 0);
853 /* Otherwise make other CPU to reprogram it. */
857 ipi_cpu(cpu, IPI_HARDCLOCK);
862 * Report or change the active event timers hardware.
865 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
868 struct eventtimer *et;
873 snprintf(buf, sizeof(buf), "%s", et->et_name);
875 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
878 if (error != 0 || req->newptr == NULL ||
879 strcasecmp(buf, et->et_name) == 0) {
883 et = et_find(buf, 0, 0);
890 if (et->et_flags & ET_FLAGS_C3STOP)
891 cpu_disable_c3_sleep++;
892 if (timer->et_flags & ET_FLAGS_C3STOP)
893 cpu_disable_c3_sleep--;
894 periodic = want_periodic;
896 et_init(timer, timercb, NULL, NULL);
901 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
902 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
903 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
906 * Report or change the active event timer periodicity.
909 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
914 error = sysctl_handle_int(oidp, &val, 0, req);
915 if (error != 0 || req->newptr == NULL)
919 periodic = want_periodic = val;
924 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
925 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
926 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");
933 DB_SHOW_COMMAND(clocksource, db_show_clocksource)
935 struct pcpu_state *st;
939 st = DPCPU_ID_PTR(c, timerstate);
941 "CPU %2d: action %d handle %d ipi %d idle %d\n"
942 " now %#jx nevent %#jx (%jd)\n"
943 " ntick %#jx (%jd) nhard %#jx (%jd)\n"
944 " nstat %#jx (%jd) nprof %#jx (%jd)\n"
945 " ncall %#jx (%jd) ncallopt %#jx (%jd)\n",
946 c, st->action, st->handle, st->ipi, st->idle,
948 (uintmax_t)st->nextevent,
949 (uintmax_t)(st->nextevent - st->now) / tick_sbt,
950 (uintmax_t)st->nexttick,
951 (uintmax_t)(st->nexttick - st->now) / tick_sbt,
952 (uintmax_t)st->nexthard,
953 (uintmax_t)(st->nexthard - st->now) / tick_sbt,
954 (uintmax_t)st->nextstat,
955 (uintmax_t)(st->nextstat - st->now) / tick_sbt,
956 (uintmax_t)st->nextprof,
957 (uintmax_t)(st->nextprof - st->now) / tick_sbt,
958 (uintmax_t)st->nextcall,
959 (uintmax_t)(st->nextcall - st->now) / tick_sbt,
960 (uintmax_t)st->nextcallopt,
961 (uintmax_t)(st->nextcallopt - st->now) / tick_sbt);