From nobody Sun May  4 20:37:08 2025
Delivered-To: importer@patchew.org
Authentication-Results: mx.zohomail.com;
	dkim=fail;
	spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as
 permitted sender)
  smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org;
	dmarc=fail(p=none dis=none)  header.from=redhat.com
ARC-Seal: i=1; a=rsa-sha256; t=1603366362; cv=none;
	d=zohomail.com; s=zohoarc;
	b=G18NlJFT6iyfPQO+kXVDnFWFoB9cy8GBcwy+NDKRytTvAo9pVEeAOf21cP7uOvY4zslesWE7AKpACzvPtNEqVjLfSXke3x0K5BqViX4kAWhB6Cpb4yy0PAGVKMdFY1Qfz3EUpz2/Lnk6a4D/0D9XJCVGJvzOD/RxzVivbLMVuBU=
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=zohomail.com;
 s=zohoarc;
	t=1603366362;
 h=Content-Type:Content-Transfer-Encoding:Cc:Date:From:In-Reply-To:List-Subscribe:List-Post:List-Id:List-Archive:List-Help:List-Unsubscribe:MIME-Version:Message-ID:References:Sender:Subject:To;
	bh=dFpMASVSNF4gnj4wpvZPZnPDmOAhSVnZ+tVY7OKNgmc=;
	b=M4MVaqZL0kbjw6wiDWyezVTppT/3yYYq4H96AnKOjJ3itvPFnuiI4vtV/a79g9rxVxdVPgX50oL0TCHFDouwPYB8G+qPhh9XC4NVDcVCI8h1GlBdlDwZYaVNiM+xCKq2VhMiAOkCQXTZ/f7FeycwwdsqOaTXehIu/spLaDbVdA0=
ARC-Authentication-Results: i=1; mx.zohomail.com;
	dkim=fail;
	spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as
 permitted sender)
  smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org;
	dmarc=fail header.from=<stefanha@redhat.com> (p=none dis=none)
 header.from=<stefanha@redhat.com>
Return-Path: <qemu-devel-bounces+importer=patchew.org@nongnu.org>
Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by
 mx.zohomail.com
	with SMTPS id 1603366362113569.916062076731;
 Thu, 22 Oct 2020 04:32:42 -0700 (PDT)
Received: from localhost ([::1]:60866 helo=lists1p.gnu.org)
	by lists.gnu.org with esmtp (Exim 4.90_1)
	(envelope-from <qemu-devel-bounces+importer=patchew.org@nongnu.org>)
	id 1kVYpk-0000ZS-KZ
	for importer@patchew.org; Thu, 22 Oct 2020 07:32:40 -0400
Received: from eggs.gnu.org ([2001:470:142:3::10]:36164)
 by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256)
 (Exim 4.90_1) (envelope-from <stefanha@redhat.com>)
 id 1kVYlN-00042Z-EJ
 for qemu-devel@nongnu.org; Thu, 22 Oct 2020 07:28:09 -0400
Received: from us-smtp-delivery-124.mimecast.com ([216.205.24.124]:32220)
 by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256)
 (Exim 4.90_1) (envelope-from <stefanha@redhat.com>)
 id 1kVYlH-00050z-0l
 for qemu-devel@nongnu.org; Thu, 22 Oct 2020 07:28:07 -0400
Received: from mimecast-mx01.redhat.com (mimecast-mx01.redhat.com
 [209.132.183.4]) (Using TLS) by relay.mimecast.com with ESMTP id
 us-mta-213-eaBDNC3nNXiokZq11uKR1w-1; Thu, 22 Oct 2020 07:27:59 -0400
Received: from smtp.corp.redhat.com (int-mx06.intmail.prod.int.phx2.redhat.com
 [10.5.11.16])
 (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits))
 (No client certificate requested)
 by mimecast-mx01.redhat.com (Postfix) with ESMTPS id CC3921009E23;
 Thu, 22 Oct 2020 11:27:57 +0000 (UTC)
Received: from localhost (ovpn-114-229.ams2.redhat.com [10.36.114.229])
 by smtp.corp.redhat.com (Postfix) with ESMTP id E62D75C1C7;
 Thu, 22 Oct 2020 11:27:49 +0000 (UTC)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com;
 s=mimecast20190719; t=1603366081;
 h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
 to:to:cc:cc:mime-version:mime-version:content-type:content-type:
 content-transfer-encoding:content-transfer-encoding:
 in-reply-to:in-reply-to:references:references;
 bh=dFpMASVSNF4gnj4wpvZPZnPDmOAhSVnZ+tVY7OKNgmc=;
 b=BK0VjHBbxQk59JxtlsxJKICSBabmahl2BORNwYOJj9wDpHVgUoZmhnuedW1Mpm1rzlv9oj
 oYlUjonoqjm03xO1YIEz5I75JspVp0iMCEkRRCpgNiondu3lmi8z7j7GOM2L1GIRD3A1mP
 tjMFiMbCEmgn+4abSEJSNIQ8uMIrn4A=
X-MC-Unique: eaBDNC3nNXiokZq11uKR1w-1
From: Stefan Hajnoczi <stefanha@redhat.com>
To: qemu-devel@nongnu.org,
	Peter Maydell <peter.maydell@linaro.org>
Subject: [PULL v2 04/28] util/vhost-user-server: generic vhost user server
Date: Thu, 22 Oct 2020 12:27:02 +0100
Message-Id: <20201022112726.736757-5-stefanha@redhat.com>
In-Reply-To: <20201022112726.736757-1-stefanha@redhat.com>
References: <20201022112726.736757-1-stefanha@redhat.com>
MIME-Version: 1.0
X-Scanned-By: MIMEDefang 2.79 on 10.5.11.16
Authentication-Results: relay.mimecast.com;
 auth=pass smtp.auth=CUSA124A263 smtp.mailfrom=stefanha@redhat.com
X-Mimecast-Spam-Score: 0
X-Mimecast-Originator: redhat.com
Content-Transfer-Encoding: quoted-printable
Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17
 as permitted sender) client-ip=209.51.188.17;
 envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org;
 helo=lists.gnu.org;
Received-SPF: pass client-ip=216.205.24.124;
 envelope-from=stefanha@redhat.com;
 helo=us-smtp-delivery-124.mimecast.com
X-detected-operating-system: by eggs.gnu.org: First seen = 2020/10/22 00:54:46
X-ACL-Warn: Detected OS   = Linux 2.2.x-3.x [generic] [fuzzy]
X-Spam_score_int: -20
X-Spam_score: -2.1
X-Spam_bar: --
X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.001,
 DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1,
 RCVD_IN_DNSWL_NONE=-0.0001, RCVD_IN_MSPIKE_H4=0.001, RCVD_IN_MSPIKE_WL=0.001,
 SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no
X-Spam_action: no action
X-BeenThere: qemu-devel@nongnu.org
X-Mailman-Version: 2.1.23
Precedence: list
List-Id: <qemu-devel.nongnu.org>
List-Unsubscribe: <https://lists.nongnu.org/mailman/options/qemu-devel>,
 <mailto:qemu-devel-request@nongnu.org?subject=unsubscribe>
List-Archive: <https://lists.nongnu.org/archive/html/qemu-devel>
List-Post: <mailto:qemu-devel@nongnu.org>
List-Help: <mailto:qemu-devel-request@nongnu.org?subject=help>
List-Subscribe: <https://lists.nongnu.org/mailman/listinfo/qemu-devel>,
 <mailto:qemu-devel-request@nongnu.org?subject=subscribe>
Cc: Kevin Wolf <kwolf@redhat.com>, Fam Zheng <fam@euphon.net>,
 =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= <berrange@redhat.com>,
 Eduardo Habkost <ehabkost@redhat.com>, qemu-block@nongnu.org,
 "Dr. David Alan Gilbert" <dgilbert@redhat.com>,
 Coiby Xu <coiby.xu@gmail.com>,
 Markus Armbruster <armbru@redhat.com>, Stefan Hajnoczi <stefanha@redhat.com>,
 =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= <marcandre.lureau@redhat.com>,
 Paolo Bonzini <pbonzini@redhat.com>, Max Reitz <mreitz@redhat.com>
Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org
Sender: "Qemu-devel" <qemu-devel-bounces+importer=patchew.org@nongnu.org>
X-ZohoMail-DKIM: fail (Header signature does not verify)
Content-Type: text/plain; charset="utf-8"

From: Coiby Xu <coiby.xu@gmail.com>

Sharing QEMU devices via vhost-user protocol.

Only one vhost-user client can connect to the server one time.

Suggested-by: Kevin Wolf <kwolf@redhat.com>
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
Signed-off-by: Coiby Xu <coiby.xu@gmail.com>
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
Reviewed-by: Marc-Andr=C3=A9 Lureau <marcandre.lureau@redhat.com>
Message-id: 20200918080912.321299-4-coiby.xu@gmail.com
[Fixed size_t %lu -> %zu format string compiler error.
--Stefan]
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
---
 util/vhost-user-server.h |  65 ++++++
 util/vhost-user-server.c | 428 +++++++++++++++++++++++++++++++++++++++
 util/meson.build         |   1 +
 3 files changed, 494 insertions(+)
 create mode 100644 util/vhost-user-server.h
 create mode 100644 util/vhost-user-server.c

diff --git a/util/vhost-user-server.h b/util/vhost-user-server.h
new file mode 100644
index 0000000000..5232f96718
--- /dev/null
+++ b/util/vhost-user-server.h
@@ -0,0 +1,65 @@
+/*
+ * Sharing QEMU devices via vhost-user protocol
+ *
+ * Copyright (c) Coiby Xu <coiby.xu@gmail.com>.
+ * Copyright (c) 2020 Red Hat, Inc.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+
+#ifndef VHOST_USER_SERVER_H
+#define VHOST_USER_SERVER_H
+
+#include "contrib/libvhost-user/libvhost-user.h"
+#include "io/channel-socket.h"
+#include "io/channel-file.h"
+#include "io/net-listener.h"
+#include "qemu/error-report.h"
+#include "qapi/error.h"
+#include "standard-headers/linux/virtio_blk.h"
+
+typedef struct VuFdWatch {
+    VuDev *vu_dev;
+    int fd; /*kick fd*/
+    void *pvt;
+    vu_watch_cb cb;
+    bool processing;
+    QTAILQ_ENTRY(VuFdWatch) next;
+} VuFdWatch;
+
+typedef struct VuServer VuServer;
+typedef void DevicePanicNotifierFn(VuServer *server);
+
+struct VuServer {
+    QIONetListener *listener;
+    AioContext *ctx;
+    DevicePanicNotifierFn *device_panic_notifier;
+    int max_queues;
+    const VuDevIface *vu_iface;
+    VuDev vu_dev;
+    QIOChannel *ioc; /* The I/O channel with the client */
+    QIOChannelSocket *sioc; /* The underlying data channel with the client=
 */
+    /* IOChannel for fd provided via VHOST_USER_SET_SLAVE_REQ_FD */
+    QIOChannel *ioc_slave;
+    QIOChannelSocket *sioc_slave;
+    Coroutine *co_trip; /* coroutine for processing VhostUserMsg */
+    QTAILQ_HEAD(, VuFdWatch) vu_fd_watches;
+    /* restart coroutine co_trip if AIOContext is changed */
+    bool aio_context_changed;
+    bool processing_msg;
+};
+
+bool vhost_user_server_start(VuServer *server,
+                             SocketAddress *unix_socket,
+                             AioContext *ctx,
+                             uint16_t max_queues,
+                             DevicePanicNotifierFn *device_panic_notifier,
+                             const VuDevIface *vu_iface,
+                             Error **errp);
+
+void vhost_user_server_stop(VuServer *server);
+
+void vhost_user_server_set_aio_context(VuServer *server, AioContext *ctx);
+
+#endif /* VHOST_USER_SERVER_H */
diff --git a/util/vhost-user-server.c b/util/vhost-user-server.c
new file mode 100644
index 0000000000..b189944856
--- /dev/null
+++ b/util/vhost-user-server.c
@@ -0,0 +1,428 @@
+/*
+ * Sharing QEMU devices via vhost-user protocol
+ *
+ * Copyright (c) Coiby Xu <coiby.xu@gmail.com>.
+ * Copyright (c) 2020 Red Hat, Inc.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or
+ * later.  See the COPYING file in the top-level directory.
+ */
+#include "qemu/osdep.h"
+#include "qemu/main-loop.h"
+#include "vhost-user-server.h"
+
+static void vmsg_close_fds(VhostUserMsg *vmsg)
+{
+    int i;
+    for (i =3D 0; i < vmsg->fd_num; i++) {
+        close(vmsg->fds[i]);
+    }
+}
+
+static void vmsg_unblock_fds(VhostUserMsg *vmsg)
+{
+    int i;
+    for (i =3D 0; i < vmsg->fd_num; i++) {
+        qemu_set_nonblock(vmsg->fds[i]);
+    }
+}
+
+static void vu_accept(QIONetListener *listener, QIOChannelSocket *sioc,
+                      gpointer opaque);
+
+static void close_client(VuServer *server)
+{
+    /*
+     * Before closing the client
+     *
+     * 1. Let vu_client_trip stop processing new vhost-user msg
+     *
+     * 2. remove kick_handler
+     *
+     * 3. wait for the kick handler to be finished
+     *
+     * 4. wait for the current vhost-user msg to be finished processing
+     */
+
+    QIOChannelSocket *sioc =3D server->sioc;
+    /* When this is set vu_client_trip will stop new processing vhost-user=
 message */
+    server->sioc =3D NULL;
+
+    VuFdWatch *vu_fd_watch, *next;
+    QTAILQ_FOREACH_SAFE(vu_fd_watch, &server->vu_fd_watches, next, next) {
+        aio_set_fd_handler(server->ioc->ctx, vu_fd_watch->fd, true, NULL,
+                           NULL, NULL, NULL);
+    }
+
+    while (!QTAILQ_EMPTY(&server->vu_fd_watches)) {
+        QTAILQ_FOREACH_SAFE(vu_fd_watch, &server->vu_fd_watches, next, nex=
t) {
+            if (!vu_fd_watch->processing) {
+                QTAILQ_REMOVE(&server->vu_fd_watches, vu_fd_watch, next);
+                g_free(vu_fd_watch);
+            }
+        }
+    }
+
+    while (server->processing_msg) {
+        if (server->ioc->read_coroutine) {
+            server->ioc->read_coroutine =3D NULL;
+            qio_channel_set_aio_fd_handler(server->ioc, server->ioc->ctx, =
NULL,
+                                           NULL, server->ioc);
+            server->processing_msg =3D false;
+        }
+    }
+
+    vu_deinit(&server->vu_dev);
+    object_unref(OBJECT(sioc));
+    object_unref(OBJECT(server->ioc));
+}
+
+static void panic_cb(VuDev *vu_dev, const char *buf)
+{
+    VuServer *server =3D container_of(vu_dev, VuServer, vu_dev);
+
+    /* avoid while loop in close_client */
+    server->processing_msg =3D false;
+
+    if (buf) {
+        error_report("vu_panic: %s", buf);
+    }
+
+    if (server->sioc) {
+        close_client(server);
+    }
+
+    if (server->device_panic_notifier) {
+        server->device_panic_notifier(server);
+    }
+
+    /*
+     * Set the callback function for network listener so another
+     * vhost-user client can connect to this server
+     */
+    qio_net_listener_set_client_func(server->listener,
+                                     vu_accept,
+                                     server,
+                                     NULL);
+}
+
+static bool coroutine_fn
+vu_message_read(VuDev *vu_dev, int conn_fd, VhostUserMsg *vmsg)
+{
+    struct iovec iov =3D {
+        .iov_base =3D (char *)vmsg,
+        .iov_len =3D VHOST_USER_HDR_SIZE,
+    };
+    int rc, read_bytes =3D 0;
+    Error *local_err =3D NULL;
+    /*
+     * Store fds/nfds returned from qio_channel_readv_full into
+     * temporary variables.
+     *
+     * VhostUserMsg is a packed structure, gcc will complain about passing
+     * pointer to a packed structure member if we pass &VhostUserMsg.fd_num
+     * and &VhostUserMsg.fds directly when calling qio_channel_readv_full,
+     * thus two temporary variables nfds and fds are used here.
+     */
+    size_t nfds =3D 0, nfds_t =3D 0;
+    const size_t max_fds =3D G_N_ELEMENTS(vmsg->fds);
+    int *fds_t =3D NULL;
+    VuServer *server =3D container_of(vu_dev, VuServer, vu_dev);
+    QIOChannel *ioc =3D server->ioc;
+
+    if (!ioc) {
+        error_report_err(local_err);
+        goto fail;
+    }
+
+    assert(qemu_in_coroutine());
+    do {
+        /*
+         * qio_channel_readv_full may have short reads, keeping calling it
+         * until getting VHOST_USER_HDR_SIZE or 0 bytes in total
+         */
+        rc =3D qio_channel_readv_full(ioc, &iov, 1, &fds_t, &nfds_t, &loca=
l_err);
+        if (rc < 0) {
+            if (rc =3D=3D QIO_CHANNEL_ERR_BLOCK) {
+                qio_channel_yield(ioc, G_IO_IN);
+                continue;
+            } else {
+                error_report_err(local_err);
+                return false;
+            }
+        }
+        read_bytes +=3D rc;
+        if (nfds_t > 0) {
+            if (nfds + nfds_t > max_fds) {
+                error_report("A maximum of %zu fds are allowed, "
+                             "however got %zu fds now",
+                             max_fds, nfds + nfds_t);
+                goto fail;
+            }
+            memcpy(vmsg->fds + nfds, fds_t,
+                   nfds_t *sizeof(vmsg->fds[0]));
+            nfds +=3D nfds_t;
+            g_free(fds_t);
+        }
+        if (read_bytes =3D=3D VHOST_USER_HDR_SIZE || rc =3D=3D 0) {
+            break;
+        }
+        iov.iov_base =3D (char *)vmsg + read_bytes;
+        iov.iov_len =3D VHOST_USER_HDR_SIZE - read_bytes;
+    } while (true);
+
+    vmsg->fd_num =3D nfds;
+    /* qio_channel_readv_full will make socket fds blocking, unblock them =
*/
+    vmsg_unblock_fds(vmsg);
+    if (vmsg->size > sizeof(vmsg->payload)) {
+        error_report("Error: too big message request: %d, "
+                     "size: vmsg->size: %u, "
+                     "while sizeof(vmsg->payload) =3D %zu",
+                     vmsg->request, vmsg->size, sizeof(vmsg->payload));
+        goto fail;
+    }
+
+    struct iovec iov_payload =3D {
+        .iov_base =3D (char *)&vmsg->payload,
+        .iov_len =3D vmsg->size,
+    };
+    if (vmsg->size) {
+        rc =3D qio_channel_readv_all_eof(ioc, &iov_payload, 1, &local_err);
+        if (rc =3D=3D -1) {
+            error_report_err(local_err);
+            goto fail;
+        }
+    }
+
+    return true;
+
+fail:
+    vmsg_close_fds(vmsg);
+
+    return false;
+}
+
+
+static void vu_client_start(VuServer *server);
+static coroutine_fn void vu_client_trip(void *opaque)
+{
+    VuServer *server =3D opaque;
+
+    while (!server->aio_context_changed && server->sioc) {
+        server->processing_msg =3D true;
+        vu_dispatch(&server->vu_dev);
+        server->processing_msg =3D false;
+    }
+
+    if (server->aio_context_changed && server->sioc) {
+        server->aio_context_changed =3D false;
+        vu_client_start(server);
+    }
+}
+
+static void vu_client_start(VuServer *server)
+{
+    server->co_trip =3D qemu_coroutine_create(vu_client_trip, server);
+    aio_co_enter(server->ctx, server->co_trip);
+}
+
+/*
+ * a wrapper for vu_kick_cb
+ *
+ * since aio_dispatch can only pass one user data pointer to the
+ * callback function, pack VuDev and pvt into a struct. Then unpack it
+ * and pass them to vu_kick_cb
+ */
+static void kick_handler(void *opaque)
+{
+    VuFdWatch *vu_fd_watch =3D opaque;
+    vu_fd_watch->processing =3D true;
+    vu_fd_watch->cb(vu_fd_watch->vu_dev, 0, vu_fd_watch->pvt);
+    vu_fd_watch->processing =3D false;
+}
+
+
+static VuFdWatch *find_vu_fd_watch(VuServer *server, int fd)
+{
+
+    VuFdWatch *vu_fd_watch, *next;
+    QTAILQ_FOREACH_SAFE(vu_fd_watch, &server->vu_fd_watches, next, next) {
+        if (vu_fd_watch->fd =3D=3D fd) {
+            return vu_fd_watch;
+        }
+    }
+    return NULL;
+}
+
+static void
+set_watch(VuDev *vu_dev, int fd, int vu_evt,
+          vu_watch_cb cb, void *pvt)
+{
+
+    VuServer *server =3D container_of(vu_dev, VuServer, vu_dev);
+    g_assert(vu_dev);
+    g_assert(fd >=3D 0);
+    g_assert(cb);
+
+    VuFdWatch *vu_fd_watch =3D find_vu_fd_watch(server, fd);
+
+    if (!vu_fd_watch) {
+        VuFdWatch *vu_fd_watch =3D g_new0(VuFdWatch, 1);
+
+        QTAILQ_INSERT_TAIL(&server->vu_fd_watches, vu_fd_watch, next);
+
+        vu_fd_watch->fd =3D fd;
+        vu_fd_watch->cb =3D cb;
+        qemu_set_nonblock(fd);
+        aio_set_fd_handler(server->ioc->ctx, fd, true, kick_handler,
+                           NULL, NULL, vu_fd_watch);
+        vu_fd_watch->vu_dev =3D vu_dev;
+        vu_fd_watch->pvt =3D pvt;
+    }
+}
+
+
+static void remove_watch(VuDev *vu_dev, int fd)
+{
+    VuServer *server;
+    g_assert(vu_dev);
+    g_assert(fd >=3D 0);
+
+    server =3D container_of(vu_dev, VuServer, vu_dev);
+
+    VuFdWatch *vu_fd_watch =3D find_vu_fd_watch(server, fd);
+
+    if (!vu_fd_watch) {
+        return;
+    }
+    aio_set_fd_handler(server->ioc->ctx, fd, true, NULL, NULL, NULL, NULL);
+
+    QTAILQ_REMOVE(&server->vu_fd_watches, vu_fd_watch, next);
+    g_free(vu_fd_watch);
+}
+
+
+static void vu_accept(QIONetListener *listener, QIOChannelSocket *sioc,
+                      gpointer opaque)
+{
+    VuServer *server =3D opaque;
+
+    if (server->sioc) {
+        warn_report("Only one vhost-user client is allowed to "
+                    "connect the server one time");
+        return;
+    }
+
+    if (!vu_init(&server->vu_dev, server->max_queues, sioc->fd, panic_cb,
+                 vu_message_read, set_watch, remove_watch, server->vu_ifac=
e)) {
+        error_report("Failed to initialize libvhost-user");
+        return;
+    }
+
+    /*
+     * Unset the callback function for network listener to make another
+     * vhost-user client keeping waiting until this client disconnects
+     */
+    qio_net_listener_set_client_func(server->listener,
+                                     NULL,
+                                     NULL,
+                                     NULL);
+    server->sioc =3D sioc;
+    /*
+     * Increase the object reference, so sioc will not freed by
+     * qio_net_listener_channel_func which will call object_unref(OBJECT(s=
ioc))
+     */
+    object_ref(OBJECT(server->sioc));
+    qio_channel_set_name(QIO_CHANNEL(sioc), "vhost-user client");
+    server->ioc =3D QIO_CHANNEL(sioc);
+    object_ref(OBJECT(server->ioc));
+    qio_channel_attach_aio_context(server->ioc, server->ctx);
+    qio_channel_set_blocking(QIO_CHANNEL(server->sioc), false, NULL);
+    vu_client_start(server);
+}
+
+
+void vhost_user_server_stop(VuServer *server)
+{
+    if (server->sioc) {
+        close_client(server);
+    }
+
+    if (server->listener) {
+        qio_net_listener_disconnect(server->listener);
+        object_unref(OBJECT(server->listener));
+    }
+
+}
+
+void vhost_user_server_set_aio_context(VuServer *server, AioContext *ctx)
+{
+    VuFdWatch *vu_fd_watch, *next;
+    void *opaque =3D NULL;
+    IOHandler *io_read =3D NULL;
+    bool attach;
+
+    server->ctx =3D ctx ? ctx : qemu_get_aio_context();
+
+    if (!server->sioc) {
+        /* not yet serving any client*/
+        return;
+    }
+
+    if (ctx) {
+        qio_channel_attach_aio_context(server->ioc, ctx);
+        server->aio_context_changed =3D true;
+        io_read =3D kick_handler;
+        attach =3D true;
+    } else {
+        qio_channel_detach_aio_context(server->ioc);
+        /* server->ioc->ctx keeps the old AioConext */
+        ctx =3D server->ioc->ctx;
+        attach =3D false;
+    }
+
+    QTAILQ_FOREACH_SAFE(vu_fd_watch, &server->vu_fd_watches, next, next) {
+        if (vu_fd_watch->cb) {
+            opaque =3D attach ? vu_fd_watch : NULL;
+            aio_set_fd_handler(ctx, vu_fd_watch->fd, true,
+                               io_read, NULL, NULL,
+                               opaque);
+        }
+    }
+}
+
+
+bool vhost_user_server_start(VuServer *server,
+                             SocketAddress *socket_addr,
+                             AioContext *ctx,
+                             uint16_t max_queues,
+                             DevicePanicNotifierFn *device_panic_notifier,
+                             const VuDevIface *vu_iface,
+                             Error **errp)
+{
+    QIONetListener *listener =3D qio_net_listener_new();
+    if (qio_net_listener_open_sync(listener, socket_addr, 1,
+                                   errp) < 0) {
+        object_unref(OBJECT(listener));
+        return false;
+    }
+
+    /* zero out unspecified fileds */
+    *server =3D (VuServer) {
+        .listener              =3D listener,
+        .vu_iface              =3D vu_iface,
+        .max_queues            =3D max_queues,
+        .ctx                   =3D ctx,
+        .device_panic_notifier =3D device_panic_notifier,
+    };
+
+    qio_net_listener_set_name(server->listener, "vhost-user-backend-listen=
er");
+
+    qio_net_listener_set_client_func(server->listener,
+                                     vu_accept,
+                                     server,
+                                     NULL);
+
+    QTAILQ_INIT(&server->vu_fd_watches);
+    return true;
+}
diff --git a/util/meson.build b/util/meson.build
index e6b207a99e..3921981ccf 100644
--- a/util/meson.build
+++ b/util/meson.build
@@ -66,6 +66,7 @@ if have_block
   util_ss.add(files('main-loop.c'))
   util_ss.add(files('nvdimm-utils.c'))
   util_ss.add(files('qemu-coroutine.c', 'qemu-coroutine-lock.c', 'qemu-cor=
outine-io.c'))
+  util_ss.add(when: 'CONFIG_LINUX', if_true: files('vhost-user-server.c'))
   util_ss.add(files('qemu-coroutine-sleep.c'))
   util_ss.add(files('qemu-co-shared-resource.c'))
   util_ss.add(files('thread-pool.c', 'qemu-timer.c'))
--=20
2.26.2