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