2 * ntp_timer.c - event timer support routines
8 #include "ntp_machine.h"
10 #include "ntp_stdlib.h"
11 #include "ntp_calendar.h"
12 #include "ntp_leapsec.h"
14 #if defined(HAVE_IO_COMPLETION_PORT)
15 # include "ntp_iocompletionport.h"
16 # include "ntp_timer.h"
21 #ifdef HAVE_SYS_SIGNAL_H
22 # include <sys/signal.h>
29 #include "ntp_syscall.h"
30 #endif /* KERNEL_PLL */
33 #include <openssl/rand.h>
37 /* TC_ERR represents the timer_create() error return value. */
45 static void check_leapsec(u_int32, const time_t*, int/*BOOL*/);
48 * These routines provide support for the event timer. The timer is
49 * implemented by an interrupt routine which sets a flag once every
50 * second, and a timer routine which is called when the mainline code
51 * gets around to seeing the flag. The timer routine dispatches the
52 * clock adjustment code if its time has come, then searches the timer
53 * queue for expiries which are dispatched to the transmit procedure.
54 * Finally, we call the hourly procedure to do cleanup and print a
57 volatile int interface_interval; /* init_io() sets def. 300s */
60 * Initializing flag. All async routines watch this and only do their
61 * thing when it is clear.
66 * Alarm flag. The mainline code imports this.
68 volatile int alarm_flag;
71 * The counters and timeouts
73 static u_long interface_timer; /* interface update timer */
74 static u_long adjust_timer; /* second timer */
75 static u_long stats_timer; /* stats timer */
76 static u_long leapf_timer; /* Report leapfile problems once/day */
77 static u_long huffpuff_timer; /* huff-n'-puff timer */
78 static u_long worker_idle_timer;/* next check for idle intres */
79 u_long leapsec; /* seconds to next leap (proximity class) */
80 int leapdif; /* TAI difference step at next leap second*/
81 u_long orphwait; /* orphan wait time */
83 static u_long revoke_timer; /* keys revoke timer */
84 static u_long keys_timer; /* session key timer */
85 u_long sys_revoke = KEY_REVOKE; /* keys revoke timeout (log2 s) */
86 u_long sys_automax = NTP_AUTOMAX; /* key list timeout (log2 s) */
90 * Statistics counter for the interested.
92 volatile u_long alarm_overflow;
94 u_long current_time; /* seconds since startup */
97 * Stats. Number of overflows and number of calls to transmit().
99 u_long timer_timereset;
100 u_long timer_overflows;
101 u_long timer_xmtcalls;
104 static int vmstimer[2]; /* time for next timer AST */
105 static int vmsinc[2]; /* timer increment */
109 HANDLE WaitableTimerHandle;
111 static RETSIGTYPE alarming (int);
112 #endif /* SYS_WINNT */
115 # if !defined SYS_WINNT || defined(SYS_CYGWIN32)
116 # ifdef HAVE_TIMER_CREATE
117 static timer_t timer_id;
118 typedef struct itimerspec intervaltimer;
119 # define itv_frac tv_nsec
121 typedef struct itimerval intervaltimer;
122 # define itv_frac tv_usec
124 intervaltimer itimer;
128 #if !defined(SYS_WINNT) && !defined(VMS)
129 void set_timer_or_die(const intervaltimer *);
133 #if !defined(SYS_WINNT) && !defined(VMS)
136 const intervaltimer * ptimer
139 const char * setfunc;
142 # ifdef HAVE_TIMER_CREATE
143 setfunc = "timer_settime";
144 rc = timer_settime(timer_id, 0, &itimer, NULL);
146 setfunc = "setitimer";
147 rc = setitimer(ITIMER_REAL, &itimer, NULL);
150 msyslog(LOG_ERR, "interval timer %s failed, %m",
155 #endif /* !SYS_WINNT && !VMS */
159 * reinit_timer - reinitialize interval timer after a clock step.
164 #if !defined(SYS_WINNT) && !defined(VMS)
166 # ifdef HAVE_TIMER_CREATE
167 timer_gettime(timer_id, &itimer);
169 getitimer(ITIMER_REAL, &itimer);
171 if (itimer.it_value.tv_sec < 0 ||
172 itimer.it_value.tv_sec > (1 << EVENT_TIMEOUT))
173 itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
174 if (itimer.it_value.itv_frac < 0)
175 itimer.it_value.itv_frac = 0;
176 if (0 == itimer.it_value.tv_sec &&
177 0 == itimer.it_value.itv_frac)
178 itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
179 itimer.it_interval.tv_sec = (1 << EVENT_TIMEOUT);
180 itimer.it_interval.itv_frac = 0;
181 set_timer_or_die(&itimer);
187 * init_timer - initialize the timer data structures
198 stats_timer = SECSPERHR;
199 leapf_timer = SECSPERDAY;
209 * Set up the alarm interrupt. The first comes 2**EVENT_TIMEOUT
210 * seconds from now and they continue on every 2**EVENT_TIMEOUT
214 # ifdef HAVE_TIMER_CREATE
215 if (TC_ERR == timer_create(CLOCK_REALTIME, NULL, &timer_id)) {
216 msyslog(LOG_ERR, "timer_create failed, %m");
220 signal_no_reset(SIGALRM, alarming);
221 itimer.it_interval.tv_sec =
222 itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
223 itimer.it_interval.itv_frac = itimer.it_value.itv_frac = 0;
224 set_timer_or_die(&itimer);
225 # else /* VMS follows */
226 vmsinc[0] = 10000000; /* 1 sec */
228 lib$emul(&(1<<EVENT_TIMEOUT), &vmsinc, &0, &vmsinc);
230 sys$gettim(&vmstimer); /* that's "now" as abstime */
232 lib$addx(&vmsinc, &vmstimer, &vmstimer);
233 sys$setimr(0, &vmstimer, alarming, alarming, 0);
235 #else /* SYS_WINNT follows */
237 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
241 WaitableTimerHandle = CreateWaitableTimer(NULL, FALSE, NULL);
242 if (WaitableTimerHandle == NULL) {
243 msyslog(LOG_ERR, "CreateWaitableTimer failed: %m");
248 LARGE_INTEGER DueTime;
251 Period = (1 << EVENT_TIMEOUT) * 1000;
252 DueTime.QuadPart = Period * 10000i64;
253 rc = SetWaitableTimer(WaitableTimerHandle, &DueTime,
254 Period, NULL, NULL, FALSE);
256 msyslog(LOG_ERR, "SetWaitableTimer failed: %m");
261 #endif /* SYS_WINNT */
266 * intres_timeout_req(s) is invoked in the parent to schedule an idle
267 * timeout to fire in s seconds, if not reset earlier by a call to
268 * intres_timeout_req(0), which clears any pending timeout. When the
269 * timeout expires, worker_idle_timer_fired() is invoked (again, in the
272 * sntp and ntpd each provide implementations adapted to their timers.
276 u_int seconds /* 0 cancels */
279 #if defined(HAVE_DROPROOT) && defined(NEED_EARLY_FORK)
281 worker_idle_timer = 0;
286 worker_idle_timer = 0;
289 worker_idle_timer = current_time + seconds;
294 * timer - event timer
300 struct peer * next_peer;
305 * The basic timerevent is one second. This is used to adjust the
306 * system clock in time and frequency, implement the kiss-o'-death
307 * function and the association polling function.
310 if (adjust_timer <= current_time) {
314 for (p = peer_list; p != NULL; p = next_peer) {
315 next_peer = p->p_link;
316 if (FLAG_REFCLOCK & p->flags)
319 #endif /* REFCLOCK */
323 * Now dispatch any peers whose event timer has expired. Be
324 * careful here, since the peer structure might go away as the
325 * result of the call.
327 for (p = peer_list; p != NULL; p = next_peer) {
328 next_peer = p->p_link;
331 * Restrain the non-burst packet rate not more
332 * than one packet every 16 seconds. This is
333 * usually tripped using iburst and minpoll of
338 if (p->nextdate <= current_time) {
340 if (FLAG_REFCLOCK & p->flags)
341 refclock_transmit(p);
343 #endif /* REFCLOCK */
349 * Orphan mode is active when enabled and when no servers less
350 * than the orphan stratum are available. A server with no other
351 * synchronization source is an orphan. It shows offset zero and
352 * reference ID the loopback address.
354 if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL &&
355 current_time > orphwait) {
356 if (sys_leap == LEAP_NOTINSYNC) {
357 set_sys_leap(LEAP_NOWARNING);
363 sys_stratum = (u_char)sys_orphan;
365 sys_refid = htonl(LOOPBACKADR);
367 memcpy(&sys_refid, "LOOP", 4);
377 * Leapseconds. Get time and defer to worker if either something
378 * is imminent or every 8th second.
380 if (leapsec > LSPROX_NOWARN || 0 == (current_time & 7))
381 check_leapsec(now.l_ui, &tnow,
382 (sys_leap == LEAP_NOTINSYNC));
383 if (sys_leap != LEAP_NOTINSYNC) {
384 if (leapsec >= LSPROX_ANNOUNCE && leapdif) {
386 set_sys_leap(LEAP_ADDSECOND);
388 set_sys_leap(LEAP_DELSECOND);
390 set_sys_leap(LEAP_NOWARNING);
395 * Update huff-n'-puff filter.
397 if (huffpuff_timer <= current_time) {
398 huffpuff_timer += HUFFPUFF;
404 * Garbage collect expired keys.
406 if (keys_timer <= current_time) {
407 keys_timer += 1 << sys_automax;
412 * Generate new private value. This causes all associations
413 * to regenerate cookies.
415 if (revoke_timer && revoke_timer <= current_time) {
416 revoke_timer += 1 << sys_revoke;
417 RAND_bytes((u_char *)&sys_private, 4);
422 * Interface update timer
424 if (interface_interval && interface_timer <= current_time) {
425 timer_interfacetimeout(current_time +
427 DPRINTF(2, ("timer: interface update\n"));
428 interface_update(NULL, NULL);
431 if (worker_idle_timer && worker_idle_timer <= current_time)
432 worker_idle_timer_fired();
435 * Finally, write hourly stats and do the hourly
436 * and daily leapfile checks.
438 if (stats_timer <= current_time) {
439 stats_timer += SECSPERHR;
441 if (leapf_timer <= current_time) {
442 leapf_timer += SECSPERDAY;
443 check_leap_file(TRUE, now.l_ui, &tnow);
445 check_leap_file(FALSE, now.l_ui, &tnow);
453 * alarming - tell the world we've been alarmed
461 const char *msg = "alarming: initializing TRUE\n";
468 msg = "alarming: overflow\n";
474 /* VMS AST routine, increment is no good */
478 msg = "alarming: normal\n";
483 lib$addx(&vmsinc, &vmstimer, &vmstimer);
484 sys$setimr(0, &vmstimer, alarming, alarming, 0);
488 (void)(-1 == write(1, msg, strlen(msg)));
491 #endif /* SYS_WINNT */
495 timer_interfacetimeout(u_long timeout)
497 interface_timer = timeout;
502 * timer_clr_stats - clear timer module stat counters
505 timer_clr_stats(void)
509 timer_timereset = current_time;
514 check_leap_sec_in_progress( const leap_result_t *lsdata ) {
515 int prv_leap_sec_in_progress = leap_sec_in_progress;
516 leap_sec_in_progress = lsdata->tai_diff && (lsdata->ddist < 3);
518 /* if changed we may have to update the leap status sent to clients */
519 if (leap_sec_in_progress != prv_leap_sec_in_progress)
520 set_sys_leap(sys_leap);
527 const time_t * tpiv ,
530 static const char leapmsg_p_step[] =
531 "Positive leap second, stepped backward.";
532 static const char leapmsg_p_slew[] =
533 "Positive leap second, no step correction. "
534 "System clock will be inaccurate for a long time.";
536 static const char leapmsg_n_step[] =
537 "Negative leap second, stepped forward.";
538 static const char leapmsg_n_slew[] =
539 "Negative leap second, no step correction. "
540 "System clock will be inaccurate for a long time.";
542 leap_result_t lsdata;
545 int/*BOOL*/ update_autokey = FALSE;
548 #ifndef SYS_WINNT /* WinNT port has its own leap second handling */
550 leapsec_electric(pll_control && kern_enable);
556 leap_smear.enabled = leap_smear_intv != 0;
559 lsprox = LSPROX_NOWARN;
560 leapsec_reset_frame();
561 memset(&lsdata, 0, sizeof(lsdata));
565 fired = leapsec_query(&lsdata, now, tpiv);
567 DPRINTF(3, ("*** leapsec_query: fired %i, now %u (0x%08X), tai_diff %i, ddist %u\n",
568 fired, now, now, lsdata.tai_diff, lsdata.ddist));
571 leap_smear.in_progress = 0;
572 leap_smear.doffset = 0.0;
574 if (leap_smear.enabled) {
575 if (lsdata.tai_diff) {
576 if (leap_smear.interval == 0) {
577 leap_smear.interval = leap_smear_intv;
578 leap_smear.intv_end = lsdata.ttime.Q_s;
579 leap_smear.intv_start = leap_smear.intv_end - leap_smear.interval;
580 DPRINTF(1, ("*** leapsec_query: setting leap_smear interval %li, begin %.0f, end %.0f\n",
581 leap_smear.interval, leap_smear.intv_start, leap_smear.intv_end));
584 if (leap_smear.interval)
585 DPRINTF(1, ("*** leapsec_query: clearing leap_smear interval\n"));
586 leap_smear.interval = 0;
589 if (leap_smear.interval) {
591 if (dtemp >= leap_smear.intv_start && dtemp <= leap_smear.intv_end) {
592 double leap_smear_time = dtemp - leap_smear.intv_start;
594 * For now we just do a linear interpolation over the smear interval
597 // linear interpolation
598 leap_smear.doffset = -(leap_smear_time * lsdata.tai_diff / leap_smear.interval);
600 // Google approach: lie(t) = (1.0 - cos(pi * t / w)) / 2.0
601 leap_smear.doffset = -((double) lsdata.tai_diff - cos( M_PI * leap_smear_time / leap_smear.interval)) / 2.0;
604 * TODO see if we're inside an inserted leap second, so we need to compute
605 * leap_smear.doffset = 1.0 - leap_smear.doffset
607 leap_smear.in_progress = 1;
608 #if 0 && defined( DEBUG )
609 msyslog(LOG_NOTICE, "*** leapsec_query: [%.0f:%.0f] (%li), now %u (%.0f), smear offset %.6f ms\n",
610 leap_smear.intv_start, leap_smear.intv_end, leap_smear.interval,
611 now, leap_smear_time, leap_smear.doffset);
613 DPRINTF(1, ("*** leapsec_query: [%.0f:%.0f] (%li), now %u (%.0f), smear offset %.6f ms\n",
614 leap_smear.intv_start, leap_smear.intv_end, leap_smear.interval,
615 now, leap_smear_time, leap_smear.doffset));
622 leap_smear.interval = 0;
625 * Update the current leap smear offset, eventually 0.0 if outside smear interval.
627 DTOLFP(leap_smear.doffset, &leap_smear.offset);
629 #endif /* LEAP_SMEAR */
632 /* Full hit. Eventually step the clock, but always
633 * announce the leap event has happened.
635 const char *leapmsg = NULL;
636 double lswarp = lsdata.warped;
638 if (clock_max_back > 0.0 &&
639 clock_max_back < -lswarp) {
640 step_systime(lswarp);
641 leapmsg = leapmsg_p_step;
643 leapmsg = leapmsg_p_slew;
645 } else if (lswarp > 0.0) {
646 if (clock_max_fwd > 0.0 &&
647 clock_max_fwd < lswarp) {
648 step_systime(lswarp);
649 leapmsg = leapmsg_n_step;
651 leapmsg = leapmsg_n_slew;
655 msyslog(LOG_NOTICE, "%s", leapmsg);
656 report_event(EVNT_LEAP, NULL, NULL);
658 update_autokey = TRUE;
660 lsprox = LSPROX_NOWARN;
661 leapsec = LSPROX_NOWARN;
662 sys_tai = lsdata.tai_offs;
665 update_autokey = (sys_tai != (u_int)lsdata.tai_offs);
667 lsprox = lsdata.proximity;
668 sys_tai = lsdata.tai_offs;
672 /* We guard against panic alarming during the red alert phase.
673 * Strange and evil things might happen if we go from stone cold
674 * to piping hot in one step. If things are already that wobbly,
675 * we let the normal clock correction take over, even if a jump
677 * Also make sure the alarming events are edge-triggered, that is,
678 * ceated only when the threshold is crossed.
680 if ( (leapsec > 0 || lsprox < LSPROX_ALERT)
681 && leapsec < lsprox ) {
682 if ( leapsec < LSPROX_SCHEDULE
683 && lsprox >= LSPROX_SCHEDULE) {
685 report_event(PEVNT_ARMED, sys_peer, NULL);
687 report_event(EVNT_ARMED, NULL, NULL);
691 if (leapsec > lsprox) {
692 if ( leapsec >= LSPROX_SCHEDULE
693 && lsprox < LSPROX_SCHEDULE) {
694 report_event(EVNT_DISARMED, NULL, NULL);
699 if (leapsec >= LSPROX_SCHEDULE)
700 leapdif = lsdata.tai_diff;
704 check_leap_sec_in_progress(&lsdata);
708 crypto_update_taichange();