From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=TXeKnQg275OclMt6rQjmYvFpzBEBAfPxtIBMmglqNScCTBLYwDnsqT4SqCxPawNtH5VA nQ/Q/hOGylISSHqCx1CjPLzojvmy9oDK9204Pn8A6cLnj8ymRMz6IJN+vtdV+daWIgo2H 6QWmR9+yvR51oHyy3qN2SyQTFPXcwfxN4H7GDOazFeywio+Uf1CKaxz6EQeHFrSZGyznf 2ReMf1qXiGVXxFQsoJl8mmPg5q4NPlrPvmMUwn6DchvC7ZlzgKO5Rnz/GyAVgxtqe595k 9kMSKjHtBXU2UTIiPxGApd7gacIZonSzKIoyvTzsZKGTbYzwju+3IM3x9XH/9nszESQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=LHsRlifsljGRXRN3+a2hsoPBPeF/jXGyHr0leVXSUNM=; b=tuuczCSVajnGylmG5QsSl8njUTzJyAcBJX2zZMahTEOTZBkKNBa3tSUmouhtMNbN3q98 emTCx95pyeaiq14ztQH8UwYiFm0gM8lzV3q6i0TG39Nuac0g3G4wB+7/GYdqz5Maaft0k pH8KVk3LUXfisYp+vS9yrVELYoZrNu828bmUHeRRYUZ75qA2Qt1Nh069u78dsv0yA0yG6 s7oFfnsqhDVKU3ohwT1INboaL4OEGpbKtSmCIsJjBrEc2s7O9dZ+08BdQiIjorweTDhJD DkMwqxrjTOJAZxQzrOMfvw6mm7MZxhzewD4qknzhrY2EvTpHfGpBRJ3jTt6v53sR1qA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=SW3hAMqY; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 1161F606B7B1; Wed, 11 Nov 2026 18:09:37 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 1161F606B7B1 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=SW3hAMqY DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=LHsRlifsljGRXRN3+a2hsoPBPeF/jXGyHr0leVXSUNM=; b=SW3hAMqYnnh+DDe/fvssjLS794 HFUUxdTw+KRaktlO2adxyKfroG22VsEs4s72KIpB9Ij60T3pJSA0dDhrFBWi3/wztujBJMcB9kklk b9yLwWo7/HYOYV9jwCB1TsYSNLobgHAKKkhtciTvYxc1BMu1M2Fb7u4GJOxlU8ne0yXHztrxJdZwc thi80wPSh/P0FCxdaCzB9EX7FlaejKI//Ug4I8cst2TTp3Vx1m1K2/iu34tVGBh/NhDSIV7U5gBtf Xsv86+T+Bn6c0DGhfIxu4Nz5IbC6ktTdCQaYuXtry/ILHVstnqk1DQ/S+lLaTJVXhMX1l1wRrZwCe RH9hjY3Q==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvI-3CEJ; Wed, 11 Nov 2026 18:09:30 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl8-0000000HWs4-3DmC; Wed, 11 Nov 2026 18:09:22 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 01/26] KVM: x86: Improve synchronization in kvm_synchronize_tsc() Date: Wed, 11 Nov 2026 10:08:57 -0800 Message-ID: <20261111180922.4177927-2-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse When synchronizing to an existing TSC (either by explicitly writing zero, or the legacy hack where the TSC is written within one second's worth of the previously written TSC), the last_tsc_write and last_tsc_nsec values were being misrecorded by __kvm_synchronize_tsc(). The *unsynchronized* value of the TSC (perhaps even zero) was being recorded, along with the current time at which kvm_synchronize_tsc() was called. This could cause *subsequent* writes to fail to synchronize correctly. Fix that by extrapolating the generation's TSC value to the current time (data =3D cur_tsc_write + elapsed cycles) before passing it to __kvm_synchronize_tsc(), so the recorded {data, ns} pair always lies on the generation's line and the one-second matching window slides forward with each synchronized write. When the TSC is stable, reuse the generation's offset exactly; when it is unstable, compute a new offset for the extrapolated value. Furthermore, there were *three* different TSC reads used for calculating the "current" time, all slightly different from each other. Fix that by using kvm_get_time_and_clockread() where possible and using the same host_tsc value in all cases. Extrapolating from the generation's origin at the nominal frequency means a guest within tsc_tolerance_ppm of the host (where hardware scaling is not engaged) drifts out of the one-second window after about 67 minutes; a write which then fails to match still installs the exact value, at the cost of a fresh generation. The old per-write re-anchoring bounded that drift, but recorded points the generation's line did not pass through =E2=80=94 the bug this patch exists to fix. Signed-off-by: David Woodhouse Reviewed-by: Paul Durrant --- arch/x86/kvm/x86.c | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 32563a91fba9..7a2b0b99373f 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -210,6 +210,10 @@ module_param(pi_inject_timer, bint, 0644); static bool __read_mostly mitigate_smt_rsb; module_param(mitigate_smt_rsb, bool, 0444); =20 +#ifdef CONFIG_X86_64 +static bool kvm_get_time_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp); +#endif + #define KVM_SUPPORTED_XCR0 (XFEATURE_MASK_FP | XFEATURE_MASK_SSE \ | XFEATURE_MASK_YMM | XFEATURE_MASK_BNDREGS \ | XFEATURE_MASK_BNDCSR | XFEATURE_MASK_AVX512 \ @@ -1374,14 +1378,23 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64= *user_value) { u64 data =3D user_value ? *user_value : 0; struct kvm *kvm =3D vcpu->kvm; - u64 offset, ns, elapsed; + u64 offset, host_tsc, elapsed; + s64 ns; unsigned long flags; bool matched =3D false; bool synchronizing =3D false; =20 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); - offset =3D kvm_compute_l1_tsc_offset(vcpu, rdtsc(), data); - ns =3D get_kvmclock_base_ns(); + +#ifdef CONFIG_X86_64 + if (!kvm_get_time_and_clockread(&ns, &host_tsc)) +#endif + { + host_tsc =3D rdtsc(); + ns =3D get_kvmclock_base_ns(); + } + + offset =3D kvm_compute_l1_tsc_offset(vcpu, host_tsc, data); elapsed =3D ns - kvm->arch.last_tsc_nsec; =20 if (vcpu->arch.virtual_tsc_khz) { @@ -1424,13 +1437,21 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64= *user_value) */ if (synchronizing && vcpu->arch.virtual_tsc_khz =3D=3D kvm->arch.last_tsc_khz) { - if (!kvm_check_tsc_unstable()) { + /* + * If synchronizing, advance the reference point to "now" + * so the matching window slides forward with each vCPU. + * Extrapolate from the generation's own origin: 'elapsed' + * is measured from the most recent write, which lies on + * the generation's line only for the first matched write. + */ + u64 delta =3D nsec_to_cycles(vcpu, ns - kvm->arch.cur_tsc_nsec); + + data =3D kvm->arch.cur_tsc_write + delta; + + if (!kvm_check_tsc_unstable()) offset =3D kvm->arch.cur_tsc_offset; - } else { - u64 delta =3D nsec_to_cycles(vcpu, elapsed); - data +=3D delta; - offset =3D kvm_compute_l1_tsc_offset(vcpu, rdtsc(), data); - } + else + offset =3D kvm_compute_l1_tsc_offset(vcpu, host_tsc, data); matched =3D true; } =20 --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=I8EK1HV7QHFAUdzQUqaTxqPLmR0APwqmbgg2UxDyZGob1nYg368Cz4z/fqa1Utx/yYex UvjmYFXfq92J+cNc35GMJAoi+Iq7KP+iU6oKum+EBSW4UZDc0qRSd49+RFqPk70r04hzd i3Oz8bJbIvoDYCfuESC9Euml68iDQneDzUpkGYLWvn5xqXZLiIrOdYnpunHKQ0crxCnJs NlFIqn3TmB63Q92aXItdKSy2V+VGH8k3Aud88w6Xvyu8A49iqYjuNSMfNYycjtvt8Ac1T /VzL0noAvtJvgGyzNG1M65HjNOJqnWQjxnmplZuKWvgwearG7e8Tb+vib/8PU6nisSg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=+A9Stxes180y3/UPopEooT4olRi063r0UwlDJ4vvUVk=; b=HeLw5X1iu0GxVrkWMbmLGdyGvHYz0JzDQIv+YQ/vQhLUe4/wPZMnydRL23G49pmASIRc c7c3X3stktpdNvvp5G0YO7xIslu1k3tkwOUcgAsNZhzZVrhSHklRDzRvGbqYu49RDaBsQ /fw2N7uAZe5ByV6zkyXGR6/MMKABWm+1VPWF+vMrmYNaSL8RgDucE2wSbG92gWzg6SCx7 LrYhOIdMDUbcom3+3NVotLq4SUx7NYPOSZAFo5fSKB0N5d/tYSKNlmvaHfvYABuSigT9U Gg31u2mL3TIi2E4hfAJp0W58bm4IY3/cnnEIZO941ZQ+UhCkGDfxL4cjskFDxNQ9vBA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=GgFWIqP5; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E4784606A324; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E4784606A324 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=GgFWIqP5 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=+A9Stxes180y3/UPopEooT4olRi063r0UwlDJ4vvUVk=; b=GgFWIqP5y2Xd7bbAKad9gvlMax OiUQJlTyRN4/Y0kgMAT93W4qPtA2rhqhIpyxW2s6SyUStbCOAXHAH37ORXrMVR1nZVn3+2qEyii7/ uTV/D2RIjNQzRfJPRaBO61kBow0ZOIRT8fGPD/X0KUgRgX5ZKGDM4QBJzzS/wgaQcD8OaLVjO/Gr3 VyHdzrlA18IFj0Hpg8QfxY1IGeLReh7R/hMhgWGzlXyjhmzDKZUGd8NnHM2+eMJ33GFeiQLipaeY4 i+hNibznKGldnTKRnXKDws6G3OaLpO2vOoeBw+dfzMghZ41OBHYeZ1K4ouTlxH92z9qwpM7viZcKp gZIKwDqA==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvR-02kT; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl8-0000000HWs7-3MR0; Wed, 11 Nov 2026 18:09:22 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 02/26] KVM: x86: Kill last_tsc_{nsec,write,offset} fields Date: Wed, 11 Nov 2026 10:08:58 -0800 Message-ID: <20261111180922.4177927-3-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse These mostly duplicate the cur_tsc_{nsec,write,offset} values. On the stable-TSC matching paths the offsets used were identical; the stored {nsec, write} anchor could differ, because a matched kvm_arch_tsc_set_attr() recorded a freshly measured point, quietly re-anchoring the 1-second matching window onto the guest's actual TSC line. Matching now measures from the generation's origin alone. A guest frequency within tsc_tolerance_ppm of the host's can therefore drift out of the window after about an hour of generation age; such a write opens a new generation and still installs the exact value =E2=80=94 a PVCLOCK_TSC_STABLE_BIT drop, healed as the siblings' own writes rejoin, never an inaccuracy. On the unstable-TSC paths the two values could genuinely diverge, so kvm_arch_tsc_set_attr() now matches against the generation's reference offset =E2=80=94 the more principled comparison anyway, and with an unstable TSC the match only affects generation accounting. Rename last_tsc_khz and last_tsc_scaling_ratio to cur_tsc_khz and cur_tsc_scaling_ratio, since they are properties of the current generation. With cur_tsc_offset the single source of truth for the generation's offset, the backwards-TSC compensation on S4 resume must adjust it by the same (guest-scaled) delta it applies to every vCPU; later synchronizations would otherwise match against a stale pre-S4 offset. And since a synchronization installs an absolute offset which already includes that delta, it clears the vCPU's pending tsc_offset_adjustment =E2=80=94 applying the deferred compensation on top at the next vcpu_load would double it. Previously a nonzero write could not hit this: zeroing the last_tsc values broke the matching window after a backwards TSC. Three races around that compensation are handled. The consume in kvm_arch_vcpu_load() now runs under tsc_write_lock, as an unlocked read-then-zero racing the hotplug-time fold could discard a delta the generation keeps. kvm_arch_tsc_set_attr() folds a pending adjustment into the user-supplied offset under the lock, since userspace computed it against the pre-jump TSC line. And the lockless vm_list walk in kvm_arch_enable_virtualization_cpu() remains as it was: unsound against a concurrent kvm_destroy_vm(), but pre-existing, and not fixable with kvm_lock without recreating the inversion against cpus_read_lock() that commit 44d174596260 ("KVM: Use dedicated mutex to protect kvm_usage_count to avoid deadlock") untangled. Signed-off-by: David Woodhouse Reviewed-by: Paul Durrant --- Documentation/virt/kvm/locking.rst | 3 +- arch/x86/include/asm/kvm_host.h | 7 +- arch/x86/kvm/x86.c | 132 ++++++++++++++++++++++------- 3 files changed, 105 insertions(+), 37 deletions(-) diff --git a/Documentation/virt/kvm/locking.rst b/Documentation/virt/kvm/lo= cking.rst index 662231e958a0..b3621eb3c1cd 100644 --- a/Documentation/virt/kvm/locking.rst +++ b/Documentation/virt/kvm/locking.rst @@ -263,7 +263,8 @@ time it will be set using the Dirty tracking mechanism = described above. =20 :Type: raw_spinlock_t :Arch: x86 -:Protects: - kvm_arch::{last_tsc_write,last_tsc_nsec,last_tsc_offset} +:Protects: - kvm_arch::{cur_tsc_write,cur_tsc_nsec,cur_tsc_offset,cur_tsc_= khz,cur_tsc_scaling_ratio} + - kvm_vcpu_arch::tsc_offset_adjustment - tsc offset in vmcb :Comment: 'raw' because updating the tsc offsets must not be preempted. =20 diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_hos= t.h index e2eef7057bd3..ea48b1949316 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -1236,11 +1236,8 @@ struct kvm_arch { * preemption-disabled region, so it must be a raw spinlock. */ raw_spinlock_t tsc_write_lock; - u64 last_tsc_nsec; - u64 last_tsc_write; - u32 last_tsc_khz; - u64 last_tsc_offset; - u64 last_tsc_scaling_ratio; + u32 cur_tsc_khz; + u64 cur_tsc_scaling_ratio; u64 cur_tsc_nsec; u64 cur_tsc_write; u64 cur_tsc_offset; diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 7a2b0b99373f..12f465040efc 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1334,17 +1334,24 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *= vcpu, u64 offset, u64 tsc, vcpu->kvm->arch.user_set_tsc =3D true; =20 /* - * We also track th most recent recorded KHZ, write and time to - * allow the matching interval to be extended at each write. + * Track the TSC frequency, scaling ratio, and offset for the current + * generation. These are used to detect matching TSC writes and to + * compute the guest TSC from the host clock. */ - kvm->arch.last_tsc_nsec =3D ns; - kvm->arch.last_tsc_write =3D tsc; - kvm->arch.last_tsc_khz =3D vcpu->arch.virtual_tsc_khz; - kvm->arch.last_tsc_offset =3D offset; - kvm->arch.last_tsc_scaling_ratio =3D vcpu->arch.l1_tsc_scaling_ratio; + kvm->arch.cur_tsc_khz =3D vcpu->arch.virtual_tsc_khz; + kvm->arch.cur_tsc_scaling_ratio =3D vcpu->arch.l1_tsc_scaling_ratio; =20 vcpu->arch.last_guest_tsc =3D tsc; =20 + /* + * The offset written below is absolute, superseding any backwards-TSC + * compensation still pending from kvm_arch_enable_virtualization_cpu() + * (which has already been folded into cur_tsc_offset, and thus into + * a matched @offset); applying it again at the next vcpu_load would + * double it. + */ + vcpu->arch.tsc_offset_adjustment =3D 0; + kvm_vcpu_write_tsc_offset(vcpu, offset); =20 if (!matched) { @@ -1354,8 +1361,6 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *vc= pu, u64 offset, u64 tsc, * nanosecond time, offset, and write, so if TSCs are in * sync, we can match exact offset, and if not, we can match * exact software computation in compute_guest_tsc() - * - * These values are tracked in kvm->arch.cur_xxx variables. */ kvm->arch.cur_tsc_generation++; kvm->arch.cur_tsc_nsec =3D ns; @@ -1395,7 +1400,7 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *= user_value) } =20 offset =3D kvm_compute_l1_tsc_offset(vcpu, host_tsc, data); - elapsed =3D ns - kvm->arch.last_tsc_nsec; + elapsed =3D ns - kvm->arch.cur_tsc_nsec; =20 if (vcpu->arch.virtual_tsc_khz) { if (data =3D=3D 0) { @@ -1405,7 +1410,7 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *= user_value) */ synchronizing =3D true; } else if (kvm->arch.user_set_tsc) { - u64 tsc_exp =3D kvm->arch.last_tsc_write + + u64 tsc_exp =3D kvm->arch.cur_tsc_write + nsec_to_cycles(vcpu, elapsed); u64 tsc_hz =3D vcpu->arch.virtual_tsc_khz * 1000LL; /* @@ -1436,15 +1441,14 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64= *user_value) * it's better to try to match offsets from the beginning. */ if (synchronizing && - vcpu->arch.virtual_tsc_khz =3D=3D kvm->arch.last_tsc_khz) { + vcpu->arch.virtual_tsc_khz =3D=3D kvm->arch.cur_tsc_khz) { /* - * If synchronizing, advance the reference point to "now" - * so the matching window slides forward with each vCPU. - * Extrapolate from the generation's own origin: 'elapsed' - * is measured from the most recent write, which lies on - * the generation's line only for the first matched write. + * If synchronizing, extrapolate the generation's value to + * "now": the matching window slides forward with wall time, + * anchored on the generation's origin alone (a matched + * write no longer updates any stored reference point). */ - u64 delta =3D nsec_to_cycles(vcpu, ns - kvm->arch.cur_tsc_nsec); + u64 delta =3D nsec_to_cycles(vcpu, elapsed); =20 data =3D kvm->arch.cur_tsc_write + delta; =20 @@ -1615,7 +1619,7 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) * get_kvmclock() to compute kvmclock from the host TSC * without needing a vCPU reference. */ - ka->master_tsc_scaling_ratio =3D ka->last_tsc_scaling_ratio; + ka->master_tsc_scaling_ratio =3D ka->cur_tsc_scaling_ratio; tsc_hz =3D (u64)get_cpu_tsc_khz() * HZ_PER_KHZ; if (tsc_hz && kvm_caps.has_tsc_control) tsc_hz =3D kvm_scale_tsc(tsc_hz, @@ -2603,8 +2607,24 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int c= pu) =20 /* Apply any externally detected TSC adjustments (due to suspend) */ if (unlikely(vcpu->arch.tsc_offset_adjustment)) { - adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment); + unsigned long flags; + u64 adj; + + /* + * Consume under tsc_write_lock: the writer in + * kvm_arch_enable_virtualization_cpu() folds the same delta + * into the generation's cur_tsc_offset under the lock, and + * an unlocked read-then-zero here could discard a delta the + * generation keeps, leaving this vCPU's offset diverged + * from a generation it is still counted as matching. + */ + raw_spin_lock_irqsave(&vcpu->kvm->arch.tsc_write_lock, flags); + adj =3D vcpu->arch.tsc_offset_adjustment; vcpu->arch.tsc_offset_adjustment =3D 0; + raw_spin_unlock_irqrestore(&vcpu->kvm->arch.tsc_write_lock, + flags); + + adjust_tsc_offset_host(vcpu, adj); kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); } =20 @@ -3343,9 +3363,25 @@ static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vc= pu, =20 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); =20 + /* + * A backwards-TSC compensation which landed after this + * ioctl's vcpu_load() consumed the pending adjustment was + * folded into cur_tsc_offset but not yet into this vCPU =E2=80=94 + * and @offset was computed by userspace against the + * pre-jump TSC line. Fold it into @offset here (scaled as + * adjust_tsc_offset_host() would), both so the matched + * comparison below compares like with like and because + * __kvm_synchronize_tsc() will clear the pending + * adjustment as superseded by the absolute offset it + * installs. + */ + if (unlikely(vcpu->arch.tsc_offset_adjustment)) + offset +=3D kvm_scale_tsc(vcpu->arch.tsc_offset_adjustment, + vcpu->arch.l1_tsc_scaling_ratio); + matched =3D (vcpu->arch.virtual_tsc_khz && - kvm->arch.last_tsc_khz =3D=3D vcpu->arch.virtual_tsc_khz && - kvm->arch.last_tsc_offset =3D=3D offset); + kvm->arch.cur_tsc_khz =3D=3D vcpu->arch.virtual_tsc_khz && + kvm->arch.cur_tsc_offset =3D=3D offset); =20 tsc =3D kvm_scale_tsc(rdtsc(), vcpu->arch.l1_tsc_scaling_ratio) + offset; ns =3D get_kvmclock_base_ns(); @@ -9803,7 +9839,7 @@ int kvm_arch_enable_virtualization_cpu(void) { struct kvm *kvm; struct kvm_vcpu *vcpu; - unsigned long i; + unsigned long i, flags; int ret; u64 local_tsc; u64 max_tsc =3D 0; @@ -9874,6 +9910,44 @@ int kvm_arch_enable_virtualization_cpu(void) if (backwards_tsc) { u64 delta_cyc =3D max_tsc - local_tsc; list_for_each_entry(kvm, &vm_list, vm_list) { + /* + * Hold tsc_write_lock across the per-vCPU adjustments + * AND the generation reference offset adjustment, so + * that a concurrent TSC synchronization cannot observe + * one without the other (it would compute an offset + * with the delta applied twice, or not at all). + * kvm_arch_vcpu_load() consumes tsc_offset_adjustment + * under the same lock, so it cannot discard a delta + * which has been folded into the generation + * reference. + * + * The generation's reference offset is adjusted by the + * same (guest-scaled, as adjust_tsc_offset_host() + * does for each vCPU) delta, so that future + * KVM_SET_TSC / vCPU creation still matches against + * the adjusted TSC timeline. + * + * The recorded {cur_tsc_nsec, cur_tsc_write} pair is + * left alone, and ends up stale by the sleep period: + * cur_tsc_nsec is CLOCK_BOOTTIME, which has the sleep + * injected on resume, while the guest TSC (kept + * continuous across the host TSC jump) does not + * advance during the sleep. It cannot be re-anchored + * here because, as noted above, timekeeping has not + * yet been resumed. The 1-second matching window + * therefore fails to match across a longer sleep, + * and the next nonzero TSC write opens a fresh, + * coherent generation. A forced synchronization + * (vCPU creation, or a zero write) bypasses the + * window and does extrapolate along the stale line, + * overshooting by the sleep period =E2=80=94 but it installs + * the compensated offset, so the vCPU's actual TSC + * is correct; only last_guest_tsc overshoots, which + * matters only if the TSC turns unstable before the + * vCPU first enters the guest, exactly as it did + * before this accounting existed. + */ + raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); kvm->arch.backwards_tsc_observed =3D true; kvm_for_each_vcpu(i, vcpu, kvm) { vcpu->arch.tsc_offset_adjustment +=3D delta_cyc; @@ -9881,14 +9955,10 @@ int kvm_arch_enable_virtualization_cpu(void) kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); } =20 - /* - * We have to disable TSC offset matching.. if you were - * booting a VM while issuing an S4 host suspend.... - * you may have some problem. Solving this issue is - * left as an exercise to the reader. - */ - kvm->arch.last_tsc_nsec =3D 0; - kvm->arch.last_tsc_write =3D 0; + kvm->arch.cur_tsc_offset +=3D + kvm_scale_tsc(delta_cyc, + kvm->arch.cur_tsc_scaling_ratio); + raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags); } =20 } --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=qv5Ny6a76gTy0m0Wx7ZkUAMXKBudH1Mr3GKgfCt3RtdOGvYOkj3PZyLg1kyRZ73nS6PB GekV4qJMDiem6nu10VHaMVr1WY7OjdRXmMqIjQnsk5oTYg2ZYdwYioxiGkj/PAjLQUnyM wJfCe17scA8Xbe3pNVbw6qVpgtlu15Rqm60EU45wUIDuv7PGBbUfBz7W/OuXi+EYGaODi hMef3oUsmxdRBi4kVK5rXJJRu+QAiXg79dUZk4+BIhClOpxoYka/v4kDYjSafgDGfOPJR le8cq/nw1C2fn7oqxcrFeAQNPIVzWS40ClGYgWTF9xnDRmKrMb3fMrs5+8NT6t3zgDA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=w+W4pvjVAWxDYqCzpcYD1NsnQ13Ri18fxSzd9QQRmFk=; b=QWYgc3dvV1193h/j436goxCpXkdO/DhLIElgYPnnhCTTiEzcGRI+5Kbq2CDG4H8Wm123 YU9D+wu+4kbnTbCw6oxDxdwgXIYU19W5ALQKkph70t2nTEwsmI57jZYvmEmNtwwbiqra3 drqtLcyMof6D+JFDQBgnTg/6wAg8fZ2rFHbaXlcI5X/k+xlJHl8jMLumgE0aVLCqlT5KL pfYYrT7CowWJBufrpUkSoTdPXyzshojKoo2BZJZMnY1DlW3sg6oR6j6GxLAtI4ayNAU4z ZF56ZToSi47u40twTcQWQEp/UgBPPgmEolv8uGhyhlwdUZVxvb5Rk+Kfamxbtjkumkw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=QQ2qW0AU; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 36717606B780; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 36717606B780 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=QQ2qW0AU DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=w+W4pvjVAWxDYqCzpcYD1NsnQ13Ri18fxSzd9QQRmFk=; b=QQ2qW0AUSVZF/Ix0kIAJF8qbiJ ABlCe+x/aOGBFABmHGw2uGR9P1uXXK3g6hnrl7eAMfWi8MkGOKZDTQECOpw6dBFDpNnqvxCOgqShq D2h6qVeUNWiMjybTvbM2KFs0OXGwAMa1oT5rL2Nq+Wn6JPrfWR80Ip6TTbvfXVo7Y91/wkgN7oPq3 zd6qxEc+/SmDGUkUfIM3z6ok8uTZ1d6WUGsM537f5yTLQI/XSUWGEZ54ELhCo4kqkZuHWwLh3e9mO rxVjF/yB8lwfAR1vb3J/RA+teE7sD//eNF5Gask0vdSb2l2iSh5h9i8/2XggBXUkDO2UYeXrd7vab rEZ6i4FQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvJ-3BI0; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl8-0000000HWsC-3ay4; Wed, 11 Nov 2026 18:09:22 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 03/26] KVM: x86: Replace nr_vcpus_matched_tsc count with all_vcpus_matched_tsc bool Date: Wed, 11 Nov 2026 10:08:59 -0800 Message-ID: <20261111180922.4177927-4-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Comparing nr_vcpus_matched_tsc against kvm->online_vcpus at read time was always racy =E2=80=94 a new vCPU can appear between the increment and i= ts first synchronization =E2=80=94 and it made "all vCPUs matched" an accident= of arithmetic rather than a property with defined semantics. Replace it with a boolean maintained at synchronization time under tsc_write_lock: set in kvm_track_tsc_matching(), cleared when a new generation opens, consumed by pvclock_update_vm_gtod_copy(). The count remains as the input from which the flag is computed, and for the trace event. The consistent interface is the point. The flag starts true at VM creation, so a VM whose vCPUs never synchronize =E2=80=94 a protected guest TSC (TDX, SNP Secure TSC) returns early from __kvm_synchronize_tsc() =E2=80= =94 is eligible for PVCLOCK_TSC_STABLE_BIT by design rather than by luck of the read-time arithmetic, and use_master_clock is true from VM creation on a TSC-clocksource host, before any vCPU exists; later patches build on exactly that. The default scaling ratio must then be initialized too (a zero ratio zeroes tsc_hz and turns the master clock straight back off), and the khz/ratio bookkeeping recorded even for a protected guest TSC: it is host-side state, which a scaled protected guest must not leave at the host's unscaled frequency. The cached state needs care at vCPU creation: the new vCPU is counted in online_vcpus before it is synchronized, and userspace taking vcpu->mutex first can hold that window open across a whole first KVM_RUN. Clear the matched state up front in postcreate =E2=80=94 the old read-time comparison failed conservatively false throughout =E2=80=94 and l= et the synchronization (or a racing host-initiated TSC write on the already-live fd) re-latch it; a postcreate aborted by a fatal signal just propagates whatever the state then is with a masterclock update. Only the instants between the online_vcpus increment and the clear remain stale-true. The explicit clear at new-generation start is currently overwritten by the unconditional recompute in kvm_track_tsc_matching(); it is preparation for later patches which consume the previous value. Signed-off-by: David Woodhouse --- arch/x86/include/asm/kvm_host.h | 6 ++- arch/x86/kvm/x86.c | 76 +++++++++++++++++++++++++++------ 2 files changed, 67 insertions(+), 15 deletions(-) diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_hos= t.h index ea48b1949316..18d7bb9fd8d2 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -1232,8 +1232,9 @@ struct kvm_arch { s64 kvmclock_offset; =20 /* - * This also protects nr_vcpus_matched_tsc which is read from a - * preemption-disabled region, so it must be a raw spinlock. + * This also protects nr_vcpus_matched_tsc and + * all_vcpus_matched_tsc, which are read from preemption-disabled + * regions, so it must be a raw spinlock. */ raw_spinlock_t tsc_write_lock; u32 cur_tsc_khz; @@ -1242,6 +1243,7 @@ struct kvm_arch { u64 cur_tsc_write; u64 cur_tsc_offset; u64 cur_tsc_generation; + bool all_vcpus_matched_tsc; int nr_vcpus_matched_tsc; =20 u32 default_tsc_khz; diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 12f465040efc..1bb0136042a6 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1125,8 +1125,10 @@ static void kvm_track_tsc_matching(struct kvm_vcpu *= vcpu, bool new_generation) * and all vCPUs must have matching TSCs. Note, the count for matching * vCPUs doesn't include the reference vCPU, hence "+1". */ - bool use_master_clock =3D (ka->nr_vcpus_matched_tsc + 1 =3D=3D - atomic_read(&vcpu->kvm->online_vcpus)) && + ka->all_vcpus_matched_tsc =3D (ka->nr_vcpus_matched_tsc + 1 =3D=3D + atomic_read(&vcpu->kvm->online_vcpus)); + + bool use_master_clock =3D ka->all_vcpus_matched_tsc && gtod_is_based_on_tsc(gtod->clock.vclock_mode); =20 /* @@ -1327,20 +1329,23 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *= vcpu, u64 offset, u64 tsc, =20 lockdep_assert_held(&kvm->arch.tsc_write_lock); =20 - if (vcpu->arch.guest_tsc_protected) - return; - - if (user_set_tsc) - vcpu->kvm->arch.user_set_tsc =3D true; - /* - * Track the TSC frequency, scaling ratio, and offset for the current + * Track the TSC frequency and scaling ratio for the current * generation. These are used to detect matching TSC writes and to - * compute the guest TSC from the host clock. + * compute the guest TSC from the host clock. This is host-side + * bookkeeping, recorded even for a protected guest TSC =E2=80=94 a scaled + * protected guest (TDX, SNP Secure TSC) must not leave the master + * clock computing with the host's unscaled frequency. */ kvm->arch.cur_tsc_khz =3D vcpu->arch.virtual_tsc_khz; kvm->arch.cur_tsc_scaling_ratio =3D vcpu->arch.l1_tsc_scaling_ratio; =20 + if (vcpu->arch.guest_tsc_protected) + return; + + if (user_set_tsc) + vcpu->kvm->arch.user_set_tsc =3D true; + vcpu->arch.last_guest_tsc =3D tsc; =20 /* @@ -1367,6 +1372,7 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *vc= pu, u64 offset, u64 tsc, kvm->arch.cur_tsc_write =3D tsc; kvm->arch.cur_tsc_offset =3D offset; kvm->arch.nr_vcpus_matched_tsc =3D 0; + kvm->arch.all_vcpus_matched_tsc =3D false; } else if (vcpu->arch.this_tsc_generation !=3D kvm->arch.cur_tsc_generati= on) { kvm->arch.nr_vcpus_matched_tsc++; } @@ -1593,8 +1599,7 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) bool host_tsc_clocksource, vcpus_matched; =20 lockdep_assert_held(&kvm->arch.tsc_write_lock); - vcpus_matched =3D (ka->nr_vcpus_matched_tsc + 1 =3D=3D - atomic_read(&kvm->online_vcpus)); + vcpus_matched =3D ka->all_vcpus_matched_tsc; =20 /* * If the host uses TSC clock, then passthrough TSC as stable @@ -9584,8 +9589,38 @@ int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu) =20 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu) { - if (mutex_lock_killable(&vcpu->mutex)) + struct kvm_arch *ka =3D &vcpu->kvm->arch; + unsigned long flags; + + /* + * The new vCPU is already counted in online_vcpus but has not + * been synchronized. Clear the cached matched state before + * trying the mutex: the old read-time comparison failed + * conservatively false throughout this window, and userspace + * can hold it open across a whole first KVM_RUN by taking + * vcpu->mutex before we do. The synchronization below (or any + * racing host-initiated TSC write on the already-live fd) + * re-latches the flags. A protected guest TSC never + * participates in offset matching, so for it there is nothing + * to clear =E2=80=94 and no later sync to re-latch. + */ + if (!vcpu->arch.guest_tsc_protected) { + raw_spin_lock_irqsave(&ka->tsc_write_lock, flags); + WRITE_ONCE(ka->all_vcpus_matched_tsc, false); + raw_spin_unlock_irqrestore(&ka->tsc_write_lock, flags); + } + + if (mutex_lock_killable(&vcpu->mutex)) { + /* + * Aborted by a fatal signal: the synchronization never + * ran. Propagate whatever the matched state now is (a + * racing TSC write may have re-latched it), so the + * master clock does not stay in its previous mode with + * running siblings keeping PVCLOCK_TSC_STABLE_BIT. + */ + kvm_update_masterclock(vcpu->kvm); return; + } vcpu_load(vcpu); kvm_synchronize_tsc(vcpu, NULL); if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) @@ -10061,6 +10096,21 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned lon= g type) ratelimit_set_flags(&kvm->arch.kvmclock_update_rs, RATELIMIT_MSG_ON_RELEA= SE); kvm->arch.kvmclock_offset =3D -get_kvmclock_base_ns(); =20 + /* + * Start with all (zero) vCPUs considered matched, so that a VM whose + * vCPUs never reach kvm_track_tsc_matching() =E2=80=94 notably when the = guest + * TSC is protected (TDX, SNP Secure TSC) and __kvm_synchronize_tsc() + * returns early =E2=80=94 is still eligible for PVCLOCK_TSC_STABLE_BIT. = The + * scaling ratio must then also be initialized: with vcpus_matched + * now true here, pvclock_update_vm_gtod_copy() reaches the scaling + * path, and a zero ratio would zero tsc_hz and turn the master + * clock straight back off (permanently so for protected-TSC guests, + * whose syncs return before kvm_track_tsc_matching() ever requests + * the masterclock update that would recompute it). + */ + kvm->arch.all_vcpus_matched_tsc =3D true; + kvm->arch.cur_tsc_scaling_ratio =3D kvm_caps.default_tsc_scaling_ratio; + raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); pvclock_update_vm_gtod_copy(kvm); raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags); --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=qNzOVoKoI1UkFKkOeZJLDJv5QLhYwNQyQgholTud4EVs9D7cas/isvqVAd9YyIEos6Wa KN2Csu4/hKjAhRLmfENUX1dGTmQnVjceKLl34XmBEtPakVpEQ8Uxf5kJ7K86d3oxtzWkk Q7d6zNpfkznsWM5ZhTA64Sm3UPQsINfJptYercOTETST+Pqk0Sv/L45RfVKVWQQ1ild+s dGyl2Q2qLIzYzaLzX8ZsOrCn3f2ASSLNM4aQSha6jZcfh9o67NOSXitsNhlR7/bsKsKUN pmY6rDHA+ijd5IIA2mLYqlh/IgGbNvorWNRIsr52dwalT5bs3x36IAxGy9/F9HuSpbA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=7860VVsdgmRTVktOXOczaQdZ/+pZ2nlkrneJWnbeC7Y=; b=kOZcwwTe11WdA85vWotx2/wgn4MbOX8ak93x3h+HA+wbwFk4y0d6V5/0QIqJxaViinzL eX8gNNfkVRsMq+IIYmAA2ezumWB6cXvZcGMMrdge3Suaqg2gH459uSCu+LSU7/CM9/8hq 8zW0bzOI0S5gAYreghKSC4p1WGrdvSHZaVNVeMEhrqsBkKQhPtytWIhHzjk1c2AwvMvri t5eqTGFZY+VWymQa6TSxTo6tPqN5+a1YxwhrDorGT2ON1o6Pkq1J2jFDE6vdYbUaORyD5 D2UfvDvgAPdTOKhSa9SXDbMOBrFjuF6Qh+087cGQPsm2CzIwzrqrkyZYa2FSCd/aBBQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=XG0I5LbO; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 378C0606B787; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 378C0606B787 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=XG0I5LbO DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=7860VVsdgmRTVktOXOczaQdZ/+pZ2nlkrneJWnbeC7Y=; b=XG0I5LbO9aCFfF5PZQXZrXcbm9 LQug70qZeG7myxwI7QWolh0b1turCyMli0kb9eh8laEQTZG01lku869ILrEbZwXHJJhcvEqlEun2G Zt46yZPiAbMVWbYaf7s9MyX0AynDIITUyhozqZBHZt5KRaUrQ8u0MdiiU9Ax+3eaUqhs9XJEoJPPr ZA874mFSl6srO2uFELT/gzw+HTHGfbwmYT5twEBSRz4+Ik7pS9+/408yVIx9F8181D8BjxNIhrcFt v5Y0cPY8GA19hqhF4vBuRleOntvHKFiTCtw+w1sqpEBBcnhUCPAC+bHMrhmfoK4Svm72F1Vtk0N4e dgatJpsQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvK-3CUO; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl8-0000000HWsG-3k8f; Wed, 11 Nov 2026 18:09:22 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 04/26] KVM: x86: Allow KVM master clock mode when TSCs are offset from each other Date: Wed, 11 Nov 2026 10:09:00 -0800 Message-ID: <20261111180922.4177927-5-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Previously, a guest writing different TSC values on different vCPUs could force KVM out of master clock mode. With this change, only a frequency mismatch disables master clock. The only ways for non-master-clock mode to happen now are archaic hardware without a TSC-based clocksource, a VMM that sets different TSC frequencies across vCPUs, or a guest using the legacy MSR_KVM_SYSTEM_TIME (addressed later in this series). Running at a different frequency leads to systemic skew between the clocks observed by different vCPUs, due to arithmetic precision in the scaling, so that should indeed force the clock back onto the host's CLOCK_MONOTONIC_RAW. But divergent TSC *offsets* are not a problem: the KVM clock is a single VM-wide nanosecond timeline, and only its expression in TSC cycles is per-vCPU. Each vCPU's pvclock structure is generated by translating the shared master snapshot into that vCPU's own TSC domain via kvm_read_l1_tsc(), so when the guest computes system_time + (rdtsc - tsc_timestamp) * rate, its own offset is present in both rdtsc and tsc_timestamp and cancels out. VM-scoped consumers (KVM_GET_CLOCK, the wall clock epoch, the Xen runstate times) operate purely in the nanosecond domain, where the offset never appears. Only two consumers genuinely depend on the TSC offsets matching, and both are already guarded by PVCLOCK_TSC_STABLE_BIT: 1. A guest vCPU reading a *sibling* vCPU's pvclock structure with its own TSC would compute garbage =E2=80=94 precisely why commit b48aa97e38= 20 ("KVM: x86: require matched TSC offsets for master clock") required matched offsets. But when PVCLOCK_TSC_STABLE_BIT is clear, guests already fall back to the global last_value monotonicity clamp. 2. The Hyper-V TSC page is a single VM-wide {scale, offset} pair, so it cannot represent divergent offsets. It is self-guarding: compute_tsc_page_parameters() refuses to populate the page unless PVCLOCK_TSC_STABLE_BIT is set, forcing such guests onto the (safe, nanosecond domain) TIME_REF_COUNT MSR. So: frequency match gates master clock eligibility, and the full TSC match (including offset) gates only PVCLOCK_TSC_STABLE_BIT, which tells the guest it may skip cross-vCPU monotonicity enforcement. Frequency matching is tracked with a dedicated generation counter (cur_tsc_freq_generation) which bumps only on actual frequency changes; each vCPU is counted once per generation via this_tsc_freq_generation. The existing offset tracking is restructured to the same pattern, and both counters use a consistent >=3D online_vcpus threshold. A vCPU set to a different frequency and back opens a new generation each time, and its siblings are only counted back in as they synchronize =E2=80=94 the migration procedure sets every vCPU, which re-latches the match as the last one lands; frequency excursions on a subset of vCPUs are not free, by design. A protected vCPU's synchronization returns before kvm_track_tsc_matching(), the only other place the match is re-latched, so its branch re-latches the frequency match itself =E2=80=94 the first vCP= U's own bump against the zero initial cur_tsc_khz would otherwise clear it for the life of the VM =E2=80=94 and raises KVM_REQ_MASTERCLOCK_UPDATE on t= he transition back to matched, since no later synchronization ever runs for a protected guest to repair a refresh taken in the window. KVM_SET_TSC_KHZ on a vCPU which has already run does not pass through __kvm_synchronize_tsc(), so at this point in the series it leaves the frequency-match state stale, exactly as it previously left the offset match stale; the later patch "KVM: x86: Re-synchronize TSC after KVM_SET_TSC_KHZ" funnels it through the invalidation. The divergent-offset behaviour is exercised by pvclock_migration_test: vCPUs with TSCs offset by =C2=B10.5-1s keep the master clock, lose PVCLOCK_TSC_STABLE_BIT, and still agree on the KVM clock to within a nanosecond, before and after a simulated live migration. Signed-off-by: David Woodhouse --- arch/x86/include/asm/kvm_host.h | 11 ++- arch/x86/kvm/trace.h | 12 +-- arch/x86/kvm/x86.c | 139 ++++++++++++++++++++++++++------ 3 files changed, 130 insertions(+), 32 deletions(-) diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_hos= t.h index 18d7bb9fd8d2..74306a81e882 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -887,6 +887,7 @@ struct kvm_vcpu_arch { u64 this_tsc_nsec; u64 this_tsc_write; u64 this_tsc_generation; + u64 this_tsc_freq_generation; bool tsc_catchup; bool tsc_always_catchup; s8 virtual_tsc_shift; @@ -1232,9 +1233,10 @@ struct kvm_arch { s64 kvmclock_offset; =20 /* - * This also protects nr_vcpus_matched_tsc and - * all_vcpus_matched_tsc, which are read from preemption-disabled - * regions, so it must be a raw spinlock. + * This also protects the matched-state fields + * ({nr_vcpus_matched,all_vcpus_matched}_{tsc,freq} and + * cur_tsc_freq_generation), which are read from + * preemption-disabled regions, so it must be a raw spinlock. */ raw_spinlock_t tsc_write_lock; u32 cur_tsc_khz; @@ -1244,6 +1246,9 @@ struct kvm_arch { u64 cur_tsc_offset; u64 cur_tsc_generation; bool all_vcpus_matched_tsc; + bool all_vcpus_matched_freq; + int nr_vcpus_matched_freq; + u64 cur_tsc_freq_generation; int nr_vcpus_matched_tsc; =20 u32 default_tsc_khz; diff --git a/arch/x86/kvm/trace.h b/arch/x86/kvm/trace.h index 93de876c318c..704683532ef0 100644 --- a/arch/x86/kvm/trace.h +++ b/arch/x86/kvm/trace.h @@ -1003,25 +1003,25 @@ TRACE_EVENT(kvm_write_tsc_offset, {VDSO_CLOCKMODE_TSC, "tsc"} \ =20 TRACE_EVENT(kvm_update_master_clock, - TP_PROTO(bool use_master_clock, unsigned int host_clock, bool offset_matc= hed), - TP_ARGS(use_master_clock, host_clock, offset_matched), + TP_PROTO(bool use_master_clock, unsigned int host_clock, bool freq_matche= d), + TP_ARGS(use_master_clock, host_clock, freq_matched), =20 TP_STRUCT__entry( __field( bool, use_master_clock ) __field( unsigned int, host_clock ) - __field( bool, offset_matched ) + __field( bool, freq_matched ) ), =20 TP_fast_assign( __entry->use_master_clock =3D use_master_clock; __entry->host_clock =3D host_clock; - __entry->offset_matched =3D offset_matched; + __entry->freq_matched =3D freq_matched; ), =20 - TP_printk("masterclock %d hostclock %s offsetmatched %u", + TP_printk("masterclock %d hostclock %s freqmatched %u", __entry->use_master_clock, __print_symbolic(__entry->host_clock, host_clocks), - __entry->offset_matched) + __entry->freq_matched) ); =20 TRACE_EVENT(kvm_track_tsc, diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 1bb0136042a6..08cc8ab3d699 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1114,30 +1114,72 @@ static inline bool gtod_is_based_on_tsc(int mode) } #endif =20 -static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool new_generat= ion) +static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool update_mclo= ck) { #ifdef CONFIG_X86_64 struct kvm_arch *ka =3D &vcpu->kvm->arch; struct pvclock_gtod_data *gtod =3D &pvclock_gtod_data; + bool prev_matched_tsc =3D ka->all_vcpus_matched_tsc; + bool prev_matched_freq =3D ka->all_vcpus_matched_freq; =20 /* - * To use the masterclock, the host clocksource must be based on TSC - * and all vCPUs must have matching TSCs. Note, the count for matching - * vCPUs doesn't include the reference vCPU, hence "+1". + * Track whether all vCPUs have matching TSC offsets (for + * PVCLOCK_TSC_STABLE_BIT) and matching frequencies (for + * master clock eligibility). + */ + + /* + * A new vCPU might already have incremented ->online_vcpus + * and cause a temporary false negative here. But will then + * call kvm_synchronize_tsc() from kvm_arch_vcpu_postcreate() + * and finish the job. + */ + int online =3D atomic_read(&vcpu->kvm->online_vcpus); + /* + * WRITE_ONCE() pairs with the READ_ONCE() in kvm_guest_time_update(), + * which samples the flag locklessly (outside both tsc_write_lock and + * its pvclock seqcount read section); the race is benign (a stale + * value merely delays the PVCLOCK_TSC_STABLE_BIT broadcast to the + * masterclock update which is requested below). + */ + WRITE_ONCE(ka->all_vcpus_matched_tsc, + ka->nr_vcpus_matched_tsc >=3D online); + + update_mclock |=3D (prev_matched_tsc !=3D ka->all_vcpus_matched_tsc); + + /* + * all_vcpus_matched_freq starts true and is cleared when + * __kvm_synchronize_tsc() detects a frequency mismatch. + * Re-enable when all vCPUs have synced with matching frequency. + * If all offsets also match, that implies frequencies match too. */ - ka->all_vcpus_matched_tsc =3D (ka->nr_vcpus_matched_tsc + 1 =3D=3D - atomic_read(&vcpu->kvm->online_vcpus)); + if (ka->all_vcpus_matched_tsc || + ka->nr_vcpus_matched_freq >=3D online) + ka->all_vcpus_matched_freq =3D true; =20 - bool use_master_clock =3D ka->all_vcpus_matched_tsc && + /* + * A frequency-match transition needs a masterclock update too: + * when the last vCPU reaches the new frequency, the masterclock + * scaling factors still describe the old one, and no toggle of + * use_master_clock occurs to trigger the refresh. + */ + update_mclock |=3D (prev_matched_freq !=3D ka->all_vcpus_matched_freq); + + /* + * To use the masterclock, the host clocksource must be based on TSC + * and all vCPUs must have matching TSC *frequency*. Different offsets + * are fine =E2=80=94 each vCPU's pvclock has its own tsc_timestamp that + * accounts for its offset. + */ + bool use_master_clock =3D ka->all_vcpus_matched_freq && gtod_is_based_on_tsc(gtod->clock.vclock_mode); =20 /* - * Request a masterclock update if the masterclock needs to be toggled - * on/off, or when starting a new generation and the masterclock is - * enabled (compute_guest_tsc() requires the masterclock snapshot to be - * taken _after_ the new generation is created). + * Request a masterclock update if needed: toggling master clock, + * new generation requiring a fresh snapshot, or a change in + * all_vcpus_matched_tsc (to broadcast PVCLOCK_TSC_STABLE_BIT). */ - if ((ka->use_master_clock && new_generation) || + if ((ka->use_master_clock && update_mclock) || (ka->use_master_clock !=3D use_master_clock)) kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); =20 @@ -1336,12 +1378,50 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *= vcpu, u64 offset, u64 tsc, * bookkeeping, recorded even for a protected guest TSC =E2=80=94 a scaled * protected guest (TDX, SNP Secure TSC) must not leave the master * clock computing with the host's unscaled frequency. + * + * If the frequency changed, master clock mode can no longer be used + * since the kvmclock scaling factors differ between vCPUs. */ + if (vcpu->arch.virtual_tsc_khz !=3D kvm->arch.cur_tsc_khz) { + kvm->arch.cur_tsc_freq_generation++; + kvm->arch.all_vcpus_matched_freq =3D false; + kvm->arch.nr_vcpus_matched_freq =3D 0; + } + + /* Count each vCPU once per freq generation */ + if (vcpu->arch.this_tsc_freq_generation !=3D kvm->arch.cur_tsc_freq_gener= ation) { + vcpu->arch.this_tsc_freq_generation =3D kvm->arch.cur_tsc_freq_generatio= n; + kvm->arch.nr_vcpus_matched_freq++; + } + kvm->arch.cur_tsc_khz =3D vcpu->arch.virtual_tsc_khz; kvm->arch.cur_tsc_scaling_ratio =3D vcpu->arch.l1_tsc_scaling_ratio; =20 - if (vcpu->arch.guest_tsc_protected) + if (vcpu->arch.guest_tsc_protected) { + /* + * A protected vCPU synchronizes only here (from postcreate, + * host-initiated MSR_IA32_TSC writes and KVM_VCPU_TSC_OFFSET + * writes) and never reaches + * kvm_track_tsc_matching() =E2=80=94 the only other place the + * frequency match is re-latched. Without this, the first + * vCPU's bump above (cur_tsc_khz starts at zero) would + * clear the match for the life of the VM, turning the + * master clock off for exactly the guests the init-to-true + * serves. On the transition back to matched, request the + * masterclock update that kvm_track_tsc_matching() would + * have: a refresh in the mismatched window (another vCPU's + * creation racing this sync) has latched use_master_clock + * off, and nothing else ever re-runs it for a protected + * guest. + */ + if (kvm->arch.nr_vcpus_matched_freq >=3D + atomic_read(&kvm->online_vcpus) && + !kvm->arch.all_vcpus_matched_freq) { + kvm->arch.all_vcpus_matched_freq =3D true; + kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); + } return; + } =20 if (user_set_tsc) vcpu->kvm->arch.user_set_tsc =3D true; @@ -1357,6 +1437,16 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *v= cpu, u64 offset, u64 tsc, */ vcpu->arch.tsc_offset_adjustment =3D 0; =20 + /* + * If the offset changes, the guest-visible pvclock must be + * rewritten before the vCPU runs again: its tsc_timestamp was + * computed with the old offset, and the masterclock (which now + * survives offset changes) will not request the refresh for a + * matched write. + */ + if (offset !=3D vcpu->arch.l1_tsc_offset) + kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); + kvm_vcpu_write_tsc_offset(vcpu, offset); =20 if (!matched) { @@ -1368,17 +1458,18 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *= vcpu, u64 offset, u64 tsc, * exact software computation in compute_guest_tsc() */ kvm->arch.cur_tsc_generation++; + WRITE_ONCE(kvm->arch.all_vcpus_matched_tsc, false); + kvm->arch.nr_vcpus_matched_tsc =3D 0; kvm->arch.cur_tsc_nsec =3D ns; kvm->arch.cur_tsc_write =3D tsc; kvm->arch.cur_tsc_offset =3D offset; - kvm->arch.nr_vcpus_matched_tsc =3D 0; - kvm->arch.all_vcpus_matched_tsc =3D false; - } else if (vcpu->arch.this_tsc_generation !=3D kvm->arch.cur_tsc_generati= on) { + } + + if (vcpu->arch.this_tsc_generation !=3D kvm->arch.cur_tsc_generation) { + vcpu->arch.this_tsc_generation =3D kvm->arch.cur_tsc_generation; kvm->arch.nr_vcpus_matched_tsc++; } =20 - /* Keep track of which generation this VCPU has synchronized to */ - vcpu->arch.this_tsc_generation =3D kvm->arch.cur_tsc_generation; vcpu->arch.this_tsc_nsec =3D kvm->arch.cur_tsc_nsec; vcpu->arch.this_tsc_write =3D kvm->arch.cur_tsc_write; =20 @@ -1596,10 +1687,10 @@ static void pvclock_update_vm_gtod_copy(struct kvm = *kvm) #ifdef CONFIG_X86_64 struct kvm_arch *ka =3D &kvm->arch; int vclock_mode; - bool host_tsc_clocksource, vcpus_matched; + bool host_tsc_clocksource, freqs_matched; =20 lockdep_assert_held(&kvm->arch.tsc_write_lock); - vcpus_matched =3D ka->all_vcpus_matched_tsc; + freqs_matched =3D ka->all_vcpus_matched_freq; =20 /* * If the host uses TSC clock, then passthrough TSC as stable @@ -1609,7 +1700,7 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) &ka->master_kernel_ns, &ka->master_cycle_now); =20 - ka->use_master_clock =3D host_tsc_clocksource && vcpus_matched + ka->use_master_clock =3D host_tsc_clocksource && freqs_matched && !ka->backwards_tsc_observed && !ka->boot_vcpu_runs_old_kvmclock; =20 @@ -1639,7 +1730,7 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) =20 vclock_mode =3D pvclock_gtod_data.clock.vclock_mode; trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode, - vcpus_matched); + freqs_matched); #endif } =20 @@ -1927,7 +2018,7 @@ int kvm_guest_time_update(struct kvm_vcpu *v) =20 /* If the host uses TSC clocksource, then it is stable */ hv_clock.flags =3D 0; - if (use_master_clock) + if (use_master_clock && READ_ONCE(ka->all_vcpus_matched_tsc)) hv_clock.flags |=3D PVCLOCK_TSC_STABLE_BIT; =20 if (vcpu->pv_time.active) { @@ -9607,6 +9698,7 @@ void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu) if (!vcpu->arch.guest_tsc_protected) { raw_spin_lock_irqsave(&ka->tsc_write_lock, flags); WRITE_ONCE(ka->all_vcpus_matched_tsc, false); + ka->all_vcpus_matched_freq =3D false; raw_spin_unlock_irqrestore(&ka->tsc_write_lock, flags); } =20 @@ -10095,6 +10187,7 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned long= type) ratelimit_state_init(&kvm->arch.kvmclock_update_rs, HZ, 10); ratelimit_set_flags(&kvm->arch.kvmclock_update_rs, RATELIMIT_MSG_ON_RELEA= SE); kvm->arch.kvmclock_offset =3D -get_kvmclock_base_ns(); + kvm->arch.all_vcpus_matched_freq =3D true; =20 /* * Start with all (zero) vCPUs considered matched, so that a VM whose --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=sExsID13GJZuoBOiQIaO01CtJqWFyF+oTggZjyNEyvi8RHzbaUIylF4Qs21tNB7AuXvI 1mgK1VL6cIHmbNlVqLNk54ueaG97AGDO925AJnzZqUn3yEhdjsVXPscKULv5pqpnFwzt2 8c7wwTtectlub7QC1lI+gi4c7ZC6RLu4nnq0u7MCof9xYBqpLHoQ2FwDd5ne9HNlKm/js yTyzHen8uekaNZ6TB2tInEftSM3AWjv/Fk1zsTNF7p1nYigSI64B8qJ9h1wU9rOM9QrOY /+0UHHAuHJBZrqI3N9zoCOOOlwnYjbHijfw96i7SLG037Giz+IiqLBmxY0FJCsDWh3A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=ZX6dTNskcRE6WZFDjl4UTz9ifrPcXg/SXw/ekisAe8k=; b=zIS2ZIBwJ6EgfkxUZFyiJjXg8atTM25aU+bvCnW/CYZWoOFOS5QEeUIA0vMo/Q2nRykn t7QPlznQciNYbH1cSXLLt1+ulYOIN9GS5l+GQy9Vmqisa6yBTIzgWFNIGs//tL5wR68zc oz8l38cIrykfAqCT4GY2/GpSivs8y0PcDBmN37Pu/Ibiu8jUc71Dk78LVt0c0COftyvdd B0JXOdBJIZDSqryJWXm5w5kLKB8PZ5cCbsUALf6Xoe1grCz3ePw3VlghF5kGWK2KJuPNg 7wWkZCxvz56DCDRcgZy+U3jGvAd7lyTtmi9w3Uh0E83JnsYiDs3pv2VTnjm+gMU+IBg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=rRmEnIef; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E4637606A31C; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E4637606A31C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=rRmEnIef DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=ZX6dTNskcRE6WZFDjl4UTz9ifrPcXg/SXw/ekisAe8k=; b=rRmEnIef9XcjjXuo0CNykhtLfD oW5mXUJIOC42po3jChilEvDq4CVOgaN7g4T7EcCgq5/oBnY6ODKm2PvEoYk+XztlFfWqVRHypYmjC 5FpGLW/jvKaL3uHwmqPZ6bEEZwNpYHj7hiC+RbNDKWiL6KplVw+JjHEfQX//tyrCO6ysBE6YsvgzV D/QVdZ1ZA3sCRnSI3uXaOX1lhRn1hE80/yaHMroKvE+3RP0KYZPrT6zIbCZvJpFsKxENnSFv2sV4U u3HLYBRZlKxZrSPBFHQg27i2H11oV+uC6p5UTVyed6OA84283v2LidIHBV8+BQakSew2bNZpJYpM8 Y4uDh20w==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvS-0fXI; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl8-0000000HWsK-3t8e; Wed, 11 Nov 2026 18:09:22 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 05/26] KVM: x86: Factor out kvm_use_master_clock() Date: Wed, 11 Nov 2026 10:09:01 -0800 Message-ID: <20261111180922.4177927-6-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Both kvm_track_tsc_matching() and pvclock_update_vm_gtod_copy() make a decision about whether the KVM clock should be in master clock mode. They used *different* criteria for the decision though. This isn't really a problem; it only has the potential to cause unnecessary invocations of KVM_REQ_MASTERCLOCK_UPDATE if the masterclock was disabled due to TSC going backwards, or the guest using the old MSR. But it isn't pretty. Factor the decision out to a single function. And document the historical reason why it's disabled for guests that use the old MSR_KVM_SYSTEM_TIME. Signed-off-by: David Woodhouse Reviewed-by: Paul Durrant --- arch/x86/kvm/x86.c | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 08cc8ab3d699..9ad217e8640a 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1112,11 +1112,30 @@ static inline bool gtod_is_based_on_tsc(int mode) { return mode =3D=3D VDSO_CLOCKMODE_TSC || mode =3D=3D VDSO_CLOCKMODE_HVCLO= CK; } -#endif + +static bool kvm_use_master_clock(struct kvm *kvm) +{ + struct kvm_arch *ka =3D &kvm->arch; + + /* + * The 'old kvmclock' check is a workaround (from 2015) for a + * SUSE 2.6.16 kernel that didn't boot if the system_time in + * its kvmclock was too far behind the current time. So the + * mode of just setting the reference point and allowing time + * to proceed linearly from there makes it fail to boot. + * Despite that being kind of the *point* of the way the clock + * is exposed to the guest. By coincidence, the offending + * kernels used the old MSR_KVM_SYSTEM_TIME, which was moved + * only because it resided in the wrong number range. So the + * workaround is activated for *all* guests using the old MSR. + */ + return ka->all_vcpus_matched_freq && + !ka->backwards_tsc_observed && + !ka->boot_vcpu_runs_old_kvmclock; +} =20 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool update_mclo= ck) { -#ifdef CONFIG_X86_64 struct kvm_arch *ka =3D &vcpu->kvm->arch; struct pvclock_gtod_data *gtod =3D &pvclock_gtod_data; bool prev_matched_tsc =3D ka->all_vcpus_matched_tsc; @@ -1171,7 +1190,7 @@ static void kvm_track_tsc_matching(struct kvm_vcpu *v= cpu, bool update_mclock) * are fine =E2=80=94 each vCPU's pvclock has its own tsc_timestamp that * accounts for its offset. */ - bool use_master_clock =3D ka->all_vcpus_matched_freq && + bool use_master_clock =3D kvm_use_master_clock(vcpu->kvm) && gtod_is_based_on_tsc(gtod->clock.vclock_mode); =20 /* @@ -1186,8 +1205,11 @@ static void kvm_track_tsc_matching(struct kvm_vcpu *= vcpu, bool update_mclock) trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc, atomic_read(&vcpu->kvm->online_vcpus), ka->use_master_clock, gtod->clock.vclock_mode); -#endif } +#else +static inline void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, + bool update_mclock) {} +#endif =20 /* * Multiply tsc by a fixed point number represented by ratio. @@ -1687,10 +1709,9 @@ static void pvclock_update_vm_gtod_copy(struct kvm *= kvm) #ifdef CONFIG_X86_64 struct kvm_arch *ka =3D &kvm->arch; int vclock_mode; - bool host_tsc_clocksource, freqs_matched; + bool host_tsc_clocksource; =20 lockdep_assert_held(&kvm->arch.tsc_write_lock); - freqs_matched =3D ka->all_vcpus_matched_freq; =20 /* * If the host uses TSC clock, then passthrough TSC as stable @@ -1700,9 +1721,8 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) &ka->master_kernel_ns, &ka->master_cycle_now); =20 - ka->use_master_clock =3D host_tsc_clocksource && freqs_matched - && !ka->backwards_tsc_observed - && !ka->boot_vcpu_runs_old_kvmclock; + ka->use_master_clock =3D host_tsc_clocksource && + kvm_use_master_clock(kvm); =20 if (ka->use_master_clock) { u64 tsc_hz; @@ -1730,7 +1750,7 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) =20 vclock_mode =3D pvclock_gtod_data.clock.vclock_mode; trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode, - freqs_matched); + ka->all_vcpus_matched_freq); #endif } =20 --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=Ddr9aWcA6Fj+IvoecjfH3/4NcH09UqMpxGpFxbXDMRupLqydM0azQVqhD9Kudz9DFVi1 gGVqFtZDQ0zzUzDX8/Zgn5LSzdGg+CGXxeadGu+oIDciW0sUI+Twv8mymujcqe9tBzDSv f/rpHGHDN2XUwiX0HAsQkEG9IRhCbEQ54bEcCfyiDDKSWI8S1+0frBO0u7uWoJjtPH8n1 dgjtrOMU2PXnMN8N/M5Mso4agFR0vEIEkpassHrfxhlWBN8q6GE4jE6zHsUHidnfc2M6k LLYJNSywLHuWARMmWYjFCMVKCt3MEirLLyjgdHd9X/VvY6+Oulbl3FS2Ma/DFMiadvA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=LSt/cjhlDC770FmWw8fWfoUicf1cn/kr7nVQwqL5nQg=; b=1movd8RP1S12Nb62wuKrAh1dPA8tsngYEDevUch0hVKEe4Cn/NTqtZwj4lHhS1xkXNQE IrQflxHFWI6QPnNQuUo1EjQQc3xHL05C296lZwPv27d0Nqy+5KoKO8tHKr5pb4KqTUKUV d1GQyMiOOXI++Da85GF7/GTGGZTlFoqtK/YcqIcQ9lMel8zrZ3NWPzX1GRsCFJlXR35O8 btapYgUlG6ahVIxNTniboxskP3aPUdo71dO3N6AnWAbe/RHNkWat5ZZQlEvLPEHhNYvpd 1jatxBh/JoMhnjB4bo4Fw9BUSQWFyPVzp5GB2m3CqBy53eRVG6Cc1/GfIlRS3QxFnMw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=XFVltFAe; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 36761606B782; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 36761606B782 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=XFVltFAe DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From: Reply-To:Content-Type:Content-ID:Content-Description; bh=LSt/cjhlDC770FmWw8fWfoUicf1cn/kr7nVQwqL5nQg=; b=XFVltFAeYxoNTn5FfTG/Gzl+Uy YeeyxrmNQNk3RUAfiuN66ThENH2MmsIsD1tLoAUi25+FQeox1j1MMkKnc4K0OOZBancz4LGBfsbsB nyg86quK89q0/WHluHa8aeqFojee4KhnnjLOQ1B3seVqf4iK95/GdrilUP+xpSi5hCqKajyoY7W2Z o+VUcs0PmomoSWb+1KzNCUys1UcAZGREY5AA/G6mwaZpGI0Z9DL5/Nyad0KVthVsGLSe+Dm9p+go9 lnmlAmplFXCGlgY+fEajj5ESFioyTFuypp8TFUS+3G73VeG+hccf/CZAClBg+DH/ISn31RoixFHvk 0mNX1xMw==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvL-3C7G; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsO-01EU; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 06/26] KVM: x86: Avoid gratuitous global clock updates Date: Wed, 11 Nov 2026 10:09:02 -0800 Message-ID: <20261111180922.4177927-7-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html Content-Type: text/plain; charset="utf-8" From: David Woodhouse Eliminate two sources of unnecessary KVM_REQ_GLOBAL_CLOCK_UPDATE: 1. kvm_write_system_time(): The global clock update was a workaround for ever-drifting clocks based on the host's CLOCK_MONOTONIC subject to NTP skew. Now that the KVM clock uses CLOCK_MONOTONIC_RAW, the clock does not drift with NTP corrections and there is no need to synchronize all vCPUs on boot or resume. Use KVM_REQ_CLOCK_UPDATE on the vCPU itself, and only when the clock is being enabled, not disabled. 2. kvm_arch_vcpu_load(): In master clock mode, migration between pCPUs does not require any clock update since the master clock reference is shared. Only request a local KVM_REQ_CLOCK_UPDATE for a load with no prior physical CPU (vcpu->cpu =3D=3D -1: its first ever load, or a TDX re-association) to generate the pvclock parameters. In non-master-clock mode, keep the global update to synchronize all vCPUs. A host in non-master-clock mode because its TSC is unstable still re-anchors all vCPUs through the global update in kvm_arch_vcpu_load(), which fires on every load there. What this deliberately no longer covers is a stable-TSC host manually switched to a non-TSC clocksource with pinned vCPUs, where vCPUs anchored far apart can skew by the TSC calibration error over the elapsed time; the removed broadcast only masked that when a guest happened to rewrite MSR_KVM_SYSTEM_TIME, which a running guest does not do. Signed-off-by: David Woodhouse --- arch/x86/kvm/msrs.c | 7 ++++--- arch/x86/kvm/x86.c | 4 +++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c index e91650af44c2..a2dffa1c706f 100644 --- a/arch/x86/kvm/msrs.c +++ b/arch/x86/kvm/msrs.c @@ -1285,14 +1285,15 @@ static void kvm_write_system_time(struct kvm_vcpu *= vcpu, gpa_t system_time, } =20 vcpu->arch.time =3D system_time; - kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu); =20 /* we verify if the enable bit is set... */ - if (system_time & 1) + if (system_time & 1) { kvm_gpc_activate(&vcpu->arch.pv_time, system_time & ~1ULL, sizeof(struct pvclock_vcpu_time_info)); - else + kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); + } else { kvm_gpc_deactivate(&vcpu->arch.pv_time); + } =20 return; } diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 9ad217e8640a..05c801973a7f 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -2765,11 +2765,13 @@ void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int = cpu) * On a host with synchronized TSC, there is no need to update * kvmclock on vcpu->cpu migration */ - if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu =3D=3D -1) { + if (!vcpu->kvm->arch.use_master_clock) { if (__ratelimit(&vcpu->kvm->arch.kvmclock_update_rs)) kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu); else kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); + } else if (vcpu->cpu =3D=3D -1) { + kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); } =20 if (vcpu->cpu !=3D cpu) --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=fjGLwlkmSJIvTPH1YjG2s59lt6XIWGN3EVOYKSYCHSDfu3FWnWtcbAKfxhumCSFHtuhn LvrMRXmT4RlhQfbctAQfzam6R15WJiRsHTRh2sesfTlyuEO7fFYXIZA/lmgHA8aPmqb/T GHmemD/IBFuFFj5Ef+JwVg30WuoQ21Yb0N82Vv7h2y8j4/22Ao/UyOUMpSurHgK7vvpif uQktza/N8O5DRFPE/Zcu6aGrz0UF34il707ki0AEZKmsOfSS7zc+NAHCAbP2Gc6yFMFXW l+ahQRd3kdLj807nd0g27kCIik661lAh0OshWZUWd2wJUVThRMr03rhh1u1KT6vZ/+g== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=1V/mMwjMcC+MDxHM1oxRcKL+FYzfa4UsShC/QgnT6ts=; b=UHvq9hO1ACn4MJ/p20Ma1jzzPw5ZMs9jC21sTYxsHjwUlTYEBJebh/lkgou4+a6vSQ9v gXm+I0BtwpHagULJ+OukpXUqnij0t1OKCO/if7bOXI/WhcTLYjgDMzoHSnvsR7m5XjGky 5Ehs19KE6tUlhDQ4NO3qUmWiFfXcpFD20zU/lHuv3NY/J8nhLdzt2nGpde2uDWndJDrnH eLWa2Evz8+zzdrWzer6imeVcP2M6Afh3PV29WGmfHmJZHgZxAhSrgxUTGZgrL0ASJOVZY d87XR/8MFpF3nnrwSs6ys5bk1Jce4Mg1s2xitJRCeZnaDpeO8scHQVd5kiZ27TqMhTA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=rdCdM0Bg; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3B09A606C155; Wed, 11 Nov 2026 18:09:38 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 3B09A606C155 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=rdCdM0Bg DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=1V/mMwjMcC+MDxHM1oxRcKL+FYzfa4UsShC/QgnT6ts=; b=rdCdM0Bga8RtX//t2h5oWGV5nk NrobMdHnlsWWu0fgt/I6d+ha7L+1JiD2Yc69jvBxcI0t87Fu1wdOzrbXUF9Sl9320wCVdwrZw9cJj NbhmdPRAuOGTvIuEGQLSGH9X+krDkyse4Uw4uoGtbdSBbLPrCx26hLJfYW/Yiz3obm/FgivEyR71R KOTaGZLj6mqMvr1sMoN9zYhouAr/CwehIYcUGB+yqMCzdNILkxNX+221aePpyOCf+nOIMb5T6xD5m B1LVp9DnDtrKs93W47JR2nQ+MoRKidU8EDEwvrJ/xvN0opSznxIg6wJh1sgPhmS7Vl3rjPD7iBDcr 4P99dECw==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvM-3ChP; Wed, 11 Nov 2026 18:09:30 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsS-0BMB; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 07/26] KVM: x86: Don't latch the Hyper-V TSC page from a superseded snapshot Date: Wed, 11 Nov 2026 10:09:03 -0800 Message-ID: <20261111180922.4177927-8-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse The Hyper-V TSC page is rewritten from kvm_guest_time_update() when its HOST_CHANGED state is set, and latches to HV_TSC_PAGE_SET, which blocks further rewrites. But the state is set before the new pvclock snapshot is published (setting it takes hv_lock, a mutex, so it cannot happen inside the tsc_write_lock section), and nothing validates the snapshot the consumer is holding. Two interleavings latch stale parameters which nothing then rewrites until some unrelated clock event invalidates the page again: - A vCPU handling an unrelated KVM_REQ_CLOCK_UPDATE completes its pvclock read, is preempted (or sleeps in kvm_write_guest(), holding hv_lock), a KVM_SET_CLOCK completes meanwhile, and the vCPU then writes the page from the old snapshot and sets HV_TSC_PAGE_SET =E2=80=94 consuming the state intended for the new one. - The state is consumed legitimately an instant before the publish, writing values which were current at that moment and superseded the next; the CLOCK_UPDATE broadcast which follows the publish finds HV_TSC_PAGE_SET and rewrites nothing. For a KVM_SET_CLOCK stepping kvmclock_offset =E2=80=94 a live migration restore =E2=80=94 the page is left disagreeing with the restored clock by t= he full step. Close the first at the consumer: kvm_hv_setup_tsc_page() revalidates the pvclock seqcount under hv_lock =E2=80=94 it must be under the lock, or = the consumer could be preempted between a check and the consumption =E2=80=94 a= nd requeues the clock update rather than consume the state against a superseded snapshot. Close the second by re-marking the page once the new snapshot is published, with a CLOCK_UPDATE queued on every vCPU behind the re-mark: the broadcast from kvm_end_pvclock_update() can have been entirely consumed by then, and no vCPU in particular is guaranteed to ever run again. The hv_lock mutex which lets a consumer sleep across the whole update is also what serializes its write against the re-mark, so the queued consumer always finds either fresh page contents or the HOST_CHANGED state; guests which never enabled the page skip the broadcast entirely. Fixes: cc9cfddb0433 ("KVM: x86: hyper-v: Track Hyper-V TSC page status") Signed-off-by: David Woodhouse --- arch/x86/kvm/hyperv.c | 20 ++++++++++++++++++-- arch/x86/kvm/hyperv.h | 10 ++++++---- arch/x86/kvm/x86.c | 36 +++++++++++++++++++++++++++++++++++- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/arch/x86/kvm/hyperv.c b/arch/x86/kvm/hyperv.c index 5d2e3617c952..56da410a7f32 100644 --- a/arch/x86/kvm/hyperv.c +++ b/arch/x86/kvm/hyperv.c @@ -1182,9 +1182,11 @@ static inline bool tsc_page_update_unsafe(struct kvm= _hv *hv) hv->hv_tsc_emulation_control; } =20 -void kvm_hv_setup_tsc_page(struct kvm *kvm, - struct pvclock_vcpu_time_info *hv_clock) +void kvm_hv_setup_tsc_page(struct kvm_vcpu *v, + struct pvclock_vcpu_time_info *hv_clock, + unsigned int seq) { + struct kvm *kvm =3D v->kvm; struct kvm_hv *hv =3D to_kvm_hv(kvm); u32 tsc_seq; u64 gfn; @@ -1202,6 +1204,20 @@ void kvm_hv_setup_tsc_page(struct kvm *kvm, if (!(hv->hv_tsc_page & HV_X64_MSR_TSC_REFERENCE_ENABLE)) return; =20 + /* + * @hv_clock derives from the pvclock snapshot current at @seq. + * Consuming the HOST_CHANGED state against a superseded snapshot + * would latch stale parameters as HV_TSC_PAGE_SET, which nothing + * then rewrites; the check must be made here, under hv_lock, or + * this vCPU could be preempted between a check and the + * consumption while an update completes. Leave the state alone + * and requeue; the retry reads the new snapshot. + */ + if (read_seqcount_retry(&kvm->arch.pvclock_sc, seq)) { + kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); + return; + } + gfn =3D hv->hv_tsc_page >> HV_X64_MSR_TSC_REFERENCE_ADDRESS_SHIFT; /* * Because the TSC parameters only vary when there is a diff --git a/arch/x86/kvm/hyperv.h b/arch/x86/kvm/hyperv.h index 622a6553e9ac..62e7922440aa 100644 --- a/arch/x86/kvm/hyperv.h +++ b/arch/x86/kvm/hyperv.h @@ -284,8 +284,9 @@ static inline bool kvm_hv_invtsc_suppressed(struct kvm_= vcpu *vcpu) =20 void kvm_hv_process_stimers(struct kvm_vcpu *vcpu); =20 -void kvm_hv_setup_tsc_page(struct kvm *kvm, - struct pvclock_vcpu_time_info *hv_clock); +void kvm_hv_setup_tsc_page(struct kvm_vcpu *v, + struct pvclock_vcpu_time_info *hv_clock, + unsigned int seq); void kvm_hv_request_tsc_page_update(struct kvm *kvm); =20 void kvm_hv_xsaves_xsavec_maybe_warn(struct kvm_vcpu *vcpu); @@ -377,8 +378,9 @@ static inline void kvm_hv_nested_transtion_tlb_flush(st= ruct kvm_vcpu *vcpu, =20 int kvm_hv_vcpu_flush_tlb(struct kvm_vcpu *vcpu); #else /* CONFIG_KVM_HYPERV */ -static inline void kvm_hv_setup_tsc_page(struct kvm *kvm, - struct pvclock_vcpu_time_info *hv_clock) {} +static inline void kvm_hv_setup_tsc_page(struct kvm_vcpu *v, + struct pvclock_vcpu_time_info *hv_clock, + unsigned int seq) {} static inline void kvm_hv_request_tsc_page_update(struct kvm *kvm) {} static inline void kvm_hv_xsaves_xsavec_maybe_warn(struct kvm_vcpu *vcpu) = {} static inline void kvm_hv_init_vm(struct kvm *kvm) {} diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 05c801973a7f..f7af94d8b3bb 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1789,6 +1789,36 @@ static void kvm_end_pvclock_update(struct kvm *kvm) kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu); } =20 +/* + * Re-mark the Hyper-V TSC page once a new pvclock snapshot is published: + * the mark made before the update may have been legitimately consumed an + * instant before the publish, writing values the publish then superseded. + * The consumer must be queued after the re-mark: the CLOCK_UPDATE + * broadcast from kvm_end_pvclock_update() can have been entirely consumed + * by the time the re-mark lands, since a consumer may sleep in + * kvm_hv_setup_tsc_page() (hv_lock is a mutex) across the whole update = =E2=80=94 + * the same sleep which serializes it against this re-mark. Queue on + * every vCPU: any one suffices (the page is VM-wide), but none in + * particular is guaranteed to ever run again. + */ +static void kvm_hv_remark_tsc_page(struct kvm *kvm) +{ +#ifdef CONFIG_KVM_HYPERV + kvm_hv_request_tsc_page_update(kvm); + + /* + * Racy, but benign: a transition to HV_TSC_PAGE_SET in the + * instants after the re-mark means a consumer has just written + * the page from the current snapshot, and a guest which never + * enabled the page (UNSET/BROKEN, the common case) needs no + * broadcast at all. + */ + if (READ_ONCE(to_kvm_hv(kvm)->hv_tsc_page_status) =3D=3D + HV_TSC_PAGE_HOST_CHANGED) + kvm_make_all_cpus_request(kvm, KVM_REQ_CLOCK_UPDATE); +#endif +} + static void kvm_update_masterclock(struct kvm *kvm) { kvm_hv_request_tsc_page_update(kvm); @@ -1961,6 +1991,7 @@ int kvm_guest_time_update(struct kvm_vcpu *v) } while (read_seqcount_retry(&ka->pvclock_sc, seq)); #else const bool use_master_clock =3D false; + unsigned int seq =3D read_seqcount_begin(&ka->pvclock_sc); #endif /* * Ensure reading the TSC+frequency pair is done on the same CPU. When @@ -2056,7 +2087,7 @@ int kvm_guest_time_update(struct kvm_vcpu *v) hv_clock.flags &=3D ~PVCLOCK_GUEST_STOPPED; } =20 - kvm_hv_setup_tsc_page(v->kvm, &hv_clock); + kvm_hv_setup_tsc_page(v, &hv_clock, seq); =20 #ifdef CONFIG_KVM_XEN /* @@ -4572,6 +4603,9 @@ static int kvm_vm_ioctl_set_clock(struct kvm *kvm, vo= id __user *argp) now_raw_ns =3D get_kvmclock_base_ns(); ka->kvmclock_offset =3D data.clock - now_raw_ns; kvm_end_pvclock_update(kvm); + + /* As in kvm_update_masterclock(): re-mark after publishing. */ + kvm_hv_remark_tsc_page(kvm); return 0; } =20 --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=FD4rZ/Dq1+ihgVS8a5mVrsehyljMXUo78x+SbEcbrdIYVim4Z/E6WoP0fq/ptI3Yg/FB 0g3GbQzlGxmRBo8M/5A10YcDm/UUzcGbTsbXHYUHjabCh9XmW/ak0e+awkzqhpqd9Jmla OKh56kDfpnqv1IeBy9s3hVD+VOzJwGEaebiuiSE9e5R8HkLWra+x+0+NBOB1C9wO8tW1H 8eqxenRUtP9fu3WKQiYkQORI58Bkxde8qemBOaPODWCjHy2xEg+3ELONwRIyKIgT5w8MM OeTvD+a+XrwEabz1fm3DWccgkU3nbr/XWSqGKsUCcfaeQB47YrePyhkTGMLiEDrt4tw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=vWs4t5uxl9jHxvt00tM8dY6zv888q/Xb7jvTWjeauvw=; b=DWVMiWGcZ5Aeksey36CFnkKNSPFsa8Va689cQp1ikSrSfouqpdQu1CcsV/JHiph1SZFW BIc6+6GIMN0//fcd5pil+3Pth+Rwc/B05N4xuhe6tsAviWX2FFW4RfuZ3yv7WWE8fcJkT aGnZvjVGzLC9LPrttyDz5UZB/79zOnicOjOveg7i69aZ/oVq6RKZnz7spwtsSKRHIsDO1 mZqzakBkyezts3uBux2QOQ79X13RJAb+CL8kigcEuO+FSVeEnHoZAexqqWb7RyGHLcK4J psnlehOZP0qHn5V8uLeYhsZ/eJWq4HRdoE+Gf1E6sfuYNsifoBcRueGsNcMJfBxePXQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=B0c6cVsS; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 367AC606B784; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 367AC606B784 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=B0c6cVsS DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=vWs4t5uxl9jHxvt00tM8dY6zv888q/Xb7jvTWjeauvw=; b=B0c6cVsSxce2OrrqxC/zRui5F5 Dz5AvMue4Sv/ggFoLJPcscu4jQ2t/mbe8NsBBgsFONIdLXMf/1TuOTjrC7eg84Jy4OEEfhzW0BxBk zmhWDaef/8um3IflDZOaVmKbiXcFF06V2cA+cpTEjwebiyWi/Sqh6m8QDYSIa30HzqvMw+txcFOuY 3ReiaJO74Zg1lCyFEgM6kWjc3yF0DWQoR5Yyq3W6IpzbgMIp/giuE6K0lPyEPnG6ah46LNofAyBfg 9BVFanOuzGu6OxCh6bGsQ1IX5MGwusfghV698fp+p5F8OJSgzwtbhC2Zy5hHCwaF6ezbMujeTZ1sC cQl6Yh+A==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvN-3CJy; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsW-0ONu; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 08/26] KVM: x86: Avoid redundant masterclock updates from multiple vCPUs Date: Wed, 11 Nov 2026 10:09:04 -0800 Message-ID: <20261111180922.4177927-9-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse When a masterclock update is triggered (e.g. by the clocksource change notifier), KVM_REQ_MASTERCLOCK_UPDATE is set on all vCPUs, and each of them independently re-executed the whole pvclock_update_vm_gtod_copy() sequence, serialized only by tsc_write_lock. Every redundant re-snapshot moves the reference point. Let the first vCPU to take the lock do the update and clear the request on the others, which then bail out; the caller in vcpu_enter_guest() uses the non-clearing kvm_test_request(), since the clearing happens under the lock. Concurrent updaters are refcounted: each broadcasts its KVM_REQ_MCLOCK_INPROGRESS kicks before contending for the lock, and only the last one out releases them, so a finishing updater cannot free vCPUs into the guest while another update is in flight. The seqcount write section opens before the pending requests are consumed =E2=80=94 a vCPU which sees its request gone and heads into kvm_guest_time_update() spins until the new snapshot is live =E2=80=94 and closes before the KVM_REQ_CLOCK_UPDATE broadcast, so readers do not spin across the request loops. Those loops run with interrupts off under tsc_write_lock: bounded by the vCPU count, paid once per deduplicated update. Since the update now consumes pending requests, the Hyper-V reenlightenment notifier must invalidate the Hyper-V TSC page itself; previously a surviving request refreshed the page later. Deduplication also strips the paper off an old race on the Hyper-V TSC page which the preceding commit fixed properly: every vCPU re-running the broadcast used to re-mark the page by accident, so the masterclock update paths must now re-mark it on purpose, as KVM_SET_CLOCK already does, once the new snapshot is published. Suggested-by: Dongli Zhang Tested-by: Dongli Zhang Signed-off-by: David Woodhouse --- arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/msrs.c | 11 ++- arch/x86/kvm/x86.c | 122 +++++++++++++++++++++++++++----- 3 files changed, 115 insertions(+), 19 deletions(-) diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_hos= t.h index 74306a81e882..3f5aa1d3f6bb 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -1241,6 +1241,7 @@ struct kvm_arch { raw_spinlock_t tsc_write_lock; u32 cur_tsc_khz; u64 cur_tsc_scaling_ratio; + int mclock_updaters; /* protected by tsc_write_lock */ u64 cur_tsc_nsec; u64 cur_tsc_write; u64 cur_tsc_offset; diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c index a2dffa1c706f..26eb30f10c43 100644 --- a/arch/x86/kvm/msrs.c +++ b/arch/x86/kvm/msrs.c @@ -1278,10 +1278,15 @@ static void kvm_write_system_time(struct kvm_vcpu *= vcpu, gpa_t system_time, struct kvm_arch *ka =3D &vcpu->kvm->arch; =20 if (vcpu->vcpu_id =3D=3D 0 && !host_initiated) { - if (ka->boot_vcpu_runs_old_kvmclock !=3D old_msr) + /* + * Store the flag before requesting the masterclock update: + * the update may now be performed by another vCPU (which + * consumes this request), and it must observe the new value. + */ + if (ka->boot_vcpu_runs_old_kvmclock !=3D old_msr) { + ka->boot_vcpu_runs_old_kvmclock =3D old_msr; kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); - - ka->boot_vcpu_runs_old_kvmclock =3D old_msr; + } } =20 vcpu->arch.time =3D system_time; diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index f7af94d8b3bb..0b3b04a156da 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1756,13 +1756,72 @@ static void pvclock_update_vm_gtod_copy(struct kvm = *kvm) =20 static void kvm_make_mclock_inprogress_request(struct kvm *kvm) { + unsigned long flags; + + /* + * Count updaters in flight: several can broadcast their + * KVM_REQ_MCLOCK_INPROGRESS kicks and then contend for + * tsc_write_lock, and whoever finishes (or bails out) first must + * not clear the kicks out from under the updates still pending =E2=80=94 + * vCPUs would re-enter the guest mid-update and miss the + * un-kicked KVM_REQ_CLOCK_UPDATE made at the end. + */ + raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); + kvm->arch.mclock_updaters++; + raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags); + kvm_make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS); } =20 -static void __kvm_start_pvclock_update(struct kvm *kvm) +/* Drop an updater; the last one out re-allows guest entries. */ +static void kvm_put_mclock_updater(struct kvm *kvm) +{ + struct kvm_vcpu *vcpu; + unsigned long i; + + lockdep_assert_held(&kvm->arch.tsc_write_lock); + + if (--kvm->arch.mclock_updaters) + return; + + kvm_for_each_vcpu(i, vcpu, kvm) + kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu); +} + +static bool __kvm_start_pvclock_update(struct kvm *kvm, struct kvm_vcpu *r= equesting_vcpu) { + struct kvm_vcpu *vcpu; + unsigned long i; + raw_spin_lock_irq(&kvm->arch.tsc_write_lock); + + /* + * If another vCPU already did the update while we were waiting + * for the lock, our request will have been cleared. Bail out, + * dropping this updater's hold on KVM_REQ_MCLOCK_INPROGRESS. + */ + if (requesting_vcpu && + !kvm_test_request(KVM_REQ_MASTERCLOCK_UPDATE, requesting_vcpu)) { + kvm_put_mclock_updater(kvm); + raw_spin_unlock_irq(&kvm->arch.tsc_write_lock); + return false; + } + + /* + * Open the seqcount before consuming the other vCPUs' requests: + * a vCPU which sees its KVM_REQ_MASTERCLOCK_UPDATE gone and goes + * straight to kvm_guest_time_update() must then spin on the + * seqcount until the new snapshot is live, rather than read the + * old one (and, via kvm_hv_setup_tsc_page(), consume the Hyper-V + * TSC page's pending state against it). + */ write_seqcount_begin(&kvm->arch.pvclock_sc); + + /* The update is VM-wide; prevent other vCPUs from redoing it. */ + kvm_for_each_vcpu(i, vcpu, kvm) + kvm_clear_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); + + return true; } =20 static void kvm_start_pvclock_update(struct kvm *kvm) @@ -1770,7 +1829,7 @@ static void kvm_start_pvclock_update(struct kvm *kvm) kvm_make_mclock_inprogress_request(kvm); =20 /* no guest entries from this point */ - __kvm_start_pvclock_update(kvm); + __kvm_start_pvclock_update(kvm, NULL); } =20 static void kvm_end_pvclock_update(struct kvm *kvm) @@ -1779,14 +1838,22 @@ static void kvm_end_pvclock_update(struct kvm *kvm) struct kvm_vcpu *vcpu; unsigned long i; =20 + /* + * The new snapshot is complete; close the seqcount first so + * readers stop spinning while the requests are broadcast. The + * CLOCK_UPDATE requests must precede the release of the + * INPROGRESS holds, so that a vCPU allowed back into the guest + * is guaranteed to refresh its pvclock on the way in. + */ write_seqcount_end(&ka->pvclock_sc); - raw_spin_unlock_irq(&ka->tsc_write_lock); + kvm_for_each_vcpu(i, vcpu, kvm) kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); =20 - /* guest entries allowed */ - kvm_for_each_vcpu(i, vcpu, kvm) - kvm_clear_request(KVM_REQ_MCLOCK_INPROGRESS, vcpu); + /* guest entries allowed, unless another update is in flight */ + kvm_put_mclock_updater(kvm); + + raw_spin_unlock_irq(&ka->tsc_write_lock); } =20 /* @@ -1819,12 +1886,27 @@ static void kvm_hv_remark_tsc_page(struct kvm *kvm) #endif } =20 -static void kvm_update_masterclock(struct kvm *kvm) +static void kvm_update_masterclock(struct kvm *kvm, struct kvm_vcpu *vcpu) { + /* + * The Hyper-V TSC page request is made before the dedupe check + * in __kvm_start_pvclock_update() because it takes a mutex and + * so cannot sit inside the tsc_write_lock critical section where + * the winning updater is known. A losing vCPU may therefore mark + * the page HOST_CHANGED after the winner has already rewritten + * it; the next clock update then rewrites the page again with + * the same contents, which the TSC-page sequence protocol makes + * safe against concurrently running guests. + */ kvm_hv_request_tsc_page_update(kvm); - kvm_start_pvclock_update(kvm); - pvclock_update_vm_gtod_copy(kvm); - kvm_end_pvclock_update(kvm); + kvm_make_mclock_inprogress_request(kvm); + + if (__kvm_start_pvclock_update(kvm, vcpu)) { + pvclock_update_vm_gtod_copy(kvm); + kvm_end_pvclock_update(kvm); + + kvm_hv_remark_tsc_page(kvm); + } } =20 /* @@ -4604,7 +4686,6 @@ static int kvm_vm_ioctl_set_clock(struct kvm *kvm, vo= id __user *argp) ka->kvmclock_offset =3D data.clock - now_raw_ns; kvm_end_pvclock_update(kvm); =20 - /* As in kvm_update_masterclock(): re-mark after publishing. */ kvm_hv_remark_tsc_page(kvm); return 0; } @@ -6961,9 +7042,18 @@ static void kvm_hyperv_tsc_notifier(void) kvm_caps.max_guest_tsc_khz =3D tsc_khz; =20 list_for_each_entry(kvm, &vm_list, vm_list) { - __kvm_start_pvclock_update(kvm); + /* + * Invalidate the Hyper-V TSC page explicitly: the update + * below consumes any pending KVM_REQ_MASTERCLOCK_UPDATE, + * which would otherwise have refreshed the page from + * kvm_update_masterclock(). + */ + kvm_hv_request_tsc_page_update(kvm); + __kvm_start_pvclock_update(kvm, NULL); pvclock_update_vm_gtod_copy(kvm); kvm_end_pvclock_update(kvm); + + kvm_hv_remark_tsc_page(kvm); } =20 mutex_unlock(&kvm_lock); @@ -8367,8 +8457,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu) kvm_mmu_free_obsolete_roots(vcpu); if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu)) __kvm_migrate_timers(vcpu); - if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) - kvm_update_masterclock(vcpu->kvm); + if (kvm_test_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) + kvm_update_masterclock(vcpu->kvm, vcpu); if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu)) kvm_gen_kvmclock_update(vcpu); if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) { @@ -9766,13 +9856,13 @@ void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu) * master clock does not stay in its previous mode with * running siblings keeping PVCLOCK_TSC_STABLE_BIT. */ - kvm_update_masterclock(vcpu->kvm); + kvm_update_masterclock(vcpu->kvm, NULL); return; } vcpu_load(vcpu); kvm_synchronize_tsc(vcpu, NULL); if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) - kvm_update_masterclock(vcpu->kvm); + kvm_update_masterclock(vcpu->kvm, NULL); vcpu_put(vcpu); =20 /* poll control enabled by default */ --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=LcbdKGC7K3OQuLelVIda+UEJyjXTPS8tjRb7yc9A4cD8qwvf64u2uD7WS7cKB2RCKd0K cO9HhsF2+EGlFzADxx1fEKuBZOPosepBfGcyptWggbxQ+N/nlTMsqzMUbZF7q4aPHKy5j Btti+okFBwctCzQ9X+8Q/Ij7RwE/wNqD5+wyUX8HegVABr/vMLagDvZkobTA04KtgdTqn a8A1Y1JMOhnOLnbv3yLVSHYU7D9KzOuodL0YuZbpovjdIBIAbaGG8iBWpZQ/I07cmWPEh w+O0RYBIoDWmUqNdNrGuBc4hf26sQ1YReRepzYvzPQMbT80X9Xw8VRw9LeFCYfAQfyA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=CwMbftQQz760x46CNDvM8hDlvtc6TEl7MUzV2LCVoJ8=; b=nfHdygxqCwmpuYBUtRh86oeXq6ieXH7zzcRtln8BCR1jtWzjgZJaUy1yz6Fvf7q/BkqB jbQHKtWh/kDrEkBeL+lUmXFtQfC/m/B81q3LS4bGkM9lVodfEPPqhuwrl6DEvbowpDyd6 luQ6ukN+iCIprDu0oReXVLwl4CucJeGs6mMAbyuKjPK7ck8K/rrZ8R59rUQsOuyPNZWJF YBPAmQzT1J7HvJVyFU2eK2t9WhSuKBey43wBz3Jg6xXbdh1SYgO11zfmw2NwUWOI4Hz30 m/ovFlj/ql3GcRWLMpFYBAALywaXEUwoN8Whbgi8qqpmO8f8PkuhMZ18ZwcyQGtRyxg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b="m1HC/fXW"; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E6752606A32E; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E6752606A32E Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=m1HC/fXW DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=CwMbftQQz760x46CNDvM8hDlvtc6TEl7MUzV2LCVoJ8=; b=m1HC/fXWMOhVcPBaVX9ACJgkhP iXh3emo0NGR0nWK2rwd8+E0IrGrZxZBfaiw4HEggmHieFrvcE1iFTJ0r3byuFZqxXgg3YEMPS7FOf eIJJGd0Fg4BqDjuNZx3szMRg0+whVz6xwejmjhGhgfBlc0ZPmCi4LM2+o62EOfOCYQ50V3OgHWH/w 5E0bE/PoUaTZKSRAJOgjX5olCtGmil9IVoA9yDoWgBPqYJslPFpa5FWtDhqbyjsMZ+GFAfFHFkDaX nIVhEMQYFKCx0bcKteGqzwYhruC3nsiI5wnrAmHKfBZoS5Sjkm2GdsYEF1fP/BX7xIwd43vBWVdY7 RmVqXlYw==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvV-1Puz; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsa-0a3H; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 09/26] KVM: x86: Stop TSC catchup when a frequency change no longer needs it Date: Wed, 11 Nov 2026 10:09:05 -0800 Message-ID: <20261111180922.4177927-10-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse On hardware without TSC scaling, KVM_SET_TSC_KHZ with a frequency above the host's puts the vCPU into always-catchup mode. Nothing ever takes it back out: a later KVM_SET_TSC_KHZ restoring a frequency within tsc_tolerance_ppm of the host's, where no scaling or catchup is needed, leaves the vCPU paying the catchup overhead on every clock update for the rest of its life =E2=80=94 and KVM_HC_CLOCK_PAIRING stays disabled, sin= ce it rejects always-catchup mode. Clear the pairing whenever set_tsc_khz() succeeds with a frequency which does not need it. Only that pairing: tsc_catchup alone also serves the unstable-host-TSC compensation in kvm_arch_vcpu_load(), which must not be disturbed. Fixes: cc578287e322 ("KVM: Infrastructure for software and hardware based T= SC rate scaling") Signed-off-by: David Woodhouse --- arch/x86/kvm/x86.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 0b3b04a156da..1d4b66257b35 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1031,7 +1031,7 @@ static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 use= r_tsc_khz, bool scale) /* Guest TSC same frequency as host TSC? */ if (!scale) { kvm_vcpu_write_tsc_multiplier(vcpu, kvm_caps.default_tsc_scaling_ratio); - return 0; + goto clear_catchup; } =20 /* TSC scaling supported? */ @@ -1057,6 +1057,19 @@ static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 us= er_tsc_khz, bool scale) } =20 kvm_vcpu_write_tsc_multiplier(vcpu, ratio); + +clear_catchup: + /* + * A frequency which no longer needs catchup must also stop it: a + * previous above-host-rate setting on scaling-less hardware set + * the always-catchup flags, and nothing else ever clears them. + * Only undo that pairing =E2=80=94 tsc_catchup alone also serves the + * unstable-host-TSC compensation in kvm_arch_vcpu_load(). + */ + if (vcpu->arch.tsc_always_catchup) { + vcpu->arch.tsc_always_catchup =3D 0; + vcpu->arch.tsc_catchup =3D 0; + } return 0; } =20 --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=jWIYtjsYKS95j7Bk95KbfVqW3FTfY8tgx/YNRXZhcnUUg7rm628kk+ykt5nIVdM3mXTk 8Fktl2IDet76PHQF7QK4ZZqHJ0+2RzVX7tuJGPxs7JH9n8XSY7X+89SXZ8Z9sbmX77Yzc pNfJGZA30yDswCF8uJtmlk99XHj81/6cNU75T3CL1JjhzSKw7Zd+JYuY/7i2z5xglmyIQ yjRK2ouIZ9Lp35zMyXeijUm/WU6fQJjliiJvhmR5sN7OOMD5L5ZIeDYlilp43yLLEeJ3a OJxRrNkGVxjmoLEqA02BhYpkKfmbob9cQ/xzzPk1Wl2m9Fm1kn40WxQwkThuxzVgmAw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=rukGdvZHi+FYhueyc7C7kJqyRtxzfRo4uOsIZilmUF4=; b=mXCAx6QJbk/arHuiMHF5NFsSG79vebqldwkyR+hY76In0bKSLJuQjl+8XXFSD5KRJskf Mtqw52zBh3GNZBQ9tirnNKZiwpdRhLzFZ3Ea4Q7/H2UGAOi50AkeTO/L7xyzZAhwXxKQ/ KbRugvmoySryTgxnaXe44NLR2CBW8i7V1gKHb0CLrRhtx7V8vnbdsVnp7kOCaOm0hGzyy NH/W8pd/tdlyOwRUe9qg6sDzk0hBN7Y0yYYBVBTYiIed3UuzJSegk0UnIjQ87j+MGwDHx VR6SRkGUnnl55TzmpPZPHYWBOzyzVW/jlV2jf+QQ3y2tU1QbbO4TvhOjun32HbIaAGw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=RO98a0B7; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E74A4606A330; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E74A4606A330 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=RO98a0B7 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=rukGdvZHi+FYhueyc7C7kJqyRtxzfRo4uOsIZilmUF4=; b=RO98a0B7yQvAbZcLbDxRyDWDE5 s1WsfHsDLoUB6ke24xUkdT14WCZ7nyXPDpjPEYombjtX59iNOL/LbKsHxhcb7So2o5DWKS/h5SKoP n6h/DeoanEookLBmxtYUdkNfhvnGZGsRoOqDQM1LtqnQRCi8Mfdngja01poMjmPGotwO4stJnryH5 QLbsApgO2GilT/H0+/I+942mIHdlZekyse+kIn4iGXgtKZj3TanL9Z/e0PmcFp+8LnOaamiev4skt OUKu9voFytCpj/XFSPl5j/Z2QtoPxrHmtzj/EEXrWwFREd2u1y0vRTCgNTYeuvuM30/ACbW6lMd61 hfmFH4tw==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvX-1aUq; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWse-0mBy; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 10/26] KVM: x86: Re-synchronize TSC after KVM_SET_TSC_KHZ Date: Wed, 11 Nov 2026 10:09:06 -0800 Message-ID: <20261111180922.4177927-11-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse KVM_SET_TSC_KHZ changes the vCPU's TSC scaling ratio but not the VM-wide cur_tsc_scaling_ratio used by get_kvmclock(), which then computes the KVM clock with a stale ratio and drifts away from what the guest observes. Re-synchronize the TSC after a frequency change. That updates the VM-wide scaling ratio, keeps the guest TSC value continuous across the change, and establishes the new generation for subsequent vCPUs to match. Two cases are skipped: vCPU creation, which is not yet counted in online_vcpus (the postcreate synchronization covers it), and an unchanged frequency, which is documented as a no-op =E2=80=94 tested before anything which could fail, since creation commits a frequency even when set_tsc_khz() cannot honour it, and a repeated set of that same frequency must not turn into -EINVAL. The preserved value is sampled as a {guest TSC, host clock} tuple and the new offset is computed against the tuple's own reference point, not against "now", so delay between sample and installation costs nothing. Preemption stays disabled from the sample until tsc_write_lock is held: this task's own preempt notifier is the one writer which could apply a pending backwards-TSC compensation to the offset the sample was read through, and one still pending at the lock is folded in there. A failed ioctl commits nothing, so a retry does not masquerade as a frequency change (creation commits regardless, as it always has =E2=80=94 its caller ignores the return value). A kernel-internal call is distinguished from a userspace write by an explicit user_initiated parameter: the internal call must not set user_set_tsc and arm the 1-second slop heuristic before userspace has ever written a TSC. Because the internal sample is exact it gets a 1ms matching window instead of the legacy API's 1-second slop: a vCPU on the generation's timeline still matches, but one which genuinely diverged (a guest TSC_ADJUST write) keeps its exact value. Values preserved from the old frequency diverge from the new generation's line at |F1-F2| per unit time =E2=80=94 the honest cost of preserving them. Only a vCPU which has run, or whose TSC userspace explicitly wrote, has a value worth preserving; track that with a new per-vCPU user_set_tsc flag, since the VM-wide flag would let one vCPU's restored TSC cause a sibling's unrestored creation-time value to be preserved. A never-run vCPU is synchronized as for a zero write, landing on the generation's timeline at the new frequency. The arithmetic corners =E2=80=94 a tuple sampled just before a sibling open= s a newer generation, the wrap-safe matching window, the zero clamp for an unrun vCPU forced onto a younger generation =E2=80=94 are documented where they live, in __kvm_synchronize_tsc_at(). The virtual_tsc_mult/shift pair is still published non-atomically, exactly as it always was. A KVM_GET_CLOCK issued before the resulting masterclock update is serviced still returns the correct time: the masterclock snapshot is self-consistent, and the ns it yields is independent of the guest frequency it encodes. Signed-off-by: David Woodhouse --- Documentation/virt/kvm/api.rst | 8 + arch/x86/include/asm/kvm_host.h | 1 + arch/x86/kvm/msrs.c | 2 +- arch/x86/kvm/x86.c | 284 ++++++++++++++++++++++++++++---- arch/x86/kvm/x86.h | 2 +- 5 files changed, 260 insertions(+), 37 deletions(-) diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst index ddc61ea36ac5..9487afc4431f 100644 --- a/Documentation/virt/kvm/api.rst +++ b/Documentation/virt/kvm/api.rst @@ -2023,6 +2023,14 @@ If the KVM_CAP_VM_TSC_CONTROL capability is advertis= ed, this can also be used as a vm ioctl to set the initial tsc frequency of subsequently created vCPUs. Note, the vm ioctl is only allowed prior to creating vCPUs. =20 +Changing the frequency of a vCPU with the vcpu ioctl re-synchronizes +its TSC: for a vCPU which has run, or whose TSC userspace has written, +the current guest TSC value is preserved across the change (the TSC +offset, as visible through the KVM_VCPU_TSC_OFFSET attribute, is +rewritten accordingly); otherwise the vCPU is synchronized to the +VM's existing TSC timeline at the new frequency. Setting the current +frequency again is a no-op. + For TSC protected Confidential Computing (CoCo) VMs where TSC frequency is configured once at VM scope and remains unchanged during VM's lifetime, the vm ioctl should be used to configure the TSC frequency diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_hos= t.h index 3f5aa1d3f6bb..773df58898ea 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -888,6 +888,7 @@ struct kvm_vcpu_arch { u64 this_tsc_write; u64 this_tsc_generation; u64 this_tsc_freq_generation; + bool user_set_tsc; bool tsc_catchup; bool tsc_always_catchup; s8 virtual_tsc_shift; diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c index 26eb30f10c43..d07831b5dfb8 100644 --- a/arch/x86/kvm/msrs.c +++ b/arch/x86/kvm/msrs.c @@ -1645,7 +1645,7 @@ int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct = msr_data *msr_info) break; case MSR_IA32_TSC: if (msr_info->host_initiated) { - kvm_synchronize_tsc(vcpu, &data); + kvm_synchronize_tsc(vcpu, &data, true); } else if (!vcpu->arch.guest_tsc_protected) { u64 adj =3D kvm_compute_l1_tsc_offset(vcpu, rdtsc(), data) - vcpu->arch.l1_tsc_offset; diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 1d4b66257b35..cf35363366f1 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1073,10 +1073,20 @@ static int set_tsc_khz(struct kvm_vcpu *vcpu, u32 u= ser_tsc_khz, bool scale) return 0; } =20 -static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz) +static void __kvm_synchronize_tsc_at(struct kvm_vcpu *vcpu, u64 *value, + u64 host_tsc, s64 ns, + bool user_initiated); + +static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 user_tsc_khz, bool i= nit) { + bool freq_changed =3D (vcpu->arch.virtual_tsc_khz !=3D user_tsc_khz); u32 thresh_lo, thresh_hi; + u32 tsc_mult; + s8 tsc_shift; int use_scaling =3D 0; + u64 tsc, host_tsc; + unsigned long flags; + s64 ns; =20 /* tsc_khz can be zero if TSC calibration fails */ if (user_tsc_khz =3D=3D 0) { @@ -1085,11 +1095,19 @@ static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u= 32 user_tsc_khz) return -1; } =20 + /* + * Setting the current frequency again is a no-op, as documented + * =E2=80=94 unconditionally, including a frequency the hardware could + * not honour at vCPU creation (which commits it regardless): + * re-running set_tsc_khz() would turn the documented no-op into + * -EINVAL. + */ + if (!init && !freq_changed) + return 0; + /* Compute a scale to convert nanoseconds in TSC cycles */ kvm_get_time_scale(user_tsc_khz * 1000LL, NSEC_PER_SEC, - &vcpu->arch.virtual_tsc_shift, - &vcpu->arch.virtual_tsc_mult); - vcpu->arch.virtual_tsc_khz =3D user_tsc_khz; + &tsc_shift, &tsc_mult); =20 /* * Compute the variation in TSC rate which is acceptable @@ -1104,7 +1122,92 @@ static int kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u3= 2 user_tsc_khz) user_tsc_khz, thresh_lo, thresh_hi); use_scaling =3D 1; } - return set_tsc_khz(vcpu, user_tsc_khz, use_scaling); + + /* + * Sample the guest TSC before changing the ratio, so continuity + * can be preserved across the change =E2=80=94 as a {guest TSC, host + * clock} tuple, not a bare value: the synchronization below + * computes the new offset against the tuple's own reference + * point, so the guest TSC keeps counting through this function. + * Preemption stays disabled from the sample until tsc_write_lock + * is held =E2=80=94 not for timing, but because this task's own preempt + * notifier (kvm_sched_in -> kvm_arch_vcpu_load) is the one + * writer which could apply a pending backwards-TSC compensation + * to the offset the sample was read through; a compensation + * still pending when the lock is taken is folded in there. + */ + if (!init) { + preempt_disable(); +#ifdef CONFIG_X86_64 + if (!kvm_get_time_and_clockread(&ns, &host_tsc)) +#endif + { + unsigned long irqflags; + + /* + * The two reads must form one coherent reference + * point. + */ + local_irq_save(irqflags); + host_tsc =3D rdtsc(); + ns =3D get_kvmclock_base_ns(); + local_irq_restore(irqflags); + } + tsc =3D kvm_read_l1_tsc(vcpu, host_tsc); + } + + /* + * Commit the new frequency only once set_tsc_khz() can no longer + * fail: a failed ioctl must leave no trace, or a retry with the + * still-active frequency would wrongly look like a change. The + * exception is vCPU creation (@init), whose caller ignores the + * return value: commit the requested frequency even when the + * hardware cannot scale to it, as creation always has, rather + * than leave the vCPU with the zeroed frequency from allocation + * (KVM_GET_TSC_KHZ would report 0, and the catchup path would + * compute with a zero mult). + */ + if (set_tsc_khz(vcpu, user_tsc_khz, use_scaling) && !init) { + preempt_enable(); + return -1; + } + + vcpu->arch.virtual_tsc_shift =3D tsc_shift; + vcpu->arch.virtual_tsc_mult =3D tsc_mult; + vcpu->arch.virtual_tsc_khz =3D user_tsc_khz; + + /* + * At vCPU creation (@init) the vCPU is not yet counted in + * online_vcpus, so synchronizing here would corrupt the VM-wide + * matching state (and leave it corrupted if creation subsequently + * fails). The initial synchronization happens in + * kvm_arch_vcpu_postcreate() instead. + */ + if (init) + return 0; + + /* + * Changing the frequency changes the vCPU's position on the + * generation's cycle timeline, so re-synchronize. For a vCPU + * which has run, preserve the guest TSC value read above across + * the change; likewise if userspace has written a TSC on this + * vCPU =E2=80=94 a zero write would discard it. Otherwise the vCPU holds + * only its creation-time synchronization, so synchronize as for + * a zero write. When the generation is already at the new + * frequency this places the vCPU on its timeline rather than + * opening a gratuitous new generation and orphaning the matched + * state of its siblings; the first vCPU to adopt a new frequency + * necessarily opens a new generation, starting at zero =E2=80=94 mixed + * frequencies within a VM forfeit the master clock anyway. + */ + raw_spin_lock_irqsave(&vcpu->kvm->arch.tsc_write_lock, flags); + preempt_enable(); + if (vcpu->arch.last_vmentry_cpu !=3D -1 || vcpu->arch.user_set_tsc) + __kvm_synchronize_tsc_at(vcpu, &tsc, host_tsc, ns, false); + else + __kvm_synchronize_tsc_at(vcpu, NULL, host_tsc, ns, false); + raw_spin_unlock_irqrestore(&vcpu->kvm->arch.tsc_write_lock, flags); + return 0; } =20 static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns) @@ -1458,8 +1561,10 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *v= cpu, u64 offset, u64 tsc, return; } =20 - if (user_set_tsc) + if (user_set_tsc) { vcpu->kvm->arch.user_set_tsc =3D true; + vcpu->arch.user_set_tsc =3D true; + } =20 vcpu->arch.last_guest_tsc =3D tsc; =20 @@ -1511,40 +1616,84 @@ static void __kvm_synchronize_tsc(struct kvm_vcpu *= vcpu, u64 offset, u64 tsc, kvm_track_tsc_matching(vcpu, !matched); } =20 -void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value) +/* + * Synchronize the vCPU's TSC against an explicit {host_tsc, ns} reference + * point: @value (when non-NULL) is the guest TSC *at* @host_tsc, not at + * some unspecified "now". The offset is computed against that reference, + * so a sampled value stays valid however much time passes between the + * sampling and this call. + */ +static void __kvm_synchronize_tsc_at(struct kvm_vcpu *vcpu, u64 *value, + u64 host_tsc, s64 ns, + bool user_initiated) { - u64 data =3D user_value ? *user_value : 0; + u64 data =3D value ? *value : 0; struct kvm *kvm =3D vcpu->kvm; - u64 offset, host_tsc, elapsed; - s64 ns; - unsigned long flags; + u64 elapsed_cycles =3D 0; + s64 elapsed; + u64 offset; bool matched =3D false; bool synchronizing =3D false; =20 - raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); + lockdep_assert_held(&kvm->arch.tsc_write_lock); =20 -#ifdef CONFIG_X86_64 - if (!kvm_get_time_and_clockread(&ns, &host_tsc)) -#endif - { - host_tsc =3D rdtsc(); - ns =3D get_kvmclock_base_ns(); - } + /* + * A backwards-TSC compensation pending now was not in a sampled + * @value: it is applied to the vCPU's offset only at vcpu_load, + * and the sample was read through the uncompensated offset. Fold + * it in (scaled as adjust_tsc_offset_host() would), since + * __kvm_synchronize_tsc() clears the pending adjustment as + * superseded by the absolute offset installed here. A + * user-initiated value is the desired guest TSC *now*, and needs + * no correction. + */ + if (unlikely(vcpu->arch.tsc_offset_adjustment) && + value && !user_initiated) + data +=3D kvm_scale_tsc(vcpu->arch.tsc_offset_adjustment, + vcpu->arch.l1_tsc_scaling_ratio); =20 offset =3D kvm_compute_l1_tsc_offset(vcpu, host_tsc, data); + + /* + * The {host_tsc, ns} reference may have been sampled before a + * concurrent synchronization (on another vCPU) opened a newer + * generation, making the elapsed time negative. The anchored + * offset above is still exact either way; extrapolate the + * generation's line backwards for the matching comparison, so + * that the error stays at |F1-F2| times the sampling skew. + * Snapping to the generation's origin instead would inflate it + * to the full guest frequency times the skew, spuriously + * splitting the generation when two vCPUs race through + * KVM_SET_TSC_KHZ. + */ elapsed =3D ns - kvm->arch.cur_tsc_nsec; =20 if (vcpu->arch.virtual_tsc_khz) { - if (data =3D=3D 0) { + /* + * Keep the cycle count as a magnitude with the sign taken + * from @elapsed itself: a genuinely huge positive elapsed + * time (a u32-limit frequency and a weeks-old generation) + * must extrapolate mod 2^64, as the guest's real TSC + * would wrap, not read as negative. + */ + elapsed_cycles =3D nsec_to_cycles(vcpu, elapsed >=3D 0 ? elapsed + : -elapsed); + + if (!value || (data =3D=3D 0 && user_initiated)) { /* - * Force synchronization when creating a vCPU, or when - * userspace explicitly writes a zero value. + * Force synchronization when creating a vCPU, or + * when userspace explicitly writes a zero value =E2=80=94 + * but not for an internal preserved sample which + * happens to be exactly zero: NULL, not zero, is + * the no-value case. */ synchronizing =3D true; - } else if (kvm->arch.user_set_tsc) { - u64 tsc_exp =3D kvm->arch.cur_tsc_write + - nsec_to_cycles(vcpu, elapsed); + } else if (kvm->arch.user_set_tsc || !user_initiated) { + u64 tsc_exp =3D elapsed >=3D 0 ? + kvm->arch.cur_tsc_write + elapsed_cycles : + kvm->arch.cur_tsc_write - elapsed_cycles; u64 tsc_hz =3D vcpu->arch.virtual_tsc_khz * 1000LL; + u64 window; /* * Here lies UAPI baggage: when a user-initiated TSC write has * a small delta (1 second) of virtual cycle time against the @@ -1559,9 +1708,35 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 = *user_value) * to this 'correction' to make it sync up with values that only * come from the kernel's default vCPU creation. Make the 1-second * slop hack only trigger if the user_set_tsc flag is already set. + * + * A kernel-internal write (a frequency change preserving the + * guest TSC) carries an exact value sampled with its own + * reference point, not a racy userspace one; a vCPU on the + * generation's line still matches it to within arithmetic + * rounding, but one which genuinely diverged (e.g. by a guest + * TSC_ADJUST write) must not be snapped back by up to a + * second. Use a 1ms window for those, unconditionally =E2=80=94 + * the sample's exactness owes nothing to the legacy API's + * flag. A frequency *change* still only matches siblings + * converted within 1ms=C2=B7F2/|F1-F2| of the first: values + * preserved from the old frequency genuinely diverge from + * the new generation's line at |F1-F2| per unit time. */ - synchronizing =3D data < tsc_exp + tsc_hz && - data + tsc_hz > tsc_exp; + /* + * 1ms of cycles is virtual_tsc_khz by definition; + * dividing tsc_hz would need libgcc's __udivdi3 + * on i386. + */ + window =3D user_initiated ? tsc_hz : + vcpu->arch.virtual_tsc_khz; + /* + * Wrap-safe |data - tsc_exp| < window: tsc_exp + * may itself have wrapped when elapsed_cycles is + * negative and exceeds the generation's origin + * value; the difference is still correct mod 2^64. + */ + synchronizing =3D (u64)(data - tsc_exp + window) < + 2 * window; } } =20 @@ -1579,10 +1754,19 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64= *user_value) * "now": the matching window slides forward with wall time, * anchored on the generation's origin alone (a matched * write no longer updates any stored reference point). + * A negative elapsed time (the tuple sampled just + * before a sibling opened this generation) must not wrap + * below zero: the wrapped value would land in + * last_guest_tsc, and an unstable-TSC host would + * re-anchor the guest TSC to it at the next vcpu_load. */ - u64 delta =3D nsec_to_cycles(vcpu, elapsed); - - data =3D kvm->arch.cur_tsc_write + delta; + if (elapsed < 0 && + elapsed_cycles > kvm->arch.cur_tsc_write) + data =3D 0; + else if (elapsed < 0) + data =3D kvm->arch.cur_tsc_write - elapsed_cycles; + else + data =3D kvm->arch.cur_tsc_write + elapsed_cycles; =20 if (!kvm_check_tsc_unstable()) offset =3D kvm->arch.cur_tsc_offset; @@ -1591,8 +1775,38 @@ void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 = *user_value) matched =3D true; } =20 - __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, !!user_value); - raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags); + __kvm_synchronize_tsc(vcpu, offset, data, ns, matched, user_initiated); +} + +static void kvm_synchronize_tsc_at(struct kvm_vcpu *vcpu, u64 *value, + u64 host_tsc, s64 ns, bool user_initiated) +{ + unsigned long flags; + + raw_spin_lock_irqsave(&vcpu->kvm->arch.tsc_write_lock, flags); + __kvm_synchronize_tsc_at(vcpu, value, host_tsc, ns, user_initiated); + raw_spin_unlock_irqrestore(&vcpu->kvm->arch.tsc_write_lock, flags); +} + +void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *value, bool user_init= iated) +{ + u64 host_tsc; + s64 ns; + +#ifdef CONFIG_X86_64 + if (!kvm_get_time_and_clockread(&ns, &host_tsc)) +#endif + { + unsigned long flags; + + /* The two reads must form one coherent reference point. */ + local_irq_save(flags); + host_tsc =3D rdtsc(); + ns =3D get_kvmclock_base_ns(); + local_irq_restore(flags); + } + + kvm_synchronize_tsc_at(vcpu, value, host_tsc, ns, user_initiated); } =20 #ifdef CONFIG_X86_64 @@ -4035,7 +4249,7 @@ long kvm_arch_vcpu_ioctl(struct file *filp, if (user_tsc_khz =3D=3D 0) user_tsc_khz =3D tsc_khz; =20 - if (!kvm_set_tsc_khz(vcpu, user_tsc_khz)) + if (!kvm_set_tsc_khz(vcpu, user_tsc_khz, false)) r =3D 0; =20 goto out; @@ -9814,7 +10028,7 @@ int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu) kvm_xen_init_vcpu(vcpu); vcpu_load(vcpu); kvm_vcpu_after_set_cpuid(vcpu); - kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz); + kvm_set_tsc_khz(vcpu, vcpu->kvm->arch.default_tsc_khz, true); kvm_vcpu_reset(vcpu, false); kvm_init_mmu(vcpu); vcpu_put(vcpu); @@ -9873,7 +10087,7 @@ void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu) return; } vcpu_load(vcpu); - kvm_synchronize_tsc(vcpu, NULL); + kvm_synchronize_tsc(vcpu, NULL, false); if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) kvm_update_masterclock(vcpu->kvm, NULL); vcpu_put(vcpu); diff --git a/arch/x86/kvm/x86.h b/arch/x86/kvm/x86.h index 436e2fb1396c..de4c86ea5a7d 100644 --- a/arch/x86/kvm/x86.h +++ b/arch/x86/kvm/x86.h @@ -330,7 +330,7 @@ uint64_t kvm_get_wall_clock_epoch(struct kvm *kvm); bool kvm_get_monotonic_and_clockread(s64 *kernel_ns, u64 *tsc_timestamp); int kvm_guest_time_update(struct kvm_vcpu *v); =20 -void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *user_value); +void kvm_synchronize_tsc(struct kvm_vcpu *vcpu, u64 *value, bool user_init= iated); u64 kvm_scale_tsc(u64 tsc, u64 ratio); u64 kvm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc); u64 kvm_calc_nested_tsc_offset(u64 l1_offset, u64 l2_offset, u64 l2_multip= lier); --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420579; b=EWA9rnKJLFLgV8xgTJ8onJvV41Ewz87trV9e87VGWtQYjTiWsLpbbe/hmrvM5qlybO3B jcs3IkV6POxIu3CGoA7gTDIaY4INeDrdf2Jk85ZWvZ4mKe90QlB+BRVCdBY+QT3xoCmqM 0LSGTNzz6zzGvDiM/ELIRx0M/xVQsdeW1CbISebGGxNGxgm8epI+AEgoiLNxiXO4gCW8m 4GzQ3Ms49LRC57pHaacbafcw8WLr3TvpesP4SIKaUiGWIhmd6uOWUncjLDkgoGnlSvyn5 5O2OOARA3uEwwu4A6Bv3Dq0FZ0tCAgLjLZWWZNRB/0OA8Hf4dtI+GoKFaoKPJ7SR3/Q== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420579; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=hG5BZ0GH5lCV4VFdff4Rs7YNoTlgAIqSVWn/Ib3MefQ=; b=iQ70Mf5NefazcI0Zz5DLds+CbEGfqOexyTEoV/R/hQhkQWz84nc7P17clbFx6e0HPujU fMNHzeMAGnu142YvhfiaGNraJ8MMTL12tZWd3g7Oay/UN2WbN0IxnYp6oI2FWII2daXUf Z7Ppwd/BmIbK5QCerJFDI6B9zsbnhA8npfQ1HtmZY/ZVQLcIKjESsCTzqBztfcb8/+uzZ wlEl9M6suW1LlFe6UWPGtzHpXV6DZjz9TXOztJg0aMwJJbBsdsOKuv2u37Rd240aYVx/W Tc79e3mGAY3bvmK0cAS7J8/tFLQTo89Tk+rOPYF4MI4zbtgafJ+w6cPkN4MJgkmyzkg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b="pRsnq65/"; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 189FE606C14D; Wed, 11 Nov 2026 18:09:38 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 189FE606C14D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=pRsnq65/ DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=hG5BZ0GH5lCV4VFdff4Rs7YNoTlgAIqSVWn/Ib3MefQ=; b=pRsnq65/l31Fvq0M3F515Ivmye 7B0IxhPzrQQtPyuijoD+5M3Q6pE/cLuHz2hllAyF+agQjSeT1wDJ8IuYYGN2IUV65R+GX+bsfuG93 JeuV7/MRYvElaaE03jdNpr6RhCDzdJllckcuEMQCqPmch4EG+NxRnh0m93XikBJgHuLr6i97TwuDm osXLbtdpBqVwanq2mJHfx1gHaZFzCmH1FwZSahqt3vP2MDcYv2vON3rOCi+52r+e8lzwHNfBsg3b3 Iqo5FSqVR605u9tXoIZDiz4amrq/hWDHqrRM9LSrMKubSTM16fp7EV2jVRUl7pfTMXdxEhGMff1vL zEhEYhlQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvO-3EGv; Wed, 11 Nov 2026 18:09:31 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsi-0xEB; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 11/26] KVM: x86: Cache host vclock_mode for masterclock eligibility checks Date: Wed, 11 Nov 2026 10:09:07 -0800 Message-ID: <20261111180922.4177927-12-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse The remaining users of pvclock_gtod_data only need to know whether the host clocksource is TSC-based. Cache the vclock_mode value in a simple kvm_host_vclock_mode variable, updated by the pvclock_gtod_notify callback, and use gtod_is_based_on_tsc() for eligibility checks. This is inherently racy (as it always was =E2=80=94 kvm_track_tsc_matching never held the gtod seqcount), relying on eventual consistency: the notifier fires on every timekeeping update and will correct any transient inconsistency within one tick. Signed-off-by: David Woodhouse --- arch/x86/kvm/x86.c | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index cf35363366f1..f7dd4129dc51 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1224,6 +1224,8 @@ static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s= 64 kernel_ns) } =20 #ifdef CONFIG_X86_64 +static int kvm_host_vclock_mode; + static inline bool gtod_is_based_on_tsc(int mode) { return mode =3D=3D VDSO_CLOCKMODE_TSC || mode =3D=3D VDSO_CLOCKMODE_HVCLO= CK; @@ -1253,7 +1255,6 @@ static bool kvm_use_master_clock(struct kvm *kvm) static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool update_mclo= ck) { struct kvm_arch *ka =3D &vcpu->kvm->arch; - struct pvclock_gtod_data *gtod =3D &pvclock_gtod_data; bool prev_matched_tsc =3D ka->all_vcpus_matched_tsc; bool prev_matched_freq =3D ka->all_vcpus_matched_freq; =20 @@ -1306,8 +1307,9 @@ static void kvm_track_tsc_matching(struct kvm_vcpu *v= cpu, bool update_mclock) * are fine =E2=80=94 each vCPU's pvclock has its own tsc_timestamp that * accounts for its offset. */ + int host_vclock_mode =3D READ_ONCE(kvm_host_vclock_mode); bool use_master_clock =3D kvm_use_master_clock(vcpu->kvm) && - gtod_is_based_on_tsc(gtod->clock.vclock_mode); + gtod_is_based_on_tsc(host_vclock_mode); =20 /* * Request a masterclock update if needed: toggling master clock, @@ -1320,7 +1322,7 @@ static void kvm_track_tsc_matching(struct kvm_vcpu *v= cpu, bool update_mclock) =20 trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc, atomic_read(&vcpu->kvm->online_vcpus), - ka->use_master_clock, gtod->clock.vclock_mode); + ka->use_master_clock, host_vclock_mode); } #else static inline void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, @@ -1491,7 +1493,7 @@ static inline bool kvm_check_tsc_unstable(void) * TSC is marked unstable when we're running on Hyper-V, * 'TSC page' clocksource is good. */ - if (pvclock_gtod_data.clock.vclock_mode =3D=3D VDSO_CLOCKMODE_HVCLOCK) + if (READ_ONCE(kvm_host_vclock_mode) =3D=3D VDSO_CLOCKMODE_HVCLOCK) return false; #endif return check_tsc_unstable(); @@ -1935,7 +1937,6 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) { #ifdef CONFIG_X86_64 struct kvm_arch *ka =3D &kvm->arch; - int vclock_mode; bool host_tsc_clocksource; =20 lockdep_assert_held(&kvm->arch.tsc_write_lock); @@ -1975,9 +1976,9 @@ static void pvclock_update_vm_gtod_copy(struct kvm *k= vm) ka->use_master_clock =3D false; } =20 - vclock_mode =3D pvclock_gtod_data.clock.vclock_mode; - trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode, - ka->all_vcpus_matched_freq); + trace_kvm_update_master_clock(ka->use_master_clock, + READ_ONCE(kvm_host_vclock_mode), + ka->all_vcpus_matched_freq); #endif } =20 @@ -7452,17 +7453,23 @@ static DEFINE_IRQ_WORK(pvclock_irq_work, pvclock_ir= q_work_fn); static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long un= used, void *priv) { - struct pvclock_gtod_data *gtod =3D &pvclock_gtod_data; struct timekeeper *tk =3D priv; =20 update_pvclock_gtod(tk); =20 + /* + * Pairs with the READ_ONCE() in the lockless readers; the race is + * benign by design, relying on eventual consistency (the notifier + * fires on every timekeeping update). + */ + WRITE_ONCE(kvm_host_vclock_mode, tk->tkr_mono.clock->vdso_clock_mode); + /* * Disable master clock if host does not trust, or does not use, * TSC based clocksource. Delegate queue_work() to irq_work as * this is invoked with tk_core.seq write held. */ - if (!gtod_is_based_on_tsc(gtod->clock.vclock_mode) && + if (!gtod_is_based_on_tsc(kvm_host_vclock_mode) && atomic_read(&kvm_guest_has_master_clock) !=3D 0) irq_work_queue(&pvclock_irq_work); return 0; --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420570; b=NoNxxNYHJeXU9irhGDFtEshJkwHeHxFxRT8xC/xwifmt7aewPPK233/ms8WICoHMLtCR hmbiRZynIxnDsCivgDHoWwLWczUGgfraQv2unuEckBLbcQBXiVbJYf/vPg8L5d26OiNSq DaTNXSQQQLteuhBVC1FhvOEEf7szagv2rm8GTCG/ZzTzO03OuTb1+5M7Oblc2KK/B2QC0 DAMjlaGflP2t/UbfqG0/SgqezNL/FF8lxbFKsBY+z7/J7Fkj+l7dpCV5QRhhyS46Q4P86 4lJjyHM7vNa6dlV682M7NdU8yOC0MOpa2tcst7F8Ta4ltM+s3ny1nOFk5XliWFh2Ipg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420570; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=c7IHUPvn0FTv4nhZrlIYskcq6KzbA1Y3PUHGVTFDTII=; b=e32yKrfoS/CtFEWISk8iHs2ga86CtsUTWMXb6HpaX3TlmqTI5HLd+OTEQk3y2GmTMpsY GRUK7JOzWJypkD8VO3VkMsTV8sZ1lM4rpPTA2QazMK16QM7KRS6zFUl1dl2M6JSg3bNwb 0dZoExOCZlS4VPx5KPAod1bsIwJpybyB/CRlTgMNQmwgC5Y3hUtOmr0C4y1XTGnFJ8L2O +grxMOV+/iNXMh4hBpd1oFcsO1W3NDzD3+4ktCadjJIglpNUVbS2Ar+ND6yQIAGZYkEs+ dNB8ewdLfuaTxYzjCrUpVAIlCqvGxKDNPuFCW8nta8ehUgzEXFxBWHizIAYCRc8bTyw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b="W/Kqrfs9"; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E4763606A321; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E4763606A321 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=W/Kqrfs9 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From: Reply-To:Content-Type:Content-ID:Content-Description; bh=c7IHUPvn0FTv4nhZrlIYskcq6KzbA1Y3PUHGVTFDTII=; b=W/Kqrfs9FVuwmhDDBSfI5xq9nL apeIKqR4cGBVdji2JSe0HO2czujbhfwt7nveDrRewLK0txz7G8hX55QRDP9MDJZac8mkgOl7oDQi1 QJoGLbLOQJAhnveFvuBNg5PUTE2cjnIaDStpChL0f7xJO36OM/jEfVcnTBQ4OymblQN2ZYLRx4a1W po686OGJGScsBQXWsoEwFRURJZMf9Xe6OLPHNi1gOhve/RCbmus/kcYZnpLPzKSKYVmUEio+8nBkQ 585LTUxUmEHjcE+R0TvwMMCwPLhxXfbyVX7cKOj81QkSYIQHgcRvQSe0ys6cn8GA+5qHe6j2CTbBJ SJtlEeeg==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvc-1ynj; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsm-181T; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 12/26] KVM: x86: Remove pvclock_gtod_data and private timekeeping code Date: Wed, 11 Nov 2026 10:09:08 -0800 Message-ID: <20261111180922.4177927-13-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html Content-Type: text/plain; charset="utf-8" From: David Woodhouse Remove the now-unused KVM-private timekeeping infrastructure: - struct pvclock_clock and struct pvclock_gtod_data - update_pvclock_gtod() and its seqcount-protected state copy (the private readers were already removed when their last callers went away) Signed-off-by: David Woodhouse --- arch/x86/kvm/x86.c | 56 ---------------------------------------------- 1 file changed, 56 deletions(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index f7dd4129dc51..bd82c9b38233 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -889,60 +889,6 @@ static inline bool kvm_vcpu_exit_request(struct kvm_vc= pu *vcpu) kvm_request_pending(vcpu) || xfer_to_guest_mode_work_pending(); } =20 -#ifdef CONFIG_X86_64 -struct pvclock_clock { - int vclock_mode; - u64 cycle_last; - u64 mask; - u32 mult; - u32 shift; - u64 base_cycles; - u64 offset; -}; - -struct pvclock_gtod_data { - seqcount_t seq; - - struct pvclock_clock clock; /* extract of a clocksource struct */ - struct pvclock_clock raw_clock; /* extract of a clocksource struct */ - - ktime_t offs_boot; - u64 wall_time_sec; -}; - -static struct pvclock_gtod_data pvclock_gtod_data; - -static void update_pvclock_gtod(struct timekeeper *tk) -{ - struct pvclock_gtod_data *vdata =3D &pvclock_gtod_data; - - write_seqcount_begin(&vdata->seq); - - /* copy pvclock gtod data */ - vdata->clock.vclock_mode =3D tk->tkr_mono.clock->vdso_clock_mode; - vdata->clock.cycle_last =3D tk->tkr_mono.cycle_last; - vdata->clock.mask =3D tk->tkr_mono.mask; - vdata->clock.mult =3D tk->tkr_mono.mult; - vdata->clock.shift =3D tk->tkr_mono.shift; - vdata->clock.base_cycles =3D tk->tkr_mono.xtime_nsec; - vdata->clock.offset =3D tk->tkr_mono.base; - - vdata->raw_clock.vclock_mode =3D tk->tkr_raw.clock->vdso_clock_mode; - vdata->raw_clock.cycle_last =3D tk->tkr_raw.cycle_last; - vdata->raw_clock.mask =3D tk->tkr_raw.mask; - vdata->raw_clock.mult =3D tk->tkr_raw.mult; - vdata->raw_clock.shift =3D tk->tkr_raw.shift; - vdata->raw_clock.base_cycles =3D tk->tkr_raw.xtime_nsec; - vdata->raw_clock.offset =3D tk->tkr_raw.base; - - vdata->wall_time_sec =3D tk->xtime_sec; - - vdata->offs_boot =3D tk->offs_boot; - - write_seqcount_end(&vdata->seq); -} -#endif - static s64 get_kvmclock_base_ns(void) { /* Count up from boot time, but with the frequency of the raw clock. */ @@ -7455,8 +7401,6 @@ static int pvclock_gtod_notify(struct notifier_block = *nb, unsigned long unused, { struct timekeeper *tk =3D priv; =20 - update_pvclock_gtod(tk); - /* * Pairs with the READ_ONCE() in the lockless readers; the race is * benign by design, relying on eventual consistency (the notifier --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=IpAccqjoqOYTx0qjgLVOZ9MOZtiAkwSxeYSbduBVMiasPdrHoBJrCrFWUFtm2QMZ2Gf/ eLOgHJEgziVuOw0ZryMRAT3QifRb1VafNeki8oha+Pj6xhrMOI2CQMyv9cbq8ZU7eZDK3 Q1jK38exolqW5fuoSx+bcK0kd3YopapLrH61GDOCuSEGjwbbGEf+4JId5h2W6H+1+SE2z KA7vvsVWqrMKnVoLrCIibQh1qcbpz55uRdHWd0lEhNL4xO3IMSf+2T+c93aYcQYCWfMuU CcYy3TGkv0fLa9iIb3NrZldGRO1Wekp4HeqIjducw00BK8r+aJvvRpBXw8uOXLQvgEQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=v6POo5WP+PNPDJb/ry79fmZWrQ0aM5wkY7uHVd2gmJo=; b=Yxqt/JMItK/3dCqO4i3DB5IeinxOkt0UE091NfdQTrvTopp5dZVKvimvXWrgfXTeloxY OZh09z7VcCgwokOXDZsnEfhBSDmwF/taAT7sD9sJiDlTEXS534CSJOrCcE9dcSValaZ8G lRyIKJIeEmfd1K8lCiHN6/z7Iek/15GjKM/hG+0XjZvDN1FFKNMlrx7BNGXU5AAoKrxpn ExrRlpRpIABQCbWX2jn6pih0viId/i/6TFe/yLfQ0F8CYF3XlTZz2Uu01ub9TBRfLflfm O05fGraaBO57T4KObQhH7Bb9ke31lJZafe+iYwH8Wg1gznPHCmHAtLLdJRi5/5lYC0A== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b="P/tBGnHf"; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E47D7606A327; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E47D7606A327 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=P/tBGnHf DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=v6POo5WP+PNPDJb/ry79fmZWrQ0aM5wkY7uHVd2gmJo=; b=P/tBGnHfKF5svGir+qjlztjv1z CyFpjRo5H3HjKmEWpG82+3UzHoPSVY/1uMpZxL3aLO54K8crHgo+wi3+I/2bUWUEnTC5UDLs7WAi2 la5cRCVMVm3Ij1csHPPX82Oq7sdJP1BhDBvGAH/4BH7f2/lLp16Ju4i0sYgPwXTISUCsTLi97O4qi 2IlVffMwxE+GcptAjNKEs5JXsM5Q41kDbLdk0FJW1lEr41k/e+RJgFWCnuwxo7ZPHi4w0js7BFnIT C1XNqCU8q3hrQWICjJWiHoJRpT3i+5eF+TX+Nm5ZdBP3hnTycBrrqnz4nA/WisGE8gyWKAE9E4gWR U0DFDiBQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvd-28xR; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsq-1JLC; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 13/26] KVM: x86: Keep the master clock trustworthy while the VM has no vCPUs Date: Wed, 11 Nov 2026 10:09:09 -0800 Message-ID: <20261111180922.4177927-14-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse The master clock snapshot is taken at VM creation and, now that it no longer requires matched vCPU TSCs, is active from that moment: KVM_GET_CLOCK returns valid {host_tsc, realtime} fields before any vCPU is created, as will KVM_[GS]ET_CLOCK_GUEST later in this series. But nothing yet defends that snapshot through the window in which the VM has no vCPUs. Sample kvmclock_offset inside the tsc_write_lock section, immediately adjacent to the snapshot it will forever be combined with, so the kvmclock epoch is anchored to the same instant rather than to some earlier point the task was preempted at. No TSC generation is established at VM creation: cur_tsc_khz stays zero, which no vCPU frequency ever equals, so the first vCPU opens its own generation with its TSC starting at zero, as it always has. A matchable VM-creation generation would be a silent guest-visible change (a first-vCPU TSC equal to the host cycles elapsed since KVM_CREATE_VM), and would hand the first vCPU a stale offset when a host suspend resets the TSC before any vCPU exists =E2=80=94 the backwards-= TSC compensation detects the reset only through existing vCPUs. The same no-vCPU suspend window can leave the snapshot itself stale: nothing refreshes it (pvclock_gtod_update_fn() also iterates vCPUs), and the post-reset host TSC may read below master_cycle_now, underflowing the delta, or above it, silently dropping the sleep period. Make __get_kvmclock_master_clock() fall back to the raw clock when the snapshot disagrees with it by more than a second =E2=80=94 both si= des computed from one coherent {ns, TSC} sample, so a reader preempted mid-ioctl cannot fake a discrepancy =E2=80=94 but only while the VM still h= as no vCPUs: the raw clock's and the masterclock's multipliers quantize the frequency ~0.1ppm apart, which would trip the threshold after a few months of an undisturbed snapshot and make the host-side clock jump while the guest's pvclock sails on. Finally, make the masterclock refresh in kvm_arch_vcpu_postcreate() unconditional and synchronous for the first vCPU, so the snapshot is valid even for userspace which queries the clock before ever running a vCPU: a clocksource change notifies only VMs with vCPUs, and a change back to TSC leaves nothing to disagree with the stale snapshot. The same call services a KVM_REQ_MASTERCLOCK_UPDATE raised by any later vCPU's postcreate synchronization, which would otherwise wait until that vCPU first entered the guest. Signed-off-by: David Woodhouse --- arch/x86/kvm/x86.c | 120 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 103 insertions(+), 17 deletions(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index bd82c9b38233..743da71cd84d 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1716,6 +1716,14 @@ static void __kvm_synchronize_tsc_at(struct kvm_vcpu= *vcpu, u64 *value, else data =3D kvm->arch.cur_tsc_write + elapsed_cycles; =20 + /* + * The generation's offset can be reused directly: it is in + * this vCPU's scaling domain, because every generation is + * opened by a vCPU (the initial VM-creation generation is + * not matchable) and set_tsc_khz() derives the scaling + * ratio deterministically from the kHz value, so two vCPUs + * at the same frequency carry the same ratio. + */ if (!kvm_check_tsc_unstable()) offset =3D kvm->arch.cur_tsc_offset; else @@ -2107,6 +2115,7 @@ static bool __get_kvmclock_master_clock(struct kvm *k= vm, struct kvm_arch *ka =3D &kvm->arch; struct pvclock_vcpu_time_info hv_clock; struct timespec64 ts; + u64 clock; =20 if (!ka->use_master_clock) return false; @@ -2114,10 +2123,6 @@ static bool __get_kvmclock_master_clock(struct kvm *= kvm, if (!kvm_get_walltime_and_clockread(&ts, &data->host_tsc)) return false; =20 - data->realtime =3D ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec; - data->flags |=3D KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC | - KVM_CLOCK_TSC_STABLE; - hv_clock.tsc_timestamp =3D ka->master_cycle_now; hv_clock.system_time =3D ka->master_kernel_ns + ka->kvmclock_offset; =20 @@ -2132,13 +2137,63 @@ static bool __get_kvmclock_master_clock(struct kvm = *kvm, u64 tsc_delta =3D data->host_tsc - ka->master_cycle_now; =20 tsc_delta =3D kvm_scale_tsc(tsc_delta, ka->master_tsc_scaling_ratio); - data->clock =3D hv_clock.system_time + - pvclock_scale_delta(tsc_delta, - hv_clock.tsc_to_system_mul, - hv_clock.tsc_shift); + clock =3D hv_clock.system_time + + pvclock_scale_delta(tsc_delta, + hv_clock.tsc_to_system_mul, + hv_clock.tsc_shift); } else { - data->clock =3D __pvclock_read_cycles(&hv_clock, data->host_tsc); + clock =3D __pvclock_read_cycles(&hv_clock, data->host_tsc); + } + + /* + * While the VM has no vCPUs, nothing can refresh the snapshot + * after a host suspend resets the TSC (both the resume + * compensation and the clocksource notifier work through vCPUs), + * and firmware may re-init the TSC to an arbitrary value =E2=80=94 + * including one below master_cycle_now, which would underflow the + * delta. Sanity-check the snapshot against the raw clock in that + * window, and use the fallback clock rather than return a + * discontinuity flagged KVM_CLOCK_TSC_STABLE. Both sides of the + * comparison derive from one coherent {ns, TSC} sample, so a + * preempted reader cannot fake a discrepancy. (A reader racing + * the first vCPU's creation can see online_vcpus already raised + * before the postcreate refresh has run and skip the check + * against a still-stale snapshot; that narrow window existed in + * full before the check did.) Once vCPUs exist + * the check must not run: the raw clock's and the masterclock's + * multipliers quantize the frequency differently, drifting apart + * by ~0.1ppm, which would trip a 1-second threshold after a few + * months of an undisturbed snapshot and make the host-side clock + * jump while the guest's pvclock sails on. A VM genuinely parked + * with no vCPUs for those months serves the fallback clock from + * then on =E2=80=94 the conservative direction for a snapshot that old. + */ + if (unlikely(!atomic_read(&kvm->online_vcpus))) { + u64 chk_tsc, delta; + s64 chk_ns, diff; + + if (!kvm_get_time_and_clockread(&chk_ns, &chk_tsc)) + return false; + + delta =3D chk_tsc - ka->master_cycle_now; + if (kvm_caps.has_tsc_control) + delta =3D kvm_scale_tsc(delta, + ka->master_tsc_scaling_ratio); + /* + * Two-sided compare rather than abs(): abs(S64_MIN) is + * S64_MIN again, which would fail open on that one value. + */ + diff =3D (s64)pvclock_scale_delta(delta, ka->master_tsc_mul, + ka->master_tsc_shift) - + (s64)(chk_ns - ka->master_kernel_ns); + if (diff > (s64)NSEC_PER_SEC || diff < -(s64)NSEC_PER_SEC) + return false; } + + data->clock =3D clock; + data->realtime =3D ts.tv_nsec + NSEC_PER_SEC * ts.tv_sec; + data->flags |=3D KVM_CLOCK_REALTIME | KVM_CLOCK_HOST_TSC | + KVM_CLOCK_TSC_STABLE; return true; #else return false; @@ -10039,8 +10094,19 @@ void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcp= u) } vcpu_load(vcpu); kvm_synchronize_tsc(vcpu, NULL, false); - if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu)) + + /* + * Refresh the VM-creation masterclock snapshot (see + * kvm_arch_init_vm), synchronously so that it is valid even for + * userspace which queries the clock before ever running a vCPU. + * Likewise service any masterclock update the synchronization + * above requested on this vCPU, which would otherwise languish + * until it first enters the guest. + */ + if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu) || + vcpu->vcpu_idx =3D=3D 0) kvm_update_masterclock(vcpu->kvm, NULL); + vcpu_put(vcpu); =20 /* poll control enabled by default */ @@ -10510,9 +10576,13 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned lon= g type) seqcount_raw_spinlock_init(&kvm->arch.pvclock_sc, &kvm->arch.tsc_write_lo= ck); ratelimit_state_init(&kvm->arch.kvmclock_update_rs, HZ, 10); ratelimit_set_flags(&kvm->arch.kvmclock_update_rs, RATELIMIT_MSG_ON_RELEA= SE); - kvm->arch.kvmclock_offset =3D -get_kvmclock_base_ns(); - kvm->arch.all_vcpus_matched_freq =3D true; =20 + kvm->arch.default_tsc_khz =3D max_tsc_khz ? : tsc_khz; + kvm->arch.apic_bus_cycle_ns =3D APIC_BUS_CYCLE_NS_DEFAULT; + kvm->arch.guest_can_read_msr_platform_info =3D true; + kvm->arch.enable_pmu =3D enable_pmu && !kvm->arch.has_protected_pmu; + + kvm->arch.all_vcpus_matched_freq =3D true; /* * Start with all (zero) vCPUs considered matched, so that a VM whose * vCPUs never reach kvm_track_tsc_matching() =E2=80=94 notably when the = guest @@ -10529,14 +10599,30 @@ int kvm_arch_init_vm(struct kvm *kvm, unsigned lo= ng type) kvm->arch.cur_tsc_scaling_ratio =3D kvm_caps.default_tsc_scaling_ratio; =20 raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); + + /* + * Take the master clock snapshot now, so that KVM_GET_CLOCK works + * before any vCPU exists. It is refreshed again when the first + * vCPU is created, in case the host clocksource changed (and + * changed back) in between: pvclock_gtod_update_fn() does not + * notify a VM with no vCPUs. + * + * No TSC generation is established here: cur_tsc_khz stays zero, + * which no vCPU frequency ever equals, so the first vCPU opens + * its own generation with its TSC starting at zero, exactly as + * it always has. Letting it match a VM-creation generation would + * make the first vCPU's TSC start at the cycles elapsed since + * KVM_CREATE_VM =E2=80=94 a silent guest-visible change over an unbounded + * window =E2=80=94 and would hand it a stale offset when a host suspend + * reset the TSC in between, since the backwards-TSC compensation + * in kvm_arch_enable_virtualization_cpu() detects the jump only + * through existing vCPUs. + */ + kvm->arch.kvmclock_offset =3D -get_kvmclock_base_ns(); + pvclock_update_vm_gtod_copy(kvm); raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags); =20 - kvm->arch.default_tsc_khz =3D max_tsc_khz ? : tsc_khz; - kvm->arch.apic_bus_cycle_ns =3D APIC_BUS_CYCLE_NS_DEFAULT; - kvm->arch.guest_can_read_msr_platform_info =3D true; - kvm->arch.enable_pmu =3D enable_pmu && !kvm->arch.has_protected_pmu; - #if IS_ENABLED(CONFIG_HYPERV) spin_lock_init(&kvm->arch.hv_root_tdp_lock); kvm->arch.hv_root_tdp =3D INVALID_PAGE; --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=aQ6iChLkdODW0T2c1TzkkXTrkDL1sqK1E7GXQYOW7H0qMZCsXnYN2/l2O635ZiExjGpA ri6c+cRnWGm0sZDFwQK60giXsXeA0cuxB1k/ExxfGjTWxkHDxtKrEid/TZINKOJ0waa2D xGuKO1PvRB8fpCzyEjGwvGyVXMulgBHHtHV7ZULu8q/Jkth8FdQvpjVkH2pTtZhcLl8lH g9mt9aKWHs3zTGjcsbkb00lCIYzfONs+XE9HIKT09MLaLAoOtqKSSpcFrU77jEpNtmMG1 FdHjiVJCA8yt/5ivKkIEFhMGNNhZjKTKxEauVxWwCoQUczOk6kvv2p6TUC9gb9t0eBg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=mKH9BxiVhD1hkWOxu0QRNvIl232YhI8uqiNY5R0UwSo=; b=YpjUzCZQ3VI10D90AEon3vB47/3QnDT7O7Dg9nFSq1U92sUKPm3gXtDWT5hPc3MzZWbP 6VRwpOIRWWvAE+RBT119Feth1syBxobwCwWZsv4Ovevy7rNTD7b+hfJsG+CB+z/FLH+X7 7/6kZ4sVr8ks3/4xN64zY+2p0uNww2XhoTYFLCLSaEbi6r3Piw/zFVgtbL3JxzAvOtRzJ DyYHsoRWDPcCjF+AYXw979DYX+tMS9SzkNOzxwil1PvuhDHtVrh2oh7giiu/R2dqo4Vcv EEKBxyEeQfBxYVNiZTybWI2ocOAno6hlLDJPDkJW4XmzzxCt3YYPO/Gxs//vKSvTnhw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=fgVrUACa; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E575A606A32D; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E575A606A32D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=fgVrUACa DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From: Reply-To:Content-Type:Content-ID:Content-Description; bh=mKH9BxiVhD1hkWOxu0QRNvIl232YhI8uqiNY5R0UwSo=; b=fgVrUACaSLph0J26X6E/7/ickG K3hS2UAraMzNHVHR2xkmPOrKX5AWdkNZ7oeNDrtt6pCdiGRLupJwii0llUquynMXlz8ehO5gqHKZ/ LlusvvLB8cDDCGYWPA97DJuDxBDNgikoDSBuosnQOTWifs5oXmIBM4b574rSa0FqdIhcYpcTVN825 ff9cnbKHI+kdyVlzabIpLVrfUWJb4D6fKPlbkHhJ8f5fQeRT6XvfdXbg5S0HzJAYhQMN6+0qRsonE tIfL4thRfwH/L2EDJolKRkyypzcIDGzsXVywbP/wFBejG/rKp13lKdeQYqbPkG/4K98Cob01nZEcY OMkEqRyQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKvf-2M2F; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsu-1UOe; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 14/26] UAPI: x86: Move pvclock-abi to UAPI for x86 platforms Date: Wed, 11 Nov 2026 10:09:10 -0800 Message-ID: <20261111180922.4177927-15-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html Content-Type: text/plain; charset="utf-8" From: Jack Allister A subsequent commit will provide a new KVM interface for performing a fixup/correction of the KVM clock against the reference TSC. The KVM_[GS]ET_CLOCK_GUEST API requires a pvclock_vcpu_time_info, as such the caller must know about this definition. Move the definition to the UAPI folder so that it is exported to usermode, change the type definitions to use the standard for UAPI exports, and add the Linux-syscall-note exception to the SPDX licence identifier as is conventional for exported headers. Define __KERNEL__ in scripts/xen-hypercalls.sh: the UAPI header now pulls in linux/types.h, and the script's raw $CPP invocation with $LINUXINCLUDE does not define it, which would trigger the "attempt to use kernel headers from user space" warning from the UAPI type headers. Signed-off-by: Jack Allister Signed-off-by: David Woodhouse Reviewed-by: Paul Durrant Tested-by: Dongli Zhang --- MAINTAINERS | 4 +-- arch/x86/include/{ =3D> uapi}/asm/pvclock-abi.h | 27 ++++++++++--------- scripts/xen-hypercalls.sh | 2 +- 3 files changed, 18 insertions(+), 15 deletions(-) rename arch/x86/include/{ =3D> uapi}/asm/pvclock-abi.h (82%) diff --git a/MAINTAINERS b/MAINTAINERS index 9fadc98d3c49..773f7c800f6a 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -14663,8 +14663,8 @@ S: Supported T: git git://git.kernel.org/pub/scm/virt/kvm/kvm.git F: arch/um/include/asm/kvm_para.h F: arch/x86/include/asm/kvm_para.h -F: arch/x86/include/asm/pvclock-abi.h F: arch/x86/include/uapi/asm/kvm_para.h +F: arch/x86/include/uapi/asm/pvclock-abi.h F: arch/x86/kernel/kvm.c F: arch/x86/kernel/kvmclock.c F: include/asm-generic/kvm_para.h @@ -29780,8 +29780,8 @@ R: Boris Ostrovsky L: xen-devel@lists.xenproject.org (moderated for non-subscribers) S: Supported F: arch/x86/configs/xen.config -F: arch/x86/include/asm/pvclock-abi.h F: arch/x86/include/asm/xen/ +F: arch/x86/include/uapi/asm/pvclock-abi.h F: arch/x86/platform/pvh/ F: arch/x86/xen/ =20 diff --git a/arch/x86/include/asm/pvclock-abi.h b/arch/x86/include/uapi/asm= /pvclock-abi.h similarity index 82% rename from arch/x86/include/asm/pvclock-abi.h rename to arch/x86/include/uapi/asm/pvclock-abi.h index b9fece5fc96d..6d70cf640362 100644 --- a/arch/x86/include/asm/pvclock-abi.h +++ b/arch/x86/include/uapi/asm/pvclock-abi.h @@ -1,6 +1,9 @@ -/* SPDX-License-Identifier: GPL-2.0 */ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _ASM_X86_PVCLOCK_ABI_H #define _ASM_X86_PVCLOCK_ABI_H + +#include + #ifndef __ASSEMBLER__ =20 /* @@ -24,20 +27,20 @@ */ =20 struct pvclock_vcpu_time_info { - u32 version; - u32 pad0; - u64 tsc_timestamp; - u64 system_time; - u32 tsc_to_system_mul; - s8 tsc_shift; - u8 flags; - u8 pad[2]; + __u32 version; + __u32 pad0; + __u64 tsc_timestamp; + __u64 system_time; + __u32 tsc_to_system_mul; + __s8 tsc_shift; + __u8 flags; + __u8 pad[2]; } __attribute__((__packed__)); /* 32 bytes */ =20 struct pvclock_wall_clock { - u32 version; - u32 sec; - u32 nsec; + __u32 version; + __u32 sec; + __u32 nsec; } __attribute__((__packed__)); =20 #define PVCLOCK_TSC_STABLE_BIT (1 << 0) diff --git a/scripts/xen-hypercalls.sh b/scripts/xen-hypercalls.sh index f18b00843df3..51a722198997 100755 --- a/scripts/xen-hypercalls.sh +++ b/scripts/xen-hypercalls.sh @@ -5,7 +5,7 @@ shift in=3D"$@" =20 for i in $in; do - eval $CPP $LINUXINCLUDE -dD -imacros "$i" -x c /dev/null + eval $CPP -D__KERNEL__ $LINUXINCLUDE -dD -imacros "$i" -x c /dev/null done | \ awk '$1 =3D=3D "#define" && $2 ~ /__HYPERVISOR_[a-z][a-z_0-9]*/ { v[$3] = =3D $2 } END { print "/* auto-generated by scripts/xen-hypercall.sh */" --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420579; b=TwNdNS8yCSqfCDMfcgN3jVpGRPEBVwIxaoaTJMxiXNuB8Xl/suKD7sRaQhCzfe8XQ5FJ 7VshseTH5yZobZWxf3DD6x7S0aoiz641QUSp26GS56o8d52W8PZ011rqzx88FsJmUHLwg AHBrCf54MiQeo6Io63tFCHET2OieW61/PMU8HUIoPlAoISgFUjfEkevYu7CQDX+gD4gQz YHf5y11ysbBUtpTF+7MBhZ+mZS64DJJtT9sU+KGbTkPaYMVKsAS+7G7iIQYMA4n4rh9GR Hkyan4G5cAI+ySP6OVYOlU1m6JpTcNU8KgcEA9SyjTjMr3aCRuyjLxEVFf418VzGNbw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420579; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=l4f9wq8L35XMCLh4CbxRCOQU8IQcsqUENU27urpKImE=; b=E+5THTOiGA+ICIr8Wc5CwhTQGPLgOYYcUb09B+TukuaI8C0xSCdqDfVZGSWNjmLKeUf1 pD/WyQtHbqz9e2HhelKGml4OqAlPqlsYFQOmaRq6zQCLeGdDy2HXe6fuFY5kAAXhZOWMF bQL8WqmnQo/UB4u5M3unN5I5HdVPNWpZw7HpxZ6j5TTRJcdsrOrEvKc1MWNv4a6Mq7CLf y0vTcC40yBjQ++7tPfVZH7RkUw6f3MMD81yPN4w1+5WsztpYgTVgJn1w9Nd2Rqj9xPVxw cK6U4fG/YWSbDqLHPBY4aboaU4CCWkc53N94mQlAx8QNTCZpdXCONGddpx/pzDhrg4Q== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=MLIRKEfJ; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3678D606B783; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 3678D606B783 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=MLIRKEfJ DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=l4f9wq8L35XMCLh4CbxRCOQU8IQcsqUENU27urpKImE=; b=MLIRKEfJnxB1TwIx2VDrYem/wp undiT0kHlpJcWxk+VWy2xCYVhkMIsyIMAeWxh24FBhEBIu2lMKywZKPnja1HKQSXwF/Y33gO6kyca WXlwL0Kq2DLQPV/YG9oI+XBli/8o+pL1qjq1pTy1CmTH1iYC0IiV8Zcz79IA+SV/tj3zrJ9ojvvxa PUzzewE/ObZUtcPnZG40e4AA81blUuHAGumU2yxf6eF8IZ+s5UHRJdfcL2I6cFeWkUEYjKHpN8e3w d4pr64l14Bkg9YAmgovORiUwuas//gC12prVUdRMYaY0yYL5Etlf5fdNVQsB1r/o/fwcngzj45wP1 /sMvnE6w==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvP-3E2k; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWsz-1fIP; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 15/26] KVM: selftests: Use UAPI pvclock-abi.h in xen_shinfo_test Date: Wed, 11 Nov 2026 10:09:11 -0800 Message-ID: <20261111180922.4177927-16-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Now that pvclock-abi.h is a UAPI header, use it in xen_shinfo_test.c instead of locally duplicating the struct definitions. Drop the tools/ mirror of the header: with the kernel copy now UAPI, the selftests resolve from the installed kernel headers, which they already depend on, and nothing else in tools/ builds against the mirror =E2=80=94 keeping it would only be a file for check-headers.sh to police with no consumer. The UAPI struct fields are __u64 (unsigned long long), so switch the verbose printfs away from PRIu64, which is "lu" on 64-bit. Signed-off-by: David Woodhouse --- tools/arch/x86/include/asm/pvclock-abi.h | 48 ------------------- .../selftests/kvm/x86/xen_shinfo_test.c | 33 ++++--------- 2 files changed, 10 insertions(+), 71 deletions(-) delete mode 100644 tools/arch/x86/include/asm/pvclock-abi.h diff --git a/tools/arch/x86/include/asm/pvclock-abi.h b/tools/arch/x86/incl= ude/asm/pvclock-abi.h deleted file mode 100644 index b9fece5fc96d..000000000000 --- a/tools/arch/x86/include/asm/pvclock-abi.h +++ /dev/null @@ -1,48 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef _ASM_X86_PVCLOCK_ABI_H -#define _ASM_X86_PVCLOCK_ABI_H -#ifndef __ASSEMBLER__ - -/* - * These structs MUST NOT be changed. - * They are the ABI between hypervisor and guest OS. - * Both Xen and KVM are using this. - * - * pvclock_vcpu_time_info holds the system time and the tsc timestamp - * of the last update. So the guest can use the tsc delta to get a - * more precise system time. There is one per virtual cpu. - * - * pvclock_wall_clock references the point in time when the system - * time was zero (usually boot time), thus the guest calculates the - * current wall clock by adding the system time. - * - * Protocol for the "version" fields is: hypervisor raises it (making - * it uneven) before it starts updating the fields and raises it again - * (making it even) when it is done. Thus the guest can make sure the - * time values it got are consistent by checking the version before - * and after reading them. - */ - -struct pvclock_vcpu_time_info { - u32 version; - u32 pad0; - u64 tsc_timestamp; - u64 system_time; - u32 tsc_to_system_mul; - s8 tsc_shift; - u8 flags; - u8 pad[2]; -} __attribute__((__packed__)); /* 32 bytes */ - -struct pvclock_wall_clock { - u32 version; - u32 sec; - u32 nsec; -} __attribute__((__packed__)); - -#define PVCLOCK_TSC_STABLE_BIT (1 << 0) -#define PVCLOCK_GUEST_STOPPED (1 << 1) -/* PVCLOCK_COUNTS_FROM_ZERO broke ABI and can't be used anymore. */ -#define PVCLOCK_COUNTS_FROM_ZERO (1 << 2) -#endif /* __ASSEMBLER__ */ -#endif /* _ASM_X86_PVCLOCK_ABI_H */ diff --git a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c b/tools/test= ing/selftests/kvm/x86/xen_shinfo_test.c index aaa414c677ad..9045f03cf2d3 100644 --- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c +++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c @@ -15,6 +15,8 @@ =20 #include =20 +#include + #define SHINFO_REGION_GVA 0xc0000000ULL #define SHINFO_REGION_GPA 0xc0000000ULL #define SHINFO_REGION_SLOT 10 @@ -98,23 +100,6 @@ struct sched_poll { u64 timeout; }; =20 -struct pvclock_vcpu_time_info { - u32 version; - u32 pad0; - u64 tsc_timestamp; - u64 system_time; - u32 tsc_to_system_mul; - s8 tsc_shift; - u8 flags; - u8 pad[2]; -} __attribute__((__packed__)); /* 32 bytes */ - -struct pvclock_wall_clock { - u32 version; - u32 sec; - u32 nsec; -} __attribute__((__packed__)); - struct vcpu_runstate_info { u32 state; u64 state_entry_time; @@ -987,12 +972,14 @@ int main(int argc, char *argv[]) =20 if (verbose) { printf("Wall clock (v %d) %d.%09d\n", wc->version, wc->sec, wc->nsec); - printf("Time info 1: v %u tsc %" PRIu64 " time %" PRIu64 " mul %u shift = %u flags %x\n", - ti->version, ti->tsc_timestamp, ti->system_time, ti->tsc_to_syste= m_mul, - ti->tsc_shift, ti->flags); - printf("Time info 2: v %u tsc %" PRIu64 " time %" PRIu64 " mul %u shift = %u flags %x\n", - ti2->version, ti2->tsc_timestamp, ti2->system_time, ti2->tsc_to_s= ystem_mul, - ti2->tsc_shift, ti2->flags); + printf("Time info 1: v %u tsc %llu time %llu mul %u shift %d flags %x\n", + ti->version, (unsigned long long)ti->tsc_timestamp, + (unsigned long long)ti->system_time, + ti->tsc_to_system_mul, ti->tsc_shift, ti->flags); + printf("Time info 2: v %u tsc %llu time %llu mul %u shift %d flags %x\n", + ti2->version, (unsigned long long)ti2->tsc_timestamp, + (unsigned long long)ti2->system_time, + ti2->tsc_to_system_mul, ti2->tsc_shift, ti2->flags); } =20 TEST_ASSERT(wc->version && !(wc->version & 1), --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=knmIpMPBKl4RFiKpZZ6TUhlR/9L7UYgijWt6dmUiHsVI9OYhTQ5Jqpwzig/IOG8mDYni paHesJdBQcv1zRPI/EVUP/8F2eogesWSKQEGk8NuIhq8+NCqd5Vn6oXQsZLLfNob3fyub g0mjQE5vod80seqq8w1wdOPzUJbEBM3oH8Zxq4ppskVbn02vyu7G/5BkMHyCaK/sq9UkR UP8S1p9eBJOLM1I6ZHksy/uJzsRTWnFYROW7c/AtxFFMAyUdJWbQjpQwS7wJ5fjKWc6Ot vtI8OBodO3+WP/3ICL1TynJJSCbolrvNV7xRAl78VobqIVrxw2rnhVwYla9ZZeEtqhQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=5G4dkMkeeEEES1E20oyB/QGve810jrImqh7f4e8JtX4=; b=BTR88jEYWJ2xU8YiztzzcPYjvQFQThxguaR04GfC8j4PdQsYd5BFIvV9PoY/FXU3ZSX9 2FiFNTptiB0SrA/pFpIqDuGZ/VkH6+0tsPViR9HY21k4veQaPRQe9XnMkPVX5ghMotciG Z/ywXPcfKmSOpNy0VBM19/OE8/lzalMQeb1pHqeDKqXPaA6fgHpQcHKc2n9djOPunL1tL Wjfkpmdb7I2zohT1qONAOczAqjl7gU51ESfnKUkTuD/VtEq4NONx6y6xFdDpjHa4hnyan +epmEfShjQw4w7e5LR8VsnbMw9YNk1Adb1kkrM/HxPWRbzOooBIzdOjeZVRD0itJ/JA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=HHsxjGw8; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 36737606B781; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 36737606B781 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=HHsxjGw8 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=5G4dkMkeeEEES1E20oyB/QGve810jrImqh7f4e8JtX4=; b=HHsxjGw8YuLdboJkLNfoNYypns ZAeCh18TQWY9tIOU1RGqCKQXummhYO+/jFzfSLBuv/6Y5GVh6BYEwGPU3AzVoUXU9KWivJzHYeoqD XRpi1556SnyJS6i/XILeZaDfZKCyPO8tzNYz8I2/QXIZk1X9seZP9UEKgaYSQr8s6qgsp541OjbUg GR5iN7zx4RHaY4lBvkweYVDey8tIdFdr/y/tjleqj5lQx7RASJJXefmAuHIBp1v1DRegjFTdmnXfC b2nJUU/zzstbd8zKNL2oG3799+2aLFlYLWaeVDnLp3BqnPTvdefm6LInlMtUBhx0Cj/hHkkCqRkcB DAK3it5Q==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvQ-3Drr; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWt3-1t6h; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 16/26] KVM: x86: Add KVM_[GS]ET_CLOCK_GUEST for accurate KVM clock migration Date: Wed, 11 Nov 2026 10:09:12 -0800 Message-ID: <20261111180922.4177927-17-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: Jack Allister In the common case (where kvm->arch.use_master_clock is true), the KVM clock is defined as a simple arithmetic function of the guest TSC, based on a reference point stored in kvm->arch.master_kernel_ns and kvm->arch.master_cycle_now. The existing KVM_[GS]ET_CLOCK functionality does not allow for this relationship to be precisely saved and restored by userspace. All it can currently do is set the KVM clock at a given UTC reference time, which is necessarily imprecise. So on live update, the guest TSC can remain cycle accurate at precisely the same offset from the host TSC, but there is no way for userspace to restore the KVM clock accurately. Even on live migration to a new host, where the accuracy of the guest time-keeping is fundamentally limited by the accuracy of wallclock synchronization between the source and destination hosts, the clock jump experienced by the guest's TSC and its KVM clock should at least be *consistent*. Even when the guest TSC suffers a discontinuity, its KVM clock should still remain the *same* arithmetic function of the guest TSC, and not suffer an *additional* discontinuity. To allow for accurate migration of the KVM clock, add per-vCPU ioctls which save and restore the actual PV clock info in pvclock_vcpu_time_info. The restoration in KVM_SET_CLOCK_GUEST works by creating a new reference point in time just as kvm_update_masterclock() does, and calculating the corresponding guest TSC value. This guest TSC value is then passed through the user-provided pvclock structure to generate the *intended* KVM clock value at that point in time, and through the *actual* KVM clock calculation. Then kvm->arch.kvmclock_offset is adjusted to eliminate the difference. Both ioctls return -ENODATA when the KVM clock is not in master clock mode (because the host TSC is unreliable, or the guest TSCs are configured strangely); the KVM clock is then not a function of the guest TSC at all, so userspace shall fall back to the legacy KVM_[GS]ET_CLOCK, whose imprecision is acceptable in a mode which is imprecise anyway. That means sending the results of *both* GET ioctls with the migration data, unless the intent is to refuse to resume on a host with a bad TSC. An unknown TSC frequency on the current CPU (possible only without CONSTANT_TSC) also reads as -ENODATA. The ioctls are advertised with KVM_CAP_CLOCK_GUEST. KVM_GET_CLOCK_GUEST services a masterclock update pending on the vCPU before reading: a backwards host TSC on resume parks the request and leaves the snapshot stale, while vcpu_load() has already applied the offset compensation =E2=80=94 combining the two yields a value whose freque= ncy still matches, which the destination could not reject. Servicing the update makes that case correctly return -ENODATA. The set side validates everything it is given =E2=80=94 padding, version (m= ust be zero), flags (nothing beyond PVCLOCK_TSC_STABLE_BIT) =E2=80=94 so the fi= elds keep meaning for the future, and re-marks the Hyper-V TSC page once the new clock is published, with a consumer queued behind the re-mark, as kvm_update_masterclock() does. Co-developed-by: David Woodhouse Signed-off-by: David Woodhouse Signed-off-by: Jack Allister Reviewed-by: Paul Durrant Cc: Dongli Zhang Tested-by: Dongli Zhang --- Documentation/virt/kvm/api.rst | 56 ++++++++ arch/x86/include/uapi/asm/kvm.h | 1 + arch/x86/kvm/x86.c | 223 ++++++++++++++++++++++++++++++++ include/uapi/linux/kvm.h | 4 + 4 files changed, 284 insertions(+) diff --git a/Documentation/virt/kvm/api.rst b/Documentation/virt/kvm/api.rst index 9487afc4431f..98f5da057b86 100644 --- a/Documentation/virt/kvm/api.rst +++ b/Documentation/virt/kvm/api.rst @@ -6767,6 +6767,62 @@ if the guest_memfd memory was pinned in IOMMU page t= ables. =20 See also: :ref:`KVM_SET_MEMORY_ATTRIBUTES`. =20 +4.147 KVM_GET_CLOCK_GUEST +---------------------------- + +:Capability: KVM_CAP_CLOCK_GUEST +:Architectures: x86_64 +:Type: vcpu ioctl +:Parameters: struct pvclock_vcpu_time_info (out) +:Returns: 0 on success, <0 on error + +Retrieves the current time information structure used for KVM/PV clocks, +in precisely the form advertised to the guest vCPU, which gives parameters +for a direct conversion from a guest TSC value to nanoseconds. + +The structure is in terms of the given vCPU's TSC. It must be passed back +to KVM_SET_CLOCK_GUEST on the *same* vCPU (on the destination VM, for +migration); vCPUs may legitimately have different TSC offsets, which would +otherwise be silently folded into the restored KVM clock. + +When the KVM clock is not in "master clock" mode, for example because the +host TSC is unreliable or the guest TSCs are oddly configured, the KVM clo= ck +is actually defined by the host CLOCK_MONOTONIC_RAW instead of the guest T= SC. +In this case, the KVM_GET_CLOCK_GUEST ioctl returns -ENODATA. + +4.148 KVM_SET_CLOCK_GUEST +---------------------------- + +:Capability: KVM_CAP_CLOCK_GUEST +:Architectures: x86_64 +:Type: vcpu ioctl +:Parameters: struct pvclock_vcpu_time_info (in) +:Returns: 0 on success, <0 on error + +Sets the KVM clock (for the whole VM) in terms of the vCPU TSC, using the +pvclock structure as returned by KVM_GET_CLOCK_GUEST. This allows the prec= ise +arithmetic relationship between guest TSC and KVM clock to be preserved by +userspace across migration. + +When the KVM clock is not in "master clock" mode, and the KVM clock is act= ually +defined by the host CLOCK_MONOTONIC_RAW, this ioctl returns -ENODATA. User= space +may choose to set the clock using the less precise KVM_SET_CLOCK ioctl, or= may +choose to fail, denying migration to a host whose TSC is misbehaving. A ho= st +whose CPU TSC frequency is unknown (only possible without +X86_FEATURE_CONSTANT_TSC) is never in "master clock" mode, so it also retu= rns +-ENODATA. + +If the mul/shift fields of the provided pvclock structure encode a TSC +frequency inconsistent with the vCPU's actual TSC frequency, this ioctl +returns -ERANGE. + +If the vCPU's current TSC is behind the tsc_timestamp in the provided +structure, this ioctl returns -EINVAL. Restore the guest TSC (which the +documented migration procedure keeps monotonic) before invoking it. +The padding fields must be zero, the version field must be zero, and +no flags beyond PVCLOCK_TSC_STABLE_BIT are accepted; anything else +returns -EINVAL. + .. _kvm_run: =20 5. The kvm_run structure diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kv= m.h index 1585ec804066..9e3cdc3adb65 100644 --- a/arch/x86/include/uapi/asm/kvm.h +++ b/arch/x86/include/uapi/asm/kvm.h @@ -12,6 +12,7 @@ #include #include #include +#include =20 #define KVM_PIO_PAGE_OFFSET 1 #define KVM_COALESCED_MMIO_PAGE_OFFSET 2 diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 743da71cd84d..16383c71131d 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -2777,6 +2777,9 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, lon= g ext) case KVM_CAP_MEMORY_FAULT_INFO: case KVM_CAP_X86_GUEST_MODE: case KVM_CAP_ONE_REG: +#ifdef CONFIG_X86_64 + case KVM_CAP_CLOCK_GUEST: +#endif r =3D 1; break; case KVM_CAP_PRE_FAULT_MEMORY: @@ -3941,6 +3944,218 @@ static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcp= u *vcpu, } } =20 +#ifdef CONFIG_X86_64 +static int kvm_vcpu_ioctl_get_clock_guest(struct kvm_vcpu *v, void __user = *argp) +{ + struct pvclock_vcpu_time_info hv_clock =3D {}; + struct kvm_arch *ka =3D &v->kvm->arch; + bool use_master_clock; + unsigned int seq; + + /* + * Construct the pvclock purely from the master clock state. The + * master mul/shift are computed for the guest TSC frequency, which + * in master clock mode is the frequency of every vCPU; only the + * tsc_timestamp is per-vCPU, translating the master snapshot into + * this vCPU's TSC domain via its scaling ratio and offset. + * + * Note, this deliberately does NOT invoke kvm_guest_time_update(), + * which would write the guest's pvclock pages: dirtying guest + * memory after the final KVM_RUN would break post-copy migration + * flows. The pvclock returned here describes the same clock as the + * guest-visible copy (the same linear function of the guest TSC), + * anchored at the current master clock snapshot. + * + * Translating the snapshot through the vCPU's *current* scaling + * ratio and offset is correct even if they changed after the + * snapshot was taken: the snapshot anchors a host TSC value, not + * a guest one. + */ + + /* + * Service a pending masterclock update first. Events like a + * backwards host TSC on resume, or a frequency change, park + * KVM_REQ_MASTERCLOCK_UPDATE on the vCPUs and leave the snapshot + * =E2=80=94 and use_master_clock itself =E2=80=94 stale until a guest en= try. + * vcpu_load() has already applied any pending backwards-TSC + * offset adjustment to this vCPU, and combining that with the + * pre-suspend snapshot would produce a value the destination + * cannot reject: the frequency still matches. + */ + if (kvm_test_request(KVM_REQ_MASTERCLOCK_UPDATE, v)) + kvm_update_masterclock(v->kvm, v); + + do { + seq =3D read_seqcount_begin(&ka->pvclock_sc); + + use_master_clock =3D ka->use_master_clock; + if (!use_master_clock) + continue; + + hv_clock.tsc_timestamp =3D kvm_read_l1_tsc(v, ka->master_cycle_now); + hv_clock.system_time =3D ka->master_kernel_ns + ka->kvmclock_offset; + hv_clock.tsc_shift =3D ka->master_tsc_shift; + hv_clock.tsc_to_system_mul =3D ka->master_tsc_mul; + hv_clock.flags =3D READ_ONCE(ka->all_vcpus_matched_tsc) ? + PVCLOCK_TSC_STABLE_BIT : 0; + } while (read_seqcount_retry(&ka->pvclock_sc, seq)); + + if (!use_master_clock) + return -ENODATA; + + if (copy_to_user(argp, &hv_clock, sizeof(hv_clock))) + return -EFAULT; + + return 0; +} + +/* + * Reverse the calculation in the hv_clock definition. + * + * time_ns =3D ( (cycles << shift) * mul ) >> 32; + * (although shift can be negative, so that's bad C) + * + * So for a single second, + * NSEC_PER_SEC =3D ( ( FREQ_HZ << shift) * mul ) >> 32 + * NSEC_PER_SEC << 32 =3D ( FREQ_HZ << shift ) * mul + * ( NSEC_PER_SEC << 32 ) / mul =3D FREQ_HZ << shift + * ( NSEC_PER_SEC << 32 ) / mul ) >> shift =3D FREQ_HZ + */ +static u64 hvclock_to_hz(u32 mul, s8 shift) +{ + u64 tm =3D NSEC_PER_SEC << 32; + + /* Maximise precision. Shift left until the top bit is set */ + tm <<=3D 2; + shift +=3D 2; + + /* While 'mul' is even, increase the shift *after* the division */ + while (!(mul & 1)) { + shift++; + mul >>=3D 1; + } + + tm /=3D mul; + + if (shift >=3D 64) + return 0; + if (shift > 0) + return tm >> shift; + + /* + * A left shift can overflow for absurd user-supplied mul/shift + * combinations; saturate (to a value which cannot itself overflow + * the rounding in the caller's kHz conversion) so the frequency + * check certainly rejects them. + */ + if (shift <=3D -64 || tm > (U64_MAX >> 1) >> -shift) + return U64_MAX >> 1; + return tm << -shift; +} + +static int kvm_vcpu_ioctl_set_clock_guest(struct kvm_vcpu *v, void __user = *argp) +{ + struct pvclock_vcpu_time_info user_hv_clock; + struct kvm *kvm =3D v->kvm; + struct kvm_arch *ka =3D &kvm->arch; + u64 curr_tsc_hz, user_tsc_hz; + u64 curr_tsc_khz, user_tsc_khz; + u64 user_clk_ns; + u64 guest_tsc; + int rc =3D 0; + + if (copy_from_user(&user_hv_clock, argp, sizeof(user_hv_clock))) + return -EFAULT; + + if (user_hv_clock.pad0 || user_hv_clock.pad[0] || user_hv_clock.pad[1]) + return -EINVAL; + + /* + * KVM_GET_CLOCK_GUEST emits version 0 and at most + * PVCLOCK_TSC_STABLE_BIT; reject anything else now, so the + * fields keep meaning for the future rather than carrying + * whatever garbage old userspace got away with. + */ + if (user_hv_clock.version || + (user_hv_clock.flags & ~PVCLOCK_TSC_STABLE_BIT)) + return -EINVAL; + + if (!user_hv_clock.tsc_to_system_mul) + return -EINVAL; + + if (user_hv_clock.tsc_shift < -31 || user_hv_clock.tsc_shift > 31) + return -EINVAL; + + user_tsc_hz =3D hvclock_to_hz(user_hv_clock.tsc_to_system_mul, + user_hv_clock.tsc_shift); + + kvm_hv_request_tsc_page_update(kvm); + + /* + * kvm_start_pvclock_update() takes tsc_write_lock and opens + * the pvclock seqcount; kvm_end_pvclock_update() closes both. + * All clock state modifications between them are atomic with + * respect to readers in kvm_guest_time_update(). + */ + kvm_start_pvclock_update(kvm); + pvclock_update_vm_gtod_copy(kvm); + + if (!ka->use_master_clock) { + rc =3D -ENODATA; + goto out; + } + + /* + * Nonzero, or pvclock_update_vm_gtod_copy() =E2=80=94 which read it on + * this CPU, with interrupts still disabled =E2=80=94 would have cleared + * use_master_clock above. + */ + curr_tsc_hz =3D (u64)get_cpu_tsc_khz() * HZ_PER_KHZ; + + if (kvm_caps.has_tsc_control) + curr_tsc_hz =3D kvm_scale_tsc(curr_tsc_hz, + v->arch.l1_tsc_scaling_ratio); + + /* + * The mul/shift in the provided pvclock structure encode the guest + * TSC frequency at which it was generated. Sanity-check that it is + * consistent with this vCPU's effective TSC frequency, allowing a + * discrepancy of 1 kHz either way since independently calibrated + * hosts will not measure precisely the same value even for the + * same nominal frequency. Compare in kHz: the reconstruction of + * each side's frequency in Hz carries a few Hz of rounding, which + * must not push two hosts calibrated exactly 1 kHz apart over the + * line. + */ + user_tsc_khz =3D DIV_ROUND_CLOSEST_ULL(user_tsc_hz, HZ_PER_KHZ); + curr_tsc_khz =3D DIV_ROUND_CLOSEST_ULL(curr_tsc_hz, HZ_PER_KHZ); + if (user_tsc_khz + 1 < curr_tsc_khz || + user_tsc_khz > curr_tsc_khz + 1) { + rc =3D -ERANGE; + goto out; + } + + /* + * Calculate the guest TSC at the new reference point, and the + * corresponding KVM clock value according to user_hv_clock. + * Adjust kvmclock_offset so both definitions agree. + */ + guest_tsc =3D kvm_read_l1_tsc(v, ka->master_cycle_now); + if ((s64)(guest_tsc - user_hv_clock.tsc_timestamp) < 0) { + rc =3D -EINVAL; + goto out; + } + user_clk_ns =3D __pvclock_read_cycles(&user_hv_clock, guest_tsc); + ka->kvmclock_offset =3D user_clk_ns - ka->master_kernel_ns; + +out: + kvm_end_pvclock_update(kvm); + + kvm_hv_remark_tsc_page(kvm); + return rc; +} +#endif + long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { @@ -4334,6 +4549,14 @@ long kvm_arch_vcpu_ioctl(struct file *filp, srcu_read_unlock(&vcpu->kvm->srcu, idx); break; } +#ifdef CONFIG_X86_64 + case KVM_SET_CLOCK_GUEST: + r =3D kvm_vcpu_ioctl_set_clock_guest(vcpu, argp); + break; + case KVM_GET_CLOCK_GUEST: + r =3D kvm_vcpu_ioctl_get_clock_guest(vcpu, argp); + break; +#endif #ifdef CONFIG_KVM_HYPERV case KVM_GET_SUPPORTED_HV_CPUID: r =3D kvm_ioctl_get_supported_hv_cpuid(vcpu, argp); diff --git a/include/uapi/linux/kvm.h b/include/uapi/linux/kvm.h index 8dff2fc1972e..1349387cceb0 100644 --- a/include/uapi/linux/kvm.h +++ b/include/uapi/linux/kvm.h @@ -1000,6 +1000,7 @@ struct kvm_enable_cap { #define KVM_CAP_PPC_COMPAT_CAPS 250 #define KVM_CAP_ARM_PMU_V3_STRICT 251 #define KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES 252 +#define KVM_CAP_CLOCK_GUEST 253 =20 struct kvm_irq_routing_irqchip { __u32 irqchip; @@ -1690,4 +1691,7 @@ struct kvm_pre_fault_memory { __u64 padding[5]; }; =20 +#define KVM_SET_CLOCK_GUEST _IOW(KVMIO, 0xd6, struct pvclock_vcpu_time_inf= o) +#define KVM_GET_CLOCK_GUEST _IOR(KVMIO, 0xd7, struct pvclock_vcpu_time_inf= o) + #endif /* __LINUX_KVM_H */ --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=at8tau5PZ9kVYteYAWqQUaFgJALvWbfK/V1oUIv9PF7YtTz6YkjeuNDvktnzKlghp9hL 9vHQiN/WjLGEd9vQlKZ3JUcGp1oTjqyxvYXq7csI3Wk6sAA6jSCcu/mUnRQqG/UmG4Nw9 RPHY+CU+FSyeFB0omUvh27KB2wOLYzjQxD7+pnwCAm8Ke4Wv0tpbSzC2ENDSh1lhrKk7/ sSR2o0XNe//oWGdDTE7ofa1xjMEW3I9KA++19DWHuTf8VSWoNV95+vNW+7SriRTbd89sE V/chFWvjtDLhdvEL1Dx1rYJgogISoNEOwUpE650jXGTzrI1yfJicY7xXqGBEytskG/g== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=iIYMQDfTQ0ULEEJl8+/Ov/AE8lIxjPKWswOvOCyc1OM=; b=lDK+VYoq240Jq5cZdNLEw08h7GNPLozAWKAE9cYK2AaJSUvwczrtnNBe0wu+YJXoKcHA OOvh5xt+iHc5YuTNykubZf4Qrcn8WmzeMjQXQYs4RfivivSP30d0N2qD3uVvyIMDvcKmR Gw3IBaxgh0laB2dRfx3/GNfJGfM3TRu3I+p/CoURElGXQ6zAxlEu818dOWGB4fumiStOx 1uc9CwfF1VwkJbaaQBoyMX0sdUD/E1DBZOfofO0uUF1wsU+vj4Rqf+G0b0Qel34PyMtX3 DIlnH7QUZdoklqLty9Ltd0PRRZQbN9V2IXWr8tAQejPvxde/1MUEMZVgXk2jzebolzg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=efTTLN+X; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 39456606B789; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 39456606B789 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=efTTLN+X DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From: Reply-To:Content-Type:Content-ID:Content-Description; bh=iIYMQDfTQ0ULEEJl8+/Ov/AE8lIxjPKWswOvOCyc1OM=; b=efTTLN+X2ESK4J6l6MZpAjrLfl 50KBNF9qmHwoujN2WeQ7k/kQmP6ctq3v/I9AdKBS8KGTZHLpqTLJLLY2nM+fCDX0+HrjE1lelRtpQ EpLlMUklhPaZn5QRIFXdLhBGb68r9AmC1cFfEdJlCrVVqYfAMnkrZft2O/mcehO8w25QHh0/m9gtW jXCyXSOeETrwPhmBhLQ+41vazEZ0KFBlNZxE4/C27PImq/xAOPVnMBfWFi/TtUNsOZXuBqBHwsyTm lEEhiXf3P9BQd/B1AypeHprvMyT50vxK+SUl0o4REgHaGInx6oPsVQGTUH7Ik9ikRG+43YuGaUUGb RD/CEatg==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvR-3Ctb; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWt7-23xv; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 17/26] KVM: selftests: Add library helpers for clock and TSC-offset ioctls Date: Wed, 11 Nov 2026 10:09:13 -0800 Message-ID: <20261111180922.4177927-18-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html Content-Type: text/plain; charset="utf-8" From: David Woodhouse Add wrappers for KVM_[GS]ET_CLOCK_GUEST, the KVM_VCPU_TSC_OFFSET device attribute and KVM_[GS]ET_CLOCK to the x86 library header, so that the KVM clock selftests don't each open-code the same ioctl invocations, and convert the existing open-coded call sites in kvm_clock_test, hyperv_clock, xen_shinfo_test and system_counter_offset_test. Signed-off-by: David Woodhouse --- .../selftests/kvm/include/x86/processor.h | 50 +++++++++++++++++++ .../kvm/system_counter_offset_test.c | 3 +- .../testing/selftests/kvm/x86/hyperv_clock.c | 2 +- .../selftests/kvm/x86/kvm_clock_test.c | 6 +-- .../selftests/kvm/x86/xen_shinfo_test.c | 2 +- 5 files changed, 56 insertions(+), 7 deletions(-) diff --git a/tools/testing/selftests/kvm/include/x86/processor.h b/tools/te= sting/selftests/kvm/include/x86/processor.h index 5898a277a2e0..4062bdb32716 100644 --- a/tools/testing/selftests/kvm/include/x86/processor.h +++ b/tools/testing/selftests/kvm/include/x86/processor.h @@ -12,6 +12,7 @@ =20 #include #include +#include =20 #include #include @@ -1029,6 +1030,55 @@ static inline void vcpu_xcrs_set(struct kvm_vcpu *vc= pu, struct kvm_xcrs *xcrs) vcpu_ioctl(vcpu, KVM_SET_XCRS, xcrs); } =20 +static inline int __vcpu_get_clock_guest(struct kvm_vcpu *vcpu, + struct pvclock_vcpu_time_info *pvti) +{ + return __vcpu_ioctl(vcpu, KVM_GET_CLOCK_GUEST, pvti); +} + +static inline void vcpu_get_clock_guest(struct kvm_vcpu *vcpu, + struct pvclock_vcpu_time_info *pvti) +{ + vcpu_ioctl(vcpu, KVM_GET_CLOCK_GUEST, pvti); +} + +static inline int __vcpu_set_clock_guest(struct kvm_vcpu *vcpu, + struct pvclock_vcpu_time_info *pvti) +{ + return __vcpu_ioctl(vcpu, KVM_SET_CLOCK_GUEST, pvti); +} + +static inline void vcpu_set_clock_guest(struct kvm_vcpu *vcpu, + struct pvclock_vcpu_time_info *pvti) +{ + vcpu_ioctl(vcpu, KVM_SET_CLOCK_GUEST, pvti); +} + +static inline u64 vcpu_get_tsc_offset(struct kvm_vcpu *vcpu) +{ + u64 offset; + + vcpu_device_attr_get(vcpu, KVM_VCPU_TSC_CTRL, KVM_VCPU_TSC_OFFSET, + &offset); + return offset; +} + +static inline void vcpu_set_tsc_offset(struct kvm_vcpu *vcpu, u64 offset) +{ + vcpu_device_attr_set(vcpu, KVM_VCPU_TSC_CTRL, KVM_VCPU_TSC_OFFSET, + &offset); +} + +static inline void vm_get_clock(struct kvm_vm *vm, struct kvm_clock_data *= data) +{ + vm_ioctl(vm, KVM_GET_CLOCK, data); +} + +static inline void vm_set_clock(struct kvm_vm *vm, struct kvm_clock_data *= data) +{ + vm_ioctl(vm, KVM_SET_CLOCK, data); +} + const struct kvm_cpuid_entry2 *get_cpuid_entry(const struct kvm_cpuid2 *cp= uid, u32 function, u32 index); const struct kvm_cpuid2 *kvm_get_supported_cpuid(void); diff --git a/tools/testing/selftests/kvm/system_counter_offset_test.c b/too= ls/testing/selftests/kvm/system_counter_offset_test.c index dc5e30b7b77f..f864e66dc789 100644 --- a/tools/testing/selftests/kvm/system_counter_offset_test.c +++ b/tools/testing/selftests/kvm/system_counter_offset_test.c @@ -35,8 +35,7 @@ static void check_preconditions(struct kvm_vcpu *vcpu) =20 static void setup_system_counter(struct kvm_vcpu *vcpu, struct test_case *= test) { - vcpu_device_attr_set(vcpu, KVM_VCPU_TSC_CTRL, KVM_VCPU_TSC_OFFSET, - &test->tsc_offset); + vcpu_set_tsc_offset(vcpu, test->tsc_offset); } =20 static u64 guest_read_system_counter(struct test_case *test) diff --git a/tools/testing/selftests/kvm/x86/hyperv_clock.c b/tools/testing= /selftests/kvm/x86/hyperv_clock.c index 7a1b3b5d1e62..ced3d9873f9a 100644 --- a/tools/testing/selftests/kvm/x86/hyperv_clock.c +++ b/tools/testing/selftests/kvm/x86/hyperv_clock.c @@ -254,7 +254,7 @@ int main(void) if (stage =3D=3D 7 || stage =3D=3D 8 || stage =3D=3D 10) { struct kvm_clock_data clock =3D {0}; =20 - vm_ioctl(vm, KVM_SET_CLOCK, &clock); + vm_set_clock(vm, &clock); } } =20 diff --git a/tools/testing/selftests/kvm/x86/kvm_clock_test.c b/tools/testi= ng/selftests/kvm/x86/kvm_clock_test.c index 5ad4aeb8e373..0028a40b8a3e 100644 --- a/tools/testing/selftests/kvm/x86/kvm_clock_test.c +++ b/tools/testing/selftests/kvm/x86/kvm_clock_test.c @@ -99,7 +99,7 @@ static void setup_clock(struct kvm_vm *vm, struct test_ca= se *test_case) data.realtime +=3D test_case->realtime_offset; } =20 - vm_ioctl(vm, KVM_SET_CLOCK, &data); + vm_set_clock(vm, &data); } =20 static void enter_guest(struct kvm_vcpu *vcpu) @@ -112,10 +112,10 @@ static void enter_guest(struct kvm_vcpu *vcpu) for (i =3D 0; i < ARRAY_SIZE(test_cases); i++) { setup_clock(vm, &test_cases[i]); =20 - vm_ioctl(vm, KVM_GET_CLOCK, &start); + vm_get_clock(vm, &start); =20 vcpu_run(vcpu); - vm_ioctl(vm, KVM_GET_CLOCK, &end); + vm_get_clock(vm, &end); =20 TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); =20 diff --git a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c b/tools/test= ing/selftests/kvm/x86/xen_shinfo_test.c index 9045f03cf2d3..f251f8ea29ec 100644 --- a/tools/testing/selftests/kvm/x86/xen_shinfo_test.c +++ b/tools/testing/selftests/kvm/x86/xen_shinfo_test.c @@ -985,7 +985,7 @@ int main(int argc, char *argv[]) TEST_ASSERT(wc->version && !(wc->version & 1), "Bad wallclock version %x", wc->version); =20 - vm_ioctl(vm, KVM_GET_CLOCK, &kcdata); + vm_get_clock(vm, &kcdata); =20 if (kcdata.flags & KVM_CLOCK_REALTIME) { if (verbose) { --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=xliuB8T6q12LUkY98mvbbISAJH/9JMd534NF1vMUw2gQVzmfBTm1JJ3+WXsQ7eEku9hS bgzK1mRVKtCy3vMnzykUZouHwnhOs+BfCRPMSq5zHIlC8SQd1Julq6xvM7ti4Zyu6L+PQ o19hSYZVUfuST8N+wAvqVAPliKiAl28reER8wJCHFG4+CuJSdah+74FWE1fb2pLGs73eS /Xm/JBbwcWpvCIFhnF7s+0xp4lXxjj31tGXQWv06OJamp0GhhQdM5zTpyYkk/ObpDET3F Z+TMe1Gstc1VryWESKyPfpS8r/8fiXbSaZxxnZcaN79aULQze1r5bBv8FjJdtY462HQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=r5p4FN/iNGe4dJB09CBCdjApkAkJtpgVFj/N1ZClpUY=; b=szh4v8sa4Y/8tMyqjCvYEgqKEbDznjMsBHO9xRhY71XeZq2N8txrr4BUmuq21fwm/AUj Trod3Kzj4jBgMRqLzlvsJIlI+bx/9kWFPx7Wmx6rtNy4UDkCSsV7DufUDaAOJwb2kY+tD C4MQofT1lA+LIRhIdr8JZouKcklih0rbt++84TIi/hjfG1CMKys+ycGpBu9A6tKk+iKZI nAGdyUWi2B+XdBhp1PvD1bVcLOQjMbfM76VMrbukDt/7LLoLYJFOVFifSf7CIzhCJ4Xpp z3uftTzaKTRhte1w5qxDU500E8lEEuPF1Igc1/iynjUb8Osc/OMlBNPYnpSsq9gafAw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=TNzgvb8s; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 386C5606B788; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 386C5606B788 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=TNzgvb8s DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=r5p4FN/iNGe4dJB09CBCdjApkAkJtpgVFj/N1ZClpUY=; b=TNzgvb8s0RpdEK2Ac0Le7J9spv xNZEXtPXyET0NUp4g1sRi73rxHnjYYBtbaXKxMziUgu83YNJXujALfw2fH9yN+7uPZOuVecsOsnYG p8W4qjafDkfZildq0+vNLxDqYkly5MLQ7vrDUhFQa5sdCp+jKLuNE5VE1VgDpKCgsBav/hjxVvrm3 MJtwF6VQ8NbWIsA47h4fYhp00npJdJdu2msR4N04Ip6lqduKI+VD8NYZ5LB0ctneQzy6Pjg1y07cI /39xD4mH4ulyItR2IjIyCTTwyX2T5bX5C8LDJPfuDs1Ckya54IN+yw2emFdKrKDH3zOokpP8HMNj5 7Kao0yDg==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvS-3Cv4; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtC-2GNU; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 18/26] KVM: x86: Add KVM_VCPU_TSC_SCALE and fix the documentation on TSC migration Date: Wed, 11 Nov 2026 10:09:14 -0800 Message-ID: <20261111180922.4177927-19-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse The documentation on TSC migration using KVM_VCPU_TSC_OFFSET is woefully inadequate. It ignores TSC scaling, and ignores the fact that the host TSC may differ from one host to the next (and in fact because of the way the kernel calibrates it, it generally differs from one boot to the next even on the same hardware). Add KVM_VCPU_TSC_SCALE to extract the actual scale ratio and frac_bits, and attempt to document the process that userspace needs to follow to preserve the TSC across migration. Add a self test to function as an exemplar. Only enumerate KVM_VCPU_TSC_SCALE when kvm_caps.has_tsc_control is true, since the scaling ratio is only meaningful when hardware TSC scaling is supported. Signed-off-by: David Woodhouse Reviewed-by: Paul Durrant --- Documentation/virt/kvm/devices/vcpu.rst | 144 +++-- arch/x86/include/uapi/asm/kvm.h | 6 + arch/x86/kvm/x86.c | 21 + tools/arch/x86/include/uapi/asm/kvm.h | 6 + tools/testing/selftests/kvm/Makefile.kvm | 1 + .../kvm/x86/pvclock_migration_test.c | 503 ++++++++++++++++++ 6 files changed, 651 insertions(+), 30 deletions(-) create mode 100644 tools/testing/selftests/kvm/x86/pvclock_migration_test.c diff --git a/Documentation/virt/kvm/devices/vcpu.rst b/Documentation/virt/k= vm/devices/vcpu.rst index deb5c51bc00c..97174132285d 100644 --- a/Documentation/virt/kvm/devices/vcpu.rst +++ b/Documentation/virt/kvm/devices/vcpu.rst @@ -239,6 +239,7 @@ including the layout of the stolen time structure. :Architectures: x86 =20 4.1 ATTRIBUTE: KVM_VCPU_TSC_OFFSET +---------------------------------- =20 :Parameters: 64-bit unsigned TSC offset =20 @@ -253,7 +254,10 @@ Returns: Specifies the guest's TSC offset relative to the host's TSC. The guest's TSC is then derived by the following equation: =20 - guest_tsc =3D host_tsc + KVM_VCPU_TSC_OFFSET + guest_tsc =3D ((host_tsc * tsc_ratio) >> tsc_frac_bits) + KVM_VCPU_TSC_O= FFSET + +The values of tsc_ratio and tsc_frac_bits can be obtained using +the KVM_VCPU_TSC_SCALE attribute. =20 This attribute is useful to adjust the guest's TSC on live migration, so that the TSC counts the time during which the VM was paused. The @@ -261,44 +265,124 @@ following describes a possible algorithm to use for = this purpose. =20 From the source VMM process: =20 -1. Invoke the KVM_GET_CLOCK ioctl to record the host TSC (tsc_src), +1. Invoke the KVM_GET_CLOCK ioctl to record the host TSC (host_tsc_src), kvmclock nanoseconds (guest_src), and host CLOCK_REALTIME nanoseconds - (host_src). + (time_src) at a given moment (Tsrc). The host_tsc field is only valid + when the returned flags include KVM_CLOCK_HOST_TSC. + +2. For each vCPU[i]: + + a. Read the KVM_VCPU_TSC_OFFSET attribute to record the guest TSC offset + (ofs_src[i]). + + b. Read the KVM_VCPU_TSC_SCALE attribute to record the guest TSC scaling + ratio (ratio_src[i], frac_bits_src[i]). If the attribute is not + supported (-ENXIO), there is no hardware TSC scaling and identity + scaling applies: use ratio 1, frac_bits 0. + + c. Invoke the KVM_GET_TSC_KHZ ioctl to record the frequency of the + guest's TSC (freq[i]). + + d. Use host_tsc_src and the scaling/offset factors to calculate this + vCPU's TSC at time Tsrc: + + tsc_src[i] =3D ((host_tsc_src * ratio_src[i]) >> frac_bits_src[i]) += ofs_src[i] =20 -2. Read the KVM_VCPU_TSC_OFFSET attribute for every vCPU to record the - guest TSC offset (ofs_src[i]). + Note that frac_bits may be as high as 48, so this multiplication + needs a 128-bit intermediate to avoid overflow. =20 -3. Invoke the KVM_GET_TSC_KHZ ioctl to record the frequency of the - guest's TSC (freq). +3. Invoke the KVM_GET_CLOCK_GUEST ioctl on the boot vCPU to return the KVM + clock as a function of the guest TSC (pvti_src). (This ioctl may not + succeed if the host and guest TSCs are not consistent and well-behaved.) =20 From the destination VMM process: =20 -4. Invoke the KVM_SET_CLOCK ioctl, providing the source nanoseconds from - kvmclock (guest_src) and CLOCK_REALTIME (host_src) in their respective - fields. Ensure that the KVM_CLOCK_REALTIME flag is set in the provided - structure. +4. Invoke the KVM_SET_TSC_KHZ ioctl to set the scaled frequency of the + guest's TSC (freq[i]) =E2=80=94 either on the VM before creating the vC= PUs, or + on each vCPU after creating it (as the exemplar test does). When using + the per-vCPU form, create all the vCPUs before setting the frequency + on any of them (each vCPU's creation synchronizes it at the default + frequency, so interleaving creation with frequency changes fragments + the TSC matching), and set the frequency before performing step 7 on + that vCPU: KVM_VCPU_TSC_SCALE reports the ratio for the currently + configured frequency. + +5. Invoke the KVM_GET_CLOCK ioctl to record the host TSC (host_tsc_dst) and + host CLOCK_REALTIME nanoseconds (time_dst) at a given moment (Tdst), + again checking KVM_CLOCK_HOST_TSC in the returned flags. + +6. Calculate the number of nanoseconds elapsed between Tsrc and Tdst: + + =CE=94T =3D time_dst - time_src + +7. As each vCPU[i] is created: + + a. Read the KVM_VCPU_TSC_SCALE attribute to record the guest TSC scaling + ratio (ratio_dst[i], frac_bits_dst[i]). As in step 2b, -ENXIO means + identity scaling: use ratio 1, frac_bits 0. + + b. Calculate the intended guest TSC value at time Tdst, taking care + with the units (=CE=94T is in nanoseconds; freq, as set by + KVM_SET_TSC_KHZ, is in kHz): + + tsc_dst[i] =3D tsc_src[i] + (=CE=94T * freq[i] / 10^6) =20 - KVM will advance the VM's kvmclock to account for elapsed time since - recording the clock values. Note that this will cause problems in - the guest (e.g., timeouts) unless CLOCK_REALTIME is synchronized - between the source and destination, and a reasonably short time passes - between the source pausing the VMs and the destination executing - steps 4-7. + As in step 2d, this multiplication needs a 128-bit intermediate: + the product exceeds a signed 64-bit value once =CE=94T reaches about + 51 minutes for a 3GHz guest. + + c. Use host_tsc_dst and the scaling factors to calculate this vCPU's + raw scaled TSC at time Tdst without offsetting: + + raw_dst[i] =3D ((host_tsc_dst * ratio_dst[i]) >> frac_bits_dst[i]) + + d. Calculate ofs_dst[i] =3D tsc_dst[i] - raw_dst[i] and set the resulti= ng + offset using the KVM_VCPU_TSC_OFFSET attribute. + +8. If pvti_src was provided, invoke the KVM_SET_CLOCK_GUEST ioctl on the b= oot + vCPU to restore the KVM clock as a precise function of the guest TSC. + +9. If KVM_SET_CLOCK_GUEST was not available or failed (e.g. because the + master clock is not active), fall back to the KVM_SET_CLOCK ioctl, + providing the source nanoseconds from kvmclock (guest_src) and + CLOCK_REALTIME (time_src) in their respective fields. Ensure that the + KVM_CLOCK_REALTIME flag is set in the provided structure. + + KVM will restore the VM's kvmclock, accounting for elapsed time since + the clock values were recorded. Note that this will cause problems in + the guest (e.g., timeouts) unless CLOCK_REALTIME is synchronized between + the source and destination, and a reasonably short time passes between + the source pausing the VMs and the destination resuming them. + Due to the KVM_[SG]ET_CLOCK API using CLOCK_REALTIME instead of + CLOCK_TAI, leap seconds during the migration may also introduce errors. + +4.2 ATTRIBUTE: KVM_VCPU_TSC_SCALE +--------------------------------- + +:Parameters: struct kvm_vcpu_tsc_scale + +Returns: + + =3D=3D=3D=3D=3D=3D=3D =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D + -EFAULT Error writing the result to the + provided address. + -ENXIO Attribute not supported (no TSC scaling) + -EINVAL Invalid request to write the attribute + =3D=3D=3D=3D=3D=3D=3D =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D =20 -5. Invoke the KVM_GET_CLOCK ioctl to record the host TSC (tsc_dest) and - kvmclock nanoseconds (guest_dest). +This read-only attribute reports the guest's TSC scaling factor, in the fo= rm +of a fixed-point number represented by the following structure:: =20 -6. Adjust the guest TSC offsets for every vCPU to account for (1) time - elapsed since recording state and (2) difference in TSCs between the - source and destination machine: + struct kvm_vcpu_tsc_scale { + __u64 tsc_ratio; + __u64 tsc_frac_bits; + }; =20 - ofs_dst[i] =3D ofs_src[i] - - (guest_src - guest_dest) * freq + - (tsc_src - tsc_dest) +The tsc_frac_bits field indicates the location of the fixed point, such th= at +host TSC values are converted to guest TSC using the formula: =20 - ("ofs[i] + tsc - guest * freq" is the guest TSC value corresponding to - a time of 0 in kvmclock. The above formula ensures that it is the - same on the destination as it was on the source). + guest_tsc =3D ((host_tsc * tsc_ratio) >> tsc_frac_bits) + offset =20 -7. Write the KVM_VCPU_TSC_OFFSET attribute for every vCPU with the - respective value derived in the previous step. +Userspace can use this to precisely calculate the guest TSC from the host +TSC at any given moment. This is needed for accurate migration of guests, +as described in the documentation for the KVM_VCPU_TSC_OFFSET attribute. diff --git a/arch/x86/include/uapi/asm/kvm.h b/arch/x86/include/uapi/asm/kv= m.h index 9e3cdc3adb65..f8274d8e471d 100644 --- a/arch/x86/include/uapi/asm/kvm.h +++ b/arch/x86/include/uapi/asm/kvm.h @@ -964,6 +964,12 @@ struct kvm_hyperv_eventfd { /* for KVM_{GET,SET,HAS}_DEVICE_ATTR */ #define KVM_VCPU_TSC_CTRL 0 /* control group for the timestamp counter (TS= C) */ #define KVM_VCPU_TSC_OFFSET 0 /* attribute for the TSC offset */ +#define KVM_VCPU_TSC_SCALE 1 /* attribute for TSC scaling factor */ + +struct kvm_vcpu_tsc_scale { + __u64 tsc_ratio; + __u64 tsc_frac_bits; +}; =20 /* x86-specific KVM_EXIT_HYPERCALL flags. */ #define KVM_EXIT_HYPERCALL_LONG_MODE _BITULL(0) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 16383c71131d..b9d3b2715403 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -3780,6 +3780,9 @@ static int kvm_arch_tsc_has_attr(struct kvm_vcpu *vcp= u, case KVM_VCPU_TSC_OFFSET: r =3D 0; break; + case KVM_VCPU_TSC_SCALE: + r =3D kvm_caps.has_tsc_control ? 0 : -ENXIO; + break; default: r =3D -ENXIO; } @@ -3800,6 +3803,21 @@ static int kvm_arch_tsc_get_attr(struct kvm_vcpu *vc= pu, break; r =3D 0; break; + case KVM_VCPU_TSC_SCALE: { + struct kvm_vcpu_tsc_scale scale; + + r =3D -ENXIO; + if (!kvm_caps.has_tsc_control) + break; + + scale.tsc_ratio =3D vcpu->arch.l1_tsc_scaling_ratio; + scale.tsc_frac_bits =3D kvm_caps.tsc_scaling_ratio_frac_bits; + r =3D -EFAULT; + if (copy_to_user(uaddr, &scale, sizeof(scale))) + break; + r =3D 0; + break; + } default: r =3D -ENXIO; } @@ -3855,6 +3873,9 @@ static int kvm_arch_tsc_set_attr(struct kvm_vcpu *vcp= u, r =3D 0; break; } + case KVM_VCPU_TSC_SCALE: + r =3D kvm_caps.has_tsc_control ? -EINVAL : -ENXIO; + break; default: r =3D -ENXIO; } diff --git a/tools/arch/x86/include/uapi/asm/kvm.h b/tools/arch/x86/include= /uapi/asm/kvm.h index 1585ec804066..7b3afccb6cb2 100644 --- a/tools/arch/x86/include/uapi/asm/kvm.h +++ b/tools/arch/x86/include/uapi/asm/kvm.h @@ -963,6 +963,12 @@ struct kvm_hyperv_eventfd { /* for KVM_{GET,SET,HAS}_DEVICE_ATTR */ #define KVM_VCPU_TSC_CTRL 0 /* control group for the timestamp counter (TS= C) */ #define KVM_VCPU_TSC_OFFSET 0 /* attribute for the TSC offset */ +#define KVM_VCPU_TSC_SCALE 1 /* attribute for TSC scaling factor */ + +struct kvm_vcpu_tsc_scale { + __u64 tsc_ratio; + __u64 tsc_frac_bits; +}; =20 /* x86-specific KVM_EXIT_HYPERCALL flags. */ #define KVM_EXIT_HYPERCALL_LONG_MODE _BITULL(0) diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selft= ests/kvm/Makefile.kvm index 888a7530a280..18605318860e 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -113,6 +113,7 @@ TEST_GEN_PROGS_x86 +=3D x86/pmu_counters_test TEST_GEN_PROGS_x86 +=3D x86/pmu_event_filter_test TEST_GEN_PROGS_x86 +=3D x86/private_mem_conversions_test TEST_GEN_PROGS_x86 +=3D x86/private_mem_kvm_exits_test +TEST_GEN_PROGS_x86 +=3D x86/pvclock_migration_test TEST_GEN_PROGS_x86 +=3D x86/save_restore_pf_stress_test TEST_GEN_PROGS_x86 +=3D x86/set_boot_cpu_id TEST_GEN_PROGS_x86 +=3D x86/set_sregs_test diff --git a/tools/testing/selftests/kvm/x86/pvclock_migration_test.c b/too= ls/testing/selftests/kvm/x86/pvclock_migration_test.c new file mode 100644 index 000000000000..a25522b5562f --- /dev/null +++ b/tools/testing/selftests/kvm/x86/pvclock_migration_test.c @@ -0,0 +1,503 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Test KVM clock precision across simulated live migration. + * + * Verifies that the documented TSC migration procedure (using + * KVM_VCPU_TSC_OFFSET, KVM_VCPU_TSC_SCALE, KVM_GET_CLOCK, and + * KVM_SET_CLOCK_GUEST) preserves the kvmclock's relationship to + * CLOCK_MONOTONIC_RAW =E2=80=94 including for vCPUs whose TSCs are offset + * from one another (same frequency), which no longer disables the + * master clock. + * + * The test: + * 1. Creates a VM with 3 vCPUs, runs each guest to enable kvmclock + * 2. Applies divergent TSC offsets to vCPUs 1 and 2 + * 3. Verifies the master clock remains active (KVM_CLOCK_HOST_TSC), + * that the guests see PVCLOCK_TSC_STABLE_BIT clear, and that all + * vCPUs' pvclocks agree on "now" despite the divergent offsets + * 4. Does a PTP-like ABA measurement of kvmclock vs CLOCK_MONOTONIC_RAW + * 5. Follows the documented migration procedure (same host, 1s pause), + * migrating each vCPU's TSC individually but setting the KVM clock + * only once, via KVM_SET_CLOCK_GUEST on vCPU0 + * 6. Does the same ABA measurement on the destination VM + * 7. Verifies the kvmclock-vs-monotonic delta is preserved, the + * cross-vCPU TSC deltas are preserved, and all destination vCPUs' + * pvclocks again agree on "now" + */ +#include +#include +#include +#include +#include +#include + +#include "test_util.h" +#include "kvm_util.h" +#include "processor.h" + +#include +#include + +#define KVMCLOCK_GPA 0xc0000000ULL +#define NR_VCPUS 3 + +/* + * Divergent TSC offsets applied to vCPUs 1 and 2, in guest cycles. + * Roughly +1s and -0.5s at 1.5 GHz =E2=80=94 large enough that any failure + * to account for them is orders of magnitude outside the ABA bounds. + */ +static const s64 tsc_deltas[NR_VCPUS] =3D { 0, 1500000000LL, -750000000LL = }; + +static void guest_code(int idx) +{ + wrmsr(MSR_KVM_SYSTEM_TIME_NEW, (KVMCLOCK_GPA + idx * PAGE_SIZE) | 1); + + for (;;) + GUEST_SYNC(0); +} + +static u64 read_kvmclock_ns(struct kvm_vm *vm) +{ + struct kvm_clock_data data =3D {}; + + vm_get_clock(vm, &data); + return data.clock; +} + +/* + * ABA measurement: read CLOCK_MONOTONIC_RAW, kvmclock, CLOCK_MONOTONIC_RA= W. + * Repeat 3 times, keep the reading with the smallest spread. + */ +static void aba_reading(struct kvm_vm *vm, u64 *lo, u64 *kvm_ns, + u64 *hi) +{ + u64 best_spread =3D UINT64_MAX; + int i; + + for (i =3D 0; i < 3; i++) { + struct timespec ts1, ts2; + u64 m1, m2, clk; + + clock_gettime(CLOCK_MONOTONIC_RAW, &ts1); + clk =3D read_kvmclock_ns(vm); + clock_gettime(CLOCK_MONOTONIC_RAW, &ts2); + + m1 =3D ts1.tv_sec * 1000000000ULL + ts1.tv_nsec; + m2 =3D ts2.tv_sec * 1000000000ULL + ts2.tv_nsec; + + if (m2 - m1 < best_spread) { + best_spread =3D m2 - m1; + *lo =3D m1; + *kvm_ns =3D clk; + *hi =3D m2; + } + } +} + +static struct kvm_vm *create_vm(struct kvm_vcpu **vcpus, u32 freq_khz) +{ + struct kvm_vm *vm; + int i; + + vm =3D vm_create_with_vcpus(NR_VCPUS, guest_code, vcpus); + + vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, + KVMCLOCK_GPA, 1, NR_VCPUS, 0); + virt_map(vm, KVMCLOCK_GPA, KVMCLOCK_GPA, NR_VCPUS); + + for (i =3D 0; i < NR_VCPUS; i++) { + vcpu_args_set(vcpus[i], 1, i); + /* Set guest TSC frequency (may trigger scaling) */ + vcpu_ioctl(vcpus[i], KVM_SET_TSC_KHZ, + (void *)(unsigned long)freq_khz); + } + return vm; +} + +static void run_to_sync(struct kvm_vcpu *vcpu) +{ + struct ucall uc; + + vcpu_run(vcpu); + TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); + TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_SYNC); +} + +/* + * Compute a vCPU's guest TSC for a given host TSC value, using the + * vCPU's scale and offset as saved from KVM_VCPU_TSC_SCALE/OFFSET. + */ +static u64 host_to_guest_tsc(struct kvm_vcpu_tsc_scale *scale, u64 ofs, + u64 host_tsc) +{ + if (scale->tsc_frac_bits) + return ((unsigned __int128)host_tsc * scale->tsc_ratio + >> scale->tsc_frac_bits) + ofs; + return host_tsc + ofs; +} + +/* + * Verify that all vCPUs agree on the KVM clock, despite having + * different TSC offsets. Take one atomic {host_tsc, kvmclock} pair + * for the whole VM, derive each vCPU's guest TSC at that instant, + * and evaluate each vCPU's pvti at its own guest TSC. All must give + * the same nanosecond value (same instant, same clock), and must + * match what KVM_GET_CLOCK itself said. + */ +static void check_cross_vcpu_coherence(struct kvm_vm *vm, + struct kvm_vcpu **vcpus, + struct pvclock_vcpu_time_info *pvtis, + const char *what) +{ + struct kvm_clock_data now =3D {}; + u64 clk[NR_VCPUS]; + int i; + + vm_get_clock(vm, &now); + TEST_ASSERT(now.flags & KVM_CLOCK_HOST_TSC, + "%s: master clock inactive with divergent TSC offsets", + what); + + for (i =3D 0; i < NR_VCPUS; i++) { + struct kvm_vcpu_tsc_scale scale =3D {}; + u64 ofs =3D vcpu_get_tsc_offset(vcpus[i]); + u64 guest_tsc; + + vcpu_device_attr_get(vcpus[i], KVM_VCPU_TSC_CTRL, + KVM_VCPU_TSC_SCALE, &scale); + guest_tsc =3D host_to_guest_tsc(&scale, ofs, now.host_tsc); + clk[i] =3D __pvclock_read_cycles(&pvtis[i], guest_tsc); + + TEST_ASSERT(!(pvtis[i].flags & PVCLOCK_TSC_STABLE_BIT), + "%s: vCPU%d still advertises TSC_STABLE with divergent offsets", + what, i); + } + + for (i =3D 1; i < NR_VCPUS; i++) { + s64 d =3D (s64)(clk[i] - clk[0]); + + pr_info(" %s: vCPU%d vs vCPU0 kvmclock delta %" PRId64 " ns\n", + what, i, d); + TEST_ASSERT(d >=3D -2 && d <=3D 2, + "%s: vCPU%d kvmclock disagrees with vCPU0 by %" PRId64 " ns", + what, i, d); + } + + /* And all of them must agree with KVM_GET_CLOCK itself */ + s64 d0 =3D (s64)(clk[0] - now.clock); + pr_info(" %s: vCPU0 pvclock vs KVM_GET_CLOCK delta %" PRId64 " ns\n", + what, d0); + TEST_ASSERT(d0 >=3D -2 && d0 <=3D 2, + "%s: vCPU0 pvclock disagrees with KVM_GET_CLOCK by %" PRId64 " ns", + what, d0); +} + +int main(void) +{ + struct pvclock_vcpu_time_info pvti_src[NR_VCPUS]; + struct pvclock_vcpu_time_info pvti_dst_ioctl[NR_VCPUS]; + struct kvm_clock_data clock_src, clock_dst; + struct kvm_vcpu_tsc_scale scale_src[NR_VCPUS], scale_dst; + struct kvm_vcpu *vcpus[NR_VCPUS]; + struct kvm_vm *vm; + u64 mono_before, kvm_before, kvm_after; + s64 delta_before; + u64 ofs_src[NR_VCPUS], tsc_src[NR_VCPUS], tsc_dst, raw_dst; + u64 ofs_dst[NR_VCPUS]; + u64 host_tsc_src, host_tsc_dst; + u64 time_src, time_dst; + s64 delta_t; + u32 freq_khz =3D 1500000; /* 1.5 GHz =E2=80=94 forces TSC scaling */ + int i, pass; + + TEST_REQUIRE(sys_clocksource_is_based_on_tsc()); + TEST_REQUIRE(kvm_has_cap(KVM_CAP_TSC_CONTROL)); + TEST_REQUIRE(kvm_has_cap(KVM_CAP_CLOCK_GUEST)); + + /* =3D=3D=3D SOURCE SIDE =3D=3D=3D */ + pr_info("=3D=3D=3D Source VM =3D=3D=3D\n"); + vm =3D create_vm(vcpus, freq_khz); + + /* Run each guest to enable its kvmclock */ + for (i =3D 0; i < NR_VCPUS; i++) + run_to_sync(vcpus[i]); + + /* + * Apply divergent TSC offsets. Same frequency, different offsets: + * this must no longer disable the master clock, but must clear + * PVCLOCK_TSC_STABLE_BIT. + */ + for (i =3D 1; i < NR_VCPUS; i++) + vcpu_set_tsc_offset(vcpus[i], + vcpu_get_tsc_offset(vcpus[i]) + tsc_deltas[i]); + + /* + * Re-run each vCPU twice. The offset writes leave a masterclock + * update pending on vCPUs 1 and 2; the first pass processes it and + * broadcasts KVM_REQ_CLOCK_UPDATE to every vCPU, and the second + * pass has each vCPU rewrite its guest-visible pvclock page with + * PVCLOCK_TSC_STABLE_BIT now clear. A single pass would leave + * vCPU0's page stale: its rewrite happens before the broadcast. + */ + for (pass =3D 0; pass < 2; pass++) + for (i =3D 0; i < NR_VCPUS; i++) + run_to_sync(vcpus[i]); + + /* Fetch each vCPU's pvti and verify cross-vCPU coherence */ + for (i =3D 0; i < NR_VCPUS; i++) + vcpu_get_clock_guest(vcpus[i], &pvti_src[i]); + check_cross_vcpu_coherence(vm, vcpus, pvti_src, "source"); + + /* The guest-visible pvti pages must also show TSC_STABLE clear */ + for (i =3D 0; i < NR_VCPUS; i++) { + struct pvclock_vcpu_time_info *pvti =3D + addr_gpa2hva(vm, KVMCLOCK_GPA + i * getpagesize()); + + TEST_ASSERT(!(pvti->flags & PVCLOCK_TSC_STABLE_BIT), + "vCPU%d guest pvti advertises TSC_STABLE with divergent offsets", i= ); + } + + /* ABA measurement: kvmclock vs CLOCK_MONOTONIC_RAW */ + u64 src_mono_lo, src_mono_hi; + aba_reading(vm, &src_mono_lo, &kvm_before, &src_mono_hi); + mono_before =3D (src_mono_lo + src_mono_hi) / 2; + delta_before =3D (s64)(kvm_before - mono_before); + pr_info(" kvmclock - MONOTONIC_RAW =3D %" PRId64 " ns (=C2=B1%" PRIu64 "= ns)\n", + delta_before, (src_mono_hi - src_mono_lo) / 2); + + /* Step 1: KVM_GET_CLOCK for atomic {host_tsc, realtime} */ + memset(&clock_src, 0, sizeof(clock_src)); + clock_src.flags =3D KVM_CLOCK_REALTIME; + vm_get_clock(vm, &clock_src); + TEST_ASSERT(clock_src.flags & KVM_CLOCK_HOST_TSC, + "KVM_GET_CLOCK did not provide host_tsc (no master clock?)"); + host_tsc_src =3D clock_src.host_tsc; + time_src =3D clock_src.realtime; + + /* Step 2: Save each vCPU's TSC offset and scale */ + for (i =3D 0; i < NR_VCPUS; i++) { + ofs_src[i] =3D vcpu_get_tsc_offset(vcpus[i]); + memset(&scale_src[i], 0, sizeof(scale_src[i])); + vcpu_device_attr_get(vcpus[i], KVM_VCPU_TSC_CTRL, + KVM_VCPU_TSC_SCALE, &scale_src[i]); + + /* Compute this vCPU's guest TSC at Tsrc */ + tsc_src[i] =3D host_to_guest_tsc(&scale_src[i], ofs_src[i], + host_tsc_src); + pr_info(" vCPU%d: TSC freq=3D%u kHz, offset=3D%" PRId64 "\n", + i, freq_khz, (s64)ofs_src[i]); + } + + /* Step 3: KVM_GET_CLOCK_GUEST (already fetched above as pvti_src[]) */ + + kvm_vm_free(vm); + + /* =3D=3D=3D PAUSE (simulate migration) =3D=3D=3D */ + pr_info("=3D=3D=3D Pausing 1 second =3D=3D=3D\n"); + sleep(1); + + /* =3D=3D=3D DESTINATION SIDE =3D=3D=3D */ + pr_info("=3D=3D=3D Destination VM =3D=3D=3D\n"); + /* Step 4: create + KVM_SET_TSC_KHZ (in create_vm) */ + vm =3D create_vm(vcpus, freq_khz); + + /* Step 5: KVM_GET_CLOCK for atomic {host_tsc, realtime} pair. + * Master clock is active from VM creation. + */ + memset(&clock_dst, 0, sizeof(clock_dst)); + vm_get_clock(vm, &clock_dst); + TEST_ASSERT(clock_dst.flags & KVM_CLOCK_HOST_TSC, + "KVM_GET_CLOCK did not provide host_tsc (no master clock?)"); + host_tsc_dst =3D clock_dst.host_tsc; + time_dst =3D clock_dst.realtime; + + /* Step 6: =CE=94T */ + delta_t =3D (s64)(time_dst - time_src); + + /* Step 7: Compute and set each vCPU's destination offset */ + memset(&scale_dst, 0, sizeof(scale_dst)); + vcpu_device_attr_get(vcpus[0], KVM_VCPU_TSC_CTRL, KVM_VCPU_TSC_SCALE, + &scale_dst); + + raw_dst =3D host_to_guest_tsc(&scale_dst, 0, host_tsc_dst); + + for (i =3D 0; i < NR_VCPUS; i++) { + tsc_dst =3D tsc_src[i] + (u64)(delta_t * (__int128)freq_khz / 1000000); + ofs_dst[i] =3D tsc_dst - raw_dst; + vcpu_set_tsc_offset(vcpus[i], ofs_dst[i]); + } + + /* + * The cross-vCPU TSC relationships must be preserved exactly: + * every vCPU's offset moved by the same amount, so the deltas + * between them are untouched by the CLOCK_REALTIME imprecision. + */ + for (i =3D 1; i < NR_VCPUS; i++) { + s64 src_delta =3D (s64)(ofs_src[i] - ofs_src[0]); + s64 dst_delta =3D (s64)(ofs_dst[i] - ofs_dst[0]); + + pr_info(" vCPU%d-vCPU0 TSC delta: src %" PRId64 + ", dst %" PRId64 " cycles\n", i, src_delta, dst_delta); + TEST_ASSERT(src_delta =3D=3D dst_delta, + "vCPU%d TSC delta not preserved: %" PRId64 " -> %" PRId64, + i, src_delta, dst_delta); + } + + /* + * The TSC offset delta introduced by using CLOCK_REALTIME to + * estimate elapsed time. On same host, the correct offset is + * ofs_src; the difference is the CLOCK_REALTIME-vs-TSC error. + */ + s64 tsc_ofs_delta =3D (s64)(ofs_dst[0] - ofs_src[0]); + s64 tsc_ofs_delta_ns =3D tsc_ofs_delta * 1000000LL / freq_khz; + pr_info(" Destination TSC offset=3D%" PRId64 + ", imprecision from CLOCK_REALTIME: %" PRId64 " cycles =3D %" + PRId64 " ns\n", (s64)ofs_dst[0], tsc_ofs_delta, tsc_ofs_delta_ns); + + /* + * Step 8: KVM_SET_CLOCK_GUEST =E2=80=94 once, via vCPU0. The other + * vCPUs' clocks must come out right too: the KVM clock is + * VM-wide, and each vCPU's pvti relates it to that vCPU's + * own TSC. + */ + vcpu_set_clock_guest(vcpus[0], &pvti_src[0]); + + /* Run each guest to write its pvclock page on the destination */ + for (i =3D 0; i < NR_VCPUS; i++) + run_to_sync(vcpus[i]); + + /* Verify cross-vCPU coherence on the destination */ + for (i =3D 0; i < NR_VCPUS; i++) + vcpu_get_clock_guest(vcpus[i], &pvti_dst_ioctl[i]); + check_cross_vcpu_coherence(vm, vcpus, pvti_dst_ioctl, "dest"); + + /* ABA measurement on destination */ + u64 mono_lo, mono_hi; + aba_reading(vm, &mono_lo, &kvm_after, &mono_hi); + + /* + * The kvmclock is tied to the guest TSC via SET_CLOCK_GUEST. + * The guest TSC is offset from the correct value by tsc_ofs_delta_ns + * (due to CLOCK_REALTIME imprecision). So the kvmclock should be + * offset from CLOCK_MONOTONIC_RAW by exactly: + * (original delta) + tsc_ofs_delta_ns + * + * The "original delta" has uncertainty from the source ABA spread, + * and the measurement has uncertainty from the destination ABA spread. + * Verify the expected value falls within the combined bounds. + */ + s64 delta_before_lo =3D (s64)(kvm_before - src_mono_hi); + s64 delta_before_hi =3D (s64)(kvm_before - src_mono_lo); + s64 expected_lo =3D delta_before_lo + tsc_ofs_delta_ns; + s64 expected_hi =3D delta_before_hi + tsc_ofs_delta_ns; + s64 actual_lo =3D (s64)(kvm_after - mono_hi); + s64 actual_hi =3D (s64)(kvm_after - mono_lo); + + /* Show the shift relative to the source measurement */ + s64 expected_mid =3D tsc_ofs_delta_ns; + s64 expected_err =3D (s64)(src_mono_hi - src_mono_lo) / 2; + s64 actual_mid =3D ((actual_lo + actual_hi) / 2) - delta_before; + s64 actual_err =3D (s64)(mono_hi - mono_lo) / 2; + pr_info(" kvmclock-mono shift: expected %" PRId64 " ns (=C2=B1%" PRId64 + "), measured %" PRId64 " ns (=C2=B1%" PRId64 ")\n", + expected_mid, expected_err, actual_mid, actual_err); + + /* The ranges must overlap */ + TEST_ASSERT(expected_hi >=3D actual_lo && expected_lo <=3D actual_hi, + "Ranges don't overlap: expected [%" PRId64 ", %" PRId64 + "] measured [%" PRId64 ", %" PRId64 "]", + expected_lo, expected_hi, actual_lo, actual_hi); + + /* + * Direct pvclock verification: read each destination pvclock page + * (as written for the guest) and verify that computing kvmclock + * from the source pvti and the destination pvti at the same + * instant gives the same result, for every vCPU. + * + * Get one atomic {host_tsc, kvmclock} pair, derive each vCPU's + * guest TSC at that instant, then compute kvmclock from both + * pvclock structs. The source pvti evaluates at the *migrated* + * guest TSC, i.e. shifted by the CLOCK_REALTIME imprecision that + * was baked into the offsets =E2=80=94 which is exactly what "the clock + * follows the TSC" means. + */ + struct kvm_clock_data clock_now =3D {}; + vm_get_clock(vm, &clock_now); + pr_info(" KVM_GET_CLOCK: %" PRIu64 " ns\n", (u64)clock_now.clock); + + u64 host_tsc_now =3D clock_now.host_tsc; + + for (i =3D 0; i < NR_VCPUS; i++) { + struct pvclock_vcpu_time_info *pvti_page =3D + addr_gpa2hva(vm, KVMCLOCK_GPA + i * getpagesize()); + u64 guest_tsc_now =3D host_to_guest_tsc(&scale_dst, ofs_dst[i], + host_tsc_now); + u64 clk_from_src =3D __pvclock_read_cycles(&pvti_src[i], + guest_tsc_now); + u64 clk_from_dst =3D __pvclock_read_cycles(pvti_page, + guest_tsc_now); + s64 pvclock_delta =3D (s64)(clk_from_src - clk_from_dst); + + pr_info(" vCPU%d pvclock direct: src=3D%" PRIu64 " dst=3D%" PRIu64 + " delta=3D%" PRId64 " ns\n", i, clk_from_src, + clk_from_dst, pvclock_delta); + + TEST_ASSERT(pvclock_delta >=3D -2 && pvclock_delta <=3D 2, + "vCPU%d pvclock src vs dst disagree by %" PRId64 " ns", + i, pvclock_delta); + } + + /* + * Tight ABA: compare pvclock_read() directly (no ioctl) against + * CLOCK_MONOTONIC_RAW. The spread should be much smaller since + * there's no syscall between the two clock_gettime calls =E2=80=94 just + * rdtsc + userspace mul/shift. + */ + struct pvclock_vcpu_time_info *pvti0 =3D addr_gpa2hva(vm, KVMCLOCK_GPA); + u64 tight_mono_lo =3D 0, tight_mono_hi =3D 0, tight_kvm =3D 0; + u64 tight_best_spread =3D UINT64_MAX; + for (i =3D 0; i < 3; i++) { + struct timespec ts1, ts2; + u64 m1, m2, tsc, clk; + + clock_gettime(CLOCK_MONOTONIC_RAW, &ts1); + tsc =3D rdtsc(); + clock_gettime(CLOCK_MONOTONIC_RAW, &ts2); + + m1 =3D ts1.tv_sec * 1000000000ULL + ts1.tv_nsec; + m2 =3D ts2.tv_sec * 1000000000ULL + ts2.tv_nsec; + + /* Scale host TSC to vCPU0's guest TSC */ + tsc =3D host_to_guest_tsc(&scale_dst, ofs_dst[0], tsc); + + clk =3D __pvclock_read_cycles(pvti0, tsc); + + if (m2 - m1 < tight_best_spread) { + tight_best_spread =3D m2 - m1; + tight_mono_lo =3D m1; + tight_mono_hi =3D m2; + tight_kvm =3D clk; + } + } + pr_info(" Tight ABA spread: %" PRIu64 " ns (best of 3)\n", tight_best_sp= read); + + s64 tight_expected_lo =3D delta_before_lo + tsc_ofs_delta_ns; + s64 tight_expected_hi =3D delta_before_hi + tsc_ofs_delta_ns; + s64 tight_actual_lo =3D (s64)(tight_kvm - tight_mono_hi); + s64 tight_actual_hi =3D (s64)(tight_kvm - tight_mono_lo); + s64 tight_actual_mid =3D ((tight_actual_lo + tight_actual_hi) / 2) - delt= a_before; + s64 tight_actual_err =3D (s64)(tight_mono_hi - tight_mono_lo) / 2; + + pr_info(" Tight kvmclock-mono shift: expected %" PRId64 + " ns (=C2=B1%" PRId64 "), measured %" PRId64 " ns (=C2=B1%" PRId64 ")\n", + expected_mid, expected_err, tight_actual_mid, tight_actual_err); + + TEST_ASSERT(tight_expected_hi >=3D tight_actual_lo && + tight_expected_lo <=3D tight_actual_hi, + "Tight ABA ranges don't overlap"); + + kvm_vm_free(vm); + pr_info("PASS: kvmclock offset matches TSC delta from CLOCK_REALTIME" + " (%" PRId64 " ns) within ABA bounds\n", tsc_ofs_delta_ns); + return 0; +} --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=qkSMs01yvvSSq3e8VsPfZc6ccWPAWWj1I301FeFqA9f5T7kZeEalskzdFRTVA0VvP+E7 uvpemYG6dszIYj0fozr7BxRYD1i8AW0ZU9raZmagCG1U5agMkUKRyLJDCVZIhYYfEwIhX mS2eo9PtMC+pbcdMiWNJJrKOijV4C53pR5jM29my0yTkLoEWHIL23ex+urMjLKsQqeLIp 09m8BmWxZw1umBYFvBJGkRg9OAO/S7+aNalGFq1H1ucZMVY6eB4ycNn1zDcBh0B0uMq4d fCYLgXzqAKa5qQiBOZqajDKh07IQe+WhrRUBWG15jSFEEZEWG48P3gfmsiHv64iqlJQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=GdnbBhvrzYUipflvGAT/EG/9EgSypN3WFvXoLDRRsWY=; b=ct63BJi5bPrrV3K33MqZ61OJ6JrvE0ZVqe329pv6P+BzCVD4aHxs4bwlBjq67o6VXb62 13QWkXZORsrYWhdf5P0GV703p8XdgrxbjNkDfWFuO7vkRnt1rRr/CoXTMOp2bqjW2e+00 SpepMRkeEDBOQzr/5YHmDHwzKn0Ti+cwNj7O6ly3jbIMVrofjUGwEYydiA5Y/sAjADXJ3 mFGvJxdXJKU8gQOvSoicPvzDhElpsIh3MTC3VR8VmCNpRE6w02icbUMFmsReyQDXb4JwJ 07fnPbCwJySamPkRg3gQ+U4VkwasuZPHVRLDQWsUPoHT8Z0E4gyAwAbJBEgIadLi0UQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=HDEZT6oO; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E47A9606A326; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E47A9606A326 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=HDEZT6oO DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=GdnbBhvrzYUipflvGAT/EG/9EgSypN3WFvXoLDRRsWY=; b=HDEZT6oOyWC3YLyw/q57JyxYNP ipW46XfuTzaA8mRqPqAtsraRuk2E5KoarIv6v/1OXEDLrZdGX8RlJdWzNxJzzDKV8fNKylgdYg/zp J1jPEbwumgjyGpA4b4hWOI30PFic7FEwvFFIJUnAx2WSY4V8C/Q/J9Da57rGER89bTBh5auTR89f6 HZPrNLnWDNMDsoPwOq91pihhvxcGj/vuAD4C8jWFZpQQWhCnTq7qdeVN7jEiUoXJ3+gTkPPy0W/Pi 6b5dtl6HKuUW3G7By0qYBZC9bZWHoWuUOrJ99kyexdeuPc9ePUx8LV6ejp8y+QrFdJTLrW1Yf0Ca1 XI5kHu9Q==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKwD-3HVq; Wed, 11 Nov 2026 18:09:23 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtG-2Rhq; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 19/26] KVM: selftests: Add KVM/PV clock selftest to prove timer correction Date: Wed, 11 Nov 2026 10:09:15 -0800 Message-ID: <20261111180922.4177927-20-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: Jack Allister A VM's KVM/PV clock has an inherent relationship to its TSC. When either the host system live-updates or the VM is live-migrated this pairing of the two clock sources should stay the same. In reality this is not the case without some correction taking place. The KVM_GET_CLOCK_GUEST/KVM_SET_CLOCK_GUEST ioctls can be used to perform a correction on the PVTI (PV time information) structure held by KVM to effectively fix up the kvmclock_offset prior to the guest VM resuming in either a live-update/migration scenario. This test proves that without the necessary fixup there is a perceived change in the guest TSC and KVM/PV clock relationship before and after a simulated LU/LM takes place, and that the correction eliminates it. The test: 1. Snapshots the PVTI at boot (PVTI0). 2. Steps the KVM clock forward 10 seconds with KVM_SET_CLOCK and induces a change in PVTI data, so the divergence the correction must eliminate is deterministic. 3. Snapshots the PVTI after the change (PVTI1). 4. Requests correction via KVM_SET_CLOCK_GUEST using PVTI0. 5. Snapshots the PVTI after correction (PVTI2). Then samples the TSC at a single point in time and calculates the KVM clock using each PVTI snapshot, verifying that the uncorrected clock diverged and that the corrected clock matches the boot clock to within =C2=B12ns. Also test PVCLOCK_TSC_STABLE_BIT across matched, offset-mismatched and frequency-mismatched vCPUs, and KVM_[GS]ET_CLOCK_GUEST on vCPUs with divergent TSC offsets. The test enumerates multiple TSC frequencies from 1GHz to 5GHz at 500MHz steps, crossing the 32-bit boundary, to exercise the scaling path at various ratios. The sleep duration between snapshots is configurable via the -s/--sleep command line option. The divergent-offset test steps the VM clock forward between the GET and the SET and asserts the divergence, so a silently ignored SET cannot pass =E2=80=94 the same discrimination the single-vCPU path already has. The pvclock arithmetic and guest-side snapshot protocol come from the shared tools/arch/x86/include/asm/pvclock.h helpers, and only the scaled-frequency sweep and frequency-mismatch case require KVM_CAP_TSC_CONTROL; the correction and offset tests still run without hardware TSC scaling. Co-developed-by: David Woodhouse Signed-off-by: David Woodhouse Signed-off-by: Jack Allister Reviewed-by: Paul Durrant Cc: Dongli Zhang --- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../testing/selftests/kvm/x86/pvclock_test.c | 462 ++++++++++++++++++ 2 files changed, 463 insertions(+) create mode 100644 tools/testing/selftests/kvm/x86/pvclock_test.c diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selft= ests/kvm/Makefile.kvm index 18605318860e..15a1a8f64723 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -114,6 +114,7 @@ TEST_GEN_PROGS_x86 +=3D x86/pmu_event_filter_test TEST_GEN_PROGS_x86 +=3D x86/private_mem_conversions_test TEST_GEN_PROGS_x86 +=3D x86/private_mem_kvm_exits_test TEST_GEN_PROGS_x86 +=3D x86/pvclock_migration_test +TEST_GEN_PROGS_x86 +=3D x86/pvclock_test TEST_GEN_PROGS_x86 +=3D x86/save_restore_pf_stress_test TEST_GEN_PROGS_x86 +=3D x86/set_boot_cpu_id TEST_GEN_PROGS_x86 +=3D x86/set_sregs_test diff --git a/tools/testing/selftests/kvm/x86/pvclock_test.c b/tools/testing= /selftests/kvm/x86/pvclock_test.c new file mode 100644 index 000000000000..cb57f5e2bf1e --- /dev/null +++ b/tools/testing/selftests/kvm/x86/pvclock_test.c @@ -0,0 +1,462 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright =C2=A9 Amazon.com, Inc. or its affiliates. + * + * Tests for pvclock API + * KVM_SET_CLOCK_GUEST/KVM_GET_CLOCK_GUEST + */ +#include +#include +#include +#include +#include + +#include "test_util.h" +#include "kvm_util.h" +#include "processor.h" + +#include +#include + +static inline void pvti_snapshot(struct pvclock_vcpu_time_info *dst, + volatile struct pvclock_vcpu_time_info *src) +{ + const struct pvclock_vcpu_time_info *p =3D (void *)src; + u32 version; + + do { + version =3D pvclock_read_begin(p); + *dst =3D *p; + } while (pvclock_read_retry(p, version)); +} + +enum { + STAGE_FIRST_BOOT, + STAGE_UNCORRECTED, + STAGE_CORRECTED +}; + +#define KVMCLOCK_GPA 0xc0000000ull +#define KVMCLOCK_SIZE sizeof(struct pvclock_vcpu_time_info) + +static void trigger_pvti_update(void) +{ + /* + * Toggle between KVM's old and new system time methods to coerce KVM + * into updating the fields in the PV time info struct. + */ + wrmsr(MSR_KVM_SYSTEM_TIME, KVMCLOCK_GPA | KVM_MSR_ENABLED); + wrmsr(MSR_KVM_SYSTEM_TIME_NEW, KVMCLOCK_GPA | KVM_MSR_ENABLED); +} + +static void guest_code(void) +{ + struct pvclock_vcpu_time_info *pvti =3D + (void *)(unsigned long)KVMCLOCK_GPA; + struct pvclock_vcpu_time_info pvti_boot; + struct pvclock_vcpu_time_info pvti_uncorrected; + struct pvclock_vcpu_time_info pvti_corrected; + u64 tsc_guest; + u64 clk_boot, clk_uncorrected, clk_corrected; + s64 delta_corrected; + + /* Set up kvmclock and snapshot the initial pvclock parameters. */ + wrmsr(MSR_KVM_SYSTEM_TIME_NEW, KVMCLOCK_GPA | KVM_MSR_ENABLED); + pvti_snapshot(&pvti_boot, pvti); + GUEST_SYNC(STAGE_FIRST_BOOT); + + /* + * Trigger an update of the PVTI. Calculating the KVM clock using this + * updated structure will show a delta from the original. + */ + trigger_pvti_update(); + pvti_snapshot(&pvti_uncorrected, pvti); + GUEST_SYNC(STAGE_UNCORRECTED); + + /* + * Snapshot the corrected time (the host does KVM_SET_CLOCK_GUEST when + * handling STAGE_UNCORRECTED). + */ + pvti_snapshot(&pvti_corrected, pvti); + + /* + * Sample the TSC at a single point in time, then calculate the + * effective KVM clock using the PVTI from each stage. Verify that the + * corrected clock matches the boot clock to within =C2=B12ns. + */ + tsc_guest =3D rdtsc(); + + clk_boot =3D __pvclock_read_cycles(&pvti_boot, tsc_guest); + clk_uncorrected =3D __pvclock_read_cycles(&pvti_uncorrected, tsc_guest); + clk_corrected =3D __pvclock_read_cycles(&pvti_corrected, tsc_guest); + + /* + * The host stepped the KVM clock forward by 10 seconds at + * STAGE_FIRST_BOOT, so the uncorrected clock must diverge; without + * this, a no-op KVM_SET_CLOCK_GUEST would pass the test below. + */ + __GUEST_ASSERT((s64)(clk_uncorrected - clk_boot) > NSEC_PER_SEC, + "uncorrected clock did not diverge (boot=3D%lu uncorrected=3D%lu)= ", + clk_boot, clk_uncorrected); + + delta_corrected =3D clk_boot - clk_corrected; + + __GUEST_ASSERT(delta_corrected >=3D -2 && delta_corrected <=3D 2, + "corrected delta %ld out of range (boot=3D%lu uncorrected=3D%lu c= orrected=3D%lu)", + delta_corrected, clk_boot, clk_uncorrected, clk_corrected); + + GUEST_SYNC(STAGE_CORRECTED); +} + +static void run_test(struct kvm_vm *vm, struct kvm_vcpu *vcpu, + unsigned int sleep_sec) +{ + struct pvclock_vcpu_time_info pvti_before; + struct kvm_clock_data clock_step; + struct ucall uc; + + for (;;) { + vcpu_run(vcpu); + TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); + + switch (get_ucall(vcpu, &uc)) { + case UCALL_ABORT: + REPORT_GUEST_ASSERT(uc); + break; + case UCALL_SYNC: + break; + default: + TEST_FAIL("Unexpected ucall"); + } + + switch (uc.args[1]) { + case STAGE_FIRST_BOOT: + /* Save the pvclock parameters before the update. */ + vcpu_get_clock_guest(vcpu, &pvti_before); + + /* Sleep to let the clocks diverge. */ + sleep(sleep_sec); + + /* + * Step the KVM clock forward 10 seconds so that the + * divergence the correction must eliminate is + * deterministic, not at the mercy of accumulated + * drift during the sleep. + */ + vm_get_clock(vm, &clock_step); + clock_step.clock +=3D 10ull * NSEC_PER_SEC; + clock_step.flags =3D 0; + vm_set_clock(vm, &clock_step); + break; + + case STAGE_UNCORRECTED: + /* Restore the original pvclock parameters. */ + vcpu_set_clock_guest(vcpu, &pvti_before); + break; + + case STAGE_CORRECTED: + /* Guest verified the delta in-guest. */ + return; + + default: + TEST_FAIL("Unknown stage %lu", uc.args[1]); + } + } +} + +static void configure_pvclock(struct kvm_vm *vm) +{ + unsigned int nr_pages; + + nr_pages =3D vm_calc_num_guest_pages(VM_MODE_DEFAULT, getpagesize()); + vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, + KVMCLOCK_GPA, 1, nr_pages, 0); + virt_map(vm, KVMCLOCK_GPA, KVMCLOCK_GPA, nr_pages); +} + +static void run_at_frequency(u64 tsc_khz, unsigned int sleep_sec) +{ + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + + pr_info("Testing at TSC frequency %lu kHz\n", tsc_khz); + vm =3D vm_create_with_one_vcpu(&vcpu, guest_code); + configure_pvclock(vm); + vcpu_ioctl(vcpu, KVM_SET_TSC_KHZ, (void *)tsc_khz); + run_test(vm, vcpu, sleep_sec); + kvm_vm_free(vm); +} + +static void test_tsc_stable_bit(void); +static void test_clock_guest_with_offsets(void); + +static void usage(const char *name) +{ + printf("Usage: %s [options]\n" + " -s, --sleep SEC sleep duration between snapshots (default: = 2)\n" + " -h, --help show this help\n", name); +} + +int main(int argc, char *argv[]) +{ + static const struct option long_opts[] =3D { + { "sleep", required_argument, NULL, 's' }, + { "help", no_argument, NULL, 'h' }, + { NULL, 0, NULL, 0 }, + }; + unsigned int sleep_sec =3D 2; + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + u64 host_khz; + u64 freq; + int opt; + + while ((opt =3D getopt_long(argc, argv, "s:h", long_opts, NULL)) !=3D -1)= { + switch (opt) { + case 's': + sleep_sec =3D atoi_non_negative("sleep", optarg); + break; + case 'h': + default: + usage(argv[0]); + return opt =3D=3D 'h' ? 0 : 1; + } + } + + TEST_REQUIRE(sys_clocksource_is_based_on_tsc()); + TEST_REQUIRE(kvm_has_cap(KVM_CAP_CLOCK_GUEST)); + + vm =3D vm_create_with_one_vcpu(&vcpu, guest_code); + configure_pvclock(vm); + + /* First run at native frequency (no scaling). */ + run_test(vm, vcpu, sleep_sec); + + /* + * Then enumerate a range of TSC frequencies crossing the 32-bit + * boundary, to exercise the scaling path at various ratios. + */ + host_khz =3D __vcpu_ioctl(vcpu, KVM_GET_TSC_KHZ, NULL); + kvm_vm_free(vm); + + if (kvm_has_cap(KVM_CAP_TSC_CONTROL)) { + for (freq =3D 1000000; freq <=3D 5000000; freq +=3D 500000) { + if (freq =3D=3D host_khz) + continue; + run_at_frequency(freq, sleep_sec); + } + } else { + pr_info("Skipping scaled frequencies (no KVM_CAP_TSC_CONTROL)\n"); + } + + test_tsc_stable_bit(); + test_clock_guest_with_offsets(); + + return 0; +} + +static volatile u32 vcpu_counter; +static void guest_code_stable_bit(void) +{ + u32 idx =3D __atomic_fetch_add(&vcpu_counter, 1, __ATOMIC_SEQ_CST); + u64 gpa =3D KVMCLOCK_GPA + idx * KVMCLOCK_SIZE; + + wrmsr(MSR_KVM_SYSTEM_TIME_NEW, gpa | KVM_MSR_ENABLED); + GUEST_SYNC(0); + GUEST_SYNC(0); + GUEST_SYNC(0); +} + +static void run_vcpu_once(struct kvm_vcpu *vcpu) +{ + struct ucall uc; + + vcpu_run(vcpu); + TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); + switch (get_ucall(vcpu, &uc)) { + case UCALL_ABORT: + REPORT_GUEST_ASSERT(uc); + break; + case UCALL_SYNC: + break; + default: + TEST_FAIL("Unexpected ucall"); + } +} + +static void test_tsc_stable_bit(void) +{ + struct pvclock_vcpu_time_info pvti; + struct kvm_vcpu *vcpus[2]; + struct kvm_vm *vm; + int ret; + + pr_info("Testing PVCLOCK_TSC_STABLE_BIT with matched/unmatched TSCs\n"); + + vm =3D vm_create_with_vcpus(2, guest_code_stable_bit, vcpus); + configure_pvclock(vm); + + /* + * Case 1: All TSCs matched (same frequency and offset). + * Master clock should be active, PVCLOCK_TSC_STABLE_BIT set. + */ + run_vcpu_once(vcpus[0]); + + vcpu_get_clock_guest(vcpus[0], &pvti); + TEST_ASSERT(pvti.flags & PVCLOCK_TSC_STABLE_BIT, + "PVCLOCK_TSC_STABLE_BIT should be set with matched TSCs"); + + /* + * Case 2: Different TSC offset, same frequency. + * Master clock should still be active (frequency matches), but + * PVCLOCK_TSC_STABLE_BIT should be cleared (offsets differ). + */ + vcpu_set_tsc_offset(vcpus[1], 12345678); + run_vcpu_once(vcpus[1]); + run_vcpu_once(vcpus[0]); + + ret =3D __vcpu_get_clock_guest(vcpus[0], &pvti); + if (ret) { + /* + * Master clock disabled by offset mismatch =E2=80=94 old kernel. + * -ENODATA is the only legitimate reason to skip; anything + * else is a regression, not an old kernel. + */ + TEST_ASSERT(errno =3D=3D ENODATA, + "GET_CLOCK_GUEST failed with unexpected errno %d", errno); + pr_info(" Skipping offset test (master clock requires matched offsets)\= n"); + goto case_freq; + } + TEST_ASSERT(!(pvti.flags & PVCLOCK_TSC_STABLE_BIT), + "PVCLOCK_TSC_STABLE_BIT should be clear with offset-mismatched TSCs"= ); + +case_freq: + /* + * Case 3: Different TSC frequency. + * Master clock should be disabled entirely. + */ + if (!kvm_has_cap(KVM_CAP_TSC_CONTROL)) { + pr_info(" Skipping frequency-mismatch case (no KVM_CAP_TSC_CONTROL)\n"); + kvm_vm_free(vm); + return; + } + vcpu_ioctl(vcpus[1], KVM_SET_TSC_KHZ, + (void *)(unsigned long)(__vcpu_ioctl(vcpus[1], KVM_GET_TSC_KHZ, NULL)= / 2)); + /* Write TSC to trigger kvm_synchronize_tsc / kvm_track_tsc_matching */ + vcpu_set_msr(vcpus[1], MSR_IA32_TSC, 0); + run_vcpu_once(vcpus[1]); + + ret =3D __vcpu_get_clock_guest(vcpus[0], &pvti); + TEST_ASSERT(ret && errno =3D=3D ENODATA, + "GET_CLOCK_GUEST should fail with frequency-mismatched TSCs, got %d = (errno %d)", + ret, errno); + + kvm_vm_free(vm); +} + +static void test_clock_guest_with_offsets(void) +{ + struct pvclock_vcpu_time_info pvti0, pvti1, pvti1_after; + struct kvm_vcpu *vcpus[2]; + struct kvm_vm *vm; + s64 delta; + int ret; + + pr_info("Testing KVM_[GS]ET_CLOCK_GUEST with different TSC offsets\n"); + + vm =3D vm_create_with_vcpus(2, guest_code_stable_bit, vcpus); + configure_pvclock(vm); + + /* Set different TSC offsets on the two vCPUs */ + vcpu_set_tsc_offset(vcpus[0], 0); + vcpu_set_tsc_offset(vcpus[1], 1000000000ull); + + /* Run both to establish kvmclock */ + run_vcpu_once(vcpus[0]); + run_vcpu_once(vcpus[1]); + + /* GET_CLOCK_GUEST on both =E2=80=94 should succeed (master clock active)= */ + ret =3D __vcpu_get_clock_guest(vcpus[0], &pvti0); + if (ret) { + TEST_ASSERT(errno =3D=3D ENODATA, + "GET_CLOCK_GUEST failed with unexpected errno %d", errno); + pr_info(" Skipping (master clock requires matched offsets on this kerne= l)\n"); + kvm_vm_free(vm); + return; + } + vcpu_get_clock_guest(vcpus[1], &pvti1); + + /* The tsc_timestamps should differ (different offsets) */ + TEST_ASSERT(pvti0.tsc_timestamp !=3D pvti1.tsc_timestamp, + "tsc_timestamps should differ with different offsets"); + + /* + * Step the VM clock forward so that a silently ignored + * KVM_SET_CLOCK_GUEST cannot pass the delta check below: after + * the step, the uncorrected clock computed from pvti0 must + * diverge from the stepped clock, and only an applied SET + * restores the original timeline. + */ + { + struct kvm_clock_data clock_step; + + vm_get_clock(vm, &clock_step); + clock_step.clock +=3D 10ull * NSEC_PER_SEC; + clock_step.flags =3D 0; + vm_set_clock(vm, &clock_step); + } + + { + struct pvclock_vcpu_time_info pvti_stepped; + s64 diverged; + + vcpu_get_clock_guest(vcpus[0], &pvti_stepped); + diverged =3D (s64)(__pvclock_read_cycles(&pvti_stepped, + pvti_stepped.tsc_timestamp) - + __pvclock_read_cycles(&pvti0, + pvti_stepped.tsc_timestamp)); + TEST_ASSERT(diverged > (s64)NSEC_PER_SEC, + "clock did not diverge after step, got %ld ns", + diverged); + } + + /* Restore vcpu0's original clock */ + vcpu_set_clock_guest(vcpus[0], &pvti0); + + /* Run vcpu0 to process the clock update */ + run_vcpu_once(vcpus[0]); + + /* + * After SET on vcpu0, verify the correction worked by getting + * the clock on vcpu0 again. The mul/shift should be the same, + * and computing kvmclock at the same TSC should give the same + * result as the original (within =C2=B12ns). + */ + { + struct pvclock_vcpu_time_info pvti0_after; + u64 tsc_now, clk_from_old, clk_from_new; + + vcpu_get_clock_guest(vcpus[0], &pvti0_after); + + TEST_ASSERT(pvti0_after.tsc_to_system_mul =3D=3D pvti0.tsc_to_system_mul= && + pvti0_after.tsc_shift =3D=3D pvti0.tsc_shift, + "mul/shift changed across KVM_SET_CLOCK_GUEST"); + + tsc_now =3D pvti0_after.tsc_timestamp; + clk_from_old =3D __pvclock_read_cycles(&pvti0, tsc_now); + clk_from_new =3D __pvclock_read_cycles(&pvti0_after, tsc_now); + + delta =3D (s64)clk_from_new - (s64)clk_from_old; + TEST_ASSERT(delta >=3D -2 && delta <=3D 2, + "clock correction delta should be <=3D2ns, got %ld ns", + delta); + } + + /* + * Also verify that vcpu1's clock is still accessible (master + * clock still active with different offsets). + */ + vcpu_get_clock_guest(vcpus[1], &pvti1_after); + + kvm_vm_free(vm); +} --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=unlxx7mFZuMhXx02sZtqcrkRbPagJVOFmekEuO1PuArfaqyalx5zo4Ry8903e3rs+ytW FimOTk7oJF62KXhXULEFTjTRlhDPaiMlYZEuCRKRX7GrFLpSe4asX0Sw4yllT0F/EAYUA diLnho4/EUS0Xa40pIDvX0ffkFbw8WUezM4IBKKBL7dvUXqHTG1LiV6HzN2rpaULpSyJ1 UyqsQNQ2HWSrl8r2Wrj0J5jL3YslsT+9ZZcRGhvfADAMovHF8quxdmbyBJVzsLRNIdDhW 4GqG1FumkX5a0Zctzo/NnYi7p61u/4pdcVL9nqOxGGSwwI3aV+GS0L7Jtu5VTa2AT/Q== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=O1JSbo6dSmTIhtBA7w37syORnO0n3Px43xR/cCKp3Ls=; b=Q15iBFOCycAQhfuOjRJ2LNIDdt6l6YAbrb9j+RKUP8OVOwOd0gjzdS6/wVoOrAq+2g0C R9Bh7YqE8b+3EBUcFMeaqS6b0hHykKZMLcW6R26kObpW4EYTZv110T/M3JKLjMLsnDKX2 gdeG8gLpAdDpyGIVnL1GkwuVXdE786/Takec5uiP4kv3mv64Y4/nxb+2yfigPheiyauhf 1ISdDrEPzgIqHG2mz/STY82dA9f2/bKQW9UdzipeXebUpsdqxiGSwFogtNRz9gp1JivBD 74Kzt7WOszSAEHdJbOYpIWbhnP34r3shYIibN07kAnDamHQkmsTI8LzLoqm67p0EdvQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=dF+Qcltt; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E4807606A32A; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E4807606A32A Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=dF+Qcltt DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=O1JSbo6dSmTIhtBA7w37syORnO0n3Px43xR/cCKp3Ls=; b=dF+QclttGB67d05ZX6xmyNH9Ee A7i8Y/K5tS7G7dHg2HYXybS1iMzjpS6NO86Ex8A9na/dr4IsVdb5PPT15TNx7oxv0oUit7UTdXIEF Z4DXMTYafIaajHYREMsk1wGYAqXWx89lOXxztRt5QQlx1zcQglsM4+H2S1Fk1OY7f4oAfGysIHe59 nKLwAzaW8ujFQrXcJYeV8mnxo/z6RHweT6OMtpHM0EsrvdyF9jG9ebJaYkvo5p0Ibkpm0QWa2wn1B 3NdLhWvLmD13ZCO7YrUqM9jonW20nnxYCYJFHIuOyMOpsTXTXhrzfVKhaT7sfh6T4reNZQhuHvjbw IIjUXJmg==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKwL-3SfK; Wed, 11 Nov 2026 18:09:24 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtK-2d6D; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 20/26] KVM: selftests: Add master clock offset test Date: Wed, 11 Nov 2026 10:09:16 -0800 Message-ID: <20261111180922.4177927-21-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Verify that KVM master clock mode remains active when vCPUs have different TSC offsets but the same frequency. Creates three vCPUs, sets one to a different TSC value, and confirms: - KVM_CLOCK_HOST_TSC is set (master clock active) - KVM_CLOCK_TSC_STABLE IS set (master clock =E2=87=92 stable flag) - PVCLOCK_TSC_STABLE_BIT is NOT set (offsets differ) Then set the KVM clock forward one hour with KVM_SET_CLOCK and verify that all vCPUs still agree on the KVM clock computed from their own pvclock parameters. This remains a separate binary from pvclock_test deliberately: the rdtsc()-plus-offset arithmetic here is exact only at the default host frequency, while pvclock_test sweeps scaled frequencies, and the two must not inherit each other's constraints. Signed-off-by: David Woodhouse --- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../kvm/x86/masterclock_offset_test.c | 249 ++++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 tools/testing/selftests/kvm/x86/masterclock_offset_test= .c diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selft= ests/kvm/Makefile.kvm index 15a1a8f64723..4d4eff41c525 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -95,6 +95,7 @@ TEST_GEN_PROGS_x86 +=3D x86/hyperv_tlb_flush TEST_GEN_PROGS_x86 +=3D x86/kvm_clock_test TEST_GEN_PROGS_x86 +=3D x86/kvm_pv_test TEST_GEN_PROGS_x86 +=3D x86/kvm_buslock_test +TEST_GEN_PROGS_x86 +=3D x86/masterclock_offset_test TEST_GEN_PROGS_x86 +=3D x86/monitor_mwait_test TEST_GEN_PROGS_x86 +=3D x86/msrs_test TEST_GEN_PROGS_x86 +=3D x86/nested_close_kvm_test diff --git a/tools/testing/selftests/kvm/x86/masterclock_offset_test.c b/to= ols/testing/selftests/kvm/x86/masterclock_offset_test.c new file mode 100644 index 000000000000..7d0fe97cedc4 --- /dev/null +++ b/tools/testing/selftests/kvm/x86/masterclock_offset_test.c @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Test that KVM master clock mode works with different TSC offsets + * as long as all vCPUs have the same TSC frequency. + */ +#include + +#include "test_util.h" +#include "kvm_util.h" +#include "processor.h" + +#include +#include + +#define KVMCLOCK_GPA 0xc0000000ull +#define TSC_OFFSET (1000000000ULL) + +#define NR_VCPUS 3 + +/* Read the per-vCPU pvclocks in an order other than creation order. */ +static const int vcpu_order[NR_VCPUS] =3D {0, 2, 1}; + +static void guest_code(u64 pvti_gpa) +{ + wrmsr(MSR_KVM_SYSTEM_TIME_NEW, pvti_gpa | KVM_MSR_ENABLED); + for (;;) + GUEST_SYNC(0); +} + +static void get_pvtis(struct kvm_vcpu **vcpus, + struct pvclock_vcpu_time_info *pvti) +{ + int i; + + for (i =3D 0; i < NR_VCPUS; i++) { + int idx =3D vcpu_order[i]; + + vcpu_get_clock_guest(vcpus[idx], &pvti[idx]); + pr_info("vCPU %d: tsc_timestamp=3D%lu system_time=3D%lu " + "mul=3D%u shift=3D%d flags=3D0x%x\n", + idx, (unsigned long)pvti[idx].tsc_timestamp, + (unsigned long)pvti[idx].system_time, + pvti[idx].tsc_to_system_mul, pvti[idx].tsc_shift, + pvti[idx].flags); + } +} + +static void run_all_vcpus(struct kvm_vcpu **vcpus) +{ + int i; + + for (i =3D 0; i < NR_VCPUS; i++) { + vcpu_run(vcpus[vcpu_order[i]]); + TEST_ASSERT_KVM_EXIT_REASON(vcpus[vcpu_order[i]], KVM_EXIT_IO); + } +} + +/* + * The guest-visible pvclock pages must carry exactly what the ioctl + * reports: in master clock mode both are derived from the same master + * snapshot. Requires every vCPU to have run since the last masterclock + * update, so the pages are written from the settled snapshot. + */ +static void assert_guest_pages_match(struct kvm_vm *vm, + struct pvclock_vcpu_time_info *pvti, + const char *what) +{ + int i; + + for (i =3D 0; i < NR_VCPUS; i++) { + struct pvclock_vcpu_time_info *guest_pvti =3D + addr_gpa2hva(vm, KVMCLOCK_GPA + i * + sizeof(struct pvclock_vcpu_time_info) * 2); + + TEST_ASSERT(guest_pvti->tsc_timestamp =3D=3D pvti[i].tsc_timestamp && + guest_pvti->system_time =3D=3D pvti[i].system_time && + guest_pvti->tsc_to_system_mul =3D=3D pvti[i].tsc_to_system_mul && + guest_pvti->tsc_shift =3D=3D pvti[i].tsc_shift, + "%s: vCPU%d guest page pvclock should match KVM_GET_CLOCK_GUEST", + what, i); + } +} + +/* + * Read the host TSC once and feed it through each vCPU's pvclock + * (adding each vCPU's TSC offset). All must compute exactly the same + * kvmclock value. + */ +static void assert_pvclocks_match(struct pvclock_vcpu_time_info *pvti, + u64 offset0, const char *what) +{ + u64 host_tsc, clk0, clk1, clk2; + + host_tsc =3D rdtsc(); + clk0 =3D __pvclock_read_cycles(&pvti[0], host_tsc + offset0); + clk1 =3D __pvclock_read_cycles(&pvti[1], host_tsc + offset0); + clk2 =3D __pvclock_read_cycles(&pvti[2], host_tsc + offset0 + TSC_OFFSET); + + pr_info("%s: kvmclock via vCPU 0: %lu ns, vCPU 1: %lu ns, vCPU 2: %lu ns\= n", + what, (unsigned long)clk0, (unsigned long)clk1, + (unsigned long)clk2); + TEST_ASSERT(clk0 =3D=3D clk1 && clk0 =3D=3D clk2, + "%s: kvmclock from all vCPUs should match exactly " + "(0: %lu, 1: %lu, 2: %lu)", what, (unsigned long)clk0, + (unsigned long)clk1, (unsigned long)clk2); +} + +static void test_masterclock_active(struct kvm_vm *vm, + struct kvm_clock_data *clock) +{ + memset(clock, 0, sizeof(*clock)); + vm_get_clock(vm, clock); + pr_info("KVM_GET_CLOCK flags: 0x%x\n", clock->flags); + TEST_ASSERT(clock->flags & KVM_CLOCK_HOST_TSC, + "Master clock should be active, flags=3D0x%x", clock->flags); + TEST_ASSERT(clock->flags & KVM_CLOCK_TSC_STABLE, + "KVM_CLOCK_TSC_STABLE should be set, flags=3D0x%x", + clock->flags); +} + +static void test_offset_consistency(struct kvm_vcpu **vcpus, + struct pvclock_vcpu_time_info *pvti, + u64 offset0) +{ + u64 gtsc0, gtsc1, gtsc2; + + get_pvtis(vcpus, pvti); + + /* Read guest TSCs: should see (0+OFF) < 2 < (1+OFF) */ + gtsc0 =3D vcpu_get_msr(vcpus[0], MSR_IA32_TSC); + gtsc2 =3D vcpu_get_msr(vcpus[2], MSR_IA32_TSC); + gtsc1 =3D vcpu_get_msr(vcpus[1], MSR_IA32_TSC); + pr_info("Guest TSCs: vcpu0=3D%lu vcpu2=3D%lu vcpu1=3D%lu\n", + (unsigned long)gtsc0, (unsigned long)gtsc2, + (unsigned long)gtsc1); + TEST_ASSERT(gtsc0 + TSC_OFFSET < gtsc2 && gtsc2 < gtsc1 + TSC_OFFSET, + "Expected (vcpu0+OFF) < vcpu2 < (vcpu1+OFF)"); + + /* PVCLOCK_TSC_STABLE_BIT should NOT be set (offsets differ) */ + TEST_ASSERT(!(pvti[2].flags & PVCLOCK_TSC_STABLE_BIT), + "PVCLOCK_TSC_STABLE_BIT should NOT be set, flags=3D0x%x", + pvti[2].flags); + + /* Same mul/shift */ + TEST_ASSERT(pvti[0].tsc_to_system_mul =3D=3D pvti[1].tsc_to_system_mul && + pvti[0].tsc_to_system_mul =3D=3D pvti[2].tsc_to_system_mul && + pvti[0].tsc_shift =3D=3D pvti[1].tsc_shift && + pvti[0].tsc_shift =3D=3D pvti[2].tsc_shift, + "All vCPUs should have same mul/shift"); + + assert_pvclocks_match(pvti, offset0, "Initial"); +} + +#define ONE_HOUR_NS (3600ULL * NSEC_PER_SEC) + +static void test_set_clock_consistency(struct kvm_vm *vm, + struct kvm_vcpu **vcpus, + struct pvclock_vcpu_time_info *pvti, + struct kvm_clock_data *clock, + u64 offset0) +{ + struct kvm_clock_data setclk =3D { .clock =3D clock->clock + ONE_HOUR_NS = }; + u64 clk0; + + /* + * Add an hour to the VM kvmclock via KVM_SET_CLOCK, run each + * vCPU to pick up the update, and check they're still in sync. + */ + vm_set_clock(vm, &setclk); + + /* + * KVM_SET_CLOCK refreshes the master snapshot synchronously and + * broadcasts a clock update, so a single pass rewrites every + * guest pvclock page from the settled snapshot. Run two passes + * anyway, so this flow doesn't silently depend on that: after a + * per-vCPU write which parks a masterclock update on one vCPU + * (as the TSC-offset writes in main() do), the first pass + * services it and only the second rewrites every page. + */ + run_all_vcpus(vcpus); + run_all_vcpus(vcpus); + + get_pvtis(vcpus, pvti); + assert_guest_pages_match(vm, pvti, "After +1h"); + + TEST_ASSERT(pvti[0].system_time =3D=3D pvti[1].system_time && + pvti[0].system_time =3D=3D pvti[2].system_time, + "system_time should still match after KVM_SET_CLOCK"); + + assert_pvclocks_match(pvti, offset0, "After +1h"); + + /* Verify the clock actually moved by ~1 hour */ + clk0 =3D __pvclock_read_cycles(&pvti[0], rdtsc() + offset0); + TEST_ASSERT(clk0 > ONE_HOUR_NS, + "Clock should be > 1 hour after set, got %lu ns", + (unsigned long)clk0); +} + +int main(void) +{ + struct pvclock_vcpu_time_info pvti[NR_VCPUS]; + struct kvm_vcpu *vcpus[NR_VCPUS]; + struct kvm_clock_data clock; + struct kvm_vm *vm; + u64 offset0; + int nr_pages; + int i; + + TEST_REQUIRE(sys_clocksource_is_based_on_tsc()); + TEST_REQUIRE(kvm_has_cap(KVM_CAP_CLOCK_GUEST)); + + vm =3D vm_create_with_vcpus(NR_VCPUS, guest_code, vcpus); + + TEST_REQUIRE(!__vcpu_has_device_attr(vcpus[0], KVM_VCPU_TSC_CTRL, + KVM_VCPU_TSC_OFFSET)); + + nr_pages =3D vm_calc_num_guest_pages(VM_MODE_DEFAULT, getpagesize()); + vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, + KVMCLOCK_GPA, 1, nr_pages, 0); + + /* Give each vCPU its own pvclock structure within the page */ + for (i =3D 0; i < NR_VCPUS; i++) + vcpu_args_set(vcpus[i], 1, KVMCLOCK_GPA + + i * sizeof(struct pvclock_vcpu_time_info) * 2); + + /* Get vCPU 0's default offset and set vCPU 2's offset higher */ + offset0 =3D vcpu_get_tsc_offset(vcpus[0]); + vcpu_set_tsc_offset(vcpus[2], offset0 + TSC_OFFSET); + + /* + * Run each vCPU twice to enable kvmclock (with the offset already + * set): the first pass services the masterclock update requested + * by the offset write, the second rewrites every guest pvclock + * page from the settled snapshot. + */ + run_all_vcpus(vcpus); + run_all_vcpus(vcpus); + + test_masterclock_active(vm, &clock); + test_offset_consistency(vcpus, pvti, offset0); + assert_guest_pages_match(vm, pvti, "Initial"); + pr_info("PASSED: pvclock consistent across offset vCPUs\n"); + + test_set_clock_consistency(vm, vcpus, pvti, &clock, offset0); + pr_info("PASSED: pvclock still consistent after KVM_SET_CLOCK +1h\n"); + + kvm_vm_free(vm); + return 0; +} --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=ofQj6whpgweKxa1OUOHoOZ8b9cZ4LJBNVpzMqWVQdesbhb57CBN7ULZPKq2KpzgIKsjk N3IUwBIbdOtUEtK5R7i7qnjV/zkSVjuDvHk5TEtZ+V/iLAcqWNJ/9pyy1uqDLCKIXEIMI W3Q/gen5tQ/BzbvRw2MnUfaANhjYS4R0DVhg/5qhOv89eQEoaozijJS/B6GfBgfzRMlE9 GoNpawiVzugBEaMzoIB4HkKwjVPo8bSPANze/5lSGh8fcdGdMO+5k3u9xZucSQnIEKHMK yf5ccb6CvLt57I2mIpaOry1uDn/C1rtl9N8xzJUww/dqYYWZ8PaFVQa3bTXeU7PNo/g== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=cXjQZKqIl2OYPcFHIBDb+bTEqqXL97xMp1LRSEJsias=; b=VIUKEfHGE7JMKNLXuZazj+d54AkJsh38TQN2lEBaOGkIK7TDnVByFf/SricOnaDE8MFC N0F476RQkkeIzB8NoEeGyQ2W+hBv4AyDISNY4dfSLLNW1BGjDVMRkRlqTx01hSHaF+l8T N1Qf62ubAAauCfXh+e6RPy4qpbVBveFidEFWXmmAszRILYj4OmxjGalDsSqmjA0WMOUfv PTLqSiM8NwF5l1uB6y1ZDVBi3KZNF5JRJCiF5LWAoQ0bWCGbLYLosu/LaBx5n6BLCxZXG C/9VXBvUHMBnd8Y724GS6xYp2W9r+3Oyf+ln5yR60yE+78udg+fIynsNnXIm4VLgpxQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=aEYDQ803; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 115FD606B7B0; Wed, 11 Nov 2026 18:09:37 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 115FD606B7B0 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=aEYDQ803 DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=cXjQZKqIl2OYPcFHIBDb+bTEqqXL97xMp1LRSEJsias=; b=aEYDQ803CRaehE4cut3cAiMuGk plgaJ+v+zciptCjVs+y7SKylPtGeqiFg6EyAFTILn+LQ8SPH6IggBpbvP/pVChFgXGCgsxrUIMM6z sJbBUr1S7vcqfLaYQYa9QMperqX8B8E9llZOTBrgmSknUi+PY0QhsR0D0eLuWxB9RJD785TPl8b0k Xnfk/zjsWJbw81WfvsgzsOOPmR+8/OUdJXM7J9a37peSj9IS+cEEPCs0f9rf0uoq6YWgofBS7dxVy WBjdAz/8KiPxEtAPEferIrkBBOPfbHjofdzbjNeVsEuMmqaBiNy9q79bPRlIciywVYVI/c5qg8jHF 8OBYFeFQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvT-3DMi; Wed, 11 Nov 2026 18:09:30 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtO-2oOe; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 21/26] KVM: selftests: Add Xen/generic CPUID timing leaf test Date: Wed, 11 Nov 2026 10:09:17 -0800 Message-ID: <20261111180922.4177927-22-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Verify that userspace can correctly populate Xen and generic CPUID timing leaves using the KVM_GET_TSC_KHZ ioctl and KVM_VCPU_TSC_SCALE attribute. This validates that commit 7d3bd21e457b ("KVM: x86: Remove runtime Xen TSC frequency CPUID update") doesn't break guests: userspace queries the effective TSC and bus frequencies, computes the pvclock mul/shift, populates the CPUID leaves, and the guest verifies the values match. The test exercises: - KVM_GET_TSC_KHZ at native and scaled frequencies - KVM_VCPU_TSC_SCALE ratio verification against effective frequency - Generic timing leaf 0x40000010 (EAX=3Dtsc_khz, EBX=3Dbus_khz) - Xen leaf 3 sub-leaf 0 (ECX=3Dguest TSC kHz) - Xen leaf 3 sub-leaf 1 (ECX=3Dmul, EDX=3Dshift) Where KVM_CAP_XEN_HVM is available, the guest is given the Xen signature leaf and the Xen hypercall MSR is enabled =E2=80=94 the exact configuration in which the removed runtime update used to fire =E2=80=94 and a sentinel is planted in leaf 3 sub-leaf 2 EAX, where it used to write, which the guest verifies survives untouched. The scaled runs are skipped on hardware without TSC scaling. For a requested frequency within tsc_tolerance_ppm of the host's (where no scaling engages and the ratio stays identity), only the ratio cross-check is skipped, and the skip is gated on the frequencies themselves =E2=80=94 read from the kernel's actual tsc_tolerance_ppm =E2=80= =94 not on the reported ratio, which is exactly what a broken KVM would get wrong. Results go through the kselftest TAP machinery, a fixed plan of five. Signed-off-by: David Woodhouse --- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../selftests/kvm/x86/xen_cpuid_timing_test.c | 293 ++++++++++++++++++ 2 files changed, 294 insertions(+) create mode 100644 tools/testing/selftests/kvm/x86/xen_cpuid_timing_test.c diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selft= ests/kvm/Makefile.kvm index 4d4eff41c525..79d26de18bf3 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -152,6 +152,7 @@ TEST_GEN_PROGS_x86 +=3D x86/xss_msr_test TEST_GEN_PROGS_x86 +=3D x86/debug_regs TEST_GEN_PROGS_x86 +=3D x86/tsc_msrs_test TEST_GEN_PROGS_x86 +=3D x86/vmx_pmu_caps_test +TEST_GEN_PROGS_x86 +=3D x86/xen_cpuid_timing_test TEST_GEN_PROGS_x86 +=3D x86/xen_shinfo_test TEST_GEN_PROGS_x86 +=3D x86/xen_vmcall_test TEST_GEN_PROGS_x86 +=3D x86/sev_dbg_test diff --git a/tools/testing/selftests/kvm/x86/xen_cpuid_timing_test.c b/tool= s/testing/selftests/kvm/x86/xen_cpuid_timing_test.c new file mode 100644 index 000000000000..33b5300efa03 --- /dev/null +++ b/tools/testing/selftests/kvm/x86/xen_cpuid_timing_test.c @@ -0,0 +1,293 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Test that userspace can correctly populate Xen and generic CPUID + * timing leaves using KVM_GET_TSC_KHZ and KVM_VCPU_TSC_SCALE. + * + * This validates that the removal of KVM's runtime Xen CPUID modification + * doesn't break guests, because userspace has all the information needed. + */ +#include +#include +#include + +#include "test_util.h" +#include "kvm_util.h" +#include "processor.h" + + +#define XEN_CPUID_BASE 0x40000100 +#define XEN_CPUID_LEAF(n) (XEN_CPUID_BASE + (n)) +#define GENERIC_TIMING_LEAF 0x40000010 + +/* + * Sentinel in Xen leaf 3 sub-leaf 2 EAX (where the removed runtime + * update used to write the vCPU's tsc_khz): it must survive untouched. + */ +#define XEN_SENTINEL 0xdeadbeef + +/* Values set by host, verified by guest */ +static u32 expected_tsc_khz; +static u32 expected_bus_khz; +static u32 expected_tsc_mul; +static s8 expected_tsc_shift; +static u64 host_khz; +static bool xen_enabled; + +static void guest_code(void) +{ + u32 eax, ebx, ecx, edx; + + /* Check generic timing leaf 0x40000010 */ + __cpuid(GENERIC_TIMING_LEAF, 0, &eax, &ebx, &ecx, &edx); + GUEST_ASSERT_EQ(eax, expected_tsc_khz); + GUEST_ASSERT_EQ(ebx, expected_bus_khz); + + /* Check Xen leaf 3, sub-leaf 0: ECX =3D guest TSC frequency */ + __cpuid(XEN_CPUID_LEAF(3), 0, &eax, &ebx, &ecx, &edx); + GUEST_ASSERT_EQ(ecx, expected_tsc_khz); + + /* Check Xen leaf 3, sub-leaf 1: ECX =3D mul, EDX =3D shift */ + __cpuid(XEN_CPUID_LEAF(3), 1, &eax, &ebx, &ecx, &edx); + GUEST_ASSERT_EQ(ecx, expected_tsc_mul); + GUEST_ASSERT_EQ((s8)edx, expected_tsc_shift); + + if (xen_enabled) { + /* + * With the Xen signature present and Xen enabled, verify the + * sentinel survives: KVM's removed runtime CPUID update used + * to clobber this sub-leaf for exactly this configuration. + */ + __cpuid(XEN_CPUID_LEAF(3), 2, &eax, &ebx, &ecx, &edx); + GUEST_ASSERT_EQ(eax, XEN_SENTINEL); + } + + GUEST_SYNC(0); +} + +static void add_cpuid_entry(struct kvm_vcpu *vcpu, u32 function, + u32 index, u32 eax, u32 ebx, + u32 ecx, u32 edx) +{ + struct kvm_cpuid2 *cpuid =3D vcpu->cpuid; + struct kvm_cpuid_entry2 *entry; + int n =3D cpuid->nent; + + cpuid =3D realloc(vcpu->cpuid, + sizeof(*cpuid) + (n + 1) * sizeof(*entry)); + TEST_ASSERT(cpuid, "Failed to grow vCPU CPUID array"); + vcpu->cpuid =3D cpuid; + cpuid->nent =3D n + 1; + + entry =3D &cpuid->entries[n]; + memset(entry, 0, sizeof(*entry)); + entry->function =3D function; + entry->index =3D index; + entry->flags =3D KVM_CPUID_FLAG_SIGNIFCANT_INDEX; + entry->eax =3D eax; + entry->ebx =3D ebx; + entry->ecx =3D ecx; + entry->edx =3D edx; +} + +/* + * Compute pvclock mul/shift from frequency, matching kvm_get_time_scale(). + */ +static void compute_tsc_mul_shift(u64 tsc_hz, u32 *mul, s8 *shift) +{ + u64 scaled =3D 1000000000ULL; + u64 base =3D tsc_hz; + s32 s =3D 0; + u32 base32; + + while (base > scaled * 2 || base >> 32) { + base >>=3D 1; + s--; + } + base32 =3D (u32)base; + while (base32 <=3D scaled || scaled >> 32) { + if (scaled >> 32 || base32 & (1U << 31)) + scaled >>=3D 1; + else + base32 <<=3D 1; + s++; + } + *mul =3D (u32)((scaled << 32) / base32); + *shift =3D (s8)s; +} + +static void run_test(u64 tsc_khz) +{ + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + struct ucall uc; + u32 effective_tsc_khz, effective_bus_khz; + int bus_cycle_ns, ret; + + vm =3D vm_create_with_one_vcpu(&vcpu, guest_code); + + if (tsc_khz) { + pr_info("Testing at TSC frequency %lu kHz\n", tsc_khz); + vcpu_ioctl(vcpu, KVM_SET_TSC_KHZ, (void *)(unsigned long)tsc_khz); + } else { + pr_info("Testing at native TSC frequency\n"); + } + + ret =3D __vcpu_ioctl(vcpu, KVM_GET_TSC_KHZ, NULL); + TEST_ASSERT(ret > 0, "KVM_GET_TSC_KHZ failed: %d", ret); + effective_tsc_khz =3D ret; + bus_cycle_ns =3D vm_check_cap(vm, KVM_CAP_X86_APIC_BUS_CYCLES_NS); + effective_bus_khz =3D bus_cycle_ns > 0 ? 1000000 / bus_cycle_ns : 1000000; + + pr_info(" Effective TSC: %u kHz, Bus: %u kHz\n", effective_tsc_khz, effe= ctive_bus_khz); + + /* Also exercise KVM_VCPU_TSC_SCALE if available */ + if (!__vcpu_has_device_attr(vcpu, KVM_VCPU_TSC_CTRL, + KVM_VCPU_TSC_SCALE)) { + struct kvm_vcpu_tsc_scale scale; + + vcpu_device_attr_get(vcpu, KVM_VCPU_TSC_CTRL, + KVM_VCPU_TSC_SCALE, &scale); + pr_info(" TSC scale: ratio=3D%llu frac_bits=3D%llu\n", + scale.tsc_ratio, scale.tsc_frac_bits); + + /* + * A requested frequency within tsc_tolerance_ppm of the + * host's does not engage hardware scaling: the effective + * frequency is the requested one but the ratio stays 1.0, + * so the ratio cross-check cannot hold. Skip only that + * check =E2=80=94 the CPUID leaf population and guest verification + * below are about the effective frequency and remain valid. + * + * Judge "within tolerance" from the frequencies, not from + * the reported ratio: an identity ratio for a frequency + * far outside tolerance is exactly the regression the + * cross-check exists to catch, and must not take the skip + * path. Read the kernel's actual tsc_tolerance_ppm, and + * compute the bounds exactly as kvm_set_tsc_khz() does + * (multiply then truncate), so the window matches even at + * its edges and when the parameter has been tuned. + */ + u64 tol_ppm =3D get_kvm_param_integer("tsc_tolerance_ppm"); + u64 thresh_lo =3D host_khz * (1000000 - tol_ppm) / 1000000; + u64 thresh_hi =3D host_khz * (1000000 + tol_ppm) / 1000000; + bool within_tol =3D tsc_khz >=3D thresh_lo && + tsc_khz <=3D thresh_hi; + + if (tsc_khz && within_tol && + scale.tsc_ratio =3D=3D (1ULL << scale.tsc_frac_bits)) { + pr_info(" Requested frequency within host tolerance; scaling not engag= ed, skipping ratio cross-check\n"); + } else if (tsc_khz) { + /* + * Verify: applying the ratio to the host TSC frequency + * should give approximately the effective frequency. + */ + u64 computed =3D ((__uint128_t)host_khz * scale.tsc_ratio) >> scale.tsc= _frac_bits; + s64 diff =3D (s64)computed - (s64)effective_tsc_khz; + + TEST_ASSERT(diff >=3D -1 && diff <=3D 1, + "TSC_SCALE ratio mismatch: computed %lu vs effective %u (diff %ld)= ", + computed, effective_tsc_khz, diff); + } + } + + compute_tsc_mul_shift((u64)effective_tsc_khz * 1000, + &expected_tsc_mul, &expected_tsc_shift); + + expected_tsc_khz =3D effective_tsc_khz; + expected_bus_khz =3D effective_bus_khz; + + sync_global_to_guest(vm, expected_tsc_khz); + sync_global_to_guest(vm, expected_bus_khz); + sync_global_to_guest(vm, expected_tsc_mul); + sync_global_to_guest(vm, expected_tsc_shift); + + /* Populate CPUID leaves as a VMM would */ + add_cpuid_entry(vcpu, GENERIC_TIMING_LEAF, 0, + effective_tsc_khz, effective_bus_khz, 0, 0); + add_cpuid_entry(vcpu, XEN_CPUID_LEAF(3), 0, + 0, 0, effective_tsc_khz, 0); + add_cpuid_entry(vcpu, XEN_CPUID_LEAF(3), 1, + 0, 0, expected_tsc_mul, + (u32)(s32)expected_tsc_shift); + + /* + * Where possible, make this a real Xen guest: install the Xen + * signature leaf and enable the Xen hypercall MSR, which is the + * configuration in which KVM's removed runtime CPUID update used + * to fire, and plant a sentinel where it used to write. + */ + xen_enabled =3D kvm_has_cap(KVM_CAP_XEN_HVM); + if (xen_enabled) { + struct kvm_xen_hvm_config cfg =3D { + .msr =3D 0x40000200, + }; + + vm_ioctl(vm, KVM_XEN_HVM_CONFIG, &cfg); + add_cpuid_entry(vcpu, XEN_CPUID_BASE, 0, XEN_CPUID_LEAF(4), + 0x566e6558 /* "XenV" */, + 0x65584d4d /* "MMXe" */, + 0x4d4d566e /* "nVMM" */); + add_cpuid_entry(vcpu, XEN_CPUID_LEAF(3), 2, + XEN_SENTINEL, 0, 0, 0); + } + sync_global_to_guest(vm, xen_enabled); + + vcpu_set_cpuid(vcpu); + + pr_info(" pvclock mul=3D%u shift=3D%d\n", expected_tsc_mul, expected_tsc= _shift); + + vcpu_run(vcpu); + TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); + + switch (get_ucall(vcpu, &uc)) { + case UCALL_ABORT: + REPORT_GUEST_ASSERT(uc); + break; + case UCALL_SYNC: + break; + default: + TEST_FAIL("Unexpected ucall"); + } + + kvm_vm_free(vm); +} + +int main(void) +{ + u64 freq; + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + bool have_tsc_scale; + + TEST_REQUIRE(sys_clocksource_is_based_on_tsc()); + + vm =3D vm_create_with_one_vcpu(&vcpu, guest_code); + have_tsc_scale =3D !__vcpu_has_device_attr(vcpu, KVM_VCPU_TSC_CTRL, + KVM_VCPU_TSC_SCALE); + host_khz =3D __vcpu_ioctl(vcpu, KVM_GET_TSC_KHZ, NULL); + kvm_vm_free(vm); + + ksft_print_header(); + ksft_set_plan(5); + + /* Native frequency */ + run_test(0); + ksft_test_result_pass("native frequency (%lu kHz)\n", + (unsigned long)host_khz); + + /* Scaled frequencies, when hardware TSC scaling is available */ + for (freq =3D 1000000; freq <=3D 4000000; freq +=3D 1000000) { + if (!have_tsc_scale) { + ksft_test_result_skip("%lu kHz (no TSC scaling)\n", + (unsigned long)freq); + } else if (freq =3D=3D host_khz) { + ksft_test_result_skip("%lu kHz is the host frequency\n", + (unsigned long)freq); + } else { + run_test(freq); + ksft_test_result_pass("%lu kHz\n", (unsigned long)freq); + } + } + + ksft_finished(); +} --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.92.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420578; b=DGGzVrj6CPhhZMzzcwi1oLZYduywMUMrM8yotnRdJLAdGNgMO9HA5bs2NqWO5dDmhmbR Al1qbnVvcMfZuY3mVgsRvWfigC0OByS4gw3/IwskabugZUhxz/tbNp4CPq2W1JEhTkw+g h4+3TRH2n+rNDh72i11HXZQY1Y7uqJzER5oyaHQExRGvIi5MGvQNdOiHDfyUdN5Agqagu y+AGueOZLXcN+CmEsj+mbvIApa9ZES5T4I0YIAJ3WzMCR7rBXo4osH72x3nniFmqRzNAc lv4Z0ZJm4qOzdhnVHbU8m9benFxVJPjUd02GePVXx/Bl7z2BsKCWewH0Nu+fOuYdZ9A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420578; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=4ef/OanmIYVhZ39mmN9i+3nPMTOvgl3kuiqty0UYfVQ=; b=VfZeOT93vw15DXFk+nHnh5x98zQqtEXgeXcCxGh+NuA9m3WIoT4bmpux16P/9Ncff1Bu 0P/W2DhcYzQ9FP8l8lUjsw3TXBm7mKERKsX51xuvfkW98C6k2hqKnygIiGyip/unuekOx nBDq3i6l48vGi9qTEa5Rkt1Iqi84Q/C/OASKPyAxhum3S7xMsBlUeE5U6KlXE3I+ueAx9 hOzD1CvzufGV3X6e5euPQ6il81giVAr2fXcyIpGYDmQdRHZ0PhjOUkM9dr8U08SgVBZ7W Po8wNdGoPCVKf2I9Sfwa77F+fZ7Ls0EIZz+5StXy44rQRPXBKb/RvLRueOGvV9/Pipw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=desiato.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=SD0xiGvv; arc=none smtp.remote-ip=90.155.92.199 Received: from desiato.infradead.org (desiato.infradead.org [90.155.92.199]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 367E7606B786; Wed, 11 Nov 2026 18:09:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 367E7606B786 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=desiato.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=desiato.20200630 header.b=SD0xiGvv DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=desiato.20200630; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=4ef/OanmIYVhZ39mmN9i+3nPMTOvgl3kuiqty0UYfVQ=; b=SD0xiGvvBw2dlcpqPpcWV9L2+k mjhmtahbMru1wSFigKkPtLdMIbq6ARAi+aPrLpmV2mivUqywxfvTIaNiGfRnwPaPSsSFrZaJL1bdv 2y8Xyu4Lob3V1L+GpGysy+IcDHm8riQaTRPULdapwbWb7Afm3NOYjqlcTX1tgRxnEGBmouft6brAr FOCFYggCV9wL2ICBKLWhAC1yAFx5/Tih0QCnu/dtzCF7i07S+zmJIghGHHoeATwhcRriZgDJvlwHN W8/AezTrx8Relfr7KFhyfQqeAoUbI8TfPHLJcEcs42UfFfalxobACwOIN174UAsdKnrXC+XzUUTrM Ld2X3mOQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by desiato.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClB-00000009PvU-3Bk1; Wed, 11 Nov 2026 18:09:25 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtS-2zfy; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 22/26] KVM: selftests: Add Xen runstate migration test Date: Wed, 11 Nov 2026 10:09:18 -0800 Message-ID: <20261111180922.4177927-23-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by desiato.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Test that Xen runstate (steal time) is correctly accounted across a simulated live migration using KVM_XEN_VCPU_ATTR and KVM_[GS]ET_CLOCK_GUEST. The test simulates what a real VMM does during migration: 1. Creates a VM with Xen HVM config and runstate tracking 2. Runs the guest to accumulate some kvmclock time 3. Saves clock (KVM_GET_CLOCK_GUEST), TSC offset, and runstate 4. Marks the saved state as RUNSTATE_runnable (vCPU not running) 5. Destroys the source VM 6. Sleeps 10ms (simulating migration network transfer time) 7. Creates a new VM and restores all state precisely as saved 8. Runs the guest and verifies the migration gap appears as steal The VM is placed in long mode explicitly (KVM_XEN_ATTR_TYPE_LONG_MODE) so the kernel writes the 64-bit runstate layout; nothing in this test writes the hypercall-page MSR, which is what would otherwise latch the mode from the guest's EFER. The guest TSC is transferred via the KVM_VCPU_TSC_OFFSET attribute. As the "migration" is to a new VM on the same host, restoring the same offset makes the guest TSC continue uninterrupted across the gap, so the restored pvclock yields a kvmclock which has kept running too. That is what makes the migration gap visible: the destination kvmclock is ahead of the saved state_entry_time by (at least) the gap duration, rather than restarting from the destination VM's creation time. The kernel accounts the gap because: on vcpu_load, it transitions from RUNSTATE_runnable to RUNSTATE_running, computing delta =3D kvmclock_now - state_entry_time. Since kvmclock has advanced past the saved entry time (real time elapsed during migration), the delta is added to time_runnable. The result is reported through the kselftest TAP machinery. Signed-off-by: David Woodhouse --- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../selftests/kvm/x86/xen_migration_test.c | 227 ++++++++++++++++++ 2 files changed, 228 insertions(+) create mode 100644 tools/testing/selftests/kvm/x86/xen_migration_test.c diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selft= ests/kvm/Makefile.kvm index 79d26de18bf3..1edc78845fd3 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -153,6 +153,7 @@ TEST_GEN_PROGS_x86 +=3D x86/debug_regs TEST_GEN_PROGS_x86 +=3D x86/tsc_msrs_test TEST_GEN_PROGS_x86 +=3D x86/vmx_pmu_caps_test TEST_GEN_PROGS_x86 +=3D x86/xen_cpuid_timing_test +TEST_GEN_PROGS_x86 +=3D x86/xen_migration_test TEST_GEN_PROGS_x86 +=3D x86/xen_shinfo_test TEST_GEN_PROGS_x86 +=3D x86/xen_vmcall_test TEST_GEN_PROGS_x86 +=3D x86/sev_dbg_test diff --git a/tools/testing/selftests/kvm/x86/xen_migration_test.c b/tools/t= esting/selftests/kvm/x86/xen_migration_test.c new file mode 100644 index 000000000000..e316e6cd82de --- /dev/null +++ b/tools/testing/selftests/kvm/x86/xen_migration_test.c @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Test Xen runstate (steal time) preservation across simulated migration. + * + * Verifies that the kernel correctly accounts the migration gap as + * steal time (runnable) when runstate data is saved and restored + * precisely, but real time elapses during the migration. + * + * The key insight: userspace saves the runstate with state=3DRUNSTATE_run= nable + * (the vCPU is not running during migration). On restore, the kernel sees + * that kvmclock has advanced past state_entry_time, and accounts the + * difference as time spent in the runnable state. + */ +#include +#include +#include +#include +#include + +#include "test_util.h" +#include "kvm_util.h" +#include "processor.h" + +#include + +#define SHINFO_GPA 0xc0000000ULL +#define RUNSTATE_GPA (SHINFO_GPA + 0x1000) + +#define RUNSTATE_running 0 +#define RUNSTATE_runnable 1 +#define RUNSTATE_blocked 2 +#define RUNSTATE_offline 3 + +/* + * The 64-bit (long mode) layout: 'state' is followed by 4 bytes of + * padding so state_entry_time is naturally aligned. The VM is placed + * in long mode explicitly below; without that, KVM would latch 32-bit + * mode (no hypercall-page write ever happens here to latch it from + * EFER) and write the packed compat layout instead. + */ +struct vcpu_runstate_info { + u32 state; + u64 state_entry_time; + u64 time[4]; +}; + +static void guest_code(void) +{ + volatile struct vcpu_runstate_info *rs =3D + (void *)(unsigned long)RUNSTATE_GPA; + + /* + * Report runstate times =E2=80=94 no need to enable the kvmclock MSR, + * the kernel writes runstate using its internal kvmclock. + */ + GUEST_SYNC_ARGS(0, rs->time[RUNSTATE_runnable], + rs->time[RUNSTATE_running], 0, 0); +} + +static struct kvm_vm *create_xen_vm(struct kvm_vcpu **vcpu) +{ + struct kvm_vm *vm; + int xen_caps; + + vm =3D vm_create_with_one_vcpu(vcpu, guest_code); + + xen_caps =3D kvm_check_cap(KVM_CAP_XEN_HVM); + TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_SHARED_INFO); + TEST_REQUIRE(xen_caps & KVM_XEN_HVM_CONFIG_RUNSTATE); + + /* Map pages */ + vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, + SHINFO_GPA, 1, 2, 0); + virt_map(vm, SHINFO_GPA, SHINFO_GPA, 2); + + /* Enable Xen HVM with MSR interception (enables runstate tracking) */ + struct kvm_xen_hvm_config cfg =3D { + .flags =3D KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL, + .msr =3D 0x40000000, + }; + vm_ioctl(vm, KVM_XEN_HVM_CONFIG, &cfg); + + /* The guest runs in long mode; make the runstate layout match. */ + struct kvm_xen_hvm_attr lm =3D { + .type =3D KVM_XEN_ATTR_TYPE_LONG_MODE, + .u.long_mode =3D 1, + }; + vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &lm); + + /* Set shared_info */ + struct kvm_xen_hvm_attr ha =3D { + .type =3D KVM_XEN_ATTR_TYPE_SHARED_INFO, + .u.shared_info.gfn =3D SHINFO_GPA >> 12, + }; + vm_ioctl(vm, KVM_XEN_HVM_SET_ATTR, &ha); + + /* Set runstate address */ + struct kvm_xen_vcpu_attr rs_addr =3D { + .type =3D KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR, + .u.gpa =3D RUNSTATE_GPA, + }; + vcpu_ioctl(*vcpu, KVM_XEN_VCPU_SET_ATTR, &rs_addr); + + return vm; +} + +int main(void) +{ + struct pvclock_vcpu_time_info pvti; + struct kvm_xen_vcpu_attr runstate_save; + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + struct ucall uc; + u64 tsc_offset; + int ret; + + TEST_REQUIRE(sys_clocksource_is_based_on_tsc()); + TEST_REQUIRE(kvm_has_cap(KVM_CAP_CLOCK_GUEST)); + + ksft_print_header(); + ksft_set_plan(1); + + /* =3D=3D=3D SOURCE SIDE =3D=3D=3D */ + pr_info("=3D=3D=3D Source: create VM and run guest =3D=3D=3D\n"); + vm =3D create_xen_vm(&vcpu); + + /* Run guest once to accumulate some runstate time */ + vcpu_run(vcpu); + TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); + TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_SYNC); + + pr_info(" Guest sees: runnable=3D%" PRIu64 " running=3D%" PRIu64 "\n", + uc.args[2], uc.args[3]); + + /* Save clock state */ + vcpu_get_clock_guest(vcpu, &pvti); + + /* + * Save the guest TSC offset. This test migrates to a new VM on + * the same host, so restoring the same offset makes the guest + * TSC continue uninterrupted across the migration gap, and the + * restored pvclock (KVM_SET_CLOCK_GUEST) then yields a kvmclock + * which has also kept running across the gap. (A real migration + * to a different host would compute the destination offset from + * KVM_GET_CLOCK's {host_tsc, realtime} pair as described in + * Documentation/virt/kvm/devices/vcpu.rst.) + */ + tsc_offset =3D vcpu_get_tsc_offset(vcpu); + + /* Save runstate =E2=80=94 the vCPU is now "runnable" (not running) */ + runstate_save.type =3D KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA; + vcpu_ioctl(vcpu, KVM_XEN_VCPU_GET_ATTR, &runstate_save); + + /* + * Transition to runnable state before saving =E2=80=94 the vCPU is + * not running during migration. + */ + runstate_save.u.runstate.state =3D RUNSTATE_runnable; + + pr_info(" Saved runstate: running=3D%" PRIu64 " runnable=3D%" PRIu64 + " entry=3D%" PRIu64 "\n", + (u64)runstate_save.u.runstate.time_running, + (u64)runstate_save.u.runstate.time_runnable, + (u64)runstate_save.u.runstate.state_entry_time); + + u64 saved_runnable =3D runstate_save.u.runstate.time_runnable; + + kvm_vm_free(vm); + + /* =3D=3D=3D MIGRATION GAP =3D=3D=3D */ + pr_info("=3D=3D=3D Simulating migration (sleeping 10ms) =3D=3D=3D\n"); + usleep(10000); + + /* =3D=3D=3D DESTINATION SIDE =3D=3D=3D */ + pr_info("=3D=3D=3D Destination: create new VM and restore =3D=3D=3D\n"); + vm =3D create_xen_vm(&vcpu); + + /* Restore the guest TSC offset (same host: TSC continues) */ + vcpu_set_tsc_offset(vcpu, tsc_offset); + + /* Restore clock =E2=80=94 kvmclock will now be ~10ms ahead of the snapsh= ot */ + vcpu_set_clock_guest(vcpu, &pvti); + + /* Restore runstate exactly as saved (state=3Drunnable) */ + runstate_save.type =3D KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA; + ret =3D __vcpu_ioctl(vcpu, KVM_XEN_VCPU_SET_ATTR, &runstate_save); + TEST_ASSERT(!ret, "Restore runstate failed: errno %d", errno); + + /* + * Run the guest. When the vCPU enters vcpu_run, the kernel + * transitions from RUNSTATE_runnable to RUNSTATE_running. + * It computes: delta =3D kvmclock_now - state_entry_time + * This delta (which includes the migration gap) is added to + * time_runnable (steal time). + */ + vcpu_run(vcpu); + TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO); + TEST_ASSERT_EQ(get_ucall(vcpu, &uc), UCALL_SYNC); + + u64 guest_runnable =3D uc.args[2]; + u64 guest_running =3D uc.args[3]; + + pr_info(" Guest sees: runnable=3D%" PRIu64 " running=3D%" PRIu64 "\n", + guest_runnable, guest_running); + + u64 steal_increase =3D guest_runnable - saved_runnable; + pr_info(" Steal time increase: %" PRIu64 " ns (migration gap)\n", + steal_increase); + + /* + * The steal time increase should be at least 10ms (the sleep). + * The actual gap runs from the source's state_entry_time to the + * destination's kvmclock "now" at vcpu_load time, which includes + * everything from the source guest's last runstate transition + * through VM teardown and re-creation =E2=80=94 so the upper bound exists + * only to catch wild miscalculation (e.g. an unscaled TSC delta), + * and is deliberately generous for slow or loaded hosts. + */ + TEST_ASSERT(steal_increase >=3D 10000000ULL && + steal_increase < 60000000000ULL, + "Steal time increase %" PRIu64 " ns not in expected range " + "[10ms, 60s]", steal_increase); + + kvm_vm_free(vm); + ksft_test_result_pass("migration gap accounted as steal time\n"); + ksft_finished(); +} --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420569; b=ywlK6pYfZ3aW/oWCmJ5x6gDeLDvddnBu6Ryk59whYOuoa4wLsmBA2qZenXNxrEqQlxjj TrrJyCqESO5bDJcYiuOxOE1FYEEWMUkHyBsZqP4OQjaMLYxZMGA6PAUJRh4oqVK4/ZQoG v//m3272kGAVXU7eD+Zygt3jmsnfGjjbi5Iyn6OLZDQ2/WlEkLu0H7dVfBftlZW16B4wA YverloPEpV6zV8Ng1Ja4Pm9Kr3KKRRusnK+rc163Kl08K05+uwp9Bzb7m7yg/AN4A9xER M41lajgICH5AuGPacRUi4q3pQEXKHiG3IzH3D9OvHWPXhXTpb+ZbAkWZNdfEBqSR0Gw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420569; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=Hl8YrP2P/VCxzOQno5RcQLYFGPX+xLljUyf4GX9zYkQ=; b=XGti7Jwoor88j/DQ6RhwBuP3NNnLdmdQeOmZO9gU2s8oP6QcSWQSwjvd6uqXT4heE4eM BkcT7HMFyDo9izwrX7bVS1UCNZjADpoyymGLznCiK27o4H//H6G9DPPmQ30zzY9kNPMRL 5IRB9olaqrYQMBMthDXrafIC+xas9EkabVP9KOtIr4idsR3MHCcwdsSujo4OCIfzFYguJ Ul1bWlOZNL8eaXonuk6s3XTInhMtGs5Fb9FXgSRPAHkiD1N8rOo2qRJIhAlUmDl9/Gf90 jPioRwUKoOEokmbL8fEMWapOqZCgCpHUr/02X3T1vrytM4v1Ulv+X2v9k7nZQeBWEtw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=Jzl5R9ac; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E8276606A331; Wed, 11 Nov 2026 18:09:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org E8276606A331 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=Jzl5R9ac DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=Hl8YrP2P/VCxzOQno5RcQLYFGPX+xLljUyf4GX9zYkQ=; b=Jzl5R9acijBatAsZq/YOqqGWcG tRo2De+4gm5F+1l0NaguFz+AwUVgaCKCQtozC2d6hRtJu9uDhbp8ufOGej0zfV0OB8vBJdfDaNPVV VFU0WkjoStEzn/77lOcILZqaMPaIaAyqcW5YRtKyEc7pUazNrqGRTzEYYk8qM5s00P1sw0+JfAwc7 vcpKfzzivbSEXMoQ1SWKqVw2zHajIqkUs5YCpQnE+A3XC2ggfQulBu7Kka6FOi3afr7wkDglgVhfF awh7M2vgJRXKAnRgz9SVt+ytDU8baSDX1ZD5WrZqTr3NUHI13NduRiNk0h84TLezPdgfVT/emf/rO IWUq4vEQ==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRCl9-0000000CKxE-4ArO; Wed, 11 Nov 2026 18:09:24 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtY-3Gyu; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 23/26] KVM: selftests: Test that the first user TSC write is honoured exactly Date: Wed, 11 Nov 2026 10:09:19 -0800 Message-ID: <20261111180922.4177927-24-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse The 1-second "slop" heuristic in kvm_synchronize_tsc() is only supposed to apply between successive userspace TSC writes, i.e. once kvm->arch.user_set_tsc has been set by a previous write. The kernel's own internal TSC synchronization on vCPU creation (and frequency changes) must not arm it, otherwise the first genuine userspace write falling within 1 second of virtual cycle time of the kernel's default generation is "corrected" back to that generation instead of being honoured =E2=80=94 breaking the restore of a guest with less than one second of runtime. Add a test which creates a vCPU and immediately performs a first host-initiated write of a TSC value corresponding to ~500ms of guest runtime, then verifies the value reads back exactly (modulo elapsed time) rather than being snapped back to the kernel's default generation near zero. In the frequency-change case, a buggy kernel carries the creation-rate TSC across the change, where (expressed at the halved rate) it reads as the creation-to-change plus creation-to-read time; a further timing gate keeps that sum comfortably below the written 500ms so a snapped-back value can never sit above the written one. Both cases report through the kselftest TAP machinery; an inconclusive case (host timing repeatedly too slow, a property of host load rather than of the kernel under test) is recorded as a skip without discarding the other case's result. A conclusively buggy kernel still fails via TEST_ASSERT before any skip is reachable. Signed-off-by: David Woodhouse --- tools/testing/selftests/kvm/Makefile.kvm | 1 + .../selftests/kvm/x86/tsc_user_set_test.c | 193 ++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 tools/testing/selftests/kvm/x86/tsc_user_set_test.c diff --git a/tools/testing/selftests/kvm/Makefile.kvm b/tools/testing/selft= ests/kvm/Makefile.kvm index 1edc78845fd3..fd063806a7fb 100644 --- a/tools/testing/selftests/kvm/Makefile.kvm +++ b/tools/testing/selftests/kvm/Makefile.kvm @@ -151,6 +151,7 @@ TEST_GEN_PROGS_x86 +=3D x86/xcr0_cpuid_test TEST_GEN_PROGS_x86 +=3D x86/xss_msr_test TEST_GEN_PROGS_x86 +=3D x86/debug_regs TEST_GEN_PROGS_x86 +=3D x86/tsc_msrs_test +TEST_GEN_PROGS_x86 +=3D x86/tsc_user_set_test TEST_GEN_PROGS_x86 +=3D x86/vmx_pmu_caps_test TEST_GEN_PROGS_x86 +=3D x86/xen_cpuid_timing_test TEST_GEN_PROGS_x86 +=3D x86/xen_migration_test diff --git a/tools/testing/selftests/kvm/x86/tsc_user_set_test.c b/tools/te= sting/selftests/kvm/x86/tsc_user_set_test.c new file mode 100644 index 000000000000..5e6eb0a26c8e --- /dev/null +++ b/tools/testing/selftests/kvm/x86/tsc_user_set_test.c @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Test that the first userspace write to MSR_IA32_TSC takes effect + * precisely, and is not subjected to the 1-second "slop" heuristic + * which is only supposed to apply between successive *userspace* + * writes (kvm->arch.user_set_tsc). + * + * The kernel synchronizes the TSC internally when a vCPU is created + * (and when its frequency is set). If any of those kernel-internal + * paths incorrectly sets user_set_tsc, then the first genuine write + * from userspace which happens to fall within 1 second of virtual + * cycle time of the kernel's default generation is "corrected" to + * match that generation instead of being honoured exactly. That + * breaks the restore of a guest which has genuinely been running + * for less than one second. + * + * Simulate exactly that: create a vCPU (kernel establishes a default + * TSC generation starting near zero), then perform the first + * host-initiated write with a value corresponding to ~500ms of guest + * runtime. If the slop heuristic fires, the written value is snapped + * back to the kernel's generation (near zero) and the TSC reads back + * hundreds of milliseconds low. Repeat with an explicit + * KVM_SET_TSC_KHZ on the never-run vCPU before the write: that is + * another kernel-internal synchronization which must not arm the + * heuristic (nor open a generation that swallows the first write). + */ +#include + +#include "kvm_util.h" +#include "processor.h" + +/* + * Returns false when the attempt was inconclusive: a snapped-back value + * tracks time since vCPU creation, so if creation-to-write time gets + * anywhere near the written 500ms, a buggy kernel's value could land + * inside the assertions' tolerance and pass. The caller retries. + */ +static bool test_first_write(bool set_freq) +{ + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + u64 freq_khz, t_write, t_read, slack_cycles, mono_ns, create_ns, read_ns; + u64 freq_ns; + struct timespec ts; + int r; + + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + create_ns =3D ts.tv_sec * 1000000000ULL + ts.tv_nsec; + freq_ns =3D create_ns; + + vm =3D vm_create_with_one_vcpu(&vcpu, NULL); + + if (set_freq) { + /* + * Halve the frequency so this is a real change, exercising + * the frequency resynchronization path rather than the + * unchanged-frequency no-op. + */ + r =3D __vcpu_ioctl(vcpu, KVM_GET_TSC_KHZ, NULL); + TEST_ASSERT(r > 0, "KVM_GET_TSC_KHZ failed"); + vcpu_ioctl(vcpu, KVM_SET_TSC_KHZ, + (void *)(unsigned long)(r / 2)); + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + freq_ns =3D ts.tv_sec * 1000000000ULL + ts.tv_nsec; + } + + r =3D __vcpu_ioctl(vcpu, KVM_GET_TSC_KHZ, NULL); + TEST_ASSERT(r > 0, "KVM_GET_TSC_KHZ failed"); + freq_khz =3D r; + + /* + * The first user write: a guest TSC corresponding to 500ms of + * runtime. This is within 1s (of virtual cycle time) of the + * kernel's default generation, so it is exactly the case that + * the slop heuristic would destroy if it were (incorrectly) + * armed by the kernel's own internal TSC synchronization. + */ + t_write =3D freq_khz * 500ULL; /* khz * ms =3D cycles */ + + /* + * Measure only the write..read window (a window measured from + * before creation would also bound a snapped-back value), and + * insist the write lands well before 500ms of creation time so + * a snapped-back value cannot sit inside the tolerance. + */ + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + mono_ns =3D ts.tv_sec * 1000000000ULL + ts.tv_nsec; + + if (mono_ns - create_ns > 250000000ULL) { + pr_info(" creation took %lu ms, retrying for a conclusive run\n", + (mono_ns - create_ns) / 1000000); + kvm_vm_free(vm); + return false; + } + + vcpu_set_msr(vcpu, MSR_IA32_TSC, t_write); + + t_read =3D vcpu_get_msr(vcpu, MSR_IA32_TSC); + + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + read_ns =3D ts.tv_sec * 1000000000ULL + ts.tv_nsec; + + /* + * Bound the whole creation..read interval too: a snapped-back + * value tracks it, so letting it approach the written 500ms + * (via a stall between the two MSR ioctls, which the slack + * below would otherwise absorb) would let a buggy kernel pass. + */ + if (read_ns - create_ns > 400000000ULL) { + pr_info(" creation..read took %lu ms, retrying for a conclusive run\n", + (read_ns - create_ns) / 1000000); + kvm_vm_free(vm); + return false; + } + + /* + * In the set_freq case a buggy kernel carries the creation-rate + * TSC across the frequency change, where it reads (expressed at + * the halved rate) as the creation..freq-change plus the + * creation..read time in milliseconds. Keep that sum comfortably + * below the written 500ms, or a snapped-back value could sit + * above t_write and pass the assertions. + */ + if ((freq_ns - create_ns) + (read_ns - create_ns) > 430000000ULL) { + pr_info(" freq-change at %lu ms + read at %lu ms, retrying for a conclu= sive run\n", + (freq_ns - create_ns) / 1000000, + (read_ns - create_ns) / 1000000); + kvm_vm_free(vm); + return false; + } + + mono_ns =3D read_ns - mono_ns; + + /* + * The TSC advances between the write and the read; bound the + * difference by the measured elapsed time around the two ioctls + * plus 10ms of slop, so a descheduled test cannot flake. If the + * write was snapped to the kernel's default generation, the + * value read back is ~500ms low (i.e. below t_write), which is + * unambiguous. + */ + slack_cycles =3D freq_khz * (mono_ns / 1000000ULL + 10); + + TEST_ASSERT(t_read >=3D t_write, + "TSC went backwards from explicit write: wrote %lu, read %lu" + " (first userspace write was subjected to 1-second slop?)", + t_write, t_read); + TEST_ASSERT(t_read - t_write < slack_cycles, + "TSC read back too far from written value: wrote %lu, read %lu", + t_write, t_read); + + kvm_vm_free(vm); + return true; +} + +static void run_first_write(bool set_freq) +{ + const char *name =3D set_freq ? "first write after KVM_SET_TSC_KHZ" + : "first write"; + int i; + + for (i =3D 0; i < 5; i++) { + if (test_first_write(set_freq)) { + ksft_test_result_pass("%s\n", name); + return; + } + } + + /* + * Inconclusive runs =E2=80=94 either gate: slow vCPU creation, or a + * stall between the MSR write and read =E2=80=94 reflect host + * scheduling load, not the behaviour under test; record a skip + * rather than report a kernel regression, without discarding a + * conclusive result the other case already established. + */ + ksft_test_result_skip("%s: host timing repeatedly too slow for a conclusi= ve run\n", + name); +} + +int main(void) +{ + ksft_print_header(); + ksft_set_plan(2); + + run_first_write(false); + + if (kvm_has_cap(KVM_CAP_TSC_CONTROL)) + run_first_write(true); + else + ksft_test_result_skip("first write after KVM_SET_TSC_KHZ: no KVM_CAP_TSC= _CONTROL\n"); + + ksft_finished(); +} --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420571; b=nlT1fuArCa/Yt6RMXueCDdHuglt2YpXUiDdTHNLpYOr3lN4aPOj3VndnoIVtCVcMorCN zVvPvMyQCHe2va7ywrPMR/Cue0YFES0phHL5byvvw2u3+4Wn09vDjotWzA0kqy2JpFE/v gz6k+c9rSXkIjZEUrluZusewV7MX4rsQ0PbWmlfT6X8aOfa2m6m5RDIzqc2UfuS4YCUqZ N9hYrg5GjxtCBgNPwyy1UtP30hF8gRJQZse4+gru6Wf9XcfyIWVBCdEcmS2o9NbWVK8pL p5IJcCgbCRx8VkA969ZD/bbI34Kb5JzqsSneG1laDt+D/fHPfQZ72eyLNVCQHGt6/mg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420571; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=UkL+2EqqLZWeKCYphLSu8F5DwrRa+T7c95HDl48bUzo=; b=gFpe0uo5DTRi748PxQB2jpxcUWpQ60iP8zgZ8fbXf4N7YpHfrG2KnRMS//yyT2HI/mP5 +XxdDEvac9luuTd7qXotpRWQltsdZ+ojIZ5cfNu/KQWH3/Bv/nR8Tir5VLkbvGqPnn2d2 /Wfx8pDb3eikISoG3FSbRYhVLsUDMCi8MD6CFf0Fo4dwCyCF0PD4y7f5sOSGIQ98J4RaG 8WoovMRKLQL8+wcj82ZWVcn4NCoAiwFiejgJ4l3zRknG79F2PwB/FKRKbyTFK4cCoSvsI 78FpAyaUeVbQjSKmyUBXkzbOBar875vCuAWnVNEtgVC39xSygE4y4Taf6r3RiEPfq7Q== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b="sZNh/csW"; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D06E960A260E; Wed, 11 Nov 2026 18:09:30 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org D06E960A260E Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=sZNh/csW DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=UkL+2EqqLZWeKCYphLSu8F5DwrRa+T7c95HDl48bUzo=; b=sZNh/csWJLZTNxolsU2BKknfNs Qo3U14mot2qyCMtFvD9jtZisiBr/I7ogzhnU9xRkrWV6H9GRcR77uA+SP/DW9/oFAKho1+vpbl6nV k/o+ygtKtoplpCD0cOl+l/V8tA3N0rZrux2exarY//L0Puagr8bACfFFjR6w0BlPgn5ab+YfmqTjt jvtgW2NeNsopaInB7Vj/ZfQ4Btlijyx2r1SZ3HApttlBpFSzD74xX4GjcxzaTM6YtpdfJW9kyPvkt zamsqJf7mfEI0WtfR0/adfos4lWf3nhifZQy/BgisEixdn03aiKUwnz6N/iUGoRuQCP+gdIcrCye1 gtHpGXVg==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClA-0000000CKxH-09O8; Wed, 11 Nov 2026 18:09:24 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtd-3VQ5; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 24/26] KVM: x86/xen: Drop open-coded fallback clock read in kvm_xen_start_timer() Date: Wed, 11 Nov 2026 10:09:20 -0800 Message-ID: <20261111180922.4177927-25-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse When no coherent (CLOCK_MONOTONIC, TSC) pair was available, kvm_xen_start_timer() computed one from separate ktime_get() and rdtsc() calls rather than using get_kvmclock_ns(), with a comment explaining that the latter had a systemic error from scaling host TSC directly to nanoseconds instead of scaling to the guest TSC first. Commit abdef42276d8 ("KVM: x86: Fix KVM clock precision in get_kvmclock() with TSC scaling") removed that systemic error: in master clock mode, get_kvmclock_ns() now scales the host TSC delta to the guest TSC and converts it with the guest's own mul/shift, computing precisely what the guest would. The fallback is also nearly unreachable. It sits behind the use_master_clock check, so on 32-bit (where the master clock is never active) it is dead code, and on 64-bit kvm_get_monotonic_and_clockread() can only fail there if the host clocksource changed after the last master clock update, in the window before the resulting masterclock update is processed. In exactly that window get_kvmclock_ns() takes its raw-clock fallback path rather than the guest TSC computation, which is continuous with the last valid snapshot =E2=80=94 though up to ~0.1ppm of the snapshot's age (multiplier quantization) away from the guest's own pvclock arithmetic =E2=80=94 and tolerable for the timers that can be started before the pending masterclock update lands (the clocksource change is noticed via a two-stage deferral, so it is not strictly one). Drop it and fall back to the existing get_kvmclock_ns() path. Signed-off-by: David Woodhouse --- arch/x86/kvm/xen.c | 50 +++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/arch/x86/kvm/xen.c b/arch/x86/kvm/xen.c index 6aa00f746cba..2a157cba1c7c 100644 --- a/arch/x86/kvm/xen.c +++ b/arch/x86/kvm/xen.c @@ -188,7 +188,7 @@ static void kvm_xen_start_timer(struct kvm_vcpu *vcpu, = u64 guest_abs, struct kvm_vcpu_xen *xen =3D &vcpu->arch.xen; int64_t kernel_now, delta; uint64_t guest_now; - int r =3D -EOPNOTSUPP; + bool fallback =3D true; =20 /* * The guest provides the requested timeout in absolute nanoseconds @@ -210,6 +210,7 @@ static void kvm_xen_start_timer(struct kvm_vcpu *vcpu, = u64 guest_abs, do { struct pvclock_vcpu_time_info hv_clock; uint64_t host_tsc, guest_tsc; + int r =3D -EOPNOTSUPP; =20 if (!cpu_feature_enabled(X86_FEATURE_CONSTANT_TSC) || !vcpu->kvm->arch.use_master_clock) @@ -230,43 +231,42 @@ static void kvm_xen_start_timer(struct kvm_vcpu *vcpu= , u64 guest_abs, if (r) break; =20 + /* + * With use_master_clock set, the clocksource was TSC-based + * when the master clock was last updated. The clockread can + * only fail here if the clocksource has changed since, in + * which case a masterclock update is already pending and + * get_kvmclock_ns() returns the raw-clock fallback value =E2=80=94 + * continuous with the last valid snapshot, though it may + * sit up to ~0.1ppm of the snapshot's age away from the + * guest's own pvclock arithmetic. Only timers armed + * before the pending update is consumed see it. + */ if (!IS_ENABLED(CONFIG_64BIT) || - !kvm_get_monotonic_and_clockread(&kernel_now, &host_tsc)) { - /* - * Don't fall back to get_kvmclock_ns() because it's - * broken; it has a systemic error in its results - * because it scales directly from host TSC to - * nanoseconds, and doesn't scale first to guest TSC - * and *then* to nanoseconds as the guest does. - * - * There is a small error introduced here because time - * continues to elapse between the ktime_get() and the - * subsequent rdtsc(). But not the systemic drift due - * to get_kvmclock_ns(). - */ - kernel_now =3D ktime_get(); /* This is CLOCK_MONOTONIC */ - host_tsc =3D rdtsc(); - } + !kvm_get_monotonic_and_clockread(&kernel_now, &host_tsc)) + break; =20 /* Calculate the guest kvmclock as the guest would do it. */ guest_tsc =3D kvm_read_l1_tsc(vcpu, host_tsc); guest_now =3D __pvclock_read_cycles(&hv_clock, guest_tsc); + fallback =3D false; } while (0); =20 - if (r) { + if (fallback) { /* - * Without CONSTANT_TSC, get_kvmclock_ns() is the only option. + * Without CONSTANT_TSC and the master clock, + * get_kvmclock_ns() is the only option. * * Also if the guest PV clock hasn't been set up yet, as is * likely to be the case during migration when the vCPU has * not been run yet. It would be possible to calculate the * scaling factors properly in that case but there's not much - * point in doing so. The get_kvmclock_ns() drift accumulates - * over time, so it's OK to use it at startup. Besides, on - * migration there's going to be a little bit of skew in the - * precise moment at which timers fire anyway. Often they'll - * be in the "past" by the time the VM is running again after - * migration. + * point in doing so. Without the master clock, the + * get_kvmclock_ns() drift accumulates over time, so it's OK + * to use it at startup. Besides, on migration there's going + * to be a little bit of skew in the precise moment at which + * timers fire anyway. Often they'll be in the "past" by the + * time the VM is running again after migration. */ guest_now =3D get_kvmclock_ns(vcpu->kvm); kernel_now =3D ktime_get(); --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420571; b=SjonVUR8SP3niVCYOarEZI4UMHZlZh0fKCTCRjUCUO8rUt/BLz+5KiTAFAZ+mA1BvH65 wbB5JxZmUJkQQxQtMmkakyv7tXw8EWsHdWjrOvPM+W9bJX5Mz53uqEtU/FUnxOfcCfwru ue+i1Pw6nk/gjuz+EP5ExEhN0kn8tzM9FgQUzf59aq16hA4v/yOYz1VEoSAWywGNI1GYU 9UjHlGon7gniz7wENklltPJdu59kV5JXkmmPZ284DWQKbyARfq5upwoFs8cg2G6aZECVA rfuZtciijqIGhlLGu1xp/4jr3feAwEiqMkY+CggGi3bvOlo6z2qCI5WV2joqqYA7BoQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420571; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=0Cp728EjuFyU5LORJlGxffVkYMCDOu/AruEqIXPRi9Q=; b=YX8r/0b1HVgu4ugyvSLTL6oV6GV8AhLJP21OgKp5iHLx4zbRz6XewDWAOAvzlYDdEvnP j3T6zK+CPy96FlajRcHu4/oQmZiMtftxVRQrK1XU4TuT8jK+Bt4BNBjs/DMkSbFAQi1p/ L/nBdE5pStsqr6G+YNyGE7kYy2o6LfaPoobC2jT2ug1q5oHEs4jjAgpfXLgEgmY6ZkLxT 9ExIdw2kCUgj0QnOYQsCbQ+ebiIQ+Pwnv/CkTW8BjolUhltwPgyhY85QIoIESfyhCRXNw YncOdeDIHhjlC5WB+HWdxIGTnWeLJcaV3ZqHDJLLUYTBJHFluuxH6d+RJLV2lmHA1Lg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b="c/SVvFgU"; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C60BE60A260A; Wed, 11 Nov 2026 18:09:30 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org C60BE60A260A Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=c/SVvFgU DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc:To:From: Reply-To:Content-Type:Content-ID:Content-Description; bh=0Cp728EjuFyU5LORJlGxffVkYMCDOu/AruEqIXPRi9Q=; b=c/SVvFgUYUltwDQy6ocScA7wHO KDoZoGedwvN5LpuW2FtpeUkIzdNyiihEgq/LyX3Uq9oy4j2LonpGeYMKQ2RS7yWZg/eoSCv4oq0lw S3ZM/Ld9X5h+qTJmhBdET9q9IU1URjld7jQ97nkeAXiDOIjz2DuigjH/hSzftnBD/GQCJO/Z84IGb +MqHzegkwud4+Mg0M9MHMIvcgU3aq3YHQQaJxKEtO7ENMjcH0Bfs45lk33sMt6uqagCYqp2qRy4ML 0xSRAaYu8hxpabFkbj0vog8BZcwL1alMG9b3Zp007JNE0pWlPNS3PdBh/9CFY+XkXZgtDfc6cDq/0 ce2fmYJg==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClA-0000000CKxI-0Kt3; Wed, 11 Nov 2026 18:09:24 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWtk-3gXj; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 25/26] KVM: x86: Use a single time snapshot in kvm_vm_ioctl_set_clock() Date: Wed, 11 Nov 2026 10:09:21 -0800 Message-ID: <20261111180922.4177927-26-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html Content-Type: text/plain; charset="utf-8" From: David Woodhouse The KVM_CLOCK_REALTIME handling read CLOCK_REALTIME with ktime_get_real_ns() and then anchored the result at a different instant: the master clock reference point captured a few lines earlier, or a separate get_kvmclock_base_ns() read. The time elapsed between the two reads is added to the restored clock as error -- bounded by the interrupts-off critical section, but gratuitous now that the timekeeping core can snapshot CLOCK_REALTIME and CLOCK_MONOTONIC_RAW at the same instant. Take one ktime_get_snapshot_id(CLOCK_REALTIME) snapshot and derive both the realtime correction and the raw reference point from it. In master clock mode, keep anchoring at master_kernel_ns -- so that 'system_time' cannot go negative for a very small data.clock, as the existing comment explains -- by projecting the snapshot's realtime value back to that reference point; CLOCK_REALTIME and CLOCK_MONOTONIC_RAW tick at the same rate across the few ns in between, give or take NTP slew. Signed-off-by: David Woodhouse --- arch/x86/kvm/x86.c | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index b9d3b2715403..921d834b9682 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -5143,19 +5143,49 @@ static int kvm_vm_ioctl_set_clock(struct kvm *kvm, = void __user *argp) * 'system_time' when 'data.clock' is very small. */ if (data.flags & KVM_CLOCK_REALTIME) { - u64 now_real_ns =3D ktime_get_real_ns(); + struct system_time_snapshot snap =3D {}; + u64 now_real_ns; + + /* + * Snapshot CLOCK_REALTIME and CLOCK_MONOTONIC_RAW at the + * same instant, so that the elapsed time applied to + * data.clock and the reference point the result is anchored + * to are coherent. + */ + ktime_get_snapshot_id(CLOCK_REALTIME, &snap); + now_real_ns =3D ktime_to_ns(snap.systime); + now_raw_ns =3D ktime_to_ns(ktime_mono_to_any(snap.monoraw, + TK_OFFS_BOOT)); + + /* + * When the master clock is in use, anchor at its reference + * point instead, projecting the realtime value back to the + * same instant. The two clocks tick at the same rate across + * the few ns in between, give or take NTP slew. In the + * absurd case that the projection would take a + * CLOCK_REALTIME set to within moments of the 1970 epoch + * (legal with CAP_SYS_TIME) below zero, clamp it to zero; + * the anchor must still move to master_kernel_ns, from + * which the master clock consumers compute system_time, + * lest a near-zero data.clock wrap it below zero. + */ + if (ka->use_master_clock) { + u64 delta =3D now_raw_ns - ka->master_kernel_ns; + + now_real_ns =3D now_real_ns > delta ? now_real_ns - delta : 0; + now_raw_ns =3D ka->master_kernel_ns; + } =20 /* * Avoid stepping the kvmclock backwards. */ if (now_real_ns > data.realtime) data.clock +=3D now_real_ns - data.realtime; - } - - if (ka->use_master_clock) + } else if (ka->use_master_clock) { now_raw_ns =3D ka->master_kernel_ns; - else + } else { now_raw_ns =3D get_kvmclock_base_ns(); + } ka->kvmclock_offset =3D data.clock - now_raw_ns; kvm_end_pvclock_update(kvm); =20 --=20 2.43.0 From nobody Mon Nov 23 22:28:42 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=90.155.50.34 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1794420571; b=ee551EEHp1A1m5VyH4Y3zEwipy4wJLspns5/ctkmz4guO1WMGlrCFllprbJ0mfx8puV3 QwiXW5IQPhwZoDNIo5q4jp4RjfnFKNGIHh5DIJh/iq+afRtHo5WfHYEWQq47NLIStu5UP E8XxkqBk/hKQwNRb0tN9NCcBrY92qFArxDFCofP40eAFVzgXBjLqfE4VeyBQVJtL8HE9P qg18NoVi62x8MLFq4kMN0UMEU3jKVjDj4a3iomBhqq8fSFSrDYsL3DsZDwBVUlXN38h+7 zADBrrrysKbAgxGARzCEeBBGtF7lfcPzb4+aX7Jo0EuGADaJAjNKCTGNQiqaGskWX3w== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1794420571; h=DMARC-Filter:DKIM-Signature:Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding:Sender:X-SRS-Rewrite; bh=RWJYzPBfROH0RDNcb8a2gkFZRf2P6KvtNVjLim21s78=; b=QMJGYnGLyhmc1d46ILGEPYdi5NLIC417zSz3TLGn6EJyF2oeX8hs8eDaYkng/KRLGT5t M/q8PjykJGBtSdD/COxmA9Yt6zEZpRtN+VBCzSip3GieKJJr6W2JNPv3yuCE7DeX1Fewk fSjZtifxSJeArZJ/gWatodRrVx5UXEkTgrSCRg1NZTK/yQCITSMVft2TKyvr/qi5UZ+DX H0F53nyy4o4oyX8/q65ahJayO34ogtIlFeCgpm5en23zUIXAd9HnMvM0TgP9U2dUzl6dO OzHW9aZS9B1NJaNPj56gGJrR6Le2SaTI0eST3+E378m8YeFlHn2LFCQOewhCm3zQCfA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=infradead.org; spf=none smtp.mailfrom=casper.srs.infradead.org; dkim=pass header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=KPI+rh0q; arc=none smtp.remote-ip=90.155.50.34 Received: from casper.infradead.org (casper.infradead.org [90.155.50.34]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C563C60A2604; Wed, 11 Nov 2026 18:09:30 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org C563C60A2604 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=infradead.org Authentication-Results: smtp.subspace.kernel.org; spf=none smtp.mailfrom=casper.srs.infradead.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=infradead.org header.i=@infradead.org header.a=rsa-sha256 header.s=casper.20170209 header.b=KPI+rh0q DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=infradead.org; s=casper.20170209; h=Sender:Content-Transfer-Encoding: Content-Type:MIME-Version:References:In-Reply-To:Message-ID:Date:Subject:Cc: To:From:Reply-To:Content-ID:Content-Description; bh=RWJYzPBfROH0RDNcb8a2gkFZRf2P6KvtNVjLim21s78=; b=KPI+rh0q9L5E0n3PtrKdGzqxmC u6ZqUrVz47cB90lrmnZyoDvUftETMhbwMtlWKnleSuFFI4TiaV6t4SXkd8qxz6PWW3oqg9YLVYuEC wzjlnYagA/T4nyMTbJS595bEm35vpz2RXbk1L8BXZpbpTz7C2CRBskFo74yShLtJuhNm8Vwl5SwdF xngOACk6Td8Z51U8fiO8a7KVDwEYru3NUcMgvtocCl5bM1fTBK/Db6fkqwLTjEar8mljiHnTDY9Ce adxalyGh6pqDgAtvNfJkV4fL+gOzZa6SyomDyG5Gtlh4BmaBqbtho21ORBMrQ+xHF8MoVLcp9c9P/ JqRPDpcA==; Received: from [2001:8b0:10b:1::425] (helo=i7.infradead.org) by casper.infradead.org with esmtpsa (Exim 4.100.1 #2 (Red Hat Linux)) id 1xRClA-0000000CKxJ-0WPu; Wed, 11 Nov 2026 18:09:24 +0000 Received: from dwoodhou by i7.infradead.org with local (Exim 4.99.5 #2 (Red Hat Linux)) id 1xRCl9-0000000HWto-3rsi; Wed, 11 Nov 2026 18:09:23 +0000 From: David Woodhouse To: kvm@vger.kernel.org Cc: linux-kernel@vger.kernel.org, linux-kselftest@vger.kernel.org, linux-doc@vger.kernel.org, xen-devel@lists.xenproject.org, x86@kernel.org, Paolo Bonzini , Sean Christopherson , Paul Durrant , Vitaly Kuznetsov , Thomas Gleixner , Ingo Molnar , Borislav Petkov , Dave Hansen , "H . Peter Anvin" , Jonathan Corbet , Shuah Khan , Juergen Gross , Boris Ostrovsky , Jonathan Cameron , Sascha Bischoff , Marc Zyngier , Joey Gouly , Jack Allister , Dongli Zhang , joe.jin@oracle.com, David Woodhouse Subject: [PATCH v13 26/26] KVM: x86: Keep master clock for guests using legacy MSR_KVM_SYSTEM_TIME Date: Wed, 11 Nov 2026 10:09:22 -0800 Message-ID: <20261111180922.4177927-27-dwmw2@infradead.org> X-Mailer: git-send-email 2.55.0 In-Reply-To: <20261111180922.4177927-1-dwmw2@infradead.org> References: <20261111180922.4177927-1-dwmw2@infradead.org> 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-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Sender: David Woodhouse X-SRS-Rewrite: SMTP reverse-path rewritten from by casper.infradead.org. See http://www.infradead.org/rpr.html From: David Woodhouse Commit 54750f2cf042 ("KVM: x86: workaround SuSE's 2.6.16 pvclock vs masterclock issue") disables the master clock entirely for any guest whose boot vCPU uses the legacy MSR. SUSE's 2.6.16 kernel treats a pvclock tsc_timestamp more than 1/5 jiffie behind the TSC as suspect and re-requests the time by rewriting the MSR; against the master clock's long-lived reference point the delta never shrinks, so it re-requests in a loop and fails to boot. Satisfy the guest's freshness heuristic instead of capitulating to it: a guest write to the legacy MSR now requests a masterclock update, sliding the reference point forward before the pvclock is written (the masterclock request is serviced before KVM_REQ_CLOCK_UPDATE on the same guest entry). The re-requested pvclock then carries a recent tsc_timestamp and the heuristic is content. Each re-anchor steps the pvclock function by the sub-nanosecond (possibly backwards) mult-rounding divergence accumulated since the previous anchor =E2=80=94 the same step every pre-existing masterclock update already takes =E2=80=94 and legacy-MSR guests now see PVCLOCK_TSC_STABLE_BIT like anyone else. A guest hammering the legacy MSR forces repeated VM-wide masterclock updates, but only its own VM's: a guest has always been able to burn its own cycles. Re-anchoring just the writing vCPU's pvclock along the masterclock line would avoid even that, but isn't worth the extra plumbing for a 2006 guest kernel. This removes the last way a guest could force the master clock off; the remaining disable, backwards_tsc_observed, is the host's own doing. The pvclock_test selftest grows a legacy-MSR case proving the master clock survives and the rewritten pvclock is fresh. Not tested against a real SLES10 image; the behaviour it demands is reconstructed from the guest comment quoted in 54750f2cf042. The freshness that guest observes can be no worse than before: with the master clock disabled it saw a tsc_timestamp one exit-to-read latency old, exactly what the rewrite now produces, and the update's own cost does not age the timestamp, which is written only after the update completes. A host loaded enough to defeat that would have livelocked the old scheme equally. Should a real SLES10 guest prove otherwise, the revert path is to restore the boot_vcpu_runs_old_kvmclock gate in kvm_use_master_clock(). Signed-off-by: David Woodhouse --- arch/x86/include/asm/kvm_host.h | 1 - arch/x86/kvm/msrs.c | 26 ++++---- arch/x86/kvm/x86.c | 15 +---- .../testing/selftests/kvm/x86/pvclock_test.c | 63 +++++++++++++++++++ 4 files changed, 77 insertions(+), 28 deletions(-) diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_hos= t.h index 773df58898ea..0db8169612a4 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -1275,7 +1275,6 @@ struct kvm_arch { #endif =20 bool backwards_tsc_observed; - bool boot_vcpu_runs_old_kvmclock; u32 bsp_vcpu_id; =20 u64 disabled_quirks; diff --git a/arch/x86/kvm/msrs.c b/arch/x86/kvm/msrs.c index d07831b5dfb8..94cd4d73689a 100644 --- a/arch/x86/kvm/msrs.c +++ b/arch/x86/kvm/msrs.c @@ -1275,19 +1275,19 @@ static void kvm_write_wall_clock(struct kvm *kvm, g= pa_t wall_clock, int sec_hi_o static void kvm_write_system_time(struct kvm_vcpu *vcpu, gpa_t system_time, bool old_msr, bool host_initiated) { - struct kvm_arch *ka =3D &vcpu->kvm->arch; - - if (vcpu->vcpu_id =3D=3D 0 && !host_initiated) { - /* - * Store the flag before requesting the masterclock update: - * the update may now be performed by another vCPU (which - * consumes this request), and it must observe the new value. - */ - if (ka->boot_vcpu_runs_old_kvmclock !=3D old_msr) { - ka->boot_vcpu_runs_old_kvmclock =3D old_msr; - kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); - } - } + /* + * Slide the master clock reference point forward, so that the + * pvclock written below carries a recent tsc_timestamp. SUSE's + * 2.6.16 kernel (the only known user of the legacy MSR with a + * reason to care) re-requests the time by rewriting this MSR + * whenever tsc_timestamp falls more than 1/5 jiffie behind the + * TSC, and would livelock against a fixed reference point; each + * rewrite now genuinely freshens it. A write with the enable + * bit clear deactivates the pvclock; there is nothing to + * freshen. + */ + if (old_msr && !host_initiated && (system_time & 1)) + kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); =20 vcpu->arch.time =3D system_time; =20 diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 921d834b9682..191f811a0cdd 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -1181,21 +1181,8 @@ static bool kvm_use_master_clock(struct kvm *kvm) { struct kvm_arch *ka =3D &kvm->arch; =20 - /* - * The 'old kvmclock' check is a workaround (from 2015) for a - * SUSE 2.6.16 kernel that didn't boot if the system_time in - * its kvmclock was too far behind the current time. So the - * mode of just setting the reference point and allowing time - * to proceed linearly from there makes it fail to boot. - * Despite that being kind of the *point* of the way the clock - * is exposed to the guest. By coincidence, the offending - * kernels used the old MSR_KVM_SYSTEM_TIME, which was moved - * only because it resided in the wrong number range. So the - * workaround is activated for *all* guests using the old MSR. - */ return ka->all_vcpus_matched_freq && - !ka->backwards_tsc_observed && - !ka->boot_vcpu_runs_old_kvmclock; + !ka->backwards_tsc_observed; } =20 static void kvm_track_tsc_matching(struct kvm_vcpu *vcpu, bool update_mclo= ck) diff --git a/tools/testing/selftests/kvm/x86/pvclock_test.c b/tools/testing= /selftests/kvm/x86/pvclock_test.c index cb57f5e2bf1e..f3c8d9d8303a 100644 --- a/tools/testing/selftests/kvm/x86/pvclock_test.c +++ b/tools/testing/selftests/kvm/x86/pvclock_test.c @@ -189,6 +189,8 @@ static void run_at_frequency(u64 tsc_khz, unsigned int = sleep_sec) =20 static void test_tsc_stable_bit(void); static void test_clock_guest_with_offsets(void); +static void test_legacy_msr(void); +static void run_vcpu_once(struct kvm_vcpu *vcpu); =20 static void usage(const char *name) { @@ -251,10 +253,71 @@ int main(int argc, char *argv[]) =20 test_tsc_stable_bit(); test_clock_guest_with_offsets(); + test_legacy_msr(); =20 return 0; } =20 +static void guest_code_legacy_msr(void) +{ + wrmsr(MSR_KVM_SYSTEM_TIME, KVMCLOCK_GPA | KVM_MSR_ENABLED); + GUEST_SYNC(0); + /* Re-request the time, as SUSE's 2.6.16 kernel would. */ + wrmsr(MSR_KVM_SYSTEM_TIME, KVMCLOCK_GPA | KVM_MSR_ENABLED); + GUEST_SYNC(1); +} + +/* + * A guest using the legacy MSR_KVM_SYSTEM_TIME must no longer lose the + * master clock, and rewriting the MSR must slide the reference point + * forward so the pvclock's tsc_timestamp is recent =E2=80=94 that freshne= ss is + * what SUSE's 2.6.16 kernel demands instead of tolerating a fixed + * reference point. + */ +static void test_legacy_msr(void) +{ + struct pvclock_vcpu_time_info *pvti; + struct kvm_clock_data clock; + struct kvm_vcpu *vcpu; + struct kvm_vm *vm; + u64 tsc_now, age_limit; + + pr_info("Testing the legacy MSR_KVM_SYSTEM_TIME\n"); + + vm =3D vm_create_with_one_vcpu(&vcpu, guest_code_legacy_msr); + configure_pvclock(vm); + + run_vcpu_once(vcpu); + vm_ioctl(vm, KVM_GET_CLOCK, &clock); + TEST_ASSERT(clock.flags & KVM_CLOCK_TSC_STABLE, + "Legacy MSR_KVM_SYSTEM_TIME should not disable the master clock"); + + /* Age the master clock reference point, then re-request. */ + usleep(300 * 1000); + run_vcpu_once(vcpu); + + pvti =3D addr_gpa2hva(vm, KVMCLOCK_GPA); + tsc_now =3D vcpu_get_msr(vcpu, MSR_IA32_TSC); + + /* + * The rewrite slid the reference point, so the pvclock must be + * anchored after the 300ms sleep: allow 250ms of slack for the + * ioctls around it. SUSE's real threshold was 1/5 jiffie, but + * asserting that tightly would flake on a loaded host. + */ + age_limit =3D (u64)__vcpu_ioctl(vcpu, KVM_GET_TSC_KHZ, NULL) * 250; + TEST_ASSERT(tsc_now - pvti->tsc_timestamp < age_limit, + "pvclock tsc_timestamp should be fresh after legacy MSR rewrite (age= %llu cycles, limit %llu)", + (unsigned long long)(tsc_now - pvti->tsc_timestamp), + (unsigned long long)age_limit); + + vm_ioctl(vm, KVM_GET_CLOCK, &clock); + TEST_ASSERT(clock.flags & KVM_CLOCK_TSC_STABLE, + "Master clock should survive a legacy MSR rewrite"); + + kvm_vm_free(vm); +} + static volatile u32 vcpu_counter; static void guest_code_stable_bit(void) { --=20 2.43.0