vhost-user-test.c 27.5 KB
Newer Older
N
Nikolay Nikolaev 已提交
1 2 3 4 5 6 7 8 9 10
/*
 * QTest testcase for the vhost-user
 *
 * Copyright (c) 2014 Virtual Open Systems Sarl.
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 *
 */

P
Peter Maydell 已提交
11
#include "qemu/osdep.h"
12

N
Nikolay Nikolaev 已提交
13
#include "libqtest.h"
14
#include "qapi/error.h"
15
#include "qapi/qmp/qdict.h"
M
Marc-André Lureau 已提交
16
#include "qemu/config-file.h"
N
Nikolay Nikolaev 已提交
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"
N
Nikolay Nikolaev 已提交
22
#include "sysemu/sysemu.h"
23 24 25
#include "libqos/libqos.h"
#include "libqos/pci-pc.h"
#include "libqos/virtio-pci.h"
N
Nikolay Nikolaev 已提交
26

27 28 29
#include "libqos/malloc-pc.h"
#include "hw/virtio/virtio-net.h"

30 31 32 33 34
#include "standard-headers/linux/vhost_types.h"
#include "standard-headers/linux/virtio_ids.h"
#include "standard-headers/linux/virtio_net.h"

#ifdef CONFIG_LINUX
N
Nikolay Nikolaev 已提交
35
#include <sys/vfs.h>
36
#endif
N
Nikolay Nikolaev 已提交
37

38

39
#define QEMU_CMD_MEM    " -m %d -object memory-backend-file,id=mem,size=%dM," \
N
Nikolay Nikolaev 已提交
40
                        "mem-path=%s,share=on -numa node,memdev=mem"
41 42
#define QEMU_CMD_MEMFD  " -m %d -object memory-backend-memfd,id=mem,size=%dM," \
                        " -numa node,memdev=mem"
43
#define QEMU_CMD_CHR    " -chardev socket,id=%s,path=%s%s"
44
#define QEMU_CMD_NETDEV " -netdev vhost-user,id=net0,chardev=%s,vhostforce"
45
#define QEMU_CMD_NET    " -device virtio-net-pci,netdev=net0"
N
Nikolay Nikolaev 已提交
46 47 48 49 50 51

#define HUGETLBFS_MAGIC       0x958458f6

/*********** FROM hw/virtio/vhost-user.c *************************************/

#define VHOST_MEMORY_MAX_NREGIONS    8
52
#define VHOST_MAX_VIRTQUEUES    0x100
N
Nikolay Nikolaev 已提交
53

54
#define VHOST_USER_F_PROTOCOL_FEATURES 30
55
#define VHOST_USER_PROTOCOL_F_MQ 0
56
#define VHOST_USER_PROTOCOL_F_LOG_SHMFD 1
57
#define VHOST_USER_PROTOCOL_F_CROSS_ENDIAN   6
58 59

#define VHOST_LOG_PAGE 0x1000
60

N
Nikolay Nikolaev 已提交
61 62 63 64 65
typedef enum VhostUserRequest {
    VHOST_USER_NONE = 0,
    VHOST_USER_GET_FEATURES = 1,
    VHOST_USER_SET_FEATURES = 2,
    VHOST_USER_SET_OWNER = 3,
66
    VHOST_USER_RESET_OWNER = 4,
N
Nikolay Nikolaev 已提交
67 68 69 70 71 72 73 74 75 76
    VHOST_USER_SET_MEM_TABLE = 5,
    VHOST_USER_SET_LOG_BASE = 6,
    VHOST_USER_SET_LOG_FD = 7,
    VHOST_USER_SET_VRING_NUM = 8,
    VHOST_USER_SET_VRING_ADDR = 9,
    VHOST_USER_SET_VRING_BASE = 10,
    VHOST_USER_GET_VRING_BASE = 11,
    VHOST_USER_SET_VRING_KICK = 12,
    VHOST_USER_SET_VRING_CALL = 13,
    VHOST_USER_SET_VRING_ERR = 14,
77 78
    VHOST_USER_GET_PROTOCOL_FEATURES = 15,
    VHOST_USER_SET_PROTOCOL_FEATURES = 16,
79
    VHOST_USER_GET_QUEUE_NUM = 17,
80
    VHOST_USER_SET_VRING_ENABLE = 18,
N
Nikolay Nikolaev 已提交
81 82 83 84 85 86 87
    VHOST_USER_MAX
} VhostUserRequest;

typedef struct VhostUserMemoryRegion {
    uint64_t guest_phys_addr;
    uint64_t memory_size;
    uint64_t userspace_addr;
88
    uint64_t mmap_offset;
N
Nikolay Nikolaev 已提交
89 90 91 92 93 94 95 96
} VhostUserMemoryRegion;

typedef struct VhostUserMemory {
    uint32_t nregions;
    uint32_t padding;
    VhostUserMemoryRegion regions[VHOST_MEMORY_MAX_NREGIONS];
} VhostUserMemory;

97 98 99 100 101
typedef struct VhostUserLog {
    uint64_t mmap_size;
    uint64_t mmap_offset;
} VhostUserLog;

N
Nikolay Nikolaev 已提交
102 103 104 105 106 107 108 109
typedef struct VhostUserMsg {
    VhostUserRequest request;

#define VHOST_USER_VERSION_MASK     (0x3)
#define VHOST_USER_REPLY_MASK       (0x1<<2)
    uint32_t flags;
    uint32_t size; /* the following payload size */
    union {
110 111
#define VHOST_USER_VRING_IDX_MASK   (0xff)
#define VHOST_USER_VRING_NOFD_MASK  (0x1<<8)
N
Nikolay Nikolaev 已提交
112 113 114 115
        uint64_t u64;
        struct vhost_vring_state state;
        struct vhost_vring_addr addr;
        VhostUserMemory memory;
116
        VhostUserLog log;
117
    } payload;
N
Nikolay Nikolaev 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130
} QEMU_PACKED VhostUserMsg;

static VhostUserMsg m __attribute__ ((unused));
#define VHOST_USER_HDR_SIZE (sizeof(m.request) \
                            + sizeof(m.flags) \
                            + sizeof(m.size))

#define VHOST_USER_PAYLOAD_SIZE (sizeof(m) - VHOST_USER_HDR_SIZE)

/* The version of the protocol we support */
#define VHOST_USER_VERSION    (0x1)
/*****************************************************************************/

131 132 133 134 135 136 137
enum {
    TEST_FLAGS_OK,
    TEST_FLAGS_DISCONNECT,
    TEST_FLAGS_BAD,
    TEST_FLAGS_END,
};

138
typedef struct TestServer {
139
    QPCIBus *bus;
140 141
    QVirtioPCIDevice *dev;
    QVirtQueue *vq[VHOST_MAX_VIRTQUEUES];
142
    gchar *socket_path;
143
    gchar *mig_path;
144
    gchar *chr_name;
145
    CharBackend chr;
146 147 148
    int fds_num;
    int fds[VHOST_MEMORY_MAX_NREGIONS];
    VhostUserMemory memory;
149 150
    GMutex data_mutex;
    GCond data_cond;
151
    int log_fd;
152
    uint64_t rings;
153
    bool test_fail;
154
    int test_flags;
155
    int queues;
156
    QGuestAllocator *alloc;
157
} TestServer;
158

159 160 161 162
static TestServer *test_server_new(const gchar *name);
static void test_server_free(TestServer *server);
static void test_server_listen(TestServer *server);

163 164 165
static const char *tmpfs;
static const char *root;

166 167 168 169 170 171 172 173 174 175
enum test_memfd {
    TEST_MEMFD_AUTO,
    TEST_MEMFD_YES,
    TEST_MEMFD_NO,
};

static char *get_qemu_cmd(TestServer *s,
                          int mem, enum test_memfd memfd, const char *mem_path,
                          const char *chr_opts, const char *extra)
{
176
    if (memfd == TEST_MEMFD_AUTO && qemu_memfd_check(0)) {
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
        memfd = TEST_MEMFD_YES;
    }

    if (memfd == TEST_MEMFD_YES) {
        return g_strdup_printf(QEMU_CMD_MEMFD QEMU_CMD_CHR
                               QEMU_CMD_NETDEV QEMU_CMD_NET "%s", mem, mem,
                               s->chr_name, s->socket_path,
                               chr_opts, s->chr_name, extra);
    } else {
        return g_strdup_printf(QEMU_CMD_MEM QEMU_CMD_CHR
                               QEMU_CMD_NETDEV QEMU_CMD_NET "%s", mem, mem,
                               mem_path, s->chr_name, s->socket_path,
                               chr_opts, s->chr_name, extra);
    }
}

193
static void init_virtio_dev(QTestState *qts, TestServer *s, uint32_t features_mask)
194 195
{
    uint32_t features;
196
    int i;
197

198
    s->bus = qpci_init_pc(qts, NULL);
199
    g_assert_nonnull(s->bus);
200

201 202
    s->dev = qvirtio_pci_device_find(s->bus, VIRTIO_ID_NET);
    g_assert_nonnull(s->dev);
203

204 205 206 207
    qvirtio_pci_device_enable(s->dev);
    qvirtio_reset(&s->dev->vdev);
    qvirtio_set_acknowledge(&s->dev->vdev);
    qvirtio_set_driver(&s->dev->vdev);
208

209
    s->alloc = pc_alloc_init(qts);
210 211 212 213 214 215

    for (i = 0; i < s->queues * 2; i++) {
        s->vq[i] = qvirtqueue_setup(&s->dev->vdev, s->alloc, i);
    }

    features = qvirtio_get_features(&s->dev->vdev);
216
    features = features & features_mask;
217 218 219 220 221 222 223 224
    qvirtio_set_features(&s->dev->vdev, features);

    qvirtio_set_driver_ok(&s->dev->vdev);
}

static void uninit_virtio_dev(TestServer *s)
{
    int i;
225

226 227 228 229 230 231
    for (i = 0; i < s->queues * 2; i++) {
        qvirtqueue_cleanup(s->dev->vdev.bus, s->vq[i], s->alloc);
    }
    pc_alloc_uninit(s->alloc);

    qvirtio_pci_device_free(s->dev);
232 233
}

234
static bool wait_for_fds(TestServer *s)
N
Nikolay Nikolaev 已提交
235 236
{
    gint64 end_time;
237 238
    bool got_region;
    int i;
N
Nikolay Nikolaev 已提交
239

240
    g_mutex_lock(&s->data_mutex);
N
Nikolay Nikolaev 已提交
241

242
    end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
243 244
    while (!s->fds_num) {
        if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
N
Nikolay Nikolaev 已提交
245
            /* timeout has passed */
246
            g_assert(s->fds_num);
N
Nikolay Nikolaev 已提交
247 248 249 250 251
            break;
        }
    }

    /* check for sanity */
252 253
    g_assert_cmpint(s->fds_num, >, 0);
    g_assert_cmpint(s->fds_num, ==, s->memory.nregions);
N
Nikolay Nikolaev 已提交
254

255
    g_mutex_unlock(&s->data_mutex);
256 257 258 259 260 261 262 263 264 265 266 267 268

    got_region = false;
    for (i = 0; i < s->memory.nregions; ++i) {
        VhostUserMemoryRegion *reg = &s->memory.regions[i];
        if (reg->guest_phys_addr == 0) {
            got_region = true;
            break;
        }
    }
    if (!got_region) {
        g_test_skip("No memory at address 0x0");
    }
    return got_region;
269 270
}

271
static void read_guest_mem_server(QTestState *qts, TestServer *s)
272
{
273
    uint8_t *guest_mem;
274 275 276
    int i, j;
    size_t size;

277
    g_mutex_lock(&s->data_mutex);
278

N
Nikolay Nikolaev 已提交
279
    /* iterate all regions */
280
    for (i = 0; i < s->fds_num; i++) {
N
Nikolay Nikolaev 已提交
281 282

        /* We'll check only the region statring at 0x0*/
283
        if (s->memory.regions[i].guest_phys_addr != 0x0) {
N
Nikolay Nikolaev 已提交
284 285 286
            continue;
        }

287
        g_assert_cmpint(s->memory.regions[i].memory_size, >, 1024);
N
Nikolay Nikolaev 已提交
288

289 290
        size = s->memory.regions[i].memory_size +
            s->memory.regions[i].mmap_offset;
291 292

        guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,
293
                         MAP_SHARED, s->fds[i], 0);
294 295

        g_assert(guest_mem != MAP_FAILED);
296
        guest_mem += (s->memory.regions[i].mmap_offset / sizeof(*guest_mem));
N
Nikolay Nikolaev 已提交
297

298
        for (j = 0; j < 1024; j++) {
299
            uint32_t a = qtest_readb(qts, s->memory.regions[i].guest_phys_addr + j);
N
Nikolay Nikolaev 已提交
300 301 302 303 304
            uint32_t b = guest_mem[j];

            g_assert_cmpint(a, ==, b);
        }

305
        munmap(guest_mem, s->memory.regions[i].memory_size);
N
Nikolay Nikolaev 已提交
306 307
    }

308
    g_mutex_unlock(&s->data_mutex);
N
Nikolay Nikolaev 已提交
309 310 311 312
}

static void *thread_function(void *data)
{
313
    GMainLoop *loop = data;
N
Nikolay Nikolaev 已提交
314 315 316 317 318 319 320 321 322 323 324
    g_main_loop_run(loop);
    return NULL;
}

static int chr_can_read(void *opaque)
{
    return VHOST_USER_HDR_SIZE;
}

static void chr_read(void *opaque, const uint8_t *buf, int size)
{
325
    TestServer *s = opaque;
326
    CharBackend *chr = &s->chr;
N
Nikolay Nikolaev 已提交
327 328
    VhostUserMsg msg;
    uint8_t *p = (uint8_t *) &msg;
329
    int fd = -1;
N
Nikolay Nikolaev 已提交
330

331
    if (s->test_fail) {
332
        qemu_chr_fe_disconnect(chr);
333 334 335 336
        /* now switch to non-failure */
        s->test_fail = false;
    }

N
Nikolay Nikolaev 已提交
337 338 339 340 341
    if (size != VHOST_USER_HDR_SIZE) {
        g_test_message("Wrong message size received %d\n", size);
        return;
    }

342
    g_mutex_lock(&s->data_mutex);
N
Nikolay Nikolaev 已提交
343 344 345 346
    memcpy(p, buf, VHOST_USER_HDR_SIZE);

    if (msg.size) {
        p += VHOST_USER_HDR_SIZE;
347
        size = qemu_chr_fe_read_all(chr, p, msg.size);
348 349 350 351 352
        if (size != msg.size) {
            g_test_message("Wrong message size received %d != %d\n",
                           size, msg.size);
            return;
        }
N
Nikolay Nikolaev 已提交
353 354 355 356
    }

    switch (msg.request) {
    case VHOST_USER_GET_FEATURES:
357 358
        /* send back features to qemu */
        msg.flags |= VHOST_USER_REPLY_MASK;
359 360
        msg.size = sizeof(m.payload.u64);
        msg.payload.u64 = 0x1ULL << VHOST_F_LOG_ALL |
361
            0x1ULL << VHOST_USER_F_PROTOCOL_FEATURES;
362 363 364
        if (s->queues > 1) {
            msg.payload.u64 |= 0x1ULL << VIRTIO_NET_F_MQ;
        }
365 366 367 368
        if (s->test_flags >= TEST_FLAGS_BAD) {
            msg.payload.u64 = 0;
            s->test_flags = TEST_FLAGS_END;
        }
369
        p = (uint8_t *) &msg;
370
        qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
371 372 373
        break;

    case VHOST_USER_SET_FEATURES:
374 375
        g_assert_cmpint(msg.payload.u64 & (0x1ULL << VHOST_USER_F_PROTOCOL_FEATURES),
                        !=, 0ULL);
376
        if (s->test_flags == TEST_FLAGS_DISCONNECT) {
377
            qemu_chr_fe_disconnect(chr);
378 379
            s->test_flags = TEST_FLAGS_BAD;
        }
380 381 382
        break;

    case VHOST_USER_GET_PROTOCOL_FEATURES:
N
Nikolay Nikolaev 已提交
383 384
        /* send back features to qemu */
        msg.flags |= VHOST_USER_REPLY_MASK;
385 386
        msg.size = sizeof(m.payload.u64);
        msg.payload.u64 = 1 << VHOST_USER_PROTOCOL_F_LOG_SHMFD;
387
        msg.payload.u64 |= 1 << VHOST_USER_PROTOCOL_F_CROSS_ENDIAN;
388 389 390
        if (s->queues > 1) {
            msg.payload.u64 |= 1 << VHOST_USER_PROTOCOL_F_MQ;
        }
N
Nikolay Nikolaev 已提交
391
        p = (uint8_t *) &msg;
392
        qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
N
Nikolay Nikolaev 已提交
393 394 395 396 397
        break;

    case VHOST_USER_GET_VRING_BASE:
        /* send back vring base to qemu */
        msg.flags |= VHOST_USER_REPLY_MASK;
398 399
        msg.size = sizeof(m.payload.state);
        msg.payload.state.num = 0;
N
Nikolay Nikolaev 已提交
400
        p = (uint8_t *) &msg;
401
        qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
402

403
        assert(msg.payload.state.index < s->queues * 2);
404
        s->rings &= ~(0x1ULL << msg.payload.state.index);
405
        g_cond_broadcast(&s->data_cond);
N
Nikolay Nikolaev 已提交
406 407 408 409
        break;

    case VHOST_USER_SET_MEM_TABLE:
        /* received the mem table */
410
        memcpy(&s->memory, &msg.payload.memory, sizeof(msg.payload.memory));
411
        s->fds_num = qemu_chr_fe_get_msgfds(chr, s->fds,
412
                                            G_N_ELEMENTS(s->fds));
N
Nikolay Nikolaev 已提交
413 414

        /* signal the test that it can continue */
415
        g_cond_broadcast(&s->data_cond);
N
Nikolay Nikolaev 已提交
416 417 418 419 420
        break;

    case VHOST_USER_SET_VRING_KICK:
    case VHOST_USER_SET_VRING_CALL:
        /* consume the fd */
421
        qemu_chr_fe_get_msgfds(chr, &fd, 1);
N
Nikolay Nikolaev 已提交
422 423 424 425 426 427 428
        /*
         * This is a non-blocking eventfd.
         * The receive function forces it to be blocking,
         * so revert it back to non-blocking.
         */
        qemu_set_nonblock(fd);
        break;
429 430 431 432 433 434

    case VHOST_USER_SET_LOG_BASE:
        if (s->log_fd != -1) {
            close(s->log_fd);
            s->log_fd = -1;
        }
435
        qemu_chr_fe_get_msgfds(chr, &s->log_fd, 1);
436 437 438
        msg.flags |= VHOST_USER_REPLY_MASK;
        msg.size = 0;
        p = (uint8_t *) &msg;
439
        qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE);
440

441
        g_cond_broadcast(&s->data_cond);
442 443
        break;

444
    case VHOST_USER_SET_VRING_BASE:
445
        assert(msg.payload.state.index < s->queues * 2);
446
        s->rings |= 0x1ULL << msg.payload.state.index;
447
        g_cond_broadcast(&s->data_cond);
448 449
        break;

450 451 452 453 454
    case VHOST_USER_GET_QUEUE_NUM:
        msg.flags |= VHOST_USER_REPLY_MASK;
        msg.size = sizeof(m.payload.u64);
        msg.payload.u64 = s->queues;
        p = (uint8_t *) &msg;
455
        qemu_chr_fe_write_all(chr, p, VHOST_USER_HDR_SIZE + msg.size);
456 457
        break;

N
Nikolay Nikolaev 已提交
458 459 460
    default:
        break;
    }
461 462

    g_mutex_unlock(&s->data_mutex);
N
Nikolay Nikolaev 已提交
463 464
}

465
#ifdef CONFIG_LINUX
466
static const char *init_hugepagefs(const char *path)
N
Nikolay Nikolaev 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
{
    struct statfs fs;
    int ret;

    if (access(path, R_OK | W_OK | X_OK)) {
        g_test_message("access on path (%s): %s\n", path, strerror(errno));
        return NULL;
    }

    do {
        ret = statfs(path, &fs);
    } while (ret != 0 && errno == EINTR);

    if (ret != 0) {
        g_test_message("statfs on path (%s): %s\n", path, strerror(errno));
        return NULL;
    }

    if (fs.f_type != HUGETLBFS_MAGIC) {
        g_test_message("Warning: path not on HugeTLBFS: %s\n", path);
        return NULL;
    }

    return path;
}
492
#endif
N
Nikolay Nikolaev 已提交
493

494
static TestServer *test_server_new(const gchar *name)
495 496 497 498
{
    TestServer *server = g_new0(TestServer, 1);

    server->socket_path = g_strdup_printf("%s/%s.sock", tmpfs, name);
499
    server->mig_path = g_strdup_printf("%s/%s.mig", tmpfs, name);
500 501 502 503 504
    server->chr_name = g_strdup_printf("chr-%s", name);

    g_mutex_init(&server->data_mutex);
    g_cond_init(&server->data_cond);

505
    server->log_fd = -1;
506
    server->queues = 1;
507

508 509 510
    return server;
}

511 512 513 514 515 516 517 518 519 520
static void chr_event(void *opaque, int event)
{
    TestServer *s = opaque;

    if (s->test_flags == TEST_FLAGS_END &&
        event == CHR_EVENT_CLOSED) {
        s->test_flags = TEST_FLAGS_OK;
    }
}

521 522 523
static void test_server_create_chr(TestServer *server, const gchar *opt)
{
    gchar *chr_path;
524
    Chardev *chr;
525

526
    chr_path = g_strdup_printf("unix:%s%s", server->socket_path, opt);
527
    chr = qemu_chr_new(server->chr_name, chr_path, NULL);
528 529
    g_free(chr_path);

530
    g_assert_nonnull(chr);
531 532
    qemu_chr_fe_init(&server->chr, chr, &error_abort);
    qemu_chr_fe_set_handlers(&server->chr, chr_can_read, chr_read,
533
                             chr_event, NULL, server, NULL, true);
534 535 536 537 538 539 540
}

static void test_server_listen(TestServer *server)
{
    test_server_create_chr(server, ",server,nowait");
}

541
static gboolean _test_server_free(TestServer *server)
542 543 544
{
    int i;

545
    qemu_chr_fe_deinit(&server->chr, true);
546 547 548 549 550

    for (i = 0; i < server->fds_num; i++) {
        close(server->fds[i]);
    }

551 552 553 554
    if (server->log_fd != -1) {
        close(server->log_fd);
    }

555 556 557
    unlink(server->socket_path);
    g_free(server->socket_path);

558 559 560
    unlink(server->mig_path);
    g_free(server->mig_path);

561
    g_free(server->chr_name);
562
    g_assert(server->bus);
563 564
    qpci_free_pc(server->bus);

565
    g_free(server);
566 567 568 569 570 571 572

    return FALSE;
}

static void test_server_free(TestServer *server)
{
    g_idle_add((GSourceFunc)_test_server_free, server);
573 574
}

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
static void wait_for_log_fd(TestServer *s)
{
    gint64 end_time;

    g_mutex_lock(&s->data_mutex);
    end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
    while (s->log_fd == -1) {
        if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
            /* timeout has passed */
            g_assert(s->log_fd != -1);
            break;
        }
    }

    g_mutex_unlock(&s->data_mutex);
}

592
static void write_guest_mem(TestServer *s, uint32_t seed)
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
{
    uint32_t *guest_mem;
    int i, j;
    size_t size;

    /* iterate all regions */
    for (i = 0; i < s->fds_num; i++) {

        /* We'll write only the region statring at 0x0 */
        if (s->memory.regions[i].guest_phys_addr != 0x0) {
            continue;
        }

        g_assert_cmpint(s->memory.regions[i].memory_size, >, 1024);

        size = s->memory.regions[i].memory_size +
            s->memory.regions[i].mmap_offset;

        guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,
                         MAP_SHARED, s->fds[i], 0);

        g_assert(guest_mem != MAP_FAILED);
        guest_mem += (s->memory.regions[i].mmap_offset / sizeof(*guest_mem));

        for (j = 0; j < 256; j++) {
            guest_mem[j] = seed + j;
        }

        munmap(guest_mem, s->memory.regions[i].memory_size);
        break;
    }
}

static guint64 get_log_size(TestServer *s)
{
    guint64 log_size = 0;
    int i;

    for (i = 0; i < s->memory.nregions; ++i) {
        VhostUserMemoryRegion *reg = &s->memory.regions[i];
        guint64 last = range_get_last(reg->guest_phys_addr,
                                       reg->memory_size);
        log_size = MAX(log_size, last / (8 * VHOST_LOG_PAGE) + 1);
    }

    return log_size;
}

641 642 643 644 645 646 647 648 649 650
typedef struct TestMigrateSource {
    GSource source;
    TestServer *src;
    TestServer *dest;
} TestMigrateSource;

static gboolean
test_migrate_source_check(GSource *source)
{
    TestMigrateSource *t = (TestMigrateSource *)source;
651
    gboolean overlap = t->src->rings && t->dest->rings;
652 653 654 655 656 657 658

    g_assert(!overlap);

    return FALSE;
}

GSourceFuncs test_migrate_source_funcs = {
659
    .check = test_migrate_source_check,
660 661
};

662
static void test_read_guest_mem(const void *arg)
663
{
664
    enum test_memfd memfd = GPOINTER_TO_INT(arg);
665 666 667 668
    TestServer *server = NULL;
    char *qemu_cmd = NULL;
    QTestState *s = NULL;

669 670
    server = test_server_new(memfd == TEST_MEMFD_YES ?
                             "read-guest-memfd" : "read-guest-mem");
671 672
    test_server_listen(server);

673
    qemu_cmd = get_qemu_cmd(server, 512, memfd, root, "", "");
674 675 676 677

    s = qtest_start(qemu_cmd);
    g_free(qemu_cmd);

678
    init_virtio_dev(global_qtest, server, 1u << VIRTIO_NET_F_MAC);
679

680 681 682 683
    if (!wait_for_fds(server)) {
        goto exit;
    }

684
    read_guest_mem_server(global_qtest, server);
685

686
exit:
687 688
    uninit_virtio_dev(server);

689 690 691 692
    qtest_quit(s);
    test_server_free(server);
}

693 694 695 696
static void test_migrate(void)
{
    TestServer *s = test_server_new("src");
    TestServer *dest = test_server_new("dest");
697
    char *uri = g_strdup_printf("%s%s", "unix:", dest->mig_path);
698
    QTestState *from, *to;
699
    GSource *source;
700
    gchar *cmd, *tmp;
701 702 703 704
    QDict *rsp;
    guint8 *log;
    guint64 size;

705 706 707
    test_server_listen(s);
    test_server_listen(dest);

708
    cmd = get_qemu_cmd(s, 2, TEST_MEMFD_AUTO, root, "", "");
709 710 711
    from = qtest_start(cmd);
    g_free(cmd);

712
    init_virtio_dev(from, s, 1u << VIRTIO_NET_F_MAC);
713 714 715 716
    if (!wait_for_fds(s)) {
        goto exit;
    }

717 718 719
    size = get_log_size(s);
    g_assert_cmpint(size, ==, (2 * 1024 * 1024) / (VHOST_LOG_PAGE * 8));

720 721 722
    tmp = g_strdup_printf(" -incoming %s", uri);
    cmd = get_qemu_cmd(dest, 2, TEST_MEMFD_AUTO, root, "", tmp);
    g_free(tmp);
723 724
    to = qtest_init(cmd);
    g_free(cmd);
725
    init_virtio_dev(to, dest, 1u << VIRTIO_NET_F_MAC);
726

727 728 729 730 731 732
    source = g_source_new(&test_migrate_source_funcs,
                          sizeof(TestMigrateSource));
    ((TestMigrateSource *)source)->src = s;
    ((TestMigrateSource *)source)->dest = dest;
    g_source_attach(source, NULL);

733 734 735 736 737
    /* slow down migration to have time to fiddle with log */
    /* TODO: qtest could learn to break on some places */
    rsp = qmp("{ 'execute': 'migrate_set_speed',"
              "'arguments': { 'value': 10 } }");
    g_assert(qdict_haskey(rsp, "return"));
738
    qobject_unref(rsp);
739

740
    rsp = qmp("{ 'execute': 'migrate', 'arguments': { 'uri': %s } }", uri);
741
    g_assert(qdict_haskey(rsp, "return"));
742
    qobject_unref(rsp);
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

    wait_for_log_fd(s);

    log = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, s->log_fd, 0);
    g_assert(log != MAP_FAILED);

    /* modify first page */
    write_guest_mem(s, 0x42);
    log[0] = 1;
    munmap(log, size);

    /* speed things up */
    rsp = qmp("{ 'execute': 'migrate_set_speed',"
              "'arguments': { 'value': 0 } }");
    g_assert(qdict_haskey(rsp, "return"));
758
    qobject_unref(rsp);
759 760

    qmp_eventwait("STOP");
761
    qtest_qmp_eventwait(to, "RESUME");
762

763 764
    g_assert(wait_for_fds(dest));
    read_guest_mem_server(to, dest);
765

766
    uninit_virtio_dev(dest);
767
    qtest_quit(to);
768

769 770 771
    g_source_destroy(source);
    g_source_unref(source);

772 773 774
exit:
    uninit_virtio_dev(s);

775 776 777
    test_server_free(dest);
    qtest_quit(from);
    test_server_free(s);
778
    g_free(uri);
779 780
}

781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
static void wait_for_rings_started(TestServer *s, size_t count)
{
    gint64 end_time;

    g_mutex_lock(&s->data_mutex);
    end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;
    while (ctpop64(s->rings) != count) {
        if (!g_cond_wait_until(&s->data_cond, &s->data_mutex, end_time)) {
            /* timeout has passed */
            g_assert_cmpint(ctpop64(s->rings), ==, count);
            break;
        }
    }

    g_mutex_unlock(&s->data_mutex);
}

798 799 800 801 802
static inline void test_server_connect(TestServer *server)
{
    test_server_create_chr(server, ",reconnect=1");
}

803 804 805 806 807
static gboolean
reconnect_cb(gpointer user_data)
{
    TestServer *s = user_data;

808
    qemu_chr_fe_disconnect(&s->chr);
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830

    return FALSE;
}

static gpointer
connect_thread(gpointer data)
{
    TestServer *s = data;

    /* wait for qemu to start before first try, to avoid extra warnings */
    g_usleep(G_USEC_PER_SEC);
    test_server_connect(s);

    return NULL;
}

static void test_reconnect_subprocess(void)
{
    TestServer *s = test_server_new("reconnect");
    char *cmd;

    g_thread_new("connect", connect_thread, s);
831
    cmd = get_qemu_cmd(s, 2, TEST_MEMFD_AUTO, root, ",server", "");
832 833 834
    qtest_start(cmd);
    g_free(cmd);

835
    init_virtio_dev(global_qtest, s, 1u << VIRTIO_NET_F_MAC);
836 837 838 839
    if (!wait_for_fds(s)) {
        goto exit;
    }

840 841 842 843 844 845
    wait_for_rings_started(s, 2);

    /* reconnect */
    s->fds_num = 0;
    s->rings = 0;
    g_idle_add(reconnect_cb, s);
846
    g_assert(wait_for_fds(s));
847 848
    wait_for_rings_started(s, 2);

849
exit:
850 851
    uninit_virtio_dev(s);

852 853 854 855 856 857 858 859 860 861 862
    qtest_end();
    test_server_free(s);
    return;
}

static void test_reconnect(void)
{
    gchar *path = g_strdup_printf("/%s/vhost-user/reconnect/subprocess",
                                  qtest_get_arch());
    g_test_trap_subprocess(path, 0, 0);
    g_test_trap_assert_passed();
863
    g_free(path);
864
}
865 866 867 868 869 870 871 872

static void test_connect_fail_subprocess(void)
{
    TestServer *s = test_server_new("connect-fail");
    char *cmd;

    s->test_fail = true;
    g_thread_new("connect", connect_thread, s);
873
    cmd = get_qemu_cmd(s, 2, TEST_MEMFD_AUTO, root, ",server", "");
874 875 876
    qtest_start(cmd);
    g_free(cmd);

877
    init_virtio_dev(global_qtest, s, 1u << VIRTIO_NET_F_MAC);
878 879 880
    if (!wait_for_fds(s)) {
        goto exit;
    }
881 882
    wait_for_rings_started(s, 2);

883
exit:
884 885
    uninit_virtio_dev(s);

886 887 888 889 890 891 892 893 894 895 896 897 898
    qtest_end();
    test_server_free(s);
}

static void test_connect_fail(void)
{
    gchar *path = g_strdup_printf("/%s/vhost-user/connect-fail/subprocess",
                                  qtest_get_arch());
    g_test_trap_subprocess(path, 0, 0);
    g_test_trap_assert_passed();
    g_free(path);
}

899 900 901 902 903 904 905
static void test_flags_mismatch_subprocess(void)
{
    TestServer *s = test_server_new("flags-mismatch");
    char *cmd;

    s->test_flags = TEST_FLAGS_DISCONNECT;
    g_thread_new("connect", connect_thread, s);
906
    cmd = get_qemu_cmd(s, 2, TEST_MEMFD_AUTO, root, ",server", "");
907 908 909
    qtest_start(cmd);
    g_free(cmd);

910
    init_virtio_dev(global_qtest, s, 1u << VIRTIO_NET_F_MAC);
911 912 913
    if (!wait_for_fds(s)) {
        goto exit;
    }
914 915
    wait_for_rings_started(s, 2);

916
exit:
917 918
    uninit_virtio_dev(s);

919 920 921 922 923 924 925 926 927 928 929 930 931
    qtest_end();
    test_server_free(s);
}

static void test_flags_mismatch(void)
{
    gchar *path = g_strdup_printf("/%s/vhost-user/flags-mismatch/subprocess",
                                  qtest_get_arch());
    g_test_trap_subprocess(path, 0, 0);
    g_test_trap_assert_passed();
    g_free(path);
}

932

933 934 935 936
static void test_multiqueue(void)
{
    TestServer *s = test_server_new("mq");
    char *cmd;
937 938 939 940
    uint32_t features_mask = ~(QVIRTIO_F_BAD_FEATURE |
                            (1u << VIRTIO_RING_F_INDIRECT_DESC) |
                            (1u << VIRTIO_RING_F_EVENT_IDX));
    s->queues = 2;
941 942
    test_server_listen(s);

943
    if (qemu_memfd_check(0)) {
944 945 946 947 948 949 950 951 952 953 954 955 956 957
        cmd = g_strdup_printf(
            QEMU_CMD_MEMFD QEMU_CMD_CHR QEMU_CMD_NETDEV ",queues=%d "
            "-device virtio-net-pci,netdev=net0,mq=on,vectors=%d",
            512, 512, s->chr_name,
            s->socket_path, "", s->chr_name,
            s->queues, s->queues * 2 + 2);
    } else {
        cmd = g_strdup_printf(
            QEMU_CMD_MEM QEMU_CMD_CHR QEMU_CMD_NETDEV ",queues=%d "
            "-device virtio-net-pci,netdev=net0,mq=on,vectors=%d",
            512, 512, root, s->chr_name,
            s->socket_path, "", s->chr_name,
            s->queues, s->queues * 2 + 2);
    }
958 959 960
    qtest_start(cmd);
    g_free(cmd);

961
    init_virtio_dev(global_qtest, s, features_mask);
962

963
    wait_for_rings_started(s, s->queues * 2);
964

965
    uninit_virtio_dev(s);
966 967 968 969 970 971

    qtest_end();

    test_server_free(s);
}

N
Nikolay Nikolaev 已提交
972 973
int main(int argc, char **argv)
{
974
    const char *hugefs;
N
Nikolay Nikolaev 已提交
975
    int ret;
976
    char template[] = "/tmp/vhost-test-XXXXXX";
977 978
    GMainLoop *loop;
    GThread *thread;
N
Nikolay Nikolaev 已提交
979 980 981 982

    g_test_init(&argc, &argv, NULL);

    module_call_init(MODULE_INIT_QOM);
983
    qemu_add_opts(&qemu_chardev_opts);
N
Nikolay Nikolaev 已提交
984

985 986
    tmpfs = mkdtemp(template);
    if (!tmpfs) {
987
        g_test_message("mkdtemp on path (%s): %s\n", template, strerror(errno));
988 989 990
    }
    g_assert(tmpfs);

991 992
    root = tmpfs;
#ifdef CONFIG_LINUX
993 994 995 996
    hugefs = getenv("QTEST_HUGETLBFS_PATH");
    if (hugefs) {
        root = init_hugepagefs(hugefs);
        g_assert(root);
N
Nikolay Nikolaev 已提交
997
    }
998
#endif
N
Nikolay Nikolaev 已提交
999

1000
    loop = g_main_loop_new(NULL, FALSE);
N
Nikolay Nikolaev 已提交
1001
    /* run the main loop thread so the chardev may operate */
1002
    thread = g_thread_new(NULL, thread_function, loop);
N
Nikolay Nikolaev 已提交
1003

1004
    if (qemu_memfd_check(0)) {
1005 1006 1007 1008 1009 1010
        qtest_add_data_func("/vhost-user/read-guest-mem/memfd",
                            GINT_TO_POINTER(TEST_MEMFD_YES),
                            test_read_guest_mem);
    }
    qtest_add_data_func("/vhost-user/read-guest-mem/memfile",
                        GINT_TO_POINTER(TEST_MEMFD_NO), test_read_guest_mem);
1011
    qtest_add_func("/vhost-user/migrate", test_migrate);
1012
    qtest_add_func("/vhost-user/multiqueue", test_multiqueue);
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    /* keeps failing on build-system since Aug 15 2017 */
    if (getenv("QTEST_VHOST_USER_FIXME")) {
        qtest_add_func("/vhost-user/reconnect/subprocess",
                       test_reconnect_subprocess);
        qtest_add_func("/vhost-user/reconnect", test_reconnect);
        qtest_add_func("/vhost-user/connect-fail/subprocess",
                       test_connect_fail_subprocess);
        qtest_add_func("/vhost-user/connect-fail", test_connect_fail);
        qtest_add_func("/vhost-user/flags-mismatch/subprocess",
                       test_flags_mismatch_subprocess);
        qtest_add_func("/vhost-user/flags-mismatch", test_flags_mismatch);
    }
N
Nikolay Nikolaev 已提交
1026 1027 1028 1029 1030

    ret = g_test_run();

    /* cleanup */

1031 1032 1033 1034 1035 1036 1037 1038
    /* finish the helper thread and dispatch pending sources */
    g_main_loop_quit(loop);
    g_thread_join(thread);
    while (g_main_context_pending(NULL)) {
        g_main_context_iteration (NULL, TRUE);
    }
    g_main_loop_unref(loop);

1039 1040 1041 1042 1043 1044 1045
    ret = rmdir(tmpfs);
    if (ret != 0) {
        g_test_message("unable to rmdir: path (%s): %s\n",
                       tmpfs, strerror(errno));
    }
    g_assert_cmpint(ret, ==, 0);

N
Nikolay Nikolaev 已提交
1046 1047
    return ret;
}