From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 8EFEF1FF0BC for ; Wed, 02 Dec 2026 18:45:51 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id DD40421766; Wed, 02 Dec 2026 18:45:47 +0100 (CET) From: Jonas Theisen 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 Message-ID: <20261202174530.565487-2-j.theisen@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261202174530.565487-1-j.theisen@proxmox.com> References: <20261202174530.565487-1-j.theisen@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796233542384 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.053 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: DZQWRCJ4JGL6WYMMIRORB6L5JMJXICWO X-Message-ID-Hash: DZQWRCJ4JGL6WYMMIRORB6L5JMJXICWO X-MailFrom: j.theisen@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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 is the TSC frequency in kHz that KVM uses for new vCPUs. C 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 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