xref: /qemu/tests/qtest/vhost-user-test.c (revision 76eb88b1)
1 /*
2  * QTest testcase for the vhost-user
3  *
4  * Copyright (c) 2014 Virtual Open Systems Sarl.
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2 or later.
7  * See the COPYING file in the top-level directory.
8  *
9  */
10 
11 #include "qemu/osdep.h"
12 
13 #include "libqtest-single.h"
14 #include "qapi/error.h"
15 #include "qapi/qmp/qdict.h"
16 #include "qemu/config-file.h"
17 #include "qemu/option.h"
18 #include "qemu/range.h"
19 #include "qemu/sockets.h"
20 #include "chardev/char-fe.h"
21 #include "qemu/memfd.h"
22 #include "qemu/module.h"
23 #include "sysemu/sysemu.h"
24 #include "libqos/libqos.h"
25 #include "libqos/pci-pc.h"
26 #include "libqos/virtio-pci.h"
27 
28 #include "libqos/malloc-pc.h"
29 #include "hw/virtio/virtio-net.h"
30 
31 #include "standard-headers/linux/vhost_types.h"
32 #include "standard-headers/linux/virtio_ids.h"
33 #include "standard-headers/linux/virtio_net.h"
34 
35 #ifdef CONFIG_LINUX
36 #include <sys/vfs.h>
37 #endif
38 
39 
40 #define QEMU_CMD_MEM    " -m %d -object memory-backend-file,id=mem,size=%dM," \
41                         "mem-path=%s,share=on -numa node,memdev=mem"
42 #define QEMU_CMD_MEMFD  " -m %d -object memory-backend-memfd,id=mem,size=%dM," \
43                         " -numa node,memdev=mem"
44 #define QEMU_CMD_CHR    " -chardev socket,id=%s,path=%s%s"
45 #define QEMU_CMD_NETDEV " -netdev vhost-user,id=hs0,chardev=%s,vhostforce=on"
46 
47 #define HUGETLBFS_MAGIC       0x958458f6
48 
49 /*********** FROM hw/virtio/vhost-user.c *************************************/
50 
51 #define VHOST_MEMORY_MAX_NREGIONS    8
52 #define VHOST_MAX_VIRTQUEUES    0x100
53 
54 #define VHOST_USER_F_PROTOCOL_FEATURES 30
55 #define VHOST_USER_PROTOCOL_F_MQ 0
56 #define VHOST_USER_PROTOCOL_F_LOG_SHMFD 1
57 #define VHOST_USER_PROTOCOL_F_CROSS_ENDIAN   6
58 
59 #define VHOST_LOG_PAGE 0x1000
60 
61 typedef enum VhostUserRequest {
62     VHOST_USER_NONE = 0,
63     VHOST_USER_GET_FEATURES = 1,
64     VHOST_USER_SET_FEATURES = 2,
65     VHOST_USER_SET_OWNER = 3,
66     VHOST_USER_RESET_OWNER = 4,
67     VHOST_USER_SET_MEM_TABLE = 5,
68     VHOST_USER_SET_LOG_BASE = 6,
69     VHOST_USER_SET_LOG_FD = 7,
70     VHOST_USER_SET_VRING_NUM = 8,
71     VHOST_USER_SET_VRING_ADDR = 9,
72     VHOST_USER_SET_VRING_BASE = 10,
73     VHOST_USER_GET_VRING_BASE = 11,
74     VHOST_USER_SET_VRING_KICK = 12,
75     VHOST_USER_SET_VRING_CALL = 13,
76     VHOST_USER_SET_VRING_ERR = 14,
77     VHOST_USER_GET_PROTOCOL_FEATURES = 15,
78     VHOST_USER_SET_PROTOCOL_FEATURES = 16,
79     VHOST_USER_GET_QUEUE_NUM = 17,
80     VHOST_USER_SET_VRING_ENABLE = 18,
81     VHOST_USER_MAX
82 } VhostUserRequest;
83 
84 typedef struct VhostUserMemoryRegion {
85     uint64_t guest_phys_addr;
86     uint64_t memory_size;
87     uint64_t userspace_addr;
88     uint64_t mmap_offset;
89 } VhostUserMemoryRegion;
90 
91 typedef struct VhostUserMemory {
92     uint32_t nregions;
93     uint32_t padding;
94     VhostUserMemoryRegion regions[VHOST_MEMORY_MAX_NREGIONS];
95 } VhostUserMemory;
96 
97 typedef struct VhostUserLog {
98     uint64_t mmap_size;
99     uint64_t mmap_offset;
100 } VhostUserLog;
101 
102 typedef struct VhostUserMsg {
103     VhostUserRequest request;
104 
105 #define VHOST_USER_VERSION_MASK     (0x3)
106 #define VHOST_USER_REPLY_MASK       (0x1<<2)
107     uint32_t flags;
108     uint32_t size; /* the following payload size */
109     union {
110 #define VHOST_USER_VRING_IDX_MASK   (0xff)
111 #define VHOST_USER_VRING_NOFD_MASK  (0x1<<8)
112         uint64_t u64;
113         struct vhost_vring_state state;
114         struct vhost_vring_addr addr;
115         VhostUserMemory memory;
116         VhostUserLog log;
117     } payload;
118 } QEMU_PACKED VhostUserMsg;
119 
120 static VhostUserMsg m __attribute__ ((unused));
121 #define VHOST_USER_HDR_SIZE (sizeof(m.request) \
122                             + sizeof(m.flags) \
123                             + sizeof(m.size))
124 
125 #define VHOST_USER_PAYLOAD_SIZE (sizeof(m) - VHOST_USER_HDR_SIZE)
126 
127 /* The version of the protocol we support */
128 #define VHOST_USER_VERSION    (0x1)
129 /*****************************************************************************/
130 
131 enum {
132     TEST_FLAGS_OK,
133     TEST_FLAGS_DISCONNECT,
134     TEST_FLAGS_BAD,
135     TEST_FLAGS_END,
136 };
137 
138 enum {
139     VHOST_USER_NET,
140 };
141 
142 typedef struct TestServer {
143     gchar *socket_path;
144     gchar *mig_path;
145     gchar *chr_name;
146     gchar *tmpfs;
147     CharBackend chr;
148     int fds_num;
149     int fds[VHOST_MEMORY_MAX_NREGIONS];
150     VhostUserMemory memory;
151     GMainContext *context;
152     GMainLoop *loop;
153     GThread *thread;
154     GMutex data_mutex;
155     GCond data_cond;
156     int log_fd;
157     uint64_t rings;
158     bool test_fail;
159     int test_flags;
160     int queues;
161     struct vhost_user_ops *vu_ops;
162 } TestServer;
163 
164 struct vhost_user_ops {
165     /* Device types. */
166     int type;
167     void (*append_opts)(TestServer *s, GString *cmd_line,
168             const char *chr_opts);
169 
170     /* VHOST-USER commands. */
171     void (*set_features)(TestServer *s, CharBackend *chr,
172             VhostUserMsg *msg);
173     void (*get_protocol_features)(TestServer *s,
174             CharBackend *chr, VhostUserMsg *msg);
175 };
176 
177 static const char *init_hugepagefs(void);
178 static TestServer *test_server_new(const gchar *name,
179         struct vhost_user_ops *ops);
180 static void test_server_free(TestServer *server);
181 static void test_server_listen(TestServer *server);
182 
183 enum test_memfd {
184     TEST_MEMFD_AUTO,
185     TEST_MEMFD_YES,
186     TEST_MEMFD_NO,
187 };
188 
189 static void append_vhost_net_opts(TestServer *s, GString *cmd_line,
190                              const char *chr_opts)
191 {
192     g_string_append_printf(cmd_line, QEMU_CMD_CHR QEMU_CMD_NETDEV,
193                            s->chr_name, s->socket_path,
194                            chr_opts, s->chr_name);
195 }
196 
197 static void append_mem_opts(TestServer *server, GString *cmd_line,
198                             int size, enum test_memfd memfd)
199 {
200     if (memfd == TEST_MEMFD_AUTO) {
201         memfd = qemu_memfd_check(MFD_ALLOW_SEALING) ? TEST_MEMFD_YES
202                                                     : TEST_MEMFD_NO;
203     }
204 
205     if (memfd == TEST_MEMFD_YES) {
206         g_string_append_printf(cmd_line, QEMU_CMD_MEMFD, size, size);
207     } else {
208         const char *root = init_hugepagefs() ? : server->tmpfs;
209 
210         g_string_append_printf(cmd_line, QEMU_CMD_MEM, size, size, root);
211     }
212 }
213 
214 static bool wait_for_fds(TestServer *s)
215 {
216     gint64 end_time;
217     bool got_region;
218     int i;
219 
220     g_mutex_lock(&s->data_mutex);
221 
222     end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
223     while (!s->fds_num) {
224         if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
225             /* timeout has passed */
226             g_assert(s->fds_num);
227             break;
228         }
229     }
230 
231     /* check for sanity */
232     g_assert_cmpint(s->fds_num, >, 0);
233     g_assert_cmpint(s->fds_num, ==, s->memory.nregions);
234 
235     g_mutex_unlock(&s->data_mutex);
236 
237     got_region = false;
238     for (i = 0; i < s->memory.nregions; ++i) {
239         VhostUserMemoryRegion *reg = &s->memory.regions[i];
240         if (reg->guest_phys_addr == 0) {
241             got_region = true;
242             break;
243         }
244     }
245     if (!got_region) {
246         g_test_skip("No memory at address 0x0");
247     }
248     return got_region;
249 }
250 
251 static void read_guest_mem_server(QTestState *qts, TestServer *s)
252 {
253     uint8_t *guest_mem;
254     int i, j;
255     size_t size;
256 
257     g_mutex_lock(&s->data_mutex);
258 
259     /* iterate all regions */
260     for (i = 0; i < s->fds_num; i++) {
261 
262         /* We'll check only the region statring at 0x0*/
263         if (s->memory.regions[i].guest_phys_addr != 0x0) {
264             continue;
265         }
266 
267         g_assert_cmpint(s->memory.regions[i].memory_size, >, 1024);
268 
269         size = s->memory.regions[i].memory_size +
270             s->memory.regions[i].mmap_offset;
271 
272         guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,
273                          MAP_SHARED, s->fds[i], 0);
274 
275         g_assert(guest_mem != MAP_FAILED);
276         guest_mem += (s->memory.regions[i].mmap_offset / sizeof(*guest_mem));
277 
278         for (j = 0; j < 1024; j++) {
279             uint32_t a = qtest_readb(qts, s->memory.regions[i].guest_phys_addr + j);
280             uint32_t b = guest_mem[j];
281 
282             g_assert_cmpint(a, ==, b);
283         }
284 
285         munmap(guest_mem, s->memory.regions[i].memory_size);
286     }
287 
288     g_mutex_unlock(&s->data_mutex);
289 }
290 
291 static void *thread_function(void *data)
292 {
293     GMainLoop *loop = data;
294     g_main_loop_run(loop);
295     return NULL;
296 }
297 
298 static int chr_can_read(void *opaque)
299 {
300     return VHOST_USER_HDR_SIZE;
301 }
302 
303 static void chr_read(void *opaque, const uint8_t *buf, int size)
304 {
305     g_autoptr(GError) err = NULL;
306     TestServer *s = opaque;
307     CharBackend *chr = &s->chr;
308     VhostUserMsg msg;
309     uint8_t *p = (uint8_t *) &msg;
310     int fd = -1;
311 
312     if (s->test_fail) {
313         qemu_chr_fe_disconnect(chr);
314         /* now switch to non-failure */
315         s->test_fail = false;
316     }
317 
318     if (size != VHOST_USER_HDR_SIZE) {
319         g_test_message("Wrong message size received %d", size);
320         return;
321     }
322 
323     g_mutex_lock(&s->data_mutex);
324     memcpy(p, buf, VHOST_USER_HDR_SIZE);
325 
326     if (msg.size) {
327         p += VHOST_USER_HDR_SIZE;
328         size = qemu_chr_fe_read_all(chr, p, msg.size);
329         if (size != msg.size) {
330             g_test_message("Wrong message size received %d != %d",
331                            size, msg.size);
332             return;
333         }
334     }
335 
336     switch (msg.request) {
337     case VHOST_USER_GET_FEATURES:
338         /* send back features to qemu */
339         msg.flags |= VHOST_USER_REPLY_MASK;
340         msg.size = sizeof(m.payload.u64);
341         msg.payload.u64 = 0x1ULL << VHOST_F_LOG_ALL |
342             0x1ULL << VHOST_USER_F_PROTOCOL_FEATURES;
343         if (s->queues > 1) {
344             msg.payload.u64 |= 0x1ULL << VIRTIO_NET_F_MQ;
345         }
346         if (s->test_flags >= TEST_FLAGS_BAD) {
347             msg.payload.u64 = 0;
348             s->test_flags = TEST_FLAGS_END;
349         }
350         p = (uint8_t *) &msg;
351         qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
352         break;
353 
354     case VHOST_USER_SET_FEATURES:
355         if (s->vu_ops->set_features) {
356             s->vu_ops->set_features(s, chr, &msg);
357         }
358         break;
359 
360     case VHOST_USER_GET_PROTOCOL_FEATURES:
361         if (s->vu_ops->get_protocol_features) {
362             s->vu_ops->get_protocol_features(s, chr, &msg);
363         }
364         break;
365 
366     case VHOST_USER_GET_VRING_BASE:
367         /* send back vring base to qemu */
368         msg.flags |= VHOST_USER_REPLY_MASK;
369         msg.size = sizeof(m.payload.state);
370         msg.payload.state.num = 0;
371         p = (uint8_t *) &msg;
372         qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
373 
374         assert(msg.payload.state.index < s->queues * 2);
375         s->rings &= ~(0x1ULL << msg.payload.state.index);
376         g_cond_broadcast(&s->data_cond);
377         break;
378 
379     case VHOST_USER_SET_MEM_TABLE:
380         /* received the mem table */
381         memcpy(&s->memory, &msg.payload.memory, sizeof(msg.payload.memory));
382         s->fds_num = qemu_chr_fe_get_msgfds(chr, s->fds,
383                                             G_N_ELEMENTS(s->fds));
384 
385         /* signal the test that it can continue */
386         g_cond_broadcast(&s->data_cond);
387         break;
388 
389     case VHOST_USER_SET_VRING_KICK:
390     case VHOST_USER_SET_VRING_CALL:
391         /* consume the fd */
392         qemu_chr_fe_get_msgfds(chr, &fd, 1);
393         /*
394          * This is a non-blocking eventfd.
395          * The receive function forces it to be blocking,
396          * so revert it back to non-blocking.
397          */
398         g_unix_set_fd_nonblocking(fd, true, &err);
399         g_assert_no_error(err);
400         break;
401 
402     case VHOST_USER_SET_LOG_BASE:
403         if (s->log_fd != -1) {
404             close(s->log_fd);
405             s->log_fd = -1;
406         }
407         qemu_chr_fe_get_msgfds(chr, &s->log_fd, 1);
408         msg.flags |= VHOST_USER_REPLY_MASK;
409         msg.size = 0;
410         p = (uint8_t *) &msg;
411         qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE);
412 
413         g_cond_broadcast(&s->data_cond);
414         break;
415 
416     case VHOST_USER_SET_VRING_BASE:
417         assert(msg.payload.state.index < s->queues * 2);
418         s->rings |= 0x1ULL << msg.payload.state.index;
419         g_cond_broadcast(&s->data_cond);
420         break;
421 
422     case VHOST_USER_GET_QUEUE_NUM:
423         msg.flags |= VHOST_USER_REPLY_MASK;
424         msg.size = sizeof(m.payload.u64);
425         msg.payload.u64 = s->queues;
426         p = (uint8_t *) &msg;
427         qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
428         break;
429 
430     default:
431         break;
432     }
433 
434     g_mutex_unlock(&s->data_mutex);
435 }
436 
437 static const char *init_hugepagefs(void)
438 {
439 #ifdef CONFIG_LINUX
440     static const char *hugepagefs;
441     const char *path = getenv("QTEST_HUGETLBFS_PATH");
442     struct statfs fs;
443     int ret;
444 
445     if (hugepagefs) {
446         return hugepagefs;
447     }
448     if (!path) {
449         return NULL;
450     }
451 
452     if (access(path, R_OK | W_OK | X_OK)) {
453         g_test_message("access on path (%s): %s", path, strerror(errno));
454         g_test_fail();
455         return NULL;
456     }
457 
458     do {
459         ret = statfs(path, &fs);
460     } while (ret != 0 && errno == EINTR);
461 
462     if (ret != 0) {
463         g_test_message("statfs on path (%s): %s", path, strerror(errno));
464         g_test_fail();
465         return NULL;
466     }
467 
468     if (fs.f_type != HUGETLBFS_MAGIC) {
469         g_test_message("Warning: path not on HugeTLBFS: %s", path);
470         g_test_fail();
471         return NULL;
472     }
473 
474     hugepagefs = path;
475     return hugepagefs;
476 #else
477     return NULL;
478 #endif
479 }
480 
481 static TestServer *test_server_new(const gchar *name,
482         struct vhost_user_ops *ops)
483 {
484     TestServer *server = g_new0(TestServer, 1);
485     g_autofree const char *tmpfs = NULL;
486     GError *err = NULL;
487 
488     server->context = g_main_context_new();
489     server->loop = g_main_loop_new(server->context, FALSE);
490 
491     /* run the main loop thread so the chardev may operate */
492     server->thread = g_thread_new(NULL, thread_function, server->loop);
493 
494     tmpfs = g_dir_make_tmp("vhost-test-XXXXXX", &err);
495     if (!tmpfs) {
496         g_test_message("g_dir_make_tmp on path (%s): %s", tmpfs,
497                        err->message);
498         g_error_free(err);
499     }
500     g_assert(tmpfs);
501 
502     server->tmpfs = g_strdup(tmpfs);
503     server->socket_path = g_strdup_printf("%s/%s.sock", tmpfs, name);
504     server->mig_path = g_strdup_printf("%s/%s.mig", tmpfs, name);
505     server->chr_name = g_strdup_printf("chr-%s", name);
506 
507     g_mutex_init(&server->data_mutex);
508     g_cond_init(&server->data_cond);
509 
510     server->log_fd = -1;
511     server->queues = 1;
512     server->vu_ops = ops;
513 
514     return server;
515 }
516 
517 static void chr_event(void *opaque, QEMUChrEvent event)
518 {
519     TestServer *s = opaque;
520 
521     if (s->test_flags == TEST_FLAGS_END &&
522         event == CHR_EVENT_CLOSED) {
523         s->test_flags = TEST_FLAGS_OK;
524     }
525 }
526 
527 static void test_server_create_chr(TestServer *server, const gchar *opt)
528 {
529     g_autofree gchar *chr_path = g_strdup_printf("unix:%s%s",
530                                                  server->socket_path, opt);
531     Chardev *chr;
532 
533     chr = qemu_chr_new(server->chr_name, chr_path, server->context);
534     g_assert(chr);
535 
536     qemu_chr_fe_init(&server->chr, chr, &error_abort);
537     qemu_chr_fe_set_handlers(&server->chr, chr_can_read, chr_read,
538                              chr_event, NULL, server, server->context, true);
539 }
540 
541 static void test_server_listen(TestServer *server)
542 {
543     test_server_create_chr(server, ",server=on,wait=off");
544 }
545 
546 static void test_server_free(TestServer *server)
547 {
548     int i, ret;
549 
550     /* finish the helper thread and dispatch pending sources */
551     g_main_loop_quit(server->loop);
552     g_thread_join(server->thread);
553     while (g_main_context_pending(NULL)) {
554         g_main_context_iteration(NULL, TRUE);
555     }
556 
557     unlink(server->socket_path);
558     g_free(server->socket_path);
559 
560     unlink(server->mig_path);
561     g_free(server->mig_path);
562 
563     ret = rmdir(server->tmpfs);
564     if (ret != 0) {
565         g_test_message("unable to rmdir: path (%s): %s",
566                        server->tmpfs, strerror(errno));
567     }
568     g_free(server->tmpfs);
569 
570     qemu_chr_fe_deinit(&server->chr, true);
571 
572     for (i = 0; i < server->fds_num; i++) {
573         close(server->fds[i]);
574     }
575 
576     if (server->log_fd != -1) {
577         close(server->log_fd);
578     }
579 
580     g_free(server->chr_name);
581 
582     g_main_loop_unref(server->loop);
583     g_main_context_unref(server->context);
584     g_cond_clear(&server->data_cond);
585     g_mutex_clear(&server->data_mutex);
586     g_free(server);
587 }
588 
589 static void wait_for_log_fd(TestServer *s)
590 {
591     gint64 end_time;
592 
593     g_mutex_lock(&s->data_mutex);
594     end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
595     while (s->log_fd == -1) {
596         if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
597             /* timeout has passed */
598             g_assert(s->log_fd != -1);
599             break;
600         }
601     }
602 
603     g_mutex_unlock(&s->data_mutex);
604 }
605 
606 static void write_guest_mem(TestServer *s, uint32_t seed)
607 {
608     uint32_t *guest_mem;
609     int i, j;
610     size_t size;
611 
612     /* iterate all regions */
613     for (i = 0; i < s->fds_num; i++) {
614 
615         /* We'll write only the region statring at 0x0 */
616         if (s->memory.regions[i].guest_phys_addr != 0x0) {
617             continue;
618         }
619 
620         g_assert_cmpint(s->memory.regions[i].memory_size, >, 1024);
621 
622         size = s->memory.regions[i].memory_size +
623             s->memory.regions[i].mmap_offset;
624 
625         guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,
626                          MAP_SHARED, s->fds[i], 0);
627 
628         g_assert(guest_mem != MAP_FAILED);
629         guest_mem += (s->memory.regions[i].mmap_offset / sizeof(*guest_mem));
630 
631         for (j = 0; j < 256; j++) {
632             guest_mem[j] = seed + j;
633         }
634 
635         munmap(guest_mem, s->memory.regions[i].memory_size);
636         break;
637     }
638 }
639 
640 static guint64 get_log_size(TestServer *s)
641 {
642     guint64 log_size = 0;
643     int i;
644 
645     for (i = 0; i < s->memory.nregions; ++i) {
646         VhostUserMemoryRegion *reg = &s->memory.regions[i];
647         guint64 last = range_get_last(reg->guest_phys_addr,
648                                        reg->memory_size);
649         log_size = MAX(log_size, last / (8 * VHOST_LOG_PAGE) + 1);
650     }
651 
652     return log_size;
653 }
654 
655 typedef struct TestMigrateSource {
656     GSource source;
657     TestServer *src;
658     TestServer *dest;
659 } TestMigrateSource;
660 
661 static gboolean
662 test_migrate_source_check(GSource *source)
663 {
664     TestMigrateSource *t = (TestMigrateSource *)source;
665     gboolean overlap = t->src->rings && t->dest->rings;
666 
667     g_assert(!overlap);
668 
669     return FALSE;
670 }
671 
672 GSourceFuncs test_migrate_source_funcs = {
673     .check = test_migrate_source_check,
674 };
675 
676 static void vhost_user_test_cleanup(void *s)
677 {
678     TestServer *server = s;
679 
680     qos_invalidate_command_line();
681     test_server_free(server);
682 }
683 
684 static void *vhost_user_test_setup(GString *cmd_line, void *arg)
685 {
686     TestServer *server = test_server_new("vhost-user-test", arg);
687     test_server_listen(server);
688 
689     append_mem_opts(server, cmd_line, 256, TEST_MEMFD_AUTO);
690     server->vu_ops->append_opts(server, cmd_line, "");
691 
692     g_test_queue_destroy(vhost_user_test_cleanup, server);
693 
694     return server;
695 }
696 
697 static void *vhost_user_test_setup_memfd(GString *cmd_line, void *arg)
698 {
699     TestServer *server = test_server_new("vhost-user-test", arg);
700     test_server_listen(server);
701 
702     append_mem_opts(server, cmd_line, 256, TEST_MEMFD_YES);
703     server->vu_ops->append_opts(server, cmd_line, "");
704 
705     g_test_queue_destroy(vhost_user_test_cleanup, server);
706 
707     return server;
708 }
709 
710 static void test_read_guest_mem(void *obj, void *arg, QGuestAllocator *alloc)
711 {
712     TestServer *server = arg;
713 
714     if (!wait_for_fds(server)) {
715         return;
716     }
717 
718     read_guest_mem_server(global_qtest, server);
719 }
720 
721 static void test_migrate(void *obj, void *arg, QGuestAllocator *alloc)
722 {
723     TestServer *s = arg;
724     TestServer *dest;
725     GString *dest_cmdline;
726     char *uri;
727     QTestState *to;
728     GSource *source;
729     QDict *rsp;
730     guint8 *log;
731     guint64 size;
732 
733     if (!wait_for_fds(s)) {
734         return;
735     }
736 
737     dest = test_server_new("dest", s->vu_ops);
738     dest_cmdline = g_string_new(qos_get_current_command_line());
739     uri = g_strdup_printf("%s%s", "unix:", dest->mig_path);
740 
741     size = get_log_size(s);
742     g_assert_cmpint(size, ==, (256 * 1024 * 1024) / (VHOST_LOG_PAGE * 8));
743 
744     test_server_listen(dest);
745     g_string_append_printf(dest_cmdline, " -incoming %s", uri);
746     append_mem_opts(dest, dest_cmdline, 256, TEST_MEMFD_AUTO);
747     dest->vu_ops->append_opts(dest, dest_cmdline, "");
748     to = qtest_init(dest_cmdline->str);
749 
750     /* This would be where you call qos_allocate_objects(to, NULL), if you want
751      * to talk to the QVirtioNet object on the destination.
752      */
753 
754     source = g_source_new(&test_migrate_source_funcs,
755                           sizeof(TestMigrateSource));
756     ((TestMigrateSource *)source)->src = s;
757     ((TestMigrateSource *)source)->dest = dest;
758     g_source_attach(source, s->context);
759 
760     /* slow down migration to have time to fiddle with log */
761     /* TODO: qtest could learn to break on some places */
762     rsp = qmp("{ 'execute': 'migrate-set-parameters',"
763               "'arguments': { 'max-bandwidth': 10 } }");
764     g_assert(qdict_haskey(rsp, "return"));
765     qobject_unref(rsp);
766 
767     rsp = qmp("{ 'execute': 'migrate', 'arguments': { 'uri': %s } }", uri);
768     g_assert(qdict_haskey(rsp, "return"));
769     qobject_unref(rsp);
770 
771     wait_for_log_fd(s);
772 
773     log = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, s->log_fd, 0);
774     g_assert(log != MAP_FAILED);
775 
776     /* modify first page */
777     write_guest_mem(s, 0x42);
778     log[0] = 1;
779     munmap(log, size);
780 
781     /* speed things up */
782     rsp = qmp("{ 'execute': 'migrate-set-parameters',"
783               "'arguments': { 'max-bandwidth': 0 } }");
784     g_assert(qdict_haskey(rsp, "return"));
785     qobject_unref(rsp);
786 
787     qmp_eventwait("STOP");
788     qtest_qmp_eventwait(to, "RESUME");
789 
790     g_assert(wait_for_fds(dest));
791     read_guest_mem_server(to, dest);
792 
793     g_source_destroy(source);
794     g_source_unref(source);
795 
796     qtest_quit(to);
797     test_server_free(dest);
798     g_free(uri);
799     g_string_free(dest_cmdline, true);
800 }
801 
802 static void wait_for_rings_started(TestServer *s, size_t count)
803 {
804     gint64 end_time;
805 
806     g_mutex_lock(&s->data_mutex);
807     end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
808     while (ctpop64(s->rings) != count) {
809         if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
810             /* timeout has passed */
811             g_assert_cmpint(ctpop64(s->rings), ==, count);
812             break;
813         }
814     }
815 
816     g_mutex_unlock(&s->data_mutex);
817 }
818 
819 static inline void test_server_connect(TestServer *server)
820 {
821     test_server_create_chr(server, ",reconnect=1");
822 }
823 
824 static gboolean
825 reconnect_cb(gpointer user_data)
826 {
827     TestServer *s = user_data;
828 
829     qemu_chr_fe_disconnect(&s->chr);
830 
831     return FALSE;
832 }
833 
834 static gpointer
835 connect_thread(gpointer data)
836 {
837     TestServer *s = data;
838 
839     /* wait for qemu to start before first try, to avoid extra warnings */
840     g_usleep(G_USEC_PER_SEC);
841     test_server_connect(s);
842 
843     return NULL;
844 }
845 
846 static void *vhost_user_test_setup_reconnect(GString *cmd_line, void *arg)
847 {
848     TestServer *s = test_server_new("reconnect", arg);
849 
850     g_thread_new("connect", connect_thread, s);
851     append_mem_opts(s, cmd_line, 256, TEST_MEMFD_AUTO);
852     s->vu_ops->append_opts(s, cmd_line, ",server=on");
853 
854     g_test_queue_destroy(vhost_user_test_cleanup, s);
855 
856     return s;
857 }
858 
859 static void test_reconnect(void *obj, void *arg, QGuestAllocator *alloc)
860 {
861     TestServer *s = arg;
862     GSource *src;
863 
864     if (!wait_for_fds(s)) {
865         return;
866     }
867 
868     wait_for_rings_started(s, 2);
869 
870     /* reconnect */
871     s->fds_num = 0;
872     s->rings = 0;
873     src = g_idle_source_new();
874     g_source_set_callback(src, reconnect_cb, s, NULL);
875     g_source_attach(src, s->context);
876     g_source_unref(src);
877     g_assert(wait_for_fds(s));
878     wait_for_rings_started(s, 2);
879 }
880 
881 static void *vhost_user_test_setup_connect_fail(GString *cmd_line, void *arg)
882 {
883     TestServer *s = test_server_new("connect-fail", arg);
884 
885     s->test_fail = true;
886 
887     g_thread_new("connect", connect_thread, s);
888     append_mem_opts(s, cmd_line, 256, TEST_MEMFD_AUTO);
889     s->vu_ops->append_opts(s, cmd_line, ",server=on");
890 
891     g_test_queue_destroy(vhost_user_test_cleanup, s);
892 
893     return s;
894 }
895 
896 static void *vhost_user_test_setup_flags_mismatch(GString *cmd_line, void *arg)
897 {
898     TestServer *s = test_server_new("flags-mismatch", arg);
899 
900     s->test_flags = TEST_FLAGS_DISCONNECT;
901 
902     g_thread_new("connect", connect_thread, s);
903     append_mem_opts(s, cmd_line, 256, TEST_MEMFD_AUTO);
904     s->vu_ops->append_opts(s, cmd_line, ",server=on");
905 
906     g_test_queue_destroy(vhost_user_test_cleanup, s);
907 
908     return s;
909 }
910 
911 static void test_vhost_user_started(void *obj, void *arg, QGuestAllocator *alloc)
912 {
913     TestServer *s = arg;
914 
915     if (!wait_for_fds(s)) {
916         return;
917     }
918     wait_for_rings_started(s, 2);
919 }
920 
921 static void *vhost_user_test_setup_multiqueue(GString *cmd_line, void *arg)
922 {
923     TestServer *s = vhost_user_test_setup(cmd_line, arg);
924 
925     s->queues = 2;
926     g_string_append_printf(cmd_line,
927                            " -set netdev.hs0.queues=%d"
928                            " -global virtio-net-pci.vectors=%d",
929                            s->queues, s->queues * 2 + 2);
930 
931     return s;
932 }
933 
934 static void test_multiqueue(void *obj, void *arg, QGuestAllocator *alloc)
935 {
936     TestServer *s = arg;
937 
938     wait_for_rings_started(s, s->queues * 2);
939 }
940 
941 static void vu_net_set_features(TestServer *s, CharBackend *chr,
942         VhostUserMsg *msg)
943 {
944     g_assert_cmpint(msg->payload.u64 &
945             (0x1ULL << VHOST_USER_F_PROTOCOL_FEATURES), !=, 0ULL);
946     if (s->test_flags == TEST_FLAGS_DISCONNECT) {
947         qemu_chr_fe_disconnect(chr);
948         s->test_flags = TEST_FLAGS_BAD;
949     }
950 }
951 
952 static void vu_net_get_protocol_features(TestServer *s, CharBackend *chr,
953         VhostUserMsg *msg)
954 {
955     /* send back features to qemu */
956     msg->flags |= VHOST_USER_REPLY_MASK;
957     msg->size = sizeof(m.payload.u64);
958     msg->payload.u64 = 1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD;
959     msg->payload.u64 |= 1 << VHOST_USER_PROTOCOL_F_CROSS_ENDIAN;
960     if (s->queues > 1) {
961         msg->payload.u64 |= 1 << VHOST_USER_PROTOCOL_F_MQ;
962     }
963     qemu_chr_fe_write_all(chr, (uint8_t *)msg, VHOST_USER_HDR_SIZE + msg->size);
964 }
965 
966 /* Each VHOST-USER device should have its ops structure defined. */
967 static struct vhost_user_ops g_vu_net_ops = {
968     .type = VHOST_USER_NET,
969 
970     .append_opts = append_vhost_net_opts,
971 
972     .set_features = vu_net_set_features,
973     .get_protocol_features = vu_net_get_protocol_features,
974 };
975 
976 static void register_vhost_user_test(void)
977 {
978     QOSGraphTestOptions opts = {
979         .before = vhost_user_test_setup,
980         .subprocess = true,
981         .arg = &g_vu_net_ops,
982     };
983 
984     qemu_add_opts(&qemu_chardev_opts);
985 
986     qos_add_test("vhost-user/read-guest-mem/memfile",
987                  "virtio-net",
988                  test_read_guest_mem, &opts);
989 
990     if (qemu_memfd_check(MFD_ALLOW_SEALING)) {
991         opts.before = vhost_user_test_setup_memfd;
992         qos_add_test("vhost-user/read-guest-mem/memfd",
993                      "virtio-net",
994                      test_read_guest_mem, &opts);
995     }
996 
997     qos_add_test("vhost-user/migrate",
998                  "virtio-net",
999                  test_migrate, &opts);
1000 
1001     opts.before = vhost_user_test_setup_reconnect;
1002     qos_add_test("vhost-user/reconnect", "virtio-net",
1003                  test_reconnect, &opts);
1004 
1005     opts.before = vhost_user_test_setup_connect_fail;
1006     qos_add_test("vhost-user/connect-fail", "virtio-net",
1007                  test_vhost_user_started, &opts);
1008 
1009     opts.before = vhost_user_test_setup_flags_mismatch;
1010     qos_add_test("vhost-user/flags-mismatch", "virtio-net",
1011                  test_vhost_user_started, &opts);
1012 
1013     opts.before = vhost_user_test_setup_multiqueue;
1014     opts.edge.extra_device_opts = "mq=on";
1015     qos_add_test("vhost-user/multiqueue",
1016                  "virtio-net",
1017                  test_multiqueue, &opts);
1018 }
1019 libqos_init(register_vhost_user_test);
1020