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