1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Kernel timekeeping code and accessor functions. Based on code from 4 * timer.c, moved in commit 8524070b7982. 5 */ 6 #include <linux/audit.h> 7 #include <linux/clocksource.h> 8 #include <linux/compiler.h> 9 #include <linux/jiffies.h> 10 #include <linux/kobject.h> 11 #include <linux/module.h> 12 #include <linux/nmi.h> 13 #include <linux/pvclock_gtod.h> 14 #include <linux/random.h> 15 #include <linux/sched/clock.h> 16 #include <linux/sched/loadavg.h> 17 #include <linux/static_key.h> 18 #include <linux/stop_machine.h> 19 #include <linux/syscore_ops.h> 20 #include <linux/tick.h> 21 #include <linux/time.h> 22 #include <linux/timex.h> 23 #include <linux/timekeeper_internal.h> 24 25 #include <vdso/auxclock.h> 26 27 #include "tick-internal.h" 28 #include "timekeeping_internal.h" 29 #include "ntp_internal.h" 30 31 #define TK_CLEAR_NTP (1 << 0) 32 #define TK_CLOCK_WAS_SET (1 << 1) 33 34 #define TK_UPDATE_ALL (TK_CLEAR_NTP | TK_CLOCK_WAS_SET) 35 36 enum timekeeping_adv_mode { 37 /* Update timekeeper when a tick has passed */ 38 TK_ADV_TICK, 39 40 /* Update timekeeper on a direct frequency change */ 41 TK_ADV_FREQ 42 }; 43 44 /* 45 * The most important data for readout fits into a single 64 byte 46 * cache line. 47 */ 48 struct tk_data { 49 seqcount_raw_spinlock_t seq; 50 struct timekeeper timekeeper; 51 struct timekeeper shadow_timekeeper; 52 raw_spinlock_t lock; 53 } ____cacheline_aligned; 54 55 static struct tk_data timekeeper_data[TIMEKEEPERS_MAX]; 56 57 /* The core timekeeper */ 58 #define tk_core (timekeeper_data[TIMEKEEPER_CORE]) 59 60 #ifdef CONFIG_POSIX_AUX_CLOCKS 61 static inline bool tk_get_aux_ts64(unsigned int tkid, struct timespec64 *ts) 62 { 63 return ktime_get_aux_ts64(CLOCK_AUX + tkid - TIMEKEEPER_AUX_FIRST, ts); 64 } 65 66 static inline bool tk_is_aux(const struct timekeeper *tk) 67 { 68 return tk->id >= TIMEKEEPER_AUX_FIRST && tk->id <= TIMEKEEPER_AUX_LAST; 69 } 70 static inline struct tk_data *aux_get_tk_data(clockid_t id); 71 #else 72 static inline bool tk_get_aux_ts64(unsigned int tkid, struct timespec64 *ts) 73 { 74 return false; 75 } 76 77 static inline bool tk_is_aux(const struct timekeeper *tk) 78 { 79 return false; 80 } 81 static inline struct tk_data *aux_get_tk_data(clockid_t id) 82 { 83 return NULL; 84 } 85 #endif 86 87 static inline void tk_update_aux_offs(struct timekeeper *tk, ktime_t offs) 88 { 89 tk->offs_aux = offs; 90 tk->monotonic_to_aux = ktime_to_timespec64(offs); 91 } 92 93 /* flag for if timekeeping is suspended */ 94 int __read_mostly timekeeping_suspended; 95 96 /** 97 * struct tk_fast - NMI safe timekeeper 98 * @seq: Sequence counter for protecting updates. The lowest bit 99 * is the index for the tk_read_base array 100 * @base: tk_read_base array. Access is indexed by the lowest bit of 101 * @seq. 102 * 103 * See @update_fast_timekeeper() below. 104 */ 105 struct tk_fast { 106 seqcount_latch_t seq; 107 struct tk_read_base base[2]; 108 }; 109 110 /* Suspend-time cycles value for halted fast timekeeper. */ 111 static u64 cycles_at_suspend; 112 113 static u64 dummy_clock_read(struct clocksource *cs) 114 { 115 if (timekeeping_suspended) 116 return cycles_at_suspend; 117 return local_clock(); 118 } 119 120 static struct clocksource dummy_clock = { 121 .read = dummy_clock_read, 122 }; 123 124 /* 125 * Boot time initialization which allows local_clock() to be utilized 126 * during early boot when clocksources are not available. local_clock() 127 * returns nanoseconds already so no conversion is required, hence mult=1 128 * and shift=0. When the first proper clocksource is installed then 129 * the fast time keepers are updated with the correct values. 130 */ 131 #define FAST_TK_INIT \ 132 { \ 133 .clock = &dummy_clock, \ 134 .mask = CLOCKSOURCE_MASK(64), \ 135 .mult = 1, \ 136 .shift = 0, \ 137 } 138 139 static struct tk_fast tk_fast_mono ____cacheline_aligned = { 140 .seq = SEQCNT_LATCH_ZERO(tk_fast_mono.seq), 141 .base[0] = FAST_TK_INIT, 142 .base[1] = FAST_TK_INIT, 143 }; 144 145 static struct tk_fast tk_fast_raw ____cacheline_aligned = { 146 .seq = SEQCNT_LATCH_ZERO(tk_fast_raw.seq), 147 .base[0] = FAST_TK_INIT, 148 .base[1] = FAST_TK_INIT, 149 }; 150 151 #ifdef CONFIG_POSIX_AUX_CLOCKS 152 static __init void tk_aux_setup(void); 153 static void tk_aux_update_clocksource(void); 154 static void tk_aux_advance(void); 155 #else 156 static inline void tk_aux_setup(void) { } 157 static inline void tk_aux_update_clocksource(void) { } 158 static inline void tk_aux_advance(void) { } 159 #endif 160 161 unsigned long timekeeper_lock_irqsave(void) 162 { 163 unsigned long flags; 164 165 raw_spin_lock_irqsave(&tk_core.lock, flags); 166 return flags; 167 } 168 169 void timekeeper_unlock_irqrestore(unsigned long flags) 170 { 171 raw_spin_unlock_irqrestore(&tk_core.lock, flags); 172 } 173 174 /* 175 * Multigrain timestamps require tracking the latest fine-grained timestamp 176 * that has been issued, and never returning a coarse-grained timestamp that is 177 * earlier than that value. 178 * 179 * mg_floor represents the latest fine-grained time that has been handed out as 180 * a file timestamp on the system. This is tracked as a monotonic ktime_t, and 181 * converted to a realtime clock value on an as-needed basis. 182 * 183 * Maintaining mg_floor ensures the multigrain interfaces never issue a 184 * timestamp earlier than one that has been previously issued. 185 * 186 * The exception to this rule is when there is a backward realtime clock jump. If 187 * such an event occurs, a timestamp can appear to be earlier than a previous one. 188 */ 189 static __cacheline_aligned_in_smp atomic64_t mg_floor; 190 191 static inline void tk_normalize_xtime(struct timekeeper *tk) 192 { 193 while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) { 194 tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift; 195 tk->xtime_sec++; 196 } 197 while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) { 198 tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift; 199 tk->raw_sec++; 200 } 201 } 202 203 static inline struct timespec64 tk_xtime(const struct timekeeper *tk) 204 { 205 struct timespec64 ts; 206 207 ts.tv_sec = tk->xtime_sec; 208 ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift); 209 return ts; 210 } 211 212 static inline struct timespec64 tk_xtime_coarse(const struct timekeeper *tk) 213 { 214 struct timespec64 ts; 215 216 ts.tv_sec = tk->xtime_sec; 217 ts.tv_nsec = tk->coarse_nsec; 218 return ts; 219 } 220 221 /* 222 * Update the nanoseconds part for the coarse time keepers. They can't rely 223 * on xtime_nsec because xtime_nsec could be adjusted by a small negative 224 * amount when the multiplication factor of the clock is adjusted, which 225 * could cause the coarse clocks to go slightly backwards. See 226 * timekeeping_apply_adjustment(). Thus we keep a separate copy for the coarse 227 * clockids which only is updated when the clock has been set or we have 228 * accumulated time. 229 */ 230 static inline void tk_update_coarse_nsecs(struct timekeeper *tk) 231 { 232 tk->coarse_nsec = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift; 233 } 234 235 static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts) 236 { 237 tk->xtime_sec = ts->tv_sec; 238 tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift; 239 tk_update_coarse_nsecs(tk); 240 } 241 242 static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts) 243 { 244 tk->xtime_sec += ts->tv_sec; 245 tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift; 246 tk_normalize_xtime(tk); 247 tk_update_coarse_nsecs(tk); 248 } 249 250 static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm) 251 { 252 struct timespec64 tmp; 253 254 /* 255 * Verify consistency of: offset_real = -wall_to_monotonic 256 * before modifying anything 257 */ 258 set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec, 259 -tk->wall_to_monotonic.tv_nsec); 260 WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp)); 261 tk->wall_to_monotonic = wtm; 262 set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec); 263 /* Paired with READ_ONCE() in ktime_mono_to_any() */ 264 WRITE_ONCE(tk->offs_real, timespec64_to_ktime(tmp)); 265 WRITE_ONCE(tk->offs_tai, ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0))); 266 } 267 268 static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta) 269 { 270 /* Paired with READ_ONCE() in ktime_mono_to_any() */ 271 WRITE_ONCE(tk->offs_boot, ktime_add(tk->offs_boot, delta)); 272 /* 273 * Timespec representation for VDSO update to avoid 64bit division 274 * on every update. 275 */ 276 tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot); 277 } 278 279 #ifdef CONFIG_ARCH_WANTS_CLOCKSOURCE_READ_INLINE 280 #include <asm/clock_inlined.h> 281 282 static DEFINE_STATIC_KEY_FALSE(clocksource_read_inlined); 283 284 /* 285 * tk_clock_read - atomic clocksource read() helper 286 * 287 * This helper is necessary to use in the read paths because, while the 288 * seqcount ensures we don't return a bad value while structures are updated, 289 * it doesn't protect from potential crashes. There is the possibility that 290 * the tkr's clocksource may change between the read reference, and the 291 * clock reference passed to the read function. This can cause crashes if 292 * the wrong clocksource is passed to the wrong read function. 293 * This isn't necessary to use when holding the tk_core.lock or doing 294 * a read of the fast-timekeeper tkrs (which is protected by its own locking 295 * and update logic). 296 */ 297 static __always_inline u64 tk_clock_read(const struct tk_read_base *tkr) 298 { 299 struct clocksource *clock = READ_ONCE(tkr->clock); 300 301 if (static_branch_likely(&clocksource_read_inlined)) 302 return arch_inlined_clocksource_read(clock); 303 304 return clock->read(clock); 305 } 306 307 static inline void clocksource_disable_inline_read(void) 308 { 309 static_branch_disable(&clocksource_read_inlined); 310 } 311 312 static inline void clocksource_enable_inline_read(void) 313 { 314 static_branch_enable(&clocksource_read_inlined); 315 } 316 #else 317 static __always_inline u64 tk_clock_read(const struct tk_read_base *tkr) 318 { 319 struct clocksource *clock = READ_ONCE(tkr->clock); 320 321 return clock->read(clock); 322 } 323 324 static inline void clocksource_disable_inline_read(void) { } 325 static inline void clocksource_enable_inline_read(void) { } 326 #endif 327 328 /** 329 * tk_setup_internals - Set up internals to use clocksource clock. 330 * 331 * @tk: The target timekeeper to setup. 332 * @clock: Pointer to clocksource. 333 * 334 * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment 335 * pair and interval request. 336 * 337 * Unless you're the timekeeping code, you should not be using this! 338 */ 339 static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock) 340 { 341 u64 interval; 342 struct clocksource *old_clock; 343 344 ++tk->cs_was_changed_seq; 345 old_clock = tk->tkr_mono.clock; 346 tk->tkr_mono.clock = clock; 347 tk->tkr_mono.mask = clock->mask; 348 tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono); 349 350 tk->tkr_raw.clock = clock; 351 tk->tkr_raw.mask = clock->mask; 352 tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last; 353 354 /* Do the ns -> cycle conversion first, using original mult */ 355 interval = (u64)NTP_INTERVAL_LENGTH << clock->shift; 356 interval += clock->mult / 2; 357 do_div(interval, clock->mult); 358 if (interval == 0) 359 interval = 1; 360 361 tk->cycle_interval = interval; 362 363 /* Go back from cycles -> shifted ns */ 364 tk->xtime_interval = interval * clock->mult; 365 tk->raw_interval = interval * clock->mult; 366 367 /* if changing clocks, convert xtime_nsec shift units */ 368 if (old_clock) { 369 int shift_change = clock->shift - old_clock->shift; 370 if (shift_change < 0) { 371 tk->tkr_mono.xtime_nsec >>= -shift_change; 372 tk->tkr_raw.xtime_nsec >>= -shift_change; 373 } else { 374 tk->tkr_mono.xtime_nsec <<= shift_change; 375 tk->tkr_raw.xtime_nsec <<= shift_change; 376 } 377 } 378 379 tk->tkr_mono.shift = clock->shift; 380 tk->tkr_raw.shift = clock->shift; 381 382 tk->ntp_error = 0; 383 tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift; 384 385 /* 386 * ntp_tick is the tick length that NTP disciplines (its ±500 PPM 387 * scales only this part), in NTP-shifted ns: the real interval of 388 * a whole number of counter cycles. Because cycle_interval is 389 * rounded to an integer number of cycles, this ntp_tick differs 390 * from the true intended 1/HZ tick length by up to half a cycle 391 * period. 392 */ 393 tk->ntp_tick = (u64)tk->xtime_interval << tk->ntp_error_shift; 394 395 /* 396 * cs_tick_adj is the constant difference between the disciplined 397 * ntp_tick above and the true 1/HZ tick, expressed per-second to 398 * match the ntp_update_frequency() addends and handed to NTP via 399 * ntp_clear() to be explicitly included in its tick_length. 400 * 401 * Worked example: HZ=1000, ACPI PM timer at 3.579545 MHz, which 402 * has 3579.545 cycles in 1ms, rounded to cycle_interval = 3580. 403 * 404 * So ntp_tick is actually 1.000127ms, as that is the amount of 405 * time that 3580 cycles will take at the nominal frequency. This 406 * is the part that NTP disciplines, causing each 3580 counts to 407 * advance the clock by up to NTP's ±500PPM of that amount. 408 * 409 * The "extra" 127ns/tick is what's stored in cs_tick_adj and 410 * applied as a constant correction by ntp_update_frequency() so 411 * that NTP *believes* it's disciplining a 1ms tick. 412 */ 413 tk->cs_tick_adj = (s64)tk->ntp_tick - 414 ((s64)NTP_INTERVAL_LENGTH << NTP_SCALE_SHIFT); 415 tk->cs_tick_adj *= NTP_INTERVAL_FREQ; 416 417 /* 418 * The timekeeper keeps its own mult values for the currently 419 * active clocksource. These value will be adjusted via NTP 420 * to counteract clock drifting. 421 */ 422 tk->tkr_mono.mult = clock->mult; 423 tk->tkr_raw.mult = clock->mult; 424 tk->ntp_err_mult = 0; 425 tk->skip_second_overflow = 0; 426 tk->skew_delta = 0; 427 428 tk->cs_id = clock->id; 429 430 /* Coupled clockevent data */ 431 if (IS_ENABLED(CONFIG_GENERIC_CLOCKEVENTS_COUPLED) && 432 clock->flags & CLOCK_SOURCE_HAS_COUPLED_CLOCK_EVENT) { 433 /* 434 * Aim for an one hour maximum delta and use KHz to handle 435 * clocksources with a frequency above 4GHz correctly as 436 * the frequency argument of clocks_calc_mult_shift() is u32. 437 */ 438 clocks_calc_mult_shift(&tk->cs_ns_to_cyc_mult, &tk->cs_ns_to_cyc_shift, 439 NSEC_PER_MSEC, clock->freq_khz, 3600 * 1000); 440 /* 441 * Initialize the conversion limit as the previous clocksource 442 * might have the same shift/mult pair so the quick check in 443 * tk_update_ns_to_cyc() fails to update it after a clocksource 444 * change leaving it effectivly zero. 445 */ 446 tk->cs_ns_to_cyc_maxns = div_u64(clock->mask, tk->cs_ns_to_cyc_mult); 447 } 448 } 449 450 /* Timekeeper helper functions. */ 451 static noinline u64 delta_to_ns_safe(const struct tk_read_base *tkr, u64 delta) 452 { 453 return mul_u64_u32_add_u64_shr(delta, tkr->mult, tkr->xtime_nsec, tkr->shift); 454 } 455 456 static __always_inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles) 457 { 458 /* Calculate the delta since the last update_wall_time() */ 459 u64 mask = tkr->mask, delta = (cycles - tkr->cycle_last) & mask; 460 461 /* 462 * This detects both negative motion and the case where the delta 463 * overflows the multiplication with tkr->mult. 464 */ 465 if (unlikely(delta > tkr->clock->max_cycles)) { 466 /* 467 * Handle clocksource inconsistency between CPUs to prevent 468 * time from going backwards by checking for the MSB of the 469 * mask being set in the delta. 470 */ 471 if (delta & ~(mask >> 1)) 472 return tkr->xtime_nsec >> tkr->shift; 473 474 return delta_to_ns_safe(tkr, delta); 475 } 476 477 return ((delta * tkr->mult) + tkr->xtime_nsec) >> tkr->shift; 478 } 479 480 static __always_inline u64 timekeeping_get_ns(const struct tk_read_base *tkr) 481 { 482 return timekeeping_cycles_to_ns(tkr, tk_clock_read(tkr)); 483 } 484 485 /** 486 * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper. 487 * @tkr: Timekeeping readout base from which we take the update 488 * @tkf: Pointer to NMI safe timekeeper 489 * 490 * We want to use this from any context including NMI and tracing / 491 * instrumenting the timekeeping code itself. 492 * 493 * Employ the latch technique; see @write_seqcount_latch. 494 * 495 * So if a NMI hits the update of base[0] then it will use base[1] 496 * which is still consistent. In the worst case this can result is a 497 * slightly wrong timestamp (a few nanoseconds). See 498 * @ktime_get_mono_fast_ns. 499 */ 500 static void update_fast_timekeeper(const struct tk_read_base *tkr, 501 struct tk_fast *tkf) 502 { 503 struct tk_read_base *base = tkf->base; 504 505 /* Force readers off to base[1] */ 506 write_seqcount_latch_begin(&tkf->seq); 507 508 /* Update base[0] */ 509 memcpy(base, tkr, sizeof(*base)); 510 511 /* Force readers back to base[0] */ 512 write_seqcount_latch(&tkf->seq); 513 514 /* Update base[1] */ 515 memcpy(base + 1, base, sizeof(*base)); 516 517 write_seqcount_latch_end(&tkf->seq); 518 } 519 520 static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf) 521 { 522 struct tk_read_base *tkr; 523 unsigned int seq; 524 u64 now; 525 526 do { 527 seq = read_seqcount_latch(&tkf->seq); 528 tkr = tkf->base + (seq & 0x01); 529 now = ktime_to_ns(tkr->base); 530 now += timekeeping_get_ns(tkr); 531 } while (read_seqcount_latch_retry(&tkf->seq, seq)); 532 533 return now; 534 } 535 536 /** 537 * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic 538 * 539 * This timestamp is not guaranteed to be monotonic across an update. 540 * The timestamp is calculated by: 541 * 542 * now = base_mono + clock_delta * slope 543 * 544 * So if the update lowers the slope, readers who are forced to the 545 * not yet updated second array are still using the old steeper slope. 546 * 547 * tmono 548 * ^ 549 * | o n 550 * | o n 551 * | u 552 * | o 553 * |o 554 * |12345678---> reader order 555 * 556 * o = old slope 557 * u = update 558 * n = new slope 559 * 560 * So reader 6 will observe time going backwards versus reader 5. 561 * 562 * While other CPUs are likely to be able to observe that, the only way 563 * for a CPU local observation is when an NMI hits in the middle of 564 * the update. Timestamps taken from that NMI context might be ahead 565 * of the following timestamps. Callers need to be aware of that and 566 * deal with it. 567 */ 568 u64 notrace ktime_get_mono_fast_ns(void) 569 { 570 return __ktime_get_fast_ns(&tk_fast_mono); 571 } 572 EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns); 573 574 /** 575 * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw 576 * 577 * Contrary to ktime_get_mono_fast_ns() this is always correct because the 578 * conversion factor is not affected by NTP/PTP correction. 579 */ 580 u64 notrace ktime_get_raw_fast_ns(void) 581 { 582 return __ktime_get_fast_ns(&tk_fast_raw); 583 } 584 EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns); 585 586 /** 587 * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock. 588 * 589 * To keep it NMI safe since we're accessing from tracing, we're not using a 590 * separate timekeeper with updates to monotonic clock and boot offset 591 * protected with seqcounts. This has the following minor side effects: 592 * 593 * (1) Its possible that a timestamp be taken after the boot offset is updated 594 * but before the timekeeper is updated. If this happens, the new boot offset 595 * is added to the old timekeeping making the clock appear to update slightly 596 * earlier: 597 * CPU 0 CPU 1 598 * timekeeping_inject_sleeptime64() 599 * __timekeeping_inject_sleeptime(tk, delta); 600 * timestamp(); 601 * timekeeping_update_staged(tkd, TK_CLEAR_NTP...); 602 * 603 * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be 604 * partially updated. Since the tk->offs_boot update is a rare event, this 605 * should be a rare occurrence which postprocessing should be able to handle. 606 * 607 * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns() 608 * apply as well. 609 */ 610 u64 notrace ktime_get_boot_fast_ns(void) 611 { 612 struct timekeeper *tk = &tk_core.timekeeper; 613 614 return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot))); 615 } 616 EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns); 617 618 /** 619 * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock. 620 * 621 * The same limitations as described for ktime_get_boot_fast_ns() apply. The 622 * mono time and the TAI offset are not read atomically which may yield wrong 623 * readouts. However, an update of the TAI offset is an rare event e.g., caused 624 * by settime or adjtimex with an offset. The user of this function has to deal 625 * with the possibility of wrong timestamps in post processing. 626 */ 627 u64 notrace ktime_get_tai_fast_ns(void) 628 { 629 struct timekeeper *tk = &tk_core.timekeeper; 630 631 return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai))); 632 } 633 EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns); 634 635 /** 636 * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime. 637 * 638 * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering. 639 */ 640 u64 ktime_get_real_fast_ns(void) 641 { 642 struct tk_fast *tkf = &tk_fast_mono; 643 struct tk_read_base *tkr; 644 u64 baser, delta; 645 unsigned int seq; 646 647 do { 648 seq = raw_read_seqcount_latch(&tkf->seq); 649 tkr = tkf->base + (seq & 0x01); 650 baser = ktime_to_ns(tkr->base_real); 651 delta = timekeeping_get_ns(tkr); 652 } while (raw_read_seqcount_latch_retry(&tkf->seq, seq)); 653 654 return baser + delta; 655 } 656 EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns); 657 658 /** 659 * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource. 660 * @tk: Timekeeper to snapshot. 661 * 662 * It generally is unsafe to access the clocksource after timekeeping has been 663 * suspended, so take a snapshot of the readout base of @tk and use it as the 664 * fast timekeeper's readout base while suspended. It will return the same 665 * number of cycles every time until timekeeping is resumed at which time the 666 * proper readout base for the fast timekeeper will be restored automatically. 667 */ 668 static void halt_fast_timekeeper(const struct timekeeper *tk) 669 { 670 static struct tk_read_base tkr_dummy; 671 const struct tk_read_base *tkr = &tk->tkr_mono; 672 673 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy)); 674 cycles_at_suspend = tk_clock_read(tkr); 675 tkr_dummy.clock = &dummy_clock; 676 tkr_dummy.base_real = tkr->base + tk->offs_real; 677 update_fast_timekeeper(&tkr_dummy, &tk_fast_mono); 678 679 tkr = &tk->tkr_raw; 680 memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy)); 681 tkr_dummy.clock = &dummy_clock; 682 update_fast_timekeeper(&tkr_dummy, &tk_fast_raw); 683 } 684 685 static RAW_NOTIFIER_HEAD(pvclock_gtod_chain); 686 687 static void update_pvclock_gtod(struct timekeeper *tk, bool was_set) 688 { 689 raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk); 690 } 691 692 /** 693 * pvclock_gtod_register_notifier - register a pvclock timedata update listener 694 * @nb: Pointer to the notifier block to register 695 */ 696 int pvclock_gtod_register_notifier(struct notifier_block *nb) 697 { 698 struct timekeeper *tk = &tk_core.timekeeper; 699 int ret; 700 701 guard(raw_spinlock_irqsave)(&tk_core.lock); 702 ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb); 703 update_pvclock_gtod(tk, true); 704 705 return ret; 706 } 707 EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier); 708 709 /** 710 * pvclock_gtod_unregister_notifier - unregister a pvclock 711 * timedata update listener 712 * @nb: Pointer to the notifier block to unregister 713 */ 714 int pvclock_gtod_unregister_notifier(struct notifier_block *nb) 715 { 716 guard(raw_spinlock_irqsave)(&tk_core.lock); 717 return raw_notifier_chain_unregister(&pvclock_gtod_chain, nb); 718 } 719 EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier); 720 721 /* 722 * tk_update_leap_state - helper to update the next_leap_ktime 723 */ 724 static inline void tk_update_leap_state(struct timekeeper *tk) 725 { 726 tk->next_leap_ktime = ntp_get_next_leap(tk->id); 727 if (tk->next_leap_ktime != KTIME_MAX) 728 /* Convert to monotonic time */ 729 tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real); 730 } 731 732 /* 733 * Leap state update for both shadow and the real timekeeper 734 * Separate to spare a full memcpy() of the timekeeper. 735 */ 736 static void tk_update_leap_state_all(struct tk_data *tkd) 737 { 738 write_seqcount_begin(&tkd->seq); 739 tk_update_leap_state(&tkd->shadow_timekeeper); 740 tkd->timekeeper.next_leap_ktime = tkd->shadow_timekeeper.next_leap_ktime; 741 write_seqcount_end(&tkd->seq); 742 } 743 744 /* 745 * Update the ktime_t based scalar nsec members of the timekeeper 746 */ 747 static inline void tk_update_ktime_data(struct timekeeper *tk) 748 { 749 u64 seconds; 750 u32 nsec; 751 752 /* 753 * The xtime based monotonic readout is: 754 * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now(); 755 * The ktime based monotonic readout is: 756 * nsec = base_mono + now(); 757 * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec 758 */ 759 seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec); 760 nsec = (u32) tk->wall_to_monotonic.tv_nsec; 761 tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec); 762 763 /* 764 * The sum of the nanoseconds portions of xtime and 765 * wall_to_monotonic can be greater/equal one second. Take 766 * this into account before updating tk->ktime_sec. 767 */ 768 nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift); 769 if (nsec >= NSEC_PER_SEC) 770 seconds++; 771 tk->ktime_sec = seconds; 772 773 /* Update the monotonic raw base */ 774 tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC); 775 } 776 777 static inline void tk_update_ns_to_cyc(struct timekeeper *tks, struct timekeeper *tkc) 778 { 779 struct tk_read_base *tkrs = &tks->tkr_mono; 780 struct tk_read_base *tkrc = &tkc->tkr_mono; 781 unsigned int shift; 782 783 if (!IS_ENABLED(CONFIG_GENERIC_CLOCKEVENTS_COUPLED) || 784 !(tkrs->clock->flags & CLOCK_SOURCE_HAS_COUPLED_CLOCK_EVENT)) 785 return; 786 787 if (tkrs->mult == tkrc->mult && tkrs->shift == tkrc->shift) 788 return; 789 /* 790 * The conversion math is simple: 791 * 792 * CS::MULT (1 << NS_TO_CYC_SHIFT) 793 * --------------- = ---------------------- 794 * (1 << CS:SHIFT) NS_TO_CYC_MULT 795 * 796 * Ergo: 797 * 798 * NS_TO_CYC_MULT = (1 << (CS::SHIFT + NS_TO_CYC_SHIFT)) / CS::MULT 799 * 800 * NS_TO_CYC_SHIFT has been set up in tk_setup_internals() 801 */ 802 shift = tkrs->shift + tks->cs_ns_to_cyc_shift; 803 tks->cs_ns_to_cyc_mult = (u32)div_u64(1ULL << shift, tkrs->mult); 804 tks->cs_ns_to_cyc_maxns = div_u64(tkrs->clock->mask, tks->cs_ns_to_cyc_mult); 805 } 806 807 /* 808 * Restore the shadow timekeeper from the real timekeeper. 809 */ 810 static void timekeeping_restore_shadow(struct tk_data *tkd) 811 { 812 lockdep_assert_held(&tkd->lock); 813 memcpy(&tkd->shadow_timekeeper, &tkd->timekeeper, sizeof(tkd->timekeeper)); 814 } 815 816 static void timekeeping_update_from_shadow(struct tk_data *tkd, unsigned int action) 817 { 818 struct timekeeper *tk = &tkd->shadow_timekeeper; 819 820 lockdep_assert_held(&tkd->lock); 821 822 /* 823 * Block out readers before running the updates below because that 824 * updates VDSO and other time related infrastructure. Not blocking 825 * the readers might let a reader see time going backwards when 826 * reading from the VDSO after the VDSO update and then reading in 827 * the kernel from the timekeeper before that got updated. 828 */ 829 write_seqcount_begin(&tkd->seq); 830 831 if (action & TK_CLEAR_NTP) { 832 tk->ntp_error = 0; 833 ntp_clear(tk->id, tk->cs_tick_adj); 834 } 835 836 tk_update_leap_state(tk); 837 tk_update_ktime_data(tk); 838 tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real; 839 840 if (tk->id == TIMEKEEPER_CORE) { 841 tk_update_ns_to_cyc(tk, &tkd->timekeeper); 842 update_vsyscall(tk); 843 update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET); 844 845 update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono); 846 update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw); 847 } else if (tk_is_aux(tk)) { 848 vdso_time_update_aux(tk); 849 } 850 851 if (action & TK_CLOCK_WAS_SET) 852 tk->clock_was_set_seq++; 853 854 /* 855 * Update the real timekeeper. 856 * 857 * We could avoid this memcpy() by switching pointers, but that has 858 * the downside that the reader side does not longer benefit from 859 * the cacheline optimized data layout of the timekeeper and requires 860 * another indirection. 861 * 862 * Write xtime_sec first so that even if the memcpy() tears the store 863 * data integrity is provided for ktime_get_real_seconds(). 864 */ 865 WRITE_ONCE(tkd->timekeeper.xtime_sec, tk->xtime_sec); 866 memcpy(&tkd->timekeeper, tk, sizeof(*tk)); 867 write_seqcount_end(&tkd->seq); 868 } 869 870 /** 871 * timekeeping_forward_now - update clock to the current time 872 * @tk: Pointer to the timekeeper to update 873 * 874 * Forward the current clock to update its state since the last call to 875 * update_wall_time(). This is useful before significant clock changes, 876 * as it avoids having to deal with this time offset explicitly. 877 */ 878 static void timekeeping_forward_now(struct timekeeper *tk) 879 { 880 u64 cycle_now, delta; 881 882 cycle_now = tk_clock_read(&tk->tkr_mono); 883 delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask, 884 tk->tkr_mono.clock->max_raw_delta); 885 tk->tkr_mono.cycle_last = cycle_now; 886 tk->tkr_raw.cycle_last = cycle_now; 887 888 while (delta > 0) { 889 u64 max = tk->tkr_mono.clock->max_cycles; 890 u64 incr = delta < max ? delta : max; 891 892 tk->tkr_mono.xtime_nsec += incr * tk->tkr_mono.mult; 893 tk->tkr_raw.xtime_nsec += incr * tk->tkr_raw.mult; 894 tk_normalize_xtime(tk); 895 delta -= incr; 896 } 897 tk_update_coarse_nsecs(tk); 898 } 899 900 /* 901 * ktime_expiry_to_cycles - Convert a expiry time to clocksource cycles 902 * @id: Clocksource ID which is required for validity 903 * @expires_ns: Absolute CLOCK_MONOTONIC expiry time (nsecs) to be converted 904 * @cycles: Pointer to storage for corresponding absolute cycles value 905 * 906 * Convert a CLOCK_MONOTONIC based absolute expiry time to a cycles value 907 * based on the correlated clocksource of the clockevent device by using 908 * the base nanoseconds and cycles values of the last timekeeper update and 909 * converting the delta between @expires_ns and base nanoseconds to cycles. 910 * 911 * This only works for clockevent devices which are using a less than or 912 * equal comparator against the clocksource. 913 * 914 * Utilizing this avoids two clocksource reads for such devices, the 915 * ktime_get() in clockevents_program_event() to calculate the delta expiry 916 * value and the readout in the device::set_next_event() callback to 917 * convert the delta back to a absolute comparator value. 918 * 919 * Returns: True if @id matches the current clocksource ID, false otherwise 920 */ 921 bool ktime_expiry_to_cycles(enum clocksource_ids id, ktime_t expires_ns, u64 *cycles) 922 { 923 struct timekeeper *tk = &tk_core.timekeeper; 924 struct tk_read_base *tkrm = &tk->tkr_mono; 925 ktime_t base_ns, delta_ns, max_ns; 926 u64 base_cycles, delta_cycles; 927 unsigned int seq; 928 u32 mult, shift; 929 930 /* 931 * Racy check to avoid the seqcount overhead when ID does not match. If 932 * the relevant clocksource is installed concurrently, then this will 933 * just delay the switch over to this mechanism until the next event is 934 * programmed. If the ID is not matching the clock events code will use 935 * the regular relative set_next_event() callback as before. 936 */ 937 if (data_race(tk->cs_id) != id) 938 return false; 939 940 do { 941 seq = read_seqcount_begin(&tk_core.seq); 942 943 if (tk->cs_id != id) 944 return false; 945 946 base_cycles = tkrm->cycle_last; 947 base_ns = tkrm->base + (tkrm->xtime_nsec >> tkrm->shift); 948 949 mult = tk->cs_ns_to_cyc_mult; 950 shift = tk->cs_ns_to_cyc_shift; 951 max_ns = tk->cs_ns_to_cyc_maxns; 952 953 } while (read_seqcount_retry(&tk_core.seq, seq)); 954 955 /* Prevent negative deltas and multiplication overflows */ 956 delta_ns = min(expires_ns - base_ns, max_ns); 957 delta_ns = max(delta_ns, 0); 958 959 /* Convert to cycles */ 960 delta_cycles = ((u64)delta_ns * mult) >> shift; 961 *cycles = base_cycles + delta_cycles; 962 return true; 963 } 964 965 /** 966 * ktime_get_real_ts64 - Returns the time of day in a timespec64. 967 * @ts: pointer to the timespec to be set 968 * 969 * Returns the time of day in a timespec64 (WARN if suspended). 970 */ 971 void ktime_get_real_ts64(struct timespec64 *ts) 972 { 973 struct timekeeper *tk = &tk_core.timekeeper; 974 unsigned int seq; 975 u64 nsecs; 976 977 WARN_ON(timekeeping_suspended); 978 979 do { 980 seq = read_seqcount_begin(&tk_core.seq); 981 982 ts->tv_sec = tk->xtime_sec; 983 nsecs = timekeeping_get_ns(&tk->tkr_mono); 984 985 } while (read_seqcount_retry(&tk_core.seq, seq)); 986 987 ts->tv_nsec = 0; 988 timespec64_add_ns(ts, nsecs); 989 } 990 EXPORT_SYMBOL(ktime_get_real_ts64); 991 992 ktime_t ktime_get(void) 993 { 994 struct timekeeper *tk = &tk_core.timekeeper; 995 unsigned int seq; 996 ktime_t base; 997 u64 nsecs; 998 999 WARN_ON(timekeeping_suspended); 1000 1001 do { 1002 seq = read_seqcount_begin(&tk_core.seq); 1003 base = tk->tkr_mono.base; 1004 nsecs = timekeeping_get_ns(&tk->tkr_mono); 1005 1006 } while (read_seqcount_retry(&tk_core.seq, seq)); 1007 1008 return ktime_add_ns(base, nsecs); 1009 } 1010 EXPORT_SYMBOL_GPL(ktime_get); 1011 1012 u32 ktime_get_resolution_ns(void) 1013 { 1014 struct timekeeper *tk = &tk_core.timekeeper; 1015 unsigned int seq; 1016 u32 nsecs; 1017 1018 WARN_ON(timekeeping_suspended); 1019 1020 do { 1021 seq = read_seqcount_begin(&tk_core.seq); 1022 nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift; 1023 } while (read_seqcount_retry(&tk_core.seq, seq)); 1024 1025 return nsecs; 1026 } 1027 EXPORT_SYMBOL_GPL(ktime_get_resolution_ns); 1028 1029 static const ktime_t *const offsets[TK_OFFS_MAX] = { 1030 [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real, 1031 [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot, 1032 [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai, 1033 }; 1034 1035 ktime_t ktime_get_with_offset(enum tk_offsets offs) 1036 { 1037 struct timekeeper *tk = &tk_core.timekeeper; 1038 const ktime_t *offset = offsets[offs]; 1039 unsigned int seq; 1040 ktime_t base; 1041 u64 nsecs; 1042 1043 WARN_ON(timekeeping_suspended); 1044 1045 do { 1046 seq = read_seqcount_begin(&tk_core.seq); 1047 base = ktime_add(tk->tkr_mono.base, *offset); 1048 nsecs = timekeeping_get_ns(&tk->tkr_mono); 1049 1050 } while (read_seqcount_retry(&tk_core.seq, seq)); 1051 1052 return ktime_add_ns(base, nsecs); 1053 1054 } 1055 EXPORT_SYMBOL_GPL(ktime_get_with_offset); 1056 1057 ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs) 1058 { 1059 struct timekeeper *tk = &tk_core.timekeeper; 1060 const ktime_t *offset = offsets[offs]; 1061 unsigned int seq; 1062 ktime_t base; 1063 u64 nsecs; 1064 1065 WARN_ON(timekeeping_suspended); 1066 1067 do { 1068 seq = read_seqcount_begin(&tk_core.seq); 1069 base = ktime_add(tk->tkr_mono.base, *offset); 1070 nsecs = tk->coarse_nsec; 1071 1072 } while (read_seqcount_retry(&tk_core.seq, seq)); 1073 1074 return ktime_add_ns(base, nsecs); 1075 } 1076 EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset); 1077 1078 /** 1079 * ktime_mono_to_any() - convert monotonic time to any other time 1080 * @tmono: time to convert. 1081 * @offs: which offset to use 1082 */ 1083 ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs) 1084 { 1085 const ktime_t *offset = offsets[offs]; 1086 unsigned int seq; 1087 ktime_t tconv; 1088 1089 if (IS_ENABLED(CONFIG_64BIT)) { 1090 /* 1091 * Paired with WRITE_ONCE()s in tk_set_wall_to_mono() and 1092 * tk_update_sleep_time(). 1093 */ 1094 return ktime_add(tmono, READ_ONCE(*offset)); 1095 } 1096 1097 do { 1098 seq = read_seqcount_begin(&tk_core.seq); 1099 tconv = ktime_add(tmono, *offset); 1100 } while (read_seqcount_retry(&tk_core.seq, seq)); 1101 1102 return tconv; 1103 } 1104 EXPORT_SYMBOL_GPL(ktime_mono_to_any); 1105 1106 /** 1107 * ktime_get_raw - Returns the raw monotonic time in ktime_t format 1108 */ 1109 ktime_t ktime_get_raw(void) 1110 { 1111 struct timekeeper *tk = &tk_core.timekeeper; 1112 unsigned int seq; 1113 ktime_t base; 1114 u64 nsecs; 1115 1116 do { 1117 seq = read_seqcount_begin(&tk_core.seq); 1118 base = tk->tkr_raw.base; 1119 nsecs = timekeeping_get_ns(&tk->tkr_raw); 1120 1121 } while (read_seqcount_retry(&tk_core.seq, seq)); 1122 1123 return ktime_add_ns(base, nsecs); 1124 } 1125 EXPORT_SYMBOL_GPL(ktime_get_raw); 1126 1127 /** 1128 * ktime_get_ts64 - get the monotonic clock in timespec64 format 1129 * @ts: pointer to timespec variable 1130 * 1131 * The function calculates the monotonic clock from the realtime 1132 * clock and the wall_to_monotonic offset and stores the result 1133 * in normalized timespec64 format in the variable pointed to by @ts. 1134 */ 1135 void ktime_get_ts64(struct timespec64 *ts) 1136 { 1137 struct timekeeper *tk = &tk_core.timekeeper; 1138 struct timespec64 tomono; 1139 unsigned int seq; 1140 u64 nsec; 1141 1142 WARN_ON(timekeeping_suspended); 1143 1144 do { 1145 seq = read_seqcount_begin(&tk_core.seq); 1146 ts->tv_sec = tk->xtime_sec; 1147 nsec = timekeeping_get_ns(&tk->tkr_mono); 1148 tomono = tk->wall_to_monotonic; 1149 1150 } while (read_seqcount_retry(&tk_core.seq, seq)); 1151 1152 ts->tv_sec += tomono.tv_sec; 1153 ts->tv_nsec = 0; 1154 timespec64_add_ns(ts, nsec + tomono.tv_nsec); 1155 } 1156 EXPORT_SYMBOL_GPL(ktime_get_ts64); 1157 1158 /** 1159 * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC 1160 * 1161 * Returns the seconds portion of CLOCK_MONOTONIC with a single non 1162 * serialized read. tk->ktime_sec is of type 'unsigned long' so this 1163 * works on both 32 and 64 bit systems. On 32 bit systems the readout 1164 * covers ~136 years of uptime which should be enough to prevent 1165 * premature wrap arounds. 1166 */ 1167 time64_t ktime_get_seconds(void) 1168 { 1169 struct timekeeper *tk = &tk_core.timekeeper; 1170 1171 WARN_ON(timekeeping_suspended); 1172 return tk->ktime_sec; 1173 } 1174 EXPORT_SYMBOL_GPL(ktime_get_seconds); 1175 1176 /** 1177 * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME 1178 * 1179 * Returns the wall clock seconds since 1970. 1180 * 1181 * For 64bit systems the fast access to tk->xtime_sec is preserved. On 1182 * 32bit systems the access must be protected with the sequence 1183 * counter to provide "atomic" access to the 64bit tk->xtime_sec 1184 * value. 1185 */ 1186 time64_t ktime_get_real_seconds(void) 1187 { 1188 struct timekeeper *tk = &tk_core.timekeeper; 1189 time64_t seconds; 1190 unsigned int seq; 1191 1192 if (IS_ENABLED(CONFIG_64BIT)) 1193 return READ_ONCE(tk->xtime_sec); 1194 1195 do { 1196 seq = read_seqcount_begin(&tk_core.seq); 1197 seconds = READ_ONCE(tk->xtime_sec); 1198 1199 } while (read_seqcount_retry(&tk_core.seq, seq)); 1200 1201 return seconds; 1202 } 1203 EXPORT_SYMBOL_GPL(ktime_get_real_seconds); 1204 1205 /** 1206 * __ktime_get_real_seconds - Unprotected access to CLOCK_REALTIME seconds 1207 * 1208 * The same as ktime_get_real_seconds() but without the sequence counter 1209 * protection. This function is used in restricted contexts like the x86 MCE 1210 * handler and in KGDB. It's unprotected on 32-bit vs. concurrent half 1211 * completed modification and only to be used for such critical contexts. 1212 * 1213 * Returns: Racy snapshot of the CLOCK_REALTIME seconds value 1214 */ 1215 noinstr time64_t __ktime_get_real_seconds(void) 1216 { 1217 struct timekeeper *tk = &tk_core.timekeeper; 1218 1219 return READ_ONCE(tk->xtime_sec); 1220 } 1221 1222 static inline u64 tk_clock_read_snapshot(const struct tk_read_base *tkr, 1223 struct clocksource_hw_snapshot *chs) 1224 { 1225 struct clocksource *clock = READ_ONCE(tkr->clock); 1226 1227 if (unlikely(clock->read_snapshot)) 1228 return clock->read_snapshot(clock, chs); 1229 1230 return clock->read(clock); 1231 } 1232 1233 1234 /** 1235 * ktime_get_snapshot_id - Simultaneously snapshot a given clock ID with 1236 * the corresponding monotonic raw and the underlying 1237 * clocksource counter value. 1238 * @clock_id: The clock ID to snapshot 1239 * @systime_snapshot: Pointer to struct receiving the system time snapshot 1240 * 1241 * For the system time keeping clocks (REALTIME, MONOTONIC and BOOTTIME) the 1242 * monotonic raw clock is CLOCK_MONOTONIC_RAW. For AUX clocks this is the 1243 * monotonic raw clock related to the AUX clock. These AUX clock related 1244 * monotonic raw clocks have a strict linear offset to the system time 1245 * CLOCK_MONOTONIC_RAW: 1246 * 1247 * MONOTONIC_RAW(AUX$N) = CLOCK_MONOTONIC_RAW(system) + offset(AUX$N) 1248 * 1249 * The offset is established when a AUX clock is initialized, but it is 1250 * currently not accessible. 1251 */ 1252 void ktime_get_snapshot_id(clockid_t clock_id, struct system_time_snapshot *systime_snapshot) 1253 { 1254 ktime_t base_raw, base_sys, offs_sys, *offs, offs_zero = 0; 1255 u64 nsec_raw, nsec_sys, now; 1256 struct timekeeper *tk; 1257 struct tk_data *tkd; 1258 unsigned int seq; 1259 1260 /* Invalidate the snapshot for all failure cases */ 1261 systime_snapshot->valid = false; 1262 1263 if (WARN_ON_ONCE(timekeeping_suspended)) 1264 return; 1265 1266 switch (clock_id) { 1267 case CLOCK_REALTIME: 1268 tkd = &tk_core; 1269 offs = &tk_core.timekeeper.offs_real; 1270 break; 1271 /* Map RAW to MONOTONIC so the loop below is trivial */ 1272 case CLOCK_MONOTONIC_RAW: 1273 case CLOCK_MONOTONIC: 1274 tkd = &tk_core; 1275 offs = &offs_zero; 1276 break; 1277 case CLOCK_BOOTTIME: 1278 tkd = &tk_core; 1279 offs = &tk_core.timekeeper.offs_boot; 1280 break; 1281 case CLOCK_AUX ... CLOCK_AUX_LAST: 1282 tkd = aux_get_tk_data(clock_id); 1283 if (!tkd) 1284 return; 1285 offs = &tkd->timekeeper.offs_aux; 1286 break; 1287 default: 1288 WARN_ON_ONCE(1); 1289 return; 1290 } 1291 1292 tk = &tkd->timekeeper; 1293 1294 do { 1295 struct clocksource_hw_snapshot chs = { }; 1296 1297 seq = read_seqcount_begin(&tkd->seq); 1298 1299 /* Aux clocks can be invalid */ 1300 if (!tk->clock_valid) 1301 return; 1302 1303 now = tk_clock_read_snapshot(&tk->tkr_mono, &chs); 1304 systime_snapshot->cs_id = tk->tkr_mono.clock->id; 1305 1306 systime_snapshot->hw_cycles = chs.hw_cycles; 1307 systime_snapshot->hw_csid = chs.hw_csid; 1308 1309 systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq; 1310 systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq; 1311 1312 base_sys = tk->tkr_mono.base; 1313 offs_sys = *offs; 1314 base_raw = tk->tkr_raw.base; 1315 1316 nsec_sys = timekeeping_cycles_to_ns(&tk->tkr_mono, now); 1317 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now); 1318 } while (read_seqcount_retry(&tkd->seq, seq)); 1319 1320 systime_snapshot->cycles = now; 1321 systime_snapshot->systime = ktime_add_ns(base_sys, offs_sys + nsec_sys); 1322 systime_snapshot->monoraw = ktime_add_ns(base_raw, nsec_raw); 1323 1324 /* 1325 * Special case for PTP. Just transfer the raw time into sys, 1326 * so the call sites can consistently use snap::systime. 1327 */ 1328 if (clock_id == CLOCK_MONOTONIC_RAW) 1329 systime_snapshot->systime = systime_snapshot->monoraw; 1330 /* Tell the consumer that this snapshot is valid */ 1331 systime_snapshot->valid = true; 1332 } 1333 EXPORT_SYMBOL_GPL(ktime_get_snapshot_id); 1334 1335 /* Scale base by mult/div checking for overflow */ 1336 static int scale64_check_overflow(u64 mult, u64 div, u64 *base) 1337 { 1338 u64 tmp, rem; 1339 1340 tmp = div64_u64_rem(*base, div, &rem); 1341 1342 if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) || 1343 ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem))) 1344 return -EOVERFLOW; 1345 tmp *= mult; 1346 1347 rem = div64_u64(rem * mult, div); 1348 *base = tmp + rem; 1349 return 0; 1350 } 1351 1352 /** 1353 * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval 1354 * @history: Snapshot representing start of history 1355 * @partial_history_cycles: Cycle offset into history (fractional part) 1356 * @total_history_cycles: Total history length in cycles 1357 * @discontinuity: True indicates clock was set on history period 1358 * @ts: Cross timestamp that should be adjusted using 1359 * partial/total ratio 1360 * 1361 * Helper function used by get_device_system_crosststamp() to correct the 1362 * crosstimestamp corresponding to the start of the current interval to the 1363 * system counter value (timestamp point) provided by the driver. The 1364 * total_history_* quantities are the total history starting at the provided 1365 * reference point and ending at the start of the current interval. The cycle 1366 * count between the driver timestamp point and the start of the current 1367 * interval is partial_history_cycles. 1368 */ 1369 static int adjust_historical_crosststamp(struct system_time_snapshot *history, 1370 u64 partial_history_cycles, 1371 u64 total_history_cycles, 1372 bool discontinuity, 1373 struct system_device_crosststamp *ts) 1374 { 1375 struct timekeeper *tk = &tk_core.timekeeper; 1376 u64 corr_raw, corr_sys; 1377 bool interp_forward; 1378 int ret; 1379 1380 if (total_history_cycles == 0 || partial_history_cycles == 0) 1381 return 0; 1382 1383 /* Interpolate shortest distance from beginning or end of history */ 1384 interp_forward = partial_history_cycles > total_history_cycles / 2; 1385 partial_history_cycles = interp_forward ? 1386 total_history_cycles - partial_history_cycles : 1387 partial_history_cycles; 1388 1389 /* 1390 * Scale the monotonic raw time delta by: 1391 * partial_history_cycles / total_history_cycles 1392 */ 1393 corr_raw = (u64)ktime_to_ns(ktime_sub(ts->sys_monoraw, history->monoraw)); 1394 ret = scale64_check_overflow(partial_history_cycles, 1395 total_history_cycles, &corr_raw); 1396 if (ret) 1397 return ret; 1398 1399 /* 1400 * If there is a discontinuity in the history, scale monotonic raw 1401 * correction by: 1402 * mult(sys)/mult(raw) yielding the system time correction 1403 * 1404 * Otherwise, calculate the system time correction similar to monotonic 1405 * raw calculation 1406 */ 1407 if (discontinuity) { 1408 corr_sys = mul_u64_u32_div(corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult); 1409 } else { 1410 corr_sys = (u64)ktime_to_ns(ktime_sub(ts->sys_systime, history->systime)); 1411 ret = scale64_check_overflow(partial_history_cycles, total_history_cycles, 1412 &corr_sys); 1413 if (ret) 1414 return ret; 1415 } 1416 1417 /* Fixup monotonic raw and system time time values */ 1418 if (interp_forward) { 1419 ts->sys_monoraw = ktime_add_ns(history->monoraw, corr_raw); 1420 ts->sys_systime = ktime_add_ns(history->systime, corr_sys); 1421 } else { 1422 ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw); 1423 ts->sys_systime = ktime_sub_ns(ts->sys_systime, corr_sys); 1424 } 1425 1426 return 0; 1427 } 1428 1429 /* 1430 * timestamp_in_interval - true if ts is chronologically in [start, end] 1431 * 1432 * True if ts occurs chronologically at or after start, and before or at end. 1433 */ 1434 static bool timestamp_in_interval(u64 start, u64 end, u64 ts) 1435 { 1436 if (ts >= start && ts <= end) 1437 return true; 1438 if (start > end && (ts >= start || ts <= end)) 1439 return true; 1440 return false; 1441 } 1442 1443 static bool convert_clock(u64 *val, u32 numerator, u32 denominator) 1444 { 1445 u64 rem, res; 1446 1447 if (!numerator || !denominator) 1448 return false; 1449 1450 res = div64_u64_rem(*val, denominator, &rem) * numerator; 1451 *val = res + div_u64(rem * numerator, denominator); 1452 return true; 1453 } 1454 1455 static bool convert_base_to_cs(struct system_counterval_t *scv) 1456 { 1457 struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock; 1458 struct clocksource_base *base; 1459 u32 num, den; 1460 1461 /* The timestamp was taken from the time keeper clock source */ 1462 if (cs->id == scv->cs_id) 1463 return true; 1464 1465 /* 1466 * Check whether cs_id matches the base clock. Prevent the compiler from 1467 * re-evaluating @base as the clocksource might change concurrently. 1468 */ 1469 base = READ_ONCE(cs->base); 1470 if (!base || base->id != scv->cs_id) 1471 return false; 1472 1473 num = scv->use_nsecs ? cs->freq_khz : base->numerator; 1474 den = scv->use_nsecs ? USEC_PER_SEC : base->denominator; 1475 1476 if (!convert_clock(&scv->cycles, num, den)) 1477 return false; 1478 1479 scv->cycles += base->offset; 1480 /* Set the clocksource ID as scv::cycles is now clocksource based */ 1481 scv->cs_id = cs->id; 1482 return true; 1483 } 1484 1485 static bool convert_cs_to_base(u64 *cycles, enum clocksource_ids base_id) 1486 { 1487 struct clocksource *cs = tk_core.timekeeper.tkr_mono.clock; 1488 struct clocksource_base *base; 1489 1490 /* 1491 * Check whether base_id matches the base clock. Prevent the compiler from 1492 * re-evaluating @base as the clocksource might change concurrently. 1493 */ 1494 base = READ_ONCE(cs->base); 1495 if (!base || base->id != base_id) 1496 return false; 1497 1498 *cycles -= base->offset; 1499 if (!convert_clock(cycles, base->denominator, base->numerator)) 1500 return false; 1501 return true; 1502 } 1503 1504 static bool convert_ns_to_cs(u64 *delta) 1505 { 1506 struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono; 1507 1508 if (BITS_TO_BYTES(fls64(*delta) + tkr->shift) >= sizeof(*delta)) 1509 return false; 1510 1511 *delta = div_u64((*delta << tkr->shift) - tkr->xtime_nsec, tkr->mult); 1512 return true; 1513 } 1514 1515 /** 1516 * ktime_real_to_base_clock() - Convert CLOCK_REALTIME timestamp to a base clock timestamp 1517 * @treal: CLOCK_REALTIME timestamp to convert 1518 * @base_id: base clocksource id 1519 * @cycles: pointer to store the converted base clock timestamp 1520 * 1521 * Converts a supplied, future realtime clock value to the corresponding base clock value. 1522 * 1523 * Return: true if the conversion is successful, false otherwise. 1524 */ 1525 bool ktime_real_to_base_clock(ktime_t treal, enum clocksource_ids base_id, u64 *cycles) 1526 { 1527 struct timekeeper *tk = &tk_core.timekeeper; 1528 unsigned int seq; 1529 u64 delta; 1530 1531 do { 1532 seq = read_seqcount_begin(&tk_core.seq); 1533 if ((u64)treal < tk->tkr_mono.base_real) 1534 return false; 1535 delta = (u64)treal - tk->tkr_mono.base_real; 1536 if (!convert_ns_to_cs(&delta)) 1537 return false; 1538 *cycles = tk->tkr_mono.cycle_last + delta; 1539 if (!convert_cs_to_base(cycles, base_id)) 1540 return false; 1541 } while (read_seqcount_retry(&tk_core.seq, seq)); 1542 1543 return true; 1544 } 1545 EXPORT_SYMBOL_GPL(ktime_real_to_base_clock); 1546 1547 /** 1548 * get_device_system_crosststamp - Synchronously capture system/device timestamp 1549 * @get_time_fn: Callback to get simultaneous device time and system counter 1550 * from the device driver 1551 * @ctx: Context passed to get_time_fn() 1552 * @history_begin: Historical reference point used to interpolate system time when 1553 * the counter value provided by the driver is before the current interval 1554 * @xtstamp: Receives simultaneously captured system and device time 1555 * 1556 * Reads a timestamp from a device and correlates it to system time 1557 * 1558 * See documentation for ktime_get_snapshot_id() for information about the raw 1559 * monotonic time stamp which is used here. 1560 */ 1561 int get_device_system_crosststamp(int (*get_time_fn) 1562 (ktime_t *device_time, 1563 struct system_counterval_t *sys_counterval, 1564 void *ctx), 1565 void *ctx, 1566 struct system_time_snapshot *history_begin, 1567 struct system_device_crosststamp *xtstamp) 1568 { 1569 u64 syscnt_cycles, cycles, now, interval_start; 1570 ktime_t base_sys, base_raw, *offs; 1571 u32 clock_was_set_seq = 0; 1572 u64 nsec_sys, nsec_raw; 1573 u8 cs_was_changed_seq; 1574 unsigned int seq; 1575 bool do_interp; 1576 struct timekeeper *tk; 1577 struct tk_data *tkd; 1578 int ret; 1579 1580 switch (xtstamp->clock_id) { 1581 case CLOCK_REALTIME: 1582 tkd = &tk_core; 1583 offs = &tk_core.timekeeper.offs_real; 1584 break; 1585 case CLOCK_AUX ... CLOCK_AUX_LAST: 1586 tkd = aux_get_tk_data(xtstamp->clock_id); 1587 if (!tkd) 1588 return -ENODEV; 1589 offs = &tkd->timekeeper.offs_aux; 1590 break; 1591 default: 1592 WARN_ON_ONCE(1); 1593 return -ENODEV; 1594 } 1595 1596 tk = &tkd->timekeeper; 1597 1598 do { 1599 seq = read_seqcount_begin(&tkd->seq); 1600 /* 1601 * Try to synchronously capture device time and a system 1602 * counter value calling back into the device driver 1603 */ 1604 ret = get_time_fn(&xtstamp->device, &xtstamp->sys_counter, ctx); 1605 if (ret) 1606 return ret; 1607 1608 /* 1609 * Verify that the clocksource ID associated with the captured 1610 * system counter value is the same as for the currently 1611 * installed timekeeper clocksource and convert to it. 1612 */ 1613 if (xtstamp->sys_counter.cs_id == CSID_GENERIC || 1614 !convert_base_to_cs(&xtstamp->sys_counter)) 1615 return -ENODEV; 1616 1617 cycles = syscnt_cycles = xtstamp->sys_counter.cycles; 1618 1619 /* 1620 * Check whether the system counter value provided by the 1621 * device driver is on the current timekeeping interval. 1622 */ 1623 now = tk_clock_read(&tk->tkr_mono); 1624 interval_start = tk->tkr_mono.cycle_last; 1625 if (!timestamp_in_interval(interval_start, now, cycles)) { 1626 clock_was_set_seq = tk->clock_was_set_seq; 1627 cs_was_changed_seq = tk->cs_was_changed_seq; 1628 cycles = interval_start; 1629 do_interp = true; 1630 } else { 1631 do_interp = false; 1632 } 1633 1634 base_sys = ktime_add(tk->tkr_mono.base, *offs); 1635 base_raw = tk->tkr_raw.base; 1636 1637 nsec_sys = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles); 1638 nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles); 1639 } while (read_seqcount_retry(&tkd->seq, seq)); 1640 1641 xtstamp->sys_systime = ktime_add_ns(base_sys, nsec_sys); 1642 xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw); 1643 1644 /* 1645 * Interpolate if necessary, adjusting back from the start of the 1646 * current interval 1647 */ 1648 if (do_interp) { 1649 u64 partial_history_cycles, total_history_cycles; 1650 bool discontinuity; 1651 1652 /* 1653 * Check that the counter value is not before the provided 1654 * history reference and that the history doesn't cross a 1655 * clocksource change 1656 */ 1657 if (!history_begin || 1658 !timestamp_in_interval(history_begin->cycles, cycles, syscnt_cycles) || 1659 history_begin->cs_was_changed_seq != cs_was_changed_seq) 1660 return -EINVAL; 1661 1662 partial_history_cycles = cycles - syscnt_cycles; 1663 total_history_cycles = cycles - history_begin->cycles; 1664 discontinuity = history_begin->clock_was_set_seq != clock_was_set_seq; 1665 1666 ret = adjust_historical_crosststamp(history_begin, partial_history_cycles, 1667 total_history_cycles, discontinuity, xtstamp); 1668 } 1669 1670 return ret; 1671 } 1672 EXPORT_SYMBOL_GPL(get_device_system_crosststamp); 1673 1674 /** 1675 * timekeeping_clocksource_has_base - Check whether the current clocksource 1676 * is based on given a base clock 1677 * @id: base clocksource ID 1678 * 1679 * Note: The return value is a snapshot which can become invalid right 1680 * after the function returns. 1681 * 1682 * Return: true if the timekeeper clocksource has a base clock with @id, 1683 * false otherwise 1684 */ 1685 bool timekeeping_clocksource_has_base(enum clocksource_ids id) 1686 { 1687 /* 1688 * This is a snapshot, so no point in using the sequence 1689 * count. Just prevent the compiler from re-evaluating @base as the 1690 * clocksource might change concurrently. 1691 */ 1692 struct clocksource_base *base = READ_ONCE(tk_core.timekeeper.tkr_mono.clock->base); 1693 1694 return base ? base->id == id : false; 1695 } 1696 EXPORT_SYMBOL_GPL(timekeeping_clocksource_has_base); 1697 1698 /** 1699 * do_settimeofday64 - Sets the time of day. 1700 * @ts: pointer to the timespec64 variable containing the new time 1701 * 1702 * Sets the time of day to the new time and update NTP and notify hrtimers 1703 */ 1704 int do_settimeofday64(const struct timespec64 *ts) 1705 { 1706 struct timespec64 ts_delta, xt; 1707 1708 if (!timespec64_valid_settod(ts)) 1709 return -EINVAL; 1710 1711 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) { 1712 struct timekeeper *tks = &tk_core.shadow_timekeeper; 1713 1714 timekeeping_forward_now(tks); 1715 1716 xt = tk_xtime(tks); 1717 ts_delta = timespec64_sub(*ts, xt); 1718 1719 if (timespec64_compare(&tks->wall_to_monotonic, &ts_delta) > 0) { 1720 timekeeping_restore_shadow(&tk_core); 1721 return -EINVAL; 1722 } 1723 1724 tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, ts_delta)); 1725 tk_set_xtime(tks, ts); 1726 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL); 1727 } 1728 1729 /* Signal hrtimers about time change */ 1730 clock_was_set(CLOCK_SET_WALL); 1731 1732 audit_tk_injoffset(ts_delta); 1733 add_device_randomness(ts, sizeof(*ts)); 1734 return 0; 1735 } 1736 EXPORT_SYMBOL(do_settimeofday64); 1737 1738 static inline bool timekeeper_is_core_tk(struct timekeeper *tk) 1739 { 1740 return !IS_ENABLED(CONFIG_POSIX_AUX_CLOCKS) || tk->id == TIMEKEEPER_CORE; 1741 } 1742 1743 /** 1744 * __timekeeping_inject_offset - Adds or subtracts from the current time. 1745 * @tkd: Pointer to the timekeeper to modify 1746 * @ts: Pointer to the timespec variable containing the offset 1747 * 1748 * Adds or subtracts an offset value from the current time. 1749 */ 1750 static int __timekeeping_inject_offset(struct tk_data *tkd, const struct timespec64 *ts) 1751 { 1752 struct timekeeper *tks = &tkd->shadow_timekeeper; 1753 struct timespec64 tmp; 1754 1755 if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC) 1756 return -EINVAL; 1757 1758 timekeeping_forward_now(tks); 1759 1760 if (timekeeper_is_core_tk(tks)) { 1761 /* Make sure the proposed value is valid */ 1762 tmp = timespec64_add(tk_xtime(tks), *ts); 1763 if (timespec64_compare(&tks->wall_to_monotonic, ts) > 0 || 1764 !timespec64_valid_settod(&tmp)) { 1765 timekeeping_restore_shadow(tkd); 1766 return -EINVAL; 1767 } 1768 1769 tk_xtime_add(tks, ts); 1770 tk_set_wall_to_mono(tks, timespec64_sub(tks->wall_to_monotonic, *ts)); 1771 } else { 1772 struct tk_read_base *tkr_mono = &tks->tkr_mono; 1773 ktime_t now, offs; 1774 1775 /* Get the current time */ 1776 now = ktime_add_ns(tkr_mono->base, timekeeping_get_ns(tkr_mono)); 1777 /* Add the relative offset change */ 1778 offs = ktime_add(tks->offs_aux, timespec64_to_ktime(*ts)); 1779 1780 /* Prevent that the resulting time becomes negative */ 1781 if (ktime_add(now, offs) < 0) { 1782 timekeeping_restore_shadow(tkd); 1783 return -EINVAL; 1784 } 1785 tk_update_aux_offs(tks, offs); 1786 } 1787 1788 timekeeping_update_from_shadow(tkd, TK_UPDATE_ALL); 1789 return 0; 1790 } 1791 1792 static int timekeeping_inject_offset(const struct timespec64 *ts) 1793 { 1794 int ret; 1795 1796 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) 1797 ret = __timekeeping_inject_offset(&tk_core, ts); 1798 1799 /* Signal hrtimers about time change */ 1800 if (!ret) 1801 clock_was_set(CLOCK_SET_WALL); 1802 return ret; 1803 } 1804 1805 /* 1806 * Indicates if there is an offset between the system clock and the hardware 1807 * clock/persistent clock/rtc. 1808 */ 1809 int persistent_clock_is_local; 1810 1811 /* 1812 * Adjust the time obtained from the CMOS to be UTC time instead of 1813 * local time. 1814 * 1815 * This is ugly, but preferable to the alternatives. Otherwise we 1816 * would either need to write a program to do it in /etc/rc (and risk 1817 * confusion if the program gets run more than once; it would also be 1818 * hard to make the program warp the clock precisely n hours) or 1819 * compile in the timezone information into the kernel. Bad, bad.... 1820 * 1821 * - TYT, 1992-01-01 1822 * 1823 * The best thing to do is to keep the CMOS clock in universal time (UTC) 1824 * as real UNIX machines always do it. This avoids all headaches about 1825 * daylight saving times and warping kernel clocks. 1826 */ 1827 void timekeeping_warp_clock(void) 1828 { 1829 if (sys_tz.tz_minuteswest != 0) { 1830 struct timespec64 adjust; 1831 1832 persistent_clock_is_local = 1; 1833 adjust.tv_sec = sys_tz.tz_minuteswest * 60; 1834 adjust.tv_nsec = 0; 1835 timekeeping_inject_offset(&adjust); 1836 } 1837 } 1838 1839 /* 1840 * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic 1841 */ 1842 static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset) 1843 { 1844 tk->tai_offset = tai_offset; 1845 tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0)); 1846 } 1847 1848 /* 1849 * change_clocksource - Swaps clocksources if a new one is available 1850 * 1851 * Accumulates current time interval and initializes new clocksource 1852 */ 1853 static int change_clocksource(void *data) 1854 { 1855 struct clocksource *new = data, *old = NULL; 1856 1857 /* 1858 * If the clocksource is in a module, get a module reference. 1859 * Succeeds for built-in code (owner == NULL) as well. Abort if the 1860 * reference can't be acquired. 1861 */ 1862 if (!try_module_get(new->owner)) 1863 return 0; 1864 1865 /* Abort if the device can't be enabled */ 1866 if (new->enable && new->enable(new) != 0) { 1867 module_put(new->owner); 1868 return 0; 1869 } 1870 1871 scoped_guard (raw_spinlock_irqsave, &tk_core.lock) { 1872 struct timekeeper *tks = &tk_core.shadow_timekeeper; 1873 1874 timekeeping_forward_now(tks); 1875 old = tks->tkr_mono.clock; 1876 tk_setup_internals(tks, new); 1877 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL); 1878 } 1879 1880 tk_aux_update_clocksource(); 1881 1882 if (old) { 1883 if (old->disable) 1884 old->disable(old); 1885 module_put(old->owner); 1886 } 1887 1888 return 0; 1889 } 1890 1891 /** 1892 * timekeeping_notify - Install a new clock source 1893 * @clock: pointer to the clock source 1894 * 1895 * This function is called from clocksource.c after a new, better clock 1896 * source has been registered. The caller holds the clocksource_mutex. 1897 */ 1898 int timekeeping_notify(struct clocksource *clock) 1899 { 1900 struct timekeeper *tk = &tk_core.timekeeper; 1901 1902 if (tk->tkr_mono.clock == clock) 1903 return 0; 1904 1905 /* Disable inlined reads accross the clocksource switch */ 1906 clocksource_disable_inline_read(); 1907 1908 stop_machine(change_clocksource, clock, NULL); 1909 1910 /* 1911 * If the clocksource has been selected and supports inlined reads 1912 * enable the branch. 1913 */ 1914 if (tk->tkr_mono.clock == clock && clock->flags & CLOCK_SOURCE_CAN_INLINE_READ) 1915 clocksource_enable_inline_read(); 1916 1917 tick_clock_notify(); 1918 return tk->tkr_mono.clock == clock ? 0 : -1; 1919 } 1920 1921 /** 1922 * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec 1923 * @ts: pointer to the timespec64 to be set 1924 * 1925 * Returns the raw monotonic time (completely un-modified by ntp) 1926 */ 1927 void ktime_get_raw_ts64(struct timespec64 *ts) 1928 { 1929 struct timekeeper *tk = &tk_core.timekeeper; 1930 unsigned int seq; 1931 u64 nsecs; 1932 1933 do { 1934 seq = read_seqcount_begin(&tk_core.seq); 1935 ts->tv_sec = tk->raw_sec; 1936 nsecs = timekeeping_get_ns(&tk->tkr_raw); 1937 1938 } while (read_seqcount_retry(&tk_core.seq, seq)); 1939 1940 ts->tv_nsec = 0; 1941 timespec64_add_ns(ts, nsecs); 1942 } 1943 EXPORT_SYMBOL(ktime_get_raw_ts64); 1944 1945 /** 1946 * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres 1947 */ 1948 int timekeeping_valid_for_hres(void) 1949 { 1950 struct timekeeper *tk = &tk_core.timekeeper; 1951 unsigned int seq; 1952 int ret; 1953 1954 do { 1955 seq = read_seqcount_begin(&tk_core.seq); 1956 1957 ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES; 1958 1959 } while (read_seqcount_retry(&tk_core.seq, seq)); 1960 1961 return ret; 1962 } 1963 1964 /** 1965 * timekeeping_max_deferment - Returns max time the clocksource can be deferred 1966 */ 1967 u64 timekeeping_max_deferment(void) 1968 { 1969 struct timekeeper *tk = &tk_core.timekeeper; 1970 unsigned int seq; 1971 u64 ret; 1972 1973 do { 1974 seq = read_seqcount_begin(&tk_core.seq); 1975 1976 ret = tk->tkr_mono.clock->max_idle_ns; 1977 1978 } while (read_seqcount_retry(&tk_core.seq, seq)); 1979 1980 return ret; 1981 } 1982 1983 /** 1984 * read_persistent_clock64 - Return time from the persistent clock. 1985 * @ts: Pointer to the storage for the readout value 1986 * 1987 * Weak dummy function for arches that do not yet support it. 1988 * Reads the time from the battery backed persistent clock. 1989 * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported. 1990 * 1991 * XXX - Do be sure to remove it once all arches implement it. 1992 */ 1993 void __weak read_persistent_clock64(struct timespec64 *ts) 1994 { 1995 ts->tv_sec = 0; 1996 ts->tv_nsec = 0; 1997 } 1998 1999 /** 2000 * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset 2001 * from the boot. 2002 * @wall_time: current time as returned by persistent clock 2003 * @boot_offset: offset that is defined as wall_time - boot_time 2004 * 2005 * Weak dummy function for arches that do not yet support it. 2006 * 2007 * The default function calculates offset based on the current value of 2008 * local_clock(). This way architectures that support sched_clock() but don't 2009 * support dedicated boot time clock will provide the best estimate of the 2010 * boot time. 2011 */ 2012 void __weak __init 2013 read_persistent_wall_and_boot_offset(struct timespec64 *wall_time, 2014 struct timespec64 *boot_offset) 2015 { 2016 read_persistent_clock64(wall_time); 2017 *boot_offset = ns_to_timespec64(local_clock()); 2018 } 2019 2020 static __init void tkd_basic_setup(struct tk_data *tkd, enum timekeeper_ids tk_id, bool valid) 2021 { 2022 raw_spin_lock_init(&tkd->lock); 2023 seqcount_raw_spinlock_init(&tkd->seq, &tkd->lock); 2024 tkd->timekeeper.id = tkd->shadow_timekeeper.id = tk_id; 2025 tkd->timekeeper.clock_valid = tkd->shadow_timekeeper.clock_valid = valid; 2026 } 2027 2028 /* 2029 * Flag reflecting whether timekeeping_resume() has injected sleeptime. 2030 * 2031 * The flag starts of false and is only set when a suspend reaches 2032 * timekeeping_suspend(), timekeeping_resume() sets it to false when the 2033 * timekeeper clocksource is not stopping across suspend and has been 2034 * used to update sleep time. If the timekeeper clocksource has stopped 2035 * then the flag stays true and is used by the RTC resume code to decide 2036 * whether sleeptime must be injected and if so the flag gets false then. 2037 * 2038 * If a suspend fails before reaching timekeeping_resume() then the flag 2039 * stays false and prevents erroneous sleeptime injection. 2040 */ 2041 static bool suspend_timing_needed; 2042 2043 /* Flag for if there is a persistent clock on this platform */ 2044 static bool persistent_clock_exists; 2045 2046 /* 2047 * timekeeping_init - Initializes the clocksource and common timekeeping values 2048 */ 2049 void __init timekeeping_init(void) 2050 { 2051 struct timespec64 wall_time, boot_offset, wall_to_mono; 2052 struct timekeeper *tks = &tk_core.shadow_timekeeper; 2053 struct clocksource *clock; 2054 2055 tkd_basic_setup(&tk_core, TIMEKEEPER_CORE, true); 2056 tk_aux_setup(); 2057 2058 read_persistent_wall_and_boot_offset(&wall_time, &boot_offset); 2059 if (timespec64_valid_settod(&wall_time) && 2060 timespec64_to_ns(&wall_time) > 0) { 2061 persistent_clock_exists = true; 2062 } else if (timespec64_to_ns(&wall_time) != 0) { 2063 pr_warn("Persistent clock returned invalid value"); 2064 wall_time = (struct timespec64){0}; 2065 } 2066 2067 if (timespec64_compare(&wall_time, &boot_offset) < 0) 2068 boot_offset = (struct timespec64){0}; 2069 2070 /* 2071 * We want set wall_to_mono, so the following is true: 2072 * wall time + wall_to_mono = boot time 2073 */ 2074 wall_to_mono = timespec64_sub(boot_offset, wall_time); 2075 2076 clock = clocksource_default_clock(); 2077 if (clock->enable) 2078 clock->enable(clock); 2079 2080 guard(raw_spinlock_irqsave)(&tk_core.lock); 2081 2082 ntp_init(); 2083 2084 tk_setup_internals(tks, clock); 2085 2086 tk_set_xtime(tks, &wall_time); 2087 tks->raw_sec = 0; 2088 2089 tk_set_wall_to_mono(tks, wall_to_mono); 2090 2091 /* 2092 * Use TK_UPDATE_ALL so the NTP layer picks up the clocksource's 2093 * cs_tick_adj via ntp_clear(). Clearing NTP here is otherwise 2094 * redundant as ntp_init() already initialised it above. 2095 */ 2096 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL); 2097 } 2098 2099 /* time in seconds when suspend began for persistent clock */ 2100 static struct timespec64 timekeeping_suspend_time; 2101 2102 /** 2103 * __timekeeping_inject_sleeptime - Internal function to add sleep interval 2104 * @tk: Pointer to the timekeeper to be updated 2105 * @delta: Pointer to the delta value in timespec64 format 2106 * 2107 * Takes a timespec offset measuring a suspend interval and properly 2108 * adds the sleep offset to the timekeeping variables. 2109 */ 2110 static void __timekeeping_inject_sleeptime(struct timekeeper *tk, 2111 const struct timespec64 *delta) 2112 { 2113 if (!timespec64_valid_strict(delta)) { 2114 printk_deferred(KERN_WARNING 2115 "__timekeeping_inject_sleeptime: Invalid " 2116 "sleep delta value!\n"); 2117 return; 2118 } 2119 tk_xtime_add(tk, delta); 2120 tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta)); 2121 tk_update_sleep_time(tk, timespec64_to_ktime(*delta)); 2122 tk_debug_account_sleep_time(delta); 2123 } 2124 2125 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE) 2126 /* 2127 * We have three kinds of time sources to use for sleep time 2128 * injection, the preference order is: 2129 * 1) non-stop clocksource 2130 * 2) persistent clock (ie: RTC accessible when irqs are off) 2131 * 3) RTC 2132 * 2133 * 1) and 2) are used by timekeeping, 3) by RTC subsystem. 2134 * If system has neither 1) nor 2), 3) will be used finally. 2135 * 2136 * 2137 * If timekeeping has injected sleeptime via either 1) or 2), 2138 * 3) becomes needless, so in this case we don't need to call 2139 * rtc_resume(), and this is what timekeeping_rtc_skipresume() 2140 * means. 2141 */ 2142 bool timekeeping_rtc_skipresume(void) 2143 { 2144 return !suspend_timing_needed; 2145 } 2146 2147 /* 2148 * 1) can be determined whether to use or not only when doing 2149 * timekeeping_resume() which is invoked after rtc_suspend(), 2150 * so we can't skip rtc_suspend() surely if system has 1). 2151 * 2152 * But if system has 2), 2) will definitely be used, so in this 2153 * case we don't need to call rtc_suspend(), and this is what 2154 * timekeeping_rtc_skipsuspend() means. 2155 */ 2156 bool timekeeping_rtc_skipsuspend(void) 2157 { 2158 return persistent_clock_exists; 2159 } 2160 2161 /** 2162 * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values 2163 * @delta: pointer to a timespec64 delta value 2164 * 2165 * This hook is for architectures that cannot support read_persistent_clock64 2166 * because their RTC/persistent clock is only accessible when irqs are enabled. 2167 * and also don't have an effective nonstop clocksource. 2168 * 2169 * This function should only be called by rtc_resume(), and allows 2170 * a suspend offset to be injected into the timekeeping values. 2171 */ 2172 void timekeeping_inject_sleeptime64(const struct timespec64 *delta) 2173 { 2174 scoped_guard(raw_spinlock_irqsave, &tk_core.lock) { 2175 struct timekeeper *tks = &tk_core.shadow_timekeeper; 2176 2177 suspend_timing_needed = false; 2178 timekeeping_forward_now(tks); 2179 __timekeeping_inject_sleeptime(tks, delta); 2180 timekeeping_update_from_shadow(&tk_core, TK_UPDATE_ALL); 2181 } 2182 2183 /* Signal hrtimers about time change */ 2184 clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT); 2185 } 2186 #endif 2187 2188 /** 2189 * timekeeping_resume - Resumes the generic timekeeping subsystem. 2190 */ 2191 void timekeeping_resume(void) 2192 { 2193 struct timekeeper *tks = &tk_core.shadow_timekeeper; 2194 struct clocksource *clock = tks->tkr_mono.clock; 2195 struct timespec64 ts_new, ts_delta; 2196 bool inject_sleeptime = false; 2197 u64 cycle_now, nsec; 2198 unsigned long flags; 2199 2200 read_persistent_clock64(&ts_new); 2201 2202 clockevents_resume(); 2203 clocksource_resume(); 2204 2205 raw_spin_lock_irqsave(&tk_core.lock, flags); 2206 2207 /* 2208 * After system resumes, we need to calculate the suspended time and 2209 * compensate it for the OS time. There are 3 sources that could be 2210 * used: Nonstop clocksource during suspend, persistent clock and rtc 2211 * device. 2212 * 2213 * One specific platform may have 1 or 2 or all of them, and the 2214 * preference will be: 2215 * suspend-nonstop clocksource -> persistent clock -> rtc 2216 * The less preferred source will only be tried if there is no better 2217 * usable source. The rtc part is handled separately in rtc core code. 2218 */ 2219 cycle_now = tk_clock_read(&tks->tkr_mono); 2220 nsec = clocksource_stop_suspend_timing(clock, cycle_now); 2221 if (nsec > 0) { 2222 ts_delta = ns_to_timespec64(nsec); 2223 inject_sleeptime = true; 2224 } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) { 2225 ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time); 2226 inject_sleeptime = true; 2227 } 2228 2229 if (inject_sleeptime) { 2230 suspend_timing_needed = false; 2231 __timekeeping_inject_sleeptime(tks, &ts_delta); 2232 } 2233 2234 /* Re-base the last cycle value */ 2235 tks->tkr_mono.cycle_last = cycle_now; 2236 tks->tkr_raw.cycle_last = cycle_now; 2237 2238 tks->ntp_error = 0; 2239 timekeeping_suspended = 0; 2240 timekeeping_update_from_shadow(&tk_core, TK_CLOCK_WAS_SET); 2241 raw_spin_unlock_irqrestore(&tk_core.lock, flags); 2242 2243 touch_softlockup_watchdog(); 2244 2245 /* Resume the clockevent device(s) and hrtimers */ 2246 tick_resume(); 2247 /* Notify timerfd as resume is equivalent to clock_was_set() */ 2248 timerfd_resume(); 2249 } 2250 2251 static void timekeeping_syscore_resume(void *data) 2252 { 2253 timekeeping_resume(); 2254 } 2255 2256 int timekeeping_suspend(void) 2257 { 2258 struct timekeeper *tks = &tk_core.shadow_timekeeper; 2259 struct timespec64 delta, delta_delta; 2260 static struct timespec64 old_delta; 2261 struct clocksource *curr_clock; 2262 unsigned long flags; 2263 u64 cycle_now; 2264 2265 read_persistent_clock64(&timekeeping_suspend_time); 2266 2267 /* 2268 * On some systems the persistent_clock can not be detected at 2269 * timekeeping_init by its return value, so if we see a valid 2270 * value returned, update the persistent_clock_exists flag. 2271 */ 2272 if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec) 2273 persistent_clock_exists = true; 2274 2275 suspend_timing_needed = true; 2276 2277 raw_spin_lock_irqsave(&tk_core.lock, flags); 2278 timekeeping_forward_now(tks); 2279 timekeeping_suspended = 1; 2280 2281 /* 2282 * Since we've called forward_now, cycle_last stores the value 2283 * just read from the current clocksource. Save this to potentially 2284 * use in suspend timing. 2285 */ 2286 curr_clock = tks->tkr_mono.clock; 2287 cycle_now = tks->tkr_mono.cycle_last; 2288 clocksource_start_suspend_timing(curr_clock, cycle_now); 2289 2290 if (persistent_clock_exists) { 2291 /* 2292 * To avoid drift caused by repeated suspend/resumes, 2293 * which each can add ~1 second drift error, 2294 * try to compensate so the difference in system time 2295 * and persistent_clock time stays close to constant. 2296 */ 2297 delta = timespec64_sub(tk_xtime(tks), timekeeping_suspend_time); 2298 delta_delta = timespec64_sub(delta, old_delta); 2299 if (abs(delta_delta.tv_sec) >= 2) { 2300 /* 2301 * if delta_delta is too large, assume time correction 2302 * has occurred and set old_delta to the current delta. 2303 */ 2304 old_delta = delta; 2305 } else { 2306 /* Otherwise try to adjust old_system to compensate */ 2307 timekeeping_suspend_time = 2308 timespec64_add(timekeeping_suspend_time, delta_delta); 2309 } 2310 } 2311 2312 timekeeping_update_from_shadow(&tk_core, 0); 2313 halt_fast_timekeeper(tks); 2314 raw_spin_unlock_irqrestore(&tk_core.lock, flags); 2315 2316 tick_suspend(); 2317 clocksource_suspend(); 2318 clockevents_suspend(); 2319 2320 return 0; 2321 } 2322 2323 static int timekeeping_syscore_suspend(void *data) 2324 { 2325 return timekeeping_suspend(); 2326 } 2327 2328 /* sysfs resume/suspend bits for timekeeping */ 2329 static const struct syscore_ops timekeeping_syscore_ops = { 2330 .resume = timekeeping_syscore_resume, 2331 .suspend = timekeeping_syscore_suspend, 2332 }; 2333 2334 static struct syscore timekeeping_syscore = { 2335 .ops = &timekeeping_syscore_ops, 2336 }; 2337 2338 static int __init timekeeping_init_ops(void) 2339 { 2340 register_syscore(&timekeeping_syscore); 2341 return 0; 2342 } 2343 device_initcall(timekeeping_init_ops); 2344 2345 /* 2346 * Apply a multiplier adjustment to the timekeeper 2347 */ 2348 static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk, 2349 s64 offset, 2350 s32 mult_adj) 2351 { 2352 s64 interval = tk->cycle_interval; 2353 2354 if (mult_adj == 0) { 2355 return; 2356 } else if (mult_adj == -1) { 2357 interval = -interval; 2358 offset = -offset; 2359 } else if (mult_adj != 1) { 2360 interval *= mult_adj; 2361 offset *= mult_adj; 2362 } 2363 2364 /* 2365 * So the following can be confusing. 2366 * 2367 * To keep things simple, lets assume mult_adj == 1 for now. 2368 * 2369 * When mult_adj != 1, remember that the interval and offset values 2370 * have been appropriately scaled so the math is the same. 2371 * 2372 * The basic idea here is that we're increasing the multiplier 2373 * by one, this causes the xtime_interval to be incremented by 2374 * one cycle_interval. This is because: 2375 * xtime_interval = cycle_interval * mult 2376 * So if mult is being incremented by one: 2377 * xtime_interval = cycle_interval * (mult + 1) 2378 * Its the same as: 2379 * xtime_interval = (cycle_interval * mult) + cycle_interval 2380 * Which can be shortened to: 2381 * xtime_interval += cycle_interval 2382 * 2383 * So offset stores the non-accumulated cycles. Thus the current 2384 * time (in shifted nanoseconds) is: 2385 * now = (offset * adj) + xtime_nsec 2386 * Now, even though we're adjusting the clock frequency, we have 2387 * to keep time consistent. In other words, we can't jump back 2388 * in time, and we also want to avoid jumping forward in time. 2389 * 2390 * So given the same offset value, we need the time to be the same 2391 * both before and after the freq adjustment. 2392 * now = (offset * adj_1) + xtime_nsec_1 2393 * now = (offset * adj_2) + xtime_nsec_2 2394 * So: 2395 * (offset * adj_1) + xtime_nsec_1 = 2396 * (offset * adj_2) + xtime_nsec_2 2397 * And we know: 2398 * adj_2 = adj_1 + 1 2399 * So: 2400 * (offset * adj_1) + xtime_nsec_1 = 2401 * (offset * (adj_1+1)) + xtime_nsec_2 2402 * (offset * adj_1) + xtime_nsec_1 = 2403 * (offset * adj_1) + offset + xtime_nsec_2 2404 * Canceling the sides: 2405 * xtime_nsec_1 = offset + xtime_nsec_2 2406 * Which gives us: 2407 * xtime_nsec_2 = xtime_nsec_1 - offset 2408 * Which simplifies to: 2409 * xtime_nsec -= offset 2410 * 2411 * When subtracting offset from xtime_nsec, the same amount 2412 * (in appropriate units) has to be added to ntp_error, in 2413 * order to correctly track the delta between the time 2414 * reported in xtime_nsec, and the intended time. 2415 */ 2416 if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) { 2417 /* NTP adjustment caused clocksource mult overflow */ 2418 WARN_ON_ONCE(1); 2419 return; 2420 } 2421 2422 tk->tkr_mono.mult += mult_adj; 2423 tk->xtime_interval += interval; 2424 tk->tkr_mono.xtime_nsec -= offset; 2425 tk->ntp_error += offset << tk->ntp_error_shift; 2426 } 2427 2428 /* 2429 * Adjust the timekeeper's multiplier to the correct frequency 2430 * and also to reduce the accumulated error value. 2431 */ 2432 static void timekeeping_adjust(struct timekeeper *tk, s64 offset) 2433 { 2434 u64 ntp_tl = ntp_tick_length(tk->id); 2435 s64 skew = ntp_get_skew_delta(tk->id); 2436 u32 mult; 2437 2438 /* 2439 * Determine the multiplier from the current NTP tick length plus 2440 * skew_delta. The skew biases mult so that ±1 dithering can deliver 2441 * the time_offset slew rate. Recompute when either changes. 2442 */ 2443 if (likely(tk->ntp_tick == ntp_tl && tk->skew_delta == skew)) { 2444 /* Revert to the base mult rate. */ 2445 mult = tk->tkr_mono.mult - tk->ntp_err_mult; 2446 } else { 2447 tk->ntp_tick = ntp_tl; 2448 tk->skew_delta = skew; 2449 /* 2450 * skew_delta is stored pre-divided by HZ (matching time_offset); 2451 * scale it back up to the full per-tick rate for the mult bias. 2452 */ 2453 skew *= NTP_INTERVAL_FREQ; 2454 mult = div64_u64((tk->ntp_tick + skew) >> tk->ntp_error_shift, 2455 tk->cycle_interval); 2456 } 2457 2458 /* 2459 * If the clock is behind the NTP time, increase the multiplier by 1 2460 * to catch up with it. If it's ahead and there was a remainder in the 2461 * tick division, the clock will slow down. Otherwise it will stay 2462 * ahead until the tick length changes to a non-divisible value. 2463 */ 2464 tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0; 2465 mult += tk->ntp_err_mult; 2466 2467 timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult); 2468 2469 if (unlikely(tk->tkr_mono.clock->maxadj && 2470 (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult) 2471 > tk->tkr_mono.clock->maxadj))) { 2472 printk_once(KERN_WARNING 2473 "Adjusting %s more than 11%% (%ld vs %ld)\n", 2474 tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult, 2475 (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj); 2476 } 2477 2478 /* 2479 * It may be possible that when we entered this function, xtime_nsec 2480 * was very small. Further, if we're slightly speeding the clocksource 2481 * in the code above, its possible the required corrective factor to 2482 * xtime_nsec could cause it to underflow. 2483 * 2484 * Now, since we have already accumulated the second and the NTP 2485 * subsystem has been notified via second_overflow(), we need to skip 2486 * the next update. 2487 */ 2488 if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) { 2489 tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC << 2490 tk->tkr_mono.shift; 2491 tk->xtime_sec--; 2492 tk->skip_second_overflow = 1; 2493 } 2494 } 2495 2496 /* 2497 * accumulate_nsecs_to_secs - Accumulates nsecs into secs 2498 * 2499 * Helper function that accumulates the nsecs greater than a second 2500 * from the xtime_nsec field to the xtime_secs field. 2501 * It also calls into the NTP code to handle leapsecond processing. 2502 */ 2503 static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk) 2504 { 2505 u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift; 2506 unsigned int clock_set = 0; 2507 2508 while (tk->tkr_mono.xtime_nsec >= nsecps) { 2509 int leap; 2510 2511 tk->tkr_mono.xtime_nsec -= nsecps; 2512 tk->xtime_sec++; 2513 2514 /* 2515 * Skip NTP update if this second was accumulated before, 2516 * i.e. xtime_nsec underflowed in timekeeping_adjust() 2517 */ 2518 if (unlikely(tk->skip_second_overflow)) { 2519 tk->skip_second_overflow = 0; 2520 continue; 2521 } 2522 2523 /* Figure out if its a leap sec and apply if needed */ 2524 leap = second_overflow(tk->id, tk->xtime_sec); 2525 if (unlikely(leap)) { 2526 struct timespec64 ts; 2527 2528 tk->xtime_sec += leap; 2529 2530 ts.tv_sec = leap; 2531 ts.tv_nsec = 0; 2532 tk_set_wall_to_mono(tk, 2533 timespec64_sub(tk->wall_to_monotonic, ts)); 2534 2535 __timekeeping_set_tai_offset(tk, tk->tai_offset - leap); 2536 2537 clock_set = TK_CLOCK_WAS_SET; 2538 } 2539 } 2540 return clock_set; 2541 } 2542 2543 /* 2544 * logarithmic_accumulation - shifted accumulation of cycles 2545 * 2546 * This functions accumulates a shifted interval of cycles into 2547 * a shifted interval nanoseconds. Allows for O(log) accumulation 2548 * loop. 2549 * 2550 * Returns the unconsumed cycles. 2551 */ 2552 static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset, 2553 u32 shift, unsigned int *clock_set) 2554 { 2555 u64 interval = tk->cycle_interval << shift; 2556 u64 snsec_per_sec; 2557 2558 /* If the offset is smaller than a shifted interval, do nothing */ 2559 if (offset < interval) 2560 return offset; 2561 2562 /* Accumulate one shifted interval */ 2563 offset -= interval; 2564 tk->tkr_mono.cycle_last += interval; 2565 tk->tkr_raw.cycle_last += interval; 2566 2567 tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift; 2568 *clock_set |= accumulate_nsecs_to_secs(tk); 2569 2570 /* Accumulate raw time */ 2571 tk->tkr_raw.xtime_nsec += tk->raw_interval << shift; 2572 snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift; 2573 while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) { 2574 tk->tkr_raw.xtime_nsec -= snsec_per_sec; 2575 tk->raw_sec++; 2576 } 2577 2578 /* Accumulate error between NTP and clock interval */ 2579 tk->ntp_error += tk->ntp_tick << shift; 2580 tk->ntp_error -= tk->xtime_interval << (tk->ntp_error_shift + shift); 2581 2582 /* 2583 * When skewing, do so by adjusting ntp_error to impart an extra 2584 * target delta into ntp_error per tick, limited to what can be 2585 * drained from time_offset / time_adjust to avoid overshoot. 2586 * 2587 * The base 'mult' value was calculated with the skew taken into 2588 * account, such that the per-tick choice of 'mult' vs. 'mult+1' 2589 * allows for the desired effective rate and ntp_error does not 2590 * grow unbounded. 2591 * 2592 * Once the full desired phase offset is delivered, any remaining 2593 * skew imparted by the adjusted 'mult', accounted above, remains 2594 * in ntp_error and will be compensated by the dithering over time. 2595 */ 2596 if (tk->skew_delta) 2597 tk->ntp_error += ntp_drain_skew(tk->id, tk->skew_delta << shift, 2598 shift) * NTP_INTERVAL_FREQ; 2599 2600 return offset; 2601 } 2602 2603 /* 2604 * timekeeping_advance - Updates the timekeeper to the current time and 2605 * current NTP tick length 2606 */ 2607 static bool __timekeeping_advance(struct tk_data *tkd, enum timekeeping_adv_mode mode) 2608 { 2609 struct timekeeper *tk = &tkd->shadow_timekeeper; 2610 struct timekeeper *real_tk = &tkd->timekeeper; 2611 unsigned int clock_set = 0; 2612 int shift = 0, maxshift; 2613 u64 offset, orig_offset; 2614 2615 /* Make sure we're fully resumed: */ 2616 if (unlikely(timekeeping_suspended)) 2617 return false; 2618 2619 offset = clocksource_delta(tk_clock_read(&tk->tkr_mono), 2620 tk->tkr_mono.cycle_last, tk->tkr_mono.mask, 2621 tk->tkr_mono.clock->max_raw_delta); 2622 orig_offset = offset; 2623 /* Check if there's really nothing to do */ 2624 if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK) 2625 return false; 2626 2627 /* 2628 * With NO_HZ we may have to accumulate many cycle_intervals 2629 * (think "ticks") worth of time at once. To do this efficiently, 2630 * we calculate the largest doubling multiple of cycle_intervals 2631 * that is smaller than the offset. We then accumulate that 2632 * chunk in one go, and then try to consume the next smaller 2633 * doubled multiple. 2634 */ 2635 shift = ilog2(offset) - ilog2(tk->cycle_interval); 2636 shift = max(0, shift); 2637 /* Bound shift to one less than what overflows tick_length */ 2638 maxshift = (64 - (ilog2(ntp_tick_length(tk->id)) + 1)) - 1; 2639 shift = min(shift, maxshift); 2640 while (offset >= tk->cycle_interval) { 2641 offset = logarithmic_accumulation(tk, offset, shift, &clock_set); 2642 if (offset < tk->cycle_interval<<shift) 2643 shift--; 2644 } 2645 2646 /* Adjust the multiplier to correct NTP error */ 2647 timekeeping_adjust(tk, offset); 2648 2649 /* 2650 * Finally, make sure that after the rounding 2651 * xtime_nsec isn't larger than NSEC_PER_SEC 2652 */ 2653 clock_set |= accumulate_nsecs_to_secs(tk); 2654 2655 /* 2656 * To avoid inconsistencies caused adjtimex TK_ADV_FREQ calls 2657 * making small negative adjustments to the base xtime_nsec 2658 * value, only update the coarse clocks if we accumulated time 2659 */ 2660 if (orig_offset != offset) 2661 tk_update_coarse_nsecs(tk); 2662 2663 timekeeping_update_from_shadow(tkd, clock_set); 2664 2665 return !!clock_set; 2666 } 2667 2668 static bool timekeeping_advance(enum timekeeping_adv_mode mode) 2669 { 2670 guard(raw_spinlock_irqsave)(&tk_core.lock); 2671 return __timekeeping_advance(&tk_core, mode); 2672 } 2673 2674 /** 2675 * update_wall_time - Uses the current clocksource to increment the wall time 2676 * 2677 * It also updates the enabled auxiliary clock timekeepers 2678 */ 2679 void update_wall_time(void) 2680 { 2681 if (timekeeping_advance(TK_ADV_TICK)) 2682 clock_was_set_delayed(); 2683 tk_aux_advance(); 2684 } 2685 2686 /** 2687 * getboottime64 - Return the real time of system boot. 2688 * @ts: pointer to the timespec64 to be set 2689 * 2690 * Returns the wall-time of boot in a timespec64. 2691 * 2692 * This is based on the wall_to_monotonic offset and the total suspend 2693 * time. Calls to settimeofday will affect the value returned (which 2694 * basically means that however wrong your real time clock is at boot time, 2695 * you get the right time here). 2696 */ 2697 void getboottime64(struct timespec64 *ts) 2698 { 2699 struct timekeeper *tk = &tk_core.timekeeper; 2700 ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot); 2701 2702 *ts = ktime_to_timespec64(t); 2703 } 2704 EXPORT_SYMBOL_GPL(getboottime64); 2705 2706 void ktime_get_coarse_real_ts64(struct timespec64 *ts) 2707 { 2708 struct timekeeper *tk = &tk_core.timekeeper; 2709 unsigned int seq; 2710 2711 do { 2712 seq = read_seqcount_begin(&tk_core.seq); 2713 2714 *ts = tk_xtime_coarse(tk); 2715 } while (read_seqcount_retry(&tk_core.seq, seq)); 2716 } 2717 EXPORT_SYMBOL(ktime_get_coarse_real_ts64); 2718 2719 /** 2720 * ktime_get_coarse_real_ts64_mg - return latter of coarse grained time or floor 2721 * @ts: timespec64 to be filled 2722 * 2723 * Fetch the global mg_floor value, convert it to realtime and compare it 2724 * to the current coarse-grained time. Fill @ts with whichever is 2725 * latest. Note that this is a filesystem-specific interface and should be 2726 * avoided outside of that context. 2727 */ 2728 void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts) 2729 { 2730 struct timekeeper *tk = &tk_core.timekeeper; 2731 u64 floor = atomic64_read(&mg_floor); 2732 ktime_t f_real, offset, coarse; 2733 unsigned int seq; 2734 2735 do { 2736 seq = read_seqcount_begin(&tk_core.seq); 2737 *ts = tk_xtime_coarse(tk); 2738 offset = tk_core.timekeeper.offs_real; 2739 } while (read_seqcount_retry(&tk_core.seq, seq)); 2740 2741 coarse = timespec64_to_ktime(*ts); 2742 f_real = ktime_add(floor, offset); 2743 if (ktime_after(f_real, coarse)) 2744 *ts = ktime_to_timespec64(f_real); 2745 } 2746 2747 /** 2748 * ktime_get_real_ts64_mg - attempt to update floor value and return result 2749 * @ts: pointer to the timespec to be set 2750 * 2751 * Get a monotonic fine-grained time value and attempt to swap it into 2752 * mg_floor. If that succeeds then accept the new floor value. If it fails 2753 * then another task raced in during the interim time and updated the 2754 * floor. Since any update to the floor must be later than the previous 2755 * floor, either outcome is acceptable. 2756 * 2757 * Typically this will be called after calling ktime_get_coarse_real_ts64_mg(), 2758 * and determining that the resulting coarse-grained timestamp did not effect 2759 * a change in ctime. Any more recent floor value would effect a change to 2760 * ctime, so there is no need to retry the atomic64_try_cmpxchg() on failure. 2761 * 2762 * @ts will be filled with the latest floor value, regardless of the outcome of 2763 * the cmpxchg. Note that this is a filesystem specific interface and should be 2764 * avoided outside of that context. 2765 */ 2766 void ktime_get_real_ts64_mg(struct timespec64 *ts) 2767 { 2768 struct timekeeper *tk = &tk_core.timekeeper; 2769 ktime_t old = atomic64_read(&mg_floor); 2770 ktime_t offset, mono; 2771 unsigned int seq; 2772 u64 nsecs; 2773 2774 do { 2775 seq = read_seqcount_begin(&tk_core.seq); 2776 2777 ts->tv_sec = tk->xtime_sec; 2778 mono = tk->tkr_mono.base; 2779 nsecs = timekeeping_get_ns(&tk->tkr_mono); 2780 offset = tk_core.timekeeper.offs_real; 2781 } while (read_seqcount_retry(&tk_core.seq, seq)); 2782 2783 mono = ktime_add_ns(mono, nsecs); 2784 2785 /* 2786 * Attempt to update the floor with the new time value. As any 2787 * update must be later then the existing floor, and would effect 2788 * a change to ctime from the perspective of the current task, 2789 * accept the resulting floor value regardless of the outcome of 2790 * the swap. 2791 */ 2792 if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) { 2793 ts->tv_nsec = 0; 2794 timespec64_add_ns(ts, nsecs); 2795 timekeeping_inc_mg_floor_swaps(); 2796 } else { 2797 /* 2798 * Another task changed mg_floor since "old" was fetched. 2799 * "old" has been updated with the latest value of "mg_floor". 2800 * That value is newer than the previous floor value, which 2801 * is enough to effect a change to ctime. Accept it. 2802 */ 2803 *ts = ktime_to_timespec64(ktime_add(old, offset)); 2804 } 2805 } 2806 2807 void ktime_get_coarse_ts64(struct timespec64 *ts) 2808 { 2809 struct timekeeper *tk = &tk_core.timekeeper; 2810 struct timespec64 now, mono; 2811 unsigned int seq; 2812 2813 do { 2814 seq = read_seqcount_begin(&tk_core.seq); 2815 2816 now = tk_xtime_coarse(tk); 2817 mono = tk->wall_to_monotonic; 2818 } while (read_seqcount_retry(&tk_core.seq, seq)); 2819 2820 set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec, 2821 now.tv_nsec + mono.tv_nsec); 2822 } 2823 EXPORT_SYMBOL(ktime_get_coarse_ts64); 2824 2825 /* 2826 * Must hold jiffies_lock 2827 */ 2828 void do_timer(unsigned long ticks) 2829 { 2830 jiffies_64 += ticks; 2831 calc_global_load(); 2832 } 2833 2834 /** 2835 * ktime_get_update_offsets_now - hrtimer helper 2836 * @cwsseq: pointer to check and store the clock was set sequence number 2837 * @offs_real: pointer to storage for monotonic -> realtime offset 2838 * @offs_boot: pointer to storage for monotonic -> boottime offset 2839 * @offs_tai: pointer to storage for monotonic -> clock tai offset 2840 * 2841 * Returns current monotonic time and updates the offsets if the 2842 * sequence number in @cwsseq and timekeeper.clock_was_set_seq are 2843 * different. 2844 * 2845 * Called from hrtimer_interrupt() or retrigger_next_event() 2846 */ 2847 ktime_t ktime_get_update_offsets_now(u32 *cwsseq, ktime_t *offs_real, 2848 ktime_t *offs_boot, ktime_t *offs_tai) 2849 { 2850 struct timekeeper *tk = &tk_core.timekeeper; 2851 unsigned int seq; 2852 ktime_t base; 2853 u64 nsecs; 2854 2855 do { 2856 seq = read_seqcount_begin(&tk_core.seq); 2857 2858 base = tk->tkr_mono.base; 2859 nsecs = timekeeping_get_ns(&tk->tkr_mono); 2860 base = ktime_add_ns(base, nsecs); 2861 2862 if (*cwsseq != tk->clock_was_set_seq) { 2863 *cwsseq = tk->clock_was_set_seq; 2864 *offs_real = tk->offs_real; 2865 *offs_boot = tk->offs_boot; 2866 *offs_tai = tk->offs_tai; 2867 } 2868 2869 /* Handle leapsecond insertion adjustments */ 2870 if (unlikely(base >= tk->next_leap_ktime)) 2871 *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0)); 2872 2873 } while (read_seqcount_retry(&tk_core.seq, seq)); 2874 2875 return base; 2876 } 2877 2878 /* 2879 * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex 2880 */ 2881 static int timekeeping_validate_timex(const struct __kernel_timex *txc, bool aux_clock) 2882 { 2883 if (txc->modes & ADJ_ADJTIME) { 2884 /* singleshot must not be used with any other mode bits */ 2885 if (!(txc->modes & ADJ_OFFSET_SINGLESHOT)) 2886 return -EINVAL; 2887 if (!(txc->modes & ADJ_OFFSET_READONLY) && 2888 !capable(CAP_SYS_TIME)) 2889 return -EPERM; 2890 } else { 2891 /* In order to modify anything, you gotta be super-user! */ 2892 if (txc->modes && !capable(CAP_SYS_TIME)) 2893 return -EPERM; 2894 /* 2895 * if the quartz is off by more than 10% then 2896 * something is VERY wrong! 2897 */ 2898 if (txc->modes & ADJ_TICK && 2899 (txc->tick < 900000/USER_HZ || 2900 txc->tick > 1100000/USER_HZ)) 2901 return -EINVAL; 2902 } 2903 2904 if (txc->modes & ADJ_SETOFFSET) { 2905 /* In order to inject time, you gotta be super-user! */ 2906 if (!capable(CAP_SYS_TIME)) 2907 return -EPERM; 2908 2909 /* 2910 * Validate if a timespec/timeval used to inject a time 2911 * offset is valid. Offsets can be positive or negative, so 2912 * we don't check tv_sec. The value of the timeval/timespec 2913 * is the sum of its fields,but *NOTE*: 2914 * The field tv_usec/tv_nsec must always be non-negative and 2915 * we can't have more nanoseconds/microseconds than a second. 2916 */ 2917 if (txc->time.tv_usec < 0) 2918 return -EINVAL; 2919 2920 if (txc->modes & ADJ_NANO) { 2921 if (txc->time.tv_usec >= NSEC_PER_SEC) 2922 return -EINVAL; 2923 } else { 2924 if (txc->time.tv_usec >= USEC_PER_SEC) 2925 return -EINVAL; 2926 } 2927 } 2928 2929 /* 2930 * Check for potential multiplication overflows that can 2931 * only happen on 64-bit systems: 2932 */ 2933 if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) { 2934 if (LLONG_MIN / PPM_SCALE > txc->freq) 2935 return -EINVAL; 2936 if (LLONG_MAX / PPM_SCALE < txc->freq) 2937 return -EINVAL; 2938 } 2939 2940 if (aux_clock) { 2941 /* Auxiliary clocks are similar to TAI and do not have leap seconds */ 2942 if (txc->modes & ADJ_STATUS && 2943 txc->status & (STA_INS | STA_DEL)) 2944 return -EINVAL; 2945 2946 /* No TAI offset setting */ 2947 if (txc->modes & ADJ_TAI) 2948 return -EINVAL; 2949 2950 /* No PPS support either */ 2951 if (txc->modes & ADJ_STATUS && 2952 txc->status & (STA_PPSFREQ | STA_PPSTIME)) 2953 return -EINVAL; 2954 } 2955 2956 return 0; 2957 } 2958 2959 /** 2960 * random_get_entropy_fallback - Returns the raw clock source value, 2961 * used by random.c for platforms with no valid random_get_entropy(). 2962 */ 2963 unsigned long random_get_entropy_fallback(void) 2964 { 2965 struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono; 2966 struct clocksource *clock = READ_ONCE(tkr->clock); 2967 2968 if (unlikely(timekeeping_suspended || !clock)) 2969 return 0; 2970 return clock->read(clock); 2971 } 2972 EXPORT_SYMBOL_GPL(random_get_entropy_fallback); 2973 2974 struct adjtimex_result { 2975 struct audit_ntp_data ad; 2976 struct timespec64 delta; 2977 bool clock_set; 2978 }; 2979 2980 static int __do_adjtimex(struct tk_data *tkd, struct __kernel_timex *txc, 2981 struct adjtimex_result *result) 2982 { 2983 struct timekeeper *tks = &tkd->shadow_timekeeper; 2984 bool aux_clock = !timekeeper_is_core_tk(tks); 2985 struct timespec64 ts; 2986 s32 orig_tai, tai; 2987 int ret; 2988 2989 /* Validate the data before disabling interrupts */ 2990 ret = timekeeping_validate_timex(txc, aux_clock); 2991 if (ret) 2992 return ret; 2993 add_device_randomness(txc, sizeof(*txc)); 2994 2995 if (!aux_clock) { 2996 ktime_get_real_ts64(&ts); 2997 } else { 2998 if (!tk_get_aux_ts64(tkd->timekeeper.id, &ts)) 2999 return -ENODEV; 3000 } 3001 3002 add_device_randomness(&ts, sizeof(ts)); 3003 3004 guard(raw_spinlock_irqsave)(&tkd->lock); 3005 3006 if (!tks->clock_valid) 3007 return -ENODEV; 3008 3009 if (txc->modes & ADJ_SETOFFSET) { 3010 result->delta.tv_sec = txc->time.tv_sec; 3011 result->delta.tv_nsec = txc->time.tv_usec; 3012 if (!(txc->modes & ADJ_NANO)) 3013 result->delta.tv_nsec *= 1000; 3014 ret = __timekeeping_inject_offset(tkd, &result->delta); 3015 if (ret) 3016 return ret; 3017 result->clock_set = true; 3018 } 3019 3020 orig_tai = tai = tks->tai_offset; 3021 ret = ntp_adjtimex(tks->id, txc, &ts, &tai, &result->ad); 3022 3023 if (tai != orig_tai) { 3024 __timekeeping_set_tai_offset(tks, tai); 3025 timekeeping_update_from_shadow(tkd, TK_CLOCK_WAS_SET); 3026 result->clock_set = true; 3027 } else { 3028 tk_update_leap_state_all(tkd); 3029 } 3030 3031 /* Update the multiplier immediately if frequency was set directly */ 3032 if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK)) 3033 result->clock_set |= __timekeeping_advance(tkd, TK_ADV_FREQ); 3034 3035 return ret; 3036 } 3037 3038 /** 3039 * do_adjtimex() - Accessor function to NTP __do_adjtimex function 3040 * @txc: Pointer to kernel_timex structure containing NTP parameters 3041 */ 3042 int do_adjtimex(struct __kernel_timex *txc) 3043 { 3044 struct adjtimex_result result = { }; 3045 int ret; 3046 3047 ret = __do_adjtimex(&tk_core, txc, &result); 3048 if (ret < 0) 3049 return ret; 3050 3051 if (txc->modes & ADJ_SETOFFSET) 3052 audit_tk_injoffset(result.delta); 3053 3054 audit_ntp_log(&result.ad); 3055 3056 if (result.clock_set) 3057 clock_was_set(CLOCK_SET_WALL); 3058 3059 ntp_notify_cmos_timer(result.delta.tv_sec != 0); 3060 3061 return ret; 3062 } 3063 3064 /* 3065 * Invoked from NTP with the time keeper lock held, so lockless access is 3066 * fine. 3067 */ 3068 long ktime_get_ntp_seconds(unsigned int id) 3069 { 3070 return timekeeper_data[id].timekeeper.xtime_sec; 3071 } 3072 3073 #ifdef CONFIG_NTP_PPS 3074 /** 3075 * hardpps() - Accessor function to NTP __hardpps function 3076 * @phase_ts: Pointer to timespec64 structure representing phase timestamp 3077 * @raw_ts: Pointer to timespec64 structure representing raw timestamp 3078 */ 3079 void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts) 3080 { 3081 guard(raw_spinlock_irqsave)(&tk_core.lock); 3082 __hardpps(phase_ts, raw_ts); 3083 } 3084 EXPORT_SYMBOL(hardpps); 3085 #endif /* CONFIG_NTP_PPS */ 3086 3087 #ifdef CONFIG_POSIX_AUX_CLOCKS 3088 #include "posix-timers.h" 3089 3090 /* 3091 * Bitmap for the activated auxiliary timekeepers to allow lockless quick 3092 * checks in the hot paths without touching extra cache lines. If set, then 3093 * the state of the corresponding timekeeper has to be re-checked under 3094 * timekeeper::lock. 3095 */ 3096 static unsigned long aux_timekeepers; 3097 3098 static inline unsigned int clockid_to_tkid(unsigned int id) 3099 { 3100 return TIMEKEEPER_AUX_FIRST + id - CLOCK_AUX; 3101 } 3102 3103 static inline struct tk_data *aux_get_tk_data(clockid_t id) 3104 { 3105 if (!clockid_is_aux_clock(id)) 3106 return NULL; 3107 return &timekeeper_data[clockid_to_tkid(id)]; 3108 } 3109 3110 /* Invoked from timekeeping after a clocksource change */ 3111 static void tk_aux_update_clocksource(void) 3112 { 3113 unsigned long active = READ_ONCE(aux_timekeepers); 3114 unsigned int id; 3115 3116 for_each_set_bit(id, &active, BITS_PER_LONG) { 3117 struct tk_data *tkd = &timekeeper_data[id + TIMEKEEPER_AUX_FIRST]; 3118 struct timekeeper *tks = &tkd->shadow_timekeeper; 3119 3120 guard(raw_spinlock_irqsave)(&tkd->lock); 3121 if (!tks->clock_valid) 3122 continue; 3123 3124 timekeeping_forward_now(tks); 3125 tk_setup_internals(tks, tk_core.timekeeper.tkr_raw.clock); 3126 timekeeping_update_from_shadow(tkd, TK_UPDATE_ALL); 3127 } 3128 } 3129 3130 static void tk_aux_advance(void) 3131 { 3132 unsigned long active = READ_ONCE(aux_timekeepers); 3133 unsigned int id; 3134 3135 /* Lockless quick check to avoid extra cache lines */ 3136 for_each_set_bit(id, &active, BITS_PER_LONG) { 3137 struct tk_data *aux_tkd = &timekeeper_data[id + TIMEKEEPER_AUX_FIRST]; 3138 3139 guard(raw_spinlock)(&aux_tkd->lock); 3140 if (aux_tkd->shadow_timekeeper.clock_valid) 3141 __timekeeping_advance(aux_tkd, TK_ADV_TICK); 3142 } 3143 } 3144 3145 /** 3146 * ktime_get_aux - Get time for a AUX clock 3147 * @id: ID of the clock to read (CLOCK_AUX...) 3148 * @kt: Pointer to ktime_t to store the time stamp 3149 * 3150 * Returns: True if the timestamp is valid, false otherwise 3151 */ 3152 bool ktime_get_aux(clockid_t id, ktime_t *kt) 3153 { 3154 struct tk_data *aux_tkd = aux_get_tk_data(id); 3155 struct timekeeper *aux_tk; 3156 unsigned int seq; 3157 ktime_t base; 3158 u64 nsecs; 3159 3160 WARN_ON(timekeeping_suspended); 3161 3162 if (!aux_tkd) 3163 return false; 3164 3165 aux_tk = &aux_tkd->timekeeper; 3166 do { 3167 seq = read_seqcount_begin(&aux_tkd->seq); 3168 if (!aux_tk->clock_valid) 3169 return false; 3170 3171 base = ktime_add(aux_tk->tkr_mono.base, aux_tk->offs_aux); 3172 nsecs = timekeeping_get_ns(&aux_tk->tkr_mono); 3173 } while (read_seqcount_retry(&aux_tkd->seq, seq)); 3174 3175 *kt = ktime_add_ns(base, nsecs); 3176 return true; 3177 } 3178 EXPORT_SYMBOL_GPL(ktime_get_aux); 3179 3180 /** 3181 * ktime_get_aux_ts64 - Get time for a AUX clock 3182 * @id: ID of the clock to read (CLOCK_AUX...) 3183 * @ts: Pointer to timespec64 to store the time stamp 3184 * 3185 * Returns: True if the timestamp is valid, false otherwise 3186 */ 3187 bool ktime_get_aux_ts64(clockid_t id, struct timespec64 *ts) 3188 { 3189 ktime_t now; 3190 3191 if (!ktime_get_aux(id, &now)) 3192 return false; 3193 *ts = ktime_to_timespec64(now); 3194 return true; 3195 } 3196 EXPORT_SYMBOL_GPL(ktime_get_aux_ts64); 3197 3198 static int aux_get_res(clockid_t id, struct timespec64 *tp) 3199 { 3200 if (!clockid_is_aux_clock(id)) 3201 return -ENODEV; 3202 3203 tp->tv_sec = aux_clock_resolution_ns() / NSEC_PER_SEC; 3204 tp->tv_nsec = aux_clock_resolution_ns() % NSEC_PER_SEC; 3205 return 0; 3206 } 3207 3208 static int aux_get_timespec(clockid_t id, struct timespec64 *tp) 3209 { 3210 return ktime_get_aux_ts64(id, tp) ? 0 : -ENODEV; 3211 } 3212 3213 static int aux_clock_set(const clockid_t id, const struct timespec64 *tnew) 3214 { 3215 struct tk_data *aux_tkd = aux_get_tk_data(id); 3216 struct timekeeper *aux_tks; 3217 ktime_t tnow, nsecs; 3218 3219 if (!timespec64_valid_settod(tnew)) 3220 return -EINVAL; 3221 if (!aux_tkd) 3222 return -ENODEV; 3223 3224 aux_tks = &aux_tkd->shadow_timekeeper; 3225 3226 guard(raw_spinlock_irq)(&aux_tkd->lock); 3227 if (!aux_tks->clock_valid) 3228 return -ENODEV; 3229 3230 /* Forward the timekeeper base time */ 3231 timekeeping_forward_now(aux_tks); 3232 /* 3233 * Get the updated base time. tkr_mono.base has not been 3234 * updated yet, so do that first. That makes the update 3235 * in timekeeping_update_from_shadow() redundant, but 3236 * that's harmless. After that @tnow can be calculated 3237 * by using tkr_mono::cycle_last, which has been set 3238 * by timekeeping_forward_now(). 3239 */ 3240 tk_update_ktime_data(aux_tks); 3241 nsecs = timekeeping_cycles_to_ns(&aux_tks->tkr_mono, aux_tks->tkr_mono.cycle_last); 3242 tnow = ktime_add(aux_tks->tkr_mono.base, nsecs); 3243 3244 /* 3245 * Calculate the new AUX offset as delta to @tnow ("monotonic"). 3246 * That avoids all the tk::xtime back and forth conversions as 3247 * xtime ("realtime") is not applicable for auxiliary clocks and 3248 * kept in sync with "monotonic". 3249 */ 3250 tk_update_aux_offs(aux_tks, ktime_sub(timespec64_to_ktime(*tnew), tnow)); 3251 3252 timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL); 3253 return 0; 3254 } 3255 3256 static int aux_clock_adj(const clockid_t id, struct __kernel_timex *txc) 3257 { 3258 struct tk_data *aux_tkd = aux_get_tk_data(id); 3259 struct adjtimex_result result = { }; 3260 3261 if (!aux_tkd) 3262 return -ENODEV; 3263 3264 /* 3265 * @result is ignored for now as there are neither hrtimers nor a 3266 * RTC related to auxiliary clocks for now. 3267 */ 3268 return __do_adjtimex(aux_tkd, txc, &result); 3269 } 3270 3271 const struct k_clock clock_aux = { 3272 .clock_getres = aux_get_res, 3273 .clock_get_timespec = aux_get_timespec, 3274 .clock_set = aux_clock_set, 3275 .clock_adj = aux_clock_adj, 3276 }; 3277 3278 static void aux_clock_enable(clockid_t id) 3279 { 3280 struct tk_read_base *tkr_raw = &tk_core.timekeeper.tkr_raw; 3281 struct tk_data *aux_tkd = aux_get_tk_data(id); 3282 struct timekeeper *aux_tks = &aux_tkd->shadow_timekeeper; 3283 3284 /* Prevent the core timekeeper from changing. */ 3285 guard(raw_spinlock_irq)(&tk_core.lock); 3286 3287 /* 3288 * Setup the auxiliary clock assuming that the raw core timekeeper 3289 * clock frequency conversion is close enough. Userspace has to 3290 * adjust for the deviation via clock_adjtime(2). 3291 */ 3292 guard(raw_spinlock_nested)(&aux_tkd->lock); 3293 3294 /* Remove leftovers of a previous registration */ 3295 memset(aux_tks, 0, sizeof(*aux_tks)); 3296 /* Restore the timekeeper id */ 3297 aux_tks->id = aux_tkd->timekeeper.id; 3298 /* Setup the timekeeper based on the current system clocksource */ 3299 tk_setup_internals(aux_tks, tkr_raw->clock); 3300 3301 /* Mark it valid and set it live */ 3302 aux_tks->clock_valid = true; 3303 timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL); 3304 } 3305 3306 static void aux_clock_disable(clockid_t id) 3307 { 3308 struct tk_data *aux_tkd = aux_get_tk_data(id); 3309 3310 guard(raw_spinlock_irq)(&aux_tkd->lock); 3311 aux_tkd->shadow_timekeeper.clock_valid = false; 3312 timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL); 3313 } 3314 3315 static DEFINE_MUTEX(aux_clock_mutex); 3316 3317 static ssize_t aux_clock_enable_store(struct kobject *kobj, struct kobj_attribute *attr, 3318 const char *buf, size_t count) 3319 { 3320 /* Lazy atoi() as name is "0..7" */ 3321 int id = kobj->name[0] & 0x7; 3322 bool enable; 3323 3324 if (!capable(CAP_SYS_TIME)) 3325 return -EPERM; 3326 3327 if (kstrtobool(buf, &enable) < 0) 3328 return -EINVAL; 3329 3330 guard(mutex)(&aux_clock_mutex); 3331 if (enable == test_bit(id, &aux_timekeepers)) 3332 return count; 3333 3334 if (enable) { 3335 aux_clock_enable(CLOCK_AUX + id); 3336 set_bit(id, &aux_timekeepers); 3337 } else { 3338 aux_clock_disable(CLOCK_AUX + id); 3339 clear_bit(id, &aux_timekeepers); 3340 } 3341 return count; 3342 } 3343 3344 static ssize_t aux_clock_enable_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) 3345 { 3346 unsigned long active = READ_ONCE(aux_timekeepers); 3347 /* Lazy atoi() as name is "0..7" */ 3348 int id = kobj->name[0] & 0x7; 3349 3350 return sysfs_emit(buf, "%d\n", test_bit(id, &active)); 3351 } 3352 3353 static struct kobj_attribute aux_clock_enable_attr = __ATTR_RW(aux_clock_enable); 3354 3355 static struct attribute *aux_clock_enable_attrs[] = { 3356 &aux_clock_enable_attr.attr, 3357 NULL 3358 }; 3359 3360 static const struct attribute_group aux_clock_enable_attr_group = { 3361 .attrs = aux_clock_enable_attrs, 3362 }; 3363 3364 static int __init tk_aux_sysfs_init(void) 3365 { 3366 struct kobject *auxo, *tko = kobject_create_and_add("time", kernel_kobj); 3367 struct kobject *clks[MAX_AUX_CLOCKS]; 3368 int ret = -ENOMEM; 3369 int i; 3370 3371 if (!tko) 3372 return ret; 3373 3374 auxo = kobject_create_and_add("aux_clocks", tko); 3375 if (!auxo) 3376 goto err_clean; 3377 3378 for (i = 0; i < MAX_AUX_CLOCKS; i++) { 3379 char id[2] = { [0] = '0' + i, }; 3380 clks[i] = kobject_create_and_add(id, auxo); 3381 3382 if (!clks[i]) { 3383 ret = -ENOMEM; 3384 goto err_clks; 3385 } 3386 3387 ret = sysfs_create_group(clks[i], &aux_clock_enable_attr_group); 3388 if (ret) 3389 goto err_clk; 3390 } 3391 return 0; 3392 3393 err_clk: 3394 kobject_put(clks[i]); 3395 err_clks: 3396 while (--i >= 0) { 3397 sysfs_remove_group(clks[i], &aux_clock_enable_attr_group); 3398 kobject_put(clks[i]); 3399 } 3400 err_clean: 3401 kobject_put(auxo); 3402 kobject_put(tko); 3403 return ret; 3404 } 3405 late_initcall(tk_aux_sysfs_init); 3406 3407 static __init void tk_aux_setup(void) 3408 { 3409 for (int i = TIMEKEEPER_AUX_FIRST; i <= TIMEKEEPER_AUX_LAST; i++) 3410 tkd_basic_setup(&timekeeper_data[i], i, false); 3411 } 3412 #endif /* CONFIG_POSIX_AUX_CLOCKS */ 3413