[PATCH] vhost: return early when memslots overflow in vhost_get_free_memslots()

Bin Guo posted 1 patch 1 week ago
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/qemu tags/patchew/20260403205011.15962-1-guobin@linux.alibaba.com
Maintainers: "Michael S. Tsirkin" <mst@redhat.com>, Stefano Garzarella <sgarzare@redhat.com>
hw/virtio/vhost.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
[PATCH] vhost: return early when memslots overflow in vhost_get_free_memslots()
Posted by Bin Guo 1 week ago
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.

Signed-off-by: Bin Guo <guobin@linux.alibaba.com>
---
 hw/virtio/vhost.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/hw/virtio/vhost.c b/hw/virtio/vhost.c
index b9dc4ed13b..9d1b56fa34 100644
--- a/hw/virtio/vhost.c
+++ b/hw/virtio/vhost.c
@@ -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;
 }
-- 
2.50.1 (Apple Git-155)