From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.221.41 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796033264; b=msSJl7wdtoFJnvGNXYG0XK9gpGh5hXepPBTUJAmvlwtxVPD3TYtJUQ1wPtQUvlXex/2E h5Q4R3I7RMHafFeYoF7VQyLY1SAOqYGyeslhh63kK3+cmxV3d21NRd234Ae31r3VQuFwV JsJr+IYibYOASY6AzHWwSeTEsECkT+qvRHUQE2sGp4cRtyoqnO9YxOIpCwxRwkfrKPeNL fvMka/k3+SGnF9NNjYFipquDi2thfT+sHZMeDJV2r+jAZZZF2ot5q072YfJ7Mtaej1t4E YhLvny2N2UCZJMCgbWaAFNv21bUxXr9z7IvUxxW++3mCWLAdP3AaobNgFyafLxibI7w== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796033264; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-ID:X-Mailer:MIME-Version: Content-Transfer-Encoding; bh=4NueczoKFnktfBR27Z7wfNy77QQ8lf1fxAukO1HVAvY=; b=IX+G0wSInDRdVTVaPyZzQfTJMhkHAXI1wKQVnMEcKzaSGJ0j/+x8fN2NlVxQt+6y1+KC hHMyQpYvnou6tKOEYrVgmI0sl6//moakEZmOitT2cdPc3Y+qoyW4j/bYTs5m7HrsvP/zS tsognVCe84M/LXVCj+f/FN152khclBdmFVUQMvK7jEIFx10WZct5jCNu5mljR0MfOyLQU fx5MBQAO8rs9F3qFd/NrBINbaOxrNj9BVlQuSd3KNcy4TGx2ECfBADh6aANIyyvr1ih8g 2kYKfO8bHAsRmla9oEi/6BrAEsXtdy/r4ALESwny/iCyaS8QrJdPxI/uQdLkkk6oTug== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=UeIB2pDH; arc=none smtp.remote-ip=209.85.221.41 Received: from mail-wr1-f41.google.com (mail-wr1-f41.google.com [209.85.221.41]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 6DDCB606A31C for ; Mon, 30 Nov 2026 10:07:44 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 6DDCB606A31C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=UeIB2pDH Received: by mail-wr1-f41.google.com with SMTP id ffacd0b85a97d-4c84abcb549so154471f8f.1 for ; Mon, 30 Nov 2026 02:07:44 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796033263; x=1796638063; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:from:to:cc:subject:date:message-id:reply-to:content-type; bh=4NueczoKFnktfBR27Z7wfNy77QQ8lf1fxAukO1HVAvY=; b=UeIB2pDHShpcQZ1dJS71AqRyDTzALUJazMU7o2NMykr9s3wAochZ7IpEzS6gpQChWO xIVhSIddGUKw0+PPMFJpwrliQezJVNWhxzrksYfSlg6qTw/tyXw5kME6K67205z7pOy5 2XNWh+I/ILgHw6CZ05gzwwR+jeJlMZ+3QHSHrpfi0B5x7duT/AJvEoDkI09CTeCrhWNs IeWHMSwPVmxsirsdkNpernWszKZqr/IJ8MbF0rzquxO0sKIXEBSc3mb6stbiCvN4zKEP 6PCTIb59FxhRHBKDTip5vyH/Z0Ri2zX9Ypls3E6bxfhhvsftCKH1TELRCAIlKckUlDU8 xVtw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796033263; x=1796638063; h=content-transfer-encoding:mime-version:message-id:date:subject:cc :to:from:x-gm-gg:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=4NueczoKFnktfBR27Z7wfNy77QQ8lf1fxAukO1HVAvY=; b=ntZpyF15V/7vQ/nl+C5wwD/kMlEcwJ7zw4moAueZ6omR7lkqI4pTMVe4a7O7vyB8b/ XHtkHzHO67zyeBxnXW71xw6l3tA2lPKfchtY+m4xCDnuias/buc6E2hGXLe9cjdypr7c DOALVH6MhwH50NEKn6cfiOpBswpbJtiJMpHdcFIrny9skZH2SwXkYS5PeMeX/lebuxT/ 1+4X1pdFE6DJJvpvtSIPl7roZDMX3GaHZpdXfbh2a6eZYyF1aFX8veZBLPcpNGfSQVs8 ifQ+dc1e2LgbGPH/Ep7LsK5ynC8bq+t/E0PZpTXNMqw7QYf1QxU5FB8G6VUFJHDVN+xj dxKA== X-Forwarded-Encrypted: i=1; AL+hErGv35z3ffs6qRR8/82rM8GCu/WLCzia8PTbB02LfYIaSxccSgMCKXlyI5GK3P2CFlOchSGz+JlQK2B5UCg=@vger.kernel.org X-Gm-Message-State: APuU4Z9CI3ij5v7NS+JS9ISyXjl9qVSp3WXWkqYVfAZi+KzSsjuFk7Jk wRsCiMx6RNmCpoeOcdUhgDSpa1GpdbMbh4hXGLMLmpW9qD+RQ0K3epVFo4/fyw== X-Gm-Gg: AZFdTZfThYTW40phMERBtA/tCOgrEeNUmPsXzqCfgIys1OE+OppPg23jF0NBH6xc99z d1l3zvI0ohjaYe8oZaCzG5Oc7048Atln/8LfXi8/q9KYYouSOcmTTBCDklz0PAGY7iUWfg4dE79 rZk37L+5PvK7pZ4sqld4yi8MRqV2+sUjXZ9wHwvj8ICLXX3Kp8uOpJoqhnGSaDe8RlmHJ66OV9T MbEWXrwg8ZxWCKGRSnTml5q5c/Oxn3jzztBUtajSsH1yWoLvMxLVWhgJcy4ukkLjDDVEZVAyi2H 1LPraoUl5HhcH5HRIUSDc2SD35Rd7t4uXgHXl8hNVLlL11qvwtDHUsl2M+LP0Jzr91Z06z8+uQg hb+nMJfaWNanf8E1SRp2dfaZ7vaa2G/p6MzmMl36BPAu/szQvSNJEZbjqrdNmqjbbrUtMpZKzAa LONWukIVVKAGaUNAHZ63GgP8rcU4AGWl47+uXzNuyJXiYe2BgTrpBOhFQf9R2QlTHmbLqm6CVqX 15KNcJPXS5wbyjLALQa/Gc35zFkvMrfN/8z9+4DA4BZiF3p2aUaSsLmy9/Gum2QF1sOop3dHhI0 2tQcvy8OMgPyVJvmwNUGTJHjmiKwdNgcGL+ZChT1FPKB8PxFo40aPwlYMaJIUy+c+Nwd42832HB d9Fcbdh5J4fykBgvPitesjzRowh9A+sauhbR9hA== X-Received: by 2002:a5d:5f08:0:b0:4ab:f5b0:a7f9 with SMTP id ffacd0b85a97d-4abf5b0a8fcmr58586399f8f.4.1796033262425; Mon, 30 Nov 2026 02:07:42 -0800 (PST) Received: from andreayoga.localdomain (93-42-14-189.ip84.fastwebnet.it. [93.42.14.189]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-4ab65cb4341sm63037297f8f.4.2026.11.30.02.07.41 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 30 Nov 2026 02:07:42 -0800 (PST) From: Andrea Parri To: John Stultz , Thomas Gleixner Cc: Stephen Boyd , Miroslav Lichvar , linux-kernel@vger.kernel.org Subject: [PATCH] timekeeping: Mark auxiliary clock active under tk_core.lock Date: Mon, 30 Nov 2026 11:07:32 +0100 Message-ID: <20261130100733.13227-1-parri.andrea@gmail.com> X-Mailer: git-send-email 2.53.0 X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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 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 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 #include #include #include #include #include #include #include #include #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