From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 69DF51FF0C2 for ; Thu, 03 Dec 2026 11:53:49 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 2B21B21822; Thu, 03 Dec 2026 11:53:14 +0100 (CET) From: Elias Huhsovitz To: pve-devel@lists.proxmox.com Subject: [PATCH qemu-server v6 5/5] cpu: add affinity module Date: Thu, 3 Dec 2026 11:53:00 +0100 Message-ID: <20261203105300.70656-6-e.huhsovitz@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261203105300.70656-1-e.huhsovitz@proxmox.com> References: <20261203105300.70656-1-e.huhsovitz@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796295187204 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.618 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) KAM_MAILER 2 Automated Mailer Tag Left in Email 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: G4O7B4UUBJK3QEFVEFZWILJVN4OYBOKJ X-Message-ID-Hash: G4O7B4UUBJK3QEFVEFZWILJVN4OYBOKJ X-MailFrom: e.huhsovitz@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 CC: Elias Huhsovitz X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Move affinity logic into new CPUAffinity.pm module. Add a 'cpu-binding' property string with a 'mode' key. CPU Binding Modes: (1) none (default): no binding, regular scheduling. (2) one-to-one: pin each vCPU to a single host CPU, picking the lowest CPU IDs from the online CPUs filtered by 'affinity'. Requires at least as many host CPUs as vCPUs. (3) numa: bind the vCPUs of each guest NUMA node to all host CPUs of the host NUMA node given by numa[N] hostnodes, so the scheduler can still balance within the node while memory access stays local. The host topology is read from sysfs (cpu/online, node/nodeN/cpulist). The generated vCPU -> host CPU map is applied via sched_setaffinity(2) using the TIDs from query-cpus-fast. Generation and validation happen before QEMU starts, application afterwards. Because affinity is just an upper bound, start the guest frozen (-S) when a binding map exists, so no vCPU executes outside its target set before the binding is applied. Re-apply the binding after CPU hotplug. A newly plugged thread runs unbound for a short window, which is unavoidable without pausing the guest. Unplug needs no action. Originally-by: Dominik Csapak Signed-off-by: Elias Huhsovitz --- src/PVE/QemuServer.pm | 44 +++++- src/PVE/QemuServer/CPUAffinity.pm | 220 ++++++++++++++++++++++++++++++ src/PVE/QemuServer/Makefile | 1 + 3 files changed, 261 insertions(+), 4 deletions(-) create mode 100644 src/PVE/QemuServer/CPUAffinity.pm diff --git a/src/PVE/QemuServer.pm b/src/PVE/QemuServer.pm index 1d665877..234ed866 100644 --- a/src/PVE/QemuServer.pm +++ b/src/PVE/QemuServer.pm @@ -62,6 +62,7 @@ use PVE::QemuServer::Helpers qw(config_aware_timeout get_iscsi_initiator_name get_host_arch min_version kvm_user_version windows_version); use PVE::QemuServer::Cloudinit; use PVE::QemuServer::CGroup; +use PVE::QemuServer::CPUAffinity; use PVE::QemuServer::CPUConfig qw( print_cpu_device get_cpu_options @@ -754,6 +755,12 @@ EODESCR optional => 1, default => 1, }, + 'cpu-binding' => { + type => 'string', + format => $PVE::QemuServer::CPUAffinity::cpu_binding_fmt, + description => "Set CPU binding mode for the guest", + optional => 1, + }, }; my $cicustom_fmt = { @@ -3207,10 +3214,7 @@ sub config_to_command { my $use_old_bios_files = undef; ($use_old_bios_files, $machine_type) = qemu_use_old_bios_files($machine_type); - my $cmd = []; - if (defined($conf->{affinity})) { - push @$cmd, '/usr/bin/taskset', '--cpu-list', '--all-tasks', $conf->{affinity}; - } + my $cmd = PVE::QemuServer::CPUAffinity::affinity_cmd_prefix($conf); push @$cmd, $kvm_binary; @@ -4340,12 +4344,16 @@ sub qemu_cpu_hotplug { #update conf after each successful cpu hotplug $conf->{vcpus} = scalar(@{$currentrunningvcpus}); PVE::QemuConfig->write_config($vmid, $conf); + eval { PVE::QemuServer::CPUAffinity::rebind_vcpus($vmid, $conf, $currentrunningvcpus) }; + log_warn("unable to bind vCPU threads after hotplug - $@") if $@; } } else { for (my $i = $currentvcpus; $i < $vcpus; $i++) { mon_cmd($vmid, "cpu-add", id => int($i)); } + eval { PVE::QemuServer::CPUAffinity::rebind_vcpus($vmid, $conf) }; + log_warn("unable to bind vCPU threads after hotplug - $@") if $@; } } @@ -5567,6 +5575,8 @@ sub vm_start_nolock { my ($cmd, $spice_port, $start_timeout); my $pci_reserve_list = []; + my $vcpu_binding_map; + my $freeze_for_binding = 0; eval { # With -blockdev, it is necessary to activate the volumes before generating the command line # Plugins can safely deactivate already-active volumes here if needed @@ -5592,10 +5602,24 @@ sub vm_start_nolock { }, ); + $vcpu_binding_map = PVE::QemuServer::CPUAffinity::conf_to_vcpu_bindings($conf); + + # Bind before the guest executes anything. Without -S, QEMU's vCPU threads start + # running as soon as they are created, so they could execute on host CPUs outside + # their intended binding until bind_vcpus() runs. Skip the cases that already start + # frozen and resume the guest themselves (backup, incoming migration, rollback with + # RAM), and the case where the user explicitly wants the guest to stay frozen. + $freeze_for_binding = + $vcpu_binding_map + && !$params->{paused} + && !$statefile + && !$conf->{freeze}; + my $memory = get_current_memory($conf->{memory}); $start_timeout = $params->{timeout} // config_aware_timeout($conf, $memory, $resume); push $cmd->@*, $state_cmdline->@*; + push @$cmd, '-S' if $freeze_for_binding; ($pci_reserve_list, my $uuid) = PVE::QemuServer::PCI::prepare_pci_devices($conf, $vmid, $pci_devices, $start_timeout); @@ -5814,6 +5838,18 @@ sub vm_start_nolock { my $qemu_pkg_string = PVE::QemuServer::QMPHelpers::get_qemu_package_string($vmid); syslog("info", "VM $vmid started with PID $pid using $qemu_pkg_string."); + if ($vcpu_binding_map) { + eval { PVE::QemuServer::CPUAffinity::bind_vcpus($vmid, $vcpu_binding_map) }; + log_warn("unable to bind vCPU threads - $@") if $@; + } + + if ($freeze_for_binding) { + eval { mon_cmd($vmid, 'cont'); }; + # Surface the failure instead of reporting a successful start while the guest + # stays frozen. Stopping a successfully started guest would be worse. + die "failed to resume VM after CPU binding - $@" if $@; + } + if (defined(my $migrate = $res->{migrate})) { if ($migrate->{proto} eq 'tcp') { my $nodename = nodename(); diff --git a/src/PVE/QemuServer/CPUAffinity.pm b/src/PVE/QemuServer/CPUAffinity.pm new file mode 100644 index 00000000..506198ad --- /dev/null +++ b/src/PVE/QemuServer/CPUAffinity.pm @@ -0,0 +1,220 @@ +package PVE::QemuServer::CPUAffinity; + +use v5.36; + +use PVE::CpuSet; +use PVE::JSONSchema qw(parse_property_string); +use PVE::Syscall; +use PVE::Tools qw(dir_glob_foreach); + +use PVE::QemuServer::Memory qw (get_current_memory get_effective_numa_cfg); +use PVE::QemuServer::Monitor qw(mon_cmd); + +use constant { + CPU_DIR => '/sys/devices/system/cpu', + NODE_DIR => '/sys/devices/system/node', +}; + +our $cpu_binding_fmt = { + mode => { + type => 'string', + enum => [qw(none one-to-one numa)], + default => 'none', + default_key => 1, + optional => 1, + description => "Determines how guest vCPUs are bound to host CPUs.", + verbose_description => <<'EODESCR', +Determines how guest vCPUs are bound/pinned to host CPUs. + +* none (default): no binding. Regular scheduling. + +* one-to-one: bind each vCPU to its own host CPU, chosen from the pool +configured by affinity. The configured affinity string acts as an upper +bound on the host CPUs that can be used for binding. +If the guest has N vCPUs and the affinity pool has M host CPUs, each vCPU +is fixed to a single one of the M host CPUs (M >= N must be true). +Each vCPU is fixed to a single host CPU, it does not float within the pool. + +An empty affinity string means all host CPUs will be considered. +On a host with 16 cores, that binds an N-vCPU VM to host CPUs +0, 1, ..., N-1. + +Example 1: 4-vCPU guest with affinity=4-9: +The resulting mapping would be: vCPU0:CPU4, vCPU1:CPU5, vCPU2:CPU6, +vCPU3:CPU7. + +Example 2: 4-vCPU guest with affinity=0,2: +The resulting mapping would be: vCPU0:CPU0, vCPU1:CPU2 + +* numa: bind the set of vCPUs of each vNUMA node to the set of CPUs of a +host NUMA node. The CPU bindings are determined by the numa[N] +configuration of the guest. If no numa[N] config is explicitly provided, +then for each socket a numa[N] node is created. +Each guest vNUMA node's vCPUs form a group that may run on any CPU of the +assigned host NUMA node. The host scheduler is free to migrate the vCPUs +within the host node. This is the intended trade-off: memory allocated by +a vCPU stays local to the host node it runs on (preserving NUMA memory +locality), while the scheduler still has room to balance load across the +node's cores and hyperthreads. + +Examples: + +numa0: cpus=0-1,hostnodes=0,memory=2048,policy=bind +Allows vCPUs 0-1 to execute on all CPUs of host NUMA node 0 + +numa1: cpus=6-7,hostnodes=3,memory=2048,policy=bind +Allows vCPUs 6-7 to execute on all CPUs of host NUMA node 3 + +numa:1, no numa[N], sockets: 2, cores: 2, total vCPUs: 4 +Allows vCPUs 0-1 to execute on all CPUs of host NUMA node 0 +Allows vCPUs 2-3 to execute on all CPUs of host NUMA node 1 +EODESCR + }, + # Planned options: 'allow-smt-siblings' to control whether vCPUs may share a + # physical core. Adding it requires reading cpuN/topology/thread_siblings_list. +}; + +my sub parse_binding_property($value) { + my $res = parse_property_string($cpu_binding_fmt, $value // ''); + $res->{mode} = 'none' if !defined($res->{mode}); + return $res; +} + +# Returns the argv prefix confining the whole QEMU process to the configured affinity. +# Applying this before exec means every thread QEMU creates inherits the mask. +# Per-vCPU binding can only narrow it further. +sub affinity_cmd_prefix($conf) { + my $affinity = $conf->{affinity}; + return [] if !defined($affinity) || $affinity eq ''; + return ['/usr/bin/taskset', '--cpu-list', '--all-tasks', $affinity]; +} + +my sub one_to_one_bindings($nr_vcpus, $available) { + # members() is sorted, so the lowest available CPU IDs are picked deterministically. + my @cpus = $available->members(); + + die "one-to-one binding needs $nr_vcpus host CPUs, got " . scalar(@cpus) . "\n" + if @cpus < $nr_vcpus; + + my $bindings = {}; + for my $vcpu (0 .. $nr_vcpus - 1) { + $bindings->{$vcpu} = PVE::CpuSet->new({ $cpus[$vcpu] => 1 }); + } + return $bindings; +} + +# Maps host NUMA node ID to the available CPUs of that node. +my sub host_numa_cpus($available) { + my $nodes = {}; + dir_glob_foreach( + NODE_DIR, + 'node(\d+)', + sub($dir, $node) { + my $node_cpus = PVE::CpuSet->from_file(NODE_DIR . "/$dir/cpulist"); + my $available_node_cpus = $available->intersect($node_cpus); + return if $available_node_cpus->size() == 0; + $nodes->{$node} = $available_node_cpus; + }, + ); + return $nodes; +} + +my sub add_vcpu_bindings($bindings, $vcpus, $host_cpus) { + for my $vcpu ($vcpus->members_unsorted()) { + $bindings->{$vcpu} = $host_cpus; + } +} + +my sub numa_bindings($conf, $available) { + my $vnodes_cfg = get_effective_numa_cfg($conf, get_current_memory($conf->{memory}), 1); + + my $host_nodes_to_cpus = host_numa_cpus($available); + die "host exposes no NUMA nodes with available CPUs\n" if !%$host_nodes_to_cpus; + + my $bindings = {}; + for my $vnode (@$vnodes_cfg) { + my $vnode_id = $vnode->{id}; + + my @vnode_host_nodes = $vnode->{hostnodes}->members(); + # unsupported config: numa[N]: ...,hostnodes=X-Y,... + die "cpu-bind: guest NUMA node $vnode_id must map to exactly one host NUMA node\n" + if @vnode_host_nodes != 1; + + my $host_cpus = $host_nodes_to_cpus->{ $vnode_host_nodes[0] }; + + add_vcpu_bindings($bindings, $vnode->{cpus}, $host_cpus); + } + return $bindings; +} + +my sub sched_setaffinity($tid, @cpus) { + die "cannot apply an empty CPU affinity\n" if !@cpus; + + # Round up to a multiple of the kernel's unsigned long. A mask shorter than the + # kernel's cpumask is fine, the missing bits are treated as zero, which is what + # glibc's dynamically sized CPU_ALLOC relies on. + my ($max_cpu) = sort { $b <=> $a } @cpus; + my $mask = "\0" x (8 * (int($max_cpu / 64) + 1)); + for my $cpu (@cpus) { + vec($mask, $cpu, 1) = 1; + } + + my $res = syscall(PVE::Syscall::sched_setaffinity(), int($tid), length($mask), $mask); + die "sched_setaffinity failed for TID $tid - $!\n" if $res != 0; +} + +# Generates and validates the vCPU to host CPU binding map for a guest. +# +# Returns a hash reference mapping vCPU ID to a PVE::CpuSet of host CPUs, or +# undef if binding is disabled. +# Dies if the configuration cannot be applied. +sub conf_to_vcpu_bindings($conf) { + return if !$conf->{'cpu-binding'}; + my $mode = parse_binding_property($conf->{'cpu-binding'})->{mode}; + return if $mode eq 'none'; + + my $nr_vcpus = ($conf->{sockets} || 1) * ($conf->{cores} || 1); + my $affinity = PVE::CpuSet->from_str($conf->{affinity} // ''); + my $available = PVE::CpuSet->from_file(CPU_DIR . "/online"); + $available = $available->intersect($affinity) if $affinity->size() > 0; + + my $bindings; + if ($mode eq 'one-to-one') { + $bindings = one_to_one_bindings($nr_vcpus, $available); + } elsif ($mode eq 'numa') { + $bindings = numa_bindings($conf, $available); + } else { + die "unknown CPU binding mode '$mode'\n"; + } + + die "CPU binding mode '$mode' produced no vCPU bindings\n" if !%$bindings; + + return $bindings; +} + +# Applies a binding map generated by conf_to_vcpu_bindings() to a guest that has +# created its vCPU threads. Pass $cpuinfo if query-cpus-fast was already queried. +sub bind_vcpus($vmid, $bindings, $cpuinfo = undef) { + $cpuinfo = mon_cmd($vmid, 'query-cpus-fast') if !defined($cpuinfo); + my $vcpu_to_tid = {}; + for my $cpu (@$cpuinfo) { + $vcpu_to_tid->{ $cpu->{'cpu-index'} } = $cpu->{'thread-id'}; + } + + for my $vcpu (keys %$bindings) { + my $tid = $vcpu_to_tid->{$vcpu}; + next if !defined($tid); # not all configured vCPUs need to be plugged + sched_setaffinity($tid, $bindings->{$vcpu}->members_unsorted()); + } +} + +# Re-applies the binding after the set of present vCPUs changed. The plan depends only +# on the config and the host topology, so it is stable across calls, and re-applying an +# unchanged mask does not migrate a running thread. +sub rebind_vcpus($vmid, $conf, $cpuinfo = undef) { + my $bindings = conf_to_vcpu_bindings($conf); + return if !$bindings; + bind_vcpus($vmid, $bindings, $cpuinfo); +} + +1; diff --git a/src/PVE/QemuServer/Makefile b/src/PVE/QemuServer/Makefile index 61ed1a4e..e830f6e8 100644 --- a/src/PVE/QemuServer/Makefile +++ b/src/PVE/QemuServer/Makefile @@ -8,6 +8,7 @@ SOURCES=Agent.pm \ Cfg2Cmd.pm \ CGroup.pm \ Cloudinit.pm \ + CPUAffinity.pm \ CPUConfig.pm \ CPUFlags.pm \ DBusVMState.pm \ -- 2.47.3