Bug 1: The the next element in the pcidevs is skipped after we
virPCIDeviceListDel the previous element.

Bug 2: virHostdevNetConfigRestore is called for store the hostdevs
which may be used by other domain.

Signed-off-by: Huanle Han <hanxueluo@gmail.com>
---
 src/util/virhostdev.c | 25 +++++++++++++++++++++----
 1 file changed, 21 insertions(+), 4 deletions(-)

diff --git a/src/util/virhostdev.c b/src/util/virhostdev.c
index 9678e2b..ecbe5d8 100644
--- a/src/util/virhostdev.c
+++ b/src/util/virhostdev.c
@@ -785,7 +785,7 @@ virHostdevReAttachPCIDevices(virHostdevManagerPtr hostdev_mgr,
      * them and reset all the devices before re-attach.
      * Attach mac and port profile parameters to devices
      */
-    for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
+    for (i = 0; i < virPCIDeviceListCount(pcidevs);) {
         virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
         virPCIDevicePtr activeDev = NULL;
 
@@ -806,6 +806,7 @@ virHostdevReAttachPCIDevices(virHostdevManagerPtr hostdev_mgr,
         }
 
         virPCIDeviceListDel(hostdev_mgr->activePCIHostdevs, dev);
+        i++;
     }
 
     /* At this point, any device that had been used by the guest is in
@@ -816,9 +817,25 @@ virHostdevReAttachPCIDevices(virHostdevManagerPtr hostdev_mgr,
      * For SRIOV net host devices, unset mac and port profile before
      * reset and reattach device
      */
-    for (i = 0; i < nhostdevs; i++)
-        virHostdevNetConfigRestore(hostdevs[i], hostdev_mgr->stateDir,
-                                   oldStateDir);
+    for (i = 0; i < nhostdevs; i++) {
+        virPCIDevicePtr dev;
+        virDomainHostdevDefPtr hostdev = hostdevs[i];
+        virDomainHostdevSubsysPCIPtr pcisrc = &hostdev->source.subsys.u.pci;
+
+        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
+            hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI ||
+            hostdev->parent.type != VIR_DOMAIN_DEVICE_NET ||
+            !hostdev->parent.data.net)
+                continue;
+
+        dev = virPCIDeviceNew(pcisrc->addr.domain, pcisrc->addr.bus,
+                              pcisrc->addr.slot, pcisrc->addr.function);
+        if (virPCIDeviceListFind(pcidevs, dev)) {
+            virHostdevNetConfigRestore(hostdev, hostdev_mgr->stateDir,
+                                       oldStateDir);
+        }
+        virPCIDeviceFree(dev);
+   }
 
     for (i = 0; i < virPCIDeviceListCount(pcidevs); i++) {
         virPCIDevicePtr dev = virPCIDeviceListGet(pcidevs, i);
--
2.1.0