* [PATCH common/qemu-server v5 0/4] vCPU binding for qemu guests
@ 2026-11-24 13:18 Elias Huhsovitz
2026-11-24 13:18 ` [PATCH qemu-server v5 1/4] helpers: return integer values for parse_number_sets Elias Huhsovitz
` (3 more replies)
0 siblings, 4 replies; 5+ messages in thread
From: Elias Huhsovitz @ 2026-11-24 13:18 UTC (permalink / raw)
To: pve-devel; +Cc: Elias Huhsovitz
This series adds a more convinient way to achive vCPU:CPU binding in PVE.
It is configurable using the the new key `cpu-binding`.
2 functional modes are added:
mode=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 pins an N-vCPU VM to host CPUs 0, 1, ..., N-1.
Examples:
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
mode=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
Why this is in perl now
-----------------------
After the discussion on the ML [0], I did some more testing and
decided to hold off on the rust code for now. There is currently only
minimal real world benefit for using rust.
But this might change in the future if we need more detailed Topology
information. e.g., complete automatic cpu pinning modes that respect
NUMA, Cache, PCI Devices, multiple vms, etc.
Then something like hwloc [1] comes in handy. If adding the external
depency is not an option or we need some kind of custom implementation,
then I suggest a new rust crate:
Exposing a Hardware Topology. The Topology exposes generic API functions to
(1) query toplogy information.
(2) Make complex decisions about placement. e.g.
Given VMs V, Configs C, with passed through devices D: provide me
with a cpu pinning + passthrough configuration for all VMs ∈ V that
maximize metric m. Metic m, could be something like maximizing GPU
NUMA memory locality.
Reproducibility
------------------
To make vCPU placement reproduceable, the config is deterministically
generated using the 3 configuration keys:
* affinity
* cpu-binding
* numa[N] config keys
Two VMs with the same config on the same host
should get the same placement. (unless there is some randomness that I
am unaware of)
Basic usage example
--------------
# One vCPU executes on exactly one host cpu (under affinity mask)
qm set <vmid> --cpu-binding mode=one-to-one
qm set <vmid> --affinity 4-7
# NUMA binding (explicit):
#Guest NUMA 0 -> host NUMA 2, guest NUMA 1 -> host NUMA 3
qm set <vmid> --numa 1
qm set <vmid> --cpu-binding mode=numa
qm set <vmid> --numa0 cpus=0-1,hostnodes=0,memory=1024,policy=bind
qm set <vmid> --numa1 cpus=2-3,hostnodes=1,memory=1024,policy=bind
I plan on adding implicit NUMA binding in the future, e.g.,
# NUMA binding (implicit):
# for each socket: one numa node is created and bound
# e.g., 2 sockets: numa0:host-numa0, numa1:host-numa:1
qm set <vmid> --numa 1
So that a user can simply enable numa bindign mode and automatically
have a sensible config utilizing the numa capeability of his hardware.
But for this I would like to refactor the Memory.pm first to unify the
how the numa[N] config is created and used. This will be provided in
a subsequent patch, or the next version of this series(if a need one is
needed).
Validation runs at VM start. Binding itself runs after QEMU spawns the
vCPU threads (The VM is frozen at start, until the affinity of the
vCPUs has been set)
What is not in this PATCH
----------------------------
* memory_binding: This is best handled by qemu directly and already
possible via, e.g.:
numa0: cpus=0-1,hostnodes=1,memory=2048,policy=bind
numa1: cpus=2-3,hostnodes=2,memory=2048,policy=bind
numa2: cpus=4-5,hostnodes=3,memory=2048,policy=bind
numa3: cpus=6-7,hostnodes=4,memory=2048,policy=bind
What we need is a convinient way to automatically apply the correct
memory bindingings for the numa node. This is will be handled in an
upcoming adjacent patch.
* Qemu I/O Thread control/binding
* CPU Isolation
I plan on adding most of the features requested in the forum post [2].
Changes v4->v5
--------------
* Refactor code: rust --> perl.
* Drop the toplogy tree data structure. IMO this only makes sense in a
typed language and might come back in the future if need it in the
future (e.g. for complex automatic pinning strategies).
* always start qemu using taskset if affinity is configured.
(i.e. current implementation on master)
* support cpu hotplug.
* Hold off on the "allow-smt-siblings" option for now.
* comment why starting the vm in frozen state is necesarry.
* die when vm is unable to be unfrozen.
Changes v3->v4
-----------------
* Drop the manual modes (manual, numa-manual).
* All modes respect the affnity setting.
* numa mode utilizes the numa[N] config.
* Freeze guest until sched_setaffinity has finished to avoid using
non-specified host cpus during startup sequence.
* Build cpu toplogy from sysfs instead of hwloc [1].
7. Previous versions
---------------------
v4: https://lore.proxmox.com/pve-devel/20261111152027.260117-1-e.huhsovitz@proxmox.com/
v3: https://lore.proxmox.com/pve-devel/20261022092227.58871-1-e.huhsovitz@proxmox.com/
v2: https://lore.proxmox.com/pve-devel/20260921095404.61552-1-e.huhsovitz@proxmox.com/
v1: https://lore.proxmox.com/pve-devel/20260217114813.2063770-1-d.csapak@proxmox.com/
v1 was originally introduced by Dominik C.
8. References
-------------
[0] https://lore.proxmox.com/pve-devel/4f5ed842-1699-45d6-895b-e5fb664bd195@proxmox.com/
[1] https://hwloc.readthedocs.io/en/hwloc-2.15.0/doxygen/html/index.html
[2] https://forum.proxmox.com/threads/hey-proxmox-community-lets-talk-about-resources-isolation.124256/
Thank you to whoever reviews this! :)
Summary of changes
------------------
qemu-server:
Elias Huhsovitz (2):
helpers: return integer values for parse_number_sets
cpu: add cpu-binding
src/PVE/QemuServer.pm | 44 ++++++-
src/PVE/QemuServer/CPUBind.pm | 222 ++++++++++++++++++++++++++++++++++
src/PVE/QemuServer/Helpers.pm | 6 +-
src/PVE/QemuServer/Makefile | 1 +
src/PVE/QemuServer/Memory.pm | 45 ++++++-
5 files changed, 312 insertions(+), 6 deletions(-)
create mode 100644 src/PVE/QemuServer/CPUBind.pm
pve-common:
Elias Huhsovitz (2):
syscall: add sched_setaffinity
cpuset: generalize to improve usability for sysfs cpusets.
src/PVE/CpuSet.pm | 42 ++++++++++++++++++++++++++++++++----------
src/PVE/Syscall.pm | 1 +
2 files changed, 33 insertions(+), 10 deletions(-)
Summary over all repositories:
7 files changed, 345 insertions(+), 16 deletions(-)
--
Generated by murpp 0.12.0
^ permalink raw reply [flat|nested] 5+ messages in thread
* [PATCH qemu-server v5 1/4] helpers: return integer values for parse_number_sets
2026-11-24 13:18 [PATCH common/qemu-server v5 0/4] vCPU binding for qemu guests Elias Huhsovitz
@ 2026-11-24 13:18 ` Elias Huhsovitz
2026-11-24 13:18 ` [PATCH qemu-server v5 2/4] cpu: add cpu-binding Elias Huhsovitz
` (2 subsequent siblings)
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
Currently the ranges returned by parse_number_sets are stored as
strings. Historically this has not been a problem, since the ranges
havent been used for calculation.
New callers of this function might expect an integer value, instead of
string.
Convert the returned value to an integer.
Signed-off-by: Elias Huhsovitz <e.huhsovitz@proxmox.com>
Reviewed-by: Dominik Csapak <d.csapak@proxmox.com>
---
src/PVE/QemuServer/Helpers.pm | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/PVE/QemuServer/Helpers.pm b/src/PVE/QemuServer/Helpers.pm
index 644287bc..cc68f0fd 100644
--- a/src/PVE/QemuServer/Helpers.pm
+++ b/src/PVE/QemuServer/Helpers.pm
@@ -301,7 +301,11 @@ sub parse_number_sets {
foreach my $part (split(/;/, $set)) {
if ($part =~ /^\s*(\d+)(?:-(\d+))?\s*$/) {
die "invalid range: $part ($2 < $1)\n" if defined($2) && $2 < $1;
- push @$res, [$1, $2];
+
+ my $start = int($1);
+ my $end = defined($2) ? int($2) : undef;
+
+ push @$res, [$start, $end];
} else {
die "invalid range: $part\n";
}
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread
* [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
* [PATCH common v5 3/4] syscall: add sched_setaffinity
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 ` [PATCH qemu-server v5 2/4] cpu: add cpu-binding Elias Huhsovitz
@ 2026-11-24 13:18 ` 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
This will be required for vCPU to CPU pinning.
Signed-off-by: Elias Huhsovitz <e.huhsovitz@proxmox.com>
---
src/PVE/Syscall.pm | 1 +
1 file changed, 1 insertion(+)
diff --git a/src/PVE/Syscall.pm b/src/PVE/Syscall.pm
index f57e48f..4cc6cc3 100644
--- a/src/PVE/Syscall.pm
+++ b/src/PVE/Syscall.pm
@@ -44,6 +44,7 @@ BEGIN {
exit => &SYS_exit,
exit_group => &SYS_exit_group,
brk => &SYS_brk,
+ sched_setaffinity => &SYS_sched_setaffinity,
# Below aren't yet in perl's syscall.ph but use asm-generic, so the same across (sane) archs
# -> none unknown currently, yay
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread
* [PATCH common v5 4/4] cpuset: generalize to improve usability for sysfs cpusets.
2026-11-24 13:18 [PATCH common/qemu-server v5 0/4] vCPU binding for qemu guests Elias Huhsovitz
` (2 preceding siblings ...)
2026-11-24 13:18 ` [PATCH common v5 3/4] syscall: add sched_setaffinity Elias Huhsovitz
@ 2026-11-24 13:18 ` 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 from_str/from_path to create cpuset directly from string/path.
Utilize from_path in existing new_from_path subroutine.
Add intersect between two CpuSet.
Add member_keys to get a list of all unsorted members.
Remove redundant for loop in is_equal by adding guard clause that
compares set sizes.
Signed-off-by: Elias Huhsovitz <e.huhsovitz@proxmox.com>
---
src/PVE/CpuSet.pm | 42 ++++++++++++++++++++++++++++++++----------
1 file changed, 32 insertions(+), 10 deletions(-)
diff --git a/src/PVE/CpuSet.pm b/src/PVE/CpuSet.pm
index 7023b8f..1f6de4c 100644
--- a/src/PVE/CpuSet.pm
+++ b/src/PVE/CpuSet.pm
@@ -15,6 +15,18 @@ sub new {
return $self;
}
+sub from_str {
+ my ($class, $s) = @_;
+ my (undef, $members) = PVE::CpuSet::parse_cpuset($s);
+ return $class->new($members);
+}
+
+sub from_path {
+ my ($class, $path) = @_;
+ my $content = PVE::File::file_read_first_line($path) // '';
+ return $class->from_str($content);
+}
+
# Create a new set with the contents of a cgroup-v1 subdirectory.
# Deprecated:
sub new_from_cgroup {
@@ -24,7 +36,7 @@ sub new_from_cgroup {
}
# Create a new set from the contents of a complete path to a cgroup directory.
-sub new_from_path {
+sub new_from_path { # TODO: naming is inaccurate and should be changed to e.g. 'from_cgroup_path'
my ($class, $path, $effective) = @_;
my $filename;
@@ -38,11 +50,7 @@ sub new_from_path {
$filename = "$path/cpuset.cpus";
}
- my $set_text = PVE::File::file_read_first_line($filename) // '';
-
- my ($count, $members) = parse_cpuset($set_text);
-
- return $class->new($members);
+ return $class->from_path($filename);
}
sub parse_cpuset {
@@ -122,6 +130,16 @@ sub delete {
return $count;
}
+sub intersect {
+ my ($self, $other) = @_;
+
+ my $res = __PACKAGE__->new();
+ for my $cpu (keys $self->{members}->%*) {
+ $res->insert($cpu) if $other->has($cpu);
+ }
+ return $res;
+}
+
sub has {
my ($self, $cpuid) = @_;
@@ -136,6 +154,11 @@ sub members {
return @sorted_members;
}
+sub member_keys {
+ my ($self) = @_;
+ return keys %{ $self->{members} };
+}
+
sub size {
my ($self) = @_;
@@ -148,11 +171,10 @@ sub is_equal {
my $members1 = $self->{members};
my $members2 = $set2->{members};
+ return 0 if keys(%$members1) != keys(%$members2);
+
foreach my $id (keys %$members1) {
- return 0 if !$members2->{$id};
- }
- foreach my $id (keys %$members2) {
- return 0 if !$members1->{$id};
+ return 0 if !exists $members2->{$id};
}
return 1;
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread
end of thread, other threads:[~2026-11-24 13:19 UTC | newest]
Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
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 ` [PATCH qemu-server v5 2/4] cpu: add cpu-binding 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
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.