135728b82SThomas Gleixner // SPDX-License-Identifier: GPL-2.0
28524070bSjohn stultz /*
358c5fc2bSThomas Gleixner * Kernel timekeeping code and accessor functions. Based on code from
458c5fc2bSThomas Gleixner * timer.c, moved in commit 8524070b7982.
58524070bSjohn stultz */
6d7b4202eSJohn Stultz #include <linux/timekeeper_internal.h>
78524070bSjohn stultz #include <linux/module.h>
88524070bSjohn stultz #include <linux/interrupt.h>
98524070bSjohn stultz #include <linux/percpu.h>
108524070bSjohn stultz #include <linux/init.h>
118524070bSjohn stultz #include <linux/mm.h>
1238b8d208SIngo Molnar #include <linux/nmi.h>
13d43c36dcSAlexey Dobriyan #include <linux/sched.h>
144f17722cSIngo Molnar #include <linux/sched/loadavg.h>
153eca9937SPavel Tatashin #include <linux/sched/clock.h>
16e1a85b2cSRafael J. Wysocki #include <linux/syscore_ops.h>
178524070bSjohn stultz #include <linux/clocksource.h>
188524070bSjohn stultz #include <linux/jiffies.h>
198524070bSjohn stultz #include <linux/time.h>
201366992eSJason A. Donenfeld #include <linux/timex.h>
218524070bSjohn stultz #include <linux/tick.h>
2275c5158fSMartin Schwidefsky #include <linux/stop_machine.h>
23e0b306feSMarcelo Tosatti #include <linux/pvclock_gtod.h>
2452f5684cSGideon Israel Dsouza #include <linux/compiler.h>
252d87a067SOndrej Mosnacek #include <linux/audit.h>
26b8ac29b4SJason A. Donenfeld #include <linux/random.h>
278524070bSjohn stultz
28eb93e4d9SThomas Gleixner #include "tick-internal.h"
29aa6f9c59SJohn Stultz #include "ntp_internal.h"
305c83545fSColin Cross #include "timekeeping_internal.h"
31155ec602SMartin Schwidefsky
3204397fe9SDavid Vrabel #define TK_CLEAR_NTP (1 << 0)
3304397fe9SDavid Vrabel #define TK_MIRROR (1 << 1)
34780427f0SDavid Vrabel #define TK_CLOCK_WAS_SET (1 << 2)
3504397fe9SDavid Vrabel
36b061c7a5SMiroslav Lichvar enum timekeeping_adv_mode {
37b061c7a5SMiroslav Lichvar /* Update timekeeper when a tick has passed */
38b061c7a5SMiroslav Lichvar TK_ADV_TICK,
39b061c7a5SMiroslav Lichvar
40b061c7a5SMiroslav Lichvar /* Update timekeeper on a direct frequency change */
41b061c7a5SMiroslav Lichvar TK_ADV_FREQ
42b061c7a5SMiroslav Lichvar };
43b061c7a5SMiroslav Lichvar
44b923f124SLinus Torvalds DEFINE_RAW_SPINLOCK(timekeeper_lock);
45025e82bcSAhmed S. Darwish
463fdb14fdSThomas Gleixner /*
473fdb14fdSThomas Gleixner * The most important data for readout fits into a single 64 byte
483fdb14fdSThomas Gleixner * cache line.
493fdb14fdSThomas Gleixner */
503fdb14fdSThomas Gleixner static struct {
51025e82bcSAhmed S. Darwish seqcount_raw_spinlock_t seq;
523fdb14fdSThomas Gleixner struct timekeeper timekeeper;
53ce10a5b3SBart Van Assche } tk_core ____cacheline_aligned = {
54025e82bcSAhmed S. Darwish .seq = SEQCNT_RAW_SPINLOCK_ZERO(tk_core.seq, &timekeeper_lock),
55ce10a5b3SBart Van Assche };
563fdb14fdSThomas Gleixner
5748cdc135SThomas Gleixner static struct timekeeper shadow_timekeeper;
58155ec602SMartin Schwidefsky
5971419b30SThomas Gleixner /* flag for if timekeeping is suspended */
6071419b30SThomas Gleixner int __read_mostly timekeeping_suspended;
6171419b30SThomas Gleixner
624396e058SThomas Gleixner /**
634396e058SThomas Gleixner * struct tk_fast - NMI safe timekeeper
644396e058SThomas Gleixner * @seq: Sequence counter for protecting updates. The lowest bit
654396e058SThomas Gleixner * is the index for the tk_read_base array
664396e058SThomas Gleixner * @base: tk_read_base array. Access is indexed by the lowest bit of
674396e058SThomas Gleixner * @seq.
684396e058SThomas Gleixner *
694396e058SThomas Gleixner * See @update_fast_timekeeper() below.
704396e058SThomas Gleixner */
714396e058SThomas Gleixner struct tk_fast {
72249d0538SAhmed S. Darwish seqcount_latch_t seq;
734396e058SThomas Gleixner struct tk_read_base base[2];
744396e058SThomas Gleixner };
754396e058SThomas Gleixner
765df32107SPrarit Bhargava /* Suspend-time cycles value for halted fast timekeeper. */
775df32107SPrarit Bhargava static u64 cycles_at_suspend;
785df32107SPrarit Bhargava
dummy_clock_read(struct clocksource * cs)795df32107SPrarit Bhargava static u64 dummy_clock_read(struct clocksource *cs)
805df32107SPrarit Bhargava {
8171419b30SThomas Gleixner if (timekeeping_suspended)
825df32107SPrarit Bhargava return cycles_at_suspend;
8371419b30SThomas Gleixner return local_clock();
845df32107SPrarit Bhargava }
855df32107SPrarit Bhargava
865df32107SPrarit Bhargava static struct clocksource dummy_clock = {
875df32107SPrarit Bhargava .read = dummy_clock_read,
885df32107SPrarit Bhargava };
895df32107SPrarit Bhargava
9071419b30SThomas Gleixner /*
9171419b30SThomas Gleixner * Boot time initialization which allows local_clock() to be utilized
9271419b30SThomas Gleixner * during early boot when clocksources are not available. local_clock()
9371419b30SThomas Gleixner * returns nanoseconds already so no conversion is required, hence mult=1
9471419b30SThomas Gleixner * and shift=0. When the first proper clocksource is installed then
9571419b30SThomas Gleixner * the fast time keepers are updated with the correct values.
9671419b30SThomas Gleixner */
9771419b30SThomas Gleixner #define FAST_TK_INIT \
9871419b30SThomas Gleixner { \
9971419b30SThomas Gleixner .clock = &dummy_clock, \
10071419b30SThomas Gleixner .mask = CLOCKSOURCE_MASK(64), \
10171419b30SThomas Gleixner .mult = 1, \
10271419b30SThomas Gleixner .shift = 0, \
10371419b30SThomas Gleixner }
10471419b30SThomas Gleixner
1055df32107SPrarit Bhargava static struct tk_fast tk_fast_mono ____cacheline_aligned = {
106249d0538SAhmed S. Darwish .seq = SEQCNT_LATCH_ZERO(tk_fast_mono.seq),
10771419b30SThomas Gleixner .base[0] = FAST_TK_INIT,
10871419b30SThomas Gleixner .base[1] = FAST_TK_INIT,
1095df32107SPrarit Bhargava };
1105df32107SPrarit Bhargava
1115df32107SPrarit Bhargava static struct tk_fast tk_fast_raw ____cacheline_aligned = {
112249d0538SAhmed S. Darwish .seq = SEQCNT_LATCH_ZERO(tk_fast_raw.seq),
11371419b30SThomas Gleixner .base[0] = FAST_TK_INIT,
11471419b30SThomas Gleixner .base[1] = FAST_TK_INIT,
1155df32107SPrarit Bhargava };
1164396e058SThomas Gleixner
tk_normalize_xtime(struct timekeeper * tk)1171e75fa8bSJohn Stultz static inline void tk_normalize_xtime(struct timekeeper *tk)
1181e75fa8bSJohn Stultz {
119876e7881SPeter Zijlstra while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
120876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
1211e75fa8bSJohn Stultz tk->xtime_sec++;
1221e75fa8bSJohn Stultz }
123fc6eead7SJohn Stultz while (tk->tkr_raw.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_raw.shift)) {
124fc6eead7SJohn Stultz tk->tkr_raw.xtime_nsec -= (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
125fc6eead7SJohn Stultz tk->raw_sec++;
126fc6eead7SJohn Stultz }
1271e75fa8bSJohn Stultz }
1288fcce546SJohn Stultz
tk_xtime(const struct timekeeper * tk)129985e6950SOndrej Mosnacek static inline struct timespec64 tk_xtime(const struct timekeeper *tk)
130c905fae4SThomas Gleixner {
131c905fae4SThomas Gleixner struct timespec64 ts;
132c905fae4SThomas Gleixner
133c905fae4SThomas Gleixner ts.tv_sec = tk->xtime_sec;
134876e7881SPeter Zijlstra ts.tv_nsec = (long)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
135c905fae4SThomas Gleixner return ts;
136c905fae4SThomas Gleixner }
137c905fae4SThomas Gleixner
tk_set_xtime(struct timekeeper * tk,const struct timespec64 * ts)1387d489d15SJohn Stultz static void tk_set_xtime(struct timekeeper *tk, const struct timespec64 *ts)
1391e75fa8bSJohn Stultz {
1401e75fa8bSJohn Stultz tk->xtime_sec = ts->tv_sec;
141876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec = (u64)ts->tv_nsec << tk->tkr_mono.shift;
1421e75fa8bSJohn Stultz }
1431e75fa8bSJohn Stultz
tk_xtime_add(struct timekeeper * tk,const struct timespec64 * ts)1447d489d15SJohn Stultz static void tk_xtime_add(struct timekeeper *tk, const struct timespec64 *ts)
1451e75fa8bSJohn Stultz {
1461e75fa8bSJohn Stultz tk->xtime_sec += ts->tv_sec;
147876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec += (u64)ts->tv_nsec << tk->tkr_mono.shift;
148784ffcbbSJohn Stultz tk_normalize_xtime(tk);
1491e75fa8bSJohn Stultz }
1508fcce546SJohn Stultz
tk_set_wall_to_mono(struct timekeeper * tk,struct timespec64 wtm)1517d489d15SJohn Stultz static void tk_set_wall_to_mono(struct timekeeper *tk, struct timespec64 wtm)
1526d0ef903SJohn Stultz {
1537d489d15SJohn Stultz struct timespec64 tmp;
1546d0ef903SJohn Stultz
1556d0ef903SJohn Stultz /*
1566d0ef903SJohn Stultz * Verify consistency of: offset_real = -wall_to_monotonic
1576d0ef903SJohn Stultz * before modifying anything
1586d0ef903SJohn Stultz */
1597d489d15SJohn Stultz set_normalized_timespec64(&tmp, -tk->wall_to_monotonic.tv_sec,
1606d0ef903SJohn Stultz -tk->wall_to_monotonic.tv_nsec);
1612456e855SThomas Gleixner WARN_ON_ONCE(tk->offs_real != timespec64_to_ktime(tmp));
1626d0ef903SJohn Stultz tk->wall_to_monotonic = wtm;
1637d489d15SJohn Stultz set_normalized_timespec64(&tmp, -wtm.tv_sec, -wtm.tv_nsec);
1647d489d15SJohn Stultz tk->offs_real = timespec64_to_ktime(tmp);
16504005f60SJohn Stultz tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tk->tai_offset, 0));
1666d0ef903SJohn Stultz }
1676d0ef903SJohn Stultz
tk_update_sleep_time(struct timekeeper * tk,ktime_t delta)16847da70d3SThomas Gleixner static inline void tk_update_sleep_time(struct timekeeper *tk, ktime_t delta)
1696d0ef903SJohn Stultz {
170a3ed0e43SThomas Gleixner tk->offs_boot = ktime_add(tk->offs_boot, delta);
171b99328a6SThomas Gleixner /*
172b99328a6SThomas Gleixner * Timespec representation for VDSO update to avoid 64bit division
173b99328a6SThomas Gleixner * on every update.
174b99328a6SThomas Gleixner */
175b99328a6SThomas Gleixner tk->monotonic_to_boot = ktime_to_timespec64(tk->offs_boot);
1766d0ef903SJohn Stultz }
1776d0ef903SJohn Stultz
178ceea5e37SJohn Stultz /*
179ceea5e37SJohn Stultz * tk_clock_read - atomic clocksource read() helper
180ceea5e37SJohn Stultz *
181ceea5e37SJohn Stultz * This helper is necessary to use in the read paths because, while the
182025e82bcSAhmed S. Darwish * seqcount ensures we don't return a bad value while structures are updated,
183ceea5e37SJohn Stultz * it doesn't protect from potential crashes. There is the possibility that
184ceea5e37SJohn Stultz * the tkr's clocksource may change between the read reference, and the
185ceea5e37SJohn Stultz * clock reference passed to the read function. This can cause crashes if
186ceea5e37SJohn Stultz * the wrong clocksource is passed to the wrong read function.
187ceea5e37SJohn Stultz * This isn't necessary to use when holding the timekeeper_lock or doing
188ceea5e37SJohn Stultz * a read of the fast-timekeeper tkrs (which is protected by its own locking
189ceea5e37SJohn Stultz * and update logic).
190ceea5e37SJohn Stultz */
tk_clock_read(const struct tk_read_base * tkr)191985e6950SOndrej Mosnacek static inline u64 tk_clock_read(const struct tk_read_base *tkr)
192ceea5e37SJohn Stultz {
193ceea5e37SJohn Stultz struct clocksource *clock = READ_ONCE(tkr->clock);
194ceea5e37SJohn Stultz
195ceea5e37SJohn Stultz return clock->read(clock);
196ceea5e37SJohn Stultz }
197ceea5e37SJohn Stultz
1983c17ad19SJohn Stultz #ifdef CONFIG_DEBUG_TIMEKEEPING
1994ca22c26SJohn Stultz #define WARNING_FREQ (HZ*300) /* 5 minute rate-limiting */
2004ca22c26SJohn Stultz
timekeeping_check_update(struct timekeeper * tk,u64 offset)201a5a1d1c2SThomas Gleixner static void timekeeping_check_update(struct timekeeper *tk, u64 offset)
2023c17ad19SJohn Stultz {
2033c17ad19SJohn Stultz
204a5a1d1c2SThomas Gleixner u64 max_cycles = tk->tkr_mono.clock->max_cycles;
205876e7881SPeter Zijlstra const char *name = tk->tkr_mono.clock->name;
2063c17ad19SJohn Stultz
2073c17ad19SJohn Stultz if (offset > max_cycles) {
208a558cd02SJohn Stultz printk_deferred("WARNING: timekeeping: Cycle offset (%lld) is larger than allowed by the '%s' clock's max_cycles value (%lld): time overflow danger\n",
2093c17ad19SJohn Stultz offset, name, max_cycles);
210a558cd02SJohn Stultz printk_deferred(" timekeeping: Your kernel is sick, but tries to cope by capping time updates\n");
2113c17ad19SJohn Stultz } else {
2123c17ad19SJohn Stultz if (offset > (max_cycles >> 1)) {
213fc4fa6e1SMasanari Iida printk_deferred("INFO: timekeeping: Cycle offset (%lld) is larger than the '%s' clock's 50%% safety margin (%lld)\n",
2143c17ad19SJohn Stultz offset, name, max_cycles >> 1);
2153c17ad19SJohn Stultz printk_deferred(" timekeeping: Your kernel is still fine, but is feeling a bit nervous\n");
2163c17ad19SJohn Stultz }
2173c17ad19SJohn Stultz }
2184ca22c26SJohn Stultz
21957d05a93SJohn Stultz if (tk->underflow_seen) {
22057d05a93SJohn Stultz if (jiffies - tk->last_warning > WARNING_FREQ) {
2214ca22c26SJohn Stultz printk_deferred("WARNING: Underflow in clocksource '%s' observed, time update ignored.\n", name);
2224ca22c26SJohn Stultz printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
2234ca22c26SJohn Stultz printk_deferred(" Your kernel is probably still fine.\n");
22457d05a93SJohn Stultz tk->last_warning = jiffies;
2254ca22c26SJohn Stultz }
22657d05a93SJohn Stultz tk->underflow_seen = 0;
2274ca22c26SJohn Stultz }
2284ca22c26SJohn Stultz
22957d05a93SJohn Stultz if (tk->overflow_seen) {
23057d05a93SJohn Stultz if (jiffies - tk->last_warning > WARNING_FREQ) {
2314ca22c26SJohn Stultz printk_deferred("WARNING: Overflow in clocksource '%s' observed, time update capped.\n", name);
2324ca22c26SJohn Stultz printk_deferred(" Please report this, consider using a different clocksource, if possible.\n");
2334ca22c26SJohn Stultz printk_deferred(" Your kernel is probably still fine.\n");
23457d05a93SJohn Stultz tk->last_warning = jiffies;
2354ca22c26SJohn Stultz }
23657d05a93SJohn Stultz tk->overflow_seen = 0;
2374ca22c26SJohn Stultz }
2383c17ad19SJohn Stultz }
239a558cd02SJohn Stultz
timekeeping_get_delta(const struct tk_read_base * tkr)240985e6950SOndrej Mosnacek static inline u64 timekeeping_get_delta(const struct tk_read_base *tkr)
241a558cd02SJohn Stultz {
24257d05a93SJohn Stultz struct timekeeper *tk = &tk_core.timekeeper;
243a5a1d1c2SThomas Gleixner u64 now, last, mask, max, delta;
2444ca22c26SJohn Stultz unsigned int seq;
245a558cd02SJohn Stultz
2464ca22c26SJohn Stultz /*
247025e82bcSAhmed S. Darwish * Since we're called holding a seqcount, the data may shift
2484ca22c26SJohn Stultz * under us while we're doing the calculation. This can cause
2494ca22c26SJohn Stultz * false positives, since we'd note a problem but throw the
250025e82bcSAhmed S. Darwish * results away. So nest another seqcount here to atomically
2514ca22c26SJohn Stultz * grab the points we are checking with.
2524ca22c26SJohn Stultz */
2534ca22c26SJohn Stultz do {
2544ca22c26SJohn Stultz seq = read_seqcount_begin(&tk_core.seq);
255ceea5e37SJohn Stultz now = tk_clock_read(tkr);
2564ca22c26SJohn Stultz last = tkr->cycle_last;
2574ca22c26SJohn Stultz mask = tkr->mask;
2584ca22c26SJohn Stultz max = tkr->clock->max_cycles;
2594ca22c26SJohn Stultz } while (read_seqcount_retry(&tk_core.seq, seq));
260a558cd02SJohn Stultz
2614ca22c26SJohn Stultz delta = clocksource_delta(now, last, mask);
262a558cd02SJohn Stultz
263057b87e3SJohn Stultz /*
264057b87e3SJohn Stultz * Try to catch underflows by checking if we are seeing small
265057b87e3SJohn Stultz * mask-relative negative values.
266057b87e3SJohn Stultz */
2674ca22c26SJohn Stultz if (unlikely((~delta & mask) < (mask >> 3))) {
26857d05a93SJohn Stultz tk->underflow_seen = 1;
269057b87e3SJohn Stultz delta = 0;
2704ca22c26SJohn Stultz }
271057b87e3SJohn Stultz
272a558cd02SJohn Stultz /* Cap delta value to the max_cycles values to avoid mult overflows */
2734ca22c26SJohn Stultz if (unlikely(delta > max)) {
27457d05a93SJohn Stultz tk->overflow_seen = 1;
275a558cd02SJohn Stultz delta = tkr->clock->max_cycles;
2764ca22c26SJohn Stultz }
277a558cd02SJohn Stultz
278a558cd02SJohn Stultz return delta;
279a558cd02SJohn Stultz }
2803c17ad19SJohn Stultz #else
timekeeping_check_update(struct timekeeper * tk,u64 offset)281a5a1d1c2SThomas Gleixner static inline void timekeeping_check_update(struct timekeeper *tk, u64 offset)
2823c17ad19SJohn Stultz {
2833c17ad19SJohn Stultz }
timekeeping_get_delta(const struct tk_read_base * tkr)284985e6950SOndrej Mosnacek static inline u64 timekeeping_get_delta(const struct tk_read_base *tkr)
285a558cd02SJohn Stultz {
286a5a1d1c2SThomas Gleixner u64 cycle_now, delta;
287a558cd02SJohn Stultz
288a558cd02SJohn Stultz /* read clocksource */
289ceea5e37SJohn Stultz cycle_now = tk_clock_read(tkr);
290a558cd02SJohn Stultz
291a558cd02SJohn Stultz /* calculate the delta since the last update_wall_time */
292a558cd02SJohn Stultz delta = clocksource_delta(cycle_now, tkr->cycle_last, tkr->mask);
293a558cd02SJohn Stultz
294a558cd02SJohn Stultz return delta;
295a558cd02SJohn Stultz }
2963c17ad19SJohn Stultz #endif
2973c17ad19SJohn Stultz
298155ec602SMartin Schwidefsky /**
299d26e4fe0SYijing Wang * tk_setup_internals - Set up internals to use clocksource clock.
300155ec602SMartin Schwidefsky *
301d26e4fe0SYijing Wang * @tk: The target timekeeper to setup.
302155ec602SMartin Schwidefsky * @clock: Pointer to clocksource.
303155ec602SMartin Schwidefsky *
304155ec602SMartin Schwidefsky * Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
305155ec602SMartin Schwidefsky * pair and interval request.
306155ec602SMartin Schwidefsky *
307155ec602SMartin Schwidefsky * Unless you're the timekeeping code, you should not be using this!
308155ec602SMartin Schwidefsky */
tk_setup_internals(struct timekeeper * tk,struct clocksource * clock)309f726a697SJohn Stultz static void tk_setup_internals(struct timekeeper *tk, struct clocksource *clock)
310155ec602SMartin Schwidefsky {
311a5a1d1c2SThomas Gleixner u64 interval;
312a386b5afSKasper Pedersen u64 tmp, ntpinterval;
3131e75fa8bSJohn Stultz struct clocksource *old_clock;
314155ec602SMartin Schwidefsky
3152c756febSChristopher S. Hall ++tk->cs_was_changed_seq;
316876e7881SPeter Zijlstra old_clock = tk->tkr_mono.clock;
317876e7881SPeter Zijlstra tk->tkr_mono.clock = clock;
318876e7881SPeter Zijlstra tk->tkr_mono.mask = clock->mask;
319ceea5e37SJohn Stultz tk->tkr_mono.cycle_last = tk_clock_read(&tk->tkr_mono);
320155ec602SMartin Schwidefsky
3214a4ad80dSPeter Zijlstra tk->tkr_raw.clock = clock;
3224a4ad80dSPeter Zijlstra tk->tkr_raw.mask = clock->mask;
3234a4ad80dSPeter Zijlstra tk->tkr_raw.cycle_last = tk->tkr_mono.cycle_last;
3244a4ad80dSPeter Zijlstra
325155ec602SMartin Schwidefsky /* Do the ns -> cycle conversion first, using original mult */
326155ec602SMartin Schwidefsky tmp = NTP_INTERVAL_LENGTH;
327155ec602SMartin Schwidefsky tmp <<= clock->shift;
328a386b5afSKasper Pedersen ntpinterval = tmp;
3290a544198SMartin Schwidefsky tmp += clock->mult/2;
3300a544198SMartin Schwidefsky do_div(tmp, clock->mult);
331155ec602SMartin Schwidefsky if (tmp == 0)
332155ec602SMartin Schwidefsky tmp = 1;
333155ec602SMartin Schwidefsky
334a5a1d1c2SThomas Gleixner interval = (u64) tmp;
335f726a697SJohn Stultz tk->cycle_interval = interval;
336155ec602SMartin Schwidefsky
337155ec602SMartin Schwidefsky /* Go back from cycles -> shifted ns */
338cbd99e3bSThomas Gleixner tk->xtime_interval = interval * clock->mult;
339f726a697SJohn Stultz tk->xtime_remainder = ntpinterval - tk->xtime_interval;
3403d88d56cSJohn Stultz tk->raw_interval = interval * clock->mult;
341155ec602SMartin Schwidefsky
3421e75fa8bSJohn Stultz /* if changing clocks, convert xtime_nsec shift units */
3431e75fa8bSJohn Stultz if (old_clock) {
3441e75fa8bSJohn Stultz int shift_change = clock->shift - old_clock->shift;
345fc6eead7SJohn Stultz if (shift_change < 0) {
346876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec >>= -shift_change;
347fc6eead7SJohn Stultz tk->tkr_raw.xtime_nsec >>= -shift_change;
348fc6eead7SJohn Stultz } else {
349876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec <<= shift_change;
350fc6eead7SJohn Stultz tk->tkr_raw.xtime_nsec <<= shift_change;
3511e75fa8bSJohn Stultz }
352fc6eead7SJohn Stultz }
3534a4ad80dSPeter Zijlstra
354876e7881SPeter Zijlstra tk->tkr_mono.shift = clock->shift;
3554a4ad80dSPeter Zijlstra tk->tkr_raw.shift = clock->shift;
356155ec602SMartin Schwidefsky
357f726a697SJohn Stultz tk->ntp_error = 0;
358f726a697SJohn Stultz tk->ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
359375f45b5SJohn Stultz tk->ntp_tick = ntpinterval << tk->ntp_error_shift;
3600a544198SMartin Schwidefsky
3610a544198SMartin Schwidefsky /*
3620a544198SMartin Schwidefsky * The timekeeper keeps its own mult values for the currently
3630a544198SMartin Schwidefsky * active clocksource. These value will be adjusted via NTP
3640a544198SMartin Schwidefsky * to counteract clock drifting.
3650a544198SMartin Schwidefsky */
366876e7881SPeter Zijlstra tk->tkr_mono.mult = clock->mult;
3674a4ad80dSPeter Zijlstra tk->tkr_raw.mult = clock->mult;
368dc491596SJohn Stultz tk->ntp_err_mult = 0;
36978b98e3cSMiroslav Lichvar tk->skip_second_overflow = 0;
370155ec602SMartin Schwidefsky }
3718524070bSjohn stultz
3722ba2a305SMartin Schwidefsky /* Timekeeper helper functions. */
3737b1f6207SStephen Warren
timekeeping_delta_to_ns(const struct tk_read_base * tkr,u64 delta)374985e6950SOndrej Mosnacek static inline u64 timekeeping_delta_to_ns(const struct tk_read_base *tkr, u64 delta)
3752ba2a305SMartin Schwidefsky {
3769c164572SThomas Gleixner u64 nsec;
3772ba2a305SMartin Schwidefsky
3786bd58f09SChristopher S. Hall nsec = delta * tkr->mult + tkr->xtime_nsec;
3796bd58f09SChristopher S. Hall nsec >>= tkr->shift;
380f2a5a085SJohn Stultz
38177f6c0b8SArnd Bergmann return nsec;
3822ba2a305SMartin Schwidefsky }
3832ba2a305SMartin Schwidefsky
timekeeping_get_ns(const struct tk_read_base * tkr)384985e6950SOndrej Mosnacek static inline u64 timekeeping_get_ns(const struct tk_read_base *tkr)
3856bd58f09SChristopher S. Hall {
386a5a1d1c2SThomas Gleixner u64 delta;
3876bd58f09SChristopher S. Hall
3886bd58f09SChristopher S. Hall delta = timekeeping_get_delta(tkr);
3896bd58f09SChristopher S. Hall return timekeeping_delta_to_ns(tkr, delta);
3906bd58f09SChristopher S. Hall }
3916bd58f09SChristopher S. Hall
timekeeping_cycles_to_ns(const struct tk_read_base * tkr,u64 cycles)392985e6950SOndrej Mosnacek static inline u64 timekeeping_cycles_to_ns(const struct tk_read_base *tkr, u64 cycles)
3936bd58f09SChristopher S. Hall {
394a5a1d1c2SThomas Gleixner u64 delta;
3956bd58f09SChristopher S. Hall
3966bd58f09SChristopher S. Hall /* calculate the delta since the last update_wall_time */
3976bd58f09SChristopher S. Hall delta = clocksource_delta(cycles, tkr->cycle_last, tkr->mask);
3986bd58f09SChristopher S. Hall return timekeeping_delta_to_ns(tkr, delta);
3996bd58f09SChristopher S. Hall }
4006bd58f09SChristopher S. Hall
4014396e058SThomas Gleixner /**
4024396e058SThomas Gleixner * update_fast_timekeeper - Update the fast and NMI safe monotonic timekeeper.
403affe3e85SRafael J. Wysocki * @tkr: Timekeeping readout base from which we take the update
404e025b031SAlex Shi * @tkf: Pointer to NMI safe timekeeper
4054396e058SThomas Gleixner *
4064396e058SThomas Gleixner * We want to use this from any context including NMI and tracing /
4074396e058SThomas Gleixner * instrumenting the timekeeping code itself.
4084396e058SThomas Gleixner *
4096695b92aSPeter Zijlstra * Employ the latch technique; see @raw_write_seqcount_latch.
4104396e058SThomas Gleixner *
4114396e058SThomas Gleixner * So if a NMI hits the update of base[0] then it will use base[1]
4124396e058SThomas Gleixner * which is still consistent. In the worst case this can result is a
4134396e058SThomas Gleixner * slightly wrong timestamp (a few nanoseconds). See
4144396e058SThomas Gleixner * @ktime_get_mono_fast_ns.
4154396e058SThomas Gleixner */
update_fast_timekeeper(const struct tk_read_base * tkr,struct tk_fast * tkf)416985e6950SOndrej Mosnacek static void update_fast_timekeeper(const struct tk_read_base *tkr,
417985e6950SOndrej Mosnacek struct tk_fast *tkf)
4184396e058SThomas Gleixner {
4194498e746SPeter Zijlstra struct tk_read_base *base = tkf->base;
4204396e058SThomas Gleixner
4214396e058SThomas Gleixner /* Force readers off to base[1] */
4224498e746SPeter Zijlstra raw_write_seqcount_latch(&tkf->seq);
4234396e058SThomas Gleixner
4244396e058SThomas Gleixner /* Update base[0] */
425affe3e85SRafael J. Wysocki memcpy(base, tkr, sizeof(*base));
4264396e058SThomas Gleixner
4274396e058SThomas Gleixner /* Force readers back to base[0] */
4284498e746SPeter Zijlstra raw_write_seqcount_latch(&tkf->seq);
4294396e058SThomas Gleixner
4304396e058SThomas Gleixner /* Update base[1] */
4314396e058SThomas Gleixner memcpy(base + 1, base, sizeof(*base));
4324396e058SThomas Gleixner }
4334396e058SThomas Gleixner
fast_tk_get_delta_ns(struct tk_read_base * tkr)43490be8d6cSThomas Gleixner static __always_inline u64 fast_tk_get_delta_ns(struct tk_read_base *tkr)
43590be8d6cSThomas Gleixner {
43690be8d6cSThomas Gleixner u64 delta, cycles = tk_clock_read(tkr);
43790be8d6cSThomas Gleixner
43890be8d6cSThomas Gleixner delta = clocksource_delta(cycles, tkr->cycle_last, tkr->mask);
43990be8d6cSThomas Gleixner return timekeeping_delta_to_ns(tkr, delta);
44090be8d6cSThomas Gleixner }
44190be8d6cSThomas Gleixner
__ktime_get_fast_ns(struct tk_fast * tkf)442c1ce406eSThomas Gleixner static __always_inline u64 __ktime_get_fast_ns(struct tk_fast *tkf)
443c1ce406eSThomas Gleixner {
444c1ce406eSThomas Gleixner struct tk_read_base *tkr;
445c1ce406eSThomas Gleixner unsigned int seq;
446c1ce406eSThomas Gleixner u64 now;
447c1ce406eSThomas Gleixner
448c1ce406eSThomas Gleixner do {
449c1ce406eSThomas Gleixner seq = raw_read_seqcount_latch(&tkf->seq);
450c1ce406eSThomas Gleixner tkr = tkf->base + (seq & 0x01);
451c1ce406eSThomas Gleixner now = ktime_to_ns(tkr->base);
45290be8d6cSThomas Gleixner now += fast_tk_get_delta_ns(tkr);
453d16317deSPeter Zijlstra } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
454c1ce406eSThomas Gleixner
455c1ce406eSThomas Gleixner return now;
456c1ce406eSThomas Gleixner }
457c1ce406eSThomas Gleixner
4584396e058SThomas Gleixner /**
4594396e058SThomas Gleixner * ktime_get_mono_fast_ns - Fast NMI safe access to clock monotonic
4604396e058SThomas Gleixner *
4614396e058SThomas Gleixner * This timestamp is not guaranteed to be monotonic across an update.
4624396e058SThomas Gleixner * The timestamp is calculated by:
4634396e058SThomas Gleixner *
4644396e058SThomas Gleixner * now = base_mono + clock_delta * slope
4654396e058SThomas Gleixner *
4664396e058SThomas Gleixner * So if the update lowers the slope, readers who are forced to the
4674396e058SThomas Gleixner * not yet updated second array are still using the old steeper slope.
4684396e058SThomas Gleixner *
4694396e058SThomas Gleixner * tmono
4704396e058SThomas Gleixner * ^
4714396e058SThomas Gleixner * | o n
4724396e058SThomas Gleixner * | o n
4734396e058SThomas Gleixner * | u
4744396e058SThomas Gleixner * | o
4754396e058SThomas Gleixner * |o
4764396e058SThomas Gleixner * |12345678---> reader order
4774396e058SThomas Gleixner *
4784396e058SThomas Gleixner * o = old slope
4794396e058SThomas Gleixner * u = update
4804396e058SThomas Gleixner * n = new slope
4814396e058SThomas Gleixner *
4824396e058SThomas Gleixner * So reader 6 will observe time going backwards versus reader 5.
4834396e058SThomas Gleixner *
484c1ce406eSThomas Gleixner * While other CPUs are likely to be able to observe that, the only way
4854396e058SThomas Gleixner * for a CPU local observation is when an NMI hits in the middle of
4864396e058SThomas Gleixner * the update. Timestamps taken from that NMI context might be ahead
4874396e058SThomas Gleixner * of the following timestamps. Callers need to be aware of that and
4884396e058SThomas Gleixner * deal with it.
4894396e058SThomas Gleixner */
ktime_get_mono_fast_ns(void)4902c33d775SKurt Kanzenbach u64 notrace ktime_get_mono_fast_ns(void)
4914498e746SPeter Zijlstra {
4924498e746SPeter Zijlstra return __ktime_get_fast_ns(&tk_fast_mono);
4934498e746SPeter Zijlstra }
4944396e058SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_mono_fast_ns);
4954396e058SThomas Gleixner
496c1ce406eSThomas Gleixner /**
497c1ce406eSThomas Gleixner * ktime_get_raw_fast_ns - Fast NMI safe access to clock monotonic raw
498c1ce406eSThomas Gleixner *
499c1ce406eSThomas Gleixner * Contrary to ktime_get_mono_fast_ns() this is always correct because the
500c1ce406eSThomas Gleixner * conversion factor is not affected by NTP/PTP correction.
501c1ce406eSThomas Gleixner */
ktime_get_raw_fast_ns(void)5022c33d775SKurt Kanzenbach u64 notrace ktime_get_raw_fast_ns(void)
503f09cb9a1SPeter Zijlstra {
504f09cb9a1SPeter Zijlstra return __ktime_get_fast_ns(&tk_fast_raw);
505f09cb9a1SPeter Zijlstra }
506f09cb9a1SPeter Zijlstra EXPORT_SYMBOL_GPL(ktime_get_raw_fast_ns);
507f09cb9a1SPeter Zijlstra
508a3ed0e43SThomas Gleixner /**
509a3ed0e43SThomas Gleixner * ktime_get_boot_fast_ns - NMI safe and fast access to boot clock.
510a3ed0e43SThomas Gleixner *
511a3ed0e43SThomas Gleixner * To keep it NMI safe since we're accessing from tracing, we're not using a
512a3ed0e43SThomas Gleixner * separate timekeeper with updates to monotonic clock and boot offset
513025e82bcSAhmed S. Darwish * protected with seqcounts. This has the following minor side effects:
514a3ed0e43SThomas Gleixner *
515a3ed0e43SThomas Gleixner * (1) Its possible that a timestamp be taken after the boot offset is updated
516a3ed0e43SThomas Gleixner * but before the timekeeper is updated. If this happens, the new boot offset
517a3ed0e43SThomas Gleixner * is added to the old timekeeping making the clock appear to update slightly
518a3ed0e43SThomas Gleixner * earlier:
519a3ed0e43SThomas Gleixner * CPU 0 CPU 1
520a3ed0e43SThomas Gleixner * timekeeping_inject_sleeptime64()
521a3ed0e43SThomas Gleixner * __timekeeping_inject_sleeptime(tk, delta);
522a3ed0e43SThomas Gleixner * timestamp();
523a3ed0e43SThomas Gleixner * timekeeping_update(tk, TK_CLEAR_NTP...);
524a3ed0e43SThomas Gleixner *
525a3ed0e43SThomas Gleixner * (2) On 32-bit systems, the 64-bit boot offset (tk->offs_boot) may be
526a3ed0e43SThomas Gleixner * partially updated. Since the tk->offs_boot update is a rare event, this
527a3ed0e43SThomas Gleixner * should be a rare occurrence which postprocessing should be able to handle.
528c1ce406eSThomas Gleixner *
529158009f1SGeert Uytterhoeven * The caveats vs. timestamp ordering as documented for ktime_get_mono_fast_ns()
530c1ce406eSThomas Gleixner * apply as well.
531a3ed0e43SThomas Gleixner */
ktime_get_boot_fast_ns(void)532a3ed0e43SThomas Gleixner u64 notrace ktime_get_boot_fast_ns(void)
533a3ed0e43SThomas Gleixner {
534a3ed0e43SThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
535a3ed0e43SThomas Gleixner
536eff4849fSThomas Gleixner return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_boot)));
537a3ed0e43SThomas Gleixner }
538a3ed0e43SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_boot_fast_ns);
539a3ed0e43SThomas Gleixner
5403dc6ffaeSKurt Kanzenbach /**
5413dc6ffaeSKurt Kanzenbach * ktime_get_tai_fast_ns - NMI safe and fast access to tai clock.
5423dc6ffaeSKurt Kanzenbach *
5433dc6ffaeSKurt Kanzenbach * The same limitations as described for ktime_get_boot_fast_ns() apply. The
5443dc6ffaeSKurt Kanzenbach * mono time and the TAI offset are not read atomically which may yield wrong
5453dc6ffaeSKurt Kanzenbach * readouts. However, an update of the TAI offset is an rare event e.g., caused
5463dc6ffaeSKurt Kanzenbach * by settime or adjtimex with an offset. The user of this function has to deal
5473dc6ffaeSKurt Kanzenbach * with the possibility of wrong timestamps in post processing.
5483dc6ffaeSKurt Kanzenbach */
ktime_get_tai_fast_ns(void)5493dc6ffaeSKurt Kanzenbach u64 notrace ktime_get_tai_fast_ns(void)
5503dc6ffaeSKurt Kanzenbach {
5513dc6ffaeSKurt Kanzenbach struct timekeeper *tk = &tk_core.timekeeper;
5523dc6ffaeSKurt Kanzenbach
5533dc6ffaeSKurt Kanzenbach return (ktime_get_mono_fast_ns() + ktime_to_ns(data_race(tk->offs_tai)));
5543dc6ffaeSKurt Kanzenbach }
5553dc6ffaeSKurt Kanzenbach EXPORT_SYMBOL_GPL(ktime_get_tai_fast_ns);
5563dc6ffaeSKurt Kanzenbach
__ktime_get_real_fast(struct tk_fast * tkf,u64 * mono)557e2d977c9SThomas Gleixner static __always_inline u64 __ktime_get_real_fast(struct tk_fast *tkf, u64 *mono)
5584c3711d7SThomas Gleixner {
5594c3711d7SThomas Gleixner struct tk_read_base *tkr;
560e2d977c9SThomas Gleixner u64 basem, baser, delta;
5614c3711d7SThomas Gleixner unsigned int seq;
5624c3711d7SThomas Gleixner
5634c3711d7SThomas Gleixner do {
5644c3711d7SThomas Gleixner seq = raw_read_seqcount_latch(&tkf->seq);
5654c3711d7SThomas Gleixner tkr = tkf->base + (seq & 0x01);
566e2d977c9SThomas Gleixner basem = ktime_to_ns(tkr->base);
567e2d977c9SThomas Gleixner baser = ktime_to_ns(tkr->base_real);
56890be8d6cSThomas Gleixner delta = fast_tk_get_delta_ns(tkr);
569d16317deSPeter Zijlstra } while (raw_read_seqcount_latch_retry(&tkf->seq, seq));
5704c3711d7SThomas Gleixner
571e2d977c9SThomas Gleixner if (mono)
572e2d977c9SThomas Gleixner *mono = basem + delta;
573e2d977c9SThomas Gleixner return baser + delta;
5744c3711d7SThomas Gleixner }
5754c3711d7SThomas Gleixner
5764c3711d7SThomas Gleixner /**
5774c3711d7SThomas Gleixner * ktime_get_real_fast_ns: - NMI safe and fast access to clock realtime.
578c1ce406eSThomas Gleixner *
579158009f1SGeert Uytterhoeven * See ktime_get_mono_fast_ns() for documentation of the time stamp ordering.
5804c3711d7SThomas Gleixner */
ktime_get_real_fast_ns(void)5814c3711d7SThomas Gleixner u64 ktime_get_real_fast_ns(void)
5824c3711d7SThomas Gleixner {
583e2d977c9SThomas Gleixner return __ktime_get_real_fast(&tk_fast_mono, NULL);
5844c3711d7SThomas Gleixner }
585df27067eSArnd Bergmann EXPORT_SYMBOL_GPL(ktime_get_real_fast_ns);
5864c3711d7SThomas Gleixner
587060407aeSRafael J. Wysocki /**
588e2d977c9SThomas Gleixner * ktime_get_fast_timestamps: - NMI safe timestamps
589e2d977c9SThomas Gleixner * @snapshot: Pointer to timestamp storage
590e2d977c9SThomas Gleixner *
591e2d977c9SThomas Gleixner * Stores clock monotonic, boottime and realtime timestamps.
592e2d977c9SThomas Gleixner *
593e2d977c9SThomas Gleixner * Boot time is a racy access on 32bit systems if the sleep time injection
594e2d977c9SThomas Gleixner * happens late during resume and not in timekeeping_resume(). That could
595e2d977c9SThomas Gleixner * be avoided by expanding struct tk_read_base with boot offset for 32bit
596e2d977c9SThomas Gleixner * and adding more overhead to the update. As this is a hard to observe
597e2d977c9SThomas Gleixner * once per resume event which can be filtered with reasonable effort using
598e2d977c9SThomas Gleixner * the accurate mono/real timestamps, it's probably not worth the trouble.
599e2d977c9SThomas Gleixner *
600e2d977c9SThomas Gleixner * Aside of that it might be possible on 32 and 64 bit to observe the
601e2d977c9SThomas Gleixner * following when the sleep time injection happens late:
602e2d977c9SThomas Gleixner *
603e2d977c9SThomas Gleixner * CPU 0 CPU 1
604e2d977c9SThomas Gleixner * timekeeping_resume()
605e2d977c9SThomas Gleixner * ktime_get_fast_timestamps()
606e2d977c9SThomas Gleixner * mono, real = __ktime_get_real_fast()
607e2d977c9SThomas Gleixner * inject_sleep_time()
608e2d977c9SThomas Gleixner * update boot offset
609e2d977c9SThomas Gleixner * boot = mono + bootoffset;
610e2d977c9SThomas Gleixner *
611e2d977c9SThomas Gleixner * That means that boot time already has the sleep time adjustment, but
612e2d977c9SThomas Gleixner * real time does not. On the next readout both are in sync again.
613e2d977c9SThomas Gleixner *
614e2d977c9SThomas Gleixner * Preventing this for 64bit is not really feasible without destroying the
615e2d977c9SThomas Gleixner * careful cache layout of the timekeeper because the sequence count and
616e2d977c9SThomas Gleixner * struct tk_read_base would then need two cache lines instead of one.
617e2d977c9SThomas Gleixner *
6184bf07f65SIngo Molnar * Access to the time keeper clock source is disabled across the innermost
619e2d977c9SThomas Gleixner * steps of suspend/resume. The accessors still work, but the timestamps
620e2d977c9SThomas Gleixner * are frozen until time keeping is resumed which happens very early.
621e2d977c9SThomas Gleixner *
622e2d977c9SThomas Gleixner * For regular suspend/resume there is no observable difference vs. sched
623e2d977c9SThomas Gleixner * clock, but it might affect some of the nasty low level debug printks.
624e2d977c9SThomas Gleixner *
6254bf07f65SIngo Molnar * OTOH, access to sched clock is not guaranteed across suspend/resume on
626e2d977c9SThomas Gleixner * all systems either so it depends on the hardware in use.
627e2d977c9SThomas Gleixner *
628e2d977c9SThomas Gleixner * If that turns out to be a real problem then this could be mitigated by
629e2d977c9SThomas Gleixner * using sched clock in a similar way as during early boot. But it's not as
630e2d977c9SThomas Gleixner * trivial as on early boot because it needs some careful protection
631e2d977c9SThomas Gleixner * against the clock monotonic timestamp jumping backwards on resume.
632e2d977c9SThomas Gleixner */
ktime_get_fast_timestamps(struct ktime_timestamps * snapshot)633e2d977c9SThomas Gleixner void ktime_get_fast_timestamps(struct ktime_timestamps *snapshot)
634e2d977c9SThomas Gleixner {
635e2d977c9SThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
636e2d977c9SThomas Gleixner
637e2d977c9SThomas Gleixner snapshot->real = __ktime_get_real_fast(&tk_fast_mono, &snapshot->mono);
638e2d977c9SThomas Gleixner snapshot->boot = snapshot->mono + ktime_to_ns(data_race(tk->offs_boot));
639e2d977c9SThomas Gleixner }
640e2d977c9SThomas Gleixner
641e2d977c9SThomas Gleixner /**
642060407aeSRafael J. Wysocki * halt_fast_timekeeper - Prevent fast timekeeper from accessing clocksource.
643060407aeSRafael J. Wysocki * @tk: Timekeeper to snapshot.
644060407aeSRafael J. Wysocki *
645060407aeSRafael J. Wysocki * It generally is unsafe to access the clocksource after timekeeping has been
646060407aeSRafael J. Wysocki * suspended, so take a snapshot of the readout base of @tk and use it as the
647060407aeSRafael J. Wysocki * fast timekeeper's readout base while suspended. It will return the same
648060407aeSRafael J. Wysocki * number of cycles every time until timekeeping is resumed at which time the
649060407aeSRafael J. Wysocki * proper readout base for the fast timekeeper will be restored automatically.
650060407aeSRafael J. Wysocki */
halt_fast_timekeeper(const struct timekeeper * tk)651985e6950SOndrej Mosnacek static void halt_fast_timekeeper(const struct timekeeper *tk)
652060407aeSRafael J. Wysocki {
653060407aeSRafael J. Wysocki static struct tk_read_base tkr_dummy;
654985e6950SOndrej Mosnacek const struct tk_read_base *tkr = &tk->tkr_mono;
655060407aeSRafael J. Wysocki
656060407aeSRafael J. Wysocki memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
657ceea5e37SJohn Stultz cycles_at_suspend = tk_clock_read(tkr);
658ceea5e37SJohn Stultz tkr_dummy.clock = &dummy_clock;
6594c3711d7SThomas Gleixner tkr_dummy.base_real = tkr->base + tk->offs_real;
6604498e746SPeter Zijlstra update_fast_timekeeper(&tkr_dummy, &tk_fast_mono);
661f09cb9a1SPeter Zijlstra
662f09cb9a1SPeter Zijlstra tkr = &tk->tkr_raw;
663f09cb9a1SPeter Zijlstra memcpy(&tkr_dummy, tkr, sizeof(tkr_dummy));
664ceea5e37SJohn Stultz tkr_dummy.clock = &dummy_clock;
665f09cb9a1SPeter Zijlstra update_fast_timekeeper(&tkr_dummy, &tk_fast_raw);
666060407aeSRafael J. Wysocki }
667060407aeSRafael J. Wysocki
668e0b306feSMarcelo Tosatti static RAW_NOTIFIER_HEAD(pvclock_gtod_chain);
669e0b306feSMarcelo Tosatti
update_pvclock_gtod(struct timekeeper * tk,bool was_set)670780427f0SDavid Vrabel static void update_pvclock_gtod(struct timekeeper *tk, bool was_set)
671e0b306feSMarcelo Tosatti {
672780427f0SDavid Vrabel raw_notifier_call_chain(&pvclock_gtod_chain, was_set, tk);
673e0b306feSMarcelo Tosatti }
674e0b306feSMarcelo Tosatti
675e0b306feSMarcelo Tosatti /**
676e0b306feSMarcelo Tosatti * pvclock_gtod_register_notifier - register a pvclock timedata update listener
677f27f7c3fSAlex Shi * @nb: Pointer to the notifier block to register
678e0b306feSMarcelo Tosatti */
pvclock_gtod_register_notifier(struct notifier_block * nb)679e0b306feSMarcelo Tosatti int pvclock_gtod_register_notifier(struct notifier_block *nb)
680e0b306feSMarcelo Tosatti {
6813fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
682e0b306feSMarcelo Tosatti unsigned long flags;
683e0b306feSMarcelo Tosatti int ret;
684e0b306feSMarcelo Tosatti
6859a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
686e0b306feSMarcelo Tosatti ret = raw_notifier_chain_register(&pvclock_gtod_chain, nb);
687780427f0SDavid Vrabel update_pvclock_gtod(tk, true);
6889a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
689e0b306feSMarcelo Tosatti
690e0b306feSMarcelo Tosatti return ret;
691e0b306feSMarcelo Tosatti }
692e0b306feSMarcelo Tosatti EXPORT_SYMBOL_GPL(pvclock_gtod_register_notifier);
693e0b306feSMarcelo Tosatti
694e0b306feSMarcelo Tosatti /**
695e0b306feSMarcelo Tosatti * pvclock_gtod_unregister_notifier - unregister a pvclock
696e0b306feSMarcelo Tosatti * timedata update listener
697f27f7c3fSAlex Shi * @nb: Pointer to the notifier block to unregister
698e0b306feSMarcelo Tosatti */
pvclock_gtod_unregister_notifier(struct notifier_block * nb)699e0b306feSMarcelo Tosatti int pvclock_gtod_unregister_notifier(struct notifier_block *nb)
700e0b306feSMarcelo Tosatti {
701e0b306feSMarcelo Tosatti unsigned long flags;
702e0b306feSMarcelo Tosatti int ret;
703e0b306feSMarcelo Tosatti
7049a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
705e0b306feSMarcelo Tosatti ret = raw_notifier_chain_unregister(&pvclock_gtod_chain, nb);
7069a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
707e0b306feSMarcelo Tosatti
708e0b306feSMarcelo Tosatti return ret;
709e0b306feSMarcelo Tosatti }
710e0b306feSMarcelo Tosatti EXPORT_SYMBOL_GPL(pvclock_gtod_unregister_notifier);
711e0b306feSMarcelo Tosatti
7127c032df5SThomas Gleixner /*
713833f32d7SJohn Stultz * tk_update_leap_state - helper to update the next_leap_ktime
714833f32d7SJohn Stultz */
tk_update_leap_state(struct timekeeper * tk)715833f32d7SJohn Stultz static inline void tk_update_leap_state(struct timekeeper *tk)
716833f32d7SJohn Stultz {
717833f32d7SJohn Stultz tk->next_leap_ktime = ntp_get_next_leap();
7182456e855SThomas Gleixner if (tk->next_leap_ktime != KTIME_MAX)
719833f32d7SJohn Stultz /* Convert to monotonic time */
720833f32d7SJohn Stultz tk->next_leap_ktime = ktime_sub(tk->next_leap_ktime, tk->offs_real);
721833f32d7SJohn Stultz }
722833f32d7SJohn Stultz
723833f32d7SJohn Stultz /*
7247c032df5SThomas Gleixner * Update the ktime_t based scalar nsec members of the timekeeper
7257c032df5SThomas Gleixner */
tk_update_ktime_data(struct timekeeper * tk)7267c032df5SThomas Gleixner static inline void tk_update_ktime_data(struct timekeeper *tk)
7277c032df5SThomas Gleixner {
7289e3680b1SHeena Sirwani u64 seconds;
7299e3680b1SHeena Sirwani u32 nsec;
7307c032df5SThomas Gleixner
7317c032df5SThomas Gleixner /*
7327c032df5SThomas Gleixner * The xtime based monotonic readout is:
7337c032df5SThomas Gleixner * nsec = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec + now();
7347c032df5SThomas Gleixner * The ktime based monotonic readout is:
7357c032df5SThomas Gleixner * nsec = base_mono + now();
7367c032df5SThomas Gleixner * ==> base_mono = (xtime_sec + wtm_sec) * 1e9 + wtm_nsec
7377c032df5SThomas Gleixner */
7389e3680b1SHeena Sirwani seconds = (u64)(tk->xtime_sec + tk->wall_to_monotonic.tv_sec);
7399e3680b1SHeena Sirwani nsec = (u32) tk->wall_to_monotonic.tv_nsec;
740876e7881SPeter Zijlstra tk->tkr_mono.base = ns_to_ktime(seconds * NSEC_PER_SEC + nsec);
741f519b1a2SThomas Gleixner
7429e3680b1SHeena Sirwani /*
7439e3680b1SHeena Sirwani * The sum of the nanoseconds portions of xtime and
7449e3680b1SHeena Sirwani * wall_to_monotonic can be greater/equal one second. Take
7459e3680b1SHeena Sirwani * this into account before updating tk->ktime_sec.
7469e3680b1SHeena Sirwani */
747876e7881SPeter Zijlstra nsec += (u32)(tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift);
7489e3680b1SHeena Sirwani if (nsec >= NSEC_PER_SEC)
7499e3680b1SHeena Sirwani seconds++;
7509e3680b1SHeena Sirwani tk->ktime_sec = seconds;
751fc6eead7SJohn Stultz
752fc6eead7SJohn Stultz /* Update the monotonic raw base */
7530bcdc098SJohn Stultz tk->tkr_raw.base = ns_to_ktime(tk->raw_sec * NSEC_PER_SEC);
7547c032df5SThomas Gleixner }
7557c032df5SThomas Gleixner
7569a7a71b1SThomas Gleixner /* must hold timekeeper_lock */
timekeeping_update(struct timekeeper * tk,unsigned int action)75704397fe9SDavid Vrabel static void timekeeping_update(struct timekeeper *tk, unsigned int action)
758cc06268cSThomas Gleixner {
75904397fe9SDavid Vrabel if (action & TK_CLEAR_NTP) {
760f726a697SJohn Stultz tk->ntp_error = 0;
761cc06268cSThomas Gleixner ntp_clear();
762cc06268cSThomas Gleixner }
76348cdc135SThomas Gleixner
764833f32d7SJohn Stultz tk_update_leap_state(tk);
7657c032df5SThomas Gleixner tk_update_ktime_data(tk);
7667c032df5SThomas Gleixner
7679bf2419fSThomas Gleixner update_vsyscall(tk);
7689bf2419fSThomas Gleixner update_pvclock_gtod(tk, action & TK_CLOCK_WAS_SET);
7699bf2419fSThomas Gleixner
7704c3711d7SThomas Gleixner tk->tkr_mono.base_real = tk->tkr_mono.base + tk->offs_real;
7714498e746SPeter Zijlstra update_fast_timekeeper(&tk->tkr_mono, &tk_fast_mono);
772f09cb9a1SPeter Zijlstra update_fast_timekeeper(&tk->tkr_raw, &tk_fast_raw);
773868a3e91SThomas Gleixner
774868a3e91SThomas Gleixner if (action & TK_CLOCK_WAS_SET)
775868a3e91SThomas Gleixner tk->clock_was_set_seq++;
776d1518326SJohn Stultz /*
777d1518326SJohn Stultz * The mirroring of the data to the shadow-timekeeper needs
778d1518326SJohn Stultz * to happen last here to ensure we don't over-write the
779d1518326SJohn Stultz * timekeeper structure on the next update with stale data
780d1518326SJohn Stultz */
781d1518326SJohn Stultz if (action & TK_MIRROR)
782d1518326SJohn Stultz memcpy(&shadow_timekeeper, &tk_core.timekeeper,
783d1518326SJohn Stultz sizeof(tk_core.timekeeper));
784cc06268cSThomas Gleixner }
785cc06268cSThomas Gleixner
7868524070bSjohn stultz /**
787155ec602SMartin Schwidefsky * timekeeping_forward_now - update clock to the current time
7886e5a9190SAlex Shi * @tk: Pointer to the timekeeper to update
7898524070bSjohn stultz *
7909a055117SRoman Zippel * Forward the current clock to update its state since the last call to
7919a055117SRoman Zippel * update_wall_time(). This is useful before significant clock changes,
7929a055117SRoman Zippel * as it avoids having to deal with this time offset explicitly.
7938524070bSjohn stultz */
timekeeping_forward_now(struct timekeeper * tk)794f726a697SJohn Stultz static void timekeeping_forward_now(struct timekeeper *tk)
7958524070bSjohn stultz {
796a5a1d1c2SThomas Gleixner u64 cycle_now, delta;
7978524070bSjohn stultz
798ceea5e37SJohn Stultz cycle_now = tk_clock_read(&tk->tkr_mono);
799876e7881SPeter Zijlstra delta = clocksource_delta(cycle_now, tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
800876e7881SPeter Zijlstra tk->tkr_mono.cycle_last = cycle_now;
8014a4ad80dSPeter Zijlstra tk->tkr_raw.cycle_last = cycle_now;
8028524070bSjohn stultz
803876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec += delta * tk->tkr_mono.mult;
804fc6eead7SJohn Stultz tk->tkr_raw.xtime_nsec += delta * tk->tkr_raw.mult;
805fc6eead7SJohn Stultz
806fc6eead7SJohn Stultz tk_normalize_xtime(tk);
8078524070bSjohn stultz }
8088524070bSjohn stultz
8098524070bSjohn stultz /**
810edca71feSArnd Bergmann * ktime_get_real_ts64 - Returns the time of day in a timespec64.
8118524070bSjohn stultz * @ts: pointer to the timespec to be set
8128524070bSjohn stultz *
813edca71feSArnd Bergmann * Returns the time of day in a timespec64 (WARN if suspended).
8148524070bSjohn stultz */
ktime_get_real_ts64(struct timespec64 * ts)815edca71feSArnd Bergmann void ktime_get_real_ts64(struct timespec64 *ts)
8168524070bSjohn stultz {
8173fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
818e1e41b6cSRasmus Villemoes unsigned int seq;
819acc89612SThomas Gleixner u64 nsecs;
8208524070bSjohn stultz
821edca71feSArnd Bergmann WARN_ON(timekeeping_suspended);
822edca71feSArnd Bergmann
8238524070bSjohn stultz do {
8243fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
8258524070bSjohn stultz
8264e250fddSJohn Stultz ts->tv_sec = tk->xtime_sec;
827876e7881SPeter Zijlstra nsecs = timekeeping_get_ns(&tk->tkr_mono);
8288524070bSjohn stultz
8293fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
8308524070bSjohn stultz
831ec145babSJohn Stultz ts->tv_nsec = 0;
832d6d29896SThomas Gleixner timespec64_add_ns(ts, nsecs);
8331e817fb6SKees Cook }
834edca71feSArnd Bergmann EXPORT_SYMBOL(ktime_get_real_ts64);
8358524070bSjohn stultz
ktime_get(void)836951ed4d3SMartin Schwidefsky ktime_t ktime_get(void)
837951ed4d3SMartin Schwidefsky {
8383fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
839951ed4d3SMartin Schwidefsky unsigned int seq;
840a016a5bdSThomas Gleixner ktime_t base;
841acc89612SThomas Gleixner u64 nsecs;
842951ed4d3SMartin Schwidefsky
843951ed4d3SMartin Schwidefsky WARN_ON(timekeeping_suspended);
844951ed4d3SMartin Schwidefsky
845951ed4d3SMartin Schwidefsky do {
8463fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
847876e7881SPeter Zijlstra base = tk->tkr_mono.base;
848876e7881SPeter Zijlstra nsecs = timekeeping_get_ns(&tk->tkr_mono);
849951ed4d3SMartin Schwidefsky
8503fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
85124e4a8c3SJohn Stultz
852a016a5bdSThomas Gleixner return ktime_add_ns(base, nsecs);
853951ed4d3SMartin Schwidefsky }
854951ed4d3SMartin Schwidefsky EXPORT_SYMBOL_GPL(ktime_get);
855951ed4d3SMartin Schwidefsky
ktime_get_resolution_ns(void)8566374f912SHarald Geyer u32 ktime_get_resolution_ns(void)
8576374f912SHarald Geyer {
8586374f912SHarald Geyer struct timekeeper *tk = &tk_core.timekeeper;
8596374f912SHarald Geyer unsigned int seq;
8606374f912SHarald Geyer u32 nsecs;
8616374f912SHarald Geyer
8626374f912SHarald Geyer WARN_ON(timekeeping_suspended);
8636374f912SHarald Geyer
8646374f912SHarald Geyer do {
8656374f912SHarald Geyer seq = read_seqcount_begin(&tk_core.seq);
8666374f912SHarald Geyer nsecs = tk->tkr_mono.mult >> tk->tkr_mono.shift;
8676374f912SHarald Geyer } while (read_seqcount_retry(&tk_core.seq, seq));
8686374f912SHarald Geyer
8696374f912SHarald Geyer return nsecs;
8706374f912SHarald Geyer }
8716374f912SHarald Geyer EXPORT_SYMBOL_GPL(ktime_get_resolution_ns);
8726374f912SHarald Geyer
8730077dc60SThomas Gleixner static ktime_t *offsets[TK_OFFS_MAX] = {
8740077dc60SThomas Gleixner [TK_OFFS_REAL] = &tk_core.timekeeper.offs_real,
875a3ed0e43SThomas Gleixner [TK_OFFS_BOOT] = &tk_core.timekeeper.offs_boot,
8760077dc60SThomas Gleixner [TK_OFFS_TAI] = &tk_core.timekeeper.offs_tai,
8770077dc60SThomas Gleixner };
8780077dc60SThomas Gleixner
ktime_get_with_offset(enum tk_offsets offs)8790077dc60SThomas Gleixner ktime_t ktime_get_with_offset(enum tk_offsets offs)
8800077dc60SThomas Gleixner {
8810077dc60SThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
8820077dc60SThomas Gleixner unsigned int seq;
8830077dc60SThomas Gleixner ktime_t base, *offset = offsets[offs];
884acc89612SThomas Gleixner u64 nsecs;
8850077dc60SThomas Gleixner
8860077dc60SThomas Gleixner WARN_ON(timekeeping_suspended);
8870077dc60SThomas Gleixner
8880077dc60SThomas Gleixner do {
8890077dc60SThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
890876e7881SPeter Zijlstra base = ktime_add(tk->tkr_mono.base, *offset);
891876e7881SPeter Zijlstra nsecs = timekeeping_get_ns(&tk->tkr_mono);
8920077dc60SThomas Gleixner
8930077dc60SThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
8940077dc60SThomas Gleixner
8950077dc60SThomas Gleixner return ktime_add_ns(base, nsecs);
8960077dc60SThomas Gleixner
8970077dc60SThomas Gleixner }
8980077dc60SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_with_offset);
8990077dc60SThomas Gleixner
ktime_get_coarse_with_offset(enum tk_offsets offs)900b9ff604cSArnd Bergmann ktime_t ktime_get_coarse_with_offset(enum tk_offsets offs)
901b9ff604cSArnd Bergmann {
902b9ff604cSArnd Bergmann struct timekeeper *tk = &tk_core.timekeeper;
903b9ff604cSArnd Bergmann unsigned int seq;
904b9ff604cSArnd Bergmann ktime_t base, *offset = offsets[offs];
905e3ff9c36SThomas Gleixner u64 nsecs;
906b9ff604cSArnd Bergmann
907b9ff604cSArnd Bergmann WARN_ON(timekeeping_suspended);
908b9ff604cSArnd Bergmann
909b9ff604cSArnd Bergmann do {
910b9ff604cSArnd Bergmann seq = read_seqcount_begin(&tk_core.seq);
911b9ff604cSArnd Bergmann base = ktime_add(tk->tkr_mono.base, *offset);
912e3ff9c36SThomas Gleixner nsecs = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
913b9ff604cSArnd Bergmann
914b9ff604cSArnd Bergmann } while (read_seqcount_retry(&tk_core.seq, seq));
915b9ff604cSArnd Bergmann
9160354c1a3SJason A. Donenfeld return ktime_add_ns(base, nsecs);
917b9ff604cSArnd Bergmann }
918b9ff604cSArnd Bergmann EXPORT_SYMBOL_GPL(ktime_get_coarse_with_offset);
919b9ff604cSArnd Bergmann
920951ed4d3SMartin Schwidefsky /**
9214bf07f65SIngo Molnar * ktime_mono_to_any() - convert monotonic time to any other time
9229a6b5197SThomas Gleixner * @tmono: time to convert.
9239a6b5197SThomas Gleixner * @offs: which offset to use
9249a6b5197SThomas Gleixner */
ktime_mono_to_any(ktime_t tmono,enum tk_offsets offs)9259a6b5197SThomas Gleixner ktime_t ktime_mono_to_any(ktime_t tmono, enum tk_offsets offs)
9269a6b5197SThomas Gleixner {
9279a6b5197SThomas Gleixner ktime_t *offset = offsets[offs];
928e1e41b6cSRasmus Villemoes unsigned int seq;
9299a6b5197SThomas Gleixner ktime_t tconv;
9309a6b5197SThomas Gleixner
9319a6b5197SThomas Gleixner do {
9329a6b5197SThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
9339a6b5197SThomas Gleixner tconv = ktime_add(tmono, *offset);
9349a6b5197SThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
9359a6b5197SThomas Gleixner
9369a6b5197SThomas Gleixner return tconv;
9379a6b5197SThomas Gleixner }
9389a6b5197SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_mono_to_any);
9399a6b5197SThomas Gleixner
9409a6b5197SThomas Gleixner /**
941f519b1a2SThomas Gleixner * ktime_get_raw - Returns the raw monotonic time in ktime_t format
942f519b1a2SThomas Gleixner */
ktime_get_raw(void)943f519b1a2SThomas Gleixner ktime_t ktime_get_raw(void)
944f519b1a2SThomas Gleixner {
945f519b1a2SThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
946f519b1a2SThomas Gleixner unsigned int seq;
947f519b1a2SThomas Gleixner ktime_t base;
948acc89612SThomas Gleixner u64 nsecs;
949f519b1a2SThomas Gleixner
950f519b1a2SThomas Gleixner do {
951f519b1a2SThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
9524a4ad80dSPeter Zijlstra base = tk->tkr_raw.base;
9534a4ad80dSPeter Zijlstra nsecs = timekeeping_get_ns(&tk->tkr_raw);
954f519b1a2SThomas Gleixner
955f519b1a2SThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
956f519b1a2SThomas Gleixner
957f519b1a2SThomas Gleixner return ktime_add_ns(base, nsecs);
958f519b1a2SThomas Gleixner }
959f519b1a2SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_raw);
960f519b1a2SThomas Gleixner
961f519b1a2SThomas Gleixner /**
962d6d29896SThomas Gleixner * ktime_get_ts64 - get the monotonic clock in timespec64 format
963951ed4d3SMartin Schwidefsky * @ts: pointer to timespec variable
964951ed4d3SMartin Schwidefsky *
965951ed4d3SMartin Schwidefsky * The function calculates the monotonic clock from the realtime
966951ed4d3SMartin Schwidefsky * clock and the wall_to_monotonic offset and stores the result
9675322e4c2SJohn Stultz * in normalized timespec64 format in the variable pointed to by @ts.
968951ed4d3SMartin Schwidefsky */
ktime_get_ts64(struct timespec64 * ts)969d6d29896SThomas Gleixner void ktime_get_ts64(struct timespec64 *ts)
970951ed4d3SMartin Schwidefsky {
9713fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
972d6d29896SThomas Gleixner struct timespec64 tomono;
973951ed4d3SMartin Schwidefsky unsigned int seq;
974acc89612SThomas Gleixner u64 nsec;
975951ed4d3SMartin Schwidefsky
976951ed4d3SMartin Schwidefsky WARN_ON(timekeeping_suspended);
977951ed4d3SMartin Schwidefsky
978951ed4d3SMartin Schwidefsky do {
9793fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
980d6d29896SThomas Gleixner ts->tv_sec = tk->xtime_sec;
981876e7881SPeter Zijlstra nsec = timekeeping_get_ns(&tk->tkr_mono);
9824e250fddSJohn Stultz tomono = tk->wall_to_monotonic;
983951ed4d3SMartin Schwidefsky
9843fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
985951ed4d3SMartin Schwidefsky
986d6d29896SThomas Gleixner ts->tv_sec += tomono.tv_sec;
987d6d29896SThomas Gleixner ts->tv_nsec = 0;
988d6d29896SThomas Gleixner timespec64_add_ns(ts, nsec + tomono.tv_nsec);
989951ed4d3SMartin Schwidefsky }
990d6d29896SThomas Gleixner EXPORT_SYMBOL_GPL(ktime_get_ts64);
991951ed4d3SMartin Schwidefsky
9929e3680b1SHeena Sirwani /**
9939e3680b1SHeena Sirwani * ktime_get_seconds - Get the seconds portion of CLOCK_MONOTONIC
9949e3680b1SHeena Sirwani *
9959e3680b1SHeena Sirwani * Returns the seconds portion of CLOCK_MONOTONIC with a single non
9969e3680b1SHeena Sirwani * serialized read. tk->ktime_sec is of type 'unsigned long' so this
9979e3680b1SHeena Sirwani * works on both 32 and 64 bit systems. On 32 bit systems the readout
9989e3680b1SHeena Sirwani * covers ~136 years of uptime which should be enough to prevent
9999e3680b1SHeena Sirwani * premature wrap arounds.
10009e3680b1SHeena Sirwani */
ktime_get_seconds(void)10019e3680b1SHeena Sirwani time64_t ktime_get_seconds(void)
10029e3680b1SHeena Sirwani {
10039e3680b1SHeena Sirwani struct timekeeper *tk = &tk_core.timekeeper;
10049e3680b1SHeena Sirwani
10059e3680b1SHeena Sirwani WARN_ON(timekeeping_suspended);
10069e3680b1SHeena Sirwani return tk->ktime_sec;
10079e3680b1SHeena Sirwani }
10089e3680b1SHeena Sirwani EXPORT_SYMBOL_GPL(ktime_get_seconds);
10099e3680b1SHeena Sirwani
1010dbe7aa62SHeena Sirwani /**
1011dbe7aa62SHeena Sirwani * ktime_get_real_seconds - Get the seconds portion of CLOCK_REALTIME
1012dbe7aa62SHeena Sirwani *
1013aba428a0SChunguang Xu * Returns the wall clock seconds since 1970.
1014dbe7aa62SHeena Sirwani *
1015dbe7aa62SHeena Sirwani * For 64bit systems the fast access to tk->xtime_sec is preserved. On
1016dbe7aa62SHeena Sirwani * 32bit systems the access must be protected with the sequence
1017dbe7aa62SHeena Sirwani * counter to provide "atomic" access to the 64bit tk->xtime_sec
1018dbe7aa62SHeena Sirwani * value.
1019dbe7aa62SHeena Sirwani */
ktime_get_real_seconds(void)1020dbe7aa62SHeena Sirwani time64_t ktime_get_real_seconds(void)
1021dbe7aa62SHeena Sirwani {
1022dbe7aa62SHeena Sirwani struct timekeeper *tk = &tk_core.timekeeper;
1023dbe7aa62SHeena Sirwani time64_t seconds;
1024dbe7aa62SHeena Sirwani unsigned int seq;
1025dbe7aa62SHeena Sirwani
1026dbe7aa62SHeena Sirwani if (IS_ENABLED(CONFIG_64BIT))
1027dbe7aa62SHeena Sirwani return tk->xtime_sec;
1028dbe7aa62SHeena Sirwani
1029dbe7aa62SHeena Sirwani do {
1030dbe7aa62SHeena Sirwani seq = read_seqcount_begin(&tk_core.seq);
1031dbe7aa62SHeena Sirwani seconds = tk->xtime_sec;
1032dbe7aa62SHeena Sirwani
1033dbe7aa62SHeena Sirwani } while (read_seqcount_retry(&tk_core.seq, seq));
1034dbe7aa62SHeena Sirwani
1035dbe7aa62SHeena Sirwani return seconds;
1036dbe7aa62SHeena Sirwani }
1037dbe7aa62SHeena Sirwani EXPORT_SYMBOL_GPL(ktime_get_real_seconds);
1038dbe7aa62SHeena Sirwani
1039dee36654SDengChao /**
1040dee36654SDengChao * __ktime_get_real_seconds - The same as ktime_get_real_seconds
1041dee36654SDengChao * but without the sequence counter protect. This internal function
1042dee36654SDengChao * is called just when timekeeping lock is already held.
1043dee36654SDengChao */
__ktime_get_real_seconds(void)1044865d3a9aSThomas Gleixner noinstr time64_t __ktime_get_real_seconds(void)
1045dee36654SDengChao {
1046dee36654SDengChao struct timekeeper *tk = &tk_core.timekeeper;
1047dee36654SDengChao
1048dee36654SDengChao return tk->xtime_sec;
1049dee36654SDengChao }
1050dee36654SDengChao
10519da0f49cSChristopher S. Hall /**
10529da0f49cSChristopher S. Hall * ktime_get_snapshot - snapshots the realtime/monotonic raw clocks with counter
10539da0f49cSChristopher S. Hall * @systime_snapshot: pointer to struct receiving the system time snapshot
10549da0f49cSChristopher S. Hall */
ktime_get_snapshot(struct system_time_snapshot * systime_snapshot)10559da0f49cSChristopher S. Hall void ktime_get_snapshot(struct system_time_snapshot *systime_snapshot)
10569da0f49cSChristopher S. Hall {
10579da0f49cSChristopher S. Hall struct timekeeper *tk = &tk_core.timekeeper;
1058e1e41b6cSRasmus Villemoes unsigned int seq;
10599da0f49cSChristopher S. Hall ktime_t base_raw;
10609da0f49cSChristopher S. Hall ktime_t base_real;
1061acc89612SThomas Gleixner u64 nsec_raw;
1062acc89612SThomas Gleixner u64 nsec_real;
1063a5a1d1c2SThomas Gleixner u64 now;
10649da0f49cSChristopher S. Hall
1065ba26621eSChristopher S. Hall WARN_ON_ONCE(timekeeping_suspended);
1066ba26621eSChristopher S. Hall
10679da0f49cSChristopher S. Hall do {
10689da0f49cSChristopher S. Hall seq = read_seqcount_begin(&tk_core.seq);
1069ceea5e37SJohn Stultz now = tk_clock_read(&tk->tkr_mono);
1070b2c67cbeSThomas Gleixner systime_snapshot->cs_id = tk->tkr_mono.clock->id;
10712c756febSChristopher S. Hall systime_snapshot->cs_was_changed_seq = tk->cs_was_changed_seq;
10722c756febSChristopher S. Hall systime_snapshot->clock_was_set_seq = tk->clock_was_set_seq;
10739da0f49cSChristopher S. Hall base_real = ktime_add(tk->tkr_mono.base,
10749da0f49cSChristopher S. Hall tk_core.timekeeper.offs_real);
10759da0f49cSChristopher S. Hall base_raw = tk->tkr_raw.base;
10769da0f49cSChristopher S. Hall nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, now);
10779da0f49cSChristopher S. Hall nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, now);
10789da0f49cSChristopher S. Hall } while (read_seqcount_retry(&tk_core.seq, seq));
10799da0f49cSChristopher S. Hall
10809da0f49cSChristopher S. Hall systime_snapshot->cycles = now;
10819da0f49cSChristopher S. Hall systime_snapshot->real = ktime_add_ns(base_real, nsec_real);
10829da0f49cSChristopher S. Hall systime_snapshot->raw = ktime_add_ns(base_raw, nsec_raw);
10839da0f49cSChristopher S. Hall }
10849da0f49cSChristopher S. Hall EXPORT_SYMBOL_GPL(ktime_get_snapshot);
1085dee36654SDengChao
10862c756febSChristopher S. Hall /* Scale base by mult/div checking for overflow */
scale64_check_overflow(u64 mult,u64 div,u64 * base)10872c756febSChristopher S. Hall static int scale64_check_overflow(u64 mult, u64 div, u64 *base)
10882c756febSChristopher S. Hall {
10892c756febSChristopher S. Hall u64 tmp, rem;
10902c756febSChristopher S. Hall
10912c756febSChristopher S. Hall tmp = div64_u64_rem(*base, div, &rem);
10922c756febSChristopher S. Hall
10932c756febSChristopher S. Hall if (((int)sizeof(u64)*8 - fls64(mult) < fls64(tmp)) ||
10942c756febSChristopher S. Hall ((int)sizeof(u64)*8 - fls64(mult) < fls64(rem)))
10952c756febSChristopher S. Hall return -EOVERFLOW;
10962c756febSChristopher S. Hall tmp *= mult;
10972c756febSChristopher S. Hall
10984cbbc3a0SWen Yang rem = div64_u64(rem * mult, div);
10992c756febSChristopher S. Hall *base = tmp + rem;
11002c756febSChristopher S. Hall return 0;
11012c756febSChristopher S. Hall }
11022c756febSChristopher S. Hall
11032c756febSChristopher S. Hall /**
11042c756febSChristopher S. Hall * adjust_historical_crosststamp - adjust crosstimestamp previous to current interval
11052c756febSChristopher S. Hall * @history: Snapshot representing start of history
11062c756febSChristopher S. Hall * @partial_history_cycles: Cycle offset into history (fractional part)
11072c756febSChristopher S. Hall * @total_history_cycles: Total history length in cycles
11082c756febSChristopher S. Hall * @discontinuity: True indicates clock was set on history period
11092c756febSChristopher S. Hall * @ts: Cross timestamp that should be adjusted using
11102c756febSChristopher S. Hall * partial/total ratio
11112c756febSChristopher S. Hall *
11122c756febSChristopher S. Hall * Helper function used by get_device_system_crosststamp() to correct the
11132c756febSChristopher S. Hall * crosstimestamp corresponding to the start of the current interval to the
11142c756febSChristopher S. Hall * system counter value (timestamp point) provided by the driver. The
11152c756febSChristopher S. Hall * total_history_* quantities are the total history starting at the provided
11162c756febSChristopher S. Hall * reference point and ending at the start of the current interval. The cycle
11172c756febSChristopher S. Hall * count between the driver timestamp point and the start of the current
11182c756febSChristopher S. Hall * interval is partial_history_cycles.
11192c756febSChristopher S. Hall */
adjust_historical_crosststamp(struct system_time_snapshot * history,u64 partial_history_cycles,u64 total_history_cycles,bool discontinuity,struct system_device_crosststamp * ts)11202c756febSChristopher S. Hall static int adjust_historical_crosststamp(struct system_time_snapshot *history,
1121a5a1d1c2SThomas Gleixner u64 partial_history_cycles,
1122a5a1d1c2SThomas Gleixner u64 total_history_cycles,
11232c756febSChristopher S. Hall bool discontinuity,
11242c756febSChristopher S. Hall struct system_device_crosststamp *ts)
11252c756febSChristopher S. Hall {
11262c756febSChristopher S. Hall struct timekeeper *tk = &tk_core.timekeeper;
11272c756febSChristopher S. Hall u64 corr_raw, corr_real;
11282c756febSChristopher S. Hall bool interp_forward;
11292c756febSChristopher S. Hall int ret;
11302c756febSChristopher S. Hall
11312c756febSChristopher S. Hall if (total_history_cycles == 0 || partial_history_cycles == 0)
11322c756febSChristopher S. Hall return 0;
11332c756febSChristopher S. Hall
11342c756febSChristopher S. Hall /* Interpolate shortest distance from beginning or end of history */
11355fc63f95SNicholas Mc Guire interp_forward = partial_history_cycles > total_history_cycles / 2;
11362c756febSChristopher S. Hall partial_history_cycles = interp_forward ?
11372c756febSChristopher S. Hall total_history_cycles - partial_history_cycles :
11382c756febSChristopher S. Hall partial_history_cycles;
11392c756febSChristopher S. Hall
11402c756febSChristopher S. Hall /*
11412c756febSChristopher S. Hall * Scale the monotonic raw time delta by:
11422c756febSChristopher S. Hall * partial_history_cycles / total_history_cycles
11432c756febSChristopher S. Hall */
11442c756febSChristopher S. Hall corr_raw = (u64)ktime_to_ns(
11452c756febSChristopher S. Hall ktime_sub(ts->sys_monoraw, history->raw));
11462c756febSChristopher S. Hall ret = scale64_check_overflow(partial_history_cycles,
11472c756febSChristopher S. Hall total_history_cycles, &corr_raw);
11482c756febSChristopher S. Hall if (ret)
11492c756febSChristopher S. Hall return ret;
11502c756febSChristopher S. Hall
11512c756febSChristopher S. Hall /*
11522c756febSChristopher S. Hall * If there is a discontinuity in the history, scale monotonic raw
11532c756febSChristopher S. Hall * correction by:
11542c756febSChristopher S. Hall * mult(real)/mult(raw) yielding the realtime correction
11552c756febSChristopher S. Hall * Otherwise, calculate the realtime correction similar to monotonic
11562c756febSChristopher S. Hall * raw calculation
11572c756febSChristopher S. Hall */
11582c756febSChristopher S. Hall if (discontinuity) {
11592c756febSChristopher S. Hall corr_real = mul_u64_u32_div
11602c756febSChristopher S. Hall (corr_raw, tk->tkr_mono.mult, tk->tkr_raw.mult);
11612c756febSChristopher S. Hall } else {
11622c756febSChristopher S. Hall corr_real = (u64)ktime_to_ns(
11632c756febSChristopher S. Hall ktime_sub(ts->sys_realtime, history->real));
11642c756febSChristopher S. Hall ret = scale64_check_overflow(partial_history_cycles,
11652c756febSChristopher S. Hall total_history_cycles, &corr_real);
11662c756febSChristopher S. Hall if (ret)
11672c756febSChristopher S. Hall return ret;
11682c756febSChristopher S. Hall }
11692c756febSChristopher S. Hall
11702c756febSChristopher S. Hall /* Fixup monotonic raw and real time time values */
11712c756febSChristopher S. Hall if (interp_forward) {
11722c756febSChristopher S. Hall ts->sys_monoraw = ktime_add_ns(history->raw, corr_raw);
11732c756febSChristopher S. Hall ts->sys_realtime = ktime_add_ns(history->real, corr_real);
11742c756febSChristopher S. Hall } else {
11752c756febSChristopher S. Hall ts->sys_monoraw = ktime_sub_ns(ts->sys_monoraw, corr_raw);
11762c756febSChristopher S. Hall ts->sys_realtime = ktime_sub_ns(ts->sys_realtime, corr_real);
11772c756febSChristopher S. Hall }
11782c756febSChristopher S. Hall
11792c756febSChristopher S. Hall return 0;
11802c756febSChristopher S. Hall }
11812c756febSChristopher S. Hall
11822c756febSChristopher S. Hall /*
11839e4d5849SPeter Hilber * timestamp_in_interval - true if ts is chronologically in [start, end]
11849e4d5849SPeter Hilber *
11859e4d5849SPeter Hilber * True if ts occurs chronologically at or after start, and before or at end.
11862c756febSChristopher S. Hall */
timestamp_in_interval(u64 start,u64 end,u64 ts)11879e4d5849SPeter Hilber static bool timestamp_in_interval(u64 start, u64 end, u64 ts)
11882c756febSChristopher S. Hall {
11899e4d5849SPeter Hilber if (ts >= start && ts <= end)
11902c756febSChristopher S. Hall return true;
11919e4d5849SPeter Hilber if (start > end && (ts >= start || ts <= end))
11922c756febSChristopher S. Hall return true;
11932c756febSChristopher S. Hall return false;
11942c756febSChristopher S. Hall }
11952c756febSChristopher S. Hall
11968524070bSjohn stultz /**
11978006c245SChristopher S. Hall * get_device_system_crosststamp - Synchronously capture system/device timestamp
11982c756febSChristopher S. Hall * @get_time_fn: Callback to get simultaneous device time and
11998006c245SChristopher S. Hall * system counter from the device driver
12002c756febSChristopher S. Hall * @ctx: Context passed to get_time_fn()
12012c756febSChristopher S. Hall * @history_begin: Historical reference point used to interpolate system
12022c756febSChristopher S. Hall * time when counter provided by the driver is before the current interval
12038006c245SChristopher S. Hall * @xtstamp: Receives simultaneously captured system and device time
12048006c245SChristopher S. Hall *
12058006c245SChristopher S. Hall * Reads a timestamp from a device and correlates it to system time
12068006c245SChristopher S. Hall */
get_device_system_crosststamp(int (* get_time_fn)(ktime_t * device_time,struct system_counterval_t * sys_counterval,void * ctx),void * ctx,struct system_time_snapshot * history_begin,struct system_device_crosststamp * xtstamp)12078006c245SChristopher S. Hall int get_device_system_crosststamp(int (*get_time_fn)
12088006c245SChristopher S. Hall (ktime_t *device_time,
12098006c245SChristopher S. Hall struct system_counterval_t *sys_counterval,
12108006c245SChristopher S. Hall void *ctx),
12118006c245SChristopher S. Hall void *ctx,
12122c756febSChristopher S. Hall struct system_time_snapshot *history_begin,
12138006c245SChristopher S. Hall struct system_device_crosststamp *xtstamp)
12148006c245SChristopher S. Hall {
12158006c245SChristopher S. Hall struct system_counterval_t system_counterval;
12168006c245SChristopher S. Hall struct timekeeper *tk = &tk_core.timekeeper;
1217a5a1d1c2SThomas Gleixner u64 cycles, now, interval_start;
12186436257bSIngo Molnar unsigned int clock_was_set_seq = 0;
12198006c245SChristopher S. Hall ktime_t base_real, base_raw;
1220acc89612SThomas Gleixner u64 nsec_real, nsec_raw;
12212c756febSChristopher S. Hall u8 cs_was_changed_seq;
1222e1e41b6cSRasmus Villemoes unsigned int seq;
12232c756febSChristopher S. Hall bool do_interp;
12248006c245SChristopher S. Hall int ret;
12258006c245SChristopher S. Hall
12268006c245SChristopher S. Hall do {
12278006c245SChristopher S. Hall seq = read_seqcount_begin(&tk_core.seq);
12288006c245SChristopher S. Hall /*
12298006c245SChristopher S. Hall * Try to synchronously capture device time and a system
12308006c245SChristopher S. Hall * counter value calling back into the device driver
12318006c245SChristopher S. Hall */
12328006c245SChristopher S. Hall ret = get_time_fn(&xtstamp->device, &system_counterval, ctx);
12338006c245SChristopher S. Hall if (ret)
12348006c245SChristopher S. Hall return ret;
12358006c245SChristopher S. Hall
12368006c245SChristopher S. Hall /*
12378006c245SChristopher S. Hall * Verify that the clocksource associated with the captured
12388006c245SChristopher S. Hall * system counter value is the same as the currently installed
12398006c245SChristopher S. Hall * timekeeper clocksource
12408006c245SChristopher S. Hall */
12418006c245SChristopher S. Hall if (tk->tkr_mono.clock != system_counterval.cs)
12428006c245SChristopher S. Hall return -ENODEV;
12432c756febSChristopher S. Hall cycles = system_counterval.cycles;
12442c756febSChristopher S. Hall
12452c756febSChristopher S. Hall /*
12462c756febSChristopher S. Hall * Check whether the system counter value provided by the
12472c756febSChristopher S. Hall * device driver is on the current timekeeping interval.
12482c756febSChristopher S. Hall */
1249ceea5e37SJohn Stultz now = tk_clock_read(&tk->tkr_mono);
12502c756febSChristopher S. Hall interval_start = tk->tkr_mono.cycle_last;
12519e4d5849SPeter Hilber if (!timestamp_in_interval(interval_start, now, cycles)) {
12522c756febSChristopher S. Hall clock_was_set_seq = tk->clock_was_set_seq;
12532c756febSChristopher S. Hall cs_was_changed_seq = tk->cs_was_changed_seq;
12542c756febSChristopher S. Hall cycles = interval_start;
12552c756febSChristopher S. Hall do_interp = true;
12562c756febSChristopher S. Hall } else {
12572c756febSChristopher S. Hall do_interp = false;
12582c756febSChristopher S. Hall }
12598006c245SChristopher S. Hall
12608006c245SChristopher S. Hall base_real = ktime_add(tk->tkr_mono.base,
12618006c245SChristopher S. Hall tk_core.timekeeper.offs_real);
12628006c245SChristopher S. Hall base_raw = tk->tkr_raw.base;
12638006c245SChristopher S. Hall
1264e42c1df3SPeter Hilber nsec_real = timekeeping_cycles_to_ns(&tk->tkr_mono, cycles);
1265e42c1df3SPeter Hilber nsec_raw = timekeeping_cycles_to_ns(&tk->tkr_raw, cycles);
12668006c245SChristopher S. Hall } while (read_seqcount_retry(&tk_core.seq, seq));
12678006c245SChristopher S. Hall
12688006c245SChristopher S. Hall xtstamp->sys_realtime = ktime_add_ns(base_real, nsec_real);
12698006c245SChristopher S. Hall xtstamp->sys_monoraw = ktime_add_ns(base_raw, nsec_raw);
12702c756febSChristopher S. Hall
12712c756febSChristopher S. Hall /*
12722c756febSChristopher S. Hall * Interpolate if necessary, adjusting back from the start of the
12732c756febSChristopher S. Hall * current interval
12742c756febSChristopher S. Hall */
12752c756febSChristopher S. Hall if (do_interp) {
1276a5a1d1c2SThomas Gleixner u64 partial_history_cycles, total_history_cycles;
12772c756febSChristopher S. Hall bool discontinuity;
12782c756febSChristopher S. Hall
12792c756febSChristopher S. Hall /*
12809e4d5849SPeter Hilber * Check that the counter value is not before the provided
12812c756febSChristopher S. Hall * history reference and that the history doesn't cross a
12822c756febSChristopher S. Hall * clocksource change
12832c756febSChristopher S. Hall */
12842c756febSChristopher S. Hall if (!history_begin ||
12859e4d5849SPeter Hilber !timestamp_in_interval(history_begin->cycles,
12869e4d5849SPeter Hilber cycles, system_counterval.cycles) ||
12872c756febSChristopher S. Hall history_begin->cs_was_changed_seq != cs_was_changed_seq)
12882c756febSChristopher S. Hall return -EINVAL;
12892c756febSChristopher S. Hall partial_history_cycles = cycles - system_counterval.cycles;
12902c756febSChristopher S. Hall total_history_cycles = cycles - history_begin->cycles;
12912c756febSChristopher S. Hall discontinuity =
12922c756febSChristopher S. Hall history_begin->clock_was_set_seq != clock_was_set_seq;
12932c756febSChristopher S. Hall
12942c756febSChristopher S. Hall ret = adjust_historical_crosststamp(history_begin,
12952c756febSChristopher S. Hall partial_history_cycles,
12962c756febSChristopher S. Hall total_history_cycles,
12972c756febSChristopher S. Hall discontinuity, xtstamp);
12982c756febSChristopher S. Hall if (ret)
12992c756febSChristopher S. Hall return ret;
13002c756febSChristopher S. Hall }
13012c756febSChristopher S. Hall
13028006c245SChristopher S. Hall return 0;
13038006c245SChristopher S. Hall }
13048006c245SChristopher S. Hall EXPORT_SYMBOL_GPL(get_device_system_crosststamp);
13058006c245SChristopher S. Hall
13068006c245SChristopher S. Hall /**
130721f7eca5Spang.xunlei * do_settimeofday64 - Sets the time of day.
130821f7eca5Spang.xunlei * @ts: pointer to the timespec64 variable containing the new time
13098524070bSjohn stultz *
13108524070bSjohn stultz * Sets the time of day to the new time and update NTP and notify hrtimers
13118524070bSjohn stultz */
do_settimeofday64(const struct timespec64 * ts)131221f7eca5Spang.xunlei int do_settimeofday64(const struct timespec64 *ts)
13138524070bSjohn stultz {
13143fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
131521f7eca5Spang.xunlei struct timespec64 ts_delta, xt;
131692c1d3edSJohn Stultz unsigned long flags;
1317e1d7ba87SWang YanQing int ret = 0;
13188524070bSjohn stultz
13197a8e61f8SThomas Gleixner if (!timespec64_valid_settod(ts))
13208524070bSjohn stultz return -EINVAL;
13218524070bSjohn stultz
13229a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
13233fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
13248524070bSjohn stultz
13254e250fddSJohn Stultz timekeeping_forward_now(tk);
13268524070bSjohn stultz
13274e250fddSJohn Stultz xt = tk_xtime(tk);
13284e8c11b6SYu Liao ts_delta = timespec64_sub(*ts, xt);
13291e75fa8bSJohn Stultz
1330e1d7ba87SWang YanQing if (timespec64_compare(&tk->wall_to_monotonic, &ts_delta) > 0) {
1331e1d7ba87SWang YanQing ret = -EINVAL;
1332e1d7ba87SWang YanQing goto out;
1333e1d7ba87SWang YanQing }
1334e1d7ba87SWang YanQing
13357d489d15SJohn Stultz tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, ts_delta));
13368524070bSjohn stultz
133721f7eca5Spang.xunlei tk_set_xtime(tk, ts);
1338e1d7ba87SWang YanQing out:
1339780427f0SDavid Vrabel timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
13408524070bSjohn stultz
13413fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
13429a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
13438524070bSjohn stultz
134417a1b882SThomas Gleixner /* Signal hrtimers about time change */
134517a1b882SThomas Gleixner clock_was_set(CLOCK_SET_WALL);
13468524070bSjohn stultz
1347b8ac29b4SJason A. Donenfeld if (!ret) {
13482d87a067SOndrej Mosnacek audit_tk_injoffset(ts_delta);
1349b8ac29b4SJason A. Donenfeld add_device_randomness(ts, sizeof(*ts));
1350b8ac29b4SJason A. Donenfeld }
13512d87a067SOndrej Mosnacek
1352e1d7ba87SWang YanQing return ret;
13538524070bSjohn stultz }
135421f7eca5Spang.xunlei EXPORT_SYMBOL(do_settimeofday64);
13558524070bSjohn stultz
1356c528f7c6SJohn Stultz /**
1357c528f7c6SJohn Stultz * timekeeping_inject_offset - Adds or subtracts from the current time.
13586e5a9190SAlex Shi * @ts: Pointer to the timespec variable containing the offset
1359c528f7c6SJohn Stultz *
1360c528f7c6SJohn Stultz * Adds or subtracts an offset value from the current time.
1361c528f7c6SJohn Stultz */
timekeeping_inject_offset(const struct timespec64 * ts)1362985e6950SOndrej Mosnacek static int timekeeping_inject_offset(const struct timespec64 *ts)
1363c528f7c6SJohn Stultz {
13643fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
136592c1d3edSJohn Stultz unsigned long flags;
13661572fa03SArnd Bergmann struct timespec64 tmp;
13674e8b1452SJohn Stultz int ret = 0;
1368c528f7c6SJohn Stultz
13691572fa03SArnd Bergmann if (ts->tv_nsec < 0 || ts->tv_nsec >= NSEC_PER_SEC)
1370c528f7c6SJohn Stultz return -EINVAL;
1371c528f7c6SJohn Stultz
13729a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
13733fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
1374c528f7c6SJohn Stultz
13754e250fddSJohn Stultz timekeeping_forward_now(tk);
1376c528f7c6SJohn Stultz
13774e8b1452SJohn Stultz /* Make sure the proposed value is valid */
13781572fa03SArnd Bergmann tmp = timespec64_add(tk_xtime(tk), *ts);
13791572fa03SArnd Bergmann if (timespec64_compare(&tk->wall_to_monotonic, ts) > 0 ||
13807a8e61f8SThomas Gleixner !timespec64_valid_settod(&tmp)) {
13814e8b1452SJohn Stultz ret = -EINVAL;
13824e8b1452SJohn Stultz goto error;
13834e8b1452SJohn Stultz }
13841e75fa8bSJohn Stultz
13851572fa03SArnd Bergmann tk_xtime_add(tk, ts);
13861572fa03SArnd Bergmann tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *ts));
1387c528f7c6SJohn Stultz
13884e8b1452SJohn Stultz error: /* even if we error out, we forwarded the time, so call update */
1389780427f0SDavid Vrabel timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1390c528f7c6SJohn Stultz
13913fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
13929a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1393c528f7c6SJohn Stultz
139417a1b882SThomas Gleixner /* Signal hrtimers about time change */
139517a1b882SThomas Gleixner clock_was_set(CLOCK_SET_WALL);
1396c528f7c6SJohn Stultz
13974e8b1452SJohn Stultz return ret;
1398c528f7c6SJohn Stultz }
1399e0956dccSArnd Bergmann
1400e0956dccSArnd Bergmann /*
1401e0956dccSArnd Bergmann * Indicates if there is an offset between the system clock and the hardware
1402e0956dccSArnd Bergmann * clock/persistent clock/rtc.
1403e0956dccSArnd Bergmann */
1404e0956dccSArnd Bergmann int persistent_clock_is_local;
1405e0956dccSArnd Bergmann
1406e0956dccSArnd Bergmann /*
1407e0956dccSArnd Bergmann * Adjust the time obtained from the CMOS to be UTC time instead of
1408e0956dccSArnd Bergmann * local time.
1409e0956dccSArnd Bergmann *
1410e0956dccSArnd Bergmann * This is ugly, but preferable to the alternatives. Otherwise we
1411e0956dccSArnd Bergmann * would either need to write a program to do it in /etc/rc (and risk
1412e0956dccSArnd Bergmann * confusion if the program gets run more than once; it would also be
1413e0956dccSArnd Bergmann * hard to make the program warp the clock precisely n hours) or
1414e0956dccSArnd Bergmann * compile in the timezone information into the kernel. Bad, bad....
1415e0956dccSArnd Bergmann *
1416e0956dccSArnd Bergmann * - TYT, 1992-01-01
1417e0956dccSArnd Bergmann *
1418e0956dccSArnd Bergmann * The best thing to do is to keep the CMOS clock in universal time (UTC)
1419e0956dccSArnd Bergmann * as real UNIX machines always do it. This avoids all headaches about
1420e0956dccSArnd Bergmann * daylight saving times and warping kernel clocks.
1421e0956dccSArnd Bergmann */
timekeeping_warp_clock(void)1422e0956dccSArnd Bergmann void timekeeping_warp_clock(void)
1423e0956dccSArnd Bergmann {
1424e0956dccSArnd Bergmann if (sys_tz.tz_minuteswest != 0) {
14251572fa03SArnd Bergmann struct timespec64 adjust;
1426e0956dccSArnd Bergmann
1427e0956dccSArnd Bergmann persistent_clock_is_local = 1;
1428e0956dccSArnd Bergmann adjust.tv_sec = sys_tz.tz_minuteswest * 60;
1429e0956dccSArnd Bergmann adjust.tv_nsec = 0;
1430e0956dccSArnd Bergmann timekeeping_inject_offset(&adjust);
1431e0956dccSArnd Bergmann }
1432e0956dccSArnd Bergmann }
1433c528f7c6SJohn Stultz
1434199d280cSAlex Shi /*
143540d9f827SStephen Boyd * __timekeeping_set_tai_offset - Sets the TAI offset from UTC and monotonic
1436cc244ddaSJohn Stultz */
__timekeeping_set_tai_offset(struct timekeeper * tk,s32 tai_offset)1437dd5d70e8SFengguang Wu static void __timekeeping_set_tai_offset(struct timekeeper *tk, s32 tai_offset)
1438cc244ddaSJohn Stultz {
1439cc244ddaSJohn Stultz tk->tai_offset = tai_offset;
144004005f60SJohn Stultz tk->offs_tai = ktime_add(tk->offs_real, ktime_set(tai_offset, 0));
1441cc244ddaSJohn Stultz }
1442cc244ddaSJohn Stultz
1443199d280cSAlex Shi /*
14448524070bSjohn stultz * change_clocksource - Swaps clocksources if a new one is available
14458524070bSjohn stultz *
14468524070bSjohn stultz * Accumulates current time interval and initializes new clocksource
14478524070bSjohn stultz */
change_clocksource(void * data)144875c5158fSMartin Schwidefsky static int change_clocksource(void *data)
14498524070bSjohn stultz {
14503fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
1451d4c7c288SNiklas Söderlund struct clocksource *new, *old = NULL;
1452f695cf94SJohn Stultz unsigned long flags;
1453d4c7c288SNiklas Söderlund bool change = false;
14548524070bSjohn stultz
145575c5158fSMartin Schwidefsky new = (struct clocksource *) data;
14568524070bSjohn stultz
145709ac369cSThomas Gleixner /*
145809ac369cSThomas Gleixner * If the cs is in module, get a module reference. Succeeds
145909ac369cSThomas Gleixner * for built-in code (owner == NULL) as well.
146009ac369cSThomas Gleixner */
146109ac369cSThomas Gleixner if (try_module_get(new->owner)) {
1462d4c7c288SNiklas Söderlund if (!new->enable || new->enable(new) == 0)
1463d4c7c288SNiklas Söderlund change = true;
1464d4c7c288SNiklas Söderlund else
146509ac369cSThomas Gleixner module_put(new->owner);
146609ac369cSThomas Gleixner }
1467d4c7c288SNiklas Söderlund
1468d4c7c288SNiklas Söderlund raw_spin_lock_irqsave(&timekeeper_lock, flags);
1469d4c7c288SNiklas Söderlund write_seqcount_begin(&tk_core.seq);
1470d4c7c288SNiklas Söderlund
1471d4c7c288SNiklas Söderlund timekeeping_forward_now(tk);
1472d4c7c288SNiklas Söderlund
1473d4c7c288SNiklas Söderlund if (change) {
1474d4c7c288SNiklas Söderlund old = tk->tkr_mono.clock;
1475d4c7c288SNiklas Söderlund tk_setup_internals(tk, new);
147675c5158fSMartin Schwidefsky }
1477d4c7c288SNiklas Söderlund
1478780427f0SDavid Vrabel timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1479f695cf94SJohn Stultz
14803fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
14819a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1482f695cf94SJohn Stultz
1483d4c7c288SNiklas Söderlund if (old) {
1484d4c7c288SNiklas Söderlund if (old->disable)
1485d4c7c288SNiklas Söderlund old->disable(old);
1486d4c7c288SNiklas Söderlund
1487d4c7c288SNiklas Söderlund module_put(old->owner);
1488d4c7c288SNiklas Söderlund }
1489d4c7c288SNiklas Söderlund
149075c5158fSMartin Schwidefsky return 0;
149175c5158fSMartin Schwidefsky }
14924614e6adSMagnus Damm
149375c5158fSMartin Schwidefsky /**
149475c5158fSMartin Schwidefsky * timekeeping_notify - Install a new clock source
149575c5158fSMartin Schwidefsky * @clock: pointer to the clock source
149675c5158fSMartin Schwidefsky *
149775c5158fSMartin Schwidefsky * This function is called from clocksource.c after a new, better clock
149875c5158fSMartin Schwidefsky * source has been registered. The caller holds the clocksource_mutex.
149975c5158fSMartin Schwidefsky */
timekeeping_notify(struct clocksource * clock)1500ba919d1cSThomas Gleixner int timekeeping_notify(struct clocksource *clock)
150175c5158fSMartin Schwidefsky {
15023fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
15034e250fddSJohn Stultz
1504876e7881SPeter Zijlstra if (tk->tkr_mono.clock == clock)
1505ba919d1cSThomas Gleixner return 0;
150675c5158fSMartin Schwidefsky stop_machine(change_clocksource, clock, NULL);
15078524070bSjohn stultz tick_clock_notify();
1508876e7881SPeter Zijlstra return tk->tkr_mono.clock == clock ? 0 : -1;
15098524070bSjohn stultz }
151075c5158fSMartin Schwidefsky
1511a40f262cSThomas Gleixner /**
1512fb7fcc96SArnd Bergmann * ktime_get_raw_ts64 - Returns the raw monotonic time in a timespec
1513cdba2ec5SJohn Stultz * @ts: pointer to the timespec64 to be set
15142d42244aSJohn Stultz *
15152d42244aSJohn Stultz * Returns the raw monotonic time (completely un-modified by ntp)
15162d42244aSJohn Stultz */
ktime_get_raw_ts64(struct timespec64 * ts)1517fb7fcc96SArnd Bergmann void ktime_get_raw_ts64(struct timespec64 *ts)
15182d42244aSJohn Stultz {
15193fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
1520e1e41b6cSRasmus Villemoes unsigned int seq;
1521acc89612SThomas Gleixner u64 nsecs;
15222d42244aSJohn Stultz
15232d42244aSJohn Stultz do {
15243fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
1525fc6eead7SJohn Stultz ts->tv_sec = tk->raw_sec;
15264a4ad80dSPeter Zijlstra nsecs = timekeeping_get_ns(&tk->tkr_raw);
15272d42244aSJohn Stultz
15283fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
15292d42244aSJohn Stultz
1530fc6eead7SJohn Stultz ts->tv_nsec = 0;
1531fc6eead7SJohn Stultz timespec64_add_ns(ts, nsecs);
15322d42244aSJohn Stultz }
1533fb7fcc96SArnd Bergmann EXPORT_SYMBOL(ktime_get_raw_ts64);
1534cdba2ec5SJohn Stultz
15352d42244aSJohn Stultz
15362d42244aSJohn Stultz /**
1537cf4fc6cbSLi Zefan * timekeeping_valid_for_hres - Check if timekeeping is suitable for hres
15388524070bSjohn stultz */
timekeeping_valid_for_hres(void)1539cf4fc6cbSLi Zefan int timekeeping_valid_for_hres(void)
15408524070bSjohn stultz {
15413fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
1542e1e41b6cSRasmus Villemoes unsigned int seq;
15438524070bSjohn stultz int ret;
15448524070bSjohn stultz
15458524070bSjohn stultz do {
15463fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
15478524070bSjohn stultz
1548876e7881SPeter Zijlstra ret = tk->tkr_mono.clock->flags & CLOCK_SOURCE_VALID_FOR_HRES;
15498524070bSjohn stultz
15503fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
15518524070bSjohn stultz
15528524070bSjohn stultz return ret;
15538524070bSjohn stultz }
15548524070bSjohn stultz
15558524070bSjohn stultz /**
155698962465SJon Hunter * timekeeping_max_deferment - Returns max time the clocksource can be deferred
155798962465SJon Hunter */
timekeeping_max_deferment(void)155898962465SJon Hunter u64 timekeeping_max_deferment(void)
155998962465SJon Hunter {
15603fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
1561e1e41b6cSRasmus Villemoes unsigned int seq;
156270471f2fSJohn Stultz u64 ret;
156342e71e81SJohn Stultz
156470471f2fSJohn Stultz do {
15653fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
156670471f2fSJohn Stultz
1567876e7881SPeter Zijlstra ret = tk->tkr_mono.clock->max_idle_ns;
156870471f2fSJohn Stultz
15693fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
157070471f2fSJohn Stultz
157170471f2fSJohn Stultz return ret;
157298962465SJon Hunter }
157398962465SJon Hunter
157498962465SJon Hunter /**
157592661788SArnd Bergmann * read_persistent_clock64 - Return time from the persistent clock.
15766e5a9190SAlex Shi * @ts: Pointer to the storage for the readout value
15778524070bSjohn stultz *
15788524070bSjohn stultz * Weak dummy function for arches that do not yet support it.
1579d4f587c6SMartin Schwidefsky * Reads the time from the battery backed persistent clock.
1580d4f587c6SMartin Schwidefsky * Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
15818524070bSjohn stultz *
15828524070bSjohn stultz * XXX - Do be sure to remove it once all arches implement it.
15838524070bSjohn stultz */
read_persistent_clock64(struct timespec64 * ts)158492661788SArnd Bergmann void __weak read_persistent_clock64(struct timespec64 *ts)
15858524070bSjohn stultz {
1586d4f587c6SMartin Schwidefsky ts->tv_sec = 0;
1587d4f587c6SMartin Schwidefsky ts->tv_nsec = 0;
15888524070bSjohn stultz }
15898524070bSjohn stultz
159023970e38SMartin Schwidefsky /**
15913eca9937SPavel Tatashin * read_persistent_wall_and_boot_offset - Read persistent clock, and also offset
15923eca9937SPavel Tatashin * from the boot.
1593f3cb8080SRandy Dunlap * @wall_time: current time as returned by persistent clock
1594f3cb8080SRandy Dunlap * @boot_offset: offset that is defined as wall_time - boot_time
159523970e38SMartin Schwidefsky *
159623970e38SMartin Schwidefsky * Weak dummy function for arches that do not yet support it.
159729efc461SAlex Shi *
15984b1b7f80SPavel Tatashin * The default function calculates offset based on the current value of
15994b1b7f80SPavel Tatashin * local_clock(). This way architectures that support sched_clock() but don't
16004b1b7f80SPavel Tatashin * support dedicated boot time clock will provide the best estimate of the
16014b1b7f80SPavel Tatashin * boot time.
160223970e38SMartin Schwidefsky */
16033eca9937SPavel Tatashin void __weak __init
read_persistent_wall_and_boot_offset(struct timespec64 * wall_time,struct timespec64 * boot_offset)16043eca9937SPavel Tatashin read_persistent_wall_and_boot_offset(struct timespec64 *wall_time,
16053eca9937SPavel Tatashin struct timespec64 *boot_offset)
160623970e38SMartin Schwidefsky {
16073eca9937SPavel Tatashin read_persistent_clock64(wall_time);
16084b1b7f80SPavel Tatashin *boot_offset = ns_to_timespec64(local_clock());
160923970e38SMartin Schwidefsky }
161023970e38SMartin Schwidefsky
1611f473e5f4SMukesh Ojha /*
1612f473e5f4SMukesh Ojha * Flag reflecting whether timekeeping_resume() has injected sleeptime.
1613f473e5f4SMukesh Ojha *
1614f473e5f4SMukesh Ojha * The flag starts of false and is only set when a suspend reaches
1615f473e5f4SMukesh Ojha * timekeeping_suspend(), timekeeping_resume() sets it to false when the
1616f473e5f4SMukesh Ojha * timekeeper clocksource is not stopping across suspend and has been
1617f473e5f4SMukesh Ojha * used to update sleep time. If the timekeeper clocksource has stopped
1618f473e5f4SMukesh Ojha * then the flag stays true and is used by the RTC resume code to decide
1619f473e5f4SMukesh Ojha * whether sleeptime must be injected and if so the flag gets false then.
1620f473e5f4SMukesh Ojha *
1621f473e5f4SMukesh Ojha * If a suspend fails before reaching timekeeping_resume() then the flag
1622f473e5f4SMukesh Ojha * stays false and prevents erroneous sleeptime injection.
1623f473e5f4SMukesh Ojha */
1624f473e5f4SMukesh Ojha static bool suspend_timing_needed;
16250fa88cb4SXunlei Pang
16260fa88cb4SXunlei Pang /* Flag for if there is a persistent clock on this platform */
16270fa88cb4SXunlei Pang static bool persistent_clock_exists;
16280fa88cb4SXunlei Pang
16298524070bSjohn stultz /*
16308524070bSjohn stultz * timekeeping_init - Initializes the clocksource and common timekeeping values
16318524070bSjohn stultz */
timekeeping_init(void)16328524070bSjohn stultz void __init timekeeping_init(void)
16338524070bSjohn stultz {
16343eca9937SPavel Tatashin struct timespec64 wall_time, boot_offset, wall_to_mono;
16353fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
1636155ec602SMartin Schwidefsky struct clocksource *clock;
16378524070bSjohn stultz unsigned long flags;
1638d4f587c6SMartin Schwidefsky
16393eca9937SPavel Tatashin read_persistent_wall_and_boot_offset(&wall_time, &boot_offset);
16407a8e61f8SThomas Gleixner if (timespec64_valid_settod(&wall_time) &&
16413eca9937SPavel Tatashin timespec64_to_ns(&wall_time) > 0) {
16420fa88cb4SXunlei Pang persistent_clock_exists = true;
1643684ad537SPavel Tatashin } else if (timespec64_to_ns(&wall_time) != 0) {
16443eca9937SPavel Tatashin pr_warn("Persistent clock returned invalid value");
16453eca9937SPavel Tatashin wall_time = (struct timespec64){0};
16464e8b1452SJohn Stultz }
16478524070bSjohn stultz
16483eca9937SPavel Tatashin if (timespec64_compare(&wall_time, &boot_offset) < 0)
16493eca9937SPavel Tatashin boot_offset = (struct timespec64){0};
16503eca9937SPavel Tatashin
16513eca9937SPavel Tatashin /*
16523eca9937SPavel Tatashin * We want set wall_to_mono, so the following is true:
16533eca9937SPavel Tatashin * wall time + wall_to_mono = boot time
16543eca9937SPavel Tatashin */
16553eca9937SPavel Tatashin wall_to_mono = timespec64_sub(boot_offset, wall_time);
16563eca9937SPavel Tatashin
16579a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
16583fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
165906c017fdSJohn Stultz ntp_init();
166006c017fdSJohn Stultz
1661f1b82746SMartin Schwidefsky clock = clocksource_default_clock();
1662a0f7d48bSMartin Schwidefsky if (clock->enable)
1663a0f7d48bSMartin Schwidefsky clock->enable(clock);
16644e250fddSJohn Stultz tk_setup_internals(tk, clock);
16658524070bSjohn stultz
16663eca9937SPavel Tatashin tk_set_xtime(tk, &wall_time);
1667fc6eead7SJohn Stultz tk->raw_sec = 0;
16681e75fa8bSJohn Stultz
16693eca9937SPavel Tatashin tk_set_wall_to_mono(tk, wall_to_mono);
16706d0ef903SJohn Stultz
167156fd16caSThomas Gleixner timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
167248cdc135SThomas Gleixner
16733fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
16749a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
16758524070bSjohn stultz }
16768524070bSjohn stultz
1677264bb3f7SXunlei Pang /* time in seconds when suspend began for persistent clock */
16787d489d15SJohn Stultz static struct timespec64 timekeeping_suspend_time;
16798524070bSjohn stultz
16808524070bSjohn stultz /**
1681304529b1SJohn Stultz * __timekeeping_inject_sleeptime - Internal function to add sleep interval
16826e5a9190SAlex Shi * @tk: Pointer to the timekeeper to be updated
16836e5a9190SAlex Shi * @delta: Pointer to the delta value in timespec64 format
1684304529b1SJohn Stultz *
1685304529b1SJohn Stultz * Takes a timespec offset measuring a suspend interval and properly
1686304529b1SJohn Stultz * adds the sleep offset to the timekeeping variables.
1687304529b1SJohn Stultz */
__timekeeping_inject_sleeptime(struct timekeeper * tk,const struct timespec64 * delta)1688f726a697SJohn Stultz static void __timekeeping_inject_sleeptime(struct timekeeper *tk,
1689985e6950SOndrej Mosnacek const struct timespec64 *delta)
1690304529b1SJohn Stultz {
16917d489d15SJohn Stultz if (!timespec64_valid_strict(delta)) {
16926d9bcb62SJohn Stultz printk_deferred(KERN_WARNING
16936d9bcb62SJohn Stultz "__timekeeping_inject_sleeptime: Invalid "
1694cb5de2f8SJohn Stultz "sleep delta value!\n");
1695cb5de2f8SJohn Stultz return;
1696cb5de2f8SJohn Stultz }
1697f726a697SJohn Stultz tk_xtime_add(tk, delta);
1698a3ed0e43SThomas Gleixner tk_set_wall_to_mono(tk, timespec64_sub(tk->wall_to_monotonic, *delta));
169947da70d3SThomas Gleixner tk_update_sleep_time(tk, timespec64_to_ktime(*delta));
17005c83545fSColin Cross tk_debug_account_sleep_time(delta);
1701304529b1SJohn Stultz }
1702304529b1SJohn Stultz
17037f298139SXunlei Pang #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_RTC_HCTOSYS_DEVICE)
1704f3cb8080SRandy Dunlap /*
17050fa88cb4SXunlei Pang * We have three kinds of time sources to use for sleep time
17060fa88cb4SXunlei Pang * injection, the preference order is:
17070fa88cb4SXunlei Pang * 1) non-stop clocksource
17080fa88cb4SXunlei Pang * 2) persistent clock (ie: RTC accessible when irqs are off)
17090fa88cb4SXunlei Pang * 3) RTC
17100fa88cb4SXunlei Pang *
17110fa88cb4SXunlei Pang * 1) and 2) are used by timekeeping, 3) by RTC subsystem.
17120fa88cb4SXunlei Pang * If system has neither 1) nor 2), 3) will be used finally.
17130fa88cb4SXunlei Pang *
17140fa88cb4SXunlei Pang *
17150fa88cb4SXunlei Pang * If timekeeping has injected sleeptime via either 1) or 2),
17160fa88cb4SXunlei Pang * 3) becomes needless, so in this case we don't need to call
17170fa88cb4SXunlei Pang * rtc_resume(), and this is what timekeeping_rtc_skipresume()
17180fa88cb4SXunlei Pang * means.
17190fa88cb4SXunlei Pang */
timekeeping_rtc_skipresume(void)17200fa88cb4SXunlei Pang bool timekeeping_rtc_skipresume(void)
17210fa88cb4SXunlei Pang {
1722f473e5f4SMukesh Ojha return !suspend_timing_needed;
17230fa88cb4SXunlei Pang }
17240fa88cb4SXunlei Pang
1725f3cb8080SRandy Dunlap /*
17260fa88cb4SXunlei Pang * 1) can be determined whether to use or not only when doing
17270fa88cb4SXunlei Pang * timekeeping_resume() which is invoked after rtc_suspend(),
17280fa88cb4SXunlei Pang * so we can't skip rtc_suspend() surely if system has 1).
17290fa88cb4SXunlei Pang *
17300fa88cb4SXunlei Pang * But if system has 2), 2) will definitely be used, so in this
17310fa88cb4SXunlei Pang * case we don't need to call rtc_suspend(), and this is what
17320fa88cb4SXunlei Pang * timekeeping_rtc_skipsuspend() means.
17330fa88cb4SXunlei Pang */
timekeeping_rtc_skipsuspend(void)17340fa88cb4SXunlei Pang bool timekeeping_rtc_skipsuspend(void)
17350fa88cb4SXunlei Pang {
17360fa88cb4SXunlei Pang return persistent_clock_exists;
17370fa88cb4SXunlei Pang }
17380fa88cb4SXunlei Pang
17390fa88cb4SXunlei Pang /**
174004d90890Spang.xunlei * timekeeping_inject_sleeptime64 - Adds suspend interval to timeekeeping values
174104d90890Spang.xunlei * @delta: pointer to a timespec64 delta value
1742304529b1SJohn Stultz *
17432ee96632SXunlei Pang * This hook is for architectures that cannot support read_persistent_clock64
1744304529b1SJohn Stultz * because their RTC/persistent clock is only accessible when irqs are enabled.
17450fa88cb4SXunlei Pang * and also don't have an effective nonstop clocksource.
1746304529b1SJohn Stultz *
1747304529b1SJohn Stultz * This function should only be called by rtc_resume(), and allows
1748304529b1SJohn Stultz * a suspend offset to be injected into the timekeeping values.
1749304529b1SJohn Stultz */
timekeeping_inject_sleeptime64(const struct timespec64 * delta)1750985e6950SOndrej Mosnacek void timekeeping_inject_sleeptime64(const struct timespec64 *delta)
1751304529b1SJohn Stultz {
17523fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
175392c1d3edSJohn Stultz unsigned long flags;
1754304529b1SJohn Stultz
17559a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
17563fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
175770471f2fSJohn Stultz
1758f473e5f4SMukesh Ojha suspend_timing_needed = false;
1759f473e5f4SMukesh Ojha
17604e250fddSJohn Stultz timekeeping_forward_now(tk);
1761304529b1SJohn Stultz
176204d90890Spang.xunlei __timekeeping_inject_sleeptime(tk, delta);
1763304529b1SJohn Stultz
1764780427f0SDavid Vrabel timekeeping_update(tk, TK_CLEAR_NTP | TK_MIRROR | TK_CLOCK_WAS_SET);
1765304529b1SJohn Stultz
17663fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
17679a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
1768304529b1SJohn Stultz
176917a1b882SThomas Gleixner /* Signal hrtimers about time change */
177017a1b882SThomas Gleixner clock_was_set(CLOCK_SET_WALL | CLOCK_SET_BOOT);
1771304529b1SJohn Stultz }
17727f298139SXunlei Pang #endif
1773304529b1SJohn Stultz
1774304529b1SJohn Stultz /**
17758524070bSjohn stultz * timekeeping_resume - Resumes the generic timekeeping subsystem.
17768524070bSjohn stultz */
timekeeping_resume(void)1777124cf911SRafael J. Wysocki void timekeeping_resume(void)
17788524070bSjohn stultz {
17793fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
1780876e7881SPeter Zijlstra struct clocksource *clock = tk->tkr_mono.clock;
178192c1d3edSJohn Stultz unsigned long flags;
17827d489d15SJohn Stultz struct timespec64 ts_new, ts_delta;
178339232ed5SBaolin Wang u64 cycle_now, nsec;
1784f473e5f4SMukesh Ojha bool inject_sleeptime = false;
1785d4f587c6SMartin Schwidefsky
17862ee96632SXunlei Pang read_persistent_clock64(&ts_new);
17878524070bSjohn stultz
1788adc78e6bSRafael J. Wysocki clockevents_resume();
1789d10ff3fbSThomas Gleixner clocksource_resume();
1790d10ff3fbSThomas Gleixner
17919a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
17923fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
17938524070bSjohn stultz
1794e445cf1cSFeng Tang /*
1795e445cf1cSFeng Tang * After system resumes, we need to calculate the suspended time and
1796e445cf1cSFeng Tang * compensate it for the OS time. There are 3 sources that could be
1797e445cf1cSFeng Tang * used: Nonstop clocksource during suspend, persistent clock and rtc
1798e445cf1cSFeng Tang * device.
1799e445cf1cSFeng Tang *
1800e445cf1cSFeng Tang * One specific platform may have 1 or 2 or all of them, and the
1801e445cf1cSFeng Tang * preference will be:
1802e445cf1cSFeng Tang * suspend-nonstop clocksource -> persistent clock -> rtc
1803e445cf1cSFeng Tang * The less preferred source will only be tried if there is no better
1804e445cf1cSFeng Tang * usable source. The rtc part is handled separately in rtc core code.
1805e445cf1cSFeng Tang */
1806ceea5e37SJohn Stultz cycle_now = tk_clock_read(&tk->tkr_mono);
180739232ed5SBaolin Wang nsec = clocksource_stop_suspend_timing(clock, cycle_now);
180839232ed5SBaolin Wang if (nsec > 0) {
18097d489d15SJohn Stultz ts_delta = ns_to_timespec64(nsec);
1810f473e5f4SMukesh Ojha inject_sleeptime = true;
18117d489d15SJohn Stultz } else if (timespec64_compare(&ts_new, &timekeeping_suspend_time) > 0) {
18127d489d15SJohn Stultz ts_delta = timespec64_sub(ts_new, timekeeping_suspend_time);
1813f473e5f4SMukesh Ojha inject_sleeptime = true;
1814e445cf1cSFeng Tang }
1815e445cf1cSFeng Tang
1816f473e5f4SMukesh Ojha if (inject_sleeptime) {
1817f473e5f4SMukesh Ojha suspend_timing_needed = false;
1818e445cf1cSFeng Tang __timekeeping_inject_sleeptime(tk, &ts_delta);
1819f473e5f4SMukesh Ojha }
1820e445cf1cSFeng Tang
1821e445cf1cSFeng Tang /* Re-base the last cycle value */
1822876e7881SPeter Zijlstra tk->tkr_mono.cycle_last = cycle_now;
18234a4ad80dSPeter Zijlstra tk->tkr_raw.cycle_last = cycle_now;
18244a4ad80dSPeter Zijlstra
18254e250fddSJohn Stultz tk->ntp_error = 0;
18268524070bSjohn stultz timekeeping_suspended = 0;
1827780427f0SDavid Vrabel timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
18283fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
18299a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
18308524070bSjohn stultz
18318524070bSjohn stultz touch_softlockup_watchdog();
18328524070bSjohn stultz
1833a761a67fSThomas Gleixner /* Resume the clockevent device(s) and hrtimers */
18344ffee521SThomas Gleixner tick_resume();
1835a761a67fSThomas Gleixner /* Notify timerfd as resume is equivalent to clock_was_set() */
1836a761a67fSThomas Gleixner timerfd_resume();
18378524070bSjohn stultz }
18388524070bSjohn stultz
timekeeping_suspend(void)1839124cf911SRafael J. Wysocki int timekeeping_suspend(void)
18408524070bSjohn stultz {
18413fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
184292c1d3edSJohn Stultz unsigned long flags;
18437d489d15SJohn Stultz struct timespec64 delta, delta_delta;
18447d489d15SJohn Stultz static struct timespec64 old_delta;
184539232ed5SBaolin Wang struct clocksource *curr_clock;
184639232ed5SBaolin Wang u64 cycle_now;
18478524070bSjohn stultz
18482ee96632SXunlei Pang read_persistent_clock64(&timekeeping_suspend_time);
18493be90950SThomas Gleixner
18500d6bd995SZoran Markovic /*
18510d6bd995SZoran Markovic * On some systems the persistent_clock can not be detected at
18520d6bd995SZoran Markovic * timekeeping_init by its return value, so if we see a valid
18530d6bd995SZoran Markovic * value returned, update the persistent_clock_exists flag.
18540d6bd995SZoran Markovic */
18550d6bd995SZoran Markovic if (timekeeping_suspend_time.tv_sec || timekeeping_suspend_time.tv_nsec)
18560fa88cb4SXunlei Pang persistent_clock_exists = true;
18570d6bd995SZoran Markovic
1858f473e5f4SMukesh Ojha suspend_timing_needed = true;
1859f473e5f4SMukesh Ojha
18609a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
18613fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
18624e250fddSJohn Stultz timekeeping_forward_now(tk);
18638524070bSjohn stultz timekeeping_suspended = 1;
1864cb33217bSJohn Stultz
186539232ed5SBaolin Wang /*
186639232ed5SBaolin Wang * Since we've called forward_now, cycle_last stores the value
186739232ed5SBaolin Wang * just read from the current clocksource. Save this to potentially
186839232ed5SBaolin Wang * use in suspend timing.
186939232ed5SBaolin Wang */
187039232ed5SBaolin Wang curr_clock = tk->tkr_mono.clock;
187139232ed5SBaolin Wang cycle_now = tk->tkr_mono.cycle_last;
187239232ed5SBaolin Wang clocksource_start_suspend_timing(curr_clock, cycle_now);
187339232ed5SBaolin Wang
18740fa88cb4SXunlei Pang if (persistent_clock_exists) {
1875cb33217bSJohn Stultz /*
1876cb33217bSJohn Stultz * To avoid drift caused by repeated suspend/resumes,
1877cb33217bSJohn Stultz * which each can add ~1 second drift error,
1878cb33217bSJohn Stultz * try to compensate so the difference in system time
1879cb33217bSJohn Stultz * and persistent_clock time stays close to constant.
1880cb33217bSJohn Stultz */
18817d489d15SJohn Stultz delta = timespec64_sub(tk_xtime(tk), timekeeping_suspend_time);
18827d489d15SJohn Stultz delta_delta = timespec64_sub(delta, old_delta);
1883cb33217bSJohn Stultz if (abs(delta_delta.tv_sec) >= 2) {
1884cb33217bSJohn Stultz /*
1885cb33217bSJohn Stultz * if delta_delta is too large, assume time correction
1886264bb3f7SXunlei Pang * has occurred and set old_delta to the current delta.
1887cb33217bSJohn Stultz */
1888cb33217bSJohn Stultz old_delta = delta;
1889cb33217bSJohn Stultz } else {
1890cb33217bSJohn Stultz /* Otherwise try to adjust old_system to compensate */
1891cb33217bSJohn Stultz timekeeping_suspend_time =
18927d489d15SJohn Stultz timespec64_add(timekeeping_suspend_time, delta_delta);
1893cb33217bSJohn Stultz }
1894264bb3f7SXunlei Pang }
1895330a1617SJohn Stultz
1896330a1617SJohn Stultz timekeeping_update(tk, TK_MIRROR);
1897060407aeSRafael J. Wysocki halt_fast_timekeeper(tk);
18983fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
18999a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
19008524070bSjohn stultz
19014ffee521SThomas Gleixner tick_suspend();
1902c54a42b1SMagnus Damm clocksource_suspend();
1903adc78e6bSRafael J. Wysocki clockevents_suspend();
19048524070bSjohn stultz
19058524070bSjohn stultz return 0;
19068524070bSjohn stultz }
19078524070bSjohn stultz
19088524070bSjohn stultz /* sysfs resume/suspend bits for timekeeping */
1909e1a85b2cSRafael J. Wysocki static struct syscore_ops timekeeping_syscore_ops = {
19108524070bSjohn stultz .resume = timekeeping_resume,
19118524070bSjohn stultz .suspend = timekeeping_suspend,
19128524070bSjohn stultz };
19138524070bSjohn stultz
timekeeping_init_ops(void)1914e1a85b2cSRafael J. Wysocki static int __init timekeeping_init_ops(void)
19158524070bSjohn stultz {
1916e1a85b2cSRafael J. Wysocki register_syscore_ops(&timekeeping_syscore_ops);
1917e1a85b2cSRafael J. Wysocki return 0;
19188524070bSjohn stultz }
1919e1a85b2cSRafael J. Wysocki device_initcall(timekeeping_init_ops);
19208524070bSjohn stultz
19218524070bSjohn stultz /*
1922dc491596SJohn Stultz * Apply a multiplier adjustment to the timekeeper
19238524070bSjohn stultz */
timekeeping_apply_adjustment(struct timekeeper * tk,s64 offset,s32 mult_adj)1924dc491596SJohn Stultz static __always_inline void timekeeping_apply_adjustment(struct timekeeper *tk,
1925dc491596SJohn Stultz s64 offset,
192678b98e3cSMiroslav Lichvar s32 mult_adj)
19278524070bSjohn stultz {
1928dc491596SJohn Stultz s64 interval = tk->cycle_interval;
19298524070bSjohn stultz
193078b98e3cSMiroslav Lichvar if (mult_adj == 0) {
193178b98e3cSMiroslav Lichvar return;
193278b98e3cSMiroslav Lichvar } else if (mult_adj == -1) {
19338524070bSjohn stultz interval = -interval;
19348524070bSjohn stultz offset = -offset;
193578b98e3cSMiroslav Lichvar } else if (mult_adj != 1) {
193678b98e3cSMiroslav Lichvar interval *= mult_adj;
193778b98e3cSMiroslav Lichvar offset *= mult_adj;
19381d17d174SIngo Molnar }
19398524070bSjohn stultz
1940c2bc1111SJohn Stultz /*
1941c2bc1111SJohn Stultz * So the following can be confusing.
1942c2bc1111SJohn Stultz *
1943dc491596SJohn Stultz * To keep things simple, lets assume mult_adj == 1 for now.
1944c2bc1111SJohn Stultz *
1945dc491596SJohn Stultz * When mult_adj != 1, remember that the interval and offset values
1946c2bc1111SJohn Stultz * have been appropriately scaled so the math is the same.
1947c2bc1111SJohn Stultz *
1948c2bc1111SJohn Stultz * The basic idea here is that we're increasing the multiplier
1949c2bc1111SJohn Stultz * by one, this causes the xtime_interval to be incremented by
1950c2bc1111SJohn Stultz * one cycle_interval. This is because:
1951c2bc1111SJohn Stultz * xtime_interval = cycle_interval * mult
1952c2bc1111SJohn Stultz * So if mult is being incremented by one:
1953c2bc1111SJohn Stultz * xtime_interval = cycle_interval * (mult + 1)
1954c2bc1111SJohn Stultz * Its the same as:
1955c2bc1111SJohn Stultz * xtime_interval = (cycle_interval * mult) + cycle_interval
1956c2bc1111SJohn Stultz * Which can be shortened to:
1957c2bc1111SJohn Stultz * xtime_interval += cycle_interval
1958c2bc1111SJohn Stultz *
1959c2bc1111SJohn Stultz * So offset stores the non-accumulated cycles. Thus the current
1960c2bc1111SJohn Stultz * time (in shifted nanoseconds) is:
1961c2bc1111SJohn Stultz * now = (offset * adj) + xtime_nsec
1962c2bc1111SJohn Stultz * Now, even though we're adjusting the clock frequency, we have
1963c2bc1111SJohn Stultz * to keep time consistent. In other words, we can't jump back
1964c2bc1111SJohn Stultz * in time, and we also want to avoid jumping forward in time.
1965c2bc1111SJohn Stultz *
1966c2bc1111SJohn Stultz * So given the same offset value, we need the time to be the same
1967c2bc1111SJohn Stultz * both before and after the freq adjustment.
1968c2bc1111SJohn Stultz * now = (offset * adj_1) + xtime_nsec_1
1969c2bc1111SJohn Stultz * now = (offset * adj_2) + xtime_nsec_2
1970c2bc1111SJohn Stultz * So:
1971c2bc1111SJohn Stultz * (offset * adj_1) + xtime_nsec_1 =
1972c2bc1111SJohn Stultz * (offset * adj_2) + xtime_nsec_2
1973c2bc1111SJohn Stultz * And we know:
1974c2bc1111SJohn Stultz * adj_2 = adj_1 + 1
1975c2bc1111SJohn Stultz * So:
1976c2bc1111SJohn Stultz * (offset * adj_1) + xtime_nsec_1 =
1977c2bc1111SJohn Stultz * (offset * (adj_1+1)) + xtime_nsec_2
1978c2bc1111SJohn Stultz * (offset * adj_1) + xtime_nsec_1 =
1979c2bc1111SJohn Stultz * (offset * adj_1) + offset + xtime_nsec_2
1980c2bc1111SJohn Stultz * Canceling the sides:
1981c2bc1111SJohn Stultz * xtime_nsec_1 = offset + xtime_nsec_2
1982c2bc1111SJohn Stultz * Which gives us:
1983c2bc1111SJohn Stultz * xtime_nsec_2 = xtime_nsec_1 - offset
19844bf07f65SIngo Molnar * Which simplifies to:
1985c2bc1111SJohn Stultz * xtime_nsec -= offset
1986c2bc1111SJohn Stultz */
1987876e7881SPeter Zijlstra if ((mult_adj > 0) && (tk->tkr_mono.mult + mult_adj < mult_adj)) {
19886067dc5aSpang.xunlei /* NTP adjustment caused clocksource mult overflow */
19896067dc5aSpang.xunlei WARN_ON_ONCE(1);
19906067dc5aSpang.xunlei return;
19916067dc5aSpang.xunlei }
19926067dc5aSpang.xunlei
1993876e7881SPeter Zijlstra tk->tkr_mono.mult += mult_adj;
1994f726a697SJohn Stultz tk->xtime_interval += interval;
1995876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec -= offset;
1996dc491596SJohn Stultz }
19972a8c0883SJohn Stultz
1998dc491596SJohn Stultz /*
1999dc491596SJohn Stultz * Adjust the timekeeper's multiplier to the correct frequency
2000dc491596SJohn Stultz * and also to reduce the accumulated error value.
2001dc491596SJohn Stultz */
timekeeping_adjust(struct timekeeper * tk,s64 offset)2002dc491596SJohn Stultz static void timekeeping_adjust(struct timekeeper *tk, s64 offset)
2003dc491596SJohn Stultz {
200478b98e3cSMiroslav Lichvar u32 mult;
2005dc491596SJohn Stultz
200678b98e3cSMiroslav Lichvar /*
200778b98e3cSMiroslav Lichvar * Determine the multiplier from the current NTP tick length.
200878b98e3cSMiroslav Lichvar * Avoid expensive division when the tick length doesn't change.
200978b98e3cSMiroslav Lichvar */
201078b98e3cSMiroslav Lichvar if (likely(tk->ntp_tick == ntp_tick_length())) {
201178b98e3cSMiroslav Lichvar mult = tk->tkr_mono.mult - tk->ntp_err_mult;
201278b98e3cSMiroslav Lichvar } else {
201378b98e3cSMiroslav Lichvar tk->ntp_tick = ntp_tick_length();
201478b98e3cSMiroslav Lichvar mult = div64_u64((tk->ntp_tick >> tk->ntp_error_shift) -
201578b98e3cSMiroslav Lichvar tk->xtime_remainder, tk->cycle_interval);
2016dc491596SJohn Stultz }
2017dc491596SJohn Stultz
201878b98e3cSMiroslav Lichvar /*
201978b98e3cSMiroslav Lichvar * If the clock is behind the NTP time, increase the multiplier by 1
202078b98e3cSMiroslav Lichvar * to catch up with it. If it's ahead and there was a remainder in the
202178b98e3cSMiroslav Lichvar * tick division, the clock will slow down. Otherwise it will stay
202278b98e3cSMiroslav Lichvar * ahead until the tick length changes to a non-divisible value.
202378b98e3cSMiroslav Lichvar */
202478b98e3cSMiroslav Lichvar tk->ntp_err_mult = tk->ntp_error > 0 ? 1 : 0;
202578b98e3cSMiroslav Lichvar mult += tk->ntp_err_mult;
202678b98e3cSMiroslav Lichvar
202778b98e3cSMiroslav Lichvar timekeeping_apply_adjustment(tk, offset, mult - tk->tkr_mono.mult);
202878b98e3cSMiroslav Lichvar
2029876e7881SPeter Zijlstra if (unlikely(tk->tkr_mono.clock->maxadj &&
2030876e7881SPeter Zijlstra (abs(tk->tkr_mono.mult - tk->tkr_mono.clock->mult)
2031876e7881SPeter Zijlstra > tk->tkr_mono.clock->maxadj))) {
2032dc491596SJohn Stultz printk_once(KERN_WARNING
2033dc491596SJohn Stultz "Adjusting %s more than 11%% (%ld vs %ld)\n",
2034876e7881SPeter Zijlstra tk->tkr_mono.clock->name, (long)tk->tkr_mono.mult,
2035876e7881SPeter Zijlstra (long)tk->tkr_mono.clock->mult + tk->tkr_mono.clock->maxadj);
2036dc491596SJohn Stultz }
2037dc491596SJohn Stultz
20382a8c0883SJohn Stultz /*
20392a8c0883SJohn Stultz * It may be possible that when we entered this function, xtime_nsec
20402a8c0883SJohn Stultz * was very small. Further, if we're slightly speeding the clocksource
20412a8c0883SJohn Stultz * in the code above, its possible the required corrective factor to
20422a8c0883SJohn Stultz * xtime_nsec could cause it to underflow.
20432a8c0883SJohn Stultz *
204478b98e3cSMiroslav Lichvar * Now, since we have already accumulated the second and the NTP
204578b98e3cSMiroslav Lichvar * subsystem has been notified via second_overflow(), we need to skip
204678b98e3cSMiroslav Lichvar * the next update.
20472a8c0883SJohn Stultz */
2048876e7881SPeter Zijlstra if (unlikely((s64)tk->tkr_mono.xtime_nsec < 0)) {
204978b98e3cSMiroslav Lichvar tk->tkr_mono.xtime_nsec += (u64)NSEC_PER_SEC <<
205078b98e3cSMiroslav Lichvar tk->tkr_mono.shift;
205178b98e3cSMiroslav Lichvar tk->xtime_sec--;
205278b98e3cSMiroslav Lichvar tk->skip_second_overflow = 1;
20532a8c0883SJohn Stultz }
20548524070bSjohn stultz }
20558524070bSjohn stultz
2056199d280cSAlex Shi /*
20571f4f9487SJohn Stultz * accumulate_nsecs_to_secs - Accumulates nsecs into secs
20581f4f9487SJohn Stultz *
2059571af55aSZhen Lei * Helper function that accumulates the nsecs greater than a second
20601f4f9487SJohn Stultz * from the xtime_nsec field to the xtime_secs field.
20611f4f9487SJohn Stultz * It also calls into the NTP code to handle leapsecond processing.
20621f4f9487SJohn Stultz */
accumulate_nsecs_to_secs(struct timekeeper * tk)2063780427f0SDavid Vrabel static inline unsigned int accumulate_nsecs_to_secs(struct timekeeper *tk)
20641f4f9487SJohn Stultz {
2065876e7881SPeter Zijlstra u64 nsecps = (u64)NSEC_PER_SEC << tk->tkr_mono.shift;
20665258d3f2SJohn Stultz unsigned int clock_set = 0;
20671f4f9487SJohn Stultz
2068876e7881SPeter Zijlstra while (tk->tkr_mono.xtime_nsec >= nsecps) {
20691f4f9487SJohn Stultz int leap;
20701f4f9487SJohn Stultz
2071876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec -= nsecps;
20721f4f9487SJohn Stultz tk->xtime_sec++;
20731f4f9487SJohn Stultz
207478b98e3cSMiroslav Lichvar /*
207578b98e3cSMiroslav Lichvar * Skip NTP update if this second was accumulated before,
207678b98e3cSMiroslav Lichvar * i.e. xtime_nsec underflowed in timekeeping_adjust()
207778b98e3cSMiroslav Lichvar */
207878b98e3cSMiroslav Lichvar if (unlikely(tk->skip_second_overflow)) {
207978b98e3cSMiroslav Lichvar tk->skip_second_overflow = 0;
208078b98e3cSMiroslav Lichvar continue;
208178b98e3cSMiroslav Lichvar }
208278b98e3cSMiroslav Lichvar
20831f4f9487SJohn Stultz /* Figure out if its a leap sec and apply if needed */
20841f4f9487SJohn Stultz leap = second_overflow(tk->xtime_sec);
20856d0ef903SJohn Stultz if (unlikely(leap)) {
20867d489d15SJohn Stultz struct timespec64 ts;
20871f4f9487SJohn Stultz
20886d0ef903SJohn Stultz tk->xtime_sec += leap;
20896d0ef903SJohn Stultz
20906d0ef903SJohn Stultz ts.tv_sec = leap;
20916d0ef903SJohn Stultz ts.tv_nsec = 0;
20926d0ef903SJohn Stultz tk_set_wall_to_mono(tk,
20937d489d15SJohn Stultz timespec64_sub(tk->wall_to_monotonic, ts));
20946d0ef903SJohn Stultz
2095cc244ddaSJohn Stultz __timekeeping_set_tai_offset(tk, tk->tai_offset - leap);
2096cc244ddaSJohn Stultz
20975258d3f2SJohn Stultz clock_set = TK_CLOCK_WAS_SET;
20986d0ef903SJohn Stultz }
20991f4f9487SJohn Stultz }
21005258d3f2SJohn Stultz return clock_set;
21011f4f9487SJohn Stultz }
21021f4f9487SJohn Stultz
2103199d280cSAlex Shi /*
2104a092ff0fSjohn stultz * logarithmic_accumulation - shifted accumulation of cycles
2105a092ff0fSjohn stultz *
2106a092ff0fSjohn stultz * This functions accumulates a shifted interval of cycles into
2107b0294f30SRandy Dunlap * a shifted interval nanoseconds. Allows for O(log) accumulation
2108a092ff0fSjohn stultz * loop.
2109a092ff0fSjohn stultz *
2110a092ff0fSjohn stultz * Returns the unconsumed cycles.
2111a092ff0fSjohn stultz */
logarithmic_accumulation(struct timekeeper * tk,u64 offset,u32 shift,unsigned int * clock_set)2112a5a1d1c2SThomas Gleixner static u64 logarithmic_accumulation(struct timekeeper *tk, u64 offset,
2113a5a1d1c2SThomas Gleixner u32 shift, unsigned int *clock_set)
2114a092ff0fSjohn stultz {
2115a5a1d1c2SThomas Gleixner u64 interval = tk->cycle_interval << shift;
21163d88d56cSJohn Stultz u64 snsec_per_sec;
2117a092ff0fSjohn stultz
2118571af55aSZhen Lei /* If the offset is smaller than a shifted interval, do nothing */
211923a9537aSThomas Gleixner if (offset < interval)
2120a092ff0fSjohn stultz return offset;
2121a092ff0fSjohn stultz
2122a092ff0fSjohn stultz /* Accumulate one shifted interval */
212323a9537aSThomas Gleixner offset -= interval;
2124876e7881SPeter Zijlstra tk->tkr_mono.cycle_last += interval;
21254a4ad80dSPeter Zijlstra tk->tkr_raw.cycle_last += interval;
2126a092ff0fSjohn stultz
2127876e7881SPeter Zijlstra tk->tkr_mono.xtime_nsec += tk->xtime_interval << shift;
21285258d3f2SJohn Stultz *clock_set |= accumulate_nsecs_to_secs(tk);
2129a092ff0fSjohn stultz
2130deda2e81SJason Wessel /* Accumulate raw time */
21313d88d56cSJohn Stultz tk->tkr_raw.xtime_nsec += tk->raw_interval << shift;
21323d88d56cSJohn Stultz snsec_per_sec = (u64)NSEC_PER_SEC << tk->tkr_raw.shift;
21333d88d56cSJohn Stultz while (tk->tkr_raw.xtime_nsec >= snsec_per_sec) {
21343d88d56cSJohn Stultz tk->tkr_raw.xtime_nsec -= snsec_per_sec;
2135fc6eead7SJohn Stultz tk->raw_sec++;
2136a092ff0fSjohn stultz }
2137a092ff0fSjohn stultz
2138a092ff0fSjohn stultz /* Accumulate error between NTP and clock interval */
2139375f45b5SJohn Stultz tk->ntp_error += tk->ntp_tick << shift;
2140f726a697SJohn Stultz tk->ntp_error -= (tk->xtime_interval + tk->xtime_remainder) <<
2141f726a697SJohn Stultz (tk->ntp_error_shift + shift);
2142a092ff0fSjohn stultz
2143a092ff0fSjohn stultz return offset;
2144a092ff0fSjohn stultz }
2145a092ff0fSjohn stultz
2146b061c7a5SMiroslav Lichvar /*
2147b061c7a5SMiroslav Lichvar * timekeeping_advance - Updates the timekeeper to the current time and
2148b061c7a5SMiroslav Lichvar * current NTP tick length
21498524070bSjohn stultz */
timekeeping_advance(enum timekeeping_adv_mode mode)21501b267793SThomas Gleixner static bool timekeeping_advance(enum timekeeping_adv_mode mode)
21518524070bSjohn stultz {
21523fdb14fdSThomas Gleixner struct timekeeper *real_tk = &tk_core.timekeeper;
215348cdc135SThomas Gleixner struct timekeeper *tk = &shadow_timekeeper;
2154a5a1d1c2SThomas Gleixner u64 offset;
2155a092ff0fSjohn stultz int shift = 0, maxshift;
21565258d3f2SJohn Stultz unsigned int clock_set = 0;
215770471f2fSJohn Stultz unsigned long flags;
215870471f2fSJohn Stultz
21599a7a71b1SThomas Gleixner raw_spin_lock_irqsave(&timekeeper_lock, flags);
21608524070bSjohn stultz
21618524070bSjohn stultz /* Make sure we're fully resumed: */
21628524070bSjohn stultz if (unlikely(timekeeping_suspended))
216370471f2fSJohn Stultz goto out;
21648524070bSjohn stultz
2165ceea5e37SJohn Stultz offset = clocksource_delta(tk_clock_read(&tk->tkr_mono),
2166876e7881SPeter Zijlstra tk->tkr_mono.cycle_last, tk->tkr_mono.mask);
21678524070bSjohn stultz
2168bf2ac312SJohn Stultz /* Check if there's really nothing to do */
2169b061c7a5SMiroslav Lichvar if (offset < real_tk->cycle_interval && mode == TK_ADV_TICK)
2170bf2ac312SJohn Stultz goto out;
2171bf2ac312SJohn Stultz
21723c17ad19SJohn Stultz /* Do some additional sanity checking */
2173a529bea8SStafford Horne timekeeping_check_update(tk, offset);
21743c17ad19SJohn Stultz
2175a092ff0fSjohn stultz /*
2176a092ff0fSjohn stultz * With NO_HZ we may have to accumulate many cycle_intervals
2177a092ff0fSjohn stultz * (think "ticks") worth of time at once. To do this efficiently,
2178a092ff0fSjohn stultz * we calculate the largest doubling multiple of cycle_intervals
217988b28adfSJim Cromie * that is smaller than the offset. We then accumulate that
2180a092ff0fSjohn stultz * chunk in one go, and then try to consume the next smaller
2181a092ff0fSjohn stultz * doubled multiple.
21828524070bSjohn stultz */
21834e250fddSJohn Stultz shift = ilog2(offset) - ilog2(tk->cycle_interval);
2184a092ff0fSjohn stultz shift = max(0, shift);
218588b28adfSJim Cromie /* Bound shift to one less than what overflows tick_length */
2186ea7cf49aSJohn Stultz maxshift = (64 - (ilog2(ntp_tick_length())+1)) - 1;
2187a092ff0fSjohn stultz shift = min(shift, maxshift);
21884e250fddSJohn Stultz while (offset >= tk->cycle_interval) {
21895258d3f2SJohn Stultz offset = logarithmic_accumulation(tk, offset, shift,
21905258d3f2SJohn Stultz &clock_set);
21914e250fddSJohn Stultz if (offset < tk->cycle_interval<<shift)
2192a092ff0fSjohn stultz shift--;
21938524070bSjohn stultz }
21948524070bSjohn stultz
219578b98e3cSMiroslav Lichvar /* Adjust the multiplier to correct NTP error */
21964e250fddSJohn Stultz timekeeping_adjust(tk, offset);
21978524070bSjohn stultz
21986a867a39SJohn Stultz /*
21996a867a39SJohn Stultz * Finally, make sure that after the rounding
22001e75fa8bSJohn Stultz * xtime_nsec isn't larger than NSEC_PER_SEC
22016a867a39SJohn Stultz */
22025258d3f2SJohn Stultz clock_set |= accumulate_nsecs_to_secs(tk);
220383f57a11SLinus Torvalds
22043fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
220548cdc135SThomas Gleixner /*
220648cdc135SThomas Gleixner * Update the real timekeeper.
220748cdc135SThomas Gleixner *
220848cdc135SThomas Gleixner * We could avoid this memcpy by switching pointers, but that
220948cdc135SThomas Gleixner * requires changes to all other timekeeper usage sites as
221048cdc135SThomas Gleixner * well, i.e. move the timekeeper pointer getter into the
221148cdc135SThomas Gleixner * spinlocked/seqcount protected sections. And we trade this
22123fdb14fdSThomas Gleixner * memcpy under the tk_core.seq against one before we start
221348cdc135SThomas Gleixner * updating.
221448cdc135SThomas Gleixner */
2215906c5557SJohn Stultz timekeeping_update(tk, clock_set);
221648cdc135SThomas Gleixner memcpy(real_tk, tk, sizeof(*tk));
2217906c5557SJohn Stultz /* The memcpy must come last. Do not put anything here! */
22183fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
2219ca4523cdSThomas Gleixner out:
22209a7a71b1SThomas Gleixner raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
22211b267793SThomas Gleixner
22221b267793SThomas Gleixner return !!clock_set;
22238524070bSjohn stultz }
22247c3f1a57STomas Janousek
22257c3f1a57STomas Janousek /**
2226b061c7a5SMiroslav Lichvar * update_wall_time - Uses the current clocksource to increment the wall time
2227b061c7a5SMiroslav Lichvar *
2228b061c7a5SMiroslav Lichvar */
update_wall_time(void)2229b061c7a5SMiroslav Lichvar void update_wall_time(void)
2230b061c7a5SMiroslav Lichvar {
22311b267793SThomas Gleixner if (timekeeping_advance(TK_ADV_TICK))
22321b267793SThomas Gleixner clock_was_set_delayed();
2233b061c7a5SMiroslav Lichvar }
2234b061c7a5SMiroslav Lichvar
2235b061c7a5SMiroslav Lichvar /**
2236d08c0cddSJohn Stultz * getboottime64 - Return the real time of system boot.
2237d08c0cddSJohn Stultz * @ts: pointer to the timespec64 to be set
22387c3f1a57STomas Janousek *
2239d08c0cddSJohn Stultz * Returns the wall-time of boot in a timespec64.
22407c3f1a57STomas Janousek *
22417c3f1a57STomas Janousek * This is based on the wall_to_monotonic offset and the total suspend
22427c3f1a57STomas Janousek * time. Calls to settimeofday will affect the value returned (which
22437c3f1a57STomas Janousek * basically means that however wrong your real time clock is at boot time,
22447c3f1a57STomas Janousek * you get the right time here).
22457c3f1a57STomas Janousek */
getboottime64(struct timespec64 * ts)2246d08c0cddSJohn Stultz void getboottime64(struct timespec64 *ts)
22477c3f1a57STomas Janousek {
22483fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
2249a3ed0e43SThomas Gleixner ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot);
2250d4f587c6SMartin Schwidefsky
2251d08c0cddSJohn Stultz *ts = ktime_to_timespec64(t);
22527c3f1a57STomas Janousek }
2253d08c0cddSJohn Stultz EXPORT_SYMBOL_GPL(getboottime64);
22547c3f1a57STomas Janousek
ktime_get_coarse_real_ts64(struct timespec64 * ts)2255fb7fcc96SArnd Bergmann void ktime_get_coarse_real_ts64(struct timespec64 *ts)
22562c6b47deSjohn stultz {
22573fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
2258e1e41b6cSRasmus Villemoes unsigned int seq;
22592c6b47deSjohn stultz
22602c6b47deSjohn stultz do {
22613fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
226283f57a11SLinus Torvalds
2263fb7fcc96SArnd Bergmann *ts = tk_xtime(tk);
22643fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
22652c6b47deSjohn stultz }
2266fb7fcc96SArnd Bergmann EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
2267da15cfdaSjohn stultz
ktime_get_coarse_ts64(struct timespec64 * ts)2268fb7fcc96SArnd Bergmann void ktime_get_coarse_ts64(struct timespec64 *ts)
2269da15cfdaSjohn stultz {
22703fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
22717d489d15SJohn Stultz struct timespec64 now, mono;
2272e1e41b6cSRasmus Villemoes unsigned int seq;
2273da15cfdaSjohn stultz
2274da15cfdaSjohn stultz do {
22753fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
227683f57a11SLinus Torvalds
22774e250fddSJohn Stultz now = tk_xtime(tk);
22784e250fddSJohn Stultz mono = tk->wall_to_monotonic;
22793fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
2280da15cfdaSjohn stultz
2281fb7fcc96SArnd Bergmann set_normalized_timespec64(ts, now.tv_sec + mono.tv_sec,
2282da15cfdaSjohn stultz now.tv_nsec + mono.tv_nsec);
2283da15cfdaSjohn stultz }
2284fb7fcc96SArnd Bergmann EXPORT_SYMBOL(ktime_get_coarse_ts64);
2285871cf1e5STorben Hohn
2286871cf1e5STorben Hohn /*
2287d6ad4187SJohn Stultz * Must hold jiffies_lock
2288871cf1e5STorben Hohn */
do_timer(unsigned long ticks)2289871cf1e5STorben Hohn void do_timer(unsigned long ticks)
2290871cf1e5STorben Hohn {
2291871cf1e5STorben Hohn jiffies_64 += ticks;
229246132e3aSPaul Gortmaker calc_global_load();
2293871cf1e5STorben Hohn }
229448cf76f7STorben Hohn
229548cf76f7STorben Hohn /**
229676f41088SJohn Stultz * ktime_get_update_offsets_now - hrtimer helper
2297868a3e91SThomas Gleixner * @cwsseq: pointer to check and store the clock was set sequence number
2298f6c06abfSThomas Gleixner * @offs_real: pointer to storage for monotonic -> realtime offset
2299a3ed0e43SThomas Gleixner * @offs_boot: pointer to storage for monotonic -> boottime offset
2300b7bc50e4SXie XiuQi * @offs_tai: pointer to storage for monotonic -> clock tai offset
2301f6c06abfSThomas Gleixner *
2302868a3e91SThomas Gleixner * Returns current monotonic time and updates the offsets if the
2303868a3e91SThomas Gleixner * sequence number in @cwsseq and timekeeper.clock_was_set_seq are
2304868a3e91SThomas Gleixner * different.
2305868a3e91SThomas Gleixner *
2306b7bc50e4SXie XiuQi * Called from hrtimer_interrupt() or retrigger_next_event()
2307f6c06abfSThomas Gleixner */
ktime_get_update_offsets_now(unsigned int * cwsseq,ktime_t * offs_real,ktime_t * offs_boot,ktime_t * offs_tai)2308868a3e91SThomas Gleixner ktime_t ktime_get_update_offsets_now(unsigned int *cwsseq, ktime_t *offs_real,
2309a3ed0e43SThomas Gleixner ktime_t *offs_boot, ktime_t *offs_tai)
2310f6c06abfSThomas Gleixner {
23113fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
2312f6c06abfSThomas Gleixner unsigned int seq;
2313a37c0aadSThomas Gleixner ktime_t base;
2314a37c0aadSThomas Gleixner u64 nsecs;
2315f6c06abfSThomas Gleixner
2316f6c06abfSThomas Gleixner do {
23173fdb14fdSThomas Gleixner seq = read_seqcount_begin(&tk_core.seq);
2318f6c06abfSThomas Gleixner
2319876e7881SPeter Zijlstra base = tk->tkr_mono.base;
2320876e7881SPeter Zijlstra nsecs = timekeeping_get_ns(&tk->tkr_mono);
2321833f32d7SJohn Stultz base = ktime_add_ns(base, nsecs);
2322833f32d7SJohn Stultz
2323868a3e91SThomas Gleixner if (*cwsseq != tk->clock_was_set_seq) {
2324868a3e91SThomas Gleixner *cwsseq = tk->clock_was_set_seq;
23254e250fddSJohn Stultz *offs_real = tk->offs_real;
2326a3ed0e43SThomas Gleixner *offs_boot = tk->offs_boot;
232790adda98SJohn Stultz *offs_tai = tk->offs_tai;
2328868a3e91SThomas Gleixner }
2329833f32d7SJohn Stultz
2330833f32d7SJohn Stultz /* Handle leapsecond insertion adjustments */
23312456e855SThomas Gleixner if (unlikely(base >= tk->next_leap_ktime))
2332833f32d7SJohn Stultz *offs_real = ktime_sub(tk->offs_real, ktime_set(1, 0));
2333833f32d7SJohn Stultz
23343fdb14fdSThomas Gleixner } while (read_seqcount_retry(&tk_core.seq, seq));
2335f6c06abfSThomas Gleixner
2336833f32d7SJohn Stultz return base;
2337f6c06abfSThomas Gleixner }
2338f6c06abfSThomas Gleixner
2339199d280cSAlex Shi /*
23401572fa03SArnd Bergmann * timekeeping_validate_timex - Ensures the timex is ok for use in do_adjtimex
2341e0956dccSArnd Bergmann */
timekeeping_validate_timex(const struct __kernel_timex * txc)2342ead25417SDeepa Dinamani static int timekeeping_validate_timex(const struct __kernel_timex *txc)
2343e0956dccSArnd Bergmann {
2344e0956dccSArnd Bergmann if (txc->modes & ADJ_ADJTIME) {
2345e0956dccSArnd Bergmann /* singleshot must not be used with any other mode bits */
2346e0956dccSArnd Bergmann if (!(txc->modes & ADJ_OFFSET_SINGLESHOT))
2347e0956dccSArnd Bergmann return -EINVAL;
2348e0956dccSArnd Bergmann if (!(txc->modes & ADJ_OFFSET_READONLY) &&
2349e0956dccSArnd Bergmann !capable(CAP_SYS_TIME))
2350e0956dccSArnd Bergmann return -EPERM;
2351e0956dccSArnd Bergmann } else {
2352e0956dccSArnd Bergmann /* In order to modify anything, you gotta be super-user! */
2353e0956dccSArnd Bergmann if (txc->modes && !capable(CAP_SYS_TIME))
2354e0956dccSArnd Bergmann return -EPERM;
2355e0956dccSArnd Bergmann /*
2356e0956dccSArnd Bergmann * if the quartz is off by more than 10% then
2357e0956dccSArnd Bergmann * something is VERY wrong!
2358e0956dccSArnd Bergmann */
2359e0956dccSArnd Bergmann if (txc->modes & ADJ_TICK &&
2360e0956dccSArnd Bergmann (txc->tick < 900000/USER_HZ ||
2361e0956dccSArnd Bergmann txc->tick > 1100000/USER_HZ))
2362e0956dccSArnd Bergmann return -EINVAL;
2363e0956dccSArnd Bergmann }
2364e0956dccSArnd Bergmann
2365e0956dccSArnd Bergmann if (txc->modes & ADJ_SETOFFSET) {
2366e0956dccSArnd Bergmann /* In order to inject time, you gotta be super-user! */
2367e0956dccSArnd Bergmann if (!capable(CAP_SYS_TIME))
2368e0956dccSArnd Bergmann return -EPERM;
2369e0956dccSArnd Bergmann
23701572fa03SArnd Bergmann /*
23711572fa03SArnd Bergmann * Validate if a timespec/timeval used to inject a time
23724bf07f65SIngo Molnar * offset is valid. Offsets can be positive or negative, so
23731572fa03SArnd Bergmann * we don't check tv_sec. The value of the timeval/timespec
23741572fa03SArnd Bergmann * is the sum of its fields,but *NOTE*:
23751572fa03SArnd Bergmann * The field tv_usec/tv_nsec must always be non-negative and
23761572fa03SArnd Bergmann * we can't have more nanoseconds/microseconds than a second.
23771572fa03SArnd Bergmann */
23781572fa03SArnd Bergmann if (txc->time.tv_usec < 0)
2379e0956dccSArnd Bergmann return -EINVAL;
2380e0956dccSArnd Bergmann
23811572fa03SArnd Bergmann if (txc->modes & ADJ_NANO) {
23821572fa03SArnd Bergmann if (txc->time.tv_usec >= NSEC_PER_SEC)
23831572fa03SArnd Bergmann return -EINVAL;
2384e0956dccSArnd Bergmann } else {
23851572fa03SArnd Bergmann if (txc->time.tv_usec >= USEC_PER_SEC)
2386e0956dccSArnd Bergmann return -EINVAL;
2387e0956dccSArnd Bergmann }
2388e0956dccSArnd Bergmann }
2389e0956dccSArnd Bergmann
2390e0956dccSArnd Bergmann /*
2391e0956dccSArnd Bergmann * Check for potential multiplication overflows that can
2392e0956dccSArnd Bergmann * only happen on 64-bit systems:
2393e0956dccSArnd Bergmann */
2394e0956dccSArnd Bergmann if ((txc->modes & ADJ_FREQUENCY) && (BITS_PER_LONG == 64)) {
2395e0956dccSArnd Bergmann if (LLONG_MIN / PPM_SCALE > txc->freq)
2396e0956dccSArnd Bergmann return -EINVAL;
2397e0956dccSArnd Bergmann if (LLONG_MAX / PPM_SCALE < txc->freq)
2398e0956dccSArnd Bergmann return -EINVAL;
2399e0956dccSArnd Bergmann }
2400e0956dccSArnd Bergmann
2401e0956dccSArnd Bergmann return 0;
2402e0956dccSArnd Bergmann }
2403e0956dccSArnd Bergmann
24041366992eSJason A. Donenfeld /**
24051366992eSJason A. Donenfeld * random_get_entropy_fallback - Returns the raw clock source value,
24061366992eSJason A. Donenfeld * used by random.c for platforms with no valid random_get_entropy().
24071366992eSJason A. Donenfeld */
random_get_entropy_fallback(void)24081366992eSJason A. Donenfeld unsigned long random_get_entropy_fallback(void)
24091366992eSJason A. Donenfeld {
24101366992eSJason A. Donenfeld struct tk_read_base *tkr = &tk_core.timekeeper.tkr_mono;
24111366992eSJason A. Donenfeld struct clocksource *clock = READ_ONCE(tkr->clock);
24121366992eSJason A. Donenfeld
24131366992eSJason A. Donenfeld if (unlikely(timekeeping_suspended || !clock))
24141366992eSJason A. Donenfeld return 0;
24151366992eSJason A. Donenfeld return clock->read(clock);
24161366992eSJason A. Donenfeld }
24171366992eSJason A. Donenfeld EXPORT_SYMBOL_GPL(random_get_entropy_fallback);
2418e0956dccSArnd Bergmann
2419e0956dccSArnd Bergmann /**
2420aa6f9c59SJohn Stultz * do_adjtimex() - Accessor function to NTP __do_adjtimex function
2421aa6f9c59SJohn Stultz */
do_adjtimex(struct __kernel_timex * txc)2422ead25417SDeepa Dinamani int do_adjtimex(struct __kernel_timex *txc)
2423aa6f9c59SJohn Stultz {
24243fdb14fdSThomas Gleixner struct timekeeper *tk = &tk_core.timekeeper;
24257e8eda73SOndrej Mosnacek struct audit_ntp_data ad;
24261b267793SThomas Gleixner bool clock_set = false;
24277d489d15SJohn Stultz struct timespec64 ts;
24281b267793SThomas Gleixner unsigned long flags;
24294e8f8b34SJohn Stultz s32 orig_tai, tai;
2430e4085693SJohn Stultz int ret;
2431e4085693SJohn Stultz
2432e4085693SJohn Stultz /* Validate the data before disabling interrupts */
24331572fa03SArnd Bergmann ret = timekeeping_validate_timex(txc);
2434e4085693SJohn Stultz if (ret)
2435e4085693SJohn Stultz return ret;
2436b8ac29b4SJason A. Donenfeld add_device_randomness(txc, sizeof(*txc));
2437e4085693SJohn Stultz
2438cef90377SJohn Stultz if (txc->modes & ADJ_SETOFFSET) {
24391572fa03SArnd Bergmann struct timespec64 delta;
2440cef90377SJohn Stultz delta.tv_sec = txc->time.tv_sec;
2441cef90377SJohn Stultz delta.tv_nsec = txc->time.tv_usec;
2442cef90377SJohn Stultz if (!(txc->modes & ADJ_NANO))
2443cef90377SJohn Stultz delta.tv_nsec *= 1000;
2444cef90377SJohn Stultz ret = timekeeping_inject_offset(&delta);
2445cef90377SJohn Stultz if (ret)
2446cef90377SJohn Stultz return ret;
24472d87a067SOndrej Mosnacek
24482d87a067SOndrej Mosnacek audit_tk_injoffset(delta);
2449cef90377SJohn Stultz }
2450cef90377SJohn Stultz
24517e8eda73SOndrej Mosnacek audit_ntp_init(&ad);
24527e8eda73SOndrej Mosnacek
2453d30faff9SArnd Bergmann ktime_get_real_ts64(&ts);
2454b8ac29b4SJason A. Donenfeld add_device_randomness(&ts, sizeof(ts));
2455aa6f9c59SJohn Stultz
245606c017fdSJohn Stultz raw_spin_lock_irqsave(&timekeeper_lock, flags);
24573fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
245806c017fdSJohn Stultz
24594e8f8b34SJohn Stultz orig_tai = tai = tk->tai_offset;
24607e8eda73SOndrej Mosnacek ret = __do_adjtimex(txc, &ts, &tai, &ad);
246187ace39bSJohn Stultz
24624e8f8b34SJohn Stultz if (tai != orig_tai) {
24630b5154fbSJohn Stultz __timekeeping_set_tai_offset(tk, tai);
2464f55c0760SJohn Stultz timekeeping_update(tk, TK_MIRROR | TK_CLOCK_WAS_SET);
24651b267793SThomas Gleixner clock_set = true;
24664e8f8b34SJohn Stultz }
2467833f32d7SJohn Stultz tk_update_leap_state(tk);
2468833f32d7SJohn Stultz
24693fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
247006c017fdSJohn Stultz raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
247106c017fdSJohn Stultz
24727e8eda73SOndrej Mosnacek audit_ntp_log(&ad);
24737e8eda73SOndrej Mosnacek
2474b061c7a5SMiroslav Lichvar /* Update the multiplier immediately if frequency was set directly */
2475b061c7a5SMiroslav Lichvar if (txc->modes & (ADJ_FREQUENCY | ADJ_TICK))
24761b267793SThomas Gleixner clock_set |= timekeeping_advance(TK_ADV_FREQ);
2477b061c7a5SMiroslav Lichvar
24781b267793SThomas Gleixner if (clock_set)
2479*65d76c0aSThomas Gleixner clock_was_set(CLOCK_SET_WALL);
24806fdda9a9SJohn Stultz
24817bd36014SJohn Stultz ntp_notify_cmos_timer();
24827bd36014SJohn Stultz
248387ace39bSJohn Stultz return ret;
248487ace39bSJohn Stultz }
2485aa6f9c59SJohn Stultz
2486aa6f9c59SJohn Stultz #ifdef CONFIG_NTP_PPS
2487aa6f9c59SJohn Stultz /**
2488aa6f9c59SJohn Stultz * hardpps() - Accessor function to NTP __hardpps function
2489aa6f9c59SJohn Stultz */
hardpps(const struct timespec64 * phase_ts,const struct timespec64 * raw_ts)24907ec88e4bSArnd Bergmann void hardpps(const struct timespec64 *phase_ts, const struct timespec64 *raw_ts)
2491aa6f9c59SJohn Stultz {
249206c017fdSJohn Stultz unsigned long flags;
249306c017fdSJohn Stultz
249406c017fdSJohn Stultz raw_spin_lock_irqsave(&timekeeper_lock, flags);
24953fdb14fdSThomas Gleixner write_seqcount_begin(&tk_core.seq);
249606c017fdSJohn Stultz
2497aa6f9c59SJohn Stultz __hardpps(phase_ts, raw_ts);
249806c017fdSJohn Stultz
24993fdb14fdSThomas Gleixner write_seqcount_end(&tk_core.seq);
250006c017fdSJohn Stultz raw_spin_unlock_irqrestore(&timekeeper_lock, flags);
2501aa6f9c59SJohn Stultz }
2502aa6f9c59SJohn Stultz EXPORT_SYMBOL(hardpps);
2503a2d81803SRobert P. J. Day #endif /* CONFIG_NTP_PPS */
2504