Add user flag to allow non-blocking vfu_run_ctx (#896)

Users may want to run the vfu_run_ctx() with non-blocking behavior while still having vfu_attach_ctx be blocking.

Test the `LIBVFIO_USER_FLAG_RUN_CTX_NB` flag by checking if `vfu_create_ctx` is still blocking, by using alarms. And by checking if `vfu_run_ctx` is non-blocking. If `vfu_run_ctx` is blocking, an alarm will be triggered and cause test will fail.

Signed-off-by: Jesse Taube <jtaubepe@redhat.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Reviewed-by: Thanos Makatos <thanos.makatos@nutanix.com>
diff --git a/include/libvfio-user.h b/include/libvfio-user.h
index 59bc788..523d9d9 100644
--- a/include/libvfio-user.h
+++ b/include/libvfio-user.h
@@ -88,6 +88,13 @@
  */
 #define LIBVFIO_USER_FLAG_ATTACH_NB  (1 << 0)
 
+/*
+ * Makes vfu_run_ctx() non-blocking without affecting vfu_attach_ctx().
+ * Use when attach should block until a client connects but the main loop
+ * needs to poll alongside other file descriptors.
+ */
+#define LIBVFIO_USER_FLAG_RUN_CTX_NB (1 << 1)
+
 typedef enum {
     VFU_TRANS_SOCK,
     // For internal testing only
diff --git a/lib/libvfio-user.c b/lib/libvfio-user.c
index 62a5f13..0205f23 100644
--- a/lib/libvfio-user.c
+++ b/lib/libvfio-user.c
@@ -1677,7 +1677,7 @@
         return ERROR_INT(EINVAL);
     }
 
-    blocking = !(vfu_ctx->flags & LIBVFIO_USER_FLAG_ATTACH_NB);
+    blocking = vfu_is_blocking(vfu_ctx);
 
     do {
         vfu_msg_t *msg;
@@ -1919,7 +1919,7 @@
     int err = 0;
     size_t i;
 
-    if ((flags & ~(LIBVFIO_USER_FLAG_ATTACH_NB)) != 0) {
+    if ((flags & ~(LIBVFIO_USER_FLAG_ATTACH_NB | LIBVFIO_USER_FLAG_RUN_CTX_NB)) != 0) {
         return ERROR_PTR(EINVAL);
     }
 
diff --git a/lib/private.h b/lib/private.h
index fbe68ef..ea93bea 100644
--- a/lib/private.h
+++ b/lib/private.h
@@ -217,6 +217,14 @@
 int
 handle_device_get_region_info(vfu_ctx_t *vfu_ctx, vfu_msg_t *msg);
 
+static inline bool vfu_is_blocking(vfu_ctx_t *vfu_ctx)
+{
+    assert(vfu_ctx != NULL);
+
+    return !(vfu_ctx->flags & (LIBVFIO_USER_FLAG_ATTACH_NB |
+                               LIBVFIO_USER_FLAG_RUN_CTX_NB));
+}
+
 MOCK_DECLARE(bool, cmd_allowed_when_stopped_and_copying, uint16_t cmd);
 
 MOCK_DECLARE(bool, should_exec_command, vfu_ctx_t *vfu_ctx, uint16_t cmd);
diff --git a/lib/tran_sock.c b/lib/tran_sock.c
index 5673a73..9036aab 100644
--- a/lib/tran_sock.c
+++ b/lib/tran_sock.c
@@ -499,7 +499,7 @@
      * faster (?). I tried that and get short reads, so we need to store the
      * partially received buffer somewhere and retry.
      */
-    if (vfu_ctx->flags & LIBVFIO_USER_FLAG_ATTACH_NB) {
+    if (!vfu_is_blocking(vfu_ctx)) {
         sock_flags = MSG_DONTWAIT | MSG_WAITALL;
     }
     return get_msg(hdr, sizeof(*hdr), fds, nr_fds, ts->conn_fd, sock_flags);
diff --git a/test/py/libvfio_user.py b/test/py/libvfio_user.py
index 896204f..a9507f2 100644
--- a/test/py/libvfio_user.py
+++ b/test/py/libvfio_user.py
@@ -149,6 +149,7 @@
 VFU_TRANS_MAX = 2
 
 LIBVFIO_USER_FLAG_ATTACH_NB = (1 << 0)
+LIBVFIO_USER_FLAG_RUN_CTX_NB = (1 << 1)
 VFU_DEV_TYPE_PCI = 0
 
 LIBVFIO_USER_MAJOR = 0
diff --git a/test/py/meson.build b/test/py/meson.build
index c841aa0..e9d2c32 100644
--- a/test/py/meson.build
+++ b/test/py/meson.build
@@ -47,6 +47,7 @@
     'test_sgl_get_put.py',
     'test_sgl_read_write.py',
     'test_vfu_create_ctx.py',
+    'test_run_ctx_nb.py',
     'test_vfu_realize_ctx.py',
     'test_pci_status.py',
 ]
diff --git a/test/py/test_run_ctx_nb.py b/test/py/test_run_ctx_nb.py
new file mode 100644
index 0000000..069005d
--- /dev/null
+++ b/test/py/test_run_ctx_nb.py
@@ -0,0 +1,95 @@
+#
+# Copyright (c) 2026 Red Hat LLC. All rights reserved.
+#
+# Authors: Jesse Taube <jtaubepe@redhat.com>
+#
+#  Redistribution and use in source and binary forms, with or without
+#  modification, are permitted provided that the following conditions are met:
+#      * Redistributions of source code must retain the above copyright
+#        notice, this list of conditions and the following disclaimer.
+#      * Redistributions in binary form must reproduce the above copyright
+#        notice, this list of conditions and the following disclaimer in the
+#        documentation and/or other materials provided with the distribution.
+#      * Neither the name of Nutanix nor the names of its contributors may be
+#        used to endorse or promote products derived from this software without
+#        specific prior written permission.
+#
+#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+#  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
+#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+#  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+#  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+#  DAMAGE.
+#
+
+from libvfio_user import *
+import errno
+import signal
+
+
+def test_run_ctx_nb():
+    """
+    LIBVFIO_USER_FLAG_RUN_CTX_NB makes vfu_run_ctx() non-blocking while
+    leaving vfu_attach_ctx() blocking.
+    """
+    ctx = vfu_create_ctx(flags=LIBVFIO_USER_FLAG_RUN_CTX_NB)
+    assert ctx is not None
+    assert vfu_realize_ctx(ctx) == 0
+
+    # SIGALRM is used to detect blocking calls. The handler does nothing; it
+    # only needs to be installed so the signal interrupts a blocked syscall
+    # (making it fail with EINTR) instead of killing the process.
+    #
+    # signal.alarm(1) asks the kernel to deliver SIGALRM to this process one
+    # second from now; it returns immediately, so the call that follows starts
+    # with a one-second deadline. signal.alarm(0) cancels the pending alarm
+    # once that call has returned, so it can't fire later in the test.
+    old_handler = signal.signal(signal.SIGALRM, lambda signum, frame: None)
+
+    # Check that vfu_attach_ctx() still blocks. No client has connected, so a
+    # blocking accept() waits until the alarm interrupts it, and
+    # vfu_attach_ctx() fails with EINTR. If the listening socket were
+    # non-blocking (as with LIBVFIO_USER_FLAG_ATTACH_NB), accept() would fail
+    # at once with EAGAIN and the test would fail.
+    signal.alarm(1)
+    vfu_attach_ctx(ctx, expect=errno.EINTR)
+    signal.alarm(0)
+
+    # The failed attach left the ctx unconnected, so attach properly.
+    # connect_client() sends the version message before calling
+    # vfu_attach_ctx(), so the blocking attach completes.
+    client = connect_client(ctx)
+
+    # Check that vfu_run_ctx() does not block. No message is pending, so it
+    # must return 0 (no requests processed) immediately. If it blocked waiting
+    # for the client, the alarm would interrupt it, vfu_run_ctx() would fail
+    # with EINTR, and the test would fail instead of hanging.
+    signal.alarm(1)
+    vfu_run_ctx(ctx, expect=0)
+    signal.alarm(0)
+
+    # Check that a pending message is still processed. msg() sends the request,
+    # calls vfu_run_ctx() once, and returns the reply; the alarm makes sure
+    # vfu_run_ctx() returns after handling it rather than waiting for more.
+    payload = vfio_user_device_info(argsz=16, flags=0,
+                                    num_regions=0, num_irqs=0)
+
+    signal.alarm(1)
+    result = msg(ctx, client.sock, VFIO_USER_DEVICE_GET_INFO, payload)
+    signal.alarm(0)
+
+    (argsz, flags, num_regions, num_irqs) = struct.unpack("IIII", result)
+    assert argsz == 16
+    assert flags == VFIO_DEVICE_FLAGS_PCI | VFIO_DEVICE_FLAGS_RESET
+    assert num_regions == VFU_PCI_DEV_NUM_REGIONS
+    assert num_irqs == VFU_DEV_NUM_IRQS
+
+    signal.signal(signal.SIGALRM, old_handler)
+
+    client.disconnect(ctx)
+    vfu_destroy_ctx(ctx)