1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * NTP state machine interfaces and logic. 4 * 5 * This code was mainly moved from kernel/timer.c and kernel/time.c 6 * Please see those files for relevant copyright info and historical 7 * changelogs. 8 */ 9 #include <linux/capability.h> 10 #include <linux/clocksource.h> 11 #include <linux/workqueue.h> 12 #include <linux/hrtimer.h> 13 #include <linux/jiffies.h> 14 #include <linux/math64.h> 15 #include <linux/timex.h> 16 #include <linux/time.h> 17 #include <linux/mm.h> 18 #include <linux/module.h> 19 #include <linux/rtc.h> 20 #include <linux/audit.h> 21 22 #include "ntp_internal.h" 23 #include "timekeeping_internal.h" 24 25 /** 26 * struct ntp_data - Structure holding all NTP related state 27 * @tick_usec: USER_HZ period in microseconds 28 * @tick_length: Adjusted tick length 29 * @tick_length_base: Base value for @tick_length 30 * @time_state: State of the clock synchronization 31 * @time_status: Clock status bits 32 * @time_offset: Time adjustment in nanoseconds 33 * @time_constant: PLL time constant 34 * @time_maxerror: Maximum error in microseconds holding the NTP sync distance 35 * (NTP dispersion + delay / 2) 36 * @time_esterror: Estimated error in microseconds holding NTP dispersion 37 * @time_freq: Frequency offset scaled nsecs/secs 38 * @time_reftime: Time at last adjustment in seconds 39 * @time_adjust: Adjustment value 40 * @ntp_tick_adj: Constant boot-param configurable NTP tick adjustment (upscaled) 41 * @ntp_next_leap_sec: Second value of the next pending leapsecond, or TIME64_MAX if no leap 42 * 43 * @pps_valid: PPS signal watchdog counter 44 * @pps_tf: PPS phase median filter 45 * @pps_jitter: PPS current jitter in nanoseconds 46 * @pps_fbase: PPS beginning of the last freq interval 47 * 48 * Protected by the timekeeping locks. 49 */ 50 struct ntp_data { 51 unsigned long tick_usec; 52 u64 tick_length; 53 u64 tick_length_base; 54 int time_state; 55 int time_status; 56 s64 time_offset; 57 long time_constant; 58 long time_maxerror; 59 long time_esterror; 60 s64 time_freq; 61 time64_t time_reftime; 62 long time_adjust; 63 s64 ntp_tick_adj; 64 time64_t ntp_next_leap_sec; 65 #ifdef CONFIG_NTP_PPS 66 int pps_valid; 67 long pps_tf[3]; 68 long pps_jitter; 69 struct timespec64 pps_fbase; 70 #endif 71 }; 72 73 static struct ntp_data tk_ntp_data = { 74 .tick_usec = USER_TICK_USEC, 75 .time_state = TIME_OK, 76 .time_status = STA_UNSYNC, 77 .time_constant = 2, 78 .time_maxerror = NTP_PHASE_LIMIT, 79 .time_esterror = NTP_PHASE_LIMIT, 80 .ntp_next_leap_sec = TIME64_MAX, 81 }; 82 83 #define SECS_PER_DAY 86400 84 #define MAX_TICKADJ 500LL /* usecs */ 85 #define MAX_TICKADJ_SCALED \ 86 (((MAX_TICKADJ * NSEC_PER_USEC) << NTP_SCALE_SHIFT) / NTP_INTERVAL_FREQ) 87 #define MAX_TAI_OFFSET 100000 88 89 #ifdef CONFIG_NTP_PPS 90 91 /* 92 * The following variables are used when a pulse-per-second (PPS) signal 93 * is available. They establish the engineering parameters of the clock 94 * discipline loop when controlled by the PPS signal. 95 */ 96 #define PPS_VALID 10 /* PPS signal watchdog max (s) */ 97 #define PPS_POPCORN 4 /* popcorn spike threshold (shift) */ 98 #define PPS_INTMIN 2 /* min freq interval (s) (shift) */ 99 #define PPS_INTMAX 8 /* max freq interval (s) (shift) */ 100 #define PPS_INTCOUNT 4 /* number of consecutive good intervals to 101 increase pps_shift or consecutive bad 102 intervals to decrease it */ 103 #define PPS_MAXWANDER 100000 /* max PPS freq wander (ns/s) */ 104 105 static int pps_shift; /* current interval duration (s) (shift) */ 106 static int pps_intcnt; /* interval counter */ 107 static s64 pps_freq; /* frequency offset (scaled ns/s) */ 108 static long pps_stabil; /* current stability (scaled ns/s) */ 109 110 /* 111 * PPS signal quality monitors 112 */ 113 static long pps_calcnt; /* calibration intervals */ 114 static long pps_jitcnt; /* jitter limit exceeded */ 115 static long pps_stbcnt; /* stability limit exceeded */ 116 static long pps_errcnt; /* calibration errors */ 117 118 119 /* 120 * PPS kernel consumer compensates the whole phase error immediately. 121 * Otherwise, reduce the offset by a fixed factor times the time constant. 122 */ 123 static inline s64 ntp_offset_chunk(struct ntp_data *ntpdata, s64 offset) 124 { 125 if (ntpdata->time_status & STA_PPSTIME && ntpdata->time_status & STA_PPSSIGNAL) 126 return offset; 127 else 128 return shift_right(offset, SHIFT_PLL + ntpdata->time_constant); 129 } 130 131 static inline void pps_reset_freq_interval(void) 132 { 133 /* The PPS calibration interval may end surprisingly early */ 134 pps_shift = PPS_INTMIN; 135 pps_intcnt = 0; 136 } 137 138 /** 139 * pps_clear - Clears the PPS state variables 140 * @ntpdata: Pointer to ntp data 141 */ 142 static inline void pps_clear(struct ntp_data *ntpdata) 143 { 144 pps_reset_freq_interval(); 145 ntpdata->pps_tf[0] = 0; 146 ntpdata->pps_tf[1] = 0; 147 ntpdata->pps_tf[2] = 0; 148 ntpdata->pps_fbase.tv_sec = ntpdata->pps_fbase.tv_nsec = 0; 149 pps_freq = 0; 150 } 151 152 /* 153 * Decrease pps_valid to indicate that another second has passed since the 154 * last PPS signal. When it reaches 0, indicate that PPS signal is missing. 155 */ 156 static inline void pps_dec_valid(struct ntp_data *ntpdata) 157 { 158 if (ntpdata->pps_valid > 0) { 159 ntpdata->pps_valid--; 160 } else { 161 ntpdata->time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER | 162 STA_PPSWANDER | STA_PPSERROR); 163 pps_clear(ntpdata); 164 } 165 } 166 167 static inline void pps_set_freq(s64 freq) 168 { 169 pps_freq = freq; 170 } 171 172 static inline bool is_error_status(int status) 173 { 174 return (status & (STA_UNSYNC|STA_CLOCKERR)) 175 /* 176 * PPS signal lost when either PPS time or PPS frequency 177 * synchronization requested 178 */ 179 || ((status & (STA_PPSFREQ|STA_PPSTIME)) 180 && !(status & STA_PPSSIGNAL)) 181 /* 182 * PPS jitter exceeded when PPS time synchronization 183 * requested 184 */ 185 || ((status & (STA_PPSTIME|STA_PPSJITTER)) 186 == (STA_PPSTIME|STA_PPSJITTER)) 187 /* 188 * PPS wander exceeded or calibration error when PPS 189 * frequency synchronization requested 190 */ 191 || ((status & STA_PPSFREQ) 192 && (status & (STA_PPSWANDER|STA_PPSERROR))); 193 } 194 195 static inline void pps_fill_timex(struct ntp_data *ntpdata, struct __kernel_timex *txc) 196 { 197 txc->ppsfreq = shift_right((pps_freq >> PPM_SCALE_INV_SHIFT) * 198 PPM_SCALE_INV, NTP_SCALE_SHIFT); 199 txc->jitter = ntpdata->pps_jitter; 200 if (!(ntpdata->time_status & STA_NANO)) 201 txc->jitter = ntpdata->pps_jitter / NSEC_PER_USEC; 202 txc->shift = pps_shift; 203 txc->stabil = pps_stabil; 204 txc->jitcnt = pps_jitcnt; 205 txc->calcnt = pps_calcnt; 206 txc->errcnt = pps_errcnt; 207 txc->stbcnt = pps_stbcnt; 208 } 209 210 #else /* !CONFIG_NTP_PPS */ 211 212 static inline s64 ntp_offset_chunk(struct ntp_data *ntpdata, s64 offset) 213 { 214 return shift_right(offset, SHIFT_PLL + ntpdata->time_constant); 215 } 216 217 static inline void pps_reset_freq_interval(void) {} 218 static inline void pps_clear(struct ntp_data *ntpdata) {} 219 static inline void pps_dec_valid(struct ntp_data *ntpdata) {} 220 static inline void pps_set_freq(s64 freq) {} 221 222 static inline bool is_error_status(int status) 223 { 224 return status & (STA_UNSYNC|STA_CLOCKERR); 225 } 226 227 static inline void pps_fill_timex(struct ntp_data *ntpdata, struct __kernel_timex *txc) 228 { 229 /* PPS is not implemented, so these are zero */ 230 txc->ppsfreq = 0; 231 txc->jitter = 0; 232 txc->shift = 0; 233 txc->stabil = 0; 234 txc->jitcnt = 0; 235 txc->calcnt = 0; 236 txc->errcnt = 0; 237 txc->stbcnt = 0; 238 } 239 240 #endif /* CONFIG_NTP_PPS */ 241 242 /* 243 * Update tick_length and tick_length_base, based on tick_usec, ntp_tick_adj and 244 * time_freq: 245 */ 246 static void ntp_update_frequency(struct ntp_data *ntpdata) 247 { 248 u64 second_length, new_base, tick_usec = (u64)ntpdata->tick_usec; 249 250 second_length = (u64)(tick_usec * NSEC_PER_USEC * USER_HZ) << NTP_SCALE_SHIFT; 251 252 second_length += ntpdata->ntp_tick_adj; 253 second_length += ntpdata->time_freq; 254 255 new_base = div_u64(second_length, NTP_INTERVAL_FREQ); 256 257 /* 258 * Don't wait for the next second_overflow, apply the change to the 259 * tick length immediately: 260 */ 261 ntpdata->tick_length += new_base - ntpdata->tick_length_base; 262 ntpdata->tick_length_base = new_base; 263 } 264 265 static inline s64 ntp_update_offset_fll(struct ntp_data *ntpdata, s64 offset64, long secs) 266 { 267 ntpdata->time_status &= ~STA_MODE; 268 269 if (secs < MINSEC) 270 return 0; 271 272 if (!(ntpdata->time_status & STA_FLL) && (secs <= MAXSEC)) 273 return 0; 274 275 ntpdata->time_status |= STA_MODE; 276 277 return div64_long(offset64 << (NTP_SCALE_SHIFT - SHIFT_FLL), secs); 278 } 279 280 static void ntp_update_offset(struct ntp_data *ntpdata, long offset) 281 { 282 s64 freq_adj, offset64; 283 long secs, real_secs; 284 285 if (!(ntpdata->time_status & STA_PLL)) 286 return; 287 288 if (!(ntpdata->time_status & STA_NANO)) { 289 /* Make sure the multiplication below won't overflow */ 290 offset = clamp(offset, -USEC_PER_SEC, USEC_PER_SEC); 291 offset *= NSEC_PER_USEC; 292 } 293 294 /* Scale the phase adjustment and clamp to the operating range. */ 295 offset = clamp(offset, -MAXPHASE, MAXPHASE); 296 297 /* 298 * Select how the frequency is to be controlled 299 * and in which mode (PLL or FLL). 300 */ 301 real_secs = __ktime_get_real_seconds(); 302 secs = (long)(real_secs - ntpdata->time_reftime); 303 if (unlikely(ntpdata->time_status & STA_FREQHOLD)) 304 secs = 0; 305 306 ntpdata->time_reftime = real_secs; 307 308 offset64 = offset; 309 freq_adj = ntp_update_offset_fll(ntpdata, offset64, secs); 310 311 /* 312 * Clamp update interval to reduce PLL gain with low 313 * sampling rate (e.g. intermittent network connection) 314 * to avoid instability. 315 */ 316 if (unlikely(secs > 1 << (SHIFT_PLL + 1 + ntpdata->time_constant))) 317 secs = 1 << (SHIFT_PLL + 1 + ntpdata->time_constant); 318 319 freq_adj += (offset64 * secs) << 320 (NTP_SCALE_SHIFT - 2 * (SHIFT_PLL + 2 + ntpdata->time_constant)); 321 322 freq_adj = min(freq_adj + ntpdata->time_freq, MAXFREQ_SCALED); 323 324 ntpdata->time_freq = max(freq_adj, -MAXFREQ_SCALED); 325 326 ntpdata->time_offset = div_s64(offset64 << NTP_SCALE_SHIFT, NTP_INTERVAL_FREQ); 327 } 328 329 static void __ntp_clear(struct ntp_data *ntpdata) 330 { 331 /* Stop active adjtime() */ 332 ntpdata->time_adjust = 0; 333 ntpdata->time_status |= STA_UNSYNC; 334 ntpdata->time_maxerror = NTP_PHASE_LIMIT; 335 ntpdata->time_esterror = NTP_PHASE_LIMIT; 336 337 ntp_update_frequency(ntpdata); 338 339 ntpdata->tick_length = ntpdata->tick_length_base; 340 ntpdata->time_offset = 0; 341 342 ntpdata->ntp_next_leap_sec = TIME64_MAX; 343 /* Clear PPS state variables */ 344 pps_clear(ntpdata); 345 } 346 347 /** 348 * ntp_clear - Clears the NTP state variables 349 */ 350 void ntp_clear(void) 351 { 352 __ntp_clear(&tk_ntp_data); 353 } 354 355 356 u64 ntp_tick_length(void) 357 { 358 return tk_ntp_data.tick_length; 359 } 360 361 /** 362 * ntp_get_next_leap - Returns the next leapsecond in CLOCK_REALTIME ktime_t 363 * 364 * Provides the time of the next leapsecond against CLOCK_REALTIME in 365 * a ktime_t format. Returns KTIME_MAX if no leapsecond is pending. 366 */ 367 ktime_t ntp_get_next_leap(void) 368 { 369 struct ntp_data *ntpdata = &tk_ntp_data; 370 ktime_t ret; 371 372 if ((ntpdata->time_state == TIME_INS) && (ntpdata->time_status & STA_INS)) 373 return ktime_set(ntpdata->ntp_next_leap_sec, 0); 374 ret = KTIME_MAX; 375 return ret; 376 } 377 378 /* 379 * This routine handles the overflow of the microsecond field 380 * 381 * The tricky bits of code to handle the accurate clock support 382 * were provided by Dave Mills ([email protected]) of NTP fame. 383 * They were originally developed for SUN and DEC kernels. 384 * All the kudos should go to Dave for this stuff. 385 * 386 * Also handles leap second processing, and returns leap offset 387 */ 388 int second_overflow(time64_t secs) 389 { 390 struct ntp_data *ntpdata = &tk_ntp_data; 391 s64 delta; 392 int leap = 0; 393 s32 rem; 394 395 /* 396 * Leap second processing. If in leap-insert state at the end of the 397 * day, the system clock is set back one second; if in leap-delete 398 * state, the system clock is set ahead one second. 399 */ 400 switch (ntpdata->time_state) { 401 case TIME_OK: 402 if (ntpdata->time_status & STA_INS) { 403 ntpdata->time_state = TIME_INS; 404 div_s64_rem(secs, SECS_PER_DAY, &rem); 405 ntpdata->ntp_next_leap_sec = secs + SECS_PER_DAY - rem; 406 } else if (ntpdata->time_status & STA_DEL) { 407 ntpdata->time_state = TIME_DEL; 408 div_s64_rem(secs + 1, SECS_PER_DAY, &rem); 409 ntpdata->ntp_next_leap_sec = secs + SECS_PER_DAY - rem; 410 } 411 break; 412 case TIME_INS: 413 if (!(ntpdata->time_status & STA_INS)) { 414 ntpdata->ntp_next_leap_sec = TIME64_MAX; 415 ntpdata->time_state = TIME_OK; 416 } else if (secs == ntpdata->ntp_next_leap_sec) { 417 leap = -1; 418 ntpdata->time_state = TIME_OOP; 419 pr_notice("Clock: inserting leap second 23:59:60 UTC\n"); 420 } 421 break; 422 case TIME_DEL: 423 if (!(ntpdata->time_status & STA_DEL)) { 424 ntpdata->ntp_next_leap_sec = TIME64_MAX; 425 ntpdata->time_state = TIME_OK; 426 } else if (secs == ntpdata->ntp_next_leap_sec) { 427 leap = 1; 428 ntpdata->ntp_next_leap_sec = TIME64_MAX; 429 ntpdata->time_state = TIME_WAIT; 430 pr_notice("Clock: deleting leap second 23:59:59 UTC\n"); 431 } 432 break; 433 case TIME_OOP: 434 ntpdata->ntp_next_leap_sec = TIME64_MAX; 435 ntpdata->time_state = TIME_WAIT; 436 break; 437 case TIME_WAIT: 438 if (!(ntpdata->time_status & (STA_INS | STA_DEL))) 439 ntpdata->time_state = TIME_OK; 440 break; 441 } 442 443 /* Bump the maxerror field */ 444 ntpdata->time_maxerror += MAXFREQ / NSEC_PER_USEC; 445 if (ntpdata->time_maxerror > NTP_PHASE_LIMIT) { 446 ntpdata->time_maxerror = NTP_PHASE_LIMIT; 447 ntpdata->time_status |= STA_UNSYNC; 448 } 449 450 /* Compute the phase adjustment for the next second */ 451 ntpdata->tick_length = ntpdata->tick_length_base; 452 453 delta = ntp_offset_chunk(ntpdata, ntpdata->time_offset); 454 ntpdata->time_offset -= delta; 455 ntpdata->tick_length += delta; 456 457 /* Check PPS signal */ 458 pps_dec_valid(ntpdata); 459 460 if (!ntpdata->time_adjust) 461 goto out; 462 463 if (ntpdata->time_adjust > MAX_TICKADJ) { 464 ntpdata->time_adjust -= MAX_TICKADJ; 465 ntpdata->tick_length += MAX_TICKADJ_SCALED; 466 goto out; 467 } 468 469 if (ntpdata->time_adjust < -MAX_TICKADJ) { 470 ntpdata->time_adjust += MAX_TICKADJ; 471 ntpdata->tick_length -= MAX_TICKADJ_SCALED; 472 goto out; 473 } 474 475 ntpdata->tick_length += (s64)(ntpdata->time_adjust * NSEC_PER_USEC / NTP_INTERVAL_FREQ) 476 << NTP_SCALE_SHIFT; 477 ntpdata->time_adjust = 0; 478 479 out: 480 return leap; 481 } 482 483 #if defined(CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) 484 static void sync_hw_clock(struct work_struct *work); 485 static DECLARE_WORK(sync_work, sync_hw_clock); 486 static struct hrtimer sync_hrtimer; 487 #define SYNC_PERIOD_NS (11ULL * 60 * NSEC_PER_SEC) 488 489 static enum hrtimer_restart sync_timer_callback(struct hrtimer *timer) 490 { 491 queue_work(system_freezable_power_efficient_wq, &sync_work); 492 493 return HRTIMER_NORESTART; 494 } 495 496 static void sched_sync_hw_clock(unsigned long offset_nsec, bool retry) 497 { 498 ktime_t exp = ktime_set(ktime_get_real_seconds(), 0); 499 500 if (retry) 501 exp = ktime_add_ns(exp, 2ULL * NSEC_PER_SEC - offset_nsec); 502 else 503 exp = ktime_add_ns(exp, SYNC_PERIOD_NS - offset_nsec); 504 505 hrtimer_start(&sync_hrtimer, exp, HRTIMER_MODE_ABS); 506 } 507 508 /* 509 * Check whether @now is correct versus the required time to update the RTC 510 * and calculate the value which needs to be written to the RTC so that the 511 * next seconds increment of the RTC after the write is aligned with the next 512 * seconds increment of clock REALTIME. 513 * 514 * tsched t1 write(t2.tv_sec - 1sec)) t2 RTC increments seconds 515 * 516 * t2.tv_nsec == 0 517 * tsched = t2 - set_offset_nsec 518 * newval = t2 - NSEC_PER_SEC 519 * 520 * ==> neval = tsched + set_offset_nsec - NSEC_PER_SEC 521 * 522 * As the execution of this code is not guaranteed to happen exactly at 523 * tsched this allows it to happen within a fuzzy region: 524 * 525 * abs(now - tsched) < FUZZ 526 * 527 * If @now is not inside the allowed window the function returns false. 528 */ 529 static inline bool rtc_tv_nsec_ok(unsigned long set_offset_nsec, 530 struct timespec64 *to_set, 531 const struct timespec64 *now) 532 { 533 /* Allowed error in tv_nsec, arbitrarily set to 5 jiffies in ns. */ 534 const unsigned long TIME_SET_NSEC_FUZZ = TICK_NSEC * 5; 535 struct timespec64 delay = {.tv_sec = -1, 536 .tv_nsec = set_offset_nsec}; 537 538 *to_set = timespec64_add(*now, delay); 539 540 if (to_set->tv_nsec < TIME_SET_NSEC_FUZZ) { 541 to_set->tv_nsec = 0; 542 return true; 543 } 544 545 if (to_set->tv_nsec > NSEC_PER_SEC - TIME_SET_NSEC_FUZZ) { 546 to_set->tv_sec++; 547 to_set->tv_nsec = 0; 548 return true; 549 } 550 return false; 551 } 552 553 #ifdef CONFIG_GENERIC_CMOS_UPDATE 554 int __weak update_persistent_clock64(struct timespec64 now64) 555 { 556 return -ENODEV; 557 } 558 #else 559 static inline int update_persistent_clock64(struct timespec64 now64) 560 { 561 return -ENODEV; 562 } 563 #endif 564 565 #ifdef CONFIG_RTC_SYSTOHC 566 /* Save NTP synchronized time to the RTC */ 567 static int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec) 568 { 569 struct rtc_device *rtc; 570 struct rtc_time tm; 571 int err = -ENODEV; 572 573 rtc = rtc_class_open(CONFIG_RTC_SYSTOHC_DEVICE); 574 if (!rtc) 575 return -ENODEV; 576 577 if (!rtc->ops || !rtc->ops->set_time) 578 goto out_close; 579 580 /* First call might not have the correct offset */ 581 if (*offset_nsec == rtc->set_offset_nsec) { 582 rtc_time64_to_tm(to_set->tv_sec, &tm); 583 err = rtc_set_time(rtc, &tm); 584 } else { 585 /* Store the update offset and let the caller try again */ 586 *offset_nsec = rtc->set_offset_nsec; 587 err = -EAGAIN; 588 } 589 out_close: 590 rtc_class_close(rtc); 591 return err; 592 } 593 #else 594 static inline int update_rtc(struct timespec64 *to_set, unsigned long *offset_nsec) 595 { 596 return -ENODEV; 597 } 598 #endif 599 600 /** 601 * ntp_synced - Tells whether the NTP status is not UNSYNC 602 * Returns: true if not UNSYNC, false otherwise 603 */ 604 static inline bool ntp_synced(void) 605 { 606 return !(tk_ntp_data.time_status & STA_UNSYNC); 607 } 608 609 /* 610 * If we have an externally synchronized Linux clock, then update RTC clock 611 * accordingly every ~11 minutes. Generally RTCs can only store second 612 * precision, but many RTCs will adjust the phase of their second tick to 613 * match the moment of update. This infrastructure arranges to call to the RTC 614 * set at the correct moment to phase synchronize the RTC second tick over 615 * with the kernel clock. 616 */ 617 static void sync_hw_clock(struct work_struct *work) 618 { 619 /* 620 * The default synchronization offset is 500ms for the deprecated 621 * update_persistent_clock64() under the assumption that it uses 622 * the infamous CMOS clock (MC146818). 623 */ 624 static unsigned long offset_nsec = NSEC_PER_SEC / 2; 625 struct timespec64 now, to_set; 626 int res = -EAGAIN; 627 628 /* 629 * Don't update if STA_UNSYNC is set and if ntp_notify_cmos_timer() 630 * managed to schedule the work between the timer firing and the 631 * work being able to rearm the timer. Wait for the timer to expire. 632 */ 633 if (!ntp_synced() || hrtimer_is_queued(&sync_hrtimer)) 634 return; 635 636 ktime_get_real_ts64(&now); 637 /* If @now is not in the allowed window, try again */ 638 if (!rtc_tv_nsec_ok(offset_nsec, &to_set, &now)) 639 goto rearm; 640 641 /* Take timezone adjusted RTCs into account */ 642 if (persistent_clock_is_local) 643 to_set.tv_sec -= (sys_tz.tz_minuteswest * 60); 644 645 /* Try the legacy RTC first. */ 646 res = update_persistent_clock64(to_set); 647 if (res != -ENODEV) 648 goto rearm; 649 650 /* Try the RTC class */ 651 res = update_rtc(&to_set, &offset_nsec); 652 if (res == -ENODEV) 653 return; 654 rearm: 655 sched_sync_hw_clock(offset_nsec, res != 0); 656 } 657 658 void ntp_notify_cmos_timer(bool offset_set) 659 { 660 /* 661 * If the time jumped (using ADJ_SETOFFSET) cancels sync timer, 662 * which may have been running if the time was synchronized 663 * prior to the ADJ_SETOFFSET call. 664 */ 665 if (offset_set) 666 hrtimer_cancel(&sync_hrtimer); 667 668 /* 669 * When the work is currently executed but has not yet the timer 670 * rearmed this queues the work immediately again. No big issue, 671 * just a pointless work scheduled. 672 */ 673 if (ntp_synced() && !hrtimer_is_queued(&sync_hrtimer)) 674 queue_work(system_freezable_power_efficient_wq, &sync_work); 675 } 676 677 static void __init ntp_init_cmos_sync(void) 678 { 679 hrtimer_init(&sync_hrtimer, CLOCK_REALTIME, HRTIMER_MODE_ABS); 680 sync_hrtimer.function = sync_timer_callback; 681 } 682 #else /* CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) */ 683 static inline void __init ntp_init_cmos_sync(void) { } 684 #endif /* !CONFIG_GENERIC_CMOS_UPDATE) || defined(CONFIG_RTC_SYSTOHC) */ 685 686 /* 687 * Propagate a new txc->status value into the NTP state: 688 */ 689 static inline void process_adj_status(struct ntp_data *ntpdata, const struct __kernel_timex *txc) 690 { 691 if ((ntpdata->time_status & STA_PLL) && !(txc->status & STA_PLL)) { 692 ntpdata->time_state = TIME_OK; 693 ntpdata->time_status = STA_UNSYNC; 694 ntpdata->ntp_next_leap_sec = TIME64_MAX; 695 /* Restart PPS frequency calibration */ 696 pps_reset_freq_interval(); 697 } 698 699 /* 700 * If we turn on PLL adjustments then reset the 701 * reference time to current time. 702 */ 703 if (!(ntpdata->time_status & STA_PLL) && (txc->status & STA_PLL)) 704 ntpdata->time_reftime = __ktime_get_real_seconds(); 705 706 /* only set allowed bits */ 707 ntpdata->time_status &= STA_RONLY; 708 ntpdata->time_status |= txc->status & ~STA_RONLY; 709 } 710 711 static inline void process_adjtimex_modes(struct ntp_data *ntpdata, const struct __kernel_timex *txc, 712 s32 *time_tai) 713 { 714 if (txc->modes & ADJ_STATUS) 715 process_adj_status(ntpdata, txc); 716 717 if (txc->modes & ADJ_NANO) 718 ntpdata->time_status |= STA_NANO; 719 720 if (txc->modes & ADJ_MICRO) 721 ntpdata->time_status &= ~STA_NANO; 722 723 if (txc->modes & ADJ_FREQUENCY) { 724 ntpdata->time_freq = txc->freq * PPM_SCALE; 725 ntpdata->time_freq = min(ntpdata->time_freq, MAXFREQ_SCALED); 726 ntpdata->time_freq = max(ntpdata->time_freq, -MAXFREQ_SCALED); 727 /* Update pps_freq */ 728 pps_set_freq(ntpdata->time_freq); 729 } 730 731 if (txc->modes & ADJ_MAXERROR) 732 ntpdata->time_maxerror = clamp(txc->maxerror, 0, NTP_PHASE_LIMIT); 733 734 if (txc->modes & ADJ_ESTERROR) 735 ntpdata->time_esterror = clamp(txc->esterror, 0, NTP_PHASE_LIMIT); 736 737 if (txc->modes & ADJ_TIMECONST) { 738 ntpdata->time_constant = clamp(txc->constant, 0, MAXTC); 739 if (!(ntpdata->time_status & STA_NANO)) 740 ntpdata->time_constant += 4; 741 ntpdata->time_constant = clamp(ntpdata->time_constant, 0, MAXTC); 742 } 743 744 if (txc->modes & ADJ_TAI && txc->constant >= 0 && txc->constant <= MAX_TAI_OFFSET) 745 *time_tai = txc->constant; 746 747 if (txc->modes & ADJ_OFFSET) 748 ntp_update_offset(ntpdata, txc->offset); 749 750 if (txc->modes & ADJ_TICK) 751 ntpdata->tick_usec = txc->tick; 752 753 if (txc->modes & (ADJ_TICK|ADJ_FREQUENCY|ADJ_OFFSET)) 754 ntp_update_frequency(ntpdata); 755 } 756 757 /* 758 * adjtimex() mainly allows reading (and writing, if superuser) of 759 * kernel time-keeping variables. used by xntpd. 760 */ 761 int __do_adjtimex(struct __kernel_timex *txc, const struct timespec64 *ts, 762 s32 *time_tai, struct audit_ntp_data *ad) 763 { 764 struct ntp_data *ntpdata = &tk_ntp_data; 765 int result; 766 767 if (txc->modes & ADJ_ADJTIME) { 768 long save_adjust = ntpdata->time_adjust; 769 770 if (!(txc->modes & ADJ_OFFSET_READONLY)) { 771 /* adjtime() is independent from ntp_adjtime() */ 772 ntpdata->time_adjust = txc->offset; 773 ntp_update_frequency(ntpdata); 774 775 audit_ntp_set_old(ad, AUDIT_NTP_ADJUST, save_adjust); 776 audit_ntp_set_new(ad, AUDIT_NTP_ADJUST, ntpdata->time_adjust); 777 } 778 txc->offset = save_adjust; 779 } else { 780 /* If there are input parameters, then process them: */ 781 if (txc->modes) { 782 audit_ntp_set_old(ad, AUDIT_NTP_OFFSET, ntpdata->time_offset); 783 audit_ntp_set_old(ad, AUDIT_NTP_FREQ, ntpdata->time_freq); 784 audit_ntp_set_old(ad, AUDIT_NTP_STATUS, ntpdata->time_status); 785 audit_ntp_set_old(ad, AUDIT_NTP_TAI, *time_tai); 786 audit_ntp_set_old(ad, AUDIT_NTP_TICK, ntpdata->tick_usec); 787 788 process_adjtimex_modes(ntpdata, txc, time_tai); 789 790 audit_ntp_set_new(ad, AUDIT_NTP_OFFSET, ntpdata->time_offset); 791 audit_ntp_set_new(ad, AUDIT_NTP_FREQ, ntpdata->time_freq); 792 audit_ntp_set_new(ad, AUDIT_NTP_STATUS, ntpdata->time_status); 793 audit_ntp_set_new(ad, AUDIT_NTP_TAI, *time_tai); 794 audit_ntp_set_new(ad, AUDIT_NTP_TICK, ntpdata->tick_usec); 795 } 796 797 txc->offset = shift_right(ntpdata->time_offset * NTP_INTERVAL_FREQ, NTP_SCALE_SHIFT); 798 if (!(ntpdata->time_status & STA_NANO)) 799 txc->offset = (u32)txc->offset / NSEC_PER_USEC; 800 } 801 802 result = ntpdata->time_state; 803 if (is_error_status(ntpdata->time_status)) 804 result = TIME_ERROR; 805 806 txc->freq = shift_right((ntpdata->time_freq >> PPM_SCALE_INV_SHIFT) * 807 PPM_SCALE_INV, NTP_SCALE_SHIFT); 808 txc->maxerror = ntpdata->time_maxerror; 809 txc->esterror = ntpdata->time_esterror; 810 txc->status = ntpdata->time_status; 811 txc->constant = ntpdata->time_constant; 812 txc->precision = 1; 813 txc->tolerance = MAXFREQ_SCALED / PPM_SCALE; 814 txc->tick = ntpdata->tick_usec; 815 txc->tai = *time_tai; 816 817 /* Fill PPS status fields */ 818 pps_fill_timex(ntpdata, txc); 819 820 txc->time.tv_sec = ts->tv_sec; 821 txc->time.tv_usec = ts->tv_nsec; 822 if (!(ntpdata->time_status & STA_NANO)) 823 txc->time.tv_usec = ts->tv_nsec / NSEC_PER_USEC; 824 825 /* Handle leapsec adjustments */ 826 if (unlikely(ts->tv_sec >= ntpdata->ntp_next_leap_sec)) { 827 if ((ntpdata->time_state == TIME_INS) && (ntpdata->time_status & STA_INS)) { 828 result = TIME_OOP; 829 txc->tai++; 830 txc->time.tv_sec--; 831 } 832 if ((ntpdata->time_state == TIME_DEL) && (ntpdata->time_status & STA_DEL)) { 833 result = TIME_WAIT; 834 txc->tai--; 835 txc->time.tv_sec++; 836 } 837 if ((ntpdata->time_state == TIME_OOP) && (ts->tv_sec == ntpdata->ntp_next_leap_sec)) 838 result = TIME_WAIT; 839 } 840 841 return result; 842 } 843 844 #ifdef CONFIG_NTP_PPS 845 846 /* 847 * struct pps_normtime is basically a struct timespec, but it is 848 * semantically different (and it is the reason why it was invented): 849 * pps_normtime.nsec has a range of ( -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] 850 * while timespec.tv_nsec has a range of [0, NSEC_PER_SEC) 851 */ 852 struct pps_normtime { 853 s64 sec; /* seconds */ 854 long nsec; /* nanoseconds */ 855 }; 856 857 /* 858 * Normalize the timestamp so that nsec is in the 859 * [ -NSEC_PER_SEC / 2, NSEC_PER_SEC / 2 ] interval 860 */ 861 static inline struct pps_normtime pps_normalize_ts(struct timespec64 ts) 862 { 863 struct pps_normtime norm = { 864 .sec = ts.tv_sec, 865 .nsec = ts.tv_nsec 866 }; 867 868 if (norm.nsec > (NSEC_PER_SEC >> 1)) { 869 norm.nsec -= NSEC_PER_SEC; 870 norm.sec++; 871 } 872 873 return norm; 874 } 875 876 /* Get current phase correction and jitter */ 877 static inline long pps_phase_filter_get(struct ntp_data *ntpdata, long *jitter) 878 { 879 *jitter = ntpdata->pps_tf[0] - ntpdata->pps_tf[1]; 880 if (*jitter < 0) 881 *jitter = -*jitter; 882 883 /* TODO: test various filters */ 884 return ntpdata->pps_tf[0]; 885 } 886 887 /* Add the sample to the phase filter */ 888 static inline void pps_phase_filter_add(struct ntp_data *ntpdata, long err) 889 { 890 ntpdata->pps_tf[2] = ntpdata->pps_tf[1]; 891 ntpdata->pps_tf[1] = ntpdata->pps_tf[0]; 892 ntpdata->pps_tf[0] = err; 893 } 894 895 /* 896 * Decrease frequency calibration interval length. It is halved after four 897 * consecutive unstable intervals. 898 */ 899 static inline void pps_dec_freq_interval(void) 900 { 901 if (--pps_intcnt <= -PPS_INTCOUNT) { 902 pps_intcnt = -PPS_INTCOUNT; 903 if (pps_shift > PPS_INTMIN) { 904 pps_shift--; 905 pps_intcnt = 0; 906 } 907 } 908 } 909 910 /* 911 * Increase frequency calibration interval length. It is doubled after 912 * four consecutive stable intervals. 913 */ 914 static inline void pps_inc_freq_interval(void) 915 { 916 if (++pps_intcnt >= PPS_INTCOUNT) { 917 pps_intcnt = PPS_INTCOUNT; 918 if (pps_shift < PPS_INTMAX) { 919 pps_shift++; 920 pps_intcnt = 0; 921 } 922 } 923 } 924 925 /* 926 * Update clock frequency based on MONOTONIC_RAW clock PPS signal 927 * timestamps 928 * 929 * At the end of the calibration interval the difference between the 930 * first and last MONOTONIC_RAW clock timestamps divided by the length 931 * of the interval becomes the frequency update. If the interval was 932 * too long, the data are discarded. 933 * Returns the difference between old and new frequency values. 934 */ 935 static long hardpps_update_freq(struct ntp_data *ntpdata, struct pps_normtime freq_norm) 936 { 937 long delta, delta_mod; 938 s64 ftemp; 939 940 /* Check if the frequency interval was too long */ 941 if (freq_norm.sec > (2 << pps_shift)) { 942 ntpdata->time_status |= STA_PPSERROR; 943 pps_errcnt++; 944 pps_dec_freq_interval(); 945 printk_deferred(KERN_ERR "hardpps: PPSERROR: interval too long - %lld s\n", 946 freq_norm.sec); 947 return 0; 948 } 949 950 /* 951 * Here the raw frequency offset and wander (stability) is 952 * calculated. If the wander is less than the wander threshold the 953 * interval is increased; otherwise it is decreased. 954 */ 955 ftemp = div_s64(((s64)(-freq_norm.nsec)) << NTP_SCALE_SHIFT, 956 freq_norm.sec); 957 delta = shift_right(ftemp - pps_freq, NTP_SCALE_SHIFT); 958 pps_freq = ftemp; 959 if (delta > PPS_MAXWANDER || delta < -PPS_MAXWANDER) { 960 printk_deferred(KERN_WARNING "hardpps: PPSWANDER: change=%ld\n", delta); 961 ntpdata->time_status |= STA_PPSWANDER; 962 pps_stbcnt++; 963 pps_dec_freq_interval(); 964 } else { 965 /* Good sample */ 966 pps_inc_freq_interval(); 967 } 968 969 /* 970 * The stability metric is calculated as the average of recent 971 * frequency changes, but is used only for performance monitoring 972 */ 973 delta_mod = delta; 974 if (delta_mod < 0) 975 delta_mod = -delta_mod; 976 pps_stabil += (div_s64(((s64)delta_mod) << (NTP_SCALE_SHIFT - SHIFT_USEC), 977 NSEC_PER_USEC) - pps_stabil) >> PPS_INTMIN; 978 979 /* If enabled, the system clock frequency is updated */ 980 if ((ntpdata->time_status & STA_PPSFREQ) && !(ntpdata->time_status & STA_FREQHOLD)) { 981 ntpdata->time_freq = pps_freq; 982 ntp_update_frequency(ntpdata); 983 } 984 985 return delta; 986 } 987 988 /* Correct REALTIME clock phase error against PPS signal */ 989 static void hardpps_update_phase(struct ntp_data *ntpdata, long error) 990 { 991 long correction = -error; 992 long jitter; 993 994 /* Add the sample to the median filter */ 995 pps_phase_filter_add(ntpdata, correction); 996 correction = pps_phase_filter_get(ntpdata, &jitter); 997 998 /* 999 * Nominal jitter is due to PPS signal noise. If it exceeds the 1000 * threshold, the sample is discarded; otherwise, if so enabled, 1001 * the time offset is updated. 1002 */ 1003 if (jitter > (ntpdata->pps_jitter << PPS_POPCORN)) { 1004 printk_deferred(KERN_WARNING "hardpps: PPSJITTER: jitter=%ld, limit=%ld\n", 1005 jitter, (ntpdata->pps_jitter << PPS_POPCORN)); 1006 ntpdata->time_status |= STA_PPSJITTER; 1007 pps_jitcnt++; 1008 } else if (ntpdata->time_status & STA_PPSTIME) { 1009 /* Correct the time using the phase offset */ 1010 ntpdata->time_offset = div_s64(((s64)correction) << NTP_SCALE_SHIFT, 1011 NTP_INTERVAL_FREQ); 1012 /* Cancel running adjtime() */ 1013 ntpdata->time_adjust = 0; 1014 } 1015 /* Update jitter */ 1016 ntpdata->pps_jitter += (jitter - ntpdata->pps_jitter) >> PPS_INTMIN; 1017 } 1018 1019 /* 1020 * __hardpps() - discipline CPU clock oscillator to external PPS signal 1021 * 1022 * This routine is called at each PPS signal arrival in order to 1023 * discipline the CPU clock oscillator to the PPS signal. It takes two 1024 * parameters: REALTIME and MONOTONIC_RAW clock timestamps. The former 1025 * is used to correct clock phase error and the latter is used to 1026 * correct the frequency. 1027 * 1028 * This code is based on David Mills's reference nanokernel 1029 * implementation. It was mostly rewritten but keeps the same idea. 1030 */ 1031 void __hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts) 1032 { 1033 struct pps_normtime pts_norm, freq_norm; 1034 struct ntp_data *ntpdata = &tk_ntp_data; 1035 1036 pts_norm = pps_normalize_ts(*phase_ts); 1037 1038 /* Clear the error bits, they will be set again if needed */ 1039 ntpdata->time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR); 1040 1041 /* indicate signal presence */ 1042 ntpdata->time_status |= STA_PPSSIGNAL; 1043 ntpdata->pps_valid = PPS_VALID; 1044 1045 /* 1046 * When called for the first time, just start the frequency 1047 * interval 1048 */ 1049 if (unlikely(ntpdata->pps_fbase.tv_sec == 0)) { 1050 ntpdata->pps_fbase = *raw_ts; 1051 return; 1052 } 1053 1054 /* Ok, now we have a base for frequency calculation */ 1055 freq_norm = pps_normalize_ts(timespec64_sub(*raw_ts, ntpdata->pps_fbase)); 1056 1057 /* 1058 * Check that the signal is in the range 1059 * [1s - MAXFREQ us, 1s + MAXFREQ us], otherwise reject it 1060 */ 1061 if ((freq_norm.sec == 0) || (freq_norm.nsec > MAXFREQ * freq_norm.sec) || 1062 (freq_norm.nsec < -MAXFREQ * freq_norm.sec)) { 1063 ntpdata->time_status |= STA_PPSJITTER; 1064 /* Restart the frequency calibration interval */ 1065 ntpdata->pps_fbase = *raw_ts; 1066 printk_deferred(KERN_ERR "hardpps: PPSJITTER: bad pulse\n"); 1067 return; 1068 } 1069 1070 /* Signal is ok. Check if the current frequency interval is finished */ 1071 if (freq_norm.sec >= (1 << pps_shift)) { 1072 pps_calcnt++; 1073 /* Restart the frequency calibration interval */ 1074 ntpdata->pps_fbase = *raw_ts; 1075 hardpps_update_freq(ntpdata, freq_norm); 1076 } 1077 1078 hardpps_update_phase(ntpdata, pts_norm.nsec); 1079 1080 } 1081 #endif /* CONFIG_NTP_PPS */ 1082 1083 static int __init ntp_tick_adj_setup(char *str) 1084 { 1085 int rc = kstrtos64(str, 0, &tk_ntp_data.ntp_tick_adj); 1086 if (rc) 1087 return rc; 1088 1089 tk_ntp_data.ntp_tick_adj <<= NTP_SCALE_SHIFT; 1090 return 1; 1091 } 1092 1093 __setup("ntp_tick_adj=", ntp_tick_adj_setup); 1094 1095 void __init ntp_init(void) 1096 { 1097 ntp_clear(); 1098 ntp_init_cmos_sync(); 1099 } 1100