diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index ddbd5dfc8f44..d18e0e41535c 100644
--- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@ -341,6 +341,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
private static final VideoDef.VideoModel X86_DEFAULT_VIDEO_MODEL = VideoDef.VideoModel.VGA;
private static final int X86_DEFAULT_VIDEO_RAM_KIB = 32768;
private static final String Q35 = "q35";
+ /**
+ * Number of pcie-root-port controllers declared for every x86 q35 guest. The q35 pcie-root bus has 32 slots, of which the
+ * host bridge, the VGA device and the ICH9 functions always take some; 28 is also the maximum OpenStack Nova allows.
+ */
+ protected static final int Q35_PCIE_ROOT_PORTS = 28;
private static final String PTY = "pty";
private static final String VNC = "vnc";
@@ -3293,9 +3298,33 @@ protected DevicesDef createDevicesDef(VirtualMachineTO vmTO, GuestDef guest, int
boolean isIothreadsEnabled = details != null && details.containsKey(VmDetailConstants.IOTHREADS);
addSCSIControllers(devices, vcpus, vmTO.getDisks().length, isIothreadsEnabled);
}
+
+ int pcieRootPortCount = getPcieRootPortCount(vmTO, guest);
+ if (pcieRootPortCount > 0) {
+ LOGGER.debug("Declaring {} PCIe root ports for Instance {}.", pcieRootPortCount, vmTO.getName());
+ }
+ devices.setPcieRootPorts(pcieRootPortCount);
return devices;
}
+ /**
+ * Returns how many pcie-root-port controllers to declare for the Instance, or 0 to leave the PCIe topology to libvirt.
+ *
+ * Only x86 KVM guests with a q35 machine type get ports, always {@link #Q35_PCIE_ROOT_PORTS}. Without them libvirt creates one
+ * root port per PCIe device present at start plus a single spare one, so at most one volume or NIC can be hot-plugged
+ * (#11212). aarch64 and s390x keep their own layout.
+ */
+ protected int getPcieRootPortCount(VirtualMachineTO vmTO, GuestDef guest) {
+ if (guest == null || guest.getGuestType() != GuestDef.GuestType.KVM || !isGuestX86(vmTO) || !isQ35MachineType(guest.getMachineType())) {
+ return 0;
+ }
+ return Q35_PCIE_ROOT_PORTS;
+ }
+
+ protected static boolean isQ35MachineType(String machineType) {
+ return machineType != null && machineType.toLowerCase().contains(Q35);
+ }
+
protected void attachGpuDevices(final VirtualMachineTO vmTO, final DevicesDef devicesDef) {
// GPU device is not set for the VM
List gpuDevices = vmTO.getGpuDevice().getGpuDevices();
diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java
index 954a86664611..5bc2f2880357 100644
--- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java
+++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java
@@ -343,6 +343,10 @@ public void setMachineType(String machine) {
_machine = machine;
}
+ public String getMachineType() {
+ return _machine;
+ }
+
public void setLoader(String loader) {
_loader = loader;
}
@@ -726,6 +730,7 @@ public String toString() {
public static class DevicesDef {
private String _emulator;
private GuestDef.GuestType _guestType;
+ private int pcieRootPorts;
private final Map> devices = new HashMap>();
public boolean addDevice(Object device) {
@@ -749,6 +754,18 @@ public void setGuestType(GuestDef.GuestType guestType) {
_guestType = guestType;
}
+ /**
+ * Number of pcie-root-port controllers to declare for an x86 PCI Express (q35) guest; 0 declares none and
+ * leaves the PCIe topology entirely to libvirt. Not used for aarch64 and s390x, which keep their own layout.
+ */
+ public void setPcieRootPorts(int pcieRootPorts) {
+ this.pcieRootPorts = Math.max(pcieRootPorts, 0);
+ }
+
+ public int getPcieRootPorts() {
+ return pcieRootPorts;
+ }
+
@Override
public String toString() {
StringBuilder devicesBuilder = new StringBuilder();
@@ -780,6 +797,15 @@ public String toString() {
devicesBuilder.append("\n");
}
devicesBuilder.append("\n");
+ } else if (pcieRootPorts > 0) {
+ // Declared after every device and without index or address. libvirt gives index 0 to the
+ // pcie-root (it must come first) and the next free indexes to the ports, then places all
+ // PCI controllers before any device, so devices keep the root ports they use without these
+ // extra ports and the extra ports stay empty for hot-plug.
+ devicesBuilder.append("\n");
+ for (int i = 0; i < pcieRootPorts; i++) {
+ devicesBuilder.append("\n");
+ }
}
devicesBuilder.append("\n");
diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
index d4b504664972..523cbd25b94a 100644
--- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
+++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapper.java
@@ -140,7 +140,7 @@ public Answer execute(final PlugNicCommand command, final LibvirtComputingResour
* controllers, balloon), in which case the next free slot above them is used.
*
* @return the slot to assign, or {@code null} to let libvirt auto-assign (domain XML unavailable
- * or unparseable, or no free slot left).
+ * or unparseable, PCI Express root complex (q35), or no free slot left).
*/
protected Integer findNextAvailablePciSlot(final Domain vm, final List pluggedNics) {
try {
@@ -150,6 +150,12 @@ protected Integer findNextAvailablePciSlot(final Domain vm, final List usedSlots = getUsedPciSlots(domXml);
if (usedSlots == null) {
return null;
@@ -165,6 +171,28 @@ protected Integer findNextAvailablePciSlot(final Domain vm, final List} element in the domain XML,
* whichever device or bus they belong to. Returns {@code null} if the XML cannot be parsed.
diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
index db45dca1942b..28a82bfdf398 100644
--- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
+++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResourceTest.java
@@ -177,6 +177,7 @@
import com.cloud.agent.api.storage.ResizeVolumeCommand;
import com.cloud.agent.api.to.DataStoreTO;
import com.cloud.agent.api.to.DiskTO;
+import com.cloud.agent.api.to.GPUDeviceTO;
import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.StorageFilerTO;
import com.cloud.agent.api.to.VirtualMachineTO;
@@ -515,6 +516,167 @@ public void testCreateDevicesWithSCSIDisk() {
assertNodeExists(domainDoc, "/devices/controller/driver[@queues='" + (to.getCpus() + 1) + "']");
}
+ private GuestDef createKvmGuest(String machineType) {
+ GuestDef guest = new GuestDef();
+ guest.setGuestType(GuestType.KVM);
+ guest.setMachineType(machineType);
+ return guest;
+ }
+
+ private static int countNodes(Document doc, String xPathExpr) {
+ try {
+ return ((Number) XPathFactory.newInstance().newXPath().evaluate("count(" + xPathExpr + ")", doc, XPathConstants.NUMBER)).intValue();
+ } catch (XPathExpressionException e) {
+ Assert.fail(e.getMessage());
+ return -1;
+ }
+ }
+
+ @Test
+ public void testCreateDevicesDefQ35AddsPcieRootPortsAfterAllDevices() {
+ VirtualMachineTO to = createDefaultVM(false);
+
+ DevicesDef devicesDef = libvirtComputingResourceSpy.createDevicesDef(to, createKvmGuest("q35"), to.getCpus(), true);
+ verifyDevices(devicesDef, to);
+ Assert.assertEquals(LibvirtComputingResource.Q35_PCIE_ROOT_PORTS, devicesDef.getPcieRootPorts());
+
+ Document domainDoc = parse(devicesDef.toString());
+ Assert.assertEquals(1, countNodes(domainDoc, "/devices/controller[@type='pci'][@model='pcie-root']"));
+ Assert.assertEquals(LibvirtComputingResource.Q35_PCIE_ROOT_PORTS, countNodes(domainDoc, "/devices/controller[@type='pci'][@model='pcie-root-port']"));
+ Assert.assertEquals(0, countNodes(domainDoc, "/devices/controller[@model='pcie-to-pci-bridge']"));
+ // no index and no address, so libvirt numbers and places them, and they come after every device
+ Assert.assertEquals(0, countNodes(domainDoc, "/devices/controller[@type='pci'][@index]"));
+ Assert.assertEquals(0, countNodes(domainDoc, "/devices/controller[@type='pci']/address"));
+ Assert.assertEquals(0, countNodes(domainDoc, "/devices/controller[@model='pcie-root']/following-sibling::*[not(self::controller[@type='pci'][@model='pcie-root-port'])]"));
+ Assert.assertEquals(0, countNodes(domainDoc, "/devices/controller[@model='pcie-root']/preceding-sibling::controller[@type='pci']"));
+ }
+
+ @Test
+ public void testCreateDevicesDefQ35VersionedMachineTypeAddsPcieRootPorts() {
+ VirtualMachineTO to = createDefaultVM(false);
+
+ DevicesDef devicesDef = libvirtComputingResourceSpy.createDevicesDef(to, createKvmGuest("pc-q35-rhel9.0.0"), to.getCpus(), false);
+ Assert.assertEquals(LibvirtComputingResource.Q35_PCIE_ROOT_PORTS, devicesDef.getPcieRootPorts());
+ }
+
+ @Test
+ public void testCreateDevicesDefI440fxHasNoPcieControllers() {
+ VirtualMachineTO to = createDefaultVM(false);
+
+ for (String machineType : new String[] {"pc", "pc-i440fx-rhel7.6.0", null}) {
+ DevicesDef devicesDef = libvirtComputingResourceSpy.createDevicesDef(to, createKvmGuest(machineType), to.getCpus(), false);
+ Assert.assertEquals(0, devicesDef.getPcieRootPorts());
+ Document domainDoc = parse(devicesDef.toString());
+ Assert.assertEquals(0, countNodes(domainDoc, "/devices/controller[@type='pci']"));
+ }
+ }
+
+ @Test
+ public void testCreateDevicesDefQ35KeepsExplicitScsiControllerAddress() {
+ VirtualMachineTO to = createDefaultVM(false);
+ to.setDetails(new HashMap<>());
+ to.setPlatformEmulator("Other PV Virtio-SCSI");
+ to.setDisks(new DiskTO[]{Mockito.mock(DiskTO.class)});
+
+ DevicesDef devicesDef = libvirtComputingResourceSpy.createDevicesDef(to, createKvmGuest("q35"), to.getCpus(), true);
+
+ Document domainDoc = parse(devicesDef.toString());
+ assertXpath(domainDoc, "/devices/controller[@model='virtio-scsi']/address/@bus", "0x00");
+ assertXpath(domainDoc, "/devices/controller[@model='virtio-scsi']/address/@slot", "0x09");
+ Assert.assertEquals(1, countNodes(domainDoc, "/devices/controller[@model='virtio-scsi']/following-sibling::controller[@model='pcie-root']"));
+ Assert.assertEquals(LibvirtComputingResource.Q35_PCIE_ROOT_PORTS, countNodes(domainDoc, "/devices/controller[@type='pci'][@model='pcie-root-port']"));
+ }
+
+ @Test
+ public void testCreateDevicesDefAarch64KeepsItsPcieLayout() {
+ VirtualMachineTO to = createDefaultVM(false);
+ to.setArch("aarch64");
+ libvirtComputingResourceSpy.guestCpuArch = "aarch64";
+ libvirtComputingResourceSpy.hypervisorPath = "/usr/bin/qemu-system-aarch64";
+
+ for (String machineType : new String[] {"virt", "q35"}) {
+ DevicesDef devicesDef = libvirtComputingResourceSpy.createDevicesDef(to, createKvmGuest(machineType), to.getCpus(), true);
+ Assert.assertEquals(0, devicesDef.getPcieRootPorts());
+ Document domainDoc = parse(devicesDef.toString());
+ Assert.assertEquals(1, countNodes(domainDoc, "/devices/controller[@type='pci'][@model='pcie-root']"));
+ Assert.assertEquals(32, countNodes(domainDoc, "/devices/controller[@type='pci'][@model='pcie-root-port']"));
+ Assert.assertEquals(1, countNodes(domainDoc, "/devices/controller[@type='pci'][@model='pcie-to-pci-bridge']"));
+ }
+ }
+
+ @Test
+ public void testGetPcieRootPortCountIsFixedForLargeInstances() {
+ VirtualMachineTO to = createDefaultVM(false);
+ NicTO[] nics = new NicTO[30];
+ for (int i = 0; i < nics.length; i++) {
+ nics[i] = new NicTO();
+ }
+ to.setNics(nics);
+ to.setDisks(new DiskTO[] {new DiskTO(), new DiskTO(), new DiskTO()});
+ to.setGpuDevice(new GPUDeviceTO("group", "passthrough", 2, new HashMap<>(),
+ Arrays.asList(Mockito.mock(VgpuTypesInfo.class), Mockito.mock(VgpuTypesInfo.class))));
+
+ // fixed count, whatever the devices; libvirt adds ports itself for start-time devices beyond these
+ Assert.assertEquals(28, libvirtComputingResourceSpy.getPcieRootPortCount(to, createKvmGuest("q35")));
+ }
+
+ @Test
+ public void testGetPcieRootPortCountOnlyForX86KvmQ35Guests() {
+ VirtualMachineTO to = createDefaultVM(false);
+ Assert.assertEquals(0, libvirtComputingResourceSpy.getPcieRootPortCount(to, null));
+
+ GuestDef lxcGuest = new GuestDef();
+ lxcGuest.setGuestType(GuestType.LXC);
+ lxcGuest.setMachineType("q35");
+ Assert.assertEquals(0, libvirtComputingResourceSpy.getPcieRootPortCount(to, lxcGuest));
+
+ to.setArch("s390x");
+ Assert.assertEquals(0, libvirtComputingResourceSpy.getPcieRootPortCount(to, createKvmGuest("q35")));
+ }
+
+ @Test
+ public void testCreateVMFromSpecUefiInstanceGetsPcieRootPorts() {
+ VirtualMachineTO to = createDefaultVM(false);
+ Map details = new HashMap<>();
+ details.put(GuestDef.BootType.UEFI.toString(), "legacy");
+ to.setDetails(details);
+
+ LibvirtVMDef vm = libvirtComputingResourceSpy.createVMFromSpec(to);
+ vm.setHvsType(hyperVisorType);
+
+ Document domainDoc = parse(vm.toString());
+ assertXpath(domainDoc, "/domain/os/type/@machine", "q35");
+ Assert.assertEquals(1, countNodes(domainDoc, "/domain/devices/controller[@type='pci'][@model='pcie-root']"));
+ Assert.assertEquals(LibvirtComputingResource.Q35_PCIE_ROOT_PORTS, countNodes(domainDoc, "/domain/devices/controller[@type='pci'][@model='pcie-root-port']"));
+ }
+
+ @Test
+ public void testCreateVMFromSpecBiosQ35InstanceGetsPcieRootPorts() {
+ VirtualMachineTO to = createDefaultVM(false);
+ Map details = new HashMap<>();
+ details.put(VmDetailConstants.KVM_GUEST_OS_MACHINE_TYPE, "q35");
+ to.setDetails(details);
+
+ LibvirtVMDef vm = libvirtComputingResourceSpy.createVMFromSpec(to);
+ vm.setHvsType(hyperVisorType);
+
+ Document domainDoc = parse(vm.toString());
+ assertXpath(domainDoc, "/domain/os/type/@machine", "q35");
+ Assert.assertEquals(0, countNodes(domainDoc, "/domain/os/loader"));
+ Assert.assertEquals(LibvirtComputingResource.Q35_PCIE_ROOT_PORTS, countNodes(domainDoc, "/domain/devices/controller[@type='pci'][@model='pcie-root-port']"));
+ }
+
+ @Test
+ public void testCreateVMFromSpecBiosInstanceGetsNoPcieRootPorts() {
+ VirtualMachineTO to = createDefaultVM(false);
+
+ LibvirtVMDef vm = libvirtComputingResourceSpy.createVMFromSpec(to);
+ vm.setHvsType(hyperVisorType);
+
+ Document domainDoc = parse(vm.toString());
+ Assert.assertEquals(0, countNodes(domainDoc, "/domain/devices/controller[@type='pci']"));
+ }
+
@Test
public void testConfigureGuestAndSystemVMToUseKVM() {
VirtualMachineTO to = createDefaultVM(false);
diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java
index f5fec8ad096e..ff0f542a7bfb 100644
--- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java
+++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDefTest.java
@@ -737,6 +737,73 @@ public void testTpmModel() {
"\n", tpmDef.toString());
}
+ private static int countOccurrences(String text, String token) {
+ return StringUtils.countMatches(text, token);
+ }
+
+ @Test
+ public void testDevicesDefWithoutPcieRootPortsHasNoPciControllers() {
+ LibvirtVMDef.DevicesDef devicesDef = new LibvirtVMDef.DevicesDef();
+ devicesDef.setEmulatorPath("/usr/libexec/qemu-kvm");
+ devicesDef.addDevice(new MemBalloonDef());
+
+ String xml = devicesDef.toString();
+ assertEquals(0, devicesDef.getPcieRootPorts());
+ assertFalse(xml.contains("type='pci'"));
+ }
+
+ @Test
+ public void testDevicesDefPcieRootPortsAreAppendedAfterTheDevices() {
+ LibvirtVMDef.DevicesDef devicesDef = new LibvirtVMDef.DevicesDef();
+ devicesDef.setEmulatorPath("/usr/libexec/qemu-kvm");
+ DiskDef disk = new DiskDef();
+ disk.defFileBasedDisk("/var/lib/libvirt/images/disk.qcow2", 0, DiskDef.DiskBus.VIRTIO, DiskDef.DiskFmtType.QCOW2);
+ devicesDef.addDevice(disk);
+ devicesDef.addDevice(new MemBalloonDef());
+ devicesDef.setPcieRootPorts(4);
+
+ String xml = devicesDef.toString();
+ String expectedTail = "\n"
+ + StringUtils.repeat("\n", 4)
+ + "\n";
+ assertTrue(xml.endsWith(expectedTail));
+ assertEquals(1, countOccurrences(xml, "model='pcie-root'"));
+ assertEquals(4, countOccurrences(xml, "model='pcie-root-port'"));
+ assertFalse(xml.contains("pcie-to-pci-bridge"));
+ assertTrue(xml.indexOf("\n", 32)
+ + "\n"
+ + "\n";
+ assertTrue(xml.endsWith(expectedTail));
+ assertEquals(1, countOccurrences(xml, "model='pcie-root'"));
+ assertEquals(32, countOccurrences(xml, "model='pcie-root-port'"));
+ }
+ }
+ }
+
@Test
public void testIsoDiskDefOnIdeBusForTheIdeCdromSlots() {
for (int[] slot : new int[][] {{3, 'c'}, {4, 'd'}}) {
diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapperTest.java
index 979ffda2f279..1bdee6bbe042 100644
--- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapperTest.java
+++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtPlugNicCommandWrapperTest.java
@@ -18,7 +18,9 @@
package com.cloud.hypervisor.kvm.resource.wrapper;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import java.util.Arrays;
@@ -81,6 +83,30 @@ public class LibvirtPlugNicCommandWrapperTest {
+ " \n"
+ "\n";
+ /**
+ * q35 layout as libvirt reports it: NICs sit in slot 0 behind pcie-root-port controllers on bus 0.
+ */
+ private static final String Q35_DOMAIN_XML =
+ "\n"
+ + " i-2-43-VM\n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + " \n"
+ + "\n";
+
@Mock
private Domain domain;
@@ -139,6 +165,20 @@ public void findNextAvailablePciSlotFallsBackWhenLibvirtFails() throws LibvirtEx
assertNull(wrapper.findNextAvailablePciSlot(domain, nicsFromXml()));
}
+ @Test
+ public void hasPcieRootComplexDetectsQ35Domains() {
+ assertTrue(wrapper.hasPcieRootComplex(Q35_DOMAIN_XML));
+ assertFalse(wrapper.hasPcieRootComplex(DOMAIN_XML));
+ assertFalse(wrapper.hasPcieRootComplex(""));
+ }
+
+ @Test
+ public void findNextAvailablePciSlotLetsLibvirtChooseOnQ35() throws LibvirtException {
+ when(domain.getXMLDesc(0)).thenReturn(Q35_DOMAIN_XML);
+ // pinning bus 0 would put the NIC on the root complex, which libvirt refuses for hot-plug
+ assertNull(wrapper.findNextAvailablePciSlot(domain, Collections.singletonList(nicAtSlot(0x00))));
+ }
+
@Test
public void findNextAvailablePciSlotFallsBackWhenBusIsFull() throws LibvirtException {
when(domain.getXMLDesc(0)).thenReturn(DOMAIN_XML);