vhost.c 40.5 KB
Newer Older
M
Michael S. Tsirkin 已提交
1 2 3 4 5 6 7 8 9 10
/*
 * vhost support
 *
 * Copyright Red Hat, Inc. 2010
 *
 * Authors:
 *  Michael S. Tsirkin <mst@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
11 12 13
 *
 * Contributions after 2012-01-13 are licensed under the terms of the
 * GNU GPL, version 2 or (at your option) any later version.
M
Michael S. Tsirkin 已提交
14 15
 */

P
Peter Maydell 已提交
16
#include "qemu/osdep.h"
17
#include "qapi/error.h"
P
Paolo Bonzini 已提交
18
#include "hw/virtio/vhost.h"
M
Michael S. Tsirkin 已提交
19
#include "hw/hw.h"
20
#include "qemu/atomic.h"
21
#include "qemu/range.h"
22
#include "qemu/error-report.h"
M
Marc-André Lureau 已提交
23
#include "qemu/memfd.h"
24
#include <linux/vhost.h>
25
#include "exec/address-spaces.h"
K
KONRAD Frederic 已提交
26
#include "hw/virtio/virtio-bus.h"
27
#include "hw/virtio/virtio-access.h"
28
#include "migration/migration.h"
M
Michael S. Tsirkin 已提交
29

J
Jason Wang 已提交
30
static struct vhost_log *vhost_log;
M
Marc-André Lureau 已提交
31
static struct vhost_log *vhost_log_shm;
J
Jason Wang 已提交
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
static unsigned int used_memslots;
static QLIST_HEAD(, vhost_dev) vhost_devices =
    QLIST_HEAD_INITIALIZER(vhost_devices);

bool vhost_has_free_slot(void)
{
    unsigned int slots_limit = ~0U;
    struct vhost_dev *hdev;

    QLIST_FOREACH(hdev, &vhost_devices, entry) {
        unsigned int r = hdev->vhost_ops->vhost_backend_memslots_limit(hdev);
        slots_limit = MIN(slots_limit, r);
    }
    return slots_limit > used_memslots;
}

M
Michael S. Tsirkin 已提交
49
static void vhost_dev_sync_region(struct vhost_dev *dev,
50
                                  MemoryRegionSection *section,
M
Michael S. Tsirkin 已提交
51 52 53
                                  uint64_t mfirst, uint64_t mlast,
                                  uint64_t rfirst, uint64_t rlast)
{
J
Jason Wang 已提交
54 55
    vhost_log_chunk_t *log = dev->log->log;

M
Michael S. Tsirkin 已提交
56 57
    uint64_t start = MAX(mfirst, rfirst);
    uint64_t end = MIN(mlast, rlast);
J
Jason Wang 已提交
58 59
    vhost_log_chunk_t *from = log + start / VHOST_LOG_CHUNK;
    vhost_log_chunk_t *to = log + end / VHOST_LOG_CHUNK + 1;
M
Michael S. Tsirkin 已提交
60 61 62 63 64
    uint64_t addr = (start / VHOST_LOG_CHUNK) * VHOST_LOG_CHUNK;

    if (end < start) {
        return;
    }
65
    assert(end / VHOST_LOG_CHUNK < dev->log_size);
66
    assert(start / VHOST_LOG_CHUNK < dev->log_size);
67

M
Michael S. Tsirkin 已提交
68 69 70 71 72
    for (;from < to; ++from) {
        vhost_log_chunk_t log;
        /* We first check with non-atomic: much cheaper,
         * and we expect non-dirty to be the common case. */
        if (!*from) {
73
            addr += VHOST_LOG_CHUNK;
M
Michael S. Tsirkin 已提交
74 75
            continue;
        }
76 77 78
        /* Data must be read atomically. We don't really need barrier semantics
         * but it's easier to use atomic_* than roll our own. */
        log = atomic_xchg(from, 0);
N
Natanael Copa 已提交
79 80
        while (log) {
            int bit = ctzl(log);
M
Michael S. Tsirkin 已提交
81 82 83 84 85 86 87
            hwaddr page_addr;
            hwaddr section_offset;
            hwaddr mr_offset;
            page_addr = addr + bit * VHOST_LOG_PAGE;
            section_offset = page_addr - section->offset_within_address_space;
            mr_offset = section_offset + section->offset_within_region;
            memory_region_set_dirty(section->mr, mr_offset, VHOST_LOG_PAGE);
M
Michael S. Tsirkin 已提交
88 89 90 91 92 93
            log &= ~(0x1ull << bit);
        }
        addr += VHOST_LOG_CHUNK;
    }
}

A
Avi Kivity 已提交
94
static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,
95
                                   MemoryRegionSection *section,
M
Michael S. Tsirkin 已提交
96 97
                                   hwaddr first,
                                   hwaddr last)
M
Michael S. Tsirkin 已提交
98 99
{
    int i;
M
Michael S. Tsirkin 已提交
100 101
    hwaddr start_addr;
    hwaddr end_addr;
A
Avi Kivity 已提交
102

M
Michael S. Tsirkin 已提交
103 104 105
    if (!dev->log_enabled || !dev->started) {
        return 0;
    }
M
Michael S. Tsirkin 已提交
106
    start_addr = section->offset_within_address_space;
107
    end_addr = range_get_last(start_addr, int128_get64(section->size));
M
Michael S. Tsirkin 已提交
108 109 110
    start_addr = MAX(first, start_addr);
    end_addr = MIN(last, end_addr);

M
Michael S. Tsirkin 已提交
111 112
    for (i = 0; i < dev->mem->nregions; ++i) {
        struct vhost_memory_region *reg = dev->mem->regions + i;
113
        vhost_dev_sync_region(dev, section, start_addr, end_addr,
M
Michael S. Tsirkin 已提交
114 115 116 117 118 119
                              reg->guest_phys_addr,
                              range_get_last(reg->guest_phys_addr,
                                             reg->memory_size));
    }
    for (i = 0; i < dev->nvqs; ++i) {
        struct vhost_virtqueue *vq = dev->vqs + i;
120
        vhost_dev_sync_region(dev, section, start_addr, end_addr, vq->used_phys,
M
Michael S. Tsirkin 已提交
121 122 123 124 125
                              range_get_last(vq->used_phys, vq->used_size));
    }
    return 0;
}

A
Avi Kivity 已提交
126 127 128 129 130
static void vhost_log_sync(MemoryListener *listener,
                          MemoryRegionSection *section)
{
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);
M
Michael S. Tsirkin 已提交
131 132
    vhost_sync_dirty_bitmap(dev, section, 0x0, ~0x0ULL);
}
A
Avi Kivity 已提交
133

M
Michael S. Tsirkin 已提交
134 135 136 137 138 139 140 141 142
static void vhost_log_sync_range(struct vhost_dev *dev,
                                 hwaddr first, hwaddr last)
{
    int i;
    /* FIXME: this is N^2 in number of sections */
    for (i = 0; i < dev->n_mem_sections; ++i) {
        MemoryRegionSection *section = &dev->mem_sections[i];
        vhost_sync_dirty_bitmap(dev, section, first, last);
    }
A
Avi Kivity 已提交
143 144
}

M
Michael S. Tsirkin 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
/* Assign/unassign. Keep an unsorted array of non-overlapping
 * memory regions in dev->mem. */
static void vhost_dev_unassign_memory(struct vhost_dev *dev,
                                      uint64_t start_addr,
                                      uint64_t size)
{
    int from, to, n = dev->mem->nregions;
    /* Track overlapping/split regions for sanity checking. */
    int overlap_start = 0, overlap_end = 0, overlap_middle = 0, split = 0;

    for (from = 0, to = 0; from < n; ++from, ++to) {
        struct vhost_memory_region *reg = dev->mem->regions + to;
        uint64_t reglast;
        uint64_t memlast;
        uint64_t change;

        /* clone old region */
        if (to != from) {
            memcpy(reg, dev->mem->regions + from, sizeof *reg);
        }

        /* No overlap is simple */
        if (!ranges_overlap(reg->guest_phys_addr, reg->memory_size,
                            start_addr, size)) {
            continue;
        }

        /* Split only happens if supplied region
         * is in the middle of an existing one. Thus it can not
         * overlap with any other existing region. */
        assert(!split);

        reglast = range_get_last(reg->guest_phys_addr, reg->memory_size);
        memlast = range_get_last(start_addr, size);

        /* Remove whole region */
        if (start_addr <= reg->guest_phys_addr && memlast >= reglast) {
            --dev->mem->nregions;
            --to;
            ++overlap_middle;
            continue;
        }

        /* Shrink region */
        if (memlast >= reglast) {
            reg->memory_size = start_addr - reg->guest_phys_addr;
            assert(reg->memory_size);
            assert(!overlap_end);
            ++overlap_end;
            continue;
        }

        /* Shift region */
        if (start_addr <= reg->guest_phys_addr) {
            change = memlast + 1 - reg->guest_phys_addr;
            reg->memory_size -= change;
            reg->guest_phys_addr += change;
            reg->userspace_addr += change;
            assert(reg->memory_size);
            assert(!overlap_start);
            ++overlap_start;
            continue;
        }

        /* This only happens if supplied region
         * is in the middle of an existing one. Thus it can not
         * overlap with any other existing region. */
        assert(!overlap_start);
        assert(!overlap_end);
        assert(!overlap_middle);
        /* Split region: shrink first part, shift second part. */
        memcpy(dev->mem->regions + n, reg, sizeof *reg);
        reg->memory_size = start_addr - reg->guest_phys_addr;
        assert(reg->memory_size);
        change = memlast + 1 - reg->guest_phys_addr;
        reg = dev->mem->regions + n;
        reg->memory_size -= change;
        assert(reg->memory_size);
        reg->guest_phys_addr += change;
        reg->userspace_addr += change;
        /* Never add more than 1 region */
        assert(dev->mem->nregions == n);
        ++dev->mem->nregions;
        ++split;
    }
}

/* Called after unassign, so no regions overlap the given range. */
static void vhost_dev_assign_memory(struct vhost_dev *dev,
                                    uint64_t start_addr,
                                    uint64_t size,
                                    uint64_t uaddr)
{
    int from, to;
    struct vhost_memory_region *merged = NULL;
    for (from = 0, to = 0; from < dev->mem->nregions; ++from, ++to) {
        struct vhost_memory_region *reg = dev->mem->regions + to;
        uint64_t prlast, urlast;
        uint64_t pmlast, umlast;
        uint64_t s, e, u;

        /* clone old region */
        if (to != from) {
            memcpy(reg, dev->mem->regions + from, sizeof *reg);
        }
        prlast = range_get_last(reg->guest_phys_addr, reg->memory_size);
        pmlast = range_get_last(start_addr, size);
        urlast = range_get_last(reg->userspace_addr, reg->memory_size);
        umlast = range_get_last(uaddr, size);

        /* check for overlapping regions: should never happen. */
        assert(prlast < start_addr || pmlast < reg->guest_phys_addr);
        /* Not an adjacent or overlapping region - do not merge. */
        if ((prlast + 1 != start_addr || urlast + 1 != uaddr) &&
            (pmlast + 1 != reg->guest_phys_addr ||
             umlast + 1 != reg->userspace_addr)) {
            continue;
        }

264 265 266 267 268 269 270
        if (dev->vhost_ops->vhost_backend_can_merge &&
            !dev->vhost_ops->vhost_backend_can_merge(dev, uaddr, size,
                                                     reg->userspace_addr,
                                                     reg->memory_size)) {
            continue;
        }

M
Michael S. Tsirkin 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        if (merged) {
            --to;
            assert(to >= 0);
        } else {
            merged = reg;
        }
        u = MIN(uaddr, reg->userspace_addr);
        s = MIN(start_addr, reg->guest_phys_addr);
        e = MAX(pmlast, prlast);
        uaddr = merged->userspace_addr = u;
        start_addr = merged->guest_phys_addr = s;
        size = merged->memory_size = e - s + 1;
        assert(merged->memory_size);
    }

    if (!merged) {
        struct vhost_memory_region *reg = dev->mem->regions + to;
        memset(reg, 0, sizeof *reg);
        reg->memory_size = size;
        assert(reg->memory_size);
        reg->guest_phys_addr = start_addr;
        reg->userspace_addr = uaddr;
        ++to;
    }
    assert(to <= dev->mem->nregions + 1);
    dev->mem->nregions = to;
}

static uint64_t vhost_get_log_size(struct vhost_dev *dev)
{
    uint64_t log_size = 0;
    int i;
    for (i = 0; i < dev->mem->nregions; ++i) {
        struct vhost_memory_region *reg = dev->mem->regions + i;
        uint64_t last = range_get_last(reg->guest_phys_addr,
                                       reg->memory_size);
        log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
    }
    for (i = 0; i < dev->nvqs; ++i) {
        struct vhost_virtqueue *vq = dev->vqs + i;
        uint64_t last = vq->used_phys + vq->used_size - 1;
        log_size = MAX(log_size, last / VHOST_LOG_CHUNK + 1);
    }
    return log_size;
}
M
Marc-André Lureau 已提交
316 317

static struct vhost_log *vhost_log_alloc(uint64_t size, bool share)
J
Jason Wang 已提交
318
{
M
Marc-André Lureau 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331
    struct vhost_log *log;
    uint64_t logsize = size * sizeof(*(log->log));
    int fd = -1;

    log = g_new0(struct vhost_log, 1);
    if (share) {
        log->log = qemu_memfd_alloc("vhost-log", logsize,
                                    F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL,
                                    &fd);
        memset(log->log, 0, logsize);
    } else {
        log->log = g_malloc0(logsize);
    }
J
Jason Wang 已提交
332 333 334

    log->size = size;
    log->refcnt = 1;
M
Marc-André Lureau 已提交
335
    log->fd = fd;
J
Jason Wang 已提交
336 337 338 339

    return log;
}

M
Marc-André Lureau 已提交
340
static struct vhost_log *vhost_log_get(uint64_t size, bool share)
J
Jason Wang 已提交
341
{
M
Marc-André Lureau 已提交
342 343 344 345 346 347 348 349 350
    struct vhost_log *log = share ? vhost_log_shm : vhost_log;

    if (!log || log->size != size) {
        log = vhost_log_alloc(size, share);
        if (share) {
            vhost_log_shm = log;
        } else {
            vhost_log = log;
        }
J
Jason Wang 已提交
351
    } else {
M
Marc-André Lureau 已提交
352
        ++log->refcnt;
J
Jason Wang 已提交
353 354
    }

M
Marc-André Lureau 已提交
355
    return log;
J
Jason Wang 已提交
356 357 358 359 360 361 362 363 364
}

static void vhost_log_put(struct vhost_dev *dev, bool sync)
{
    struct vhost_log *log = dev->log;

    if (!log) {
        return;
    }
365 366
    dev->log = NULL;
    dev->log_size = 0;
J
Jason Wang 已提交
367 368 369 370 371 372 373

    --log->refcnt;
    if (log->refcnt == 0) {
        /* Sync only the range covered by the old log */
        if (dev->log_size && sync) {
            vhost_log_sync_range(dev, 0, dev->log_size * VHOST_LOG_CHUNK - 1);
        }
M
Marc-André Lureau 已提交
374

J
Jason Wang 已提交
375
        if (vhost_log == log) {
M
Marc-André Lureau 已提交
376
            g_free(log->log);
J
Jason Wang 已提交
377
            vhost_log = NULL;
M
Marc-André Lureau 已提交
378 379 380 381
        } else if (vhost_log_shm == log) {
            qemu_memfd_free(log->log, log->size * sizeof(*(log->log)),
                            log->fd);
            vhost_log_shm = NULL;
J
Jason Wang 已提交
382
        }
M
Marc-André Lureau 已提交
383

J
Jason Wang 已提交
384 385 386
        g_free(log);
    }
}
M
Michael S. Tsirkin 已提交
387

M
Marc-André Lureau 已提交
388 389 390 391 392 393 394
static bool vhost_dev_log_is_shared(struct vhost_dev *dev)
{
    return dev->vhost_ops->vhost_requires_shm_log &&
           dev->vhost_ops->vhost_requires_shm_log(dev);
}

static inline void vhost_dev_log_resize(struct vhost_dev *dev, uint64_t size)
M
Michael S. Tsirkin 已提交
395
{
M
Marc-André Lureau 已提交
396
    struct vhost_log *log = vhost_log_get(size, vhost_dev_log_is_shared(dev));
J
Jason Wang 已提交
397
    uint64_t log_base = (uintptr_t)log->log;
M
Michael S. Tsirkin 已提交
398
    int r;
399

M
Marc-André Lureau 已提交
400 401
    /* inform backend of log switching, this must be done before
       releasing the current log, to ensure no logging is lost */
402
    r = dev->vhost_ops->vhost_set_log_base(dev, log_base, log);
M
Michael S. Tsirkin 已提交
403
    assert(r >= 0);
J
Jason Wang 已提交
404
    vhost_log_put(dev, true);
M
Michael S. Tsirkin 已提交
405 406 407 408 409 410 411 412 413
    dev->log = log;
    dev->log_size = size;
}

static int vhost_verify_ring_mappings(struct vhost_dev *dev,
                                      uint64_t start_addr,
                                      uint64_t size)
{
    int i;
414 415 416
    int r = 0;

    for (i = 0; !r && i < dev->nvqs; ++i) {
M
Michael S. Tsirkin 已提交
417
        struct vhost_virtqueue *vq = dev->vqs + i;
A
Avi Kivity 已提交
418
        hwaddr l;
M
Michael S. Tsirkin 已提交
419 420 421 422 423 424 425 426 427
        void *p;

        if (!ranges_overlap(start_addr, size, vq->ring_phys, vq->ring_size)) {
            continue;
        }
        l = vq->ring_size;
        p = cpu_physical_memory_map(vq->ring_phys, &l, 1);
        if (!p || l != vq->ring_size) {
            fprintf(stderr, "Unable to map ring buffer for ring %d\n", i);
428
            r = -ENOMEM;
M
Michael S. Tsirkin 已提交
429 430 431
        }
        if (p != vq->ring) {
            fprintf(stderr, "Ring buffer relocated for ring %d\n", i);
432
            r = -EBUSY;
M
Michael S. Tsirkin 已提交
433 434 435
        }
        cpu_physical_memory_unmap(p, l, 0, 0);
    }
436
    return r;
M
Michael S. Tsirkin 已提交
437 438
}

439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
static struct vhost_memory_region *vhost_dev_find_reg(struct vhost_dev *dev,
						      uint64_t start_addr,
						      uint64_t size)
{
    int i, n = dev->mem->nregions;
    for (i = 0; i < n; ++i) {
        struct vhost_memory_region *reg = dev->mem->regions + i;
        if (ranges_overlap(reg->guest_phys_addr, reg->memory_size,
                           start_addr, size)) {
            return reg;
        }
    }
    return NULL;
}

static bool vhost_dev_cmp_memory(struct vhost_dev *dev,
                                 uint64_t start_addr,
                                 uint64_t size,
                                 uint64_t uaddr)
{
    struct vhost_memory_region *reg = vhost_dev_find_reg(dev, start_addr, size);
    uint64_t reglast;
    uint64_t memlast;

    if (!reg) {
        return true;
    }

    reglast = range_get_last(reg->guest_phys_addr, reg->memory_size);
    memlast = range_get_last(start_addr, size);

    /* Need to extend region? */
    if (start_addr < reg->guest_phys_addr || memlast > reglast) {
        return true;
    }
    /* userspace_addr changed? */
    return uaddr != reg->userspace_addr + start_addr - reg->guest_phys_addr;
}

A
Avi Kivity 已提交
478 479 480
static void vhost_set_memory(MemoryListener *listener,
                             MemoryRegionSection *section,
                             bool add)
M
Michael S. Tsirkin 已提交
481
{
A
Avi Kivity 已提交
482 483
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);
A
Avi Kivity 已提交
484
    hwaddr start_addr = section->offset_within_address_space;
485
    ram_addr_t size = int128_get64(section->size);
486 487
    bool log_dirty =
        memory_region_get_dirty_log_mask(section->mr) & ~(1 << DIRTY_MEMORY_MIGRATION);
M
Michael S. Tsirkin 已提交
488 489
    int s = offsetof(struct vhost_memory, regions) +
        (dev->mem->nregions + 1) * sizeof dev->mem->regions[0];
A
Avi Kivity 已提交
490 491
    void *ram;

492
    dev->mem = g_realloc(dev->mem, s);
M
Michael S. Tsirkin 已提交
493

494
    if (log_dirty) {
A
Avi Kivity 已提交
495
        add = false;
496 497
    }

M
Michael S. Tsirkin 已提交
498 499
    assert(size);

500
    /* Optimize no-change case. At least cirrus_vga does this a lot at this time. */
501
    ram = memory_region_get_ram_ptr(section->mr) + section->offset_within_region;
A
Avi Kivity 已提交
502 503
    if (add) {
        if (!vhost_dev_cmp_memory(dev, start_addr, size, (uintptr_t)ram)) {
504 505 506 507 508 509 510 511 512 513
            /* Region exists with same address. Nothing to do. */
            return;
        }
    } else {
        if (!vhost_dev_find_reg(dev, start_addr, size)) {
            /* Removing region that we don't access. Nothing to do. */
            return;
        }
    }

M
Michael S. Tsirkin 已提交
514
    vhost_dev_unassign_memory(dev, start_addr, size);
A
Avi Kivity 已提交
515
    if (add) {
M
Michael S. Tsirkin 已提交
516
        /* Add given mapping, merging adjacent regions if any */
A
Avi Kivity 已提交
517
        vhost_dev_assign_memory(dev, start_addr, size, (uintptr_t)ram);
M
Michael S. Tsirkin 已提交
518 519 520 521
    } else {
        /* Remove old mapping for this memory, if any. */
        vhost_dev_unassign_memory(dev, start_addr, size);
    }
522 523 524
    dev->mem_changed_start_addr = MIN(dev->mem_changed_start_addr, start_addr);
    dev->mem_changed_end_addr = MAX(dev->mem_changed_end_addr, start_addr + size - 1);
    dev->memory_changed = true;
525
    used_memslots = dev->mem->nregions;
526 527 528 529 530 531 532 533 534 535 536 537 538 539
}

static bool vhost_section(MemoryRegionSection *section)
{
    return memory_region_is_ram(section->mr);
}

static void vhost_begin(MemoryListener *listener)
{
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);
    dev->mem_changed_end_addr = 0;
    dev->mem_changed_start_addr = -1;
}
M
Michael S. Tsirkin 已提交
540

541 542 543 544 545 546 547 548 549 550 551 552
static void vhost_commit(MemoryListener *listener)
{
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);
    hwaddr start_addr = 0;
    ram_addr_t size = 0;
    uint64_t log_size;
    int r;

    if (!dev->memory_changed) {
        return;
    }
M
Michael S. Tsirkin 已提交
553 554 555
    if (!dev->started) {
        return;
    }
556 557 558
    if (dev->mem_changed_start_addr > dev->mem_changed_end_addr) {
        return;
    }
M
Michael S. Tsirkin 已提交
559 560

    if (dev->started) {
561 562 563
        start_addr = dev->mem_changed_start_addr;
        size = dev->mem_changed_end_addr - dev->mem_changed_start_addr + 1;

M
Michael S. Tsirkin 已提交
564 565 566 567 568
        r = vhost_verify_ring_mappings(dev, start_addr, size);
        assert(r >= 0);
    }

    if (!dev->log_enabled) {
569
        r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
M
Michael S. Tsirkin 已提交
570
        assert(r >= 0);
571
        dev->memory_changed = false;
M
Michael S. Tsirkin 已提交
572 573 574 575 576 577 578 579 580 581
        return;
    }
    log_size = vhost_get_log_size(dev);
    /* We allocate an extra 4K bytes to log,
     * to reduce the * number of reallocations. */
#define VHOST_LOG_BUFFER (0x1000 / sizeof *dev->log)
    /* To log more, must increase log size before table update. */
    if (dev->log_size < log_size) {
        vhost_dev_log_resize(dev, log_size + VHOST_LOG_BUFFER);
    }
582
    r = dev->vhost_ops->vhost_set_mem_table(dev, dev->mem);
M
Michael S. Tsirkin 已提交
583 584 585 586 587
    assert(r >= 0);
    /* To log less, can only decrease log size after table update. */
    if (dev->log_size > log_size + VHOST_LOG_BUFFER) {
        vhost_dev_log_resize(dev, log_size);
    }
588
    dev->memory_changed = false;
589 590
}

A
Avi Kivity 已提交
591 592 593
static void vhost_region_add(MemoryListener *listener,
                             MemoryRegionSection *section)
{
594 595 596
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);

A
Avi Kivity 已提交
597 598 599 600
    if (!vhost_section(section)) {
        return;
    }

601 602 603 604
    ++dev->n_mem_sections;
    dev->mem_sections = g_renew(MemoryRegionSection, dev->mem_sections,
                                dev->n_mem_sections);
    dev->mem_sections[dev->n_mem_sections - 1] = *section;
P
Paolo Bonzini 已提交
605
    memory_region_ref(section->mr);
A
Avi Kivity 已提交
606 607 608 609 610 611
    vhost_set_memory(listener, section, true);
}

static void vhost_region_del(MemoryListener *listener,
                             MemoryRegionSection *section)
{
612 613 614 615
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);
    int i;

A
Avi Kivity 已提交
616 617 618 619
    if (!vhost_section(section)) {
        return;
    }

A
Avi Kivity 已提交
620
    vhost_set_memory(listener, section, false);
P
Paolo Bonzini 已提交
621
    memory_region_unref(section->mr);
622 623 624 625 626
    for (i = 0; i < dev->n_mem_sections; ++i) {
        if (dev->mem_sections[i].offset_within_address_space
            == section->offset_within_address_space) {
            --dev->n_mem_sections;
            memmove(&dev->mem_sections[i], &dev->mem_sections[i+1],
627
                    (dev->n_mem_sections - i) * sizeof(*dev->mem_sections));
628 629 630
            break;
        }
    }
A
Avi Kivity 已提交
631 632
}

633 634 635 636 637
static void vhost_region_nop(MemoryListener *listener,
                             MemoryRegionSection *section)
{
}

M
Michael S. Tsirkin 已提交
638 639 640 641 642 643
static int vhost_virtqueue_set_addr(struct vhost_dev *dev,
                                    struct vhost_virtqueue *vq,
                                    unsigned idx, bool enable_log)
{
    struct vhost_vring_addr addr = {
        .index = idx,
644 645 646
        .desc_user_addr = (uint64_t)(unsigned long)vq->desc,
        .avail_user_addr = (uint64_t)(unsigned long)vq->avail,
        .used_user_addr = (uint64_t)(unsigned long)vq->used,
M
Michael S. Tsirkin 已提交
647 648 649
        .log_guest_addr = vq->used_phys,
        .flags = enable_log ? (1 << VHOST_VRING_F_LOG) : 0,
    };
650
    int r = dev->vhost_ops->vhost_set_vring_addr(dev, &addr);
M
Michael S. Tsirkin 已提交
651 652 653 654 655 656 657 658 659 660 661
    if (r < 0) {
        return -errno;
    }
    return 0;
}

static int vhost_dev_set_features(struct vhost_dev *dev, bool enable_log)
{
    uint64_t features = dev->acked_features;
    int r;
    if (enable_log) {
C
Cornelia Huck 已提交
662
        features |= 0x1ULL << VHOST_F_LOG_ALL;
M
Michael S. Tsirkin 已提交
663
    }
664
    r = dev->vhost_ops->vhost_set_features(dev, features);
M
Michael S. Tsirkin 已提交
665 666 667 668 669
    return r < 0 ? -errno : 0;
}

static int vhost_dev_set_log(struct vhost_dev *dev, bool enable_log)
{
670
    int r, t, i, idx;
M
Michael S. Tsirkin 已提交
671 672 673 674 675
    r = vhost_dev_set_features(dev, enable_log);
    if (r < 0) {
        goto err_features;
    }
    for (i = 0; i < dev->nvqs; ++i) {
676 677
        idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
        r = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
M
Michael S. Tsirkin 已提交
678 679 680 681 682 683 684 685
                                     enable_log);
        if (r < 0) {
            goto err_vq;
        }
    }
    return 0;
err_vq:
    for (; i >= 0; --i) {
686 687
        idx = dev->vhost_ops->vhost_get_vq_index(dev, dev->vq_index + i);
        t = vhost_virtqueue_set_addr(dev, dev->vqs + i, idx,
M
Michael S. Tsirkin 已提交
688 689 690 691 692 693 694 695 696
                                     dev->log_enabled);
        assert(t >= 0);
    }
    t = vhost_dev_set_features(dev, dev->log_enabled);
    assert(t >= 0);
err_features:
    return r;
}

A
Avi Kivity 已提交
697
static int vhost_migration_log(MemoryListener *listener, int enable)
M
Michael S. Tsirkin 已提交
698
{
A
Avi Kivity 已提交
699 700
    struct vhost_dev *dev = container_of(listener, struct vhost_dev,
                                         memory_listener);
M
Michael S. Tsirkin 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713
    int r;
    if (!!enable == dev->log_enabled) {
        return 0;
    }
    if (!dev->started) {
        dev->log_enabled = enable;
        return 0;
    }
    if (!enable) {
        r = vhost_dev_set_log(dev, false);
        if (r < 0) {
            return r;
        }
J
Jason Wang 已提交
714
        vhost_log_put(dev, false);
M
Michael S. Tsirkin 已提交
715 716 717 718 719 720 721 722 723 724 725
    } else {
        vhost_dev_log_resize(dev, vhost_get_log_size(dev));
        r = vhost_dev_set_log(dev, true);
        if (r < 0) {
            return r;
        }
    }
    dev->log_enabled = enable;
    return 0;
}

A
Avi Kivity 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
static void vhost_log_global_start(MemoryListener *listener)
{
    int r;

    r = vhost_migration_log(listener, true);
    if (r < 0) {
        abort();
    }
}

static void vhost_log_global_stop(MemoryListener *listener)
{
    int r;

    r = vhost_migration_log(listener, false);
    if (r < 0) {
        abort();
    }
}

static void vhost_log_start(MemoryListener *listener,
747 748
                            MemoryRegionSection *section,
                            int old, int new)
A
Avi Kivity 已提交
749 750 751 752 753
{
    /* FIXME: implement */
}

static void vhost_log_stop(MemoryListener *listener,
754 755
                           MemoryRegionSection *section,
                           int old, int new)
A
Avi Kivity 已提交
756 757 758 759
{
    /* FIXME: implement */
}

760 761 762 763 764
/* The vhost driver natively knows how to handle the vrings of non
 * cross-endian legacy devices and modern devices. Only legacy devices
 * exposed to a bi-endian guest may require the vhost driver to use a
 * specific endianness.
 */
765 766
static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)
{
767 768 769
    if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {
        return false;
    }
770
#ifdef HOST_WORDS_BIGENDIAN
771
    return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_LITTLE;
772
#else
773
    return vdev->device_endian == VIRTIO_DEVICE_ENDIAN_BIG;
774 775 776
#endif
}

777 778 779 780 781 782 783 784 785
static int vhost_virtqueue_set_vring_endian_legacy(struct vhost_dev *dev,
                                                   bool is_big_endian,
                                                   int vhost_vq_index)
{
    struct vhost_vring_state s = {
        .index = vhost_vq_index,
        .num = is_big_endian
    };

786
    if (!dev->vhost_ops->vhost_set_vring_endian(dev, &s)) {
787 788 789 790 791 792 793 794 795 796 797
        return 0;
    }

    if (errno == ENOTTY) {
        error_report("vhost does not support cross-endian");
        return -ENOSYS;
    }

    return -errno;
}

798
static int vhost_virtqueue_start(struct vhost_dev *dev,
M
Michael S. Tsirkin 已提交
799 800 801 802
                                struct VirtIODevice *vdev,
                                struct vhost_virtqueue *vq,
                                unsigned idx)
{
A
Avi Kivity 已提交
803
    hwaddr s, l, a;
M
Michael S. Tsirkin 已提交
804
    int r;
805
    int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
M
Michael S. Tsirkin 已提交
806
    struct vhost_vring_file file = {
J
Jason Wang 已提交
807
        .index = vhost_vq_index
M
Michael S. Tsirkin 已提交
808 809
    };
    struct vhost_vring_state state = {
J
Jason Wang 已提交
810
        .index = vhost_vq_index
M
Michael S. Tsirkin 已提交
811 812 813
    };
    struct VirtQueue *vvq = virtio_get_queue(vdev, idx);

J
Jason Wang 已提交
814

M
Michael S. Tsirkin 已提交
815
    vq->num = state.num = virtio_queue_get_num(vdev, idx);
816
    r = dev->vhost_ops->vhost_set_vring_num(dev, &state);
M
Michael S. Tsirkin 已提交
817 818 819 820 821
    if (r) {
        return -errno;
    }

    state.num = virtio_queue_get_last_avail_idx(vdev, idx);
822
    r = dev->vhost_ops->vhost_set_vring_base(dev, &state);
M
Michael S. Tsirkin 已提交
823 824 825 826
    if (r) {
        return -errno;
    }

827
    if (vhost_needs_vring_endian(vdev)) {
828 829 830 831 832 833 834 835
        r = vhost_virtqueue_set_vring_endian_legacy(dev,
                                                    virtio_is_big_endian(vdev),
                                                    vhost_vq_index);
        if (r) {
            return -errno;
        }
    }

M
Michael S. Tsirkin 已提交
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    s = l = virtio_queue_get_desc_size(vdev, idx);
    a = virtio_queue_get_desc_addr(vdev, idx);
    vq->desc = cpu_physical_memory_map(a, &l, 0);
    if (!vq->desc || l != s) {
        r = -ENOMEM;
        goto fail_alloc_desc;
    }
    s = l = virtio_queue_get_avail_size(vdev, idx);
    a = virtio_queue_get_avail_addr(vdev, idx);
    vq->avail = cpu_physical_memory_map(a, &l, 0);
    if (!vq->avail || l != s) {
        r = -ENOMEM;
        goto fail_alloc_avail;
    }
    vq->used_size = s = l = virtio_queue_get_used_size(vdev, idx);
    vq->used_phys = a = virtio_queue_get_used_addr(vdev, idx);
    vq->used = cpu_physical_memory_map(a, &l, 1);
    if (!vq->used || l != s) {
        r = -ENOMEM;
        goto fail_alloc_used;
    }

    vq->ring_size = s = l = virtio_queue_get_ring_size(vdev, idx);
    vq->ring_phys = a = virtio_queue_get_ring_addr(vdev, idx);
    vq->ring = cpu_physical_memory_map(a, &l, 1);
    if (!vq->ring || l != s) {
        r = -ENOMEM;
        goto fail_alloc_ring;
    }

J
Jason Wang 已提交
866
    r = vhost_virtqueue_set_addr(dev, vq, vhost_vq_index, dev->log_enabled);
M
Michael S. Tsirkin 已提交
867 868 869 870
    if (r < 0) {
        r = -errno;
        goto fail_alloc;
    }
J
Jason Wang 已提交
871

M
Michael S. Tsirkin 已提交
872
    file.fd = event_notifier_get_fd(virtio_queue_get_host_notifier(vvq));
873
    r = dev->vhost_ops->vhost_set_vring_kick(dev, &file);
M
Michael S. Tsirkin 已提交
874
    if (r) {
M
Michael S. Tsirkin 已提交
875
        r = -errno;
M
Michael S. Tsirkin 已提交
876 877 878
        goto fail_kick;
    }

879 880
    /* Clear and discard previous events if any. */
    event_notifier_test_and_clear(&vq->masked_notifier);
M
Michael S. Tsirkin 已提交
881

882 883 884 885 886 887 888 889
    /* Init vring in unmasked state, unless guest_notifier_mask
     * will do it later.
     */
    if (!vdev->use_guest_notifier_mask) {
        /* TODO: check and handle errors. */
        vhost_virtqueue_mask(dev, vdev, idx, false);
    }

M
Michael S. Tsirkin 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    return 0;

fail_kick:
fail_alloc:
    cpu_physical_memory_unmap(vq->ring, virtio_queue_get_ring_size(vdev, idx),
                              0, 0);
fail_alloc_ring:
    cpu_physical_memory_unmap(vq->used, virtio_queue_get_used_size(vdev, idx),
                              0, 0);
fail_alloc_used:
    cpu_physical_memory_unmap(vq->avail, virtio_queue_get_avail_size(vdev, idx),
                              0, 0);
fail_alloc_avail:
    cpu_physical_memory_unmap(vq->desc, virtio_queue_get_desc_size(vdev, idx),
                              0, 0);
fail_alloc_desc:
    return r;
}

909
static void vhost_virtqueue_stop(struct vhost_dev *dev,
M
Michael S. Tsirkin 已提交
910 911 912 913
                                    struct VirtIODevice *vdev,
                                    struct vhost_virtqueue *vq,
                                    unsigned idx)
{
914
    int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);
M
Michael S. Tsirkin 已提交
915
    struct vhost_vring_state state = {
916
        .index = vhost_vq_index,
M
Michael S. Tsirkin 已提交
917 918
    };
    int r;
919

920
    r = dev->vhost_ops->vhost_get_vring_base(dev, &state);
M
Michael S. Tsirkin 已提交
921 922 923 924 925
    if (r < 0) {
        fprintf(stderr, "vhost VQ %d ring restore failed: %d\n", idx, r);
        fflush(stderr);
    }
    virtio_queue_set_last_avail_idx(vdev, idx, state.num);
926
    virtio_queue_invalidate_signalled_used(vdev, idx);
927 928 929 930

    /* In the cross-endian case, we need to reset the vring endianness to
     * native as legacy devices expect so by default.
     */
931
    if (vhost_needs_vring_endian(vdev)) {
932 933 934 935 936 937 938 939
        r = vhost_virtqueue_set_vring_endian_legacy(dev,
                                                    !virtio_is_big_endian(vdev),
                                                    vhost_vq_index);
        if (r < 0) {
            error_report("failed to reset vring endianness");
        }
    }

M
Michael S. Tsirkin 已提交
940 941 942 943 944 945 946 947 948 949 950
    assert (r >= 0);
    cpu_physical_memory_unmap(vq->ring, virtio_queue_get_ring_size(vdev, idx),
                              0, virtio_queue_get_ring_size(vdev, idx));
    cpu_physical_memory_unmap(vq->used, virtio_queue_get_used_size(vdev, idx),
                              1, virtio_queue_get_used_size(vdev, idx));
    cpu_physical_memory_unmap(vq->avail, virtio_queue_get_avail_size(vdev, idx),
                              0, virtio_queue_get_avail_size(vdev, idx));
    cpu_physical_memory_unmap(vq->desc, virtio_queue_get_desc_size(vdev, idx),
                              0, virtio_queue_get_desc_size(vdev, idx));
}

951 952
static void vhost_eventfd_add(MemoryListener *listener,
                              MemoryRegionSection *section,
953
                              bool match_data, uint64_t data, EventNotifier *e)
954 955 956 957 958
{
}

static void vhost_eventfd_del(MemoryListener *listener,
                              MemoryRegionSection *section,
959
                              bool match_data, uint64_t data, EventNotifier *e)
960 961 962
{
}

J
Jason Wang 已提交
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
static int vhost_virtqueue_set_busyloop_timeout(struct vhost_dev *dev,
                                                int n, uint32_t timeout)
{
    int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
    struct vhost_vring_state state = {
        .index = vhost_vq_index,
        .num = timeout,
    };
    int r;

    if (!dev->vhost_ops->vhost_set_vring_busyloop_timeout) {
        return -EINVAL;
    }

    r = dev->vhost_ops->vhost_set_vring_busyloop_timeout(dev, &state);
    if (r) {
        return r;
    }

    return 0;
}

985 986 987
static int vhost_virtqueue_init(struct vhost_dev *dev,
                                struct vhost_virtqueue *vq, int n)
{
988
    int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, n);
989
    struct vhost_vring_file file = {
990
        .index = vhost_vq_index,
991 992 993 994 995 996 997
    };
    int r = event_notifier_init(&vq->masked_notifier, 0);
    if (r < 0) {
        return r;
    }

    file.fd = event_notifier_get_fd(&vq->masked_notifier);
998
    r = dev->vhost_ops->vhost_set_vring_call(dev, &file);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    if (r) {
        r = -errno;
        goto fail_call;
    }
    return 0;
fail_call:
    event_notifier_cleanup(&vq->masked_notifier);
    return r;
}

static void vhost_virtqueue_cleanup(struct vhost_virtqueue *vq)
{
    event_notifier_cleanup(&vq->masked_notifier);
}

1014
int vhost_dev_init(struct vhost_dev *hdev, void *opaque,
J
Jason Wang 已提交
1015
                   VhostBackendType backend_type, uint32_t busyloop_timeout)
M
Michael S. Tsirkin 已提交
1016 1017
{
    uint64_t features;
1018
    int i, r, n_initialized_vqs = 0;
1019

1020 1021
    hdev->migration_blocker = NULL;

1022 1023
    r = vhost_set_backend_type(hdev, backend_type);
    assert(r >= 0);
1024

1025 1026 1027
    r = hdev->vhost_ops->vhost_backend_init(hdev, opaque);
    if (r < 0) {
        goto fail;
1028 1029
    }

1030 1031 1032
    if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {
        fprintf(stderr, "vhost backend memory slots limit is less"
                " than current number of present memory slots\n");
1033 1034
        r = -1;
        goto fail;
1035
    }
1036

1037
    r = hdev->vhost_ops->vhost_set_owner(hdev);
M
Michael S. Tsirkin 已提交
1038 1039 1040 1041
    if (r < 0) {
        goto fail;
    }

1042
    r = hdev->vhost_ops->vhost_get_features(hdev, &features);
M
Michael S. Tsirkin 已提交
1043 1044 1045
    if (r < 0) {
        goto fail;
    }
1046

1047
    for (i = 0; i < hdev->nvqs; ++i, ++n_initialized_vqs) {
1048
        r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);
1049
        if (r < 0) {
1050
            goto fail;
1051 1052
        }
    }
J
Jason Wang 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

    if (busyloop_timeout) {
        for (i = 0; i < hdev->nvqs; ++i) {
            r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,
                                                     busyloop_timeout);
            if (r < 0) {
                goto fail_busyloop;
            }
        }
    }

M
Michael S. Tsirkin 已提交
1064 1065
    hdev->features = features;

A
Avi Kivity 已提交
1066
    hdev->memory_listener = (MemoryListener) {
1067 1068
        .begin = vhost_begin,
        .commit = vhost_commit,
A
Avi Kivity 已提交
1069 1070
        .region_add = vhost_region_add,
        .region_del = vhost_region_del,
1071
        .region_nop = vhost_region_nop,
A
Avi Kivity 已提交
1072 1073 1074 1075 1076
        .log_start = vhost_log_start,
        .log_stop = vhost_log_stop,
        .log_sync = vhost_log_sync,
        .log_global_start = vhost_log_global_start,
        .log_global_stop = vhost_log_global_stop,
1077 1078
        .eventfd_add = vhost_eventfd_add,
        .eventfd_del = vhost_eventfd_del,
1079
        .priority = 10
A
Avi Kivity 已提交
1080
    };
1081 1082 1083 1084 1085

    if (hdev->migration_blocker == NULL) {
        if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {
            error_setg(&hdev->migration_blocker,
                       "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");
1086 1087 1088
        } else if (!qemu_memfd_check()) {
            error_setg(&hdev->migration_blocker,
                       "Migration disabled: failed to allocate shared memory");
1089 1090 1091 1092
        }
    }

    if (hdev->migration_blocker != NULL) {
1093 1094
        migrate_add_blocker(hdev->migration_blocker);
    }
1095

1096
    hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));
1097 1098
    hdev->n_mem_sections = 0;
    hdev->mem_sections = NULL;
M
Michael S. Tsirkin 已提交
1099 1100 1101 1102
    hdev->log = NULL;
    hdev->log_size = 0;
    hdev->log_enabled = false;
    hdev->started = false;
1103
    hdev->memory_changed = false;
1104
    memory_listener_register(&hdev->memory_listener, &address_space_memory);
1105
    QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);
M
Michael S. Tsirkin 已提交
1106
    return 0;
1107

J
Jason Wang 已提交
1108 1109 1110 1111
fail_busyloop:
    while (--i >= 0) {
        vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);
    }
M
Michael S. Tsirkin 已提交
1112
fail:
1113 1114
    hdev->nvqs = n_initialized_vqs;
    vhost_dev_cleanup(hdev);
M
Michael S. Tsirkin 已提交
1115 1116 1117 1118 1119
    return r;
}

void vhost_dev_cleanup(struct vhost_dev *hdev)
{
1120
    int i;
1121

1122 1123 1124
    for (i = 0; i < hdev->nvqs; ++i) {
        vhost_virtqueue_cleanup(hdev->vqs + i);
    }
1125 1126 1127 1128 1129
    if (hdev->mem) {
        /* those are only safe after successful init */
        memory_listener_unregister(&hdev->memory_listener);
        QLIST_REMOVE(hdev, entry);
    }
1130 1131 1132 1133
    if (hdev->migration_blocker) {
        migrate_del_blocker(hdev->migration_blocker);
        error_free(hdev->migration_blocker);
    }
1134
    g_free(hdev->mem);
1135
    g_free(hdev->mem_sections);
1136 1137 1138
    if (hdev->vhost_ops) {
        hdev->vhost_ops->vhost_backend_cleanup(hdev);
    }
1139
    assert(!hdev->log);
1140 1141

    memset(hdev, 0, sizeof(struct vhost_dev));
M
Michael S. Tsirkin 已提交
1142 1143
}

1144 1145 1146 1147 1148
/* Stop processing guest IO notifications in qemu.
 * Start processing them in vhost in kernel.
 */
int vhost_dev_enable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
{
K
KONRAD Frederic 已提交
1149 1150 1151
    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
    VirtioBusState *vbus = VIRTIO_BUS(qbus);
    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(vbus);
1152
    int i, r, e;
1153
    if (!k->ioeventfd_started) {
1154 1155 1156 1157 1158 1159
        fprintf(stderr, "binding does not support host notifiers\n");
        r = -ENOSYS;
        goto fail;
    }

    for (i = 0; i < hdev->nvqs; ++i) {
1160 1161
        r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
                                         true);
1162 1163 1164 1165 1166 1167 1168 1169 1170
        if (r < 0) {
            fprintf(stderr, "vhost VQ %d notifier binding failed: %d\n", i, -r);
            goto fail_vq;
        }
    }

    return 0;
fail_vq:
    while (--i >= 0) {
1171 1172
        e = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
                                         false);
1173
        if (e < 0) {
1174 1175 1176
            fprintf(stderr, "vhost VQ %d notifier cleanup error: %d\n", i, -r);
            fflush(stderr);
        }
1177
        assert (e >= 0);
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    }
fail:
    return r;
}

/* Stop processing guest IO notifications in vhost.
 * Start processing them in qemu.
 * This might actually run the qemu handlers right away,
 * so virtio in qemu must be completely setup when this is called.
 */
void vhost_dev_disable_notifiers(struct vhost_dev *hdev, VirtIODevice *vdev)
{
K
KONRAD Frederic 已提交
1190
    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
1191 1192 1193
    int i, r;

    for (i = 0; i < hdev->nvqs; ++i) {
1194 1195
        r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), hdev->vq_index + i,
                                         false);
1196 1197 1198 1199 1200 1201 1202 1203
        if (r < 0) {
            fprintf(stderr, "vhost VQ %d notifier cleanup failed: %d\n", i, -r);
            fflush(stderr);
        }
        assert (r >= 0);
    }
}

1204 1205 1206 1207 1208
/* Test and clear event pending status.
 * Should be called after unmask to avoid losing events.
 */
bool vhost_virtqueue_pending(struct vhost_dev *hdev, int n)
{
J
Jason Wang 已提交
1209 1210
    struct vhost_virtqueue *vq = hdev->vqs + n - hdev->vq_index;
    assert(n >= hdev->vq_index && n < hdev->vq_index + hdev->nvqs);
1211 1212 1213 1214 1215 1216 1217 1218
    return event_notifier_test_and_clear(&vq->masked_notifier);
}

/* Mask/unmask events from this vq. */
void vhost_virtqueue_mask(struct vhost_dev *hdev, VirtIODevice *vdev, int n,
                         bool mask)
{
    struct VirtQueue *vvq = virtio_get_queue(vdev, n);
J
Jason Wang 已提交
1219
    int r, index = n - hdev->vq_index;
1220
    struct vhost_vring_file file;
1221 1222

    if (mask) {
1223
        assert(vdev->use_guest_notifier_mask);
J
Jason Wang 已提交
1224
        file.fd = event_notifier_get_fd(&hdev->vqs[index].masked_notifier);
1225 1226 1227
    } else {
        file.fd = event_notifier_get_fd(virtio_queue_get_guest_notifier(vvq));
    }
1228

1229 1230
    file.index = hdev->vhost_ops->vhost_get_vq_index(hdev, n);
    r = hdev->vhost_ops->vhost_set_vring_call(hdev, &file);
1231 1232 1233
    assert(r >= 0);
}

C
Cornelia Huck 已提交
1234 1235
uint64_t vhost_get_features(struct vhost_dev *hdev, const int *feature_bits,
                            uint64_t features)
1236 1237 1238
{
    const int *bit = feature_bits;
    while (*bit != VHOST_INVALID_FEATURE_BIT) {
C
Cornelia Huck 已提交
1239
        uint64_t bit_mask = (1ULL << *bit);
1240 1241 1242 1243 1244 1245 1246 1247 1248
        if (!(hdev->features & bit_mask)) {
            features &= ~bit_mask;
        }
        bit++;
    }
    return features;
}

void vhost_ack_features(struct vhost_dev *hdev, const int *feature_bits,
C
Cornelia Huck 已提交
1249
                        uint64_t features)
1250 1251 1252
{
    const int *bit = feature_bits;
    while (*bit != VHOST_INVALID_FEATURE_BIT) {
C
Cornelia Huck 已提交
1253
        uint64_t bit_mask = (1ULL << *bit);
1254 1255 1256 1257 1258 1259 1260
        if (features & bit_mask) {
            hdev->acked_features |= bit_mask;
        }
        bit++;
    }
}

1261
/* Host notifiers must be enabled at this point. */
M
Michael S. Tsirkin 已提交
1262 1263 1264
int vhost_dev_start(struct vhost_dev *hdev, VirtIODevice *vdev)
{
    int i, r;
1265 1266 1267

    hdev->started = true;

M
Michael S. Tsirkin 已提交
1268 1269
    r = vhost_dev_set_features(hdev, hdev->log_enabled);
    if (r < 0) {
1270
        goto fail_features;
M
Michael S. Tsirkin 已提交
1271
    }
1272
    r = hdev->vhost_ops->vhost_set_mem_table(hdev, hdev->mem);
M
Michael S. Tsirkin 已提交
1273 1274
    if (r < 0) {
        r = -errno;
1275
        goto fail_mem;
M
Michael S. Tsirkin 已提交
1276
    }
1277
    for (i = 0; i < hdev->nvqs; ++i) {
1278
        r = vhost_virtqueue_start(hdev,
J
Jason Wang 已提交
1279 1280 1281
                                  vdev,
                                  hdev->vqs + i,
                                  hdev->vq_index + i);
1282 1283 1284 1285 1286
        if (r < 0) {
            goto fail_vq;
        }
    }

M
Michael S. Tsirkin 已提交
1287
    if (hdev->log_enabled) {
M
Michael S. Tsirkin 已提交
1288 1289
        uint64_t log_base;

M
Michael S. Tsirkin 已提交
1290
        hdev->log_size = vhost_get_log_size(hdev);
M
Marc-André Lureau 已提交
1291 1292
        hdev->log = vhost_log_get(hdev->log_size,
                                  vhost_dev_log_is_shared(hdev));
J
Jason Wang 已提交
1293
        log_base = (uintptr_t)hdev->log->log;
1294
        r = hdev->vhost_ops->vhost_set_log_base(hdev,
1295 1296
                                                hdev->log_size ? log_base : 0,
                                                hdev->log);
M
Michael S. Tsirkin 已提交
1297 1298
        if (r < 0) {
            r = -errno;
1299
            goto fail_log;
M
Michael S. Tsirkin 已提交
1300 1301
        }
    }
1302

M
Michael S. Tsirkin 已提交
1303
    return 0;
1304
fail_log:
1305
    vhost_log_put(hdev, false);
M
Michael S. Tsirkin 已提交
1306 1307
fail_vq:
    while (--i >= 0) {
1308
        vhost_virtqueue_stop(hdev,
J
Jason Wang 已提交
1309 1310 1311
                             vdev,
                             hdev->vqs + i,
                             hdev->vq_index + i);
M
Michael S. Tsirkin 已提交
1312
    }
J
Jason Wang 已提交
1313
    i = hdev->nvqs;
1314 1315
fail_mem:
fail_features:
1316 1317

    hdev->started = false;
M
Michael S. Tsirkin 已提交
1318 1319 1320
    return r;
}

1321
/* Host notifiers must be enabled at this point. */
M
Michael S. Tsirkin 已提交
1322 1323
void vhost_dev_stop(struct vhost_dev *hdev, VirtIODevice *vdev)
{
J
Jason Wang 已提交
1324
    int i;
1325

M
Michael S. Tsirkin 已提交
1326
    for (i = 0; i < hdev->nvqs; ++i) {
1327
        vhost_virtqueue_stop(hdev,
J
Jason Wang 已提交
1328 1329 1330
                             vdev,
                             hdev->vqs + i,
                             hdev->vq_index + i);
M
Michael S. Tsirkin 已提交
1331
    }
1332

J
Jason Wang 已提交
1333
    vhost_log_put(hdev, true);
M
Michael S. Tsirkin 已提交
1334 1335
    hdev->started = false;
}