]> git.proxmox.com Git - mirror_qemu.git/blame - hw/virtio/virtio-balloon.c
Merge tag 'pull-maintainer-may24-160524-2' of https://gitlab.com/stsquad/qemu into...
[mirror_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"
b85ea5fa 20#include "qemu/madvise.h"
0d09e41a 21#include "hw/virtio/virtio.h"
2070aaeb 22#include "hw/mem/pc-dimm.h"
a27bd6c7 23#include "hw/qdev-properties.h"
b326b6ea 24#include "hw/boards.h"
9c17d615 25#include "sysemu/balloon.h"
0d09e41a 26#include "hw/virtio/virtio-balloon.h"
022c62cb 27#include "exec/address-spaces.h"
e688df6b 28#include "qapi/error.h"
a83e24ba 29#include "qapi/qapi-events-machine.h"
7e6ccd9c 30#include "qapi/visitor.h"
6adfdc5a 31#include "trace.h"
2ab4b135 32#include "qemu/error-report.h"
c13c4153 33#include "migration/misc.h"
bd322087 34
0d09e41a 35#include "hw/virtio/virtio-bus.h"
8609d2a8 36#include "hw/virtio/virtio-access.h"
1ab461b5 37
01310e2a
TH
38#define BALLOON_PAGE_SIZE (1 << VIRTIO_BALLOON_PFN_SHIFT)
39
a8cd64d4 40typedef struct PartiallyBalloonedPage {
1c5cfc2b 41 ram_addr_t base_gpa;
1c5cfc2b 42 unsigned long *bitmap;
a8cd64d4 43} PartiallyBalloonedPage;
ed48c598 44
1c5cfc2b
DH
45static void virtio_balloon_pbp_free(PartiallyBalloonedPage *pbp)
46{
1b47b37c 47 if (!pbp->bitmap) {
1c5cfc2b
DH
48 return;
49 }
50 g_free(pbp->bitmap);
1b47b37c 51 pbp->bitmap = NULL;
1c5cfc2b
DH
52}
53
1b47b37c
MT
54static void virtio_balloon_pbp_alloc(PartiallyBalloonedPage *pbp,
55 ram_addr_t base_gpa,
56 long subpages)
1c5cfc2b 57{
1c5cfc2b 58 pbp->base_gpa = base_gpa;
1c5cfc2b 59 pbp->bitmap = bitmap_new(subpages);
1c5cfc2b
DH
60}
61
62static bool virtio_balloon_pbp_matches(PartiallyBalloonedPage *pbp,
9a7ca8a7 63 ram_addr_t base_gpa)
1c5cfc2b 64{
9a7ca8a7 65 return pbp->base_gpa == base_gpa;
1c5cfc2b
DH
66}
67
06df2e69
DH
68static bool virtio_balloon_inhibited(void)
69{
1a8e44a8
AG
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();
06df2e69
DH
76}
77
e9550234 78static void balloon_inflate_page(VirtIOBalloon *balloon,
a8cd64d4 79 MemoryRegion *mr, hwaddr mr_offset,
1b47b37c 80 PartiallyBalloonedPage *pbp)
bd322087 81{
e6129b27 82 void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
1c5cfc2b 83 ram_addr_t rb_offset, rb_aligned_offset, base_gpa;
dbe1a277
DG
84 RAMBlock *rb;
85 size_t rb_page_size;
ed48c598 86 int subpages;
e9550234 87
dbe1a277
DG
88 /* XXX is there a better way to get to the RAMBlock than via a
89 * host address? */
e6129b27 90 rb = qemu_ram_block_from_host(addr, false, &rb_offset);
dbe1a277 91 rb_page_size = qemu_ram_pagesize(rb);
ed48c598
DG
92
93 if (rb_page_size == BALLOON_PAGE_SIZE) {
94 /* Easy case */
dbe1a277 95
e6129b27 96 ram_block_discard_range(rb, rb_offset, rb_page_size);
ed48c598
DG
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 */
dbe1a277
DG
100 return;
101 }
102
ed48c598
DG
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
e6129b27 112 rb_aligned_offset = QEMU_ALIGN_DOWN(rb_offset, rb_page_size);
ed48c598 113 subpages = rb_page_size / BALLOON_PAGE_SIZE;
1c5cfc2b
DH
114 base_gpa = memory_region_get_ram_addr(mr) + mr_offset -
115 (rb_offset - rb_aligned_offset);
ed48c598 116
1b47b37c 117 if (pbp->bitmap && !virtio_balloon_pbp_matches(pbp, base_gpa)) {
ed48c598
DG
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 */
1b47b37c 121 virtio_balloon_pbp_free(pbp);
dbe1a277
DG
122 }
123
1b47b37c
MT
124 if (!pbp->bitmap) {
125 virtio_balloon_pbp_alloc(pbp, base_gpa, subpages);
ed48c598
DG
126 }
127
1c5cfc2b 128 set_bit((rb_offset - rb_aligned_offset) / BALLOON_PAGE_SIZE,
1b47b37c 129 pbp->bitmap);
ed48c598 130
1b47b37c 131 if (bitmap_full(pbp->bitmap, subpages)) {
ed48c598
DG
132 /* We've accumulated a full host page, we can actually discard
133 * it now */
134
1c5cfc2b 135 ram_block_discard_range(rb, rb_aligned_offset, rb_page_size);
ed48c598
DG
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 */
1b47b37c 139 virtio_balloon_pbp_free(pbp);
ed48c598 140 }
bd322087
AL
141}
142
b27b3239 143static void balloon_deflate_page(VirtIOBalloon *balloon,
e6129b27 144 MemoryRegion *mr, hwaddr mr_offset)
b27b3239 145{
e6129b27
DH
146 void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
147 ram_addr_t rb_offset;
b27b3239
DG
148 RAMBlock *rb;
149 size_t rb_page_size;
596546fe
DG
150 void *host_addr;
151 int ret;
b27b3239
DG
152
153 /* XXX is there a better way to get to the RAMBlock than via a
154 * host address? */
e6129b27 155 rb = qemu_ram_block_from_host(addr, false, &rb_offset);
b27b3239 156 rb_page_size = qemu_ram_pagesize(rb);
b27b3239 157
596546fe
DG
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 }
b27b3239
DG
168}
169
7e6ccd9c
LC
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",
a0d06486 177 [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
bf1e7140 178 [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
b7b12644
JH
179 [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
180 [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
7e6ccd9c
LC
181 [VIRTIO_BALLOON_S_NR] = NULL
182};
183
625a5bef
AL
184/*
185 * reset_stats - Mark all items in the stats array as unset
186 *
52f35022
SW
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
625a5bef
AL
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
7e6ccd9c
LC
198static bool balloon_stats_supported(const VirtIOBalloon *s)
199{
c96caced 200 VirtIODevice *vdev = VIRTIO_DEVICE(s);
95129d6f 201 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
7e6ccd9c
LC
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)) {
bc72ad67 212 timer_free(s->stats_timer);
7e6ccd9c
LC
213 s->stats_timer = NULL;
214 s->stats_poll_interval = 0;
215 }
216}
217
1f9296b5 218static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
7e6ccd9c 219{
bc72ad67 220 timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
7e6ccd9c
LC
221}
222
223static void balloon_stats_poll_cb(void *opaque)
224{
225 VirtIOBalloon *s = opaque;
c96caced 226 VirtIODevice *vdev = VIRTIO_DEVICE(s);
7e6ccd9c 227
4eae2a65 228 if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
7e6ccd9c
LC
229 /* re-schedule */
230 balloon_stats_change_timer(s, s->stats_poll_interval);
231 return;
232 }
233
d3f1f940 234 virtqueue_push(s->svq, s->stats_vq_elem, 0);
c96caced 235 virtio_notify(vdev, s->svq);
51b19ebe
PB
236 g_free(s->stats_vq_elem);
237 s->stats_vq_elem = NULL;
7e6ccd9c
LC
238}
239
d7bce999
EB
240static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
241 void *opaque, Error **errp)
7e6ccd9c 242{
a2d860bb 243 VirtIOBalloon *s = VIRTIO_BALLOON(obj);
d1c81c34 244 bool ok = false;
7e6ccd9c
LC
245 int i;
246
d1c81c34
MA
247 if (!visit_start_struct(v, name, NULL, 0, errp)) {
248 return;
2ddb16a9 249 }
d1c81c34 250 if (!visit_type_int(v, "last-update", &s->stats_last_update, errp)) {
297a3646
MA
251 goto out_end;
252 }
7e6ccd9c 253
d1c81c34 254 if (!visit_start_struct(v, "stats", NULL, 0, errp)) {
2ddb16a9
MA
255 goto out_end;
256 }
9dbb8fa7 257 for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
d1c81c34 258 if (!visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], errp)) {
15c2f669 259 goto out_nested;
9dbb8fa7 260 }
7e6ccd9c 261 }
d1c81c34 262 ok = visit_check_struct(v, errp);
15c2f669 263out_nested:
1158bb2a 264 visit_end_struct(v, NULL);
2ddb16a9 265
d1c81c34
MA
266 if (ok) {
267 visit_check_struct(v, errp);
15c2f669 268 }
2ddb16a9 269out_end:
1158bb2a 270 visit_end_struct(v, NULL);
7e6ccd9c
LC
271}
272
4fa45492 273static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
d7bce999 274 const char *name, void *opaque,
7e6ccd9c
LC
275 Error **errp)
276{
a2d860bb 277 VirtIOBalloon *s = VIRTIO_BALLOON(obj);
51e72bc1 278 visit_type_int(v, name, &s->stats_poll_interval, errp);
7e6ccd9c
LC
279}
280
4fa45492 281static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
d7bce999 282 const char *name, void *opaque,
7e6ccd9c
LC
283 Error **errp)
284{
a2d860bb 285 VirtIOBalloon *s = VIRTIO_BALLOON(obj);
7e6ccd9c
LC
286 int64_t value;
287
668f62ec 288 if (!visit_type_int(v, name, &value, errp)) {
7e6ccd9c
LC
289 return;
290 }
291
292 if (value < 0) {
293 error_setg(errp, "timer value must be greater than zero");
294 return;
295 }
296
22644cd2 297 if (value > UINT32_MAX) {
1f9296b5
LC
298 error_setg(errp, "timer value is too big");
299 return;
300 }
301
7e6ccd9c
LC
302 if (value == s->stats_poll_interval) {
303 return;
304 }
305
306 if (value == 0) {
307 /* timer=0 disables the timer */
308 balloon_stats_destroy_timer(s);
309 return;
310 }
311
312 if (balloon_stats_enabled(s)) {
313 /* timer interval change */
314 s->stats_poll_interval = value;
315 balloon_stats_change_timer(s, value);
316 return;
317 }
318
319 /* create a new timer */
320 g_assert(s->stats_timer == NULL);
bc72ad67 321 s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
7e6ccd9c
LC
322 s->stats_poll_interval = value;
323 balloon_stats_change_timer(s, 0);
324}
325
91b86719
AD
326static void virtio_balloon_handle_report(VirtIODevice *vdev, VirtQueue *vq)
327{
328 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
329 VirtQueueElement *elem;
330
331 while ((elem = virtqueue_pop(vq, sizeof(VirtQueueElement)))) {
332 unsigned int i;
333
334 /*
335 * When we discard the page it has the effect of removing the page
336 * from the hypervisor itself and causing it to be zeroed when it
337 * is returned to us. So we must not discard the page if it is
338 * accessible by another device or process, or if the guest is
339 * expecting it to retain a non-zero value.
340 */
06df2e69 341 if (virtio_balloon_inhibited() || dev->poison_val) {
91b86719
AD
342 goto skip_element;
343 }
344
345 for (i = 0; i < elem->in_num; i++) {
346 void *addr = elem->in_sg[i].iov_base;
347 size_t size = elem->in_sg[i].iov_len;
348 ram_addr_t ram_offset;
349 RAMBlock *rb;
350
351 /*
352 * There is no need to check the memory section to see if
353 * it is ram/readonly/romd like there is for handle_output
354 * below. If the region is not meant to be written to then
355 * address_space_map will have allocated a bounce buffer
356 * and it will be freed in address_space_unmap and trigger
357 * and unassigned_mem_write before failing to copy over the
358 * buffer. If more than one bad descriptor is provided it
359 * will return NULL after the first bounce buffer and fail
360 * to map any resources.
361 */
362 rb = qemu_ram_block_from_host(addr, false, &ram_offset);
363 if (!rb) {
364 trace_virtio_balloon_bad_addr(elem->in_addr[i]);
365 continue;
366 }
367
368 /*
369 * For now we will simply ignore unaligned memory regions, or
370 * regions that overrun the end of the RAMBlock.
371 */
372 if (!QEMU_IS_ALIGNED(ram_offset | size, qemu_ram_pagesize(rb)) ||
373 (ram_offset + size) > qemu_ram_get_used_length(rb)) {
374 continue;
375 }
376
377 ram_block_discard_range(rb, ram_offset, size);
378 }
379
380skip_element:
381 virtqueue_push(vq, elem, 0);
382 virtio_notify(vdev, vq);
383 g_free(elem);
384 }
385}
386
bd322087
AL
387static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
388{
c96caced 389 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
51b19ebe 390 VirtQueueElement *elem;
b7c28c74 391 MemoryRegionSection section;
bd322087 392
51b19ebe 393 for (;;) {
1b47b37c 394 PartiallyBalloonedPage pbp = {};
bd322087
AL
395 size_t offset = 0;
396 uint32_t pfn;
1b47b37c 397
51b19ebe
PB
398 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
399 if (!elem) {
a8cd64d4 400 break;
51b19ebe 401 }
bd322087 402
51b19ebe 403 while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
ffa207d0 404 unsigned int p = virtio_ldl_p(vdev, &pfn);
b218a70e 405 hwaddr pa;
bd322087 406
b218a70e 407 pa = (hwaddr) p << VIRTIO_BALLOON_PFN_SHIFT;
bd322087
AL
408 offset += 4;
409
b218a70e
DG
410 section = memory_region_find(get_system_memory(), pa,
411 BALLOON_PAGE_SIZE);
412 if (!section.mr) {
413 trace_virtio_balloon_bad_addr(pa);
414 continue;
415 }
416 if (!memory_region_is_ram(section.mr) ||
f2fd57db
DDAG
417 memory_region_is_rom(section.mr) ||
418 memory_region_is_romd(section.mr)) {
419 trace_virtio_balloon_bad_addr(pa);
b86107ab 420 memory_region_unref(section.mr);
bd322087 421 continue;
f2fd57db 422 }
bd322087 423
6adfdc5a
HZ
424 trace_virtio_balloon_handle_output(memory_region_name(section.mr),
425 pa);
06df2e69 426 if (!virtio_balloon_inhibited()) {
b27b3239
DG
427 if (vq == s->ivq) {
428 balloon_inflate_page(s, section.mr,
a8cd64d4 429 section.offset_within_region, &pbp);
b27b3239
DG
430 } else if (vq == s->dvq) {
431 balloon_deflate_page(s, section.mr, section.offset_within_region);
432 } else {
433 g_assert_not_reached();
434 }
e9550234 435 }
dfde4e6e 436 memory_region_unref(section.mr);
bd322087
AL
437 }
438
d3f1f940 439 virtqueue_push(vq, elem, 0);
bd322087 440 virtio_notify(vdev, vq);
51b19ebe 441 g_free(elem);
1b47b37c 442 virtio_balloon_pbp_free(&pbp);
bd322087
AL
443 }
444}
445
625a5bef
AL
446static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
447{
c96caced 448 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
51b19ebe 449 VirtQueueElement *elem;
625a5bef
AL
450 VirtIOBalloonStat stat;
451 size_t offset = 0;
452
4eae2a65 453 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
51b19ebe 454 if (!elem) {
7e6ccd9c 455 goto out;
625a5bef
AL
456 }
457
4eae2a65
LP
458 if (s->stats_vq_elem != NULL) {
459 /* This should never happen if the driver follows the spec. */
460 virtqueue_push(vq, s->stats_vq_elem, 0);
461 virtio_notify(vdev, vq);
462 g_free(s->stats_vq_elem);
463 }
464
465 s->stats_vq_elem = elem;
466
625a5bef
AL
467 /* Initialize the stats to get rid of any stale values. This is only
468 * needed to handle the case where a guest supports fewer stats than it
469 * used to (ie. it has booted into an old kernel).
470 */
471 reset_stats(s);
472
dcf6f5e1 473 while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
fa6111f2 474 == sizeof(stat)) {
8609d2a8
RR
475 uint16_t tag = virtio_tswap16(vdev, stat.tag);
476 uint64_t val = virtio_tswap64(vdev, stat.val);
625a5bef
AL
477
478 offset += sizeof(stat);
479 if (tag < VIRTIO_BALLOON_S_NR)
480 s->stats[tag] = val;
481 }
482 s->stats_vq_offset = offset;
f793dde0 483 s->stats_last_update = g_get_real_time() / G_USEC_PER_SEC;
7e6ccd9c
LC
484
485out:
486 if (balloon_stats_enabled(s)) {
487 balloon_stats_change_timer(s, s->stats_poll_interval);
488 }
625a5bef
AL
489}
490
c13c4153
WW
491static void virtio_balloon_handle_free_page_vq(VirtIODevice *vdev,
492 VirtQueue *vq)
493{
494 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
495 qemu_bh_schedule(s->free_page_bh);
496}
497
498static bool get_free_page_hints(VirtIOBalloon *dev)
499{
500 VirtQueueElement *elem;
501 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
502 VirtQueue *vq = dev->free_page_vq;
ae440bd1 503 bool ret = true;
0fe7245d 504 int i;
c13c4153
WW
505
506 while (dev->block_iothread) {
507 qemu_cond_wait(&dev->free_page_cond, &dev->free_page_lock);
508 }
509
510 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
511 if (!elem) {
512 return false;
513 }
514
515 if (elem->out_num) {
516 uint32_t id;
517 size_t size = iov_to_buf(elem->out_sg, elem->out_num, 0,
518 &id, sizeof(id));
c13c4153
WW
519
520 virtio_tswap32s(vdev, &id);
521 if (unlikely(size != sizeof(id))) {
522 virtio_error(vdev, "received an incorrect cmd id");
ae440bd1
WW
523 ret = false;
524 goto out;
c13c4153 525 }
3219b42f
AD
526 if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED &&
527 id == dev->free_page_hint_cmd_id) {
528 dev->free_page_hint_status = FREE_PAGE_HINT_S_START;
2d050ed0 529 } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
c13c4153
WW
530 /*
531 * Stop the optimization only when it has started. This
532 * avoids a stale stop sign for the previous command.
533 */
2d050ed0 534 dev->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
c13c4153
WW
535 }
536 }
537
2d050ed0 538 if (elem->in_num && dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
0fe7245d
JW
539 for (i = 0; i < elem->in_num; i++) {
540 qemu_guest_free_page_hint(elem->in_sg[i].iov_base,
541 elem->in_sg[i].iov_len);
542 }
c13c4153
WW
543 }
544
ae440bd1 545out:
d3f1f940 546 virtqueue_push(vq, elem, 0);
ae440bd1
WW
547 g_free(elem);
548 return ret;
c13c4153
WW
549}
550
551static void virtio_ballloon_get_free_page_hints(void *opaque)
552{
553 VirtIOBalloon *dev = opaque;
554 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
555 VirtQueue *vq = dev->free_page_vq;
556 bool continue_to_get_hints;
557
558 do {
559 qemu_mutex_lock(&dev->free_page_lock);
560 virtio_queue_set_notification(vq, 0);
561 continue_to_get_hints = get_free_page_hints(dev);
562 qemu_mutex_unlock(&dev->free_page_lock);
563 virtio_notify(vdev, vq);
564 /*
3219b42f 565 * Start to poll the vq once the hinting started. Otherwise, continue
c13c4153
WW
566 * only when there are entries on the vq, which need to be given back.
567 */
568 } while (continue_to_get_hints ||
3219b42f 569 dev->free_page_hint_status == FREE_PAGE_HINT_S_START);
c13c4153
WW
570 virtio_queue_set_notification(vq, 1);
571}
572
573static bool virtio_balloon_free_page_support(void *opaque)
574{
575 VirtIOBalloon *s = opaque;
576 VirtIODevice *vdev = VIRTIO_DEVICE(s);
577
578 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT);
579}
580
581static void virtio_balloon_free_page_start(VirtIOBalloon *s)
582{
583 VirtIODevice *vdev = VIRTIO_DEVICE(s);
584
1a83e0b9
AD
585 qemu_mutex_lock(&s->free_page_lock);
586
3219b42f 587 if (s->free_page_hint_cmd_id == UINT_MAX) {
2d050ed0 588 s->free_page_hint_cmd_id = VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
c13c4153 589 } else {
3219b42f 590 s->free_page_hint_cmd_id++;
c13c4153
WW
591 }
592
3219b42f 593 s->free_page_hint_status = FREE_PAGE_HINT_S_REQUESTED;
1a83e0b9
AD
594 qemu_mutex_unlock(&s->free_page_lock);
595
c13c4153
WW
596 virtio_notify_config(vdev);
597}
598
599static void virtio_balloon_free_page_stop(VirtIOBalloon *s)
600{
601 VirtIODevice *vdev = VIRTIO_DEVICE(s);
602
3219b42f 603 if (s->free_page_hint_status != FREE_PAGE_HINT_S_STOP) {
c13c4153
WW
604 /*
605 * The lock also guarantees us that the
606 * virtio_ballloon_get_free_page_hints exits after the
3219b42f 607 * free_page_hint_status is set to S_STOP.
c13c4153
WW
608 */
609 qemu_mutex_lock(&s->free_page_lock);
610 /*
3219b42f
AD
611 * The guest isn't done hinting, so send a notification
612 * to the guest to actively stop the hinting.
c13c4153 613 */
3219b42f 614 s->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
c13c4153
WW
615 qemu_mutex_unlock(&s->free_page_lock);
616 virtio_notify_config(vdev);
617 }
618}
619
620static void virtio_balloon_free_page_done(VirtIOBalloon *s)
621{
622 VirtIODevice *vdev = VIRTIO_DEVICE(s);
623
3219b42f 624 if (s->free_page_hint_status != FREE_PAGE_HINT_S_DONE) {
dd8eeb96
DH
625 /* See virtio_balloon_free_page_stop() */
626 qemu_mutex_lock(&s->free_page_lock);
3219b42f 627 s->free_page_hint_status = FREE_PAGE_HINT_S_DONE;
dd8eeb96
DH
628 qemu_mutex_unlock(&s->free_page_lock);
629 virtio_notify_config(vdev);
630 }
c13c4153
WW
631}
632
633static int
be19d836
SS
634virtio_balloon_free_page_hint_notify(NotifierWithReturn *n, void *data,
635 Error **errp)
c13c4153 636{
2d050ed0 637 VirtIOBalloon *dev = container_of(n, VirtIOBalloon, free_page_hint_notify);
c13c4153
WW
638 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
639 PrecopyNotifyData *pnd = data;
640
641 if (!virtio_balloon_free_page_support(dev)) {
642 /*
643 * This is an optimization provided to migration, so just return 0 to
644 * have the normal migration process not affected when this feature is
645 * not supported.
646 */
647 return 0;
648 }
649
fd51e54f
DH
650 /*
651 * Pages hinted via qemu_guest_free_page_hint() are cleared from the dirty
652 * bitmap and will not get migrated, especially also not when the postcopy
653 * destination starts using them and requests migration from the source; the
654 * faulting thread will stall until postcopy migration finishes and
655 * all threads are woken up. Let's not start free page hinting if postcopy
656 * is possible.
657 */
658 if (migrate_postcopy_ram()) {
659 return 0;
660 }
661
c13c4153 662 switch (pnd->reason) {
c13c4153
WW
663 case PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC:
664 virtio_balloon_free_page_stop(dev);
665 break;
666 case PRECOPY_NOTIFY_AFTER_BITMAP_SYNC:
667 if (vdev->vm_running) {
668 virtio_balloon_free_page_start(dev);
dd8eeb96 669 break;
c13c4153 670 }
dd8eeb96
DH
671 /*
672 * Set S_DONE before migrating the vmstate, so the guest will reuse
673 * all hinted pages once running on the destination. Fall through.
674 */
675 case PRECOPY_NOTIFY_CLEANUP:
676 /*
677 * Especially, if something goes wrong during precopy or if migration
678 * is canceled, we have to properly communicate S_DONE to the VM.
679 */
680 virtio_balloon_free_page_done(dev);
681 break;
1a373522 682 case PRECOPY_NOTIFY_SETUP:
dd8eeb96 683 case PRECOPY_NOTIFY_COMPLETE:
c13c4153
WW
684 break;
685 default:
686 virtio_error(vdev, "%s: %d reason unknown", __func__, pnd->reason);
687 }
688
689 return 0;
690}
691
2bbadb08
SH
692static size_t virtio_balloon_config_size(VirtIOBalloon *s)
693{
694 uint64_t features = s->host_features;
695
696 if (s->qemu_4_0_config_size) {
697 return sizeof(struct virtio_balloon_config);
698 }
699 if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON)) {
700 return sizeof(struct virtio_balloon_config);
701 }
702 if (virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
703 return offsetof(struct virtio_balloon_config, poison_val);
704 }
3219b42f 705 return offsetof(struct virtio_balloon_config, free_page_hint_cmd_id);
2bbadb08
SH
706}
707
bd322087
AL
708static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
709{
c96caced 710 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
5385a598 711 struct virtio_balloon_config config = {};
bd322087
AL
712
713 config.num_pages = cpu_to_le32(dev->num_pages);
714 config.actual = cpu_to_le32(dev->actual);
7483cbba 715 config.poison_val = cpu_to_le32(dev->poison_val);
bd322087 716
3219b42f
AD
717 if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED) {
718 config.free_page_hint_cmd_id =
719 cpu_to_le32(dev->free_page_hint_cmd_id);
720 } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_STOP) {
721 config.free_page_hint_cmd_id =
c13c4153 722 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_STOP);
3219b42f
AD
723 } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_DONE) {
724 config.free_page_hint_cmd_id =
c13c4153
WW
725 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_DONE);
726 }
727
6adfdc5a 728 trace_virtio_balloon_get_config(config.num_pages, config.actual);
2bbadb08 729 memcpy(config_data, &config, virtio_balloon_config_size(dev));
bd322087
AL
730}
731
39de9984
VSO
732static ram_addr_t get_current_ram_size(void)
733{
e919402b
Y
734 MachineState *machine = MACHINE(qdev_get_machine());
735 if (machine->device_memory) {
736 return machine->ram_size + machine->device_memory->dimm_size;
737 } else {
738 return machine->ram_size;
39de9984 739 }
39de9984
VSO
740}
741
7483cbba
AD
742static bool virtio_balloon_page_poison_support(void *opaque)
743{
744 VirtIOBalloon *s = opaque;
745 VirtIODevice *vdev = VIRTIO_DEVICE(s);
746
747 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON);
748}
749
bd322087
AL
750static void virtio_balloon_set_config(VirtIODevice *vdev,
751 const uint8_t *config_data)
752{
c96caced 753 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
bd322087 754 struct virtio_balloon_config config;
973603a8 755 uint32_t oldactual = dev->actual;
463756d0
HZ
756 ram_addr_t vm_ram_size = get_current_ram_size();
757
2bbadb08 758 memcpy(&config, config_data, virtio_balloon_config_size(dev));
e54f1771 759 dev->actual = le32_to_cpu(config.actual);
973603a8 760 if (dev->actual != oldactual) {
463756d0 761 qapi_event_send_balloon_change(vm_ram_size -
3ab72385 762 ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
973603a8 763 }
7483cbba
AD
764 dev->poison_val = 0;
765 if (virtio_balloon_page_poison_support(dev)) {
766 dev->poison_val = le32_to_cpu(config.poison_val);
767 }
6adfdc5a 768 trace_virtio_balloon_set_config(dev->actual, oldactual);
bd322087
AL
769}
770
9d5b731d
JW
771static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
772 Error **errp)
bd322087 773{
e3816255
DL
774 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
775 f |= dev->host_features;
40de55af 776 virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
c13c4153 777
8172539d 778 return f;
bd322087
AL
779}
780
96637bcd 781static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
dce911c7
AS
782{
783 VirtIOBalloon *dev = opaque;
463756d0
HZ
784 info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
785 VIRTIO_BALLOON_PFN_SHIFT);
dce911c7
AS
786}
787
30fb2ca6 788static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
bd322087 789{
c96caced
FK
790 VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
791 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
463756d0 792 ram_addr_t vm_ram_size = get_current_ram_size();
bd322087 793
463756d0
HZ
794 if (target > vm_ram_size) {
795 target = vm_ram_size;
dce911c7 796 }
bd322087 797 if (target) {
463756d0 798 dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
c96caced 799 virtio_notify_config(vdev);
bd322087 800 }
6adfdc5a 801 trace_virtio_balloon_to_target(target, dev->num_pages);
bd322087
AL
802}
803
019518a8 804static int virtio_balloon_post_load_device(void *opaque, int version_id)
9ea2511c 805{
019518a8 806 VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
fecb48f7
PB
807
808 if (balloon_stats_enabled(s)) {
809 balloon_stats_change_timer(s, s->stats_poll_interval);
810 }
bd322087
AL
811 return 0;
812}
813
3219b42f 814static const VMStateDescription vmstate_virtio_balloon_free_page_hint = {
c13c4153
WW
815 .name = "virtio-balloon-device/free-page-report",
816 .version_id = 1,
817 .minimum_version_id = 1,
818 .needed = virtio_balloon_free_page_support,
ca02a170 819 .fields = (const VMStateField[]) {
3219b42f
AD
820 VMSTATE_UINT32(free_page_hint_cmd_id, VirtIOBalloon),
821 VMSTATE_UINT32(free_page_hint_status, VirtIOBalloon),
c13c4153
WW
822 VMSTATE_END_OF_LIST()
823 }
824};
825
7483cbba 826static const VMStateDescription vmstate_virtio_balloon_page_poison = {
243a9284 827 .name = "virtio-balloon-device/page-poison",
7483cbba
AD
828 .version_id = 1,
829 .minimum_version_id = 1,
830 .needed = virtio_balloon_page_poison_support,
ca02a170 831 .fields = (const VMStateField[]) {
7483cbba
AD
832 VMSTATE_UINT32(poison_val, VirtIOBalloon),
833 VMSTATE_END_OF_LIST()
834 }
835};
836
019518a8
DDAG
837static const VMStateDescription vmstate_virtio_balloon_device = {
838 .name = "virtio-balloon-device",
839 .version_id = 1,
840 .minimum_version_id = 1,
841 .post_load = virtio_balloon_post_load_device,
ca02a170 842 .fields = (const VMStateField[]) {
019518a8
DDAG
843 VMSTATE_UINT32(num_pages, VirtIOBalloon),
844 VMSTATE_UINT32(actual, VirtIOBalloon),
845 VMSTATE_END_OF_LIST()
846 },
ca02a170 847 .subsections = (const VMStateDescription * const []) {
3219b42f 848 &vmstate_virtio_balloon_free_page_hint,
7483cbba 849 &vmstate_virtio_balloon_page_poison,
c13c4153
WW
850 NULL
851 }
019518a8
DDAG
852};
853
74def47c 854static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
bd322087 855{
74def47c 856 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
a546fb17 857 VirtIOBalloon *s = VIRTIO_BALLOON(dev);
f76f6655 858 int ret;
bd322087 859
3857cd5c 860 virtio_init(vdev, VIRTIO_ID_BALLOON, virtio_balloon_config_size(s));
bd322087 861
f76f6655
AS
862 ret = qemu_add_balloon_handler(virtio_balloon_to_target,
863 virtio_balloon_stat, s);
5c7d0962 864
1ab461b5 865 if (ret < 0) {
46abb812 866 error_setg(errp, "Only one balloon device is supported");
a546fb17 867 virtio_cleanup(vdev);
74def47c 868 return;
1ab461b5 869 }
f76f6655 870
12fc8903
DH
871 if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_FREE_PAGE_HINT) &&
872 !s->iothread) {
873 error_setg(errp, "'free-page-hint' requires 'iothread' to be set");
874 virtio_cleanup(vdev);
875 return;
876 }
877
5c7d0962
FK
878 s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
879 s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
880 s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
bd322087 881
2d050ed0 882 if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
c13c4153
WW
883 s->free_page_vq = virtio_add_queue(vdev, VIRTQUEUE_MAX_SIZE,
884 virtio_balloon_handle_free_page_vq);
3219b42f 885 precopy_add_notifier(&s->free_page_hint_notify);
12fc8903
DH
886
887 object_ref(OBJECT(s->iothread));
f63192b0
AB
888 s->free_page_bh = aio_bh_new_guarded(iothread_get_aio_context(s->iothread),
889 virtio_ballloon_get_free_page_hints, s,
890 &dev->mem_reentrancy_guard);
c13c4153 891 }
91b86719
AD
892
893 if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_REPORTING)) {
894 s->reporting_vq = virtio_add_queue(vdev, 32,
895 virtio_balloon_handle_report);
896 }
897
38dbd48b 898 reset_stats(s);
1ab461b5
FK
899}
900
b69c3c21 901static void virtio_balloon_device_unrealize(DeviceState *dev)
1ab461b5 902{
306ec6c3
AF
903 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
904 VirtIOBalloon *s = VIRTIO_BALLOON(dev);
1ab461b5 905
49b01711 906 if (s->free_page_bh) {
c13c4153 907 qemu_bh_delete(s->free_page_bh);
105aef9c 908 object_unref(OBJECT(s->iothread));
c13c4153 909 virtio_balloon_free_page_stop(s);
3219b42f 910 precopy_remove_notifier(&s->free_page_hint_notify);
c13c4153 911 }
1ab461b5
FK
912 balloon_stats_destroy_timer(s);
913 qemu_remove_balloon_handler(s);
36278428
PN
914
915 virtio_delete_queue(s->ivq);
916 virtio_delete_queue(s->dvq);
917 virtio_delete_queue(s->svq);
918 if (s->free_page_vq) {
919 virtio_delete_queue(s->free_page_vq);
920 }
91b86719
AD
921 if (s->reporting_vq) {
922 virtio_delete_queue(s->reporting_vq);
923 }
6a1a8cc7 924 virtio_cleanup(vdev);
1ab461b5
FK
925}
926
4eae2a65
LP
927static void virtio_balloon_device_reset(VirtIODevice *vdev)
928{
929 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
930
c13c4153
WW
931 if (virtio_balloon_free_page_support(s)) {
932 virtio_balloon_free_page_stop(s);
933 }
934
4eae2a65 935 if (s->stats_vq_elem != NULL) {
27e57efe 936 virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
4eae2a65
LP
937 g_free(s->stats_vq_elem);
938 s->stats_vq_elem = NULL;
939 }
7483cbba
AD
940
941 s->poison_val = 0;
4eae2a65
LP
942}
943
4a1e48be
LP
944static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
945{
946 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
947
948 if (!s->stats_vq_elem && vdev->vm_running &&
949 (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
950 /* poll stats queue for the element we have discarded when the VM
951 * was stopped */
952 virtio_balloon_receive_stats(vdev, s->svq);
953 }
c13c4153
WW
954
955 if (virtio_balloon_free_page_support(s)) {
956 /*
957 * The VM is woken up and the iothread was blocked, so signal it to
958 * continue.
959 */
960 if (vdev->vm_running && s->block_iothread) {
961 qemu_mutex_lock(&s->free_page_lock);
962 s->block_iothread = false;
963 qemu_cond_signal(&s->free_page_cond);
964 qemu_mutex_unlock(&s->free_page_lock);
965 }
966
967 /* The VM is stopped, block the iothread. */
968 if (!vdev->vm_running) {
969 qemu_mutex_lock(&s->free_page_lock);
970 s->block_iothread = true;
971 qemu_mutex_unlock(&s->free_page_lock);
972 }
973 }
4a1e48be
LP
974}
975
1190044e
SZ
976static void virtio_balloon_instance_init(Object *obj)
977{
978 VirtIOBalloon *s = VIRTIO_BALLOON(obj);
979
12fc8903
DH
980 qemu_mutex_init(&s->free_page_lock);
981 qemu_cond_init(&s->free_page_cond);
3219b42f
AD
982 s->free_page_hint_cmd_id = VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
983 s->free_page_hint_notify.notify = virtio_balloon_free_page_hint_notify;
12fc8903 984
1190044e 985 object_property_add(obj, "guest-stats", "guest statistics",
a2d860bb 986 balloon_stats_get_all, NULL, NULL, NULL);
1190044e
SZ
987
988 object_property_add(obj, "guest-stats-polling-interval", "int",
989 balloon_stats_get_poll_interval,
990 balloon_stats_set_poll_interval,
a2d860bb 991 NULL, NULL);
1190044e
SZ
992}
993
c5dc16b7
HP
994static const VMStateDescription vmstate_virtio_balloon = {
995 .name = "virtio-balloon",
996 .minimum_version_id = 1,
997 .version_id = 1,
ca02a170 998 .fields = (const VMStateField[]) {
c5dc16b7
HP
999 VMSTATE_VIRTIO_DEVICE,
1000 VMSTATE_END_OF_LIST()
1001 },
1002};
7f1ca9b2 1003
1ab461b5 1004static Property virtio_balloon_properties[] = {
e3816255
DL
1005 DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
1006 VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
c13c4153
WW
1007 DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon, host_features,
1008 VIRTIO_BALLOON_F_FREE_PAGE_HINT, false),
7483cbba
AD
1009 DEFINE_PROP_BIT("page-poison", VirtIOBalloon, host_features,
1010 VIRTIO_BALLOON_F_PAGE_POISON, true),
91b86719
AD
1011 DEFINE_PROP_BIT("free-page-reporting", VirtIOBalloon, host_features,
1012 VIRTIO_BALLOON_F_REPORTING, false),
2bbadb08
SH
1013 /* QEMU 4.0 accidentally changed the config size even when free-page-hint
1014 * is disabled, resulting in QEMU 3.1 migration incompatibility. This
1015 * property retains this quirk for QEMU 4.1 machine types.
1016 */
1017 DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon,
1018 qemu_4_0_config_size, false),
c13c4153
WW
1019 DEFINE_PROP_LINK("iothread", VirtIOBalloon, iothread, TYPE_IOTHREAD,
1020 IOThread *),
1ab461b5
FK
1021 DEFINE_PROP_END_OF_LIST(),
1022};
1023
1024static void virtio_balloon_class_init(ObjectClass *klass, void *data)
1025{
1026 DeviceClass *dc = DEVICE_CLASS(klass);
1027 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
74def47c 1028
4f67d30b 1029 device_class_set_props(dc, virtio_balloon_properties);
7f1ca9b2 1030 dc->vmsd = &vmstate_virtio_balloon;
125ee0ed 1031 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
74def47c 1032 vdc->realize = virtio_balloon_device_realize;
306ec6c3 1033 vdc->unrealize = virtio_balloon_device_unrealize;
4eae2a65 1034 vdc->reset = virtio_balloon_device_reset;
1ab461b5
FK
1035 vdc->get_config = virtio_balloon_get_config;
1036 vdc->set_config = virtio_balloon_set_config;
1037 vdc->get_features = virtio_balloon_get_features;
4a1e48be 1038 vdc->set_status = virtio_balloon_set_status;
019518a8 1039 vdc->vmsd = &vmstate_virtio_balloon_device;
1ab461b5
FK
1040}
1041
1042static const TypeInfo virtio_balloon_info = {
1043 .name = TYPE_VIRTIO_BALLOON,
1044 .parent = TYPE_VIRTIO_DEVICE,
1045 .instance_size = sizeof(VirtIOBalloon),
1190044e 1046 .instance_init = virtio_balloon_instance_init,
1ab461b5
FK
1047 .class_init = virtio_balloon_class_init,
1048};
1049
1050static void virtio_register_types(void)
1051{
1052 type_register_static(&virtio_balloon_info);
1053}
1054
1055type_init(virtio_register_types)