[PATCH] PCI: don't free in-use device instances

Jan Beulich posted 1 patch 1 day, 22 hours ago
[PATCH] PCI: don't free in-use device instances
Posted by Jan Beulich 1 day, 22 hours ago
When a device is already known, alloc_pdev() will not allocate anything.
Consequently the device should then also not be freed upon encountering
an error (specifically: pci_add_device() dealing with an SR-IOV VF without
known PF).

Fixes: 8fe330a4daf6 ("xen/pci: remove logic catering to adding VF without PF")
Reported-by: Roger Pau Monné <roger.pau@amd.com>
Signed-off-by: Jan Beulich <jbeulich@suse.com>
---
Yes, find_pdev() could also be passed sbdf_t, but using bus+devfn better
fits alloc_pdev()'s signature and is also easier in pci_add_device().

--- a/xen/drivers/passthrough/pci.c
+++ b/xen/drivers/passthrough/pci.c
@@ -315,16 +315,27 @@ static void apply_quirks(struct pci_dev
             pdev->ignore_bars = true;
 }
 
-static struct pci_dev *alloc_pdev(struct pci_seg *pseg, u8 bus, u8 devfn)
+static struct pci_dev *find_pdev(const struct pci_seg *pseg, uint8_t bus,
+                                 uint8_t devfn)
 {
     struct pci_dev *pdev;
-    unsigned int pos;
-    int rc;
 
     list_for_each_entry ( pdev, &pseg->alldevs_list, alldevs_list )
         if ( pdev->bus == bus && pdev->devfn == devfn )
             return pdev;
 
+    return NULL;
+}
+
+static struct pci_dev *alloc_pdev(struct pci_seg *pseg, u8 bus, u8 devfn)
+{
+    struct pci_dev *pdev = find_pdev(pseg, bus, devfn);
+    unsigned int pos;
+    int rc;
+
+    if ( pdev )
+        return pdev;
+
     pdev = xzalloc(struct pci_dev);
     if ( !pdev )
         return NULL;
@@ -669,6 +680,7 @@ int pci_add_device(u16 seg, u8 bus, u8 d
     struct pci_dev *pdev;
     unsigned int slot = PCI_SLOT(devfn), func = PCI_FUNC(devfn);
     const char *type;
+    bool fresh = false;
     int ret;
 
     if ( !info )
@@ -690,9 +702,14 @@ int pci_add_device(u16 seg, u8 bus, u8 d
     pseg = alloc_pseg(seg);
     if ( !pseg )
         goto out;
-    pdev = alloc_pdev(pseg, bus, devfn);
+    pdev = find_pdev(pseg, bus, devfn);
     if ( !pdev )
-        goto out;
+    {
+        pdev = alloc_pdev(pseg, bus, devfn);
+        if ( !pdev )
+            goto out;
+        fresh = true;
+    }
 
     pdev->node = node;
 
@@ -711,7 +728,8 @@ int pci_add_device(u16 seg, u8 bus, u8 d
                        "Attempted to add SR-IOV VF %pp without PF %pp\n",
                        &pdev->sbdf,
                        &PCI_SBDF(seg, info->physfn.bus, info->physfn.devfn));
-                free_pdev(pseg, pdev);
+                if ( fresh )
+                    free_pdev(pseg, pdev);
                 ret = -ENODEV;
                 goto out;
             }