* [PATCH] timekeeping: Mark auxiliary clock active under tk_core.lock
@ 2026-11-30 10:07 Andrea Parri
0 siblings, 0 replies; only message in thread
From: Andrea Parri @ 2026-11-30 10:07 UTC (permalink / raw)
To: John Stultz, Thomas Gleixner; +Cc: Stephen Boyd, Miroslav Lichvar, linux-kernel
Enabling an auxiliary clock can race with a clocksource change, leaving
its timekeeper on the old clocksource until the next change. On x86-64,
a timekeeper left on hpet after tsc is selected runs fast by the
TSC/HPET frequency ratio, 31 with a 3.1 GHz TSC and QEMU's 100 MHz HPET.
aux_clock_enable() binds the auxiliary timekeeper to the current
clocksource under tk_core.lock, but aux_clock_enable_store() sets its
bit in aux_timekeepers only after the lock is dropped. On a preemptible
kernel the stopper thread can run in between, and
tk_aux_update_clocksource() rebinds only timekeepers whose bit is set:
CPU 0 CPU 1
aux_clock_enable()
lock tk_core.lock
bind aux timekeeper to old
unlock tk_core.lock
<preempted by stopper> stop_machine(change_clocksource, new)
switch core timekeeper to new
tk_aux_update_clocksource()
bit clear, timekeeper skipped
old->disable(old)
module_put(old->owner)
set_bit(id, &aux_timekeepers)
The auxiliary timekeeper then keeps the old clocksource pointer along
with its mult, shift, mask and cycle_last. Since commit 2e27beeb66e4
("timekeeping: Allow inlining clocksource::read()"), tk_clock_read() on
x86-64 reads the TSC directly once tsc is selected, so a timekeeper left
on hpet converts TSC cycles with the HPET mult and shift.
Without the inline read, tk_clock_read() calls the old clocksource's
read() callback instead. Either way, timekeeping_cycles_to_ns() and
__timekeeping_advance() read ->max_cycles and ->max_raw_delta from the
old clocksource, which is a use-after-free if it was unregistered and
freed. That case was not tested.
Set the bit in aux_clock_enable() before tk_core.lock is released.
stop_machine() cannot run change_clocksource() while this CPU holds
tk_core.lock with interrupts disabled, so the change either runs before
the timekeeper is set up, which then uses the new clocksource, or after
the bit is set and rebinds it.
The disable path needs no change. aux_clock_disable() clears
clock_valid before the bit is cleared, and tk_aux_update_clocksource()
skips timekeepers with clock_valid false.
Tested in a 4-vCPU x86-64 KVM guest with PREEMPT_LAZY. One thread
alternates the clocksource between tsc and hpet. Another toggles aux
clock 0, checks current_clocksource after each enable and samples the
CLOCK_AUX rate after every transition to tsc. Unpatched, 3 out of 3
runs hit the race within 3 transitions to tsc. Patched, none of
919075 transitions to tsc did.
The bug was found with the help of an LLM, which was also used to write
the fix, the changelog and the tests.
Fixes: 7b95663a3d96 ("timekeeping: Provide interface to control auxiliary clocks")
Signed-off-by: Andrea Parri <parri.andrea@gmail.com>
Cc: stable@vger.kernel.org
---
Reproducer below, run as root with "auxrace [seconds]". It needs a
preemptible x86-64 kernel and the tsc and hpet clocksources, e.g. a QEMU
guest with "-cpu host,+invtsc" and a machine type that provides an HPET.
Without this patch it prints "HIT" and a rate of about 31 until the next
clocksource switch. With it, it prints "no hit" along with the
transition and sample counts. It exits with 3 if no transition to tsc
was sampled or a switch request failed, and with 4 if tsc or hpet is
missing.
// SPDX-License-Identifier: GPL-2.0
/*
* Race enabling an auxiliary clock against clocksource changes.
*
* CPU 1 toggles aux clock 0 on and off. CPU 2 alternates the system
* clocksource between tsc and hpet, one switch per request from CPU 1.
*
* After each enable, CPU 1 reads current_clocksource. The read takes
* clocksource_mutex, so it waits for a switch in flight and reports every
* completed transition, including one that ran during the enable. On each
* transition to tsc, with the clock still enabled, CPU 1 compares the rate
* of CLOCK_AUX against CLOCK_MONOTONIC_RAW. An auxiliary timekeeper left
* on hpet after a switch to tsc runs at the TSC/HPET frequency ratio. A
* stale binding after a switch to hpet keeps the right rate and is not
* detected.
*
* Needs root, at least three CPUs, the tsc and hpet clocksources and a
* preemptible x86-64 kernel: the race window needs preemption, and only
* x86-64 reads the TSC inline, which is what makes a stale hpet binding
* visible in the rate.
* Build: gcc -O2 -pthread -o auxrace auxrace.c
* Usage: auxrace [seconds] (default 60)
* Exit status: 0 race hit, 2 no hit, 3 inconclusive (no transition to tsc
* sampled, or a switch request failed), 4 tsc or hpet missing.
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define CLOCK_AUX0 16
#define EN_PATH "/sys/kernel/time/aux_clocks/0/aux_clock_enable"
#define CS_PATH "/sys/devices/system/clocksource/clocksource0/current_clocksource"
#define AV_PATH "/sys/devices/system/clocksource/clocksource0/available_clocksource"
static atomic_int go, stop;
static const char *_Atomic target;
static void pin(int cpu)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
if (sched_setaffinity(0, sizeof(set), &set))
perror("sched_setaffinity");
}
static void wr(int fd, const char *s)
{
if (pwrite(fd, s, strlen(s), 0) < 0) {
perror("pwrite");
exit(1);
}
}
/* Current clocksource name, without the trailing newline */
static void rd(int fd, char *buf, size_t len)
{
ssize_t n = pread(fd, buf, len - 1, 0);
if (n <= 0) {
perror("pread");
exit(1);
}
buf[n] = '\0';
buf[strcspn(buf, "\n")] = '\0';
}
/* Whether @name is listed in available_clocksource */
static int available(const char *name)
{
char buf[256], *tok, *save;
int fd = open(AV_PATH, O_RDONLY);
ssize_t n;
if (fd < 0) {
perror(AV_PATH);
exit(1);
}
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0)
return 0;
buf[n] = '\0';
for (tok = strtok_r(buf, " \n", &save); tok; tok = strtok_r(NULL, " \n", &save))
if (!strcmp(tok, name))
return 1;
return 0;
}
static long long ns(clockid_t clk)
{
struct timespec ts;
clock_gettime(clk, &ts);
return ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
/* Lower bound of the CLOCK_AUX0 / CLOCK_MONOTONIC_RAW rate ratio */
static double rate(long long interval)
{
long long r0 = ns(CLOCK_MONOTONIC_RAW), a0 = ns(CLOCK_AUX0), a1, r1;
while (ns(CLOCK_MONOTONIC_RAW) - r0 < interval)
;
a1 = ns(CLOCK_AUX0);
r1 = ns(CLOCK_MONOTONIC_RAW);
return (double)(a1 - a0) / (r1 - r0);
}
static void *switcher(void *arg)
{
int fd = open(CS_PATH, O_WRONLY);
if (fd < 0) {
perror(CS_PATH);
exit(1);
}
pin(2);
while (!atomic_load(&stop)) {
if (!atomic_load(&go))
continue;
wr(fd, atomic_load(&target));
atomic_store(&go, 0);
}
close(fd);
return NULL;
}
static unsigned long requests;
static int pending; /* a request is out and not yet accounted for */
static void request_other(const char *cur)
{
atomic_store(&target, strcmp(cur, "tsc") ? "tsc" : "hpet");
atomic_store(&go, 1);
requests++;
pending = 1;
}
int main(int argc, char **argv)
{
long long end = ns(CLOCK_MONOTONIC) +
(argc > 1 ? atoll(argv[1]) : 60) * 1000000000LL;
unsigned long enables = 0;
unsigned long transitions = 0, to_tsc = 0, samples = 0, failed = 0;
int k, busy, hit = 0, en = open(EN_PATH, O_WRONLY), cs = open(CS_PATH, O_RDONLY);
char cur[32], now[32];
double r = 0;
pthread_t t;
if (en < 0 || cs < 0) {
perror("open");
return 1;
}
if (!available("tsc") || !available("hpet")) {
printf("skip: tsc and hpet must both be in available_clocksource\n");
return 4;
}
pin(1);
wr(en, "0");
rd(cs, cur, sizeof(cur));
k = pthread_create(&t, NULL, switcher, NULL);
if (k) {
fprintf(stderr, "pthread_create: %s\n", strerror(k));
return 1;
}
request_other(cur);
/* After the deadline, keep going until the last request is resolved */
while (!hit && (pending || ns(CLOCK_MONOTONIC) < end)) {
wr(en, "1");
enables++;
busy = atomic_load(&go);
rd(cs, now, sizeof(now));
if (strcmp(now, cur)) {
transitions++;
pending = 0;
strcpy(cur, now);
if (!strcmp(cur, "tsc")) {
to_tsc++;
samples++;
r = rate(200000);
if (r > 3.0) {
hit = 1;
break;
}
}
while (atomic_load(&go))
;
} else if (pending && !busy) {
/* The request completed without a transition */
failed++;
pending = 0;
}
if (!pending && ns(CLOCK_MONOTONIC) < end)
request_other(cur);
wr(en, "0");
}
/* No further switches, they would rebind the auxiliary timekeeper */
while (atomic_load(&go))
;
atomic_store(&stop, 1);
pthread_join(t, NULL);
printf("enables=%lu requests=%lu transitions=%lu to_tsc=%lu samples=%lu failed=%lu\n",
enables, requests, transitions, to_tsc, samples, failed);
if (!hit && (!samples || failed)) {
printf("inconclusive: no transition to tsc sampled, or a switch request failed\n");
return 3;
}
if (!hit) {
printf("no hit\n");
return 2;
}
printf("HIT: aux/raw rate %.2f after transition to tsc\n", r);
for (k = 0; k < 3; k++) {
usleep(200000);
printf(" aux/raw rate over 1ms: %.2f\n", rate(1000000));
}
wr(open(CS_PATH, O_WRONLY), "hpet");
printf(" after switching to hpet: %.2f\n", rate(1000000));
return 0;
}
kernel/time/timekeeping.c | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/kernel/time/timekeeping.c b/kernel/time/timekeeping.c
index be72cfd2b1ca0..d8560d9d0ff32 100644
--- a/kernel/time/timekeeping.c
+++ b/kernel/time/timekeeping.c
@@ -3319,6 +3319,12 @@ static void aux_clock_enable(clockid_t id)
/* Mark it valid and set it live */
aux_tks->clock_valid = true;
timekeeping_update_from_shadow(aux_tkd, TK_UPDATE_ALL);
+
+ /*
+ * Mark it active before tk_core.lock is dropped, so that any later
+ * clocksource change rebinds it in tk_aux_update_clocksource().
+ */
+ set_bit(id - CLOCK_AUX, &aux_timekeepers);
}
static void aux_clock_disable(clockid_t id)
@@ -3351,7 +3357,6 @@ static ssize_t aux_clock_enable_store(struct kobject *kobj, struct kobj_attribut
if (enable) {
aux_clock_enable(CLOCK_AUX + id);
- set_bit(id, &aux_timekeepers);
} else {
aux_clock_disable(CLOCK_AUX + id);
clear_bit(id, &aux_timekeepers);
--
2.53.0
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2026-11-30 10:07 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-30 10:07 [PATCH] timekeeping: Mark auxiliary clock active under tk_core.lock Andrea Parri
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®