* [PATCH qemu-server v5 2/4] cpu: add cpu-binding
2026-11-24 13:18 [PATCH common/qemu-server v5 0/4] vCPU binding for qemu guests Elias Huhsovitz
2026-11-24 13:18 ` [PATCH qemu-server v5 1/4] helpers: return integer values for parse_number_sets Elias Huhsovitz
@ 2026-11-24 13:18 ` Elias Huhsovitz
2026-11-24 13:18 ` [PATCH common v5 3/4] syscall: add sched_setaffinity Elias Huhsovitz
2026-11-24 13:18 ` [PATCH common v5 4/4] cpuset: generalize to improve usability for sysfs cpusets Elias Huhsovitz
3 siblings, 0 replies; 5+ messages in thread
From: Elias Huhsovitz @ 2026-11-24 13:18 UTC (permalink / raw)
To: pve-devel; +Cc: Elias Huhsovitz
Add a 'cpu-binding' property string with a 'mode' key.
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 <d.csapak@proxmox.com>
Signed-off-by: Elias Huhsovitz <e.huhsovitz@proxmox.com>
---
src/PVE/QemuServer.pm | 44 ++++++-
src/PVE/QemuServer/CPUBind.pm | 222 ++++++++++++++++++++++++++++++++++
src/PVE/QemuServer/Makefile | 1 +
src/PVE/QemuServer/Memory.pm | 45 ++++++-
4 files changed, 307 insertions(+), 5 deletions(-)
create mode 100644 src/PVE/QemuServer/CPUBind.pm
diff --git a/src/PVE/QemuServer.pm b/src/PVE/QemuServer.pm
index ecbaa27f..7b9deb43 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::CPUBind;
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::CPUBind::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::CPUBind::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::CPUBind::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::CPUBind::rebind_vcpus($vmid, $conf) };
+ log_warn("unable to bind vCPU threads after hotplug - $@") if $@;
}
}
@@ -5559,6 +5567,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
@@ -5584,10 +5594,24 @@ sub vm_start_nolock {
},
);
+ $vcpu_binding_map = PVE::QemuServer::CPUBind::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);
@@ -5806,6 +5830,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::CPUBind::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/CPUBind.pm b/src/PVE/QemuServer/CPUBind.pm
new file mode 100644
index 00000000..9af17f69
--- /dev/null
+++ b/src/PVE/QemuServer/CPUBind.pm
@@ -0,0 +1,222 @@
+package PVE::QemuServer::CPUBind;
+
+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;
+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_path(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->member_keys()) {
+ $bindings->{$vcpu} = $host_cpus;
+ }
+}
+
+my sub numa_bindings($conf, $available) {
+ my $vnodes_cfg = PVE::QemuServer::Memory::numa_conf_to_map($conf);
+
+ my $host_nodes = host_numa_cpus($available);
+ die "host exposes no NUMA nodes with available CPUs\n" if !%$host_nodes;
+
+ my $bindings = {};
+ # Indexed by virtual node ID, so iteration order is numeric.
+ for my $vnode_id (0 .. $#$vnodes_cfg) {
+ my $vnode_cfg = $vnodes_cfg->[$vnode_id];
+
+ my @hostnodes = $vnode_cfg->{hostnodes}->members();
+ # unsupported config: numa[N]: ...,hostnodes=X-Y,...
+ die "guest NUMA node $vnode_id must map to exactly one host NUMA node\n"
+ if @hostnodes != 1;
+
+ my $hnode_id = $hostnodes[0];
+ my $host_cpus = $host_nodes->{$hnode_id};
+ die "host NUMA node $hnode_id does not exist or has no available CPUs\n" if !$host_cpus;
+
+ add_vcpu_bindings($bindings, $vnode_cfg->{vcpus}, $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) {
+ my $mode = parse_binding_property($conf->{'cpu-binding'})->{mode};
+ return if $mode eq 'none';
+
+ my $nr_vcpus = $conf->{sockets} * $conf->{cores};
+ my $affinity = PVE::CpuSet->from_str($conf->{affinity} // '');
+ my $available = PVE::CpuSet->from_path(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}->member_keys());
+ }
+}
+
+# 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..c4cd9077 100644
--- a/src/PVE/QemuServer/Makefile
+++ b/src/PVE/QemuServer/Makefile
@@ -8,6 +8,7 @@ SOURCES=Agent.pm \
Cfg2Cmd.pm \
CGroup.pm \
Cloudinit.pm \
+ CPUBind.pm \
CPUConfig.pm \
CPUFlags.pm \
DBusVMState.pm \
diff --git a/src/PVE/QemuServer/Memory.pm b/src/PVE/QemuServer/Memory.pm
index 2dbf2dc7..70969b55 100644
--- a/src/PVE/QemuServer/Memory.pm
+++ b/src/PVE/QemuServer/Memory.pm
@@ -87,6 +87,50 @@ our $memory_fmt = {
},
};
+my sub number_sets_to_cpuset {
+ my ($sets) = @_;
+ my $cpus = PVE::CpuSet->new();
+ for my $range (@{ $sets // [] }) {
+ my ($first, $last) = @$range;
+ $cpus->insert($first .. ($last // $first));
+ }
+ return $cpus;
+}
+
+# Returns the effective guest NUMA topology as an array reference indexed by guest
+# NUMA node ID. Each entry holds 'vcpus' and 'hostnodes' as PVE::CpuSet objects.
+# Without an explicit numa[N] configuration this mirrors what config() passes to
+# QEMU: one node per socket, mapped 1:1 onto host NUMA nodes. Gaps in the numa[N]
+# numbering leave undefined entries.
+sub numa_conf_to_map {
+ my ($conf) = @_;
+ my $nodes = [];
+ my $custom = 0;
+
+ for (my $i = 0; $i < $MAX_NUMA; $i++) {
+ my $entry = $conf->{"numa$i"} or next;
+ $custom = 1;
+ my $numa = parse_numa($entry);
+ $nodes->[$i] = {
+ vcpus => number_sets_to_cpuset($numa->{cpus}),
+ hostnodes => number_sets_to_cpuset($numa->{hostnodes}),
+ };
+ }
+ return $nodes if $custom;
+ return [] if !$conf->{numa};
+
+ my $sockets = $conf->{sockets} || 1;
+ my $cores = $conf->{cores} || 1;
+ for (my $i = 0; $i < $sockets; $i++) {
+ my $first = $cores * $i;
+ $nodes->[$i] = {
+ vcpus => PVE::CpuSet->new({ map { $_ => 1 } ($first .. $first + $cores - 1) }),
+ hostnodes => PVE::CpuSet->new({ $i => 1 }),
+ };
+ }
+ return $nodes;
+}
+
sub print_memory {
my $memory = shift;
@@ -824,4 +868,3 @@ sub hugepages_update_locked {
return $res;
}
1;
-
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread