Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * sched_clock() for unstable CPU clocks
0004  *
0005  *  Copyright (C) 2008 Red Hat, Inc., Peter Zijlstra
0006  *
0007  *  Updates and enhancements:
0008  *    Copyright (C) 2008 Red Hat, Inc. Steven Rostedt <srostedt@redhat.com>
0009  *
0010  * Based on code by:
0011  *   Ingo Molnar <mingo@redhat.com>
0012  *   Guillaume Chazarain <guichaz@gmail.com>
0013  *
0014  *
0015  * What this file implements:
0016  *
0017  * cpu_clock(i) provides a fast (execution time) high resolution
0018  * clock with bounded drift between CPUs. The value of cpu_clock(i)
0019  * is monotonic for constant i. The timestamp returned is in nanoseconds.
0020  *
0021  * ######################### BIG FAT WARNING ##########################
0022  * # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
0023  * # go backwards !!                                                  #
0024  * ####################################################################
0025  *
0026  * There is no strict promise about the base, although it tends to start
0027  * at 0 on boot (but people really shouldn't rely on that).
0028  *
0029  * cpu_clock(i)       -- can be used from any context, including NMI.
0030  * local_clock()      -- is cpu_clock() on the current CPU.
0031  *
0032  * sched_clock_cpu(i)
0033  *
0034  * How it is implemented:
0035  *
0036  * The implementation either uses sched_clock() when
0037  * !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK, which means in that case the
0038  * sched_clock() is assumed to provide these properties (mostly it means
0039  * the architecture provides a globally synchronized highres time source).
0040  *
0041  * Otherwise it tries to create a semi stable clock from a mixture of other
0042  * clocks, including:
0043  *
0044  *  - GTOD (clock monotonic)
0045  *  - sched_clock()
0046  *  - explicit idle events
0047  *
0048  * We use GTOD as base and use sched_clock() deltas to improve resolution. The
0049  * deltas are filtered to provide monotonicity and keeping it within an
0050  * expected window.
0051  *
0052  * Furthermore, explicit sleep and wakeup hooks allow us to account for time
0053  * that is otherwise invisible (TSC gets stopped).
0054  *
0055  */
0056 
0057 /*
0058  * Scheduler clock - returns current time in nanosec units.
0059  * This is default implementation.
0060  * Architectures and sub-architectures can override this.
0061  */
0062 notrace unsigned long long __weak sched_clock(void)
0063 {
0064     return (unsigned long long)(jiffies - INITIAL_JIFFIES)
0065                     * (NSEC_PER_SEC / HZ);
0066 }
0067 EXPORT_SYMBOL_GPL(sched_clock);
0068 
0069 static DEFINE_STATIC_KEY_FALSE(sched_clock_running);
0070 
0071 #ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
0072 /*
0073  * We must start with !__sched_clock_stable because the unstable -> stable
0074  * transition is accurate, while the stable -> unstable transition is not.
0075  *
0076  * Similarly we start with __sched_clock_stable_early, thereby assuming we
0077  * will become stable, such that there's only a single 1 -> 0 transition.
0078  */
0079 static DEFINE_STATIC_KEY_FALSE(__sched_clock_stable);
0080 static int __sched_clock_stable_early = 1;
0081 
0082 /*
0083  * We want: ktime_get_ns() + __gtod_offset == sched_clock() + __sched_clock_offset
0084  */
0085 __read_mostly u64 __sched_clock_offset;
0086 static __read_mostly u64 __gtod_offset;
0087 
0088 struct sched_clock_data {
0089     u64         tick_raw;
0090     u64         tick_gtod;
0091     u64         clock;
0092 };
0093 
0094 static DEFINE_PER_CPU_SHARED_ALIGNED(struct sched_clock_data, sched_clock_data);
0095 
0096 notrace static inline struct sched_clock_data *this_scd(void)
0097 {
0098     return this_cpu_ptr(&sched_clock_data);
0099 }
0100 
0101 notrace static inline struct sched_clock_data *cpu_sdc(int cpu)
0102 {
0103     return &per_cpu(sched_clock_data, cpu);
0104 }
0105 
0106 notrace int sched_clock_stable(void)
0107 {
0108     return static_branch_likely(&__sched_clock_stable);
0109 }
0110 
0111 notrace static void __scd_stamp(struct sched_clock_data *scd)
0112 {
0113     scd->tick_gtod = ktime_get_ns();
0114     scd->tick_raw = sched_clock();
0115 }
0116 
0117 notrace static void __set_sched_clock_stable(void)
0118 {
0119     struct sched_clock_data *scd;
0120 
0121     /*
0122      * Since we're still unstable and the tick is already running, we have
0123      * to disable IRQs in order to get a consistent scd->tick* reading.
0124      */
0125     local_irq_disable();
0126     scd = this_scd();
0127     /*
0128      * Attempt to make the (initial) unstable->stable transition continuous.
0129      */
0130     __sched_clock_offset = (scd->tick_gtod + __gtod_offset) - (scd->tick_raw);
0131     local_irq_enable();
0132 
0133     printk(KERN_INFO "sched_clock: Marking stable (%lld, %lld)->(%lld, %lld)\n",
0134             scd->tick_gtod, __gtod_offset,
0135             scd->tick_raw,  __sched_clock_offset);
0136 
0137     static_branch_enable(&__sched_clock_stable);
0138     tick_dep_clear(TICK_DEP_BIT_CLOCK_UNSTABLE);
0139 }
0140 
0141 /*
0142  * If we ever get here, we're screwed, because we found out -- typically after
0143  * the fact -- that TSC wasn't good. This means all our clocksources (including
0144  * ktime) could have reported wrong values.
0145  *
0146  * What we do here is an attempt to fix up and continue sort of where we left
0147  * off in a coherent manner.
0148  *
0149  * The only way to fully avoid random clock jumps is to boot with:
0150  * "tsc=unstable".
0151  */
0152 notrace static void __sched_clock_work(struct work_struct *work)
0153 {
0154     struct sched_clock_data *scd;
0155     int cpu;
0156 
0157     /* take a current timestamp and set 'now' */
0158     preempt_disable();
0159     scd = this_scd();
0160     __scd_stamp(scd);
0161     scd->clock = scd->tick_gtod + __gtod_offset;
0162     preempt_enable();
0163 
0164     /* clone to all CPUs */
0165     for_each_possible_cpu(cpu)
0166         per_cpu(sched_clock_data, cpu) = *scd;
0167 
0168     printk(KERN_WARNING "TSC found unstable after boot, most likely due to broken BIOS. Use 'tsc=unstable'.\n");
0169     printk(KERN_INFO "sched_clock: Marking unstable (%lld, %lld)<-(%lld, %lld)\n",
0170             scd->tick_gtod, __gtod_offset,
0171             scd->tick_raw,  __sched_clock_offset);
0172 
0173     static_branch_disable(&__sched_clock_stable);
0174 }
0175 
0176 static DECLARE_WORK(sched_clock_work, __sched_clock_work);
0177 
0178 notrace static void __clear_sched_clock_stable(void)
0179 {
0180     if (!sched_clock_stable())
0181         return;
0182 
0183     tick_dep_set(TICK_DEP_BIT_CLOCK_UNSTABLE);
0184     schedule_work(&sched_clock_work);
0185 }
0186 
0187 notrace void clear_sched_clock_stable(void)
0188 {
0189     __sched_clock_stable_early = 0;
0190 
0191     smp_mb(); /* matches sched_clock_init_late() */
0192 
0193     if (static_key_count(&sched_clock_running.key) == 2)
0194         __clear_sched_clock_stable();
0195 }
0196 
0197 notrace static void __sched_clock_gtod_offset(void)
0198 {
0199     struct sched_clock_data *scd = this_scd();
0200 
0201     __scd_stamp(scd);
0202     __gtod_offset = (scd->tick_raw + __sched_clock_offset) - scd->tick_gtod;
0203 }
0204 
0205 void __init sched_clock_init(void)
0206 {
0207     /*
0208      * Set __gtod_offset such that once we mark sched_clock_running,
0209      * sched_clock_tick() continues where sched_clock() left off.
0210      *
0211      * Even if TSC is buggered, we're still UP at this point so it
0212      * can't really be out of sync.
0213      */
0214     local_irq_disable();
0215     __sched_clock_gtod_offset();
0216     local_irq_enable();
0217 
0218     static_branch_inc(&sched_clock_running);
0219 }
0220 /*
0221  * We run this as late_initcall() such that it runs after all built-in drivers,
0222  * notably: acpi_processor and intel_idle, which can mark the TSC as unstable.
0223  */
0224 static int __init sched_clock_init_late(void)
0225 {
0226     static_branch_inc(&sched_clock_running);
0227     /*
0228      * Ensure that it is impossible to not do a static_key update.
0229      *
0230      * Either {set,clear}_sched_clock_stable() must see sched_clock_running
0231      * and do the update, or we must see their __sched_clock_stable_early
0232      * and do the update, or both.
0233      */
0234     smp_mb(); /* matches {set,clear}_sched_clock_stable() */
0235 
0236     if (__sched_clock_stable_early)
0237         __set_sched_clock_stable();
0238 
0239     return 0;
0240 }
0241 late_initcall(sched_clock_init_late);
0242 
0243 /*
0244  * min, max except they take wrapping into account
0245  */
0246 
0247 notrace static inline u64 wrap_min(u64 x, u64 y)
0248 {
0249     return (s64)(x - y) < 0 ? x : y;
0250 }
0251 
0252 notrace static inline u64 wrap_max(u64 x, u64 y)
0253 {
0254     return (s64)(x - y) > 0 ? x : y;
0255 }
0256 
0257 /*
0258  * update the percpu scd from the raw @now value
0259  *
0260  *  - filter out backward motion
0261  *  - use the GTOD tick value to create a window to filter crazy TSC values
0262  */
0263 notrace static u64 sched_clock_local(struct sched_clock_data *scd)
0264 {
0265     u64 now, clock, old_clock, min_clock, max_clock, gtod;
0266     s64 delta;
0267 
0268 again:
0269     now = sched_clock();
0270     delta = now - scd->tick_raw;
0271     if (unlikely(delta < 0))
0272         delta = 0;
0273 
0274     old_clock = scd->clock;
0275 
0276     /*
0277      * scd->clock = clamp(scd->tick_gtod + delta,
0278      *            max(scd->tick_gtod, scd->clock),
0279      *            scd->tick_gtod + TICK_NSEC);
0280      */
0281 
0282     gtod = scd->tick_gtod + __gtod_offset;
0283     clock = gtod + delta;
0284     min_clock = wrap_max(gtod, old_clock);
0285     max_clock = wrap_max(old_clock, gtod + TICK_NSEC);
0286 
0287     clock = wrap_max(clock, min_clock);
0288     clock = wrap_min(clock, max_clock);
0289 
0290     if (!try_cmpxchg64(&scd->clock, &old_clock, clock))
0291         goto again;
0292 
0293     return clock;
0294 }
0295 
0296 notrace static u64 sched_clock_remote(struct sched_clock_data *scd)
0297 {
0298     struct sched_clock_data *my_scd = this_scd();
0299     u64 this_clock, remote_clock;
0300     u64 *ptr, old_val, val;
0301 
0302 #if BITS_PER_LONG != 64
0303 again:
0304     /*
0305      * Careful here: The local and the remote clock values need to
0306      * be read out atomic as we need to compare the values and
0307      * then update either the local or the remote side. So the
0308      * cmpxchg64 below only protects one readout.
0309      *
0310      * We must reread via sched_clock_local() in the retry case on
0311      * 32-bit kernels as an NMI could use sched_clock_local() via the
0312      * tracer and hit between the readout of
0313      * the low 32-bit and the high 32-bit portion.
0314      */
0315     this_clock = sched_clock_local(my_scd);
0316     /*
0317      * We must enforce atomic readout on 32-bit, otherwise the
0318      * update on the remote CPU can hit inbetween the readout of
0319      * the low 32-bit and the high 32-bit portion.
0320      */
0321     remote_clock = cmpxchg64(&scd->clock, 0, 0);
0322 #else
0323     /*
0324      * On 64-bit kernels the read of [my]scd->clock is atomic versus the
0325      * update, so we can avoid the above 32-bit dance.
0326      */
0327     sched_clock_local(my_scd);
0328 again:
0329     this_clock = my_scd->clock;
0330     remote_clock = scd->clock;
0331 #endif
0332 
0333     /*
0334      * Use the opportunity that we have both locks
0335      * taken to couple the two clocks: we take the
0336      * larger time as the latest time for both
0337      * runqueues. (this creates monotonic movement)
0338      */
0339     if (likely((s64)(remote_clock - this_clock) < 0)) {
0340         ptr = &scd->clock;
0341         old_val = remote_clock;
0342         val = this_clock;
0343     } else {
0344         /*
0345          * Should be rare, but possible:
0346          */
0347         ptr = &my_scd->clock;
0348         old_val = this_clock;
0349         val = remote_clock;
0350     }
0351 
0352     if (!try_cmpxchg64(ptr, &old_val, val))
0353         goto again;
0354 
0355     return val;
0356 }
0357 
0358 /*
0359  * Similar to cpu_clock(), but requires local IRQs to be disabled.
0360  *
0361  * See cpu_clock().
0362  */
0363 notrace u64 sched_clock_cpu(int cpu)
0364 {
0365     struct sched_clock_data *scd;
0366     u64 clock;
0367 
0368     if (sched_clock_stable())
0369         return sched_clock() + __sched_clock_offset;
0370 
0371     if (!static_branch_likely(&sched_clock_running))
0372         return sched_clock();
0373 
0374     preempt_disable_notrace();
0375     scd = cpu_sdc(cpu);
0376 
0377     if (cpu != smp_processor_id())
0378         clock = sched_clock_remote(scd);
0379     else
0380         clock = sched_clock_local(scd);
0381     preempt_enable_notrace();
0382 
0383     return clock;
0384 }
0385 EXPORT_SYMBOL_GPL(sched_clock_cpu);
0386 
0387 notrace void sched_clock_tick(void)
0388 {
0389     struct sched_clock_data *scd;
0390 
0391     if (sched_clock_stable())
0392         return;
0393 
0394     if (!static_branch_likely(&sched_clock_running))
0395         return;
0396 
0397     lockdep_assert_irqs_disabled();
0398 
0399     scd = this_scd();
0400     __scd_stamp(scd);
0401     sched_clock_local(scd);
0402 }
0403 
0404 notrace void sched_clock_tick_stable(void)
0405 {
0406     if (!sched_clock_stable())
0407         return;
0408 
0409     /*
0410      * Called under watchdog_lock.
0411      *
0412      * The watchdog just found this TSC to (still) be stable, so now is a
0413      * good moment to update our __gtod_offset. Because once we find the
0414      * TSC to be unstable, any computation will be computing crap.
0415      */
0416     local_irq_disable();
0417     __sched_clock_gtod_offset();
0418     local_irq_enable();
0419 }
0420 
0421 /*
0422  * We are going deep-idle (irqs are disabled):
0423  */
0424 notrace void sched_clock_idle_sleep_event(void)
0425 {
0426     sched_clock_cpu(smp_processor_id());
0427 }
0428 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
0429 
0430 /*
0431  * We just idled; resync with ktime.
0432  */
0433 notrace void sched_clock_idle_wakeup_event(void)
0434 {
0435     unsigned long flags;
0436 
0437     if (sched_clock_stable())
0438         return;
0439 
0440     if (unlikely(timekeeping_suspended))
0441         return;
0442 
0443     local_irq_save(flags);
0444     sched_clock_tick();
0445     local_irq_restore(flags);
0446 }
0447 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
0448 
0449 #else /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
0450 
0451 void __init sched_clock_init(void)
0452 {
0453     static_branch_inc(&sched_clock_running);
0454     local_irq_disable();
0455     generic_sched_clock_init();
0456     local_irq_enable();
0457 }
0458 
0459 notrace u64 sched_clock_cpu(int cpu)
0460 {
0461     if (!static_branch_likely(&sched_clock_running))
0462         return 0;
0463 
0464     return sched_clock();
0465 }
0466 
0467 #endif /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
0468 
0469 /*
0470  * Running clock - returns the time that has elapsed while a guest has been
0471  * running.
0472  * On a guest this value should be local_clock minus the time the guest was
0473  * suspended by the hypervisor (for any reason).
0474  * On bare metal this function should return the same as local_clock.
0475  * Architectures and sub-architectures can override this.
0476  */
0477 notrace u64 __weak running_clock(void)
0478 {
0479     return local_clock();
0480 }