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