From: Jonas Theisen <j.theisen@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH qemu-server v4 1/7] helpers: add helper to query the host's TSC frequency and scaling support
Date: Wed, 2 Dec 2026 18:45:18 +0100 [thread overview]
Message-ID: <20261202174530.565487-2-j.theisen@proxmox.com> (raw)
In-Reply-To: <20261202174530.565487-1-j.theisen@proxmox.com>
Keeping the time stamp counter (TSC) frequency of a VM across live
migrations requires the TSC frequency of the host the VM is started
on, and whether a target node can scale the TSC frequency for its
guests.
Query both directly from KVM, as nothing else exposes them reliably:
upstream Linux does not export the TSC frequency to user space, and
/proc/cpuinfo shows the TSC scaling flag in different places for Intel
and AMD CPUs, regardless of whether KVM uses it. KVM_GET_TSC_KHZ is a
vCPU ioctl, so a temporary VM with a single vCPU is created, which is
cheap, as no guest memory is set up.
If one query fails, the other value is still returned, and a failed
capability check is not mistaken for a missing capability, so that
consumers can tell unknown values from reported ones. The results are
cached, as they cannot change while the host runs, but only if all
queries succeeded. Failed queries are retried after ten minutes, as
callers like pvestatd query this regularly and each query creates a
KVM VM and logs a warning on failure. Without /dev/kvm, nothing is
returned or logged.
Signed-off-by: Jonas Theisen <j.theisen@proxmox.com>
---
src/PVE/QemuServer/Helpers.pm | 93 +++++++++++++++++++++++
src/test/Makefile | 5 +-
src/test/run_host_tsc_tests.pl | 133 +++++++++++++++++++++++++++++++++
3 files changed, 230 insertions(+), 1 deletion(-)
create mode 100755 src/test/run_host_tsc_tests.pl
diff --git a/src/PVE/QemuServer/Helpers.pm b/src/PVE/QemuServer/Helpers.pm
index 70f9c817..a871473e 100644
--- a/src/PVE/QemuServer/Helpers.pm
+++ b/src/PVE/QemuServer/Helpers.pm
@@ -3,6 +3,7 @@ package PVE::QemuServer::Helpers;
use strict;
use warnings;
+use Fcntl qw(O_RDWR);
use File::stat;
use IO::File;
@@ -364,6 +365,98 @@ sub get_host_phys_address_bits {
return; # undef, cannot really do anything..
}
+# KVM ioctl request numbers and capabilities, see include/uapi/linux/kvm.h in Linux
+my $KVM_CREATE_VM = 0xae01;
+my $KVM_CHECK_EXTENSION = 0xae03;
+my $KVM_CREATE_VCPU = 0xae41;
+my $KVM_GET_TSC_KHZ = 0xaea3;
+my $KVM_CAP_TSC_CONTROL = 60;
+my $KVM_CAP_GET_TSC_KHZ = 61;
+
+my $_host_tsc_info;
+# the incomplete result of the last failed query, and when to query again
+my ($_failed_host_tsc_info, $_host_tsc_info_retry_time);
+my $host_tsc_info_retry_delay_sec = 600;
+
+# KVM_GET_TSC_KHZ is a vCPU ioctl, so it needs a temporary VM with a single vCPU
+my sub query_vcpu_tsc_khz {
+ my ($kvm_fh) = @_;
+
+ my $vm_fd = ioctl($kvm_fh, $KVM_CREATE_VM, 0) // die "unable to create KVM VM - $!\n";
+ open(my $vm_fh, '+<&=', int($vm_fd)) or die "unable to open KVM VM fd - $!\n";
+
+ my $vcpu_fd = ioctl($vm_fh, $KVM_CREATE_VCPU, 0) // die "unable to create KVM vCPU - $!\n";
+ open(my $vcpu_fh, '+<&=', int($vcpu_fd)) or die "unable to open KVM vCPU fd - $!\n";
+
+ my $khz = ioctl($vcpu_fh, $KVM_GET_TSC_KHZ, 0) // die "KVM_GET_TSC_KHZ failed - $!\n";
+ return int($khz);
+}
+
+=head3 get_host_tsc_info
+
+ my $tsc_info = get_host_tsc_info();
+ my ($khz, $scaling) = $tsc_info->@{qw(khz scaling)};
+
+Returns a hash reference with information about the time stamp counter (TSC) of this host, as
+KVM reports it. C<khz> is the TSC frequency in kHz that KVM uses for new vCPUs. C<scaling> is true
+if KVM can run vCPUs with a different TSC frequency. A value is missing if KVM does not report it
+or querying it fails. Failed queries are logged as warnings, and do not affect the other value.
+
+The values are cached once all queries succeeded, as they cannot change while the host is running.
+After a failed query, the incomplete values are returned for ten minutes before querying again,
+as each query creates a KVM VM and callers like pvestatd query this regularly.
+
+Returns no values if C</dev/kvm> does not exist. Dies only if it exists, but cannot be opened.
+
+=cut
+
+sub get_host_tsc_info {
+ return $_host_tsc_info if defined($_host_tsc_info);
+ return $_failed_host_tsc_info
+ if defined($_host_tsc_info_retry_time)
+ && time() < $_host_tsc_info_retry_time;
+
+ my $kvm_fh;
+ if (!sysopen($kvm_fh, '/dev/kvm', O_RDWR)) {
+ return {} if $!{ENOENT}; # for example, KVM is not available on this host
+ die "unable to open /dev/kvm - $!\n";
+ }
+
+ my ($info, $complete) = ({}, 1);
+
+ # a failed check is not cached, unlike a capability KVM reports as unsupported
+ my $check_extension = sub {
+ my ($name, $cap) = @_;
+ my $res = ioctl($kvm_fh, $KVM_CHECK_EXTENSION, $cap);
+ return int($res) if defined($res);
+ warn "unable to check KVM capability $name - $!\n";
+ $complete = 0;
+ return;
+ };
+
+ my $tsc_control = $check_extension->('KVM_CAP_TSC_CONTROL', $KVM_CAP_TSC_CONTROL);
+ $info->{scaling} = $tsc_control ? 1 : 0 if defined($tsc_control);
+
+ if ($check_extension->('KVM_CAP_GET_TSC_KHZ', $KVM_CAP_GET_TSC_KHZ)) {
+ my $khz = eval { query_vcpu_tsc_khz($kvm_fh) };
+ if (my $err = $@) {
+ warn "unable to query the TSC frequency - $err";
+ $complete = 0;
+ } elsif ($khz > 0) {
+ $info->{khz} = $khz;
+ }
+ }
+
+ if ($complete) {
+ $_host_tsc_info = $info;
+ } else {
+ $_failed_host_tsc_info = $info;
+ $_host_tsc_info_retry_time = time() + $host_tsc_info_retry_delay_sec;
+ }
+
+ return $info;
+}
+
=head3 get_host_cpu_info
my $info = get_host_cpu_info();
diff --git a/src/test/Makefile b/src/test/Makefile
index 2d3a55da..706ce4fd 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -1,6 +1,6 @@
all: test
-test: test_snapshot test_cfg_to_cmd test_cfg_to_cmd_aarch64 test_hotplug test_hotplug_aarch64 test_pci_addr_conflicts test_pci_reservation test_qemu_img_convert test_migration test_restore_config test_parse_config test_memory test_agent test_raw_config_write test_api test_api_cloudinit_dump test_mtunnel test_guest_identity test_network
+test: test_snapshot test_cfg_to_cmd test_cfg_to_cmd_aarch64 test_hotplug test_hotplug_aarch64 test_pci_addr_conflicts test_pci_reservation test_qemu_img_convert test_migration test_restore_config test_parse_config test_memory test_agent test_raw_config_write test_api test_api_cloudinit_dump test_mtunnel test_guest_identity test_network test_host_tsc
test_snapshot: run_snapshot_tests.pl
./run_snapshot_tests.pl
@@ -66,6 +66,9 @@ test_mtunnel: run_mtunnel_tests.pl QemuServerTest/FakeCFS.pm QemuServerTest/MTun
test_guest_identity: run_guest_identity_tests.pl QemuServerTest/FakeCFS.pm
./run_guest_identity_tests.pl
+test_host_tsc: run_host_tsc_tests.pl
+ ./run_host_tsc_tests.pl
+
.PHONY: clean
clean:
rm -rf MigrationTest/run
diff --git a/src/test/run_host_tsc_tests.pl b/src/test/run_host_tsc_tests.pl
new file mode 100755
index 00000000..a1f21c78
--- /dev/null
+++ b/src/test/run_host_tsc_tests.pl
@@ -0,0 +1,133 @@
+#!/usr/bin/perl
+
+# Tests querying the TSC information of the host from KVM, with the KVM ioctls replaced by
+# predefined results.
+
+use v5.36;
+
+use lib qw(..);
+
+use Test::More;
+
+# The KVM ioctls of the helper are answered by $ioctl, by request number. /dev/kvm is replaced by
+# /dev/null, which also provides the file descriptors of the created VM and vCPU.
+my ($ioctl, $kvm_missing);
+# the time the helper sees, to test when it queries KVM again after a failed query
+my $now = 1_000_000;
+
+BEGIN {
+ *CORE::GLOBAL::time = sub { return $now; };
+ *CORE::GLOBAL::sysopen = sub : prototype(*$$;$) {
+ my (undef, $path) = @_;
+ die "unexpected sysopen of '$path'\n" if $path ne '/dev/kvm';
+ if ($kvm_missing) {
+ $! = 2; # ENOENT
+ return;
+ }
+ return open($_[0], '+<', '/dev/null');
+ };
+ *CORE::GLOBAL::ioctl = sub : prototype(*$$) {
+ my (undef, $request, $arg) = @_;
+ return $ioctl->($request, $arg);
+ };
+}
+
+use PVE::QemuServer::Helpers;
+
+open(my $null_fh, '+<', '/dev/null') or die "unable to open /dev/null - $!\n";
+
+my ($KVM_CREATE_VM, $KVM_CHECK_EXTENSION, $KVM_CREATE_VCPU, $KVM_GET_TSC_KHZ) =
+ (0xae01, 0xae03, 0xae41, 0xaea3);
+my ($KVM_CAP_TSC_CONTROL, $KVM_CAP_GET_TSC_KHZ) = (60, 61);
+
+# Each result is a number, or undef for an ioctl that fails with EIO. Perl's ioctl() returns
+# "0 but true" for 0.
+my sub mock_kvm {
+ my (%results) = @_;
+
+ $ioctl = sub {
+ my ($request, $arg) = @_;
+
+ my $res;
+ if ($request == $KVM_CHECK_EXTENSION) {
+ $res = $results{"cap-$arg"};
+ } elsif ($request == $KVM_CREATE_VM || $request == $KVM_CREATE_VCPU) {
+ $res = fileno($null_fh);
+ } elsif ($request == $KVM_GET_TSC_KHZ) {
+ $res = $results{khz};
+ } else {
+ die "unexpected ioctl $request\n";
+ }
+
+ if (!defined($res)) {
+ $! = 5; # EIO
+ return;
+ }
+ return $res == 0 ? "0 but true" : $res;
+ };
+}
+
+my sub tsc_info_test {
+ my ($name, $expected, $expected_warnings) = @_;
+
+ my @warnings;
+ local $SIG{__WARN__} = sub { push @warnings, $_[0] };
+
+ is_deeply(PVE::QemuServer::Helpers::get_host_tsc_info(), $expected, "$name: result");
+ is_deeply(
+ [map { s/\n$//r } @warnings], $expected_warnings // [], "$name: warnings",
+ );
+}
+
+# not cached, as KVM might become available later
+$kvm_missing = 1;
+tsc_info_test('no KVM', {});
+$kvm_missing = 0;
+
+# Results of failed queries are only kept until KVM is queried again after a delay, so these do
+# not affect each other.
+my $retry_delay = 600;
+
+mock_kvm("cap-$KVM_CAP_TSC_CONTROL" => 0, "cap-$KVM_CAP_GET_TSC_KHZ" => 1, khz => undef);
+tsc_info_test(
+ 'failing TSC frequency query keeps the reported lack of scaling',
+ { scaling => 0 },
+ ["unable to query the TSC frequency - KVM_GET_TSC_KHZ failed - Input/output error"],
+);
+
+$now += $retry_delay;
+mock_kvm("cap-$KVM_CAP_TSC_CONTROL" => undef, "cap-$KVM_CAP_GET_TSC_KHZ" => 1, khz => 2999999);
+tsc_info_test(
+ 'failing scaling check is not reported as lacking scaling',
+ { khz => 2999999 },
+ ["unable to check KVM capability KVM_CAP_TSC_CONTROL - Input/output error"],
+);
+
+$now += $retry_delay;
+mock_kvm("cap-$KVM_CAP_TSC_CONTROL" => 1, "cap-$KVM_CAP_GET_TSC_KHZ" => undef);
+tsc_info_test(
+ 'failing check for the TSC frequency query keeps the scaling support',
+ { scaling => 1 },
+ ["unable to check KVM capability KVM_CAP_GET_TSC_KHZ - Input/output error"],
+);
+
+$now += $retry_delay;
+mock_kvm("cap-$KVM_CAP_TSC_CONTROL" => undef, "cap-$KVM_CAP_GET_TSC_KHZ" => 1, khz => 0);
+tsc_info_test(
+ 'reported zero frequency is not a frequency',
+ {},
+ ["unable to check KVM capability KVM_CAP_TSC_CONTROL - Input/output error"],
+);
+
+# all queries succeed, so the results are cached, but only once KVM is queried again
+mock_kvm("cap-$KVM_CAP_TSC_CONTROL" => 1, "cap-$KVM_CAP_GET_TSC_KHZ" => 1, khz => 2999999);
+$now += $retry_delay - 1;
+tsc_info_test('failed query is not repeated before the delay', {});
+$now += 1;
+tsc_info_test('failed query is repeated after the delay', { scaling => 1, khz => 2999999 });
+
+mock_kvm();
+$now += $retry_delay;
+tsc_info_test('complete results are cached', { scaling => 1, khz => 2999999 });
+
+done_testing();
--
2.47.3
next prev parent reply other threads:[~2026-12-02 17:45 UTC|newest]
Thread overview: 8+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-02 17:45 [PATCH docs/qemu-server v4 0/7] live migrate VMs with an invariant TSC or re-enlightenment Jonas Theisen
2026-12-02 17:45 ` Jonas Theisen [this message]
2026-12-02 17:45 ` [PATCH qemu-server v4 2/7] migrate: allow CPU checks that only need information of the target Jonas Theisen
2026-12-02 17:45 ` [PATCH qemu-server v4 3/7] cpu config: add hv-reenlightenment flag and set TSC frequency for it Jonas Theisen
2026-12-02 17:45 ` [PATCH qemu-server v4 4/7] migrate: block migration to nodes that cannot provide the TSC frequency Jonas Theisen
2026-12-02 17:45 ` [PATCH qemu-server v4 5/7] cpu flags: report invtsc support of nodes Jonas Theisen
2026-12-02 17:45 ` [PATCH qemu-server v4 6/7] cpu config: set TSC frequency for invtsc to allow live migration Jonas Theisen
2026-12-02 17:45 ` [PATCH docs v4 7/7] qm: document hv-reenlightenment and invtsc Jonas Theisen
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261202174530.565487-2-j.theisen@proxmox.com \
--to=j.theisen@proxmox.com \
--cc=pve-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox