hw/pci: reserve IO and mem for pci-2-pci bridges with no devices attached

If a pci-2-pci bridge supports hot-plug functionality but there are no devices
connected to it, reserve IO/mem in order to be able to attach devices
later. Do not waste space, use minimum allowed.

Reviewed-by: Michael S. Tsirkin <mst@redhat.com>
Signed-off-by: Marcel Apfelbaum <marcel.a@redhat.com>
diff --git a/src/fw/pciinit.c b/src/fw/pciinit.c
index 64f1d41..9b5d7ad 100644
--- a/src/fw/pciinit.c
+++ b/src/fw/pciinit.c
@@ -677,12 +677,15 @@
             continue;
         struct pci_bus *parent = &busses[pci_bdf_to_bus(s->bus_dev->bdf)];
         int type;
+        u8 shpc_cap = pci_find_capability(s->bus_dev, PCI_CAP_ID_SHPC);
         for (type = 0; type < PCI_REGION_TYPE_COUNT; type++) {
             u64 align = (type == PCI_REGION_TYPE_IO) ?
                 PCI_BRIDGE_IO_MIN : PCI_BRIDGE_MEM_MIN;
             if (pci_region_align(&s->r[type]) > align)
                  align = pci_region_align(&s->r[type]);
             u64 sum = pci_region_sum(&s->r[type]);
+            if (!sum && shpc_cap)
+                sum = align; /* reserve min size for hot-plug */
             u64 size = ALIGN(sum, align);
             int is64 = pci_bios_bridge_region_is64(&s->r[type],
                                             s->bus_dev, type);
diff --git a/src/hw/pci.c b/src/hw/pci.c
index a31b4a2..781c1cc 100644
--- a/src/hw/pci.c
+++ b/src/hw/pci.c
@@ -221,6 +221,25 @@
     return NULL;
 }
 
+u8 pci_find_capability(struct pci_device *pci, u8 cap_id)
+{
+    int i;
+    u8 cap;
+    u16 status = pci_config_readw(pci->bdf, PCI_STATUS);
+
+    if (!(status & PCI_STATUS_CAP_LIST))
+        return 0;
+
+    cap = pci_config_readb(pci->bdf, PCI_CAPABILITY_LIST);
+    for (i = 0; cap && i <= 0xff; i++) {
+        if (pci_config_readb(pci->bdf, cap + PCI_CAP_LIST_ID) == cap_id)
+            return cap;
+        cap = pci_config_readb(pci->bdf, cap + PCI_CAP_LIST_NEXT);
+    }
+
+    return 0;
+}
+
 void
 pci_reboot(void)
 {
diff --git a/src/hw/pci.h b/src/hw/pci.h
index 167a027..e828225 100644
--- a/src/hw/pci.h
+++ b/src/hw/pci.h
@@ -116,6 +116,7 @@
                     , struct pci_device *pci, void *arg);
 struct pci_device *pci_find_init_device(const struct pci_device_id *ids
                                         , void *arg);
+u8 pci_find_capability(struct pci_device *pci, u8 cap_id);
 void pci_reboot(void);
 
 #endif