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