Skip to contentSkip to conversation

vhost: return early when memslots overflow in vhost_get_free_memslots()

PATCH New Bin Guo 1 participant 1 message Apr 3

lore
Share & tools
lore

Bin Guo

author
#0 lore raw

PATCH 1/1 vhost: return early when memslots overflow in vhost_get_free_memslots()

The vhost_get_free_memslots() function continues iterating through all vhost devices even after detecting a memslot overflow, which is unnecessary since the result is already determined to be 0.

Use early return to immediately exit the loop when overflow is detected, avoiding redundant iterations and unnecessary arithmetic operations. This optimizes the best case from O(n) to O(1) when the first device overflows, and saves n-k iterations on average where k is the position of the overflowing device.

---
 hw/virtio/vhost.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
hw/virtio/vhost.c +5 -4
index b9dc4ed13b..9d1b56fa34 100644
@@ -70,15 +70,16 @@ unsigned int vhost_get_free_memslots(void)
 
     QLIST_FOREACH(hdev, &vhost_devices, entry) {
         unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
-        unsigned int cur_free = r - hdev->mem->nregions;
+        unsigned int cur_free;
 
         if (unlikely(r < hdev->mem->nregions)) {
             warn_report_once("used (%u) vhost backend memory slots exceed"
                              " the device limit (%u).", hdev->mem->nregions, r);
-            free = 0;
-        } else {
-            free = MIN(free, cur_free);
+            return 0;
         }
+
+        cur_free = r - hdev->mem->nregions;
+        free = MIN(free, cur_free);
     }
     return free;
 }
Signature · 1 line
2.50.1 (Apple Git-155)