]> git.ipfire.org Git - thirdparty/qemu.git/blame - hw/virtio/virtio-balloon.c
qdev: set properties with device_class_set_props()
[thirdparty/qemu.git] / hw / virtio / virtio-balloon.c
CommitLineData
bd322087 1/*
d4443cb6 2 * Virtio Balloon Device
bd322087
AL
3 *
4 * Copyright IBM, Corp. 2008
d4443cb6
AS
5 * Copyright (C) 2011 Red Hat, Inc.
6 * Copyright (C) 2011 Amit Shah <amit.shah@redhat.com>
bd322087
AL
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
9b8bfe21 16#include "qemu/osdep.h"
1de7afc9 17#include "qemu/iov.h"
0b8fa32f 18#include "qemu/module.h"
7e6ccd9c 19#include "qemu/timer.h"
0d09e41a 20#include "hw/virtio/virtio.h"
2070aaeb 21#include "hw/mem/pc-dimm.h"
a27bd6c7 22#include "hw/qdev-properties.h"
9c17d615 23#include "sysemu/balloon.h"
0d09e41a 24#include "hw/virtio/virtio-balloon.h"
022c62cb 25#include "exec/address-spaces.h"
e688df6b 26#include "qapi/error.h"
112ed241 27#include "qapi/qapi-events-misc.h"
7e6ccd9c 28#include "qapi/visitor.h"
6adfdc5a 29#include "trace.h"
2ab4b135 30#include "qemu/error-report.h"
c13c4153 31#include "migration/misc.h"
bd322087 32
0d09e41a 33#include "hw/virtio/virtio-bus.h"
8609d2a8 34#include "hw/virtio/virtio-access.h"
1ab461b5 35
01310e2a
TH
36#define BALLOON_PAGE_SIZE (1 << VIRTIO_BALLOON_PFN_SHIFT)
37
a8cd64d4 38typedef struct PartiallyBalloonedPage {
1c5cfc2b 39 ram_addr_t base_gpa;
1c5cfc2b 40 unsigned long *bitmap;
a8cd64d4 41} PartiallyBalloonedPage;
ed48c598 42
1c5cfc2b
DH
43static void virtio_balloon_pbp_free(PartiallyBalloonedPage *pbp)
44{
1b47b37c 45 if (!pbp->bitmap) {
1c5cfc2b
DH
46 return;
47 }
48 g_free(pbp->bitmap);
1b47b37c 49 pbp->bitmap = NULL;
1c5cfc2b
DH
50}
51
1b47b37c
MT
52static void virtio_balloon_pbp_alloc(PartiallyBalloonedPage *pbp,
53 ram_addr_t base_gpa,
54 long subpages)
1c5cfc2b 55{
1c5cfc2b 56 pbp->base_gpa = base_gpa;
1c5cfc2b 57 pbp->bitmap = bitmap_new(subpages);
1c5cfc2b
DH
58}
59
60static bool virtio_balloon_pbp_matches(PartiallyBalloonedPage *pbp,
9a7ca8a7 61 ram_addr_t base_gpa)
1c5cfc2b 62{
9a7ca8a7 63 return pbp->base_gpa == base_gpa;
1c5cfc2b
DH
64}
65
e9550234 66static void balloon_inflate_page(VirtIOBalloon *balloon,
a8cd64d4 67 MemoryRegion *mr, hwaddr mr_offset,
1b47b37c 68 PartiallyBalloonedPage *pbp)
bd322087 69{
e6129b27 70 void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
1c5cfc2b 71 ram_addr_t rb_offset, rb_aligned_offset, base_gpa;
dbe1a277
DG
72 RAMBlock *rb;
73 size_t rb_page_size;
ed48c598 74 int subpages;
e9550234 75
dbe1a277
DG
76 /* XXX is there a better way to get to the RAMBlock than via a
77 * host address? */
e6129b27 78 rb = qemu_ram_block_from_host(addr, false, &rb_offset);
dbe1a277 79 rb_page_size = qemu_ram_pagesize(rb);
ed48c598
DG
80
81 if (rb_page_size == BALLOON_PAGE_SIZE) {
82 /* Easy case */
dbe1a277 83
e6129b27 84 ram_block_discard_range(rb, rb_offset, rb_page_size);
ed48c598
DG
85 /* We ignore errors from ram_block_discard_range(), because it
86 * has already reported them, and failing to discard a balloon
87 * page is not fatal */
dbe1a277
DG
88 return;
89 }
90
ed48c598
DG
91 /* Hard case
92 *
93 * We've put a piece of a larger host page into the balloon - we
94 * need to keep track until we have a whole host page to
95 * discard
96 */
97 warn_report_once(
98"Balloon used with backing page size > 4kiB, this may not be reliable");
99
e6129b27 100 rb_aligned_offset = QEMU_ALIGN_DOWN(rb_offset, rb_page_size);
ed48c598 101 subpages = rb_page_size / BALLOON_PAGE_SIZE;
1c5cfc2b
DH
102 base_gpa = memory_region_get_ram_addr(mr) + mr_offset -
103 (rb_offset - rb_aligned_offset);
ed48c598 104
1b47b37c 105 if (pbp->bitmap && !virtio_balloon_pbp_matches(pbp, base_gpa)) {
ed48c598
DG
106 /* We've partially ballooned part of a host page, but now
107 * we're trying to balloon part of a different one. Too hard,
108 * give up on the old partial page */
1b47b37c 109 virtio_balloon_pbp_free(pbp);
dbe1a277
DG
110 }
111
1b47b37c
MT
112 if (!pbp->bitmap) {
113 virtio_balloon_pbp_alloc(pbp, base_gpa, subpages);
ed48c598
DG
114 }
115
1c5cfc2b 116 set_bit((rb_offset - rb_aligned_offset) / BALLOON_PAGE_SIZE,
1b47b37c 117 pbp->bitmap);
ed48c598 118
1b47b37c 119 if (bitmap_full(pbp->bitmap, subpages)) {
ed48c598
DG
120 /* We've accumulated a full host page, we can actually discard
121 * it now */
122
1c5cfc2b 123 ram_block_discard_range(rb, rb_aligned_offset, rb_page_size);
ed48c598
DG
124 /* We ignore errors from ram_block_discard_range(), because it
125 * has already reported them, and failing to discard a balloon
126 * page is not fatal */
1b47b37c 127 virtio_balloon_pbp_free(pbp);
ed48c598 128 }
bd322087
AL
129}
130
b27b3239 131static void balloon_deflate_page(VirtIOBalloon *balloon,
e6129b27 132 MemoryRegion *mr, hwaddr mr_offset)
b27b3239 133{
e6129b27
DH
134 void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
135 ram_addr_t rb_offset;
b27b3239
DG
136 RAMBlock *rb;
137 size_t rb_page_size;
596546fe
DG
138 void *host_addr;
139 int ret;
b27b3239
DG
140
141 /* XXX is there a better way to get to the RAMBlock than via a
142 * host address? */
e6129b27 143 rb = qemu_ram_block_from_host(addr, false, &rb_offset);
b27b3239 144 rb_page_size = qemu_ram_pagesize(rb);
b27b3239 145
596546fe
DG
146 host_addr = (void *)((uintptr_t)addr & ~(rb_page_size - 1));
147
148 /* When a page is deflated, we hint the whole host page it lives
149 * on, since we can't do anything smaller */
150 ret = qemu_madvise(host_addr, rb_page_size, QEMU_MADV_WILLNEED);
151 if (ret != 0) {
152 warn_report("Couldn't MADV_WILLNEED on balloon deflate: %s",
153 strerror(errno));
154 /* Otherwise ignore, failing to page hint shouldn't be fatal */
155 }
b27b3239
DG
156}
157
7e6ccd9c
LC
158static const char *balloon_stat_names[] = {
159 [VIRTIO_BALLOON_S_SWAP_IN] = "stat-swap-in",
160 [VIRTIO_BALLOON_S_SWAP_OUT] = "stat-swap-out",
161 [VIRTIO_BALLOON_S_MAJFLT] = "stat-major-faults",
162 [VIRTIO_BALLOON_S_MINFLT] = "stat-minor-faults",
163 [VIRTIO_BALLOON_S_MEMFREE] = "stat-free-memory",
164 [VIRTIO_BALLOON_S_MEMTOT] = "stat-total-memory",
a0d06486 165 [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
bf1e7140 166 [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
b7b12644
JH
167 [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
168 [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
7e6ccd9c
LC
169 [VIRTIO_BALLOON_S_NR] = NULL
170};
171
625a5bef
AL
172/*
173 * reset_stats - Mark all items in the stats array as unset
174 *
52f35022
SW
175 * This function needs to be called at device initialization and before
176 * updating to a set of newly-generated stats. This will ensure that no
625a5bef
AL
177 * stale values stick around in case the guest reports a subset of the supported
178 * statistics.
179 */
180static inline void reset_stats(VirtIOBalloon *dev)
181{
182 int i;
183 for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
184}
185
7e6ccd9c
LC
186static bool balloon_stats_supported(const VirtIOBalloon *s)
187{
c96caced 188 VirtIODevice *vdev = VIRTIO_DEVICE(s);
95129d6f 189 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
7e6ccd9c
LC
190}
191
192static bool balloon_stats_enabled(const VirtIOBalloon *s)
193{
194 return s->stats_poll_interval > 0;
195}
196
197static void balloon_stats_destroy_timer(VirtIOBalloon *s)
198{
199 if (balloon_stats_enabled(s)) {
bc72ad67
AB
200 timer_del(s->stats_timer);
201 timer_free(s->stats_timer);
7e6ccd9c
LC
202 s->stats_timer = NULL;
203 s->stats_poll_interval = 0;
204 }
205}
206
1f9296b5 207static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
7e6ccd9c 208{
bc72ad67 209 timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
7e6ccd9c
LC
210}
211
212static void balloon_stats_poll_cb(void *opaque)
213{
214 VirtIOBalloon *s = opaque;
c96caced 215 VirtIODevice *vdev = VIRTIO_DEVICE(s);
7e6ccd9c 216
4eae2a65 217 if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
7e6ccd9c
LC
218 /* re-schedule */
219 balloon_stats_change_timer(s, s->stats_poll_interval);
220 return;
221 }
222
51b19ebe 223 virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
c96caced 224 virtio_notify(vdev, s->svq);
51b19ebe
PB
225 g_free(s->stats_vq_elem);
226 s->stats_vq_elem = NULL;
7e6ccd9c
LC
227}
228
d7bce999
EB
229static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
230 void *opaque, Error **errp)
7e6ccd9c 231{
2ddb16a9 232 Error *err = NULL;
7e6ccd9c
LC
233 VirtIOBalloon *s = opaque;
234 int i;
235
337283df 236 visit_start_struct(v, name, NULL, 0, &err);
2ddb16a9
MA
237 if (err) {
238 goto out;
239 }
51e72bc1 240 visit_type_int(v, "last-update", &s->stats_last_update, &err);
297a3646
MA
241 if (err) {
242 goto out_end;
243 }
7e6ccd9c 244
337283df 245 visit_start_struct(v, "stats", NULL, 0, &err);
2ddb16a9
MA
246 if (err) {
247 goto out_end;
248 }
9dbb8fa7 249 for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
51e72bc1 250 visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err);
9dbb8fa7 251 if (err) {
15c2f669 252 goto out_nested;
9dbb8fa7 253 }
7e6ccd9c 254 }
15c2f669
EB
255 visit_check_struct(v, &err);
256out_nested:
1158bb2a 257 visit_end_struct(v, NULL);
2ddb16a9 258
15c2f669
EB
259 if (!err) {
260 visit_check_struct(v, &err);
261 }
2ddb16a9 262out_end:
1158bb2a 263 visit_end_struct(v, NULL);
2ddb16a9
MA
264out:
265 error_propagate(errp, err);
7e6ccd9c
LC
266}
267
4fa45492 268static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
d7bce999 269 const char *name, void *opaque,
7e6ccd9c
LC
270 Error **errp)
271{
272 VirtIOBalloon *s = opaque;
51e72bc1 273 visit_type_int(v, name, &s->stats_poll_interval, errp);
7e6ccd9c
LC
274}
275
4fa45492 276static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
d7bce999 277 const char *name, void *opaque,
7e6ccd9c
LC
278 Error **errp)
279{
280 VirtIOBalloon *s = opaque;
65cd9064 281 Error *local_err = NULL;
7e6ccd9c
LC
282 int64_t value;
283
51e72bc1 284 visit_type_int(v, name, &value, &local_err);
65cd9064
MA
285 if (local_err) {
286 error_propagate(errp, local_err);
7e6ccd9c
LC
287 return;
288 }
289
290 if (value < 0) {
291 error_setg(errp, "timer value must be greater than zero");
292 return;
293 }
294
22644cd2 295 if (value > UINT32_MAX) {
1f9296b5
LC
296 error_setg(errp, "timer value is too big");
297 return;
298 }
299
7e6ccd9c
LC
300 if (value == s->stats_poll_interval) {
301 return;
302 }
303
304 if (value == 0) {
305 /* timer=0 disables the timer */
306 balloon_stats_destroy_timer(s);
307 return;
308 }
309
310 if (balloon_stats_enabled(s)) {
311 /* timer interval change */
312 s->stats_poll_interval = value;
313 balloon_stats_change_timer(s, value);
314 return;
315 }
316
317 /* create a new timer */
318 g_assert(s->stats_timer == NULL);
bc72ad67 319 s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
7e6ccd9c
LC
320 s->stats_poll_interval = value;
321 balloon_stats_change_timer(s, 0);
322}
323
bd322087
AL
324static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
325{
c96caced 326 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
51b19ebe 327 VirtQueueElement *elem;
b7c28c74 328 MemoryRegionSection section;
bd322087 329
51b19ebe 330 for (;;) {
1b47b37c 331 PartiallyBalloonedPage pbp = {};
bd322087
AL
332 size_t offset = 0;
333 uint32_t pfn;
1b47b37c 334
51b19ebe
PB
335 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
336 if (!elem) {
a8cd64d4 337 break;
51b19ebe 338 }
bd322087 339
51b19ebe 340 while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
ffa207d0 341 unsigned int p = virtio_ldl_p(vdev, &pfn);
b218a70e 342 hwaddr pa;
bd322087 343
b218a70e 344 pa = (hwaddr) p << VIRTIO_BALLOON_PFN_SHIFT;
bd322087
AL
345 offset += 4;
346
b218a70e
DG
347 section = memory_region_find(get_system_memory(), pa,
348 BALLOON_PAGE_SIZE);
349 if (!section.mr) {
350 trace_virtio_balloon_bad_addr(pa);
351 continue;
352 }
353 if (!memory_region_is_ram(section.mr) ||
f2fd57db
DDAG
354 memory_region_is_rom(section.mr) ||
355 memory_region_is_romd(section.mr)) {
356 trace_virtio_balloon_bad_addr(pa);
b86107ab 357 memory_region_unref(section.mr);
bd322087 358 continue;
f2fd57db 359 }
bd322087 360
6adfdc5a
HZ
361 trace_virtio_balloon_handle_output(memory_region_name(section.mr),
362 pa);
b27b3239
DG
363 if (!qemu_balloon_is_inhibited()) {
364 if (vq == s->ivq) {
365 balloon_inflate_page(s, section.mr,
a8cd64d4 366 section.offset_within_region, &pbp);
b27b3239
DG
367 } else if (vq == s->dvq) {
368 balloon_deflate_page(s, section.mr, section.offset_within_region);
369 } else {
370 g_assert_not_reached();
371 }
e9550234 372 }
dfde4e6e 373 memory_region_unref(section.mr);
bd322087
AL
374 }
375
51b19ebe 376 virtqueue_push(vq, elem, offset);
bd322087 377 virtio_notify(vdev, vq);
51b19ebe 378 g_free(elem);
1b47b37c 379 virtio_balloon_pbp_free(&pbp);
bd322087
AL
380 }
381}
382
625a5bef
AL
383static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
384{
c96caced 385 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
51b19ebe 386 VirtQueueElement *elem;
625a5bef
AL
387 VirtIOBalloonStat stat;
388 size_t offset = 0;
7e6ccd9c 389 qemu_timeval tv;
625a5bef 390
4eae2a65 391 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
51b19ebe 392 if (!elem) {
7e6ccd9c 393 goto out;
625a5bef
AL
394 }
395
4eae2a65
LP
396 if (s->stats_vq_elem != NULL) {
397 /* This should never happen if the driver follows the spec. */
398 virtqueue_push(vq, s->stats_vq_elem, 0);
399 virtio_notify(vdev, vq);
400 g_free(s->stats_vq_elem);
401 }
402
403 s->stats_vq_elem = elem;
404
625a5bef
AL
405 /* Initialize the stats to get rid of any stale values. This is only
406 * needed to handle the case where a guest supports fewer stats than it
407 * used to (ie. it has booted into an old kernel).
408 */
409 reset_stats(s);
410
dcf6f5e1 411 while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
fa6111f2 412 == sizeof(stat)) {
8609d2a8
RR
413 uint16_t tag = virtio_tswap16(vdev, stat.tag);
414 uint64_t val = virtio_tswap64(vdev, stat.val);
625a5bef
AL
415
416 offset += sizeof(stat);
417 if (tag < VIRTIO_BALLOON_S_NR)
418 s->stats[tag] = val;
419 }
420 s->stats_vq_offset = offset;
7e6ccd9c
LC
421
422 if (qemu_gettimeofday(&tv) < 0) {
2ab4b135 423 warn_report("%s: failed to get time of day", __func__);
7e6ccd9c
LC
424 goto out;
425 }
426
427 s->stats_last_update = tv.tv_sec;
428
429out:
430 if (balloon_stats_enabled(s)) {
431 balloon_stats_change_timer(s, s->stats_poll_interval);
432 }
625a5bef
AL
433}
434
c13c4153
WW
435static void virtio_balloon_handle_free_page_vq(VirtIODevice *vdev,
436 VirtQueue *vq)
437{
438 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
439 qemu_bh_schedule(s->free_page_bh);
440}
441
442static bool get_free_page_hints(VirtIOBalloon *dev)
443{
444 VirtQueueElement *elem;
445 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
446 VirtQueue *vq = dev->free_page_vq;
ae440bd1 447 bool ret = true;
c13c4153
WW
448
449 while (dev->block_iothread) {
450 qemu_cond_wait(&dev->free_page_cond, &dev->free_page_lock);
451 }
452
453 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
454 if (!elem) {
455 return false;
456 }
457
458 if (elem->out_num) {
459 uint32_t id;
460 size_t size = iov_to_buf(elem->out_sg, elem->out_num, 0,
461 &id, sizeof(id));
c13c4153
WW
462
463 virtio_tswap32s(vdev, &id);
464 if (unlikely(size != sizeof(id))) {
465 virtio_error(vdev, "received an incorrect cmd id");
ae440bd1
WW
466 ret = false;
467 goto out;
c13c4153
WW
468 }
469 if (id == dev->free_page_report_cmd_id) {
470 dev->free_page_report_status = FREE_PAGE_REPORT_S_START;
471 } else {
472 /*
473 * Stop the optimization only when it has started. This
474 * avoids a stale stop sign for the previous command.
475 */
476 if (dev->free_page_report_status == FREE_PAGE_REPORT_S_START) {
477 dev->free_page_report_status = FREE_PAGE_REPORT_S_STOP;
478 }
479 }
480 }
481
482 if (elem->in_num) {
483 if (dev->free_page_report_status == FREE_PAGE_REPORT_S_START) {
484 qemu_guest_free_page_hint(elem->in_sg[0].iov_base,
485 elem->in_sg[0].iov_len);
486 }
c13c4153
WW
487 }
488
ae440bd1
WW
489out:
490 virtqueue_push(vq, elem, 1);
491 g_free(elem);
492 return ret;
c13c4153
WW
493}
494
495static void virtio_ballloon_get_free_page_hints(void *opaque)
496{
497 VirtIOBalloon *dev = opaque;
498 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
499 VirtQueue *vq = dev->free_page_vq;
500 bool continue_to_get_hints;
501
502 do {
503 qemu_mutex_lock(&dev->free_page_lock);
504 virtio_queue_set_notification(vq, 0);
505 continue_to_get_hints = get_free_page_hints(dev);
506 qemu_mutex_unlock(&dev->free_page_lock);
507 virtio_notify(vdev, vq);
508 /*
509 * Start to poll the vq once the reporting started. Otherwise, continue
510 * only when there are entries on the vq, which need to be given back.
511 */
512 } while (continue_to_get_hints ||
513 dev->free_page_report_status == FREE_PAGE_REPORT_S_START);
514 virtio_queue_set_notification(vq, 1);
515}
516
517static bool virtio_balloon_free_page_support(void *opaque)
518{
519 VirtIOBalloon *s = opaque;
520 VirtIODevice *vdev = VIRTIO_DEVICE(s);
521
522 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT);
523}
524
525static void virtio_balloon_free_page_start(VirtIOBalloon *s)
526{
527 VirtIODevice *vdev = VIRTIO_DEVICE(s);
528
529 /* For the stop and copy phase, we don't need to start the optimization */
530 if (!vdev->vm_running) {
531 return;
532 }
533
534 if (s->free_page_report_cmd_id == UINT_MAX) {
535 s->free_page_report_cmd_id =
536 VIRTIO_BALLOON_FREE_PAGE_REPORT_CMD_ID_MIN;
537 } else {
538 s->free_page_report_cmd_id++;
539 }
540
541 s->free_page_report_status = FREE_PAGE_REPORT_S_REQUESTED;
542 virtio_notify_config(vdev);
543}
544
545static void virtio_balloon_free_page_stop(VirtIOBalloon *s)
546{
547 VirtIODevice *vdev = VIRTIO_DEVICE(s);
548
549 if (s->free_page_report_status != FREE_PAGE_REPORT_S_STOP) {
550 /*
551 * The lock also guarantees us that the
552 * virtio_ballloon_get_free_page_hints exits after the
553 * free_page_report_status is set to S_STOP.
554 */
555 qemu_mutex_lock(&s->free_page_lock);
556 /*
557 * The guest hasn't done the reporting, so host sends a notification
558 * to the guest to actively stop the reporting.
559 */
560 s->free_page_report_status = FREE_PAGE_REPORT_S_STOP;
561 qemu_mutex_unlock(&s->free_page_lock);
562 virtio_notify_config(vdev);
563 }
564}
565
566static void virtio_balloon_free_page_done(VirtIOBalloon *s)
567{
568 VirtIODevice *vdev = VIRTIO_DEVICE(s);
569
570 s->free_page_report_status = FREE_PAGE_REPORT_S_DONE;
571 virtio_notify_config(vdev);
572}
573
574static int
575virtio_balloon_free_page_report_notify(NotifierWithReturn *n, void *data)
576{
577 VirtIOBalloon *dev = container_of(n, VirtIOBalloon,
578 free_page_report_notify);
579 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
580 PrecopyNotifyData *pnd = data;
581
582 if (!virtio_balloon_free_page_support(dev)) {
583 /*
584 * This is an optimization provided to migration, so just return 0 to
585 * have the normal migration process not affected when this feature is
586 * not supported.
587 */
588 return 0;
589 }
590
591 switch (pnd->reason) {
592 case PRECOPY_NOTIFY_SETUP:
593 precopy_enable_free_page_optimization();
594 break;
595 case PRECOPY_NOTIFY_COMPLETE:
596 case PRECOPY_NOTIFY_CLEANUP:
597 case PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC:
598 virtio_balloon_free_page_stop(dev);
599 break;
600 case PRECOPY_NOTIFY_AFTER_BITMAP_SYNC:
601 if (vdev->vm_running) {
602 virtio_balloon_free_page_start(dev);
603 } else {
604 virtio_balloon_free_page_done(dev);
605 }
606 break;
607 default:
608 virtio_error(vdev, "%s: %d reason unknown", __func__, pnd->reason);
609 }
610
611 return 0;
612}
613
2bbadb08
SH
614static size_t virtio_balloon_config_size(VirtIOBalloon *s)
615{
616 uint64_t features = s->host_features;
617
618 if (s->qemu_4_0_config_size) {
619 return sizeof(struct virtio_balloon_config);
620 }
621 if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON)) {
622 return sizeof(struct virtio_balloon_config);
623 }
624 if (virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
625 return offsetof(struct virtio_balloon_config, poison_val);
626 }
627 return offsetof(struct virtio_balloon_config, free_page_report_cmd_id);
628}
629
bd322087
AL
630static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
631{
c96caced 632 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
5385a598 633 struct virtio_balloon_config config = {};
bd322087
AL
634
635 config.num_pages = cpu_to_le32(dev->num_pages);
636 config.actual = cpu_to_le32(dev->actual);
637
c13c4153
WW
638 if (dev->free_page_report_status == FREE_PAGE_REPORT_S_REQUESTED) {
639 config.free_page_report_cmd_id =
640 cpu_to_le32(dev->free_page_report_cmd_id);
641 } else if (dev->free_page_report_status == FREE_PAGE_REPORT_S_STOP) {
642 config.free_page_report_cmd_id =
643 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_STOP);
644 } else if (dev->free_page_report_status == FREE_PAGE_REPORT_S_DONE) {
645 config.free_page_report_cmd_id =
646 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_DONE);
647 }
648
6adfdc5a 649 trace_virtio_balloon_get_config(config.num_pages, config.actual);
2bbadb08 650 memcpy(config_data, &config, virtio_balloon_config_size(dev));
bd322087
AL
651}
652
2b75f848
VSO
653static int build_dimm_list(Object *obj, void *opaque)
654{
655 GSList **list = opaque;
656
657 if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
658 DeviceState *dev = DEVICE(obj);
659 if (dev->realized) { /* only realized DIMMs matter */
660 *list = g_slist_prepend(*list, dev);
661 }
662 }
663
664 object_child_foreach(obj, build_dimm_list, opaque);
665 return 0;
666}
667
39de9984
VSO
668static ram_addr_t get_current_ram_size(void)
669{
e8dc06d2 670 GSList *list = NULL, *item;
39de9984
VSO
671 ram_addr_t size = ram_size;
672
2b75f848 673 build_dimm_list(qdev_get_machine(), &list);
e8dc06d2
VSO
674 for (item = list; item; item = g_slist_next(item)) {
675 Object *obj = OBJECT(item->data);
2b75f848
VSO
676 if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
677 size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
678 &error_abort);
679 }
39de9984 680 }
e8dc06d2 681 g_slist_free(list);
39de9984
VSO
682
683 return size;
684}
685
bd322087
AL
686static void virtio_balloon_set_config(VirtIODevice *vdev,
687 const uint8_t *config_data)
688{
c96caced 689 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
bd322087 690 struct virtio_balloon_config config;
973603a8 691 uint32_t oldactual = dev->actual;
463756d0
HZ
692 ram_addr_t vm_ram_size = get_current_ram_size();
693
2bbadb08 694 memcpy(&config, config_data, virtio_balloon_config_size(dev));
e54f1771 695 dev->actual = le32_to_cpu(config.actual);
973603a8 696 if (dev->actual != oldactual) {
463756d0 697 qapi_event_send_balloon_change(vm_ram_size -
3ab72385 698 ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
973603a8 699 }
6adfdc5a 700 trace_virtio_balloon_set_config(dev->actual, oldactual);
bd322087
AL
701}
702
9d5b731d
JW
703static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
704 Error **errp)
bd322087 705{
e3816255
DL
706 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
707 f |= dev->host_features;
40de55af 708 virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
c13c4153 709
8172539d 710 return f;
bd322087
AL
711}
712
96637bcd 713static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
dce911c7
AS
714{
715 VirtIOBalloon *dev = opaque;
463756d0
HZ
716 info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
717 VIRTIO_BALLOON_PFN_SHIFT);
dce911c7
AS
718}
719
30fb2ca6 720static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
bd322087 721{
c96caced
FK
722 VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
723 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
463756d0 724 ram_addr_t vm_ram_size = get_current_ram_size();
bd322087 725
463756d0
HZ
726 if (target > vm_ram_size) {
727 target = vm_ram_size;
dce911c7 728 }
bd322087 729 if (target) {
463756d0 730 dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
c96caced 731 virtio_notify_config(vdev);
bd322087 732 }
6adfdc5a 733 trace_virtio_balloon_to_target(target, dev->num_pages);
bd322087
AL
734}
735
019518a8 736static int virtio_balloon_post_load_device(void *opaque, int version_id)
9ea2511c 737{
019518a8 738 VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
fecb48f7
PB
739
740 if (balloon_stats_enabled(s)) {
741 balloon_stats_change_timer(s, s->stats_poll_interval);
742 }
bd322087
AL
743 return 0;
744}
745
c13c4153
WW
746static const VMStateDescription vmstate_virtio_balloon_free_page_report = {
747 .name = "virtio-balloon-device/free-page-report",
748 .version_id = 1,
749 .minimum_version_id = 1,
750 .needed = virtio_balloon_free_page_support,
751 .fields = (VMStateField[]) {
752 VMSTATE_UINT32(free_page_report_cmd_id, VirtIOBalloon),
753 VMSTATE_UINT32(free_page_report_status, VirtIOBalloon),
754 VMSTATE_END_OF_LIST()
755 }
756};
757
019518a8
DDAG
758static const VMStateDescription vmstate_virtio_balloon_device = {
759 .name = "virtio-balloon-device",
760 .version_id = 1,
761 .minimum_version_id = 1,
762 .post_load = virtio_balloon_post_load_device,
763 .fields = (VMStateField[]) {
764 VMSTATE_UINT32(num_pages, VirtIOBalloon),
765 VMSTATE_UINT32(actual, VirtIOBalloon),
766 VMSTATE_END_OF_LIST()
767 },
c13c4153
WW
768 .subsections = (const VMStateDescription * []) {
769 &vmstate_virtio_balloon_free_page_report,
770 NULL
771 }
019518a8
DDAG
772};
773
74def47c 774static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
bd322087 775{
74def47c 776 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
a546fb17 777 VirtIOBalloon *s = VIRTIO_BALLOON(dev);
f76f6655 778 int ret;
bd322087 779
e6baf613 780 virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
2bbadb08 781 virtio_balloon_config_size(s));
bd322087 782
f76f6655
AS
783 ret = qemu_add_balloon_handler(virtio_balloon_to_target,
784 virtio_balloon_stat, s);
5c7d0962 785
1ab461b5 786 if (ret < 0) {
46abb812 787 error_setg(errp, "Only one balloon device is supported");
a546fb17 788 virtio_cleanup(vdev);
74def47c 789 return;
1ab461b5 790 }
f76f6655 791
5c7d0962
FK
792 s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
793 s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
794 s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
bd322087 795
c13c4153
WW
796 if (virtio_has_feature(s->host_features,
797 VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
798 s->free_page_vq = virtio_add_queue(vdev, VIRTQUEUE_MAX_SIZE,
799 virtio_balloon_handle_free_page_vq);
800 s->free_page_report_status = FREE_PAGE_REPORT_S_STOP;
801 s->free_page_report_cmd_id =
802 VIRTIO_BALLOON_FREE_PAGE_REPORT_CMD_ID_MIN;
803 s->free_page_report_notify.notify =
804 virtio_balloon_free_page_report_notify;
805 precopy_add_notifier(&s->free_page_report_notify);
806 if (s->iothread) {
807 object_ref(OBJECT(s->iothread));
808 s->free_page_bh = aio_bh_new(iothread_get_aio_context(s->iothread),
809 virtio_ballloon_get_free_page_hints, s);
810 qemu_mutex_init(&s->free_page_lock);
811 qemu_cond_init(&s->free_page_cond);
812 s->block_iothread = false;
813 } else {
814 /* Simply disable this feature if the iothread wasn't created. */
815 s->host_features &= ~(1 << VIRTIO_BALLOON_F_FREE_PAGE_HINT);
816 virtio_error(vdev, "iothread is missing");
817 }
818 }
38dbd48b 819 reset_stats(s);
1ab461b5
FK
820}
821
306ec6c3 822static void virtio_balloon_device_unrealize(DeviceState *dev, Error **errp)
1ab461b5 823{
306ec6c3
AF
824 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
825 VirtIOBalloon *s = VIRTIO_BALLOON(dev);
1ab461b5 826
c13c4153
WW
827 if (virtio_balloon_free_page_support(s)) {
828 qemu_bh_delete(s->free_page_bh);
829 virtio_balloon_free_page_stop(s);
830 precopy_remove_notifier(&s->free_page_report_notify);
831 }
1ab461b5
FK
832 balloon_stats_destroy_timer(s);
833 qemu_remove_balloon_handler(s);
36278428
PN
834
835 virtio_delete_queue(s->ivq);
836 virtio_delete_queue(s->dvq);
837 virtio_delete_queue(s->svq);
838 if (s->free_page_vq) {
839 virtio_delete_queue(s->free_page_vq);
840 }
6a1a8cc7 841 virtio_cleanup(vdev);
1ab461b5
FK
842}
843
4eae2a65
LP
844static void virtio_balloon_device_reset(VirtIODevice *vdev)
845{
846 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
847
c13c4153
WW
848 if (virtio_balloon_free_page_support(s)) {
849 virtio_balloon_free_page_stop(s);
850 }
851
4eae2a65 852 if (s->stats_vq_elem != NULL) {
27e57efe 853 virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
4eae2a65
LP
854 g_free(s->stats_vq_elem);
855 s->stats_vq_elem = NULL;
856 }
857}
858
4a1e48be
LP
859static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
860{
861 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
862
863 if (!s->stats_vq_elem && vdev->vm_running &&
864 (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
865 /* poll stats queue for the element we have discarded when the VM
866 * was stopped */
867 virtio_balloon_receive_stats(vdev, s->svq);
868 }
c13c4153
WW
869
870 if (virtio_balloon_free_page_support(s)) {
871 /*
872 * The VM is woken up and the iothread was blocked, so signal it to
873 * continue.
874 */
875 if (vdev->vm_running && s->block_iothread) {
876 qemu_mutex_lock(&s->free_page_lock);
877 s->block_iothread = false;
878 qemu_cond_signal(&s->free_page_cond);
879 qemu_mutex_unlock(&s->free_page_lock);
880 }
881
882 /* The VM is stopped, block the iothread. */
883 if (!vdev->vm_running) {
884 qemu_mutex_lock(&s->free_page_lock);
885 s->block_iothread = true;
886 qemu_mutex_unlock(&s->free_page_lock);
887 }
888 }
4a1e48be
LP
889}
890
1190044e
SZ
891static void virtio_balloon_instance_init(Object *obj)
892{
893 VirtIOBalloon *s = VIRTIO_BALLOON(obj);
894
895 object_property_add(obj, "guest-stats", "guest statistics",
896 balloon_stats_get_all, NULL, NULL, s, NULL);
897
898 object_property_add(obj, "guest-stats-polling-interval", "int",
899 balloon_stats_get_poll_interval,
900 balloon_stats_set_poll_interval,
901 NULL, s, NULL);
902}
903
c5dc16b7
HP
904static const VMStateDescription vmstate_virtio_balloon = {
905 .name = "virtio-balloon",
906 .minimum_version_id = 1,
907 .version_id = 1,
908 .fields = (VMStateField[]) {
909 VMSTATE_VIRTIO_DEVICE,
910 VMSTATE_END_OF_LIST()
911 },
912};
7f1ca9b2 913
1ab461b5 914static Property virtio_balloon_properties[] = {
e3816255
DL
915 DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
916 VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
c13c4153
WW
917 DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon, host_features,
918 VIRTIO_BALLOON_F_FREE_PAGE_HINT, false),
2bbadb08
SH
919 /* QEMU 4.0 accidentally changed the config size even when free-page-hint
920 * is disabled, resulting in QEMU 3.1 migration incompatibility. This
921 * property retains this quirk for QEMU 4.1 machine types.
922 */
923 DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon,
924 qemu_4_0_config_size, false),
c13c4153
WW
925 DEFINE_PROP_LINK("iothread", VirtIOBalloon, iothread, TYPE_IOTHREAD,
926 IOThread *),
1ab461b5
FK
927 DEFINE_PROP_END_OF_LIST(),
928};
929
930static void virtio_balloon_class_init(ObjectClass *klass, void *data)
931{
932 DeviceClass *dc = DEVICE_CLASS(klass);
933 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
74def47c 934
4f67d30b 935 device_class_set_props(dc, virtio_balloon_properties);
7f1ca9b2 936 dc->vmsd = &vmstate_virtio_balloon;
125ee0ed 937 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
74def47c 938 vdc->realize = virtio_balloon_device_realize;
306ec6c3 939 vdc->unrealize = virtio_balloon_device_unrealize;
4eae2a65 940 vdc->reset = virtio_balloon_device_reset;
1ab461b5
FK
941 vdc->get_config = virtio_balloon_get_config;
942 vdc->set_config = virtio_balloon_set_config;
943 vdc->get_features = virtio_balloon_get_features;
4a1e48be 944 vdc->set_status = virtio_balloon_set_status;
019518a8 945 vdc->vmsd = &vmstate_virtio_balloon_device;
1ab461b5
FK
946}
947
948static const TypeInfo virtio_balloon_info = {
949 .name = TYPE_VIRTIO_BALLOON,
950 .parent = TYPE_VIRTIO_DEVICE,
951 .instance_size = sizeof(VirtIOBalloon),
1190044e 952 .instance_init = virtio_balloon_instance_init,
1ab461b5
FK
953 .class_init = virtio_balloon_class_init,
954};
955
956static void virtio_register_types(void)
957{
958 type_register_static(&virtio_balloon_info);
959}
960
961type_init(virtio_register_types)