virtio-balloon.c 15.9 KB
Newer Older
A
aliguori 已提交
1
/*
2
 * Virtio Balloon Device
A
aliguori 已提交
3 4
 *
 * Copyright IBM, Corp. 2008
5 6
 * Copyright (C) 2011 Red Hat, Inc.
 * Copyright (C) 2011 Amit Shah <amit.shah@redhat.com>
A
aliguori 已提交
7 8 9 10 11 12 13 14 15
 *
 * Authors:
 *  Anthony Liguori   <aliguori@us.ibm.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
 *
 */

P
Peter Maydell 已提交
16
#include "qemu/osdep.h"
17
#include "qemu/iov.h"
18
#include "qemu/timer.h"
A
aliguori 已提交
19
#include "qemu-common.h"
P
Paolo Bonzini 已提交
20
#include "hw/virtio/virtio.h"
21
#include "hw/mem/pc-dimm.h"
22
#include "sysemu/balloon.h"
P
Paolo Bonzini 已提交
23
#include "hw/virtio/virtio-balloon.h"
24
#include "exec/address-spaces.h"
25
#include "qapi/error.h"
26
#include "qapi/qapi-events-misc.h"
27
#include "qapi/visitor.h"
28
#include "trace.h"
29
#include "qemu/error-report.h"
A
aliguori 已提交
30

P
Paolo Bonzini 已提交
31
#include "hw/virtio/virtio-bus.h"
32
#include "hw/virtio/virtio-access.h"
33

34 35
#define BALLOON_PAGE_SIZE  (1 << VIRTIO_BALLOON_PFN_SHIFT)

A
aliguori 已提交
36 37
static void balloon_page(void *addr, int deflate)
{
38
    if (!qemu_balloon_is_inhibited()) {
39
        qemu_madvise(addr, BALLOON_PAGE_SIZE,
A
Andreas Färber 已提交
40
                deflate ? QEMU_MADV_WILLNEED : QEMU_MADV_DONTNEED);
41
    }
A
aliguori 已提交
42 43
}

44 45 46 47 48 49 50
static const char *balloon_stat_names[] = {
   [VIRTIO_BALLOON_S_SWAP_IN] = "stat-swap-in",
   [VIRTIO_BALLOON_S_SWAP_OUT] = "stat-swap-out",
   [VIRTIO_BALLOON_S_MAJFLT] = "stat-major-faults",
   [VIRTIO_BALLOON_S_MINFLT] = "stat-minor-faults",
   [VIRTIO_BALLOON_S_MEMFREE] = "stat-free-memory",
   [VIRTIO_BALLOON_S_MEMTOT] = "stat-total-memory",
51
   [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
52
   [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
53 54
   [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
   [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
55 56 57
   [VIRTIO_BALLOON_S_NR] = NULL
};

58 59 60
/*
 * reset_stats - Mark all items in the stats array as unset
 *
61 62
 * This function needs to be called at device initialization and before
 * updating to a set of newly-generated stats.  This will ensure that no
63 64 65 66 67 68 69 70 71
 * stale values stick around in case the guest reports a subset of the supported
 * statistics.
 */
static inline void reset_stats(VirtIOBalloon *dev)
{
    int i;
    for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
}

72 73
static bool balloon_stats_supported(const VirtIOBalloon *s)
{
74
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
75
    return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
76 77 78 79 80 81 82 83 84 85
}

static bool balloon_stats_enabled(const VirtIOBalloon *s)
{
    return s->stats_poll_interval > 0;
}

static void balloon_stats_destroy_timer(VirtIOBalloon *s)
{
    if (balloon_stats_enabled(s)) {
86 87
        timer_del(s->stats_timer);
        timer_free(s->stats_timer);
88 89 90 91 92
        s->stats_timer = NULL;
        s->stats_poll_interval = 0;
    }
}

93
static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
94
{
95
    timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
96 97 98 99 100
}

static void balloon_stats_poll_cb(void *opaque)
{
    VirtIOBalloon *s = opaque;
101
    VirtIODevice *vdev = VIRTIO_DEVICE(s);
102

103
    if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
104 105 106 107 108
        /* re-schedule */
        balloon_stats_change_timer(s, s->stats_poll_interval);
        return;
    }

109
    virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
110
    virtio_notify(vdev, s->svq);
111 112
    g_free(s->stats_vq_elem);
    s->stats_vq_elem = NULL;
113 114
}

115 116
static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
                                  void *opaque, Error **errp)
117
{
118
    Error *err = NULL;
119 120 121
    VirtIOBalloon *s = opaque;
    int i;

122
    visit_start_struct(v, name, NULL, 0, &err);
123 124 125
    if (err) {
        goto out;
    }
126
    visit_type_int(v, "last-update", &s->stats_last_update, &err);
127 128 129
    if (err) {
        goto out_end;
    }
130

131
    visit_start_struct(v, "stats", NULL, 0, &err);
132 133 134
    if (err) {
        goto out_end;
    }
135
    for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
136
        visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err);
137
        if (err) {
138
            goto out_nested;
139
        }
140
    }
141 142
    visit_check_struct(v, &err);
out_nested:
E
Eric Blake 已提交
143
    visit_end_struct(v, NULL);
144

145 146 147
    if (!err) {
        visit_check_struct(v, &err);
    }
148
out_end:
E
Eric Blake 已提交
149
    visit_end_struct(v, NULL);
150 151
out:
    error_propagate(errp, err);
152 153
}

E
Eric Blake 已提交
154
static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
155
                                            const char *name, void *opaque,
156 157 158
                                            Error **errp)
{
    VirtIOBalloon *s = opaque;
159
    visit_type_int(v, name, &s->stats_poll_interval, errp);
160 161
}

E
Eric Blake 已提交
162
static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
163
                                            const char *name, void *opaque,
164 165 166
                                            Error **errp)
{
    VirtIOBalloon *s = opaque;
167
    Error *local_err = NULL;
168 169
    int64_t value;

170
    visit_type_int(v, name, &value, &local_err);
171 172
    if (local_err) {
        error_propagate(errp, local_err);
173 174 175 176 177 178 179 180
        return;
    }

    if (value < 0) {
        error_setg(errp, "timer value must be greater than zero");
        return;
    }

181
    if (value > UINT32_MAX) {
182 183 184 185
        error_setg(errp, "timer value is too big");
        return;
    }

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    if (value == s->stats_poll_interval) {
        return;
    }

    if (value == 0) {
        /* timer=0 disables the timer */
        balloon_stats_destroy_timer(s);
        return;
    }

    if (balloon_stats_enabled(s)) {
        /* timer interval change */
        s->stats_poll_interval = value;
        balloon_stats_change_timer(s, value);
        return;
    }

    /* create a new timer */
    g_assert(s->stats_timer == NULL);
205
    s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
206 207 208 209
    s->stats_poll_interval = value;
    balloon_stats_change_timer(s, 0);
}

A
aliguori 已提交
210 211
static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
{
212
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
213
    VirtQueueElement *elem;
214
    MemoryRegionSection section;
A
aliguori 已提交
215

216
    for (;;) {
A
aliguori 已提交
217 218
        size_t offset = 0;
        uint32_t pfn;
219 220 221 222
        elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
        if (!elem) {
            return;
        }
A
aliguori 已提交
223

224
        while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
A
Anthony Liguori 已提交
225 226
            ram_addr_t pa;
            ram_addr_t addr;
227
            int p = virtio_ldl_p(vdev, &pfn);
A
aliguori 已提交
228

229
            pa = (ram_addr_t) p << VIRTIO_BALLOON_PFN_SHIFT;
A
aliguori 已提交
230 231
            offset += 4;

232 233
            /* FIXME: remove get_system_memory(), but how? */
            section = memory_region_find(get_system_memory(), pa, 1);
234 235 236 237 238
            if (!int128_nz(section.size) ||
                !memory_region_is_ram(section.mr) ||
                memory_region_is_rom(section.mr) ||
                memory_region_is_romd(section.mr)) {
                trace_virtio_balloon_bad_addr(pa);
239
                memory_region_unref(section.mr);
A
aliguori 已提交
240
                continue;
241
            }
A
aliguori 已提交
242

243 244
            trace_virtio_balloon_handle_output(memory_region_name(section.mr),
                                               pa);
245
            /* Using memory_region_get_ram_ptr is bending the rules a bit, but
P
pbrook 已提交
246
               should be OK because we only want a single page.  */
247 248 249
            addr = section.offset_within_region;
            balloon_page(memory_region_get_ram_ptr(section.mr) + addr,
                         !!(vq == s->dvq));
P
Paolo Bonzini 已提交
250
            memory_region_unref(section.mr);
A
aliguori 已提交
251 252
        }

253
        virtqueue_push(vq, elem, offset);
A
aliguori 已提交
254
        virtio_notify(vdev, vq);
255
        g_free(elem);
A
aliguori 已提交
256 257 258
    }
}

259 260
static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
{
261
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
262
    VirtQueueElement *elem;
263 264
    VirtIOBalloonStat stat;
    size_t offset = 0;
265
    qemu_timeval tv;
266

267
    elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
268
    if (!elem) {
269
        goto out;
270 271
    }

272 273 274 275 276 277 278 279 280
    if (s->stats_vq_elem != NULL) {
        /* This should never happen if the driver follows the spec. */
        virtqueue_push(vq, s->stats_vq_elem, 0);
        virtio_notify(vdev, vq);
        g_free(s->stats_vq_elem);
    }

    s->stats_vq_elem = elem;

281 282 283 284 285 286
    /* Initialize the stats to get rid of any stale values.  This is only
     * needed to handle the case where a guest supports fewer stats than it
     * used to (ie. it has booted into an old kernel).
     */
    reset_stats(s);

287
    while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
288
           == sizeof(stat)) {
289 290
        uint16_t tag = virtio_tswap16(vdev, stat.tag);
        uint64_t val = virtio_tswap64(vdev, stat.val);
291 292 293 294 295 296

        offset += sizeof(stat);
        if (tag < VIRTIO_BALLOON_S_NR)
            s->stats[tag] = val;
    }
    s->stats_vq_offset = offset;
297 298

    if (qemu_gettimeofday(&tv) < 0) {
299
        warn_report("%s: failed to get time of day", __func__);
300 301 302 303 304 305 306 307 308
        goto out;
    }

    s->stats_last_update = tv.tv_sec;

out:
    if (balloon_stats_enabled(s)) {
        balloon_stats_change_timer(s, s->stats_poll_interval);
    }
309 310
}

A
aliguori 已提交
311 312
static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
{
313
    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
A
aliguori 已提交
314 315 316 317 318
    struct virtio_balloon_config config;

    config.num_pages = cpu_to_le32(dev->num_pages);
    config.actual = cpu_to_le32(dev->actual);

319
    trace_virtio_balloon_get_config(config.num_pages, config.actual);
320
    memcpy(config_data, &config, sizeof(struct virtio_balloon_config));
A
aliguori 已提交
321 322
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
static int build_dimm_list(Object *obj, void *opaque)
{
    GSList **list = opaque;

    if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
        DeviceState *dev = DEVICE(obj);
        if (dev->realized) { /* only realized DIMMs matter */
            *list = g_slist_prepend(*list, dev);
        }
    }

    object_child_foreach(obj, build_dimm_list, opaque);
    return 0;
}

338 339
static ram_addr_t get_current_ram_size(void)
{
340
    GSList *list = NULL, *item;
341 342
    ram_addr_t size = ram_size;

343
    build_dimm_list(qdev_get_machine(), &list);
344 345
    for (item = list; item; item = g_slist_next(item)) {
        Object *obj = OBJECT(item->data);
346 347 348 349
        if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
            size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
                                            &error_abort);
        }
350
    }
351
    g_slist_free(list);
352 353 354 355

    return size;
}

A
aliguori 已提交
356 357 358
static void virtio_balloon_set_config(VirtIODevice *vdev,
                                      const uint8_t *config_data)
{
359
    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
A
aliguori 已提交
360
    struct virtio_balloon_config config;
361
    uint32_t oldactual = dev->actual;
362 363
    ram_addr_t vm_ram_size = get_current_ram_size();

364
    memcpy(&config, config_data, sizeof(struct virtio_balloon_config));
365
    dev->actual = le32_to_cpu(config.actual);
366
    if (dev->actual != oldactual) {
367
        qapi_event_send_balloon_change(vm_ram_size -
368
                        ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
369
    }
370
    trace_virtio_balloon_set_config(dev->actual, oldactual);
A
aliguori 已提交
371 372
}

J
Jason Wang 已提交
373 374
static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
                                            Error **errp)
A
aliguori 已提交
375
{
376 377
    VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
    f |= dev->host_features;
378
    virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
379
    return f;
A
aliguori 已提交
380 381
}

L
Luiz Capitulino 已提交
382
static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
383 384
{
    VirtIOBalloon *dev = opaque;
385 386
    info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
                                             VIRTIO_BALLOON_PFN_SHIFT);
387 388
}

389
static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
A
aliguori 已提交
390
{
391 392
    VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
393
    ram_addr_t vm_ram_size = get_current_ram_size();
A
aliguori 已提交
394

395 396
    if (target > vm_ram_size) {
        target = vm_ram_size;
397
    }
A
aliguori 已提交
398
    if (target) {
399
        dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
400
        virtio_notify_config(vdev);
A
aliguori 已提交
401
    }
402
    trace_virtio_balloon_to_target(target, dev->num_pages);
A
aliguori 已提交
403 404
}

405
static int virtio_balloon_post_load_device(void *opaque, int version_id)
406
{
407
    VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
408 409 410 411

    if (balloon_stats_enabled(s)) {
        balloon_stats_change_timer(s, s->stats_poll_interval);
    }
A
aliguori 已提交
412 413 414
    return 0;
}

415 416 417 418 419 420 421 422 423 424 425 426
static const VMStateDescription vmstate_virtio_balloon_device = {
    .name = "virtio-balloon-device",
    .version_id = 1,
    .minimum_version_id = 1,
    .post_load = virtio_balloon_post_load_device,
    .fields = (VMStateField[]) {
        VMSTATE_UINT32(num_pages, VirtIOBalloon),
        VMSTATE_UINT32(actual, VirtIOBalloon),
        VMSTATE_END_OF_LIST()
    },
};

427
static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
A
aliguori 已提交
428
{
429
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
430
    VirtIOBalloon *s = VIRTIO_BALLOON(dev);
431
    int ret;
A
aliguori 已提交
432

433 434
    virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
                sizeof(struct virtio_balloon_config));
A
aliguori 已提交
435

436 437
    ret = qemu_add_balloon_handler(virtio_balloon_to_target,
                                   virtio_balloon_stat, s);
438

439
    if (ret < 0) {
440
        error_setg(errp, "Only one balloon device is supported");
441
        virtio_cleanup(vdev);
442
        return;
443
    }
444

445 446 447
    s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
    s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
    s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
A
aliguori 已提交
448

449
    reset_stats(s);
450 451
}

452
static void virtio_balloon_device_unrealize(DeviceState *dev, Error **errp)
453
{
454 455
    VirtIODevice *vdev = VIRTIO_DEVICE(dev);
    VirtIOBalloon *s = VIRTIO_BALLOON(dev);
456 457 458

    balloon_stats_destroy_timer(s);
    qemu_remove_balloon_handler(s);
459
    virtio_cleanup(vdev);
460 461
}

462 463 464 465 466
static void virtio_balloon_device_reset(VirtIODevice *vdev)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);

    if (s->stats_vq_elem != NULL) {
467
        virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
468 469 470 471 472
        g_free(s->stats_vq_elem);
        s->stats_vq_elem = NULL;
    }
}

473 474 475 476 477 478 479 480 481 482 483 484
static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(vdev);

    if (!s->stats_vq_elem && vdev->vm_running &&
        (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
        /* poll stats queue for the element we have discarded when the VM
         * was stopped */
        virtio_balloon_receive_stats(vdev, s->svq);
    }
}

485 486 487 488 489 490 491 492 493 494 495 496 497
static void virtio_balloon_instance_init(Object *obj)
{
    VirtIOBalloon *s = VIRTIO_BALLOON(obj);

    object_property_add(obj, "guest-stats", "guest statistics",
                        balloon_stats_get_all, NULL, NULL, s, NULL);

    object_property_add(obj, "guest-stats-polling-interval", "int",
                        balloon_stats_get_poll_interval,
                        balloon_stats_set_poll_interval,
                        NULL, s, NULL);
}

498 499 500 501 502 503 504 505 506
static const VMStateDescription vmstate_virtio_balloon = {
    .name = "virtio-balloon",
    .minimum_version_id = 1,
    .version_id = 1,
    .fields = (VMStateField[]) {
        VMSTATE_VIRTIO_DEVICE,
        VMSTATE_END_OF_LIST()
    },
};
507

508
static Property virtio_balloon_properties[] = {
509 510
    DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
                    VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
511 512 513 514 515 516 517
    DEFINE_PROP_END_OF_LIST(),
};

static void virtio_balloon_class_init(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);
    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
518

519
    dc->props = virtio_balloon_properties;
520
    dc->vmsd = &vmstate_virtio_balloon;
521
    set_bit(DEVICE_CATEGORY_MISC, dc->categories);
522
    vdc->realize = virtio_balloon_device_realize;
523
    vdc->unrealize = virtio_balloon_device_unrealize;
524
    vdc->reset = virtio_balloon_device_reset;
525 526 527
    vdc->get_config = virtio_balloon_get_config;
    vdc->set_config = virtio_balloon_set_config;
    vdc->get_features = virtio_balloon_get_features;
528
    vdc->set_status = virtio_balloon_set_status;
529
    vdc->vmsd = &vmstate_virtio_balloon_device;
530 531 532 533 534 535
}

static const TypeInfo virtio_balloon_info = {
    .name = TYPE_VIRTIO_BALLOON,
    .parent = TYPE_VIRTIO_DEVICE,
    .instance_size = sizeof(VirtIOBalloon),
536
    .instance_init = virtio_balloon_instance_init,
537 538 539 540 541 542 543 544 545
    .class_init = virtio_balloon_class_init,
};

static void virtio_register_types(void)
{
    type_register_static(&virtio_balloon_info);
}

type_init(virtio_register_types)