xref: /qemu/util/vhost-user-server.c (revision 8f5e9a8ee189b44ffa90cc6db61e25499b9d786a) !
1 /*
2  * Sharing QEMU devices via vhost-user protocol
3  *
4  * Copyright (c) Coiby Xu <coiby.xu@gmail.com>.
5  * Copyright (c) 2020 Red Hat, Inc.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2 or
8  * later.  See the COPYING file in the top-level directory.
9  */
10 #include "qemu/osdep.h"
11 #include "qemu/error-report.h"
12 #include "qemu/main-loop.h"
13 #include "qemu/vhost-user-server.h"
14 #include "block/aio-wait.h"
15 
16 /*
17  * Theory of operation:
18  *
19  * VuServer is started and stopped by vhost_user_server_start() and
20  * vhost_user_server_stop() from the main loop thread. Starting the server
21  * opens a vhost-user UNIX domain socket and listens for incoming connections.
22  * Only one connection is allowed at a time.
23  *
24  * The connection is handled by the vu_client_trip() coroutine in the
25  * VuServer->ctx AioContext. The coroutine consists of a vu_dispatch() loop
26  * where libvhost-user calls vu_message_read() to receive the next vhost-user
27  * protocol messages over the UNIX domain socket.
28  *
29  * When virtqueues are set up libvhost-user calls set_watch() to monitor kick
30  * fds. These fds are also handled in the VuServer->ctx AioContext.
31  *
32  * Both vu_client_trip() and kick fd monitoring can be stopped by shutting down
33  * the socket connection. Shutting down the socket connection causes
34  * vu_message_read() to fail since no more data can be received from the socket.
35  * After vu_dispatch() fails, vu_client_trip() calls vu_deinit() to stop
36  * libvhost-user before terminating the coroutine. vu_deinit() calls
37  * remove_watch() to stop monitoring kick fds and this stops virtqueue
38  * processing.
39  *
40  * When vu_client_trip() has finished cleaning up it schedules a BH in the main
41  * loop thread to accept the next client connection.
42  *
43  * When libvhost-user detects an error it calls panic_cb() and sets the
44  * dev->broken flag. Both vu_client_trip() and kick fd processing stop when
45  * the dev->broken flag is set.
46  *
47  * It is possible to switch AioContexts using
48  * vhost_user_server_detach_aio_context() and
49  * vhost_user_server_attach_aio_context(). They stop monitoring fds in the old
50  * AioContext and resume monitoring in the new AioContext. The vu_client_trip()
51  * coroutine remains in a yielded state during the switch. This is made
52  * possible by QIOChannel's support for spurious coroutine re-entry in
53  * qio_channel_yield(). The coroutine will restart I/O when re-entered from the
54  * new AioContext.
55  */
56 
57 static void vmsg_close_fds(VhostUserMsg *vmsg)
58 {
59     int i;
60     for (i = 0; i < vmsg->fd_num; i++) {
61         close(vmsg->fds[i]);
62     }
63 }
64 
65 static void vmsg_unblock_fds(VhostUserMsg *vmsg)
66 {
67     int i;
68     for (i = 0; i < vmsg->fd_num; i++) {
69         qemu_socket_set_nonblock(vmsg->fds[i]);
70     }
71 }
72 
73 static void panic_cb(VuDev *vu_dev, const char *buf)
74 {
75     error_report("vu_panic: %s", buf);
76 }
77 
78 void vhost_user_server_inc_in_flight(VuServer *server)
79 {
80     assert(!server->wait_idle);
81     qatomic_inc(&server->in_flight);
82 }
83 
84 void vhost_user_server_dec_in_flight(VuServer *server)
85 {
86     if (qatomic_fetch_dec(&server->in_flight) == 1) {
87         if (server->wait_idle) {
88             aio_co_wake(server->co_trip);
89         }
90     }
91 }
92 
93 bool vhost_user_server_has_in_flight(VuServer *server)
94 {
95     return qatomic_load_acquire(&server->in_flight) > 0;
96 }
97 
98 static bool coroutine_fn
99 vu_message_read(VuDev *vu_dev, int conn_fd, VhostUserMsg *vmsg)
100 {
101     struct iovec iov = {
102         .iov_base = (char *)vmsg,
103         .iov_len = VHOST_USER_HDR_SIZE,
104     };
105     int rc, read_bytes = 0;
106     Error *local_err = NULL;
107     const size_t max_fds = G_N_ELEMENTS(vmsg->fds);
108     VuServer *server = container_of(vu_dev, VuServer, vu_dev);
109     QIOChannel *ioc = server->ioc;
110 
111     vmsg->fd_num = 0;
112     if (!ioc) {
113         error_report_err(local_err);
114         goto fail;
115     }
116 
117     assert(qemu_in_coroutine());
118     do {
119         size_t nfds = 0;
120         int *fds = NULL;
121 
122         /*
123          * qio_channel_readv_full may have short reads, keeping calling it
124          * until getting VHOST_USER_HDR_SIZE or 0 bytes in total
125          */
126         rc = qio_channel_readv_full(ioc, &iov, 1, &fds, &nfds, 0, &local_err);
127         if (rc < 0) {
128             if (rc == QIO_CHANNEL_ERR_BLOCK) {
129                 assert(local_err == NULL);
130                 qio_channel_yield(ioc, G_IO_IN);
131                 continue;
132             } else {
133                 error_report_err(local_err);
134                 goto fail;
135             }
136         }
137 
138         if (nfds > 0) {
139             if (vmsg->fd_num + nfds > max_fds) {
140                 error_report("A maximum of %zu fds are allowed, "
141                              "however got %zu fds now",
142                              max_fds, vmsg->fd_num + nfds);
143                 g_free(fds);
144                 goto fail;
145             }
146             memcpy(vmsg->fds + vmsg->fd_num, fds, nfds * sizeof(vmsg->fds[0]));
147             vmsg->fd_num += nfds;
148             g_free(fds);
149         }
150 
151         if (rc == 0) { /* socket closed */
152             goto fail;
153         }
154 
155         iov.iov_base += rc;
156         iov.iov_len -= rc;
157         read_bytes += rc;
158     } while (read_bytes != VHOST_USER_HDR_SIZE);
159 
160     /* qio_channel_readv_full will make socket fds blocking, unblock them */
161     vmsg_unblock_fds(vmsg);
162     if (vmsg->size > sizeof(vmsg->payload)) {
163         error_report("Error: too big message request: %d, "
164                      "size: vmsg->size: %u, "
165                      "while sizeof(vmsg->payload) = %zu",
166                      vmsg->request, vmsg->size, sizeof(vmsg->payload));
167         goto fail;
168     }
169 
170     struct iovec iov_payload = {
171         .iov_base = (char *)&vmsg->payload,
172         .iov_len = vmsg->size,
173     };
174     if (vmsg->size) {
175         rc = qio_channel_readv_all_eof(ioc, &iov_payload, 1, &local_err);
176         if (rc != 1) {
177             if (local_err) {
178                 error_report_err(local_err);
179             }
180             goto fail;
181         }
182     }
183 
184     return true;
185 
186 fail:
187     vmsg_close_fds(vmsg);
188 
189     return false;
190 }
191 
192 static coroutine_fn void vu_client_trip(void *opaque)
193 {
194     VuServer *server = opaque;
195     VuDev *vu_dev = &server->vu_dev;
196 
197     while (!vu_dev->broken && vu_dispatch(vu_dev)) {
198         /* Keep running */
199     }
200 
201     if (vhost_user_server_has_in_flight(server)) {
202         /* Wait for requests to complete before we can unmap the memory */
203         server->wait_idle = true;
204         qemu_coroutine_yield();
205         server->wait_idle = false;
206     }
207     assert(!vhost_user_server_has_in_flight(server));
208 
209     vu_deinit(vu_dev);
210 
211     /* vu_deinit() should have called remove_watch() */
212     assert(QTAILQ_EMPTY(&server->vu_fd_watches));
213 
214     object_unref(OBJECT(server->sioc));
215     server->sioc = NULL;
216 
217     object_unref(OBJECT(server->ioc));
218     server->ioc = NULL;
219 
220     server->co_trip = NULL;
221     if (server->restart_listener_bh) {
222         qemu_bh_schedule(server->restart_listener_bh);
223     }
224     aio_wait_kick();
225 }
226 
227 /*
228  * a wrapper for vu_kick_cb
229  *
230  * since aio_dispatch can only pass one user data pointer to the
231  * callback function, pack VuDev and pvt into a struct. Then unpack it
232  * and pass them to vu_kick_cb
233  */
234 static void kick_handler(void *opaque)
235 {
236     VuFdWatch *vu_fd_watch = opaque;
237     VuDev *vu_dev = vu_fd_watch->vu_dev;
238 
239     vu_fd_watch->cb(vu_dev, 0, vu_fd_watch->pvt);
240 
241     /* Stop vu_client_trip() if an error occurred in vu_fd_watch->cb() */
242     if (vu_dev->broken) {
243         VuServer *server = container_of(vu_dev, VuServer, vu_dev);
244 
245         qio_channel_shutdown(server->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
246     }
247 }
248 
249 static VuFdWatch *find_vu_fd_watch(VuServer *server, int fd)
250 {
251 
252     VuFdWatch *vu_fd_watch, *next;
253     QTAILQ_FOREACH_SAFE(vu_fd_watch, &server->vu_fd_watches, next, next) {
254         if (vu_fd_watch->fd == fd) {
255             return vu_fd_watch;
256         }
257     }
258     return NULL;
259 }
260 
261 static void
262 set_watch(VuDev *vu_dev, int fd, int vu_evt,
263           vu_watch_cb cb, void *pvt)
264 {
265 
266     VuServer *server = container_of(vu_dev, VuServer, vu_dev);
267     g_assert(vu_dev);
268     g_assert(fd >= 0);
269     g_assert(cb);
270 
271     VuFdWatch *vu_fd_watch = find_vu_fd_watch(server, fd);
272 
273     if (!vu_fd_watch) {
274         VuFdWatch *vu_fd_watch = g_new0(VuFdWatch, 1);
275 
276         QTAILQ_INSERT_TAIL(&server->vu_fd_watches, vu_fd_watch, next);
277 
278         vu_fd_watch->fd = fd;
279         vu_fd_watch->cb = cb;
280         qemu_socket_set_nonblock(fd);
281         aio_set_fd_handler(server->ioc->ctx, fd, true, kick_handler,
282                            NULL, NULL, NULL, vu_fd_watch);
283         vu_fd_watch->vu_dev = vu_dev;
284         vu_fd_watch->pvt = pvt;
285     }
286 }
287 
288 
289 static void remove_watch(VuDev *vu_dev, int fd)
290 {
291     VuServer *server;
292     g_assert(vu_dev);
293     g_assert(fd >= 0);
294 
295     server = container_of(vu_dev, VuServer, vu_dev);
296 
297     VuFdWatch *vu_fd_watch = find_vu_fd_watch(server, fd);
298 
299     if (!vu_fd_watch) {
300         return;
301     }
302     aio_set_fd_handler(server->ioc->ctx, fd, true,
303                        NULL, NULL, NULL, NULL, NULL);
304 
305     QTAILQ_REMOVE(&server->vu_fd_watches, vu_fd_watch, next);
306     g_free(vu_fd_watch);
307 }
308 
309 
310 static void vu_accept(QIONetListener *listener, QIOChannelSocket *sioc,
311                       gpointer opaque)
312 {
313     VuServer *server = opaque;
314 
315     if (server->sioc) {
316         warn_report("Only one vhost-user client is allowed to "
317                     "connect the server one time");
318         return;
319     }
320 
321     if (!vu_init(&server->vu_dev, server->max_queues, sioc->fd, panic_cb,
322                  vu_message_read, set_watch, remove_watch, server->vu_iface)) {
323         error_report("Failed to initialize libvhost-user");
324         return;
325     }
326 
327     /*
328      * Unset the callback function for network listener to make another
329      * vhost-user client keeping waiting until this client disconnects
330      */
331     qio_net_listener_set_client_func(server->listener,
332                                      NULL,
333                                      NULL,
334                                      NULL);
335     server->sioc = sioc;
336     /*
337      * Increase the object reference, so sioc will not freed by
338      * qio_net_listener_channel_func which will call object_unref(OBJECT(sioc))
339      */
340     object_ref(OBJECT(server->sioc));
341     qio_channel_set_name(QIO_CHANNEL(sioc), "vhost-user client");
342     server->ioc = QIO_CHANNEL(sioc);
343     object_ref(OBJECT(server->ioc));
344 
345     /* TODO vu_message_write() spins if non-blocking! */
346     qio_channel_set_blocking(server->ioc, false, NULL);
347 
348     server->co_trip = qemu_coroutine_create(vu_client_trip, server);
349 
350     aio_context_acquire(server->ctx);
351     vhost_user_server_attach_aio_context(server, server->ctx);
352     aio_context_release(server->ctx);
353 }
354 
355 /* server->ctx acquired by caller */
356 void vhost_user_server_stop(VuServer *server)
357 {
358     qemu_bh_delete(server->restart_listener_bh);
359     server->restart_listener_bh = NULL;
360 
361     if (server->sioc) {
362         VuFdWatch *vu_fd_watch;
363 
364         QTAILQ_FOREACH(vu_fd_watch, &server->vu_fd_watches, next) {
365             aio_set_fd_handler(server->ctx, vu_fd_watch->fd, true,
366                                NULL, NULL, NULL, NULL, vu_fd_watch);
367         }
368 
369         qio_channel_shutdown(server->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
370 
371         AIO_WAIT_WHILE(server->ctx, server->co_trip);
372     }
373 
374     if (server->listener) {
375         qio_net_listener_disconnect(server->listener);
376         object_unref(OBJECT(server->listener));
377     }
378 }
379 
380 /*
381  * Allow the next client to connect to the server. Called from a BH in the main
382  * loop.
383  */
384 static void restart_listener_bh(void *opaque)
385 {
386     VuServer *server = opaque;
387 
388     qio_net_listener_set_client_func(server->listener, vu_accept, server,
389                                      NULL);
390 }
391 
392 /* Called with ctx acquired */
393 void vhost_user_server_attach_aio_context(VuServer *server, AioContext *ctx)
394 {
395     VuFdWatch *vu_fd_watch;
396 
397     server->ctx = ctx;
398 
399     if (!server->sioc) {
400         return;
401     }
402 
403     qio_channel_attach_aio_context(server->ioc, ctx);
404 
405     QTAILQ_FOREACH(vu_fd_watch, &server->vu_fd_watches, next) {
406         aio_set_fd_handler(ctx, vu_fd_watch->fd, true, kick_handler, NULL,
407                            NULL, NULL, vu_fd_watch);
408     }
409 
410     aio_co_schedule(ctx, server->co_trip);
411 }
412 
413 /* Called with server->ctx acquired */
414 void vhost_user_server_detach_aio_context(VuServer *server)
415 {
416     if (server->sioc) {
417         VuFdWatch *vu_fd_watch;
418 
419         QTAILQ_FOREACH(vu_fd_watch, &server->vu_fd_watches, next) {
420             aio_set_fd_handler(server->ctx, vu_fd_watch->fd, true,
421                                NULL, NULL, NULL, NULL, vu_fd_watch);
422         }
423 
424         qio_channel_detach_aio_context(server->ioc);
425     }
426 
427     server->ctx = NULL;
428 }
429 
430 bool vhost_user_server_start(VuServer *server,
431                              SocketAddress *socket_addr,
432                              AioContext *ctx,
433                              uint16_t max_queues,
434                              const VuDevIface *vu_iface,
435                              Error **errp)
436 {
437     QEMUBH *bh;
438     QIONetListener *listener;
439 
440     if (socket_addr->type != SOCKET_ADDRESS_TYPE_UNIX &&
441         socket_addr->type != SOCKET_ADDRESS_TYPE_FD) {
442         error_setg(errp, "Only socket address types 'unix' and 'fd' are supported");
443         return false;
444     }
445 
446     listener = qio_net_listener_new();
447     if (qio_net_listener_open_sync(listener, socket_addr, 1,
448                                    errp) < 0) {
449         object_unref(OBJECT(listener));
450         return false;
451     }
452 
453     bh = qemu_bh_new(restart_listener_bh, server);
454 
455     /* zero out unspecified fields */
456     *server = (VuServer) {
457         .listener              = listener,
458         .restart_listener_bh   = bh,
459         .vu_iface              = vu_iface,
460         .max_queues            = max_queues,
461         .ctx                   = ctx,
462     };
463 
464     qio_net_listener_set_name(server->listener, "vhost-user-backend-listener");
465 
466     qio_net_listener_set_client_func(server->listener,
467                                      vu_accept,
468                                      server,
469                                      NULL);
470 
471     QTAILQ_INIT(&server->vu_fd_watches);
472     return true;
473 }
474