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