1 /* 2 * ntp_timer.c - event timer support routines 3 */ 4 #ifdef HAVE_CONFIG_H 5 # include <config.h> 6 #endif 7 8 #include "ntp_machine.h" 9 #include "ntpd.h" 10 #include "ntp_stdlib.h" 11 #include "ntp_calendar.h" 12 #include "ntp_leapsec.h" 13 14 #if defined(HAVE_IO_COMPLETION_PORT) 15 # include "ntp_iocompletionport.h" 16 # include "ntp_timer.h" 17 #endif 18 19 #include <stdio.h> 20 #include <signal.h> 21 #ifdef HAVE_SYS_SIGNAL_H 22 # include <sys/signal.h> 23 #endif 24 #ifdef HAVE_UNISTD_H 25 # include <unistd.h> 26 #endif 27 28 #ifdef KERNEL_PLL 29 #include "ntp_syscall.h" 30 #endif /* KERNEL_PLL */ 31 32 #ifdef AUTOKEY 33 #include <openssl/rand.h> 34 #endif /* AUTOKEY */ 35 36 37 /* TC_ERR represents the timer_create() error return value. */ 38 #ifdef SYS_VXWORKS 39 #define TC_ERR ERROR 40 #else 41 #define TC_ERR (-1) 42 #endif 43 44 45 static void check_leapsec(u_int32, const time_t*, int/*BOOL*/); 46 47 /* 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 55 * message. 56 */ 57 volatile int interface_interval; /* init_io() sets def. 300s */ 58 59 /* 60 * Initializing flag. All async routines watch this and only do their 61 * thing when it is clear. 62 */ 63 int initializing; 64 65 /* 66 * Alarm flag. The mainline code imports this. 67 */ 68 volatile int alarm_flag; 69 70 /* 71 * The counters and timeouts 72 */ 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 */ 82 #ifdef AUTOKEY 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) */ 87 #endif /* AUTOKEY */ 88 89 /* 90 * Statistics counter for the interested. 91 */ 92 volatile u_long alarm_overflow; 93 94 u_long current_time; /* seconds since startup */ 95 96 /* 97 * Stats. Number of overflows and number of calls to transmit(). 98 */ 99 u_long timer_timereset; 100 u_long timer_overflows; 101 u_long timer_xmtcalls; 102 103 #if defined(VMS) 104 static int vmstimer[2]; /* time for next timer AST */ 105 static int vmsinc[2]; /* timer increment */ 106 #endif /* VMS */ 107 108 #ifdef SYS_WINNT 109 HANDLE WaitableTimerHandle; 110 #else 111 static RETSIGTYPE alarming (int); 112 #endif /* SYS_WINNT */ 113 114 #if !defined(VMS) 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 120 # else 121 typedef struct itimerval intervaltimer; 122 # define itv_frac tv_usec 123 # endif 124 intervaltimer itimer; 125 # endif 126 #endif 127 128 #if !defined(SYS_WINNT) && !defined(VMS) 129 void set_timer_or_die(const intervaltimer *); 130 #endif 131 132 133 #if !defined(SYS_WINNT) && !defined(VMS) 134 void 135 set_timer_or_die( 136 const intervaltimer * ptimer 137 ) 138 { 139 const char * setfunc; 140 int rc; 141 142 # ifdef HAVE_TIMER_CREATE 143 setfunc = "timer_settime"; 144 rc = timer_settime(timer_id, 0, &itimer, NULL); 145 # else 146 setfunc = "setitimer"; 147 rc = setitimer(ITIMER_REAL, &itimer, NULL); 148 # endif 149 if (-1 == rc) { 150 msyslog(LOG_ERR, "interval timer %s failed, %m", 151 setfunc); 152 exit(1); 153 } 154 } 155 #endif /* !SYS_WINNT && !VMS */ 156 157 158 /* 159 * reinit_timer - reinitialize interval timer after a clock step. 160 */ 161 void 162 reinit_timer(void) 163 { 164 #if !defined(SYS_WINNT) && !defined(VMS) 165 ZERO(itimer); 166 # ifdef HAVE_TIMER_CREATE 167 timer_gettime(timer_id, &itimer); 168 # else 169 getitimer(ITIMER_REAL, &itimer); 170 # endif 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); 182 # endif /* VMS */ 183 } 184 185 186 /* 187 * init_timer - initialize the timer data structures 188 */ 189 void 190 init_timer(void) 191 { 192 /* 193 * Initialize... 194 */ 195 alarm_flag = FALSE; 196 alarm_overflow = 0; 197 adjust_timer = 1; 198 stats_timer = SECSPERHR; 199 leapf_timer = SECSPERDAY; 200 huffpuff_timer = 0; 201 interface_timer = 0; 202 current_time = 0; 203 timer_overflows = 0; 204 timer_xmtcalls = 0; 205 timer_timereset = 0; 206 207 #ifndef SYS_WINNT 208 /* 209 * Set up the alarm interrupt. The first comes 2**EVENT_TIMEOUT 210 * seconds from now and they continue on every 2**EVENT_TIMEOUT 211 * seconds. 212 */ 213 # ifndef VMS 214 # ifdef HAVE_TIMER_CREATE 215 if (TC_ERR == timer_create(CLOCK_REALTIME, NULL, &timer_id)) { 216 msyslog(LOG_ERR, "timer_create failed, %m"); 217 exit(1); 218 } 219 # endif 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 */ 227 vmsinc[1] = 0; 228 lib$emul(&(1<<EVENT_TIMEOUT), &vmsinc, &0, &vmsinc); 229 230 sys$gettim(&vmstimer); /* that's "now" as abstime */ 231 232 lib$addx(&vmsinc, &vmstimer, &vmstimer); 233 sys$setimr(0, &vmstimer, alarming, alarming, 0); 234 # endif /* VMS */ 235 #else /* SYS_WINNT follows */ 236 /* 237 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds 238 * Under Windows/NT, 239 */ 240 241 WaitableTimerHandle = CreateWaitableTimer(NULL, FALSE, NULL); 242 if (WaitableTimerHandle == NULL) { 243 msyslog(LOG_ERR, "CreateWaitableTimer failed: %m"); 244 exit(1); 245 } 246 else { 247 DWORD Period; 248 LARGE_INTEGER DueTime; 249 BOOL rc; 250 251 Period = (1 << EVENT_TIMEOUT) * 1000; 252 DueTime.QuadPart = Period * 10000i64; 253 rc = SetWaitableTimer(WaitableTimerHandle, &DueTime, 254 Period, NULL, NULL, FALSE); 255 if (!rc) { 256 msyslog(LOG_ERR, "SetWaitableTimer failed: %m"); 257 exit(1); 258 } 259 } 260 261 #endif /* SYS_WINNT */ 262 } 263 264 265 /* 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 270 * parent). 271 * 272 * sntp and ntpd each provide implementations adapted to their timers. 273 */ 274 void 275 intres_timeout_req( 276 u_int seconds /* 0 cancels */ 277 ) 278 { 279 if (0 == seconds) { 280 worker_idle_timer = 0; 281 return; 282 } 283 worker_idle_timer = current_time + seconds; 284 } 285 286 287 /* 288 * timer - event timer 289 */ 290 void 291 timer(void) 292 { 293 struct peer * p; 294 struct peer * next_peer; 295 l_fp now; 296 time_t tnow; 297 298 /* 299 * The basic timerevent is one second. This is used to adjust the 300 * system clock in time and frequency, implement the kiss-o'-death 301 * function and the association polling function. 302 */ 303 current_time++; 304 if (adjust_timer <= current_time) { 305 adjust_timer += 1; 306 adj_host_clock(); 307 #ifdef REFCLOCK 308 for (p = peer_list; p != NULL; p = next_peer) { 309 next_peer = p->p_link; 310 if (FLAG_REFCLOCK & p->flags) 311 refclock_timer(p); 312 } 313 #endif /* REFCLOCK */ 314 } 315 316 /* 317 * Now dispatch any peers whose event timer has expired. Be 318 * careful here, since the peer structure might go away as the 319 * result of the call. 320 */ 321 for (p = peer_list; p != NULL; p = next_peer) { 322 next_peer = p->p_link; 323 324 /* 325 * Restrain the non-burst packet rate not more 326 * than one packet every 16 seconds. This is 327 * usually tripped using iburst and minpoll of 328 * 128 s or less. 329 */ 330 if (p->throttle > 0) 331 p->throttle--; 332 if (p->nextdate <= current_time) { 333 #ifdef REFCLOCK 334 if (FLAG_REFCLOCK & p->flags) 335 refclock_transmit(p); 336 else 337 #endif /* REFCLOCK */ 338 transmit(p); 339 } 340 } 341 342 /* 343 * Orphan mode is active when enabled and when no servers less 344 * than the orphan stratum are available. A server with no other 345 * synchronization source is an orphan. It shows offset zero and 346 * reference ID the loopback address. 347 */ 348 if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL && 349 current_time > orphwait) { 350 if (sys_leap == LEAP_NOTINSYNC) { 351 set_sys_leap(LEAP_NOWARNING); 352 #ifdef AUTOKEY 353 if (crypto_flags) 354 crypto_update(); 355 #endif /* AUTOKEY */ 356 } 357 sys_stratum = (u_char)sys_orphan; 358 if (sys_stratum > 1) 359 sys_refid = htonl(LOOPBACKADR); 360 else 361 memcpy(&sys_refid, "LOOP", 4); 362 sys_offset = 0; 363 sys_rootdelay = 0; 364 sys_rootdisp = 0; 365 } 366 367 get_systime(&now); 368 time(&tnow); 369 370 /* 371 * Leapseconds. Get time and defer to worker if either something 372 * is imminent or every 8th second. 373 */ 374 if (leapsec > LSPROX_NOWARN || 0 == (current_time & 7)) 375 check_leapsec(now.l_ui, &tnow, 376 (sys_leap == LEAP_NOTINSYNC)); 377 if (sys_leap != LEAP_NOTINSYNC) { 378 if (leapsec >= LSPROX_ANNOUNCE && leapdif) { 379 if (leapdif > 0) 380 set_sys_leap(LEAP_ADDSECOND); 381 else 382 set_sys_leap(LEAP_DELSECOND); 383 } else { 384 set_sys_leap(LEAP_NOWARNING); 385 } 386 } 387 388 /* 389 * Update huff-n'-puff filter. 390 */ 391 if (huffpuff_timer <= current_time) { 392 huffpuff_timer += HUFFPUFF; 393 huffpuff(); 394 } 395 396 #ifdef AUTOKEY 397 /* 398 * Garbage collect expired keys. 399 */ 400 if (keys_timer <= current_time) { 401 keys_timer += 1 << sys_automax; 402 auth_agekeys(); 403 } 404 405 /* 406 * Generate new private value. This causes all associations 407 * to regenerate cookies. 408 */ 409 if (revoke_timer && revoke_timer <= current_time) { 410 revoke_timer += 1 << sys_revoke; 411 RAND_bytes((u_char *)&sys_private, 4); 412 } 413 #endif /* AUTOKEY */ 414 415 /* 416 * Interface update timer 417 */ 418 if (interface_interval && interface_timer <= current_time) { 419 timer_interfacetimeout(current_time + 420 interface_interval); 421 DPRINTF(2, ("timer: interface update\n")); 422 interface_update(NULL, NULL); 423 } 424 425 if (worker_idle_timer && worker_idle_timer <= current_time) 426 worker_idle_timer_fired(); 427 428 /* 429 * Finally, write hourly stats and do the hourly 430 * and daily leapfile checks. 431 */ 432 if (stats_timer <= current_time) { 433 stats_timer += SECSPERHR; 434 write_stats(); 435 if (leapf_timer <= current_time) { 436 leapf_timer += SECSPERDAY; 437 check_leap_file(TRUE, now.l_ui, &tnow); 438 } else { 439 check_leap_file(FALSE, now.l_ui, &tnow); 440 } 441 } 442 } 443 444 445 #ifndef SYS_WINNT 446 /* 447 * alarming - tell the world we've been alarmed 448 */ 449 static RETSIGTYPE 450 alarming( 451 int sig 452 ) 453 { 454 # ifdef DEBUG 455 const char *msg = "alarming: initializing TRUE\n"; 456 # endif 457 458 if (!initializing) { 459 if (alarm_flag) { 460 alarm_overflow++; 461 # ifdef DEBUG 462 msg = "alarming: overflow\n"; 463 # endif 464 } else { 465 # ifndef VMS 466 alarm_flag++; 467 # else 468 /* VMS AST routine, increment is no good */ 469 alarm_flag = 1; 470 # endif 471 # ifdef DEBUG 472 msg = "alarming: normal\n"; 473 # endif 474 } 475 } 476 # ifdef VMS 477 lib$addx(&vmsinc, &vmstimer, &vmstimer); 478 sys$setimr(0, &vmstimer, alarming, alarming, 0); 479 # endif 480 # ifdef DEBUG 481 if (debug >= 4) 482 (void)(-1 == write(1, msg, strlen(msg))); 483 # endif 484 } 485 #endif /* SYS_WINNT */ 486 487 488 void 489 timer_interfacetimeout(u_long timeout) 490 { 491 interface_timer = timeout; 492 } 493 494 495 /* 496 * timer_clr_stats - clear timer module stat counters 497 */ 498 void 499 timer_clr_stats(void) 500 { 501 timer_overflows = 0; 502 timer_xmtcalls = 0; 503 timer_timereset = current_time; 504 } 505 506 507 static void 508 check_leap_sec_in_progress( const leap_result_t *lsdata ) { 509 int prv_leap_sec_in_progress = leap_sec_in_progress; 510 leap_sec_in_progress = lsdata->tai_diff && (lsdata->ddist < 3); 511 512 /* if changed we may have to update the leap status sent to clients */ 513 if (leap_sec_in_progress != prv_leap_sec_in_progress) 514 set_sys_leap(sys_leap); 515 } 516 517 518 static void 519 check_leapsec( 520 u_int32 now , 521 const time_t * tpiv , 522 int/*BOOL*/ reset) 523 { 524 static const char leapmsg_p_step[] = 525 "Positive leap second, stepped backward."; 526 static const char leapmsg_p_slew[] = 527 "Positive leap second, no step correction. " 528 "System clock will be inaccurate for a long time."; 529 530 static const char leapmsg_n_step[] = 531 "Negative leap second, stepped forward."; 532 static const char leapmsg_n_slew[] = 533 "Negative leap second, no step correction. " 534 "System clock will be inaccurate for a long time."; 535 536 leap_result_t lsdata; 537 u_int32 lsprox; 538 #ifdef AUTOKEY 539 int/*BOOL*/ update_autokey = FALSE; 540 #endif 541 542 #ifndef SYS_WINNT /* WinNT port has its own leap second handling */ 543 # ifdef KERNEL_PLL 544 leapsec_electric(pll_control && kern_enable); 545 # else 546 leapsec_electric(0); 547 # endif 548 #endif 549 #ifdef LEAP_SMEAR 550 leap_smear.enabled = leap_smear_intv != 0; 551 #endif 552 if (reset) { 553 lsprox = LSPROX_NOWARN; 554 leapsec_reset_frame(); 555 memset(&lsdata, 0, sizeof(lsdata)); 556 } else { 557 int fired = leapsec_query(&lsdata, now, tpiv); 558 559 DPRINTF(1, ("*** leapsec_query: fired %i, now %u (0x%08X), tai_diff %i, ddist %u\n", 560 fired, now, now, lsdata.tai_diff, lsdata.ddist)); 561 562 #ifdef LEAP_SMEAR 563 leap_smear.in_progress = 0; 564 leap_smear.doffset = 0.0; 565 566 if (leap_smear.enabled) { 567 if (lsdata.tai_diff) { 568 if (leap_smear.interval == 0) { 569 leap_smear.interval = leap_smear_intv; 570 leap_smear.intv_end = lsdata.ttime.Q_s; 571 leap_smear.intv_start = leap_smear.intv_end - leap_smear.interval; 572 DPRINTF(1, ("*** leapsec_query: setting leap_smear interval %li, begin %.0f, end %.0f\n", 573 leap_smear.interval, leap_smear.intv_start, leap_smear.intv_end)); 574 } 575 } 576 else { 577 if (leap_smear.interval) 578 DPRINTF(1, ("*** leapsec_query: clearing leap_smear interval\n")); 579 leap_smear.interval = 0; 580 } 581 582 if (leap_smear.interval) { 583 double dtemp = now; 584 if (dtemp >= leap_smear.intv_start && dtemp <= leap_smear.intv_end) { 585 double leap_smear_time = dtemp - leap_smear.intv_start; 586 /* 587 * For now we just do a linear interpolation over the smear interval 588 */ 589 #if 0 590 // linear interpolation 591 leap_smear.doffset = -(leap_smear_time * lsdata.tai_diff / leap_smear.interval); 592 #else 593 // Google approach: lie(t) = (1.0 - cos(pi * t / w)) / 2.0 594 leap_smear.doffset = -((double) lsdata.tai_diff - cos( M_PI * leap_smear_time / leap_smear.interval)) / 2.0; 595 #endif 596 /* 597 * TODO see if we're inside an inserted leap second, so we need to compute 598 * leap_smear.doffset = 1.0 - leap_smear.doffset 599 */ 600 leap_smear.in_progress = 1; 601 #if 0 && defined( DEBUG ) 602 msyslog(LOG_NOTICE, "*** leapsec_query: [%.0f:%.0f] (%li), now %u (%.0f), smear offset %.6f ms\n", 603 leap_smear.intv_start, leap_smear.intv_end, leap_smear.interval, 604 now, leap_smear_time, leap_smear.doffset); 605 #else 606 DPRINTF(1, ("*** leapsec_query: [%.0f:%.0f] (%li), now %u (%.0f), smear offset %.6f ms\n", 607 leap_smear.intv_start, leap_smear.intv_end, leap_smear.interval, 608 now, leap_smear_time, leap_smear.doffset)); 609 #endif 610 611 } 612 } 613 } 614 else 615 leap_smear.interval = 0; 616 617 /* 618 * Update the current leap smear offset, eventually 0.0 if outside smear interval. 619 */ 620 DTOLFP(leap_smear.doffset, &leap_smear.offset); 621 622 #endif /* LEAP_SMEAR */ 623 624 if (fired) { 625 /* Full hit. Eventually step the clock, but always 626 * announce the leap event has happened. 627 */ 628 const char *leapmsg = NULL; 629 if (lsdata.warped < 0) { 630 if (clock_max_back > 0.0 && 631 clock_max_back < fabs(lsdata.warped)) { 632 step_systime(lsdata.warped); 633 leapmsg = leapmsg_p_step; 634 } else { 635 leapmsg = leapmsg_p_slew; 636 } 637 } else if (lsdata.warped > 0) { 638 if (clock_max_fwd > 0.0 && 639 clock_max_fwd < fabs(lsdata.warped)) { 640 step_systime(lsdata.warped); 641 leapmsg = leapmsg_n_step; 642 } else { 643 leapmsg = leapmsg_n_slew; 644 } 645 } 646 if (leapmsg) 647 msyslog(LOG_NOTICE, "%s", leapmsg); 648 report_event(EVNT_LEAP, NULL, NULL); 649 #ifdef AUTOKEY 650 update_autokey = TRUE; 651 #endif 652 lsprox = LSPROX_NOWARN; 653 leapsec = LSPROX_NOWARN; 654 sys_tai = lsdata.tai_offs; 655 } else { 656 #ifdef AUTOKEY 657 update_autokey = (sys_tai != lsdata.tai_offs); 658 #endif 659 lsprox = lsdata.proximity; 660 sys_tai = lsdata.tai_offs; 661 } 662 } 663 664 /* We guard against panic alarming during the red alert phase. 665 * Strange and evil things might happen if we go from stone cold 666 * to piping hot in one step. If things are already that wobbly, 667 * we let the normal clock correction take over, even if a jump 668 * is involved. 669 * Also make sure the alarming events are edge-triggered, that is, 670 * ceated only when the threshold is crossed. 671 */ 672 if ( (leapsec > 0 || lsprox < LSPROX_ALERT) 673 && leapsec < lsprox ) { 674 if ( leapsec < LSPROX_SCHEDULE 675 && lsprox >= LSPROX_SCHEDULE) { 676 if (lsdata.dynamic) 677 report_event(PEVNT_ARMED, sys_peer, NULL); 678 else 679 report_event(EVNT_ARMED, NULL, NULL); 680 } 681 leapsec = lsprox; 682 } 683 if (leapsec > lsprox) { 684 if ( leapsec >= LSPROX_SCHEDULE 685 && lsprox < LSPROX_SCHEDULE) { 686 report_event(EVNT_DISARMED, NULL, NULL); 687 } 688 leapsec = lsprox; 689 } 690 691 if (leapsec >= LSPROX_SCHEDULE) 692 leapdif = lsdata.tai_diff; 693 else 694 leapdif = 0; 695 696 check_leap_sec_in_progress(&lsdata); 697 698 #ifdef AUTOKEY 699 if (update_autokey) 700 crypto_update_taichange(); 701 #endif 702 } 703