Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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.
* <br>
* 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
* (<a href="https://github.com/apache/cloudstack/issues/11212">#11212</a>). 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<VgpuTypesInfo> gpuDevices = vmTO.getGpuDevice().getGpuDevices();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,10 @@ public void setMachineType(String machine) {
_machine = machine;
}

public String getMachineType() {
return _machine;
}

public void setLoader(String loader) {
_loader = loader;
}
Expand Down Expand Up @@ -726,6 +730,7 @@ public String toString() {
public static class DevicesDef {
private String _emulator;
private GuestDef.GuestType _guestType;
private int pcieRootPorts;
private final Map<String, List<?>> devices = new HashMap<String, List<?>>();

public boolean addDevice(Object device) {
Expand All @@ -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();
Expand Down Expand Up @@ -780,6 +797,15 @@ public String toString() {
devicesBuilder.append("<controller type='pci' model='pcie-root-port'/>\n");
}
devicesBuilder.append("<controller type='pci' model='pcie-to-pci-bridge'/>\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("<controller type='pci' model='pcie-root'/>\n");
for (int i = 0; i < pcieRootPorts; i++) {
devicesBuilder.append("<controller type='pci' model='pcie-root-port'/>\n");
}
}

devicesBuilder.append("</devices>\n");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<InterfaceDef> pluggedNics) {
try {
Expand All @@ -150,6 +150,12 @@ protected Integer findNextAvailablePciSlot(final Domain vm, final List<Interface
logger.debug("Domain XML unavailable, letting libvirt auto-assign PCI slot");
return null;
}
if (hasPcieRootComplex(domXml)) {
// q35: bus 0 is the PCIe root complex, which takes no hot-plugged device. Libvirt puts the NIC on the lowest
// free hot-pluggable root port, which is above the ports used at start.
logger.debug("Domain uses a PCI Express root complex, letting libvirt choose a free root port for the NIC");
return null;
}
final Set<Integer> usedSlots = getUsedPciSlots(domXml);
if (usedSlots == null) {
return null;
Expand All @@ -165,6 +171,28 @@ protected Integer findNextAvailablePciSlot(final Domain vm, final List<Interface
}
}

/**
* True when the domain XML has a {@code pcie-root} controller (q35). Its bus 0 does not support hot-plug, so pinning a
* hot-plugged NIC to a bus 0 slot would make libvirt refuse the attach. Returns {@code false} if the XML cannot be parsed,
* which keeps the slot selection below unchanged.
*/
protected boolean hasPcieRootComplex(final String domXml) {
try {
final DocumentBuilder builder = ParserUtils.getSaferDocumentBuilderFactory().newDocumentBuilder();
final Document doc = builder.parse(new InputSource(new StringReader(domXml)));
final NodeList controllers = doc.getElementsByTagName("controller");
for (int i = 0; i < controllers.getLength(); i++) {
final Element controller = (Element) controllers.item(i);
if ("pci".equals(controller.getAttribute("type")) && "pcie-root".equals(controller.getAttribute("model"))) {
return true;
}
}
} catch (final ParserConfigurationException | SAXException | IOException e) {
logger.warn("Failed to parse domain XML to find the PCI root controller", e);
}
return false;
}

/**
* Collects the slot numbers of every {@code <address type='pci' .../>} element in the domain XML,
* whichever device or bus they belong to. Returns {@code null} if the XML cannot be parsed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String, String> 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<String, String> 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);
Expand Down
Loading
Loading