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_can_deep_sleep = 0; /* C3 state is available. */
58 int cpu_disable_deep_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 hardlock() 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) {
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 /* Prepare broadcasting to other CPUs for non-per-CPU timers. */
326 if ((et->et_flags & ET_FLAGS_PERCPU) == 0 && smp_started) {
328 state = DPCPU_ID_PTR(cpu, timerstate);
331 if (now >= state->nextevent) {
332 state->nextevent += SBT_1S;
343 /* Handle events for this time on this CPU. */
344 handleevents(now, 0);
347 /* Broadcast interrupt to other CPUs for non-per-CPU timers. */
352 state = DPCPU_ID_PTR(cpu, timerstate);
355 ipi_cpu(cpu, IPI_HARDCLOCK);
363 * Load new value into hardware timer.
366 loadtimer(sbintime_t now, int start)
368 struct pcpu_state *state;
374 if (timer->et_flags & ET_FLAGS_PERCPU) {
375 state = DPCPU_PTR(timerstate);
376 next = &state->nexttick;
382 * Try to start all periodic timers aligned
383 * to period to make events synchronous.
385 tmp = now % timerperiod;
386 new = timerperiod - tmp;
387 if (new < tmp) /* Left less then passed. */
389 CTR5(KTR_SPARE2, "load p at %d: now %d.%08x first in %d.%08x",
390 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff),
391 (int)(new >> 32), (u_int)(new & 0xffffffff));
393 et_start(timer, new, timerperiod);
396 new = getnextevent();
398 CTR4(KTR_SPARE2, "load at %d: next %d.%08x eq %d",
399 curcpu, (int)(new >> 32), (u_int)(new & 0xffffffff), eq);
402 et_start(timer, new - now, 0);
408 * Prepare event timer parameters after configuration changes.
415 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
417 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
419 singlemul = MIN(MAX(singlemul, 1), 20);
420 freq = hz * singlemul;
421 while (freq < (profiling ? profhz : stathz))
423 freq = round_freq(timer, freq);
424 timerperiod = SBT_1S / freq;
428 * Reconfigure specified per-CPU timer on other CPU. Called from IPI handler.
434 struct pcpu_state *state;
436 state = DPCPU_PTR(timerstate);
437 switch (atomic_load_acq_int(&state->action)) {
444 atomic_store_rel_int(&state->action, 0);
451 atomic_store_rel_int(&state->action, 0);
454 if (atomic_readandclear_int(&state->handle) && !busy) {
456 handleevents(now, 0);
463 * Reconfigure specified timer.
464 * For per-CPU timers use IPI to make other CPUs to reconfigure.
467 configtimer(int start)
469 sbintime_t now, next;
470 struct pcpu_state *state;
479 ET_HW_LOCK(DPCPU_PTR(timerstate));
481 /* Initialize time machine parameters. */
482 next = now + timerperiod;
488 state = DPCPU_ID_PTR(cpu, timerstate);
490 if (!smp_started && cpu != CPU_FIRST())
491 state->nextevent = SBT_MAX;
493 state->nextevent = next;
495 state->nexttick = next;
497 state->nexttick = -1;
498 state->nexthard = next;
499 state->nextstat = next;
500 state->nextprof = next;
501 state->nextcall = next;
502 state->nextcallopt = next;
506 /* Start global timer or per-CPU timer of this CPU. */
510 /* Stop global timer or per-CPU timer of this CPU. */
513 ET_HW_UNLOCK(DPCPU_PTR(timerstate));
515 /* If timer is global or there is no other CPUs yet - we are done. */
516 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || !smp_started) {
520 /* Set reconfigure flags for other CPUs. */
522 state = DPCPU_ID_PTR(cpu, timerstate);
523 atomic_store_rel_int(&state->action,
524 (cpu == curcpu) ? 0 : ( start ? 1 : 2));
526 /* Broadcast reconfigure IPI. */
527 ipi_all_but_self(IPI_HARDCLOCK);
528 /* Wait for reconfiguration completed. */
534 state = DPCPU_ID_PTR(cpu, timerstate);
535 if (atomic_load_acq_int(&state->action))
543 * Calculate nearest frequency supported by hardware timer.
546 round_freq(struct eventtimer *et, int freq)
550 if (et->et_frequency != 0) {
551 div = lmax((et->et_frequency + freq / 2) / freq, 1);
552 if (et->et_flags & ET_FLAGS_POW2DIV)
553 div = 1 << (flsl(div + div / 2) - 1);
554 freq = (et->et_frequency + div / 2) / div;
556 if (et->et_min_period > SBT_1S)
557 panic("Event timer \"%s\" doesn't support sub-second periods!",
559 else if (et->et_min_period != 0)
560 freq = min(freq, SBT2FREQ(et->et_min_period));
561 if (et->et_max_period < SBT_1S && et->et_max_period != 0)
562 freq = max(freq, SBT2FREQ(et->et_max_period));
567 * Configure and start event timers (BSP part).
570 cpu_initclocks_bsp(void)
572 struct pcpu_state *state;
575 mtx_init(&et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
577 state = DPCPU_ID_PTR(cpu, timerstate);
578 mtx_init(&state->et_hw_mtx, "et_hw_mtx", NULL, MTX_SPIN);
579 state->nextcall = SBT_MAX;
580 state->nextcallopt = SBT_MAX;
582 periodic = want_periodic;
583 /* Grab requested timer or the best of present. */
585 timer = et_find(timername, 0, 0);
586 if (timer == NULL && periodic) {
587 timer = et_find(NULL,
588 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
591 timer = et_find(NULL,
592 ET_FLAGS_ONESHOT, ET_FLAGS_ONESHOT);
594 if (timer == NULL && !periodic) {
595 timer = et_find(NULL,
596 ET_FLAGS_PERIODIC, ET_FLAGS_PERIODIC);
599 panic("No usable event timer found!");
600 et_init(timer, timercb, NULL, NULL);
602 /* Adapt to timer capabilities. */
603 if (periodic && (timer->et_flags & ET_FLAGS_PERIODIC) == 0)
605 else if (!periodic && (timer->et_flags & ET_FLAGS_ONESHOT) == 0)
607 if (timer->et_flags & ET_FLAGS_C3STOP)
608 cpu_disable_deep_sleep++;
611 * We honor the requested 'hz' value.
612 * We want to run stathz in the neighborhood of 128hz.
613 * We would like profhz to run as often as possible.
615 if (singlemul <= 0 || singlemul > 20) {
616 if (hz >= 1500 || (hz % 128) == 0)
624 base = round_freq(timer, hz * singlemul);
625 singlemul = max((base + hz / 2) / hz, 1);
626 hz = (base + singlemul / 2) / singlemul;
631 if (div >= singlemul && (div % singlemul) == 0)
636 while ((profhz + stathz) <= 128 * 64)
638 profhz = round_freq(timer, profhz);
640 hz = round_freq(timer, hz);
641 stathz = round_freq(timer, 127);
642 profhz = round_freq(timer, stathz * 64);
645 tick_sbt = SBT_1S / hz;
646 tick_bt = sbttobt(tick_sbt);
647 statperiod = SBT_1S / stathz;
648 profperiod = SBT_1S / profhz;
655 * Start per-CPU event timers on APs.
658 cpu_initclocks_ap(void)
661 struct pcpu_state *state;
664 state = DPCPU_PTR(timerstate);
668 hardclock_sync(curcpu);
672 td->td_intr_nesting_level++;
673 handleevents(state->now, 2);
674 td->td_intr_nesting_level--;
679 * Switch to profiling clock rates.
682 cpu_startprofclock(void)
686 if (profiling == 0) {
699 * Switch to regular clock rates.
702 cpu_stopprofclock(void)
706 if (profiling == 1) {
719 * Switch to idle mode (all ticks handled).
725 struct pcpu_state *state;
727 if (idletick || busy ||
728 (periodic && (timer->et_flags & ET_FLAGS_PERCPU))
729 #ifdef DEVICE_POLLING
730 || curcpu == CPU_FIRST()
734 state = DPCPU_PTR(timerstate);
739 CTR3(KTR_SPARE2, "idle at %d: now %d.%08x",
740 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
741 t = getnextcpuevent(1);
744 state->nextevent = t;
748 return (MAX(t - now, 0));
752 * Switch to active mode (skip empty ticks).
755 cpu_activeclock(void)
758 struct pcpu_state *state;
761 state = DPCPU_PTR(timerstate);
762 if (state->idle == 0 || busy)
768 CTR3(KTR_SPARE2, "active at %d: now %d.%08x",
769 curcpu, (int)(now >> 32), (u_int)(now & 0xffffffff));
772 td->td_intr_nesting_level++;
773 handleevents(now, 1);
774 td->td_intr_nesting_level--;
779 * Change the frequency of the given timer. This changes et->et_frequency and
780 * if et is the active timer it reconfigures the timer on all CPUs. This is
781 * intended to be a private interface for the use of et_change_frequency() only.
784 cpu_et_frequency(struct eventtimer *et, uint64_t newfreq)
790 et->et_frequency = newfreq;
793 et->et_frequency = newfreq;
798 cpu_new_callout(int cpu, sbintime_t bt, sbintime_t bt_opt)
800 struct pcpu_state *state;
802 /* Do not touch anything if somebody reconfiguring timers. */
805 CTR6(KTR_SPARE2, "new co at %d: on %d at %d.%08x - %d.%08x",
806 curcpu, cpu, (int)(bt_opt >> 32), (u_int)(bt_opt & 0xffffffff),
807 (int)(bt >> 32), (u_int)(bt & 0xffffffff));
808 state = DPCPU_ID_PTR(cpu, timerstate);
812 * If there is callout time already set earlier -- do nothing.
813 * This check may appear redundant because we check already in
814 * callout_process() but this double check guarantees we're safe
815 * with respect to race conditions between interrupts execution
818 state->nextcallopt = bt_opt;
819 if (bt >= state->nextcall)
821 state->nextcall = bt;
822 /* If there is some other event set earlier -- do nothing. */
823 if (bt >= state->nextevent)
825 state->nextevent = bt;
826 /* If timer is periodic -- there is nothing to reprogram. */
829 /* If timer is global or of the current CPU -- reprogram it. */
830 if ((timer->et_flags & ET_FLAGS_PERCPU) == 0 || cpu == curcpu) {
831 loadtimer(sbinuptime(), 0);
836 /* Otherwise make other CPU to reprogram it. */
840 ipi_cpu(cpu, IPI_HARDCLOCK);
845 * Report or change the active event timers hardware.
848 sysctl_kern_eventtimer_timer(SYSCTL_HANDLER_ARGS)
851 struct eventtimer *et;
856 snprintf(buf, sizeof(buf), "%s", et->et_name);
858 error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
861 if (error != 0 || req->newptr == NULL ||
862 strcasecmp(buf, et->et_name) == 0) {
866 et = et_find(buf, 0, 0);
873 if (et->et_flags & ET_FLAGS_C3STOP)
874 cpu_disable_deep_sleep++;
875 if (timer->et_flags & ET_FLAGS_C3STOP)
876 cpu_disable_deep_sleep--;
877 periodic = want_periodic;
879 et_init(timer, timercb, NULL, NULL);
884 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, timer,
885 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
886 0, 0, sysctl_kern_eventtimer_timer, "A", "Chosen event timer");
889 * Report or change the active event timer periodicity.
892 sysctl_kern_eventtimer_periodic(SYSCTL_HANDLER_ARGS)
897 error = sysctl_handle_int(oidp, &val, 0, req);
898 if (error != 0 || req->newptr == NULL)
902 periodic = want_periodic = val;
907 SYSCTL_PROC(_kern_eventtimer, OID_AUTO, periodic,
908 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
909 0, 0, sysctl_kern_eventtimer_periodic, "I", "Enable event timer periodic mode");