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. */
44 static void check_leapsec(u_int32, const time_t*, int/*BOOL*/);
47 * These routines provide support for the event timer. The timer is
48 * implemented by an interrupt routine which sets a flag once every
49 * second, and a timer routine which is called when the mainline code
50 * gets around to seeing the flag. The timer routine dispatches the
51 * clock adjustment code if its time has come, then searches the timer
52 * queue for expiries which are dispatched to the transmit procedure.
53 * Finally, we call the hourly procedure to do cleanup and print a
56 volatile int interface_interval; /* init_io() sets def. 300s */
59 * Alarm flag. The mainline code imports this.
61 volatile int alarm_flag;
64 * The counters and timeouts
66 static u_long interface_timer; /* interface update timer */
67 static u_long adjust_timer; /* second timer */
68 static u_long stats_timer; /* stats timer */
69 static u_long leapf_timer; /* Report leapfile problems once/day */
70 static u_long huffpuff_timer; /* huff-n'-puff timer */
71 static u_long worker_idle_timer;/* next check for idle intres */
72 u_long leapsec; /* seconds to next leap (proximity class) */
73 int leapdif; /* TAI difference step at next leap second*/
74 u_long orphwait; /* orphan wait time */
76 static u_long revoke_timer; /* keys revoke timer */
77 static u_long keys_timer; /* session key timer */
78 u_long sys_revoke = KEY_REVOKE; /* keys revoke timeout (log2 s) */
79 u_long sys_automax = NTP_AUTOMAX; /* key list timeout (log2 s) */
83 * Statistics counter for the interested.
85 volatile u_long alarm_overflow;
87 u_long current_time; /* seconds since startup */
90 * Stats. Number of overflows and number of calls to transmit().
92 u_long timer_timereset;
93 u_long timer_overflows;
94 u_long timer_xmtcalls;
97 static int vmstimer[2]; /* time for next timer AST */
98 static int vmsinc[2]; /* timer increment */
102 HANDLE WaitableTimerHandle;
104 static RETSIGTYPE alarming (int);
105 #endif /* SYS_WINNT */
108 # if !defined SYS_WINNT || defined(SYS_CYGWIN32)
109 # ifdef HAVE_TIMER_CREATE
110 static timer_t timer_id;
111 typedef struct itimerspec intervaltimer;
112 # define itv_frac tv_nsec
114 typedef struct itimerval intervaltimer;
115 # define itv_frac tv_usec
117 intervaltimer itimer;
121 #if !defined(SYS_WINNT) && !defined(VMS)
122 void set_timer_or_die(const intervaltimer *);
126 #if !defined(SYS_WINNT) && !defined(VMS)
129 const intervaltimer * ptimer
132 const char * setfunc;
135 # ifdef HAVE_TIMER_CREATE
136 setfunc = "timer_settime";
137 rc = timer_settime(timer_id, 0, &itimer, NULL);
139 setfunc = "setitimer";
140 rc = setitimer(ITIMER_REAL, &itimer, NULL);
143 msyslog(LOG_ERR, "interval timer %s failed, %m",
148 #endif /* !SYS_WINNT && !VMS */
152 * reinit_timer - reinitialize interval timer after a clock step.
157 #if !defined(SYS_WINNT) && !defined(VMS)
159 # ifdef HAVE_TIMER_CREATE
160 timer_gettime(timer_id, &itimer);
162 getitimer(ITIMER_REAL, &itimer);
164 if (itimer.it_value.tv_sec < 0 ||
165 itimer.it_value.tv_sec > (1 << EVENT_TIMEOUT))
166 itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
167 if (itimer.it_value.itv_frac < 0)
168 itimer.it_value.itv_frac = 0;
169 if (0 == itimer.it_value.tv_sec &&
170 0 == itimer.it_value.itv_frac)
171 itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
172 itimer.it_interval.tv_sec = (1 << EVENT_TIMEOUT);
173 itimer.it_interval.itv_frac = 0;
174 set_timer_or_die(&itimer);
180 * init_timer - initialize the timer data structures
191 stats_timer = SECSPERHR;
192 leapf_timer = SECSPERDAY;
202 * Set up the alarm interrupt. The first comes 2**EVENT_TIMEOUT
203 * seconds from now and they continue on every 2**EVENT_TIMEOUT
207 # ifdef HAVE_TIMER_CREATE
208 if (TC_ERR == timer_create(CLOCK_REALTIME, NULL, &timer_id)) {
209 msyslog(LOG_ERR, "timer_create failed, %m");
213 signal_no_reset(SIGALRM, alarming);
214 itimer.it_interval.tv_sec =
215 itimer.it_value.tv_sec = (1 << EVENT_TIMEOUT);
216 itimer.it_interval.itv_frac = itimer.it_value.itv_frac = 0;
217 set_timer_or_die(&itimer);
218 # else /* VMS follows */
219 vmsinc[0] = 10000000; /* 1 sec */
221 lib$emul(&(1<<EVENT_TIMEOUT), &vmsinc, &0, &vmsinc);
223 sys$gettim(&vmstimer); /* that's "now" as abstime */
225 lib$addx(&vmsinc, &vmstimer, &vmstimer);
226 sys$setimr(0, &vmstimer, alarming, alarming, 0);
228 #else /* SYS_WINNT follows */
230 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
234 WaitableTimerHandle = CreateWaitableTimer(NULL, FALSE, NULL);
235 if (WaitableTimerHandle == NULL) {
236 msyslog(LOG_ERR, "CreateWaitableTimer failed: %m");
241 LARGE_INTEGER DueTime;
244 Period = (1 << EVENT_TIMEOUT) * 1000;
245 DueTime.QuadPart = Period * 10000i64;
246 rc = SetWaitableTimer(WaitableTimerHandle, &DueTime,
247 Period, NULL, NULL, FALSE);
249 msyslog(LOG_ERR, "SetWaitableTimer failed: %m");
254 #endif /* SYS_WINNT */
259 * intres_timeout_req(s) is invoked in the parent to schedule an idle
260 * timeout to fire in s seconds, if not reset earlier by a call to
261 * intres_timeout_req(0), which clears any pending timeout. When the
262 * timeout expires, worker_idle_timer_fired() is invoked (again, in the
265 * sntp and ntpd each provide implementations adapted to their timers.
269 u_int seconds /* 0 cancels */
273 worker_idle_timer = 0;
276 worker_idle_timer = current_time + seconds;
281 * timer - event timer
287 struct peer * next_peer;
292 * The basic timerevent is one second. This is used to adjust the
293 * system clock in time and frequency, implement the kiss-o'-death
294 * function and the association polling function.
297 if (adjust_timer <= current_time) {
301 for (p = peer_list; p != NULL; p = next_peer) {
302 next_peer = p->p_link;
303 if (FLAG_REFCLOCK & p->flags)
306 #endif /* REFCLOCK */
310 * Now dispatch any peers whose event timer has expired. Be
311 * careful here, since the peer structure might go away as the
312 * result of the call.
314 for (p = peer_list; p != NULL; p = next_peer) {
315 next_peer = p->p_link;
318 * Restrain the non-burst packet rate not more
319 * than one packet every 16 seconds. This is
320 * usually tripped using iburst and minpoll of
325 if (p->nextdate <= current_time) {
327 if (FLAG_REFCLOCK & p->flags)
328 refclock_transmit(p);
330 #endif /* REFCLOCK */
336 * Orphan mode is active when enabled and when no servers less
337 * than the orphan stratum are available. A server with no other
338 * synchronization source is an orphan. It shows offset zero and
339 * reference ID the loopback address.
341 if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL &&
342 current_time > orphwait) {
343 if (sys_leap == LEAP_NOTINSYNC) {
344 sys_leap = LEAP_NOWARNING;
350 sys_stratum = (u_char)sys_orphan;
352 sys_refid = htonl(LOOPBACKADR);
354 memcpy(&sys_refid, "LOOP", 4);
364 * Leapseconds. Get time and defer to worker if either something
365 * is imminent or every 8th second.
367 if (leapsec > LSPROX_NOWARN || 0 == (current_time & 7))
368 check_leapsec(now.l_ui, &tnow,
369 (sys_leap == LEAP_NOTINSYNC));
370 if (sys_leap != LEAP_NOTINSYNC) {
371 if (leapsec >= LSPROX_ANNOUNCE && leapdif) {
373 sys_leap = LEAP_ADDSECOND;
375 sys_leap = LEAP_DELSECOND;
377 sys_leap = LEAP_NOWARNING;
382 * Update huff-n'-puff filter.
384 if (huffpuff_timer <= current_time) {
385 huffpuff_timer += HUFFPUFF;
391 * Garbage collect expired keys.
393 if (keys_timer <= current_time) {
394 keys_timer += 1 << sys_automax;
399 * Generate new private value. This causes all associations
400 * to regenerate cookies.
402 if (revoke_timer && revoke_timer <= current_time) {
403 revoke_timer += 1 << sys_revoke;
404 RAND_bytes((u_char *)&sys_private, 4);
409 * Interface update timer
411 if (interface_interval && interface_timer <= current_time) {
412 timer_interfacetimeout(current_time +
414 DPRINTF(2, ("timer: interface update\n"));
415 interface_update(NULL, NULL);
418 if (worker_idle_timer && worker_idle_timer <= current_time)
419 worker_idle_timer_fired();
422 * Finally, write hourly stats and do the hourly
423 * and daily leapfile checks.
425 if (stats_timer <= current_time) {
426 stats_timer += SECSPERHR;
428 if (leapf_timer <= current_time) {
429 leapf_timer += SECSPERDAY;
430 check_leap_file(TRUE, now.l_ui, &tnow);
432 check_leap_file(FALSE, now.l_ui, &tnow);
440 * alarming - tell the world we've been alarmed
448 const char *msg = "alarming: initializing TRUE\n";
455 msg = "alarming: overflow\n";
461 /* VMS AST routine, increment is no good */
465 msg = "alarming: normal\n";
470 lib$addx(&vmsinc, &vmstimer, &vmstimer);
471 sys$setimr(0, &vmstimer, alarming, alarming, 0);
475 write(1, msg, strlen(msg));
478 #endif /* SYS_WINNT */
482 timer_interfacetimeout(u_long timeout)
484 interface_timer = timeout;
489 * timer_clr_stats - clear timer module stat counters
492 timer_clr_stats(void)
496 timer_timereset = current_time;
502 const time_t * tpiv ,
505 leap_result_t lsdata;
508 #ifndef SYS_WINNT /* WinNT port has its own leap second handling */
510 leapsec_electric(pll_control && kern_enable);
516 lsprox = LSPROX_NOWARN;
517 leapsec_reset_frame();
518 memset(&lsdata, 0, sizeof(lsdata));
519 } else if (leapsec_query(&lsdata, now, tpiv)) {
520 /* Full hit. Eventually step the clock, but always
521 * announce the leap event has happened.
523 if (lsdata.warped < 0) {
524 step_systime(lsdata.warped);
525 msyslog(LOG_NOTICE, "Inserting positive leap second.");
526 } else if (lsdata.warped > 0) {
527 step_systime(lsdata.warped);
528 msyslog(LOG_NOTICE, "Inserting negative leap second.");
530 report_event(EVNT_LEAP, NULL, NULL);
531 lsprox = LSPROX_NOWARN;
532 leapsec = LSPROX_NOWARN;
533 sys_tai = lsdata.tai_offs;
535 lsprox = lsdata.proximity;
536 sys_tai = lsdata.tai_offs;
539 /* We guard against panic alarming during the red alert phase.
540 * Strange and evil things might happen if we go from stone cold
541 * to piping hot in one step. If things are already that wobbly,
542 * we let the normal clock correction take over, even if a jump
544 * Also make sure the alarming events are edge-triggered, that is,
545 * ceated only when the threshold is crossed.
547 if ( (leapsec > 0 || lsprox < LSPROX_ALERT)
548 && leapsec < lsprox ) {
549 if ( leapsec < LSPROX_SCHEDULE
550 && lsprox >= LSPROX_SCHEDULE) {
552 report_event(PEVNT_ARMED, sys_peer, NULL);
554 report_event(EVNT_ARMED, NULL, NULL);
558 if (leapsec > lsprox) {
559 if ( leapsec >= LSPROX_SCHEDULE
560 && lsprox < LSPROX_SCHEDULE) {
561 report_event(EVNT_DISARMED, NULL, NULL);
566 if (leapsec >= LSPROX_SCHEDULE)
567 leapdif = lsdata.tai_diff;