[PATCH] timekeeping: Skip unchanged leap state publication in adjtimex()
From: Hagen Paul Pfeifer
Date: Tue Nov 24 2026 - 14:14:01 EST
Every adjtimex() call that does not set the clock ends in
tk_update_leap_state_all(), plain read-only queries included. The
function always opens the timekeeper sequence count, so tasks that read
the time at that moment have to retry, although the published leap
state stays the same. Without a pending leap second next_leap_ktime is
KTIME_MAX before and after the call, and with a leap second pending,
repeated queries leave it unchanged as well.
Compute the new value in the shadow timekeeper first and open the
sequence count only if it differs from the published value. Both values
are protected by tkd->lock, which __do_adjtimex() holds;
lockdep_assert_held() documents this. Comparing the computed value
instead of the adjtimex mode bits keeps real changes, such as cancelling
a pending leap second.
The leap state changes only when a leap second is set, cancelled or has
passed, which is rare. So the extra comparison is cheap and saves the
write section on almost every call.
Noticed while tracing the stress-ng clock stressor on PREEMPT_RT, which
calls adjtimex() at a high rate.
Tested on x86_64 under KVM on top of tip timers/core: 10,000
read-only queries went from 10,000 publications to none, also with a
leap second pending. Setting, cancelling or switching a pending leap
second still publishes exactly once, and the leap second still takes
effect. A 60 second stress run with concurrent clock readers and
adjtimex() callers saw no clock going backwards. The timer selftests
valid-adjtimex, set-tai, nanosleep, posix_timers and leap-a-day pass,
with and without PREEMPT_RT.
Signed-off-by: Hagen Paul Pfeifer <hagen@xxxxxxxx>
---
Notes:
Also run on auxiliary clocks (CONFIG_POSIX_AUX_CLOCKS): same behaviour
with and without the patch, read-only clock_adjtime() calls no longer
publish. No measurable change in adjtimex() throughput. 32-bit x86 is
compile-tested only (i386_defconfig, W=1).
kernel/time/timekeeping.c | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/kernel/time/timekeeping.c b/kernel/time/timekeeping.c
index 3668bd24fa4f..22b146822049 100644
--- a/kernel/time/timekeeping.c
+++ b/kernel/time/timekeeping.c
@@ -738,9 +738,16 @@ static inline void tk_update_leap_state(struct timekeeper *tk)
*/
static void tk_update_leap_state_all(struct tk_data *tkd)
{
+ struct timekeeper *tks = &tkd->shadow_timekeeper;
+
+ lockdep_assert_held(&tkd->lock);
+
+ tk_update_leap_state(tks);
+ if (tkd->timekeeper.next_leap_ktime == tks->next_leap_ktime)
+ return;
+
write_seqcount_begin(&tkd->seq);
- tk_update_leap_state(&tkd->shadow_timekeeper);
- tkd->timekeeper.next_leap_ktime = tkd->shadow_timekeeper.next_leap_ktime;
+ tkd->timekeeper.next_leap_ktime = tks->next_leap_ktime;
write_seqcount_end(&tkd->seq);
}
base-commit: 0359ecff58853a491dd0f09792fea8e87235ae06
--
2.53.0