qemu/hw/virtio/virtio-balloon.c
<<
>>
Prefs
   1/*
   2 * Virtio Balloon Device
   3 *
   4 * Copyright IBM, Corp. 2008
   5 * Copyright (C) 2011 Red Hat, Inc.
   6 * Copyright (C) 2011 Amit Shah <amit.shah@redhat.com>
   7 *
   8 * Authors:
   9 *  Anthony Liguori   <aliguori@us.ibm.com>
  10 *
  11 * This work is licensed under the terms of the GNU GPL, version 2.  See
  12 * the COPYING file in the top-level directory.
  13 *
  14 */
  15
  16#include "qemu/osdep.h"
  17#include "qemu/iov.h"
  18#include "qemu/module.h"
  19#include "qemu/timer.h"
  20#include "hw/virtio/virtio.h"
  21#include "hw/mem/pc-dimm.h"
  22#include "hw/qdev-properties.h"
  23#include "hw/boards.h"
  24#include "sysemu/balloon.h"
  25#include "hw/virtio/virtio-balloon.h"
  26#include "exec/address-spaces.h"
  27#include "qapi/error.h"
  28#include "qapi/qapi-events-machine.h"
  29#include "qapi/visitor.h"
  30#include "trace.h"
  31#include "qemu/error-report.h"
  32#include "migration/misc.h"
  33#include "migration/migration.h"
  34
  35#include "hw/virtio/virtio-bus.h"
  36#include "hw/virtio/virtio-access.h"
  37
  38#define BALLOON_PAGE_SIZE  (1 << VIRTIO_BALLOON_PFN_SHIFT)
  39
  40typedef struct PartiallyBalloonedPage {
  41    ram_addr_t base_gpa;
  42    unsigned long *bitmap;
  43} PartiallyBalloonedPage;
  44
  45static void virtio_balloon_pbp_free(PartiallyBalloonedPage *pbp)
  46{
  47    if (!pbp->bitmap) {
  48        return;
  49    }
  50    g_free(pbp->bitmap);
  51    pbp->bitmap = NULL;
  52}
  53
  54static void virtio_balloon_pbp_alloc(PartiallyBalloonedPage *pbp,
  55                                     ram_addr_t base_gpa,
  56                                     long subpages)
  57{
  58    pbp->base_gpa = base_gpa;
  59    pbp->bitmap = bitmap_new(subpages);
  60}
  61
  62static bool virtio_balloon_pbp_matches(PartiallyBalloonedPage *pbp,
  63                                       ram_addr_t base_gpa)
  64{
  65    return pbp->base_gpa == base_gpa;
  66}
  67
  68static bool virtio_balloon_inhibited(void)
  69{
  70    /*
  71     * Postcopy cannot deal with concurrent discards,
  72     * so it's special, as well as background snapshots.
  73     */
  74    return ram_block_discard_is_disabled() || migration_in_incoming_postcopy() ||
  75            migration_in_bg_snapshot();
  76}
  77
  78static void balloon_inflate_page(VirtIOBalloon *balloon,
  79                                 MemoryRegion *mr, hwaddr mr_offset,
  80                                 PartiallyBalloonedPage *pbp)
  81{
  82    void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
  83    ram_addr_t rb_offset, rb_aligned_offset, base_gpa;
  84    RAMBlock *rb;
  85    size_t rb_page_size;
  86    int subpages;
  87
  88    /* XXX is there a better way to get to the RAMBlock than via a
  89     * host address? */
  90    rb = qemu_ram_block_from_host(addr, false, &rb_offset);
  91    rb_page_size = qemu_ram_pagesize(rb);
  92
  93    if (rb_page_size == BALLOON_PAGE_SIZE) {
  94        /* Easy case */
  95
  96        ram_block_discard_range(rb, rb_offset, rb_page_size);
  97        /* We ignore errors from ram_block_discard_range(), because it
  98         * has already reported them, and failing to discard a balloon
  99         * page is not fatal */
 100        return;
 101    }
 102
 103    /* Hard case
 104     *
 105     * We've put a piece of a larger host page into the balloon - we
 106     * need to keep track until we have a whole host page to
 107     * discard
 108     */
 109    warn_report_once(
 110"Balloon used with backing page size > 4kiB, this may not be reliable");
 111
 112    rb_aligned_offset = QEMU_ALIGN_DOWN(rb_offset, rb_page_size);
 113    subpages = rb_page_size / BALLOON_PAGE_SIZE;
 114    base_gpa = memory_region_get_ram_addr(mr) + mr_offset -
 115               (rb_offset - rb_aligned_offset);
 116
 117    if (pbp->bitmap && !virtio_balloon_pbp_matches(pbp, base_gpa)) {
 118        /* We've partially ballooned part of a host page, but now
 119         * we're trying to balloon part of a different one.  Too hard,
 120         * give up on the old partial page */
 121        virtio_balloon_pbp_free(pbp);
 122    }
 123
 124    if (!pbp->bitmap) {
 125        virtio_balloon_pbp_alloc(pbp, base_gpa, subpages);
 126    }
 127
 128    set_bit((rb_offset - rb_aligned_offset) / BALLOON_PAGE_SIZE,
 129            pbp->bitmap);
 130
 131    if (bitmap_full(pbp->bitmap, subpages)) {
 132        /* We've accumulated a full host page, we can actually discard
 133         * it now */
 134
 135        ram_block_discard_range(rb, rb_aligned_offset, rb_page_size);
 136        /* We ignore errors from ram_block_discard_range(), because it
 137         * has already reported them, and failing to discard a balloon
 138         * page is not fatal */
 139        virtio_balloon_pbp_free(pbp);
 140    }
 141}
 142
 143static void balloon_deflate_page(VirtIOBalloon *balloon,
 144                                 MemoryRegion *mr, hwaddr mr_offset)
 145{
 146    void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
 147    ram_addr_t rb_offset;
 148    RAMBlock *rb;
 149    size_t rb_page_size;
 150    void *host_addr;
 151    int ret;
 152
 153    /* XXX is there a better way to get to the RAMBlock than via a
 154     * host address? */
 155    rb = qemu_ram_block_from_host(addr, false, &rb_offset);
 156    rb_page_size = qemu_ram_pagesize(rb);
 157
 158    host_addr = (void *)((uintptr_t)addr & ~(rb_page_size - 1));
 159
 160    /* When a page is deflated, we hint the whole host page it lives
 161     * on, since we can't do anything smaller */
 162    ret = qemu_madvise(host_addr, rb_page_size, QEMU_MADV_WILLNEED);
 163    if (ret != 0) {
 164        warn_report("Couldn't MADV_WILLNEED on balloon deflate: %s",
 165                    strerror(errno));
 166        /* Otherwise ignore, failing to page hint shouldn't be fatal */
 167    }
 168}
 169
 170static const char *balloon_stat_names[] = {
 171   [VIRTIO_BALLOON_S_SWAP_IN] = "stat-swap-in",
 172   [VIRTIO_BALLOON_S_SWAP_OUT] = "stat-swap-out",
 173   [VIRTIO_BALLOON_S_MAJFLT] = "stat-major-faults",
 174   [VIRTIO_BALLOON_S_MINFLT] = "stat-minor-faults",
 175   [VIRTIO_BALLOON_S_MEMFREE] = "stat-free-memory",
 176   [VIRTIO_BALLOON_S_MEMTOT] = "stat-total-memory",
 177   [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
 178   [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
 179   [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
 180   [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
 181   [VIRTIO_BALLOON_S_NR] = NULL
 182};
 183
 184/*
 185 * reset_stats - Mark all items in the stats array as unset
 186 *
 187 * This function needs to be called at device initialization and before
 188 * updating to a set of newly-generated stats.  This will ensure that no
 189 * stale values stick around in case the guest reports a subset of the supported
 190 * statistics.
 191 */
 192static inline void reset_stats(VirtIOBalloon *dev)
 193{
 194    int i;
 195    for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
 196}
 197
 198static bool balloon_stats_supported(const VirtIOBalloon *s)
 199{
 200    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 201    return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
 202}
 203
 204static bool balloon_stats_enabled(const VirtIOBalloon *s)
 205{
 206    return s->stats_poll_interval > 0;
 207}
 208
 209static void balloon_stats_destroy_timer(VirtIOBalloon *s)
 210{
 211    if (balloon_stats_enabled(s)) {
 212        timer_free(s->stats_timer);
 213        s->stats_timer = NULL;
 214        s->stats_poll_interval = 0;
 215    }
 216}
 217
 218static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
 219{
 220    timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
 221}
 222
 223static void balloon_stats_poll_cb(void *opaque)
 224{
 225    VirtIOBalloon *s = opaque;
 226    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 227
 228    if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
 229        /* re-schedule */
 230        balloon_stats_change_timer(s, s->stats_poll_interval);
 231        return;
 232    }
 233
 234    virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
 235    virtio_notify(vdev, s->svq);
 236    g_free(s->stats_vq_elem);
 237    s->stats_vq_elem = NULL;
 238}
 239
 240static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
 241                                  void *opaque, Error **errp)
 242{
 243    Error *err = NULL;
 244    VirtIOBalloon *s = opaque;
 245    int i;
 246
 247    if (!visit_start_struct(v, name, NULL, 0, &err)) {
 248        goto out;
 249    }
 250    if (!visit_type_int(v, "last-update", &s->stats_last_update, &err)) {
 251        goto out_end;
 252    }
 253
 254    if (!visit_start_struct(v, "stats", NULL, 0, &err)) {
 255        goto out_end;
 256    }
 257    for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
 258        if (!visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err)) {
 259            goto out_nested;
 260        }
 261    }
 262    visit_check_struct(v, &err);
 263out_nested:
 264    visit_end_struct(v, NULL);
 265
 266    if (!err) {
 267        visit_check_struct(v, &err);
 268    }
 269out_end:
 270    visit_end_struct(v, NULL);
 271out:
 272    error_propagate(errp, err);
 273}
 274
 275static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
 276                                            const char *name, void *opaque,
 277                                            Error **errp)
 278{
 279    VirtIOBalloon *s = opaque;
 280    visit_type_int(v, name, &s->stats_poll_interval, errp);
 281}
 282
 283static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
 284                                            const char *name, void *opaque,
 285                                            Error **errp)
 286{
 287    VirtIOBalloon *s = opaque;
 288    int64_t value;
 289
 290    if (!visit_type_int(v, name, &value, errp)) {
 291        return;
 292    }
 293
 294    if (value < 0) {
 295        error_setg(errp, "timer value must be greater than zero");
 296        return;
 297    }
 298
 299    if (value > UINT32_MAX) {
 300        error_setg(errp, "timer value is too big");
 301        return;
 302    }
 303
 304    if (value == s->stats_poll_interval) {
 305        return;
 306    }
 307
 308    if (value == 0) {
 309        /* timer=0 disables the timer */
 310        balloon_stats_destroy_timer(s);
 311        return;
 312    }
 313
 314    if (balloon_stats_enabled(s)) {
 315        /* timer interval change */
 316        s->stats_poll_interval = value;
 317        balloon_stats_change_timer(s, value);
 318        return;
 319    }
 320
 321    /* create a new timer */
 322    g_assert(s->stats_timer == NULL);
 323    s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
 324    s->stats_poll_interval = value;
 325    balloon_stats_change_timer(s, 0);
 326}
 327
 328static void virtio_balloon_handle_report(VirtIODevice *vdev, VirtQueue *vq)
 329{
 330    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
 331    VirtQueueElement *elem;
 332
 333    while ((elem = virtqueue_pop(vq, sizeof(VirtQueueElement)))) {
 334        unsigned int i;
 335
 336        /*
 337         * When we discard the page it has the effect of removing the page
 338         * from the hypervisor itself and causing it to be zeroed when it
 339         * is returned to us. So we must not discard the page if it is
 340         * accessible by another device or process, or if the guest is
 341         * expecting it to retain a non-zero value.
 342         */
 343        if (virtio_balloon_inhibited() || dev->poison_val) {
 344            goto skip_element;
 345        }
 346
 347        for (i = 0; i < elem->in_num; i++) {
 348            void *addr = elem->in_sg[i].iov_base;
 349            size_t size = elem->in_sg[i].iov_len;
 350            ram_addr_t ram_offset;
 351            RAMBlock *rb;
 352
 353            /*
 354             * There is no need to check the memory section to see if
 355             * it is ram/readonly/romd like there is for handle_output
 356             * below. If the region is not meant to be written to then
 357             * address_space_map will have allocated a bounce buffer
 358             * and it will be freed in address_space_unmap and trigger
 359             * and unassigned_mem_write before failing to copy over the
 360             * buffer. If more than one bad descriptor is provided it
 361             * will return NULL after the first bounce buffer and fail
 362             * to map any resources.
 363             */
 364            rb = qemu_ram_block_from_host(addr, false, &ram_offset);
 365            if (!rb) {
 366                trace_virtio_balloon_bad_addr(elem->in_addr[i]);
 367                continue;
 368            }
 369
 370            /*
 371             * For now we will simply ignore unaligned memory regions, or
 372             * regions that overrun the end of the RAMBlock.
 373             */
 374            if (!QEMU_IS_ALIGNED(ram_offset | size, qemu_ram_pagesize(rb)) ||
 375                (ram_offset + size) > qemu_ram_get_used_length(rb)) {
 376                continue;
 377            }
 378
 379            ram_block_discard_range(rb, ram_offset, size);
 380        }
 381
 382skip_element:
 383        virtqueue_push(vq, elem, 0);
 384        virtio_notify(vdev, vq);
 385        g_free(elem);
 386    }
 387}
 388
 389static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
 390{
 391    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
 392    VirtQueueElement *elem;
 393    MemoryRegionSection section;
 394
 395    for (;;) {
 396        PartiallyBalloonedPage pbp = {};
 397        size_t offset = 0;
 398        uint32_t pfn;
 399
 400        elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
 401        if (!elem) {
 402            break;
 403        }
 404
 405        while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
 406            unsigned int p = virtio_ldl_p(vdev, &pfn);
 407            hwaddr pa;
 408
 409            pa = (hwaddr) p << VIRTIO_BALLOON_PFN_SHIFT;
 410            offset += 4;
 411
 412            section = memory_region_find(get_system_memory(), pa,
 413                                         BALLOON_PAGE_SIZE);
 414            if (!section.mr) {
 415                trace_virtio_balloon_bad_addr(pa);
 416                continue;
 417            }
 418            if (!memory_region_is_ram(section.mr) ||
 419                memory_region_is_rom(section.mr) ||
 420                memory_region_is_romd(section.mr)) {
 421                trace_virtio_balloon_bad_addr(pa);
 422                memory_region_unref(section.mr);
 423                continue;
 424            }
 425
 426            trace_virtio_balloon_handle_output(memory_region_name(section.mr),
 427                                               pa);
 428            if (!virtio_balloon_inhibited()) {
 429                if (vq == s->ivq) {
 430                    balloon_inflate_page(s, section.mr,
 431                                         section.offset_within_region, &pbp);
 432                } else if (vq == s->dvq) {
 433                    balloon_deflate_page(s, section.mr, section.offset_within_region);
 434                } else {
 435                    g_assert_not_reached();
 436                }
 437            }
 438            memory_region_unref(section.mr);
 439        }
 440
 441        virtqueue_push(vq, elem, offset);
 442        virtio_notify(vdev, vq);
 443        g_free(elem);
 444        virtio_balloon_pbp_free(&pbp);
 445    }
 446}
 447
 448static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
 449{
 450    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
 451    VirtQueueElement *elem;
 452    VirtIOBalloonStat stat;
 453    size_t offset = 0;
 454    qemu_timeval tv;
 455
 456    elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
 457    if (!elem) {
 458        goto out;
 459    }
 460
 461    if (s->stats_vq_elem != NULL) {
 462        /* This should never happen if the driver follows the spec. */
 463        virtqueue_push(vq, s->stats_vq_elem, 0);
 464        virtio_notify(vdev, vq);
 465        g_free(s->stats_vq_elem);
 466    }
 467
 468    s->stats_vq_elem = elem;
 469
 470    /* Initialize the stats to get rid of any stale values.  This is only
 471     * needed to handle the case where a guest supports fewer stats than it
 472     * used to (ie. it has booted into an old kernel).
 473     */
 474    reset_stats(s);
 475
 476    while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
 477           == sizeof(stat)) {
 478        uint16_t tag = virtio_tswap16(vdev, stat.tag);
 479        uint64_t val = virtio_tswap64(vdev, stat.val);
 480
 481        offset += sizeof(stat);
 482        if (tag < VIRTIO_BALLOON_S_NR)
 483            s->stats[tag] = val;
 484    }
 485    s->stats_vq_offset = offset;
 486
 487    if (qemu_gettimeofday(&tv) < 0) {
 488        warn_report("%s: failed to get time of day", __func__);
 489        goto out;
 490    }
 491
 492    s->stats_last_update = tv.tv_sec;
 493
 494out:
 495    if (balloon_stats_enabled(s)) {
 496        balloon_stats_change_timer(s, s->stats_poll_interval);
 497    }
 498}
 499
 500static void virtio_balloon_handle_free_page_vq(VirtIODevice *vdev,
 501                                               VirtQueue *vq)
 502{
 503    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
 504    qemu_bh_schedule(s->free_page_bh);
 505}
 506
 507static bool get_free_page_hints(VirtIOBalloon *dev)
 508{
 509    VirtQueueElement *elem;
 510    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
 511    VirtQueue *vq = dev->free_page_vq;
 512    bool ret = true;
 513
 514    while (dev->block_iothread) {
 515        qemu_cond_wait(&dev->free_page_cond, &dev->free_page_lock);
 516    }
 517
 518    elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
 519    if (!elem) {
 520        return false;
 521    }
 522
 523    if (elem->out_num) {
 524        uint32_t id;
 525        size_t size = iov_to_buf(elem->out_sg, elem->out_num, 0,
 526                                 &id, sizeof(id));
 527
 528        virtio_tswap32s(vdev, &id);
 529        if (unlikely(size != sizeof(id))) {
 530            virtio_error(vdev, "received an incorrect cmd id");
 531            ret = false;
 532            goto out;
 533        }
 534        if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED &&
 535            id == dev->free_page_hint_cmd_id) {
 536            dev->free_page_hint_status = FREE_PAGE_HINT_S_START;
 537        } else {
 538            /*
 539             * Stop the optimization only when it has started. This
 540             * avoids a stale stop sign for the previous command.
 541             */
 542            if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
 543                dev->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
 544            }
 545        }
 546    }
 547
 548    if (elem->in_num) {
 549        if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
 550            qemu_guest_free_page_hint(elem->in_sg[0].iov_base,
 551                                      elem->in_sg[0].iov_len);
 552        }
 553    }
 554
 555out:
 556    virtqueue_push(vq, elem, 1);
 557    g_free(elem);
 558    return ret;
 559}
 560
 561static void virtio_ballloon_get_free_page_hints(void *opaque)
 562{
 563    VirtIOBalloon *dev = opaque;
 564    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
 565    VirtQueue *vq = dev->free_page_vq;
 566    bool continue_to_get_hints;
 567
 568    do {
 569        qemu_mutex_lock(&dev->free_page_lock);
 570        virtio_queue_set_notification(vq, 0);
 571        continue_to_get_hints = get_free_page_hints(dev);
 572        qemu_mutex_unlock(&dev->free_page_lock);
 573        virtio_notify(vdev, vq);
 574      /*
 575       * Start to poll the vq once the hinting started. Otherwise, continue
 576       * only when there are entries on the vq, which need to be given back.
 577       */
 578    } while (continue_to_get_hints ||
 579             dev->free_page_hint_status == FREE_PAGE_HINT_S_START);
 580    virtio_queue_set_notification(vq, 1);
 581}
 582
 583static bool virtio_balloon_free_page_support(void *opaque)
 584{
 585    VirtIOBalloon *s = opaque;
 586    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 587
 588    return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT);
 589}
 590
 591static void virtio_balloon_free_page_start(VirtIOBalloon *s)
 592{
 593    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 594
 595    /* For the stop and copy phase, we don't need to start the optimization */
 596    if (!vdev->vm_running) {
 597        return;
 598    }
 599
 600    qemu_mutex_lock(&s->free_page_lock);
 601
 602    if (s->free_page_hint_cmd_id == UINT_MAX) {
 603        s->free_page_hint_cmd_id =
 604                       VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
 605    } else {
 606        s->free_page_hint_cmd_id++;
 607    }
 608
 609    s->free_page_hint_status = FREE_PAGE_HINT_S_REQUESTED;
 610    qemu_mutex_unlock(&s->free_page_lock);
 611
 612    virtio_notify_config(vdev);
 613}
 614
 615static void virtio_balloon_free_page_stop(VirtIOBalloon *s)
 616{
 617    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 618
 619    if (s->free_page_hint_status != FREE_PAGE_HINT_S_STOP) {
 620        /*
 621         * The lock also guarantees us that the
 622         * virtio_ballloon_get_free_page_hints exits after the
 623         * free_page_hint_status is set to S_STOP.
 624         */
 625        qemu_mutex_lock(&s->free_page_lock);
 626        /*
 627         * The guest isn't done hinting, so send a notification
 628         * to the guest to actively stop the hinting.
 629         */
 630        s->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
 631        qemu_mutex_unlock(&s->free_page_lock);
 632        virtio_notify_config(vdev);
 633    }
 634}
 635
 636static void virtio_balloon_free_page_done(VirtIOBalloon *s)
 637{
 638    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 639
 640    if (s->free_page_hint_status != FREE_PAGE_HINT_S_DONE) {
 641        /* See virtio_balloon_free_page_stop() */
 642        qemu_mutex_lock(&s->free_page_lock);
 643        s->free_page_hint_status = FREE_PAGE_HINT_S_DONE;
 644        qemu_mutex_unlock(&s->free_page_lock);
 645        virtio_notify_config(vdev);
 646    }
 647}
 648
 649static int
 650virtio_balloon_free_page_hint_notify(NotifierWithReturn *n, void *data)
 651{
 652    VirtIOBalloon *dev = container_of(n, VirtIOBalloon,
 653                                      free_page_hint_notify);
 654    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
 655    PrecopyNotifyData *pnd = data;
 656
 657    if (!virtio_balloon_free_page_support(dev)) {
 658        /*
 659         * This is an optimization provided to migration, so just return 0 to
 660         * have the normal migration process not affected when this feature is
 661         * not supported.
 662         */
 663        return 0;
 664    }
 665
 666    /*
 667     * Pages hinted via qemu_guest_free_page_hint() are cleared from the dirty
 668     * bitmap and will not get migrated, especially also not when the postcopy
 669     * destination starts using them and requests migration from the source; the
 670     * faulting thread will stall until postcopy migration finishes and
 671     * all threads are woken up. Let's not start free page hinting if postcopy
 672     * is possible.
 673     */
 674    if (migrate_postcopy_ram()) {
 675        return 0;
 676    }
 677
 678    switch (pnd->reason) {
 679    case PRECOPY_NOTIFY_SETUP:
 680        precopy_enable_free_page_optimization();
 681        break;
 682    case PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC:
 683        virtio_balloon_free_page_stop(dev);
 684        break;
 685    case PRECOPY_NOTIFY_AFTER_BITMAP_SYNC:
 686        if (vdev->vm_running) {
 687            virtio_balloon_free_page_start(dev);
 688            break;
 689        }
 690        /*
 691         * Set S_DONE before migrating the vmstate, so the guest will reuse
 692         * all hinted pages once running on the destination. Fall through.
 693         */
 694    case PRECOPY_NOTIFY_CLEANUP:
 695        /*
 696         * Especially, if something goes wrong during precopy or if migration
 697         * is canceled, we have to properly communicate S_DONE to the VM.
 698         */
 699        virtio_balloon_free_page_done(dev);
 700        break;
 701    case PRECOPY_NOTIFY_COMPLETE:
 702        break;
 703    default:
 704        virtio_error(vdev, "%s: %d reason unknown", __func__, pnd->reason);
 705    }
 706
 707    return 0;
 708}
 709
 710static size_t virtio_balloon_config_size(VirtIOBalloon *s)
 711{
 712    uint64_t features = s->host_features;
 713
 714    if (s->qemu_4_0_config_size) {
 715        return sizeof(struct virtio_balloon_config);
 716    }
 717    if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON)) {
 718        return sizeof(struct virtio_balloon_config);
 719    }
 720    if (virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
 721        return offsetof(struct virtio_balloon_config, poison_val);
 722    }
 723    return offsetof(struct virtio_balloon_config, free_page_hint_cmd_id);
 724}
 725
 726static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
 727{
 728    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
 729    struct virtio_balloon_config config = {};
 730
 731    config.num_pages = cpu_to_le32(dev->num_pages);
 732    config.actual = cpu_to_le32(dev->actual);
 733    config.poison_val = cpu_to_le32(dev->poison_val);
 734
 735    if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED) {
 736        config.free_page_hint_cmd_id =
 737                       cpu_to_le32(dev->free_page_hint_cmd_id);
 738    } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_STOP) {
 739        config.free_page_hint_cmd_id =
 740                       cpu_to_le32(VIRTIO_BALLOON_CMD_ID_STOP);
 741    } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_DONE) {
 742        config.free_page_hint_cmd_id =
 743                       cpu_to_le32(VIRTIO_BALLOON_CMD_ID_DONE);
 744    }
 745
 746    trace_virtio_balloon_get_config(config.num_pages, config.actual);
 747    memcpy(config_data, &config, virtio_balloon_config_size(dev));
 748}
 749
 750static int build_dimm_list(Object *obj, void *opaque)
 751{
 752    GSList **list = opaque;
 753
 754    if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
 755        DeviceState *dev = DEVICE(obj);
 756        if (dev->realized) { /* only realized DIMMs matter */
 757            *list = g_slist_prepend(*list, dev);
 758        }
 759    }
 760
 761    object_child_foreach(obj, build_dimm_list, opaque);
 762    return 0;
 763}
 764
 765static ram_addr_t get_current_ram_size(void)
 766{
 767    GSList *list = NULL, *item;
 768    ram_addr_t size = current_machine->ram_size;
 769
 770    build_dimm_list(qdev_get_machine(), &list);
 771    for (item = list; item; item = g_slist_next(item)) {
 772        Object *obj = OBJECT(item->data);
 773        if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
 774            size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
 775                                            &error_abort);
 776        }
 777    }
 778    g_slist_free(list);
 779
 780    return size;
 781}
 782
 783static bool virtio_balloon_page_poison_support(void *opaque)
 784{
 785    VirtIOBalloon *s = opaque;
 786    VirtIODevice *vdev = VIRTIO_DEVICE(s);
 787
 788    return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON);
 789}
 790
 791static void virtio_balloon_set_config(VirtIODevice *vdev,
 792                                      const uint8_t *config_data)
 793{
 794    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
 795    struct virtio_balloon_config config;
 796    uint32_t oldactual = dev->actual;
 797    ram_addr_t vm_ram_size = get_current_ram_size();
 798
 799    memcpy(&config, config_data, virtio_balloon_config_size(dev));
 800    dev->actual = le32_to_cpu(config.actual);
 801    if (dev->actual != oldactual) {
 802        qapi_event_send_balloon_change(vm_ram_size -
 803                        ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
 804    }
 805    dev->poison_val = 0;
 806    if (virtio_balloon_page_poison_support(dev)) {
 807        dev->poison_val = le32_to_cpu(config.poison_val);
 808    }
 809    trace_virtio_balloon_set_config(dev->actual, oldactual);
 810}
 811
 812static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
 813                                            Error **errp)
 814{
 815    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
 816    f |= dev->host_features;
 817    virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
 818
 819    return f;
 820}
 821
 822static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
 823{
 824    VirtIOBalloon *dev = opaque;
 825    info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
 826                                             VIRTIO_BALLOON_PFN_SHIFT);
 827}
 828
 829static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
 830{
 831    VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
 832    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
 833    ram_addr_t vm_ram_size = get_current_ram_size();
 834
 835    if (target > vm_ram_size) {
 836        target = vm_ram_size;
 837    }
 838    if (target) {
 839        dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
 840        virtio_notify_config(vdev);
 841    }
 842    trace_virtio_balloon_to_target(target, dev->num_pages);
 843}
 844
 845static int virtio_balloon_post_load_device(void *opaque, int version_id)
 846{
 847    VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
 848
 849    if (balloon_stats_enabled(s)) {
 850        balloon_stats_change_timer(s, s->stats_poll_interval);
 851    }
 852    return 0;
 853}
 854
 855static const VMStateDescription vmstate_virtio_balloon_free_page_hint = {
 856    .name = "virtio-balloon-device/free-page-report",
 857    .version_id = 1,
 858    .minimum_version_id = 1,
 859    .needed = virtio_balloon_free_page_support,
 860    .fields = (VMStateField[]) {
 861        VMSTATE_UINT32(free_page_hint_cmd_id, VirtIOBalloon),
 862        VMSTATE_UINT32(free_page_hint_status, VirtIOBalloon),
 863        VMSTATE_END_OF_LIST()
 864    }
 865};
 866
 867static const VMStateDescription vmstate_virtio_balloon_page_poison = {
 868    .name = "vitio-balloon-device/page-poison",
 869    .version_id = 1,
 870    .minimum_version_id = 1,
 871    .needed = virtio_balloon_page_poison_support,
 872    .fields = (VMStateField[]) {
 873        VMSTATE_UINT32(poison_val, VirtIOBalloon),
 874        VMSTATE_END_OF_LIST()
 875    }
 876};
 877
 878static const VMStateDescription vmstate_virtio_balloon_device = {
 879    .name = "virtio-balloon-device",
 880    .version_id = 1,
 881    .minimum_version_id = 1,
 882    .post_load = virtio_balloon_post_load_device,
 883    .fields = (VMStateField[]) {
 884        VMSTATE_UINT32(num_pages, VirtIOBalloon),
 885        VMSTATE_UINT32(actual, VirtIOBalloon),
 886        VMSTATE_END_OF_LIST()
 887    },
 888    .subsections = (const VMStateDescription * []) {
 889        &vmstate_virtio_balloon_free_page_hint,
 890        &vmstate_virtio_balloon_page_poison,
 891        NULL
 892    }
 893};
 894
 895static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
 896{
 897    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
 898    VirtIOBalloon *s = VIRTIO_BALLOON(dev);
 899    int ret;
 900
 901    virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
 902                virtio_balloon_config_size(s));
 903
 904    ret = qemu_add_balloon_handler(virtio_balloon_to_target,
 905                                   virtio_balloon_stat, s);
 906
 907    if (ret < 0) {
 908        error_setg(errp, "Only one balloon device is supported");
 909        virtio_cleanup(vdev);
 910        return;
 911    }
 912
 913    if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_FREE_PAGE_HINT) &&
 914        !s->iothread) {
 915        error_setg(errp, "'free-page-hint' requires 'iothread' to be set");
 916        virtio_cleanup(vdev);
 917        return;
 918    }
 919
 920    s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
 921    s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
 922    s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
 923
 924    if (virtio_has_feature(s->host_features,
 925                           VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
 926        s->free_page_vq = virtio_add_queue(vdev, VIRTQUEUE_MAX_SIZE,
 927                                           virtio_balloon_handle_free_page_vq);
 928        precopy_add_notifier(&s->free_page_hint_notify);
 929
 930        object_ref(OBJECT(s->iothread));
 931        s->free_page_bh = aio_bh_new(iothread_get_aio_context(s->iothread),
 932                                     virtio_ballloon_get_free_page_hints, s);
 933    }
 934
 935    if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_REPORTING)) {
 936        s->reporting_vq = virtio_add_queue(vdev, 32,
 937                                           virtio_balloon_handle_report);
 938    }
 939
 940    reset_stats(s);
 941}
 942
 943static void virtio_balloon_device_unrealize(DeviceState *dev)
 944{
 945    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
 946    VirtIOBalloon *s = VIRTIO_BALLOON(dev);
 947
 948    if (s->free_page_bh) {
 949        qemu_bh_delete(s->free_page_bh);
 950        object_unref(OBJECT(s->iothread));
 951        virtio_balloon_free_page_stop(s);
 952        precopy_remove_notifier(&s->free_page_hint_notify);
 953    }
 954    balloon_stats_destroy_timer(s);
 955    qemu_remove_balloon_handler(s);
 956
 957    virtio_delete_queue(s->ivq);
 958    virtio_delete_queue(s->dvq);
 959    virtio_delete_queue(s->svq);
 960    if (s->free_page_vq) {
 961        virtio_delete_queue(s->free_page_vq);
 962    }
 963    if (s->reporting_vq) {
 964        virtio_delete_queue(s->reporting_vq);
 965    }
 966    virtio_cleanup(vdev);
 967}
 968
 969static void virtio_balloon_device_reset(VirtIODevice *vdev)
 970{
 971    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
 972
 973    if (virtio_balloon_free_page_support(s)) {
 974        virtio_balloon_free_page_stop(s);
 975    }
 976
 977    if (s->stats_vq_elem != NULL) {
 978        virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
 979        g_free(s->stats_vq_elem);
 980        s->stats_vq_elem = NULL;
 981    }
 982
 983    s->poison_val = 0;
 984}
 985
 986static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
 987{
 988    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
 989
 990    if (!s->stats_vq_elem && vdev->vm_running &&
 991        (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
 992        /* poll stats queue for the element we have discarded when the VM
 993         * was stopped */
 994        virtio_balloon_receive_stats(vdev, s->svq);
 995    }
 996
 997    if (virtio_balloon_free_page_support(s)) {
 998        /*
 999         * The VM is woken up and the iothread was blocked, so signal it to
1000         * continue.
1001         */
1002        if (vdev->vm_running && s->block_iothread) {
1003            qemu_mutex_lock(&s->free_page_lock);
1004            s->block_iothread = false;
1005            qemu_cond_signal(&s->free_page_cond);
1006            qemu_mutex_unlock(&s->free_page_lock);
1007        }
1008
1009        /* The VM is stopped, block the iothread. */
1010        if (!vdev->vm_running) {
1011            qemu_mutex_lock(&s->free_page_lock);
1012            s->block_iothread = true;
1013            qemu_mutex_unlock(&s->free_page_lock);
1014        }
1015    }
1016}
1017
1018static void virtio_balloon_instance_init(Object *obj)
1019{
1020    VirtIOBalloon *s = VIRTIO_BALLOON(obj);
1021
1022    qemu_mutex_init(&s->free_page_lock);
1023    qemu_cond_init(&s->free_page_cond);
1024    s->free_page_hint_cmd_id = VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
1025    s->free_page_hint_notify.notify = virtio_balloon_free_page_hint_notify;
1026
1027    object_property_add(obj, "guest-stats", "guest statistics",
1028                        balloon_stats_get_all, NULL, NULL, s);
1029
1030    object_property_add(obj, "guest-stats-polling-interval", "int",
1031                        balloon_stats_get_poll_interval,
1032                        balloon_stats_set_poll_interval,
1033                        NULL, s);
1034}
1035
1036static const VMStateDescription vmstate_virtio_balloon = {
1037    .name = "virtio-balloon",
1038    .minimum_version_id = 1,
1039    .version_id = 1,
1040    .fields = (VMStateField[]) {
1041        VMSTATE_VIRTIO_DEVICE,
1042        VMSTATE_END_OF_LIST()
1043    },
1044};
1045
1046static Property virtio_balloon_properties[] = {
1047    DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
1048                    VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
1049    DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon, host_features,
1050                    VIRTIO_BALLOON_F_FREE_PAGE_HINT, false),
1051    DEFINE_PROP_BIT("page-poison", VirtIOBalloon, host_features,
1052                    VIRTIO_BALLOON_F_PAGE_POISON, true),
1053    DEFINE_PROP_BIT("free-page-reporting", VirtIOBalloon, host_features,
1054                    VIRTIO_BALLOON_F_REPORTING, false),
1055    /* QEMU 4.0 accidentally changed the config size even when free-page-hint
1056     * is disabled, resulting in QEMU 3.1 migration incompatibility.  This
1057     * property retains this quirk for QEMU 4.1 machine types.
1058     */
1059    DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon,
1060                     qemu_4_0_config_size, false),
1061    DEFINE_PROP_LINK("iothread", VirtIOBalloon, iothread, TYPE_IOTHREAD,
1062                     IOThread *),
1063    DEFINE_PROP_END_OF_LIST(),
1064};
1065
1066static void virtio_balloon_class_init(ObjectClass *klass, void *data)
1067{
1068    DeviceClass *dc = DEVICE_CLASS(klass);
1069    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1070
1071    device_class_set_props(dc, virtio_balloon_properties);
1072    dc->vmsd = &vmstate_virtio_balloon;
1073    set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1074    vdc->realize = virtio_balloon_device_realize;
1075    vdc->unrealize = virtio_balloon_device_unrealize;
1076    vdc->reset = virtio_balloon_device_reset;
1077    vdc->get_config = virtio_balloon_get_config;
1078    vdc->set_config = virtio_balloon_set_config;
1079    vdc->get_features = virtio_balloon_get_features;
1080    vdc->set_status = virtio_balloon_set_status;
1081    vdc->vmsd = &vmstate_virtio_balloon_device;
1082}
1083
1084static const TypeInfo virtio_balloon_info = {
1085    .name = TYPE_VIRTIO_BALLOON,
1086    .parent = TYPE_VIRTIO_DEVICE,
1087    .instance_size = sizeof(VirtIOBalloon),
1088    .instance_init = virtio_balloon_instance_init,
1089    .class_init = virtio_balloon_class_init,
1090};
1091
1092static void virtio_register_types(void)
1093{
1094    type_register_static(&virtio_balloon_info);
1095}
1096
1097type_init(virtio_register_types)
1098