From: David Woodhouse <dwmw2@infradead.org>
To: John Stultz <jstultz@google.com>
Cc: "Miroslav Lichvar" <mlichvar@redhat.com>,
"Richard Cochran" <richardcochran@gmail.com>,
"Wen Gu" <guwen@linux.alibaba.com>,
"Andrew Lunn" <andrew+netdev@lunn.ch>,
"David S. Miller" <davem@davemloft.net>,
"Eric Dumazet" <edumazet@google.com>,
"Jakub Kicinski" <kuba@kernel.org>,
"Paolo Abeni" <pabeni@redhat.com>,
"Thomas Gleixner" <tglx@kernel.org>,
"Stephen Boyd" <sboyd@kernel.org>,
"Anna-Maria Behnsen" <anna-maria@linutronix.de>,
"Frederic Weisbecker" <frederic@kernel.org>,
"Shuah Khan" <shuah@kernel.org>,
"Peter Zijlstra" <peterz@infradead.org>,
"Thomas Weißschuh" <thomas.weissschuh@linutronix.de>,
"Arnd Bergmann" <arnd@arndb.de>,
linux-kernel@vger.kernel.org
Subject: Re: [RFC PATCH 1/4] timekeeping: Remove xtime_remainder from ntp_error accumulation
Date: Tue, 19 May 2026 23:20:07 +0100 [thread overview]
Message-ID: <b48d8b78d5c4f330d1bda16943609abf104ec11d.camel@infradead.org> (raw)
In-Reply-To: <CANDhNCoGOUj9O7VWWN2Um8svMb0UfU7X6becmAJUyGFaH7EYoQ@mail.gmail.com>
[-- Attachment #1: Type: text/plain, Size: 10139 bytes --]
On Tue, 2026-05-19 at 14:54 -0700, John Stultz wrote:
>
> Its a nice analogy. Though if you're going to use it in your commit
> messages, it might be good to also add a comment to the
> timekeeping_adjustment() logic so there is an clear anchor to the code
> for folks who might not be as familiar with the detail.
>
>
> > > Also I'm not sure its very clear what you mean by "monotonicity clawback".
> >
> > This is the offset applied by timekeeping_apply_adjustment() in order
> > to ensure that the observed xtime remains monotonic when the dithering
> > switches back from 'mult+1' to 'mult' and a consumer may have seen a
> > 'later' time than it's about to set in {cycle_last,mult}.
> >
>
> This one I find less clarifying, but I do recognize "adjustments to
> the base xtime_nsec made when adjusting the multiplier due to
> unaccumulated cycles" is a mouthful.
>
> The "xtime_nsec adjustment in timekeeping_apply_adjustment()" is
> probably easier/clearer?
How's this...
# Linux Timekeeping: Tick-Based Clock Discipline
## Overview
The kernel exposes time to userspace via the vDSO as a linear function:
`time = base + (cycles_since_base * mult) >> shift`. Userspace reads the
cycle counter and computes the current time without a syscall.
Every tick (1ms at HZ=1000), the kernel updates this linear function: it
reads the counter, computes how much time elapsed since the last update,
advances `base` (called `xtime_nsec` internally), and publishes the new
parameters.
## mult, tick_length, and Dithering
`tick_length` is the intended duration of one tick — how much wall-clock
time should pass per tick. Again using HZ=1000 as the example, at boot
it's exactly 1ms (in shifted-ns: `1,000,000 << 32`). NTP adjusts it by
up to ±500 PPM to correct for clock drift: if the TSC runs 50 PPM slow,
NTP sets tick_length to 1.00005ms so each tick advances time slightly
more than 1ms.
`cycle_interval` is the number of counter cycles per tick — fixed at
boot from the initial TSC calibration (e.g. 2,400,000 for a 2.4 GHz TSC
at HZ=1000). This never changes.
`mult` converts cycles to time: `nanoseconds = cycles * mult >> shift`.
It's derived from `mult = tick_length / cycle_interval`. Since this
division rarely yields an integer, the kernel uses two adjacent values:
- `mult_lo = floor(tick_length / cycle_interval)` — slightly too slow
- `mult_hi = mult_lo + 1` — slightly too fast
The kernel alternates ("dithers") between these each tick so the
long-term average rate matches `tick_length` exactly. If the fractional
part of the division is 0.8, then 80% of ticks use mult_hi and 20% use
mult_lo.
There is a constraint: the vDSO must never return a time that goes
backwards. Between ticks, userspace interpolates using the published
mult. If the kernel switches from mult_hi to mult_lo, the new (slower)
interpolation line might be below where the old (faster) line already
reached. To prevent this, the kernel adjusts `base` forward when
lowering mult — setting it to where the old line would have been at the
current counter value. This adjustment is applied in
`timekeeping_apply_adjustment()`.
## The Three Reference Times
The timekeeping code tracks three distinct time values (ignoring units
for clarity):
• **(A) xtime** — the time actually output to the vDSO and userspace.
This is `xtime_nsec`, advanced each tick by `xtime_interval` (plus
the monotonicity adjustment when mult changes).
• **(B) xtime + ntp_error** — the time we *want* to be outputting
right now. The mult dithering and monotonicity adjustment keep (A)
from reaching (B) instantly, but the dithering steers (A) toward
(B) over time.
• **(C) xtime + ntp_error + time_offset** — the time we *eventually*
want to output, once we've finished slewing toward it. This is the
target set by `adjtimex()` or `timekeeping_set_reference()`.
On each tick:
• (A) advances by `xtime_interval` (= `cycle_interval * mult`), plus
the monotonicity adjustment when mult changes.
• (B) advances by `tick_length + skew_delta` — the configured rate
plus a per-tick bias that effects the slew toward (C).
• (C) advances by `tick_length` — the rate corresponding to the
`adjtimex` frequency (or the rate set by
`timekeeping_set_reference()`).
So `ntp_error`, being the delta between (B) and (A), advances each tick
by `tick_length + skew_delta - xtime_interval`. The dithering oracle
uses the sign of `ntp_error` to choose mult_hi or mult_lo, steering (A)
toward (B).
And `time_offset`, being the delta between (C) and (B), is consumed
gradually as `skew_delta` biases (B) faster or slower than (C). Once
the slew completes, `time_offset` and `skew_delta` reach zero and
(B) = (C).
## Tick Accumulation and Leftover Cycles
On each timer interrupt (which may arrive late), the kernel reads the
cycle counter and computes the delta since `cycle_last`. It then
consumes as many full `cycle_interval` chunks as fit, advancing
`cycle_last` by `cycle_interval` for each and adding `xtime_interval` to
`xtime_nsec`.
After accumulation, `cycle_last` points to the last full-tick boundary
— NOT the actual counter value at interrupt time. The remaining cycles
between `cycle_last` and the actual counter reading are the `offset`:
offset = counter_at_irq - cycle_last
These leftover cycles are NOT added to `xtime_nsec`. They remain as the
implicit gap that the vDSO interpolates: userspace computes
`time = xtime_nsec + (tsc_now - cycle_last) * mult >> shift`, so the
leftover is always accounted for at the current `mult`.
On the next interrupt, the new delta includes the previous leftover plus
new cycles. Full ticks are consumed, a new leftover remains.
This leftover is the `offset` parameter passed to `timekeeping_adjust()`
after accumulation completes. It represents cycles that the vDSO is
already interpolating at the current mult, but which haven't yet been
folded into `xtime_nsec`.
When `timekeeping_apply_adjustment()` changes mult, it must compensate:
the vDSO was interpolating those leftover cycles at the old mult, and
will now interpolate them at the new mult. To prevent a time
discontinuity visible to userspace, it adjusts:
xtime_nsec -= offset (for mult increasing by 1)
xtime_nsec += offset (for mult decreasing by 1)
This ensures `xtime_nsec + offset * mult` is the same before and after
the mult change — maintaining vDSO monotonicity.
## ntp_error: The Dithering Accumulator
`ntp_error` tracks the accumulated difference between the target rate
and the actual rate. Each tick:
```
ntp_error += ntp_tick (target advance)
ntp_error -= xtime_interval << shift (actual advance)
```
When NTP adjusts the frequency, `ntp_tick` changes but
`xtime_interval` stays at the boot-time value. The per-tick residual
drives `ntp_error` positive or negative, triggering the dithering to
compensate.
The oracle: when `ntp_error > 0` (clock is behind), use mult_hi. When
`ntp_error ≤ 0` (clock is ahead), use mult_lo.
The monotonicity adjustment (`xtime_nsec -= offset`) moves time forward
without the dithering oracle knowing. To keep `ntp_error` accurate,
`timekeeping_apply_adjustment()` adds the same offset to ntp_error:
ntp_error += offset << ntp_error_shift
This accounts for the fact that the adjustment advanced `xtime_nsec` by
`offset` shifted-ns, which the oracle must treat as actual progress.
## skew_delta and time_offset Slewing
When NTP (or `timekeeping_set_reference()`) sets a `time_offset`, the
NTP layer computes a `skew_delta` — a per-tick bias added to
`tick_length` that causes the clock to slew toward the target offset.
The slew rate is limited to ±500 µs/s (adjtime) or the full offset
divided over a decay period.
`timekeeping_adjust()` recomputes mult whenever `ntp_tick` or
`skew_delta` changes:
mult = (ntp_tick + skew_delta) >> ntp_error_shift / cycle_interval
The `skew_delta` biases mult so that the ±1 dithering naturally delivers
the slew. As the offset is consumed, `skew_delta` decays toward zero.
The `ntp_error` accumulator accounts for `skew_delta` partially: it
credits only the portion of `skew_delta` actually delivered by the
current tick's mult choice, not the full requested amount. This allows
the dithering to converge `ntp_error` toward zero while simultaneously
delivering the slew.
## timekeeping_set_reference(): Feed-Forward Discipline
An external reference (e.g. vmclock from a host with NTP-disciplined
time) can set the clock's rate and phase directly via
`timekeeping_set_reference()`. This function:
1. **Validates the clocksource** — returns `-ENODEV` if the active
clocksource doesn't match the reference's `cs_id`.
2. **Sets tick_length** — converts the reference's `period_frac_sec`
(counter period in 1/2^64 seconds) to the kernel's `tick_length`
format (shifted-ns per tick):
tick_length = period_frac_sec * cycle_interval * NSEC_PER_SEC
>> (32 + period_shift)
3. **Computes the phase offset** — extrapolates the reference time to
`cycle_last` and compares with the kernel's current `xtime_nsec`:
ref_time_at_cycle_last = time_frac_sec +
delta_cycles * period_frac_sec >> period_shift
ref_err = ref_time_in_shifted_ns - xtime_nsec
4. **Sets time_offset** — programs the NTP slew machinery to converge
toward the reference phase. The existing `skew_delta` mechanism
delivers this offset over subsequent ticks.
5. **Clears ntp_error** — resets the dithering accumulator so it starts
fresh relative to the new rate, avoiding stale bias from the
previous discipline state.
All of this happens under `tk_core.lock`, making it atomic with respect
to tick processing. The function is fire-and-forget: it programs the
rate and phase, then the normal tick machinery delivers the correction
autonomously.
[-- Attachment #2: smime.p7s --]
[-- Type: application/pkcs7-signature, Size: 5069 bytes --]
next prev parent reply other threads:[~2026-05-19 22:20 UTC|newest]
Thread overview: 16+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-05-13 20:44 [RFC PATCH 0/4] timekeeping: add feed-forward clock discipline via vmclock David Woodhouse
2026-05-13 20:44 ` [RFC PATCH 1/4] timekeeping: Remove xtime_remainder from ntp_error accumulation David Woodhouse
2026-05-15 22:49 ` John Stultz
2026-05-16 8:25 ` David Woodhouse
2026-05-19 1:37 ` John Stultz
2026-05-19 9:16 ` David Woodhouse
2026-05-19 21:54 ` John Stultz
2026-05-19 22:18 ` David Woodhouse
2026-05-20 0:01 ` John Stultz
2026-05-20 1:01 ` David Woodhouse
2026-05-19 22:20 ` David Woodhouse [this message]
2026-05-20 0:32 ` John Stultz
2026-05-20 0:50 ` David Woodhouse
2026-05-13 20:44 ` [RFC PATCH 2/4] WIP: kernel/time: Add /dev/vmclock_host miscdev David Woodhouse
2026-05-13 20:44 ` [RFC PATCH 3/4] timekeeping: Add absolute reference for feed-forward clock discipline David Woodhouse
2026-05-13 20:44 ` [RFC PATCH 4/4] ptp_vmclock: Feed reference to timekeeping for feed-forward discipline David Woodhouse
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=b48d8b78d5c4f330d1bda16943609abf104ec11d.camel@infradead.org \
--to=dwmw2@infradead.org \
--cc=andrew+netdev@lunn.ch \
--cc=anna-maria@linutronix.de \
--cc=arnd@arndb.de \
--cc=davem@davemloft.net \
--cc=edumazet@google.com \
--cc=frederic@kernel.org \
--cc=guwen@linux.alibaba.com \
--cc=jstultz@google.com \
--cc=kuba@kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=mlichvar@redhat.com \
--cc=pabeni@redhat.com \
--cc=peterz@infradead.org \
--cc=richardcochran@gmail.com \
--cc=sboyd@kernel.org \
--cc=shuah@kernel.org \
--cc=tglx@kernel.org \
--cc=thomas.weissschuh@linutronix.de \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®