1 /* $NetBSD: ntp_timer.c,v 1.12 2024/08/18 20:47:18 christos 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 a signal 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 60 /* 61 * Initializing flag. All async routines watch this and only do their 62 * thing when it is clear. 63 */ 64 int initializing; 65 66 /* 67 * Alarm flag. The mainline code imports this. 68 */ 69 volatile int alarm_flag; 70 71 /* 72 * The counters and timeouts 73 */ 74 u_long endpt_scan_timer; /* interface update timer */ 75 static u_long adjust_timer; /* second timer */ 76 static u_long stats_timer; /* stats timer */ 77 static u_long leapf_timer; /* Report leapfile problems once/day */ 78 static u_long huffpuff_timer; /* huff-n'-puff timer */ 79 static u_long worker_idle_timer;/* next check for idle intres */ 80 int endpt_scan_period; /* init_io() sets def. 301s */ 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 endpt_scan_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 * 10000ll; 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 } 341 if (p->nextdate <= current_time) { 342 #ifdef REFCLOCK 343 if (FLAG_REFCLOCK & p->flags) { 344 refclock_transmit(p); 345 } else 346 #endif /* REFCLOCK */ 347 { 348 transmit(p); 349 } 350 } 351 } 352 353 /* 354 * Orphan mode is active when enabled and when no servers less 355 * than the orphan stratum are available. A server with no other 356 * synchronization source is an orphan. It shows offset zero and 357 * reference ID the loopback address. 358 * 359 * [bug 3644] If the orphan stratum is >= STRATUM_UNSPEC, we 360 * have to do it a bit different. 'clock_select()' simply 361 * tiptoed home, but since we're unsync'd and have no peer, we 362 * should eventually declare we're out of sync. Otherwise we 363 * would persistently claim we're good, and we're everything but 364 * that... 365 * 366 * XXX: do we want to log an event about this? 367 */ 368 if (sys_peer == NULL && current_time > orphwait) { 369 if (sys_orphan < STRATUM_UNSPEC) { 370 if (sys_leap == LEAP_NOTINSYNC) { 371 set_sys_leap(LEAP_NOWARNING); 372 #ifdef AUTOKEY 373 if (crypto_flags) 374 crypto_update(); 375 #endif /* AUTOKEY */ 376 } 377 sys_stratum = (u_char)sys_orphan; 378 } 379 else { 380 if (sys_leap != LEAP_NOTINSYNC) { 381 set_sys_leap(LEAP_NOTINSYNC); 382 msyslog(LOG_WARNING, "%s", 383 "no peer for too long, server running free now"); 384 } 385 sys_stratum = STRATUM_UNSPEC; 386 } 387 if (sys_stratum > 1) 388 sys_refid = htonl(LOOPBACKADR); 389 else 390 memcpy(&sys_refid, "ORPH", 4); 391 sys_offset = 0; 392 sys_rootdelay = 0; 393 sys_rootdisp = 0; 394 } 395 396 get_systime(&now); 397 time(&tnow); 398 399 /* 400 * Leapseconds. Get time and defer to worker if either something 401 * is imminent or every 8th second. 402 */ 403 if (leapsec > LSPROX_NOWARN || 0 == (current_time & 7)) 404 check_leapsec( now.l_ui 405 , &tnow 406 , (sys_leap == LEAP_NOTINSYNC)); 407 if (sys_leap != LEAP_NOTINSYNC) { 408 if (leapsec >= LSPROX_ANNOUNCE && leapdif) { 409 if (leapdif > 0) { 410 set_sys_leap(LEAP_ADDSECOND); 411 } else { 412 set_sys_leap(LEAP_DELSECOND); 413 } 414 } else { 415 set_sys_leap(LEAP_NOWARNING); 416 } 417 } 418 419 /* 420 * Update huff-n'-puff filter. 421 */ 422 if (huffpuff_timer <= current_time) { 423 huffpuff_timer += HUFFPUFF; 424 huffpuff(); 425 } 426 427 #ifdef AUTOKEY 428 /* 429 * Garbage collect expired keys. 430 */ 431 if (keys_timer <= current_time) { 432 keys_timer += (1UL << sys_automax); 433 auth_agekeys(); 434 } 435 436 /* 437 * Generate new private value. This causes all associations 438 * to regenerate cookies. 439 */ 440 if (revoke_timer && revoke_timer <= current_time) { 441 revoke_timer += (1UL << sys_revoke); 442 RAND_bytes((u_char *)&sys_private, sizeof(sys_private)); 443 } 444 #endif /* AUTOKEY */ 445 446 /* 447 * Network interface rescan timer 448 */ 449 if (endpt_scan_timer && endpt_scan_timer <= current_time) { 450 if (no_periodic_scan) { 451 endpt_scan_timer = 0; 452 DPRINTF(2, ("timer: network interface rescan disabled\n")); 453 } else { 454 endpt_scan_timer = current_time 455 + endpt_scan_period; 456 DPRINTF(2, ("timer: network interface rescan in %d seconds\n", endpt_scan_period)); 457 } 458 interface_update(NULL, NULL); 459 } 460 461 if (worker_idle_timer && worker_idle_timer <= current_time) { 462 worker_idle_timer_fired(); 463 } 464 /* 465 * Finally, write hourly stats and do the hourly 466 * and daily leapfile checks. 467 */ 468 if (stats_timer <= current_time) { 469 stats_timer += SECSPERHR; 470 write_stats(); 471 if (leapf_timer <= current_time) { 472 leapf_timer += SECSPERDAY; 473 check_leap_file(TRUE, now.l_ui, &tnow); 474 } else { 475 check_leap_file(FALSE, now.l_ui, &tnow); 476 } 477 } 478 } 479 480 481 #ifndef SYS_WINNT 482 /* 483 * alarming - tell the world we've been alarmed 484 */ 485 static RETSIGTYPE 486 alarming( 487 int sig 488 ) 489 { 490 # ifdef DEBUG 491 const char *msg = "alarming: initializing TRUE\n"; 492 # endif 493 494 if (!initializing) { 495 if (alarm_flag) { 496 alarm_overflow++; 497 # ifdef DEBUG 498 msg = "alarming: overflow\n"; 499 # endif 500 } else { 501 # ifndef VMS 502 alarm_flag++; 503 # else 504 /* VMS AST routine, increment is no good */ 505 alarm_flag = 1; 506 # endif 507 # ifdef DEBUG 508 msg = "alarming: normal\n"; 509 # endif 510 } 511 } 512 # ifdef VMS 513 lib$addx(&vmsinc, &vmstimer, &vmstimer); 514 sys$setimr(0, &vmstimer, alarming, alarming, 0); 515 # endif 516 # ifdef DEBUG 517 if (debug >= 4) 518 (void)(-1 == write(1, msg, strlen(msg))); 519 # endif 520 } 521 #endif /* SYS_WINNT */ 522 523 524 /* 525 * timer_clr_stats - clear timer module stat counters 526 */ 527 void 528 timer_clr_stats(void) 529 { 530 timer_overflows = 0; 531 timer_xmtcalls = 0; 532 timer_timereset = current_time; 533 } 534 535 536 static void 537 check_leap_sec_in_progress( 538 const leap_result_t *lsdata 539 ) 540 { 541 int prv_leap_sec_in_progress = leap_sec_in_progress; 542 543 leap_sec_in_progress = lsdata->tai_diff && (lsdata->ddist < 3); 544 545 /* if changed we have to update the leap bits sent to clients */ 546 if (leap_sec_in_progress != prv_leap_sec_in_progress) { 547 set_sys_leap(sys_leap); 548 } 549 } 550 551 552 static void 553 check_leapsec( 554 u_int32 now, 555 const time_t * tpiv, 556 int/*BOOL*/ reset 557 ) 558 { 559 static const char leapmsg_p_step[] = 560 "Positive leap second, stepped backward."; 561 static const char leapmsg_p_slew[] = 562 "Positive leap second, no step correction. " 563 "System clock will be inaccurate for a long time."; 564 565 static const char leapmsg_n_step[] = 566 "Negative leap second, stepped forward."; 567 static const char leapmsg_n_slew[] = 568 "Negative leap second, no step correction. " 569 "System clock will be inaccurate for a long time."; 570 571 leap_result_t lsdata; 572 u_int32 lsprox; 573 #ifdef AUTOKEY 574 int/*BOOL*/ update_autokey = FALSE; 575 #endif 576 577 #ifndef SYS_WINNT /* WinNT port has its own leap second handling */ 578 # ifdef KERNEL_PLL 579 leapsec_electric(pll_control && kern_enable); 580 # else 581 leapsec_electric(0); 582 # endif 583 #endif /* !SYS_WINNT */ 584 585 #ifdef LEAP_SMEAR 586 leap_smear.enabled = leap_smear_intv != 0; 587 #endif 588 if (reset) { 589 lsprox = LSPROX_NOWARN; 590 leapsec_reset_frame(); 591 ZERO(lsdata); 592 } else { 593 int fired; 594 595 fired = leapsec_query(&lsdata, now, tpiv); 596 597 DPRINTF(3, ("*** leapsec_query: fired %i, now %u (0x%08X)," 598 " tai_diff %i, ddist %u\n", 599 fired, now, now, lsdata.tai_diff, lsdata.ddist)); 600 601 #ifdef LEAP_SMEAR 602 leap_smear.in_progress = FALSE; 603 leap_smear.doffset = 0.0; 604 605 if (leap_smear.enabled) { 606 if (lsdata.tai_diff) { 607 if (0 == leap_smear.interval) { 608 leap_smear.interval = leap_smear_intv; 609 leap_smear.intv_end = lsdata.ttime.Q_s; 610 leap_smear.intv_start = leap_smear.intv_end - leap_smear.interval; 611 DPRINTF(1, ("*** leapsec_query: setting leap_smear interval %li, begin %.0f, end %.0f\n", 612 leap_smear.interval, leap_smear.intv_start, leap_smear.intv_end)); 613 } 614 } else { 615 if (leap_smear.interval) { 616 DPRINTF(1, ("*** leapsec_query: clearing leap_smear interval\n")); 617 leap_smear.interval = 0; 618 } 619 } 620 621 if (leap_smear.interval) { 622 double dtemp = now; 623 624 if (dtemp >= leap_smear.intv_start && dtemp <= leap_smear.intv_end) { 625 double leap_smear_time = dtemp - leap_smear.intv_start; 626 #if 0 627 /* linear interpolation */ 628 leap_smear.doffset = -(leap_smear_time * lsdata.tai_diff / leap_smear.interval); 629 #else 630 /* Google approach : lie(t) = (1.0 - cos(pi * t / w)) / 2.0 */ 631 leap_smear.doffset = -((double) lsdata.tai_diff - cos( M_PI * leap_smear_time / leap_smear.interval)) / 2.0; 632 #endif 633 /* 634 * TODO see if we're inside an inserted leap second, so we need to compute 635 * leap_smear.doffset = 1.0 - leap_smear.doffset 636 */ 637 leap_smear.in_progress = TRUE; 638 DPRINTF(1, ("*** leapsec_query: [%.0f:%.0f] (%li), now %u (%.0f), smear offset %.6f ms\n", 639 leap_smear.intv_start, leap_smear.intv_end, leap_smear.interval, 640 now, leap_smear_time, leap_smear.doffset)); 641 642 } 643 } 644 } else { 645 leap_smear.interval = 0; 646 } 647 /* 648 * Update the current leap smear offset, eventually 0.0 if outside smear interval. 649 */ 650 DTOLFP(leap_smear.doffset, &leap_smear.offset); 651 #endif /* LEAP_SMEAR */ 652 653 if (fired) { 654 /* Full hit. Eventually step the clock, but always 655 * announce the leap event has happened. 656 */ 657 const char *leapmsg = NULL; 658 double lswarp = lsdata.warped; 659 if (lswarp < 0.0) { 660 if (clock_max_back > 0.0 && 661 clock_max_back < -lswarp) { 662 step_systime(lswarp); 663 leapmsg = leapmsg_p_step; 664 } else { 665 leapmsg = leapmsg_p_slew; 666 } 667 } else if (lswarp > 0.0) { 668 if (clock_max_fwd > 0.0 && 669 clock_max_fwd < lswarp) { 670 step_systime(lswarp); 671 leapmsg = leapmsg_n_step; 672 } else { 673 leapmsg = leapmsg_n_slew; 674 } 675 } 676 if (leapmsg) { 677 msyslog(LOG_NOTICE, "%s", leapmsg); 678 } 679 report_event(EVNT_LEAP, NULL, NULL); 680 #ifdef AUTOKEY 681 update_autokey = TRUE; 682 #endif 683 lsprox = LSPROX_NOWARN; 684 leapsec = LSPROX_NOWARN; 685 sys_tai = lsdata.tai_offs; 686 } else { 687 #ifdef AUTOKEY 688 update_autokey = (sys_tai != (u_int)lsdata.tai_offs); 689 #endif 690 lsprox = lsdata.proximity; 691 sys_tai = lsdata.tai_offs; 692 } 693 } 694 695 /* We guard against panic alarming during the red alert phase. 696 * Strange and evil things might happen if we go from stone cold 697 * to piping hot in one step. If things are already that wobbly, 698 * we let the normal clock correction take over, even if a jump 699 * is involved. 700 * Also make sure the alarming events are edge-triggered, that is, 701 * created only when the threshold is crossed. 702 */ 703 if ( (leapsec > 0 || lsprox < LSPROX_ALERT) 704 && leapsec < lsprox) { 705 if ( leapsec < LSPROX_SCHEDULE 706 && lsprox >= LSPROX_SCHEDULE) { 707 if (lsdata.dynamic) 708 report_event(PEVNT_ARMED, sys_peer, NULL); 709 else 710 report_event(EVNT_ARMED, NULL, NULL); 711 } 712 leapsec = lsprox; 713 } 714 if (leapsec > lsprox) { 715 if ( leapsec >= LSPROX_SCHEDULE 716 && lsprox < LSPROX_SCHEDULE) { 717 report_event(EVNT_DISARMED, NULL, NULL); 718 } 719 leapsec = lsprox; 720 } 721 722 if (leapsec >= LSPROX_SCHEDULE) { 723 leapdif = lsdata.tai_diff; 724 } else { 725 leapdif = 0; 726 } 727 check_leap_sec_in_progress(&lsdata); 728 729 #ifdef AUTOKEY 730 if (update_autokey) { 731 crypto_update_taichange(); 732 } 733 #endif 734 } 735