[pve-devel] [PATCH qemu-server 2/3] pci: add helpers to (un)reserve pciids for a vm

Dominik Csapak d.csapak at proxmox.com
Tue Oct 5 15:11:59 CEST 2021


saves a list of pciid <-> vmid mappings in /var/run
that we can check when we start a vm

Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
---
 PVE/QemuServer/PCI.pm | 89 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 89 insertions(+)

diff --git a/PVE/QemuServer/PCI.pm b/PVE/QemuServer/PCI.pm
index 5608207..0626b76 100644
--- a/PVE/QemuServer/PCI.pm
+++ b/PVE/QemuServer/PCI.pm
@@ -5,6 +5,7 @@ use strict;
 
 use PVE::JSONSchema;
 use PVE::SysFSTools;
+use PVE::Tools;
 
 use base 'Exporter';
 
@@ -461,4 +462,92 @@ sub print_hostpci_devices {
     return ($kvm_off, $gpu_passthrough, $legacy_igd);
 }
 
+my $PCIID_RESERVATION_FILE = "/var/run/pve-reserved-pciids";
+my $PCIID_RESERVATION_LCK = "/var/lock/pve-reserved-pciids.lck";
+
+my $parse_pci_reservation = sub {
+    my $pciids = {};
+
+    if (my $fh = IO::File->new ($PCIID_RESERVATION_FILE, "r")) {
+	while (my $line = <$fh>) {
+	    if ($line =~ m/^($PCIRE)\s(\d+)\s(\d+)$/) {
+		$pciids->{$1} = {
+		    timestamp => $2,
+		    vmid => $3,
+		};
+	    }
+	}
+    }
+
+    return $pciids;
+};
+
+my $write_pci_reservation = sub {
+    my ($pciids) = @_;
+
+    my $data = "";
+    foreach my $p (keys %$pciids) {
+	$data .= "$p $pciids->{$p}->{timestamp} $pciids->{$p}->{vmid}\n";
+    }
+
+    PVE::Tools::file_set_contents($PCIID_RESERVATION_FILE, $data);
+};
+
+sub remove_pci_reservation {
+    my ($id) = @_;
+
+    my $code = sub {
+	my $pciids = $parse_pci_reservation->();
+
+	delete $pciids->{$id};
+
+	$write_pci_reservation->($pciids);
+    };
+
+    PVE::Tools::lock_file($PCIID_RESERVATION_LCK, 10, $code);
+    die $@ if $@;
+
+    return;
+}
+
+sub reserve_pci_usage {
+    my ($id, $vmid) = @_;
+
+    my $code = sub {
+
+	# have a 60 second grace period, since we reserve before
+	# we actually start the vm
+	my $graceperiod = 60;
+	my $ctime = time();
+
+	my $pciids = $parse_pci_reservation->();
+
+	if (my $pciid = $pciids->{$id}) {
+	    if ($pciid->{vmid} == $vmid) {
+		return; # already reserved
+	    }
+
+	    if (($pciid->{timestamp} + $graceperiod > $ctime) ||
+		PVE::QemuServer::Helpers::vm_running_locally($vmid))
+	    {
+		die "PCI device '$id' already in use\n";
+	    }
+	}
+
+	$pciids->{$id} = {
+	    timestamp => $ctime,
+	    vmid => $vmid,
+	};
+
+	$write_pci_reservation->($pciids);
+
+	return;
+    };
+
+    PVE::Tools::lock_file($PCIID_RESERVATION_LCK, 10, $code);
+    die $@ if $@;
+
+    return;
+}
+
 1;
-- 
2.30.2






More information about the pve-devel mailing list