* [PATCH qemu-server v6 4/5] memory: unify NUMA config parsing and resolution
2026-12-03 10:52 [PATCH common/qemu-server v6 0/5] vCPU binding for qemu guests Elias Huhsovitz
` (2 preceding siblings ...)
2026-12-03 10:52 ` [PATCH qemu-server v6 3/5] helpers: return integer values for parse_number_sets Elias Huhsovitz
@ 2026-12-03 10:52 ` Elias Huhsovitz
2026-12-03 11:34 ` Elias Huhsovitz
2026-12-03 10:53 ` [PATCH qemu-server v6 5/5] cpu: add affinity module Elias Huhsovitz
4 siblings, 1 reply; 7+ messages in thread
From: Elias Huhsovitz @ 2026-12-03 10:52 UTC (permalink / raw)
To: pve-devel; +Cc: Elias Huhsovitz
Currently NUMA configuration is read and interpreted at each call site.
Validation is scattered across differente paths, leading to inconsistent
rules when enabling NUMA with different additional options, such as
hugepages or memory hotplug.
Introduce a single resolver, `get_effective_numa_cfg()`, that parses all
custom numa[N] entries, auto-completes omitted memory and CPU
assignments, generates a default topology when none is configured, and
validates the result in one place . All three call sites now consume the
resolved node list instead of re-parsing the raw config.
As a side effect, users may now under-specify their NUMA config: omitted
memory values are distributed across the remaining nodes, and a fully
omitted CPU assignment is derived from sockets and cores.
Signed-off-by: Elias Huhsovitz <e.huhsovitz@proxmox.com>
---
src/PVE/QemuServer/Memory.pm | 444 +++++++++++++++++++----------------
src/test/run_memory_tests.pl | 31 ++-
2 files changed, 264 insertions(+), 211 deletions(-)
diff --git a/src/PVE/QemuServer/Memory.pm b/src/PVE/QemuServer/Memory.pm
index 2dbf2dc7..36b2865a 100644
--- a/src/PVE/QemuServer/Memory.pm
+++ b/src/PVE/QemuServer/Memory.pm
@@ -3,11 +3,12 @@ package PVE::QemuServer::Memory;
use strict;
use warnings;
+use PVE::CpuSet;
use PVE::JSONSchema qw(parse_property_string);
use PVE::Tools qw(run_command lock_file lock_file_full file_read_firstline dir_glob_foreach);
use PVE::Exception qw(raise raise_param_exc);
-use PVE::QemuServer::Helpers qw(parse_number_sets);
+use PVE::QemuServer::Helpers;
use PVE::QemuServer::Monitor qw(mon_cmd);
use PVE::QemuServer::QMPHelpers qw(qemu_devicedel qemu_objectdel);
@@ -15,6 +16,7 @@ use base qw(Exporter);
our @EXPORT_OK = qw(
get_current_memory
+ get_effective_numa_cfg
);
our $MAX_NUMA = 8;
@@ -23,8 +25,9 @@ my $numa_fmt = {
cpus => {
type => "string",
pattern => qr/\d+(?:-\d+)?(?:;\d+(?:-\d+)?)*/,
- description => "CPUs accessing this NUMA node.",
+ description => "vCPUs accessing this NUMA node.",
format_description => "id[-id];...",
+ optional => 1,
},
memory => {
type => "number",
@@ -64,15 +67,6 @@ our $numadesc = {
};
PVE::JSONSchema::register_standard_option("pve-qm-numanode", $numadesc);
-sub parse_numa {
- my ($data) = @_;
-
- my $res = parse_property_string($numa_fmt, $data);
- $res->{cpus} = parse_number_sets($res->{cpus}) if defined($res->{cpus});
- $res->{hostnodes} = parse_number_sets($res->{hostnodes}) if defined($res->{hostnodes});
- return $res;
-}
-
my $STATICMEM = 1024;
our $memory_fmt = {
@@ -98,9 +92,7 @@ sub parse_memory {
return { current => $memory_fmt->{current}->{default} } if !defined($value);
- my $res = PVE::JSONSchema::parse_property_string($memory_fmt, $value);
-
- return $res;
+ return PVE::JSONSchema::parse_property_string($memory_fmt, $value);
}
my sub get_max_mem {
@@ -145,17 +137,196 @@ sub get_current_memory {
return $memory->{current};
}
-sub get_numa_node_list {
+my sub get_static_memory {
+ my ($conf, $sockets, $hotplug, $memory) = @_;
+
+ return $memory if !$hotplug;
+
+ my $static_memory = $STATICMEM;
+ if ($conf->{hugepages} && $conf->{hugepages} == 1024) {
+ $static_memory *= $sockets;
+ }
+
+ return $static_memory;
+}
+
+# Split $total into $count integer parts that sum to exactly $total.
+# The first ($total % $count) parts get one extra unit.
+my sub distribute_evenly {
+ my ($total, $count) = @_;
+
+ my $base = int($total / $count);
+ my $remainder = $total - $base * $count;
+
+ return map { $base + ($_ < $remainder ? 1 : 0) } (0 .. $count - 1);
+}
+
+my sub parse_numa_node {
+ my ($id, $entry) = @_;
+
+ my $numa = parse_property_string($numa_fmt, $entry);
+
+ my $cpus = defined($numa->{cpus}) ? PVE::CpuSet->from_str($numa->{cpus}, ';') : undef;
+
+ my $hostnodes;
+ if (defined($numa->{hostnodes})) {
+ die "numa$id: policy is required when hostnodes is set\n"
+ if !defined($numa->{policy});
+ $hostnodes = PVE::CpuSet->from_str($numa->{hostnodes}, ';');
+ } elsif (defined($numa->{policy})) {
+ die "numa$id: policy requires hostnodes\n";
+ }
+
+ return {
+ id => $id,
+ cpus => $cpus,
+ memory => $numa->{memory},
+ hostnodes => $hostnodes,
+ policy => $numa->{policy},
+ };
+}
+
+my sub parse_numa_cfg {
my ($conf) = @_;
- my @numa_map;
- for (my $i = 0; $i < $MAX_NUMA; $i++) {
- my $entry = $conf->{"numa$i"} or next;
- my $numa = parse_numa($entry) or next;
- push @numa_map, $i;
+
+ my $nodes = [];
+ for my $id (0 .. $MAX_NUMA - 1) {
+ my $entry = $conf->{"numa$id"} or next;
+ my $node = parse_numa_node($id, $entry);
+ # Custom nodes need an explicit host binding for hugepages. Generated nodes
+ # use the implicit 1:1 mapping and never pass through here.
+ die "numa hostnodes need to be defined to use hugepages\n"
+ if $conf->{hugepages} && !$node->{hostnodes};
+ push @$nodes, $node;
}
- return @numa_map if @numa_map;
+
+ return $nodes;
+}
+
+my sub gen_basic_numa_cfg {
+ my ($sockets, $cores, $mem) = @_;
+
+ # Do not use distribute_evenly here, to match legacy behaviour
+ my $mem_per_node = $mem / $sockets;
+ my $nodes = [];
+ for my $id (0 .. $sockets - 1) {
+ my $start = $cores * $id;
+ push @$nodes,
+ {
+ id => $id,
+ cpus => PVE::CpuSet->from_range($start, $start + $cores - 1),
+ memory => $mem_per_node,
+ hostnodes => undef,
+ policy => undef,
+ generated => 1,
+ };
+ }
+
+ return $nodes;
+}
+
+my sub complete_numa_memory {
+ my ($nodes, $mem) = @_;
+
+ my $omitted = [grep { !defined($_->{memory}) } @$nodes];
+ return if !@$omitted;
+
+ my $explicit_sum = 0;
+ for my $node (@$nodes) {
+ $explicit_sum += $node->{memory} if defined($node->{memory});
+ }
+
+ my $remaining = $mem - $explicit_sum;
+ die "cannot auto-complete NUMA memory: remaining budget ($remaining) is not positive\n"
+ if $remaining <= 0;
+
+ my @shares = distribute_evenly($remaining, scalar(@$omitted));
+ for my $i (0 .. $#$omitted) {
+ $omitted->[$i]->{memory} = $shares[$i];
+ }
+}
+
+my sub complete_numa_cpus {
+ my ($nodes, $sockets, $cores) = @_;
+
+ my $omitted = [grep { !defined($_->{cpus}) } @$nodes];
+ return if !@$omitted;
+ die "cannot auto-complete NUMA cpus: mix of explicit and omitted cpus\n"
+ if @$omitted != @$nodes;
+ die "cannot auto-complete NUMA cpus: node count must equal sockets ($sockets)\n"
+ if @$nodes != $sockets;
+
+ for my $i (0 .. $#$nodes) {
+ my $start = $cores * $i;
+ $nodes->[$i]->{cpus} = PVE::CpuSet->from_range($start, $start + $cores - 1);
+ }
+}
+
+my sub validate_numa_cfg {
+ my ($nodes, $sockets, $cores, $mem, $hugepages) = @_;
+
+ my $expected_id = 0;
+ my $max_vcpus = $sockets * $cores;
+ my $mem_sum = 0;
+ my %seen;
+ for my $node (@$nodes) {
+ die "NUMA node IDs must be sequential starting from 0 (missing $expected_id)\n"
+ if $node->{id} != $expected_id;
+ $expected_id++;
+
+ die "numa$node->{id}: memory is not set\n" if !defined($node->{memory});
+ die "numa$node->{id}: memory must be positive\n" if $node->{memory} <= 0;
+ $mem_sum += $node->{memory};
+ die "numa$node->{id}: cpus is not set\n" if !defined($node->{cpus});
+
+ for my $cpu ($node->{cpus}->members_unsorted()) {
+ die "vCPU $cpu is assigned to multiple NUMA nodes\n" if $seen{$cpu}++;
+ die "vCPU $cpu exceeds max vCPUs ($max_vcpus)\n" if $cpu >= $max_vcpus;
+ }
+
+ if (defined($node->{hostnodes})) {
+ die
+ "numa$node->{id}: exactly one host node per NUMA node is required when hugepages are enabled\n"
+ if $hugepages && $node->{hostnodes}->size() != 1;
+ for my $host_node ($node->{hostnodes}->members_unsorted()) {
+ die "host NUMA node $host_node doesn't exist\n"
+ if !host_numanode_exists($host_node);
+ }
+ } elsif ($hugepages) {
+ # Generated nodes use the implicit 1:1 mapping.
+ die "host NUMA node $node->{id} doesn't exist\n"
+ if !host_numanode_exists($node->{id});
+ }
+ }
+
+ # legacy behaviour allows for fractional memory
+ die "total NUMA memory ($mem_sum) must equal memory budget ($mem)\n"
+ if abs($mem_sum - $mem) > 1e-6;
+}
+
+sub get_effective_numa_cfg {
+ my ($conf, $mem_budget, $auto_complete) = @_;
+ # auto_complete=1 should not hurt any existing guests.
+ # therefore we could set auto_complete=1 and set auto_complete=0
+ # as opt-out in the numa config.
+ return [] if !$conf->{numa};
+
+ my $nodes = parse_numa_cfg($conf);
my $sockets = $conf->{sockets} || 1;
- return (0 .. ($sockets - 1));
+ my $cores = $conf->{cores} || 1;
+
+ if ($auto_complete) {
+ if (!@$nodes) {
+ $nodes = gen_basic_numa_cfg($sockets, $cores, $mem_budget);
+ } else {
+ complete_numa_memory($nodes, $mem_budget);
+ complete_numa_cpus($nodes, $sockets, $cores);
+ }
+ }
+
+ validate_numa_cfg($nodes, $sockets, $cores, $mem_budget, $conf->{hugepages});
+
+ return $nodes;
}
sub host_numanode_exists {
@@ -164,22 +335,18 @@ sub host_numanode_exists {
return -d "/sys/devices/system/node/node$id/";
}
-# only valid when numa nodes map to a single host node
-sub get_numa_guest_to_host_map {
- my ($conf) = @_;
- my $map = {};
- for (my $i = 0; $i < $MAX_NUMA; $i++) {
- my $entry = $conf->{"numa$i"} or next;
- my $numa = parse_numa($entry) or next;
- $map->{$i} = print_numa_hostnodes($numa->{hostnodes});
- }
- return $map if %$map;
- my $sockets = $conf->{sockets} || 1;
- return { map { $_ => $_ } (0 .. ($sockets - 1)) };
+# Resolved single host NUMA node for hugepages allocation. Generated nodes without
+# an explicit binding map 1:1 by guest node ID.
+my sub get_hugepages_numa_host_node {
+ my ($node) = @_;
+
+ return $node->{id} if !defined($node->{hostnodes});
+
+ return ($node->{hostnodes}->members())[0];
}
-sub foreach_dimm {
- my ($conf, $vmid, $memory, $static_memory, $func) = @_;
+my sub foreach_dimm {
+ my ($conf, $vmid, $nodes, $memory, $static_memory, $func) = @_;
my $dimm_id = 0;
my $current_size = $static_memory;
@@ -193,15 +360,13 @@ sub foreach_dimm {
return if $current_size == $memory;
- my @numa_map = get_numa_node_list($conf);
-
for (my $j = 0; $j < 8; $j++) {
for (my $i = 0; $i < 32; $i++) {
my $name = "dimm${dimm_id}";
$dimm_id++;
- my $numanode = $numa_map[$i % @numa_map];
+ my $node = $nodes->[$i % @$nodes];
$current_size += $dimm_size;
- &$func($conf, $vmid, $name, $dimm_size, $numanode, $current_size, $memory);
+ $func->($conf, $vmid, $name, $dimm_size, $node, $current_size, $memory);
return $current_size if $current_size >= $memory;
}
$dimm_size *= 2;
@@ -222,34 +387,30 @@ sub qemu_memory_hotplug {
$value = $newmem->{current};
my $sockets = $conf->{sockets} || 1;
- my $static_memory = $STATICMEM;
- $static_memory = $static_memory * $sockets
- if ($conf->{hugepages} && $conf->{hugepages} == 1024);
+ my $static_memory = get_static_memory($conf, $sockets, 1, $memory);
die "memory can't be lower than $static_memory MB" if $value < $static_memory;
my $MAX_MEM = get_max_mem($conf);
die "you cannot add more memory than max mem $MAX_MEM MB!\n" if $value > $MAX_MEM;
if ($value > $memory) {
-
- my $numa_hostmap;
+ my $nodes = get_effective_numa_cfg($conf, $static_memory, 1);
foreach_dimm(
$conf,
$vmid,
+ $nodes,
$value,
$static_memory,
sub {
- my ($conf, $vmid, $name, $dimm_size, $numanode, $current_size, $memory) = @_;
+ my ($conf, $vmid, $name, $dimm_size, $node, $current_size, $memory) = @_;
return if $current_size <= get_current_memory($conf->{memory});
if ($conf->{hugepages}) {
- $numa_hostmap = get_numa_guest_to_host_map($conf) if !$numa_hostmap;
-
my $hugepages_size = hugepages_size($conf, $dimm_size);
my $path = hugepages_mount_path($hugepages_size);
- my $host_numanode = $numa_hostmap->{$numanode};
+ my $host_numanode = get_hugepages_numa_host_node($node);
my $hugepages_topology->{$hugepages_size}->{$host_numanode} =
hugepages_nr($dimm_size, $hugepages_size);
@@ -299,7 +460,7 @@ sub qemu_memory_hotplug {
driver => "pc-dimm",
id => "$name",
memdev => "mem-$name",
- node => $numanode,
+ node => $node->{id},
);
};
if (my $err = $@) {
@@ -368,113 +529,44 @@ sub config {
my ($conf, $vmid, $sockets, $cores, $hotplug, $virtiofs_enabled, $cmd, $machine_flags) = @_;
my $memory = get_current_memory($conf->{memory});
- my $static_memory = 0;
+ my $static_memory = get_static_memory($conf, $sockets, $hotplug, $memory);
if ($hotplug) {
die "NUMA needs to be enabled for memory hotplug\n" if !$conf->{numa};
my $MAX_MEM = get_max_mem($conf);
die "Total memory is bigger than ${MAX_MEM}MB\n" if $memory > $MAX_MEM;
- for (my $i = 0; $i < $MAX_NUMA; $i++) {
- die "cannot enable memory hotplugging with custom NUMA topology\n"
- if $conf->{"numa$i"};
- }
-
- my $sockets = $conf->{sockets} || 1;
-
- $static_memory = $STATICMEM;
- $static_memory = $static_memory * $sockets
- if ($conf->{hugepages} && $conf->{hugepages} == 1024);
+ die "cannot enable memory hotplugging with custom NUMA topology\n" if $conf->{numa0};
- die "minimum memory must be ${static_memory}MB\n" if ($memory < $static_memory);
+ die "minimum memory must be ${static_memory}MB\n" if $memory < $static_memory;
push @$cmd, '-m', "size=${static_memory},slots=255,maxmem=${MAX_MEM}M";
-
} else {
-
- $static_memory = $memory;
push @$cmd, '-m', $static_memory;
}
die "numa needs to be enabled to use hugepages" if $conf->{hugepages} && !$conf->{numa};
-
die "Memory hotplug does not work in combination with virtio-fs.\n"
if $hotplug && $virtiofs_enabled;
- if ($conf->{numa}) {
-
- my $numa_totalmemory = undef;
- for (my $i = 0; $i < $MAX_NUMA; $i++) {
- next if !$conf->{"numa$i"};
- my $numa = parse_numa($conf->{"numa$i"});
- next if !$numa;
- # memory
- die "missing NUMA node$i memory value\n" if !$numa->{memory};
- my $numa_memory = $numa->{memory};
- $numa_totalmemory += $numa_memory;
-
- my $memdev = $virtiofs_enabled ? "virtiofs-mem$i" : "ram-node$i";
- my $mem_object = print_mem_object($conf, $memdev, $numa_memory);
-
- # cpus
- my $cpulists = $numa->{cpus};
- die "missing NUMA node$i cpus\n" if !defined($cpulists);
- my $cpus = join(
- ',cpus=',
- map {
- my ($start, $end) = @$_;
- defined($end) ? "$start-$end" : $start
- } @$cpulists,
- );
-
- # hostnodes
- my $hostnodelists = $numa->{hostnodes};
- if (defined($hostnodelists)) {
-
- my $hostnodes = print_numa_hostnodes($hostnodelists);
-
- # policy - note that the value 'default' is not exposed, because it can't be used in
- # combination with host-nodes:
- # > kvm: host-nodes must be empty for policy default, or you should explicitly
- # > specify a policy other than default
- my $policy = $numa->{policy};
- die "you need to define a policy for hostnode $hostnodes\n" if !$policy;
-
- # QEMU splits object options at commas, so each range needs its own host-nodes key
- my $host_node_ranges = join(
- ',host-nodes=',
- map {
- my ($start, $end) = @$_;
- defined($end) ? "$start-$end" : $start
- } @$hostnodelists,
- );
- $mem_object .= ",host-nodes=$host_node_ranges,policy=$policy";
- } else {
- die "numa hostnodes need to be defined to use hugepages" if $conf->{hugepages};
- }
-
- push @$cmd, '-object', $mem_object;
- push @$cmd, '-numa', "node,nodeid=$i,cpus=$cpus,memdev=$memdev";
- }
+ my $nodes = get_effective_numa_cfg($conf, $static_memory, 1);
- die "total memory for NUMA nodes must be equal to vm static memory\n"
- if $numa_totalmemory && $numa_totalmemory != $static_memory;
+ if (@$nodes) {
+ for my $node (@$nodes) {
+ my $node_id = $node->{id};
+ my $memdev = $virtiofs_enabled ? "virtiofs-mem$node_id" : "ram-node$node_id";
+ my $mem_object = print_mem_object($conf, $memdev, $node->{memory});
- #if no custom tology, we split memory and cores across numa nodes
- if (!$numa_totalmemory) {
- my $numa_memory = ($static_memory / $sockets);
-
- for (my $i = 0; $i < $sockets; $i++) {
- die "host NUMA node$i doesn't exist\n"
- if !host_numanode_exists($i) && $conf->{hugepages};
+ if (defined($node->{hostnodes})) {
+ for my $range (split(',', $node->{hostnodes}->short_string())) {
+ $mem_object .= ",host-nodes=$range";
+ }
+ $mem_object .= ",policy=$node->{policy}";
+ }
- my $cpus = ($cores * $i);
- $cpus .= "-" . ($cpus + $cores - 1) if $cores > 1;
+ my $cpus = join(',cpus=', split(',', $node->{cpus}->short_string()));
- my $memdev = $virtiofs_enabled ? "virtiofs-mem$i" : "ram-node$i";
- my $mem_object = print_mem_object($conf, $memdev, $numa_memory);
- push @$cmd, '-object', $mem_object;
- push @$cmd, '-numa', "node,nodeid=$i,cpus=$cpus,memdev=$memdev";
- }
+ push @$cmd, '-object', $mem_object;
+ push @$cmd, '-numa', "node,nodeid=$node_id,cpus=$cpus,memdev=$memdev";
}
} elsif ($virtiofs_enabled) {
# kvm: '-machine memory-backend' and '-numa memdev' properties are mutually exclusive
@@ -486,15 +578,16 @@ sub config {
foreach_dimm(
$conf,
$vmid,
+ $nodes,
$memory,
$static_memory,
sub {
- my ($conf, $vmid, $name, $dimm_size, $numanode, $current_size, $memory) = @_;
+ my ($conf, $vmid, $name, $dimm_size, $node, $current_size, $memory) = @_;
my $mem_object = print_mem_object($conf, "mem-$name", $dimm_size);
push @$cmd, "-object", $mem_object;
- push @$cmd, "-device", "pc-dimm,id=$name,memdev=mem-$name,node=$numanode";
+ push @$cmd, "-device", "pc-dimm,id=$name,memdev=mem-$name,node=$node->{id}";
die "memory size ($memory) must be aligned to $dimm_size for hotplugging\n"
if $current_size > $memory;
@@ -520,23 +613,6 @@ sub print_mem_object {
}
-sub print_numa_hostnodes {
- my ($hostnodelists) = @_;
-
- my $hostnodes;
- foreach my $hostnoderange (@$hostnodelists) {
- my ($start, $end) = @$hostnoderange;
- $hostnodes .= ',' if defined($hostnodes);
- $hostnodes .= $start;
- $hostnodes .= "-$end" if defined($end);
- $end //= $start;
- for (my $i = $start; $i <= $end; ++$i) {
- die "host NUMA node$i doesn't exist\n" if !host_numanode_exists($i);
- }
- }
- return $hostnodes;
-}
-
sub hugepages_mount {
my $mountdata = PVE::ProcFSTools::parse_proc_mounts();
@@ -619,70 +695,37 @@ sub hugepages_size {
sub hugepages_topology {
my ($conf, $hotplug) = @_;
- my $hugepages_topology = {};
-
return if !$conf->{numa};
my $memory = get_current_memory($conf->{memory});
- my $static_memory = 0;
my $sockets = $conf->{sockets} || 1;
- my $numa_custom_topology = undef;
-
- if ($hotplug) {
- $static_memory = $STATICMEM;
- $static_memory = $static_memory * $sockets
- if ($conf->{hugepages} && $conf->{hugepages} == 1024);
- } else {
- $static_memory = $memory;
- }
-
- #custom numa topology
- for (my $i = 0; $i < $MAX_NUMA; $i++) {
- next if !$conf->{"numa$i"};
- my $numa = parse_numa($conf->{"numa$i"});
- next if !$numa;
+ my $static_memory = get_static_memory($conf, $sockets, $hotplug, $memory);
- $numa_custom_topology = 1;
- my $numa_memory = $numa->{memory};
- my $hostnodelists = $numa->{hostnodes};
- my $hostnodes = print_numa_hostnodes($hostnodelists);
+ my $nodes = get_effective_numa_cfg($conf, $static_memory, 1);
- die "more than 1 hostnode value in numa node is not supported when hugepages are enabled"
- if $hostnodes !~ m/^\d+$/;
+ my $hugepages_topology = {};
+ for my $node (@$nodes) {
+ my $numa_memory = $node->{memory};
my $hugepages_size = hugepages_size($conf, $numa_memory);
- $hugepages_topology->{$hugepages_size}->{$hostnodes} +=
+ my $host_node = get_hugepages_numa_host_node($node);
+ $hugepages_topology->{$hugepages_size}->{$host_node} +=
hugepages_nr($numa_memory, $hugepages_size);
-
- }
-
- #if no custom numa tology, we split memory and cores across numa nodes
- if (!$numa_custom_topology) {
-
- my $numa_memory = ($static_memory / $sockets);
-
- for (my $i = 0; $i < $sockets; $i++) {
-
- my $hugepages_size = hugepages_size($conf, $numa_memory);
- $hugepages_topology->{$hugepages_size}->{$i} +=
- hugepages_nr($numa_memory, $hugepages_size);
- }
}
if ($hotplug) {
- my $numa_hostmap = get_numa_guest_to_host_map($conf);
-
foreach_dimm(
$conf,
undef,
+ $nodes,
$memory,
$static_memory,
sub {
- my ($conf, undef, $name, $dimm_size, $numanode, $current_size, $memory) = @_;
+ my ($conf, undef, $name, $dimm_size, $node, $current_size, $memory) = @_;
- $numanode = $numa_hostmap->{$numanode};
+ my $host_node = get_hugepages_numa_host_node($node);
my $hugepages_size = hugepages_size($conf, $dimm_size);
- $hugepages_topology->{$hugepages_size}->{$numanode} +=
+ $hugepages_topology->{$hugepages_size}->{$host_node} +=
hugepages_nr($dimm_size, $hugepages_size);
},
);
@@ -824,4 +867,3 @@ sub hugepages_update_locked {
return $res;
}
1;
-
diff --git a/src/test/run_memory_tests.pl b/src/test/run_memory_tests.pl
index 97b89961..90f6a1bb 100755
--- a/src/test/run_memory_tests.pl
+++ b/src/test/run_memory_tests.pl
@@ -31,19 +31,23 @@ for my $test (@$tests) {
subtest "host nodes $hostnodes" => sub {
my $numa_config = "cpus=0,memory=1024,hostnodes=$hostnodes,policy=bind";
- my $numa = PVE::QemuServer::Memory::parse_numa($numa_config);
- is(
- PVE::QemuServer::Memory::print_numa_hostnodes($numa->{hostnodes}),
- $expected,
- 'preserve node and range separators',
- );
-
- my $conf = {
+ my $base_conf = {
numa => 1,
memory => 1024,
- hugepages => 2,
+ sockets => 1,
+ cores => 1,
numa0 => $numa_config,
};
+
+ # Without hugepages, multi-node bindings are valid; inspect the parsed set.
+ my $nodes = PVE::QemuServer::Memory::get_effective_numa_cfg($base_conf, 1, 1, 1024, 1);
+ is(
+ $nodes->[0]->{hostnodes}->short_string(),
+ $expected,
+ 'hostnodes normalize to a canonical CpuSet rendering',
+ );
+
+ my $conf = { %$base_conf, hugepages => 2 };
my $topology = eval { PVE::QemuServer::Memory::hugepages_topology($conf, 0); };
if ($single_node) {
is($@, '', 'accept a single host node for hugepages');
@@ -51,11 +55,18 @@ for my $test (@$tests) {
} else {
like(
$@,
- qr/^more than 1 hostnode value in numa node is not supported when hugepages are enabled/,
+ qr/exactly one host node per NUMA node is required when hugepages are enabled/,
'reject host node lists and ranges for hugepages',
);
}
};
}
+subtest 'generated topology with hugepages' => sub {
+ my $conf = { numa => 1, memory => 1024, sockets => 1, cores => 1, hugepages => 2 };
+ my $topology = eval { PVE::QemuServer::Memory::hugepages_topology($conf, 0); };
+ is($@, '', 'generated nodes use the implicit 1:1 host mapping');
+ is_deeply($topology, { 2 => { 0 => 512 } }, 'allocate on host node 0');
+};
+
done_testing();
--
2.47.3
^ permalink raw reply related [flat|nested] 7+ messages in thread* [PATCH qemu-server v6 5/5] cpu: add affinity module
2026-12-03 10:52 [PATCH common/qemu-server v6 0/5] vCPU binding for qemu guests Elias Huhsovitz
` (3 preceding siblings ...)
2026-12-03 10:52 ` [PATCH qemu-server v6 4/5] memory: unify NUMA config parsing and resolution Elias Huhsovitz
@ 2026-12-03 10:53 ` Elias Huhsovitz
4 siblings, 0 replies; 7+ messages in thread
From: Elias Huhsovitz @ 2026-12-03 10:53 UTC (permalink / raw)
To: pve-devel; +Cc: Elias Huhsovitz
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 <d.csapak@proxmox.com>
Signed-off-by: Elias Huhsovitz <e.huhsovitz@proxmox.com>
---
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
^ permalink raw reply related [flat|nested] 7+ messages in thread