2 * Virtio Balloon Device
4 * Copyright IBM, Corp. 2008
5 * Copyright (C) 2011 Red Hat, Inc.
6 * Copyright (C) 2011 Amit Shah <amit.shah@redhat.com>
9 * Anthony Liguori <aliguori@us.ibm.com>
11 * This work is licensed under the terms of the GNU GPL, version 2. See
12 * the COPYING file in the top-level directory.
16 #include "qemu/osdep.h"
18 #include "qemu/module.h"
19 #include "qemu/timer.h"
20 #include "hw/virtio/virtio.h"
21 #include "hw/mem/pc-dimm.h"
22 #include "hw/qdev-properties.h"
23 #include "hw/boards.h"
24 #include "sysemu/balloon.h"
25 #include "hw/virtio/virtio-balloon.h"
26 #include "exec/address-spaces.h"
27 #include "qapi/error.h"
28 #include "qapi/qapi-events-machine.h"
29 #include "qapi/visitor.h"
31 #include "qemu/error-report.h"
32 #include "migration/misc.h"
34 #include "hw/virtio/virtio-bus.h"
35 #include "hw/virtio/virtio-access.h"
37 #define BALLOON_PAGE_SIZE (1 << VIRTIO_BALLOON_PFN_SHIFT)
39 typedef struct PartiallyBalloonedPage
{
41 unsigned long *bitmap
;
42 } PartiallyBalloonedPage
;
44 static void virtio_balloon_pbp_free(PartiallyBalloonedPage
*pbp
)
53 static void virtio_balloon_pbp_alloc(PartiallyBalloonedPage
*pbp
,
57 pbp
->base_gpa
= base_gpa
;
58 pbp
->bitmap
= bitmap_new(subpages
);
61 static bool virtio_balloon_pbp_matches(PartiallyBalloonedPage
*pbp
,
64 return pbp
->base_gpa
== base_gpa
;
67 static bool virtio_balloon_inhibited(void)
69 /* Postcopy cannot deal with concurrent discards, so it's special. */
70 return ram_block_discard_is_disabled() || migration_in_incoming_postcopy();
73 static void balloon_inflate_page(VirtIOBalloon
*balloon
,
74 MemoryRegion
*mr
, hwaddr mr_offset
,
75 PartiallyBalloonedPage
*pbp
)
77 void *addr
= memory_region_get_ram_ptr(mr
) + mr_offset
;
78 ram_addr_t rb_offset
, rb_aligned_offset
, base_gpa
;
83 /* XXX is there a better way to get to the RAMBlock than via a
85 rb
= qemu_ram_block_from_host(addr
, false, &rb_offset
);
86 rb_page_size
= qemu_ram_pagesize(rb
);
88 if (rb_page_size
== BALLOON_PAGE_SIZE
) {
91 ram_block_discard_range(rb
, rb_offset
, rb_page_size
);
92 /* We ignore errors from ram_block_discard_range(), because it
93 * has already reported them, and failing to discard a balloon
94 * page is not fatal */
100 * We've put a piece of a larger host page into the balloon - we
101 * need to keep track until we have a whole host page to
105 "Balloon used with backing page size > 4kiB, this may not be reliable");
107 rb_aligned_offset
= QEMU_ALIGN_DOWN(rb_offset
, rb_page_size
);
108 subpages
= rb_page_size
/ BALLOON_PAGE_SIZE
;
109 base_gpa
= memory_region_get_ram_addr(mr
) + mr_offset
-
110 (rb_offset
- rb_aligned_offset
);
112 if (pbp
->bitmap
&& !virtio_balloon_pbp_matches(pbp
, base_gpa
)) {
113 /* We've partially ballooned part of a host page, but now
114 * we're trying to balloon part of a different one. Too hard,
115 * give up on the old partial page */
116 virtio_balloon_pbp_free(pbp
);
120 virtio_balloon_pbp_alloc(pbp
, base_gpa
, subpages
);
123 set_bit((rb_offset
- rb_aligned_offset
) / BALLOON_PAGE_SIZE
,
126 if (bitmap_full(pbp
->bitmap
, subpages
)) {
127 /* We've accumulated a full host page, we can actually discard
130 ram_block_discard_range(rb
, rb_aligned_offset
, rb_page_size
);
131 /* We ignore errors from ram_block_discard_range(), because it
132 * has already reported them, and failing to discard a balloon
133 * page is not fatal */
134 virtio_balloon_pbp_free(pbp
);
138 static void balloon_deflate_page(VirtIOBalloon
*balloon
,
139 MemoryRegion
*mr
, hwaddr mr_offset
)
141 void *addr
= memory_region_get_ram_ptr(mr
) + mr_offset
;
142 ram_addr_t rb_offset
;
148 /* XXX is there a better way to get to the RAMBlock than via a
150 rb
= qemu_ram_block_from_host(addr
, false, &rb_offset
);
151 rb_page_size
= qemu_ram_pagesize(rb
);
153 host_addr
= (void *)((uintptr_t)addr
& ~(rb_page_size
- 1));
155 /* When a page is deflated, we hint the whole host page it lives
156 * on, since we can't do anything smaller */
157 ret
= qemu_madvise(host_addr
, rb_page_size
, QEMU_MADV_WILLNEED
);
159 warn_report("Couldn't MADV_WILLNEED on balloon deflate: %s",
161 /* Otherwise ignore, failing to page hint shouldn't be fatal */
165 static const char *balloon_stat_names
[] = {
166 [VIRTIO_BALLOON_S_SWAP_IN
] = "stat-swap-in",
167 [VIRTIO_BALLOON_S_SWAP_OUT
] = "stat-swap-out",
168 [VIRTIO_BALLOON_S_MAJFLT
] = "stat-major-faults",
169 [VIRTIO_BALLOON_S_MINFLT
] = "stat-minor-faults",
170 [VIRTIO_BALLOON_S_MEMFREE
] = "stat-free-memory",
171 [VIRTIO_BALLOON_S_MEMTOT
] = "stat-total-memory",
172 [VIRTIO_BALLOON_S_AVAIL
] = "stat-available-memory",
173 [VIRTIO_BALLOON_S_CACHES
] = "stat-disk-caches",
174 [VIRTIO_BALLOON_S_HTLB_PGALLOC
] = "stat-htlb-pgalloc",
175 [VIRTIO_BALLOON_S_HTLB_PGFAIL
] = "stat-htlb-pgfail",
176 [VIRTIO_BALLOON_S_NR
] = NULL
180 * reset_stats - Mark all items in the stats array as unset
182 * This function needs to be called at device initialization and before
183 * updating to a set of newly-generated stats. This will ensure that no
184 * stale values stick around in case the guest reports a subset of the supported
187 static inline void reset_stats(VirtIOBalloon
*dev
)
190 for (i
= 0; i
< VIRTIO_BALLOON_S_NR
; dev
->stats
[i
++] = -1);
193 static bool balloon_stats_supported(const VirtIOBalloon
*s
)
195 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
196 return virtio_vdev_has_feature(vdev
, VIRTIO_BALLOON_F_STATS_VQ
);
199 static bool balloon_stats_enabled(const VirtIOBalloon
*s
)
201 return s
->stats_poll_interval
> 0;
204 static void balloon_stats_destroy_timer(VirtIOBalloon
*s
)
206 if (balloon_stats_enabled(s
)) {
207 timer_del(s
->stats_timer
);
208 timer_free(s
->stats_timer
);
209 s
->stats_timer
= NULL
;
210 s
->stats_poll_interval
= 0;
214 static void balloon_stats_change_timer(VirtIOBalloon
*s
, int64_t secs
)
216 timer_mod(s
->stats_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) + secs
* 1000);
219 static void balloon_stats_poll_cb(void *opaque
)
221 VirtIOBalloon
*s
= opaque
;
222 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
224 if (s
->stats_vq_elem
== NULL
|| !balloon_stats_supported(s
)) {
226 balloon_stats_change_timer(s
, s
->stats_poll_interval
);
230 virtqueue_push(s
->svq
, s
->stats_vq_elem
, s
->stats_vq_offset
);
231 virtio_notify(vdev
, s
->svq
);
232 g_free(s
->stats_vq_elem
);
233 s
->stats_vq_elem
= NULL
;
236 static void balloon_stats_get_all(Object
*obj
, Visitor
*v
, const char *name
,
237 void *opaque
, Error
**errp
)
240 VirtIOBalloon
*s
= opaque
;
243 if (!visit_start_struct(v
, name
, NULL
, 0, &err
)) {
246 if (!visit_type_int(v
, "last-update", &s
->stats_last_update
, &err
)) {
250 if (!visit_start_struct(v
, "stats", NULL
, 0, &err
)) {
253 for (i
= 0; i
< VIRTIO_BALLOON_S_NR
; i
++) {
254 if (!visit_type_uint64(v
, balloon_stat_names
[i
], &s
->stats
[i
], &err
)) {
258 visit_check_struct(v
, &err
);
260 visit_end_struct(v
, NULL
);
263 visit_check_struct(v
, &err
);
266 visit_end_struct(v
, NULL
);
268 error_propagate(errp
, err
);
271 static void balloon_stats_get_poll_interval(Object
*obj
, Visitor
*v
,
272 const char *name
, void *opaque
,
275 VirtIOBalloon
*s
= opaque
;
276 visit_type_int(v
, name
, &s
->stats_poll_interval
, errp
);
279 static void balloon_stats_set_poll_interval(Object
*obj
, Visitor
*v
,
280 const char *name
, void *opaque
,
283 VirtIOBalloon
*s
= opaque
;
286 if (!visit_type_int(v
, name
, &value
, errp
)) {
291 error_setg(errp
, "timer value must be greater than zero");
295 if (value
> UINT32_MAX
) {
296 error_setg(errp
, "timer value is too big");
300 if (value
== s
->stats_poll_interval
) {
305 /* timer=0 disables the timer */
306 balloon_stats_destroy_timer(s
);
310 if (balloon_stats_enabled(s
)) {
311 /* timer interval change */
312 s
->stats_poll_interval
= value
;
313 balloon_stats_change_timer(s
, value
);
317 /* create a new timer */
318 g_assert(s
->stats_timer
== NULL
);
319 s
->stats_timer
= timer_new_ms(QEMU_CLOCK_VIRTUAL
, balloon_stats_poll_cb
, s
);
320 s
->stats_poll_interval
= value
;
321 balloon_stats_change_timer(s
, 0);
324 static void virtio_balloon_handle_report(VirtIODevice
*vdev
, VirtQueue
*vq
)
326 VirtIOBalloon
*dev
= VIRTIO_BALLOON(vdev
);
327 VirtQueueElement
*elem
;
329 while ((elem
= virtqueue_pop(vq
, sizeof(VirtQueueElement
)))) {
333 * When we discard the page it has the effect of removing the page
334 * from the hypervisor itself and causing it to be zeroed when it
335 * is returned to us. So we must not discard the page if it is
336 * accessible by another device or process, or if the guest is
337 * expecting it to retain a non-zero value.
339 if (virtio_balloon_inhibited() || dev
->poison_val
) {
343 for (i
= 0; i
< elem
->in_num
; i
++) {
344 void *addr
= elem
->in_sg
[i
].iov_base
;
345 size_t size
= elem
->in_sg
[i
].iov_len
;
346 ram_addr_t ram_offset
;
350 * There is no need to check the memory section to see if
351 * it is ram/readonly/romd like there is for handle_output
352 * below. If the region is not meant to be written to then
353 * address_space_map will have allocated a bounce buffer
354 * and it will be freed in address_space_unmap and trigger
355 * and unassigned_mem_write before failing to copy over the
356 * buffer. If more than one bad descriptor is provided it
357 * will return NULL after the first bounce buffer and fail
358 * to map any resources.
360 rb
= qemu_ram_block_from_host(addr
, false, &ram_offset
);
362 trace_virtio_balloon_bad_addr(elem
->in_addr
[i
]);
367 * For now we will simply ignore unaligned memory regions, or
368 * regions that overrun the end of the RAMBlock.
370 if (!QEMU_IS_ALIGNED(ram_offset
| size
, qemu_ram_pagesize(rb
)) ||
371 (ram_offset
+ size
) > qemu_ram_get_used_length(rb
)) {
375 ram_block_discard_range(rb
, ram_offset
, size
);
379 virtqueue_push(vq
, elem
, 0);
380 virtio_notify(vdev
, vq
);
385 static void virtio_balloon_handle_output(VirtIODevice
*vdev
, VirtQueue
*vq
)
387 VirtIOBalloon
*s
= VIRTIO_BALLOON(vdev
);
388 VirtQueueElement
*elem
;
389 MemoryRegionSection section
;
392 PartiallyBalloonedPage pbp
= {};
396 elem
= virtqueue_pop(vq
, sizeof(VirtQueueElement
));
401 while (iov_to_buf(elem
->out_sg
, elem
->out_num
, offset
, &pfn
, 4) == 4) {
402 unsigned int p
= virtio_ldl_p(vdev
, &pfn
);
405 pa
= (hwaddr
) p
<< VIRTIO_BALLOON_PFN_SHIFT
;
408 section
= memory_region_find(get_system_memory(), pa
,
411 trace_virtio_balloon_bad_addr(pa
);
414 if (!memory_region_is_ram(section
.mr
) ||
415 memory_region_is_rom(section
.mr
) ||
416 memory_region_is_romd(section
.mr
)) {
417 trace_virtio_balloon_bad_addr(pa
);
418 memory_region_unref(section
.mr
);
422 trace_virtio_balloon_handle_output(memory_region_name(section
.mr
),
424 if (!virtio_balloon_inhibited()) {
426 balloon_inflate_page(s
, section
.mr
,
427 section
.offset_within_region
, &pbp
);
428 } else if (vq
== s
->dvq
) {
429 balloon_deflate_page(s
, section
.mr
, section
.offset_within_region
);
431 g_assert_not_reached();
434 memory_region_unref(section
.mr
);
437 virtqueue_push(vq
, elem
, offset
);
438 virtio_notify(vdev
, vq
);
440 virtio_balloon_pbp_free(&pbp
);
444 static void virtio_balloon_receive_stats(VirtIODevice
*vdev
, VirtQueue
*vq
)
446 VirtIOBalloon
*s
= VIRTIO_BALLOON(vdev
);
447 VirtQueueElement
*elem
;
448 VirtIOBalloonStat stat
;
452 elem
= virtqueue_pop(vq
, sizeof(VirtQueueElement
));
457 if (s
->stats_vq_elem
!= NULL
) {
458 /* This should never happen if the driver follows the spec. */
459 virtqueue_push(vq
, s
->stats_vq_elem
, 0);
460 virtio_notify(vdev
, vq
);
461 g_free(s
->stats_vq_elem
);
464 s
->stats_vq_elem
= elem
;
466 /* Initialize the stats to get rid of any stale values. This is only
467 * needed to handle the case where a guest supports fewer stats than it
468 * used to (ie. it has booted into an old kernel).
472 while (iov_to_buf(elem
->out_sg
, elem
->out_num
, offset
, &stat
, sizeof(stat
))
474 uint16_t tag
= virtio_tswap16(vdev
, stat
.tag
);
475 uint64_t val
= virtio_tswap64(vdev
, stat
.val
);
477 offset
+= sizeof(stat
);
478 if (tag
< VIRTIO_BALLOON_S_NR
)
481 s
->stats_vq_offset
= offset
;
483 if (qemu_gettimeofday(&tv
) < 0) {
484 warn_report("%s: failed to get time of day", __func__
);
488 s
->stats_last_update
= tv
.tv_sec
;
491 if (balloon_stats_enabled(s
)) {
492 balloon_stats_change_timer(s
, s
->stats_poll_interval
);
496 static void virtio_balloon_handle_free_page_vq(VirtIODevice
*vdev
,
499 VirtIOBalloon
*s
= VIRTIO_BALLOON(vdev
);
500 qemu_bh_schedule(s
->free_page_bh
);
503 static bool get_free_page_hints(VirtIOBalloon
*dev
)
505 VirtQueueElement
*elem
;
506 VirtIODevice
*vdev
= VIRTIO_DEVICE(dev
);
507 VirtQueue
*vq
= dev
->free_page_vq
;
510 while (dev
->block_iothread
) {
511 qemu_cond_wait(&dev
->free_page_cond
, &dev
->free_page_lock
);
514 elem
= virtqueue_pop(vq
, sizeof(VirtQueueElement
));
521 size_t size
= iov_to_buf(elem
->out_sg
, elem
->out_num
, 0,
524 virtio_tswap32s(vdev
, &id
);
525 if (unlikely(size
!= sizeof(id
))) {
526 virtio_error(vdev
, "received an incorrect cmd id");
530 if (dev
->free_page_hint_status
== FREE_PAGE_HINT_S_REQUESTED
&&
531 id
== dev
->free_page_hint_cmd_id
) {
532 dev
->free_page_hint_status
= FREE_PAGE_HINT_S_START
;
535 * Stop the optimization only when it has started. This
536 * avoids a stale stop sign for the previous command.
538 if (dev
->free_page_hint_status
== FREE_PAGE_HINT_S_START
) {
539 dev
->free_page_hint_status
= FREE_PAGE_HINT_S_STOP
;
545 if (dev
->free_page_hint_status
== FREE_PAGE_HINT_S_START
) {
546 qemu_guest_free_page_hint(elem
->in_sg
[0].iov_base
,
547 elem
->in_sg
[0].iov_len
);
552 virtqueue_push(vq
, elem
, 1);
557 static void virtio_ballloon_get_free_page_hints(void *opaque
)
559 VirtIOBalloon
*dev
= opaque
;
560 VirtIODevice
*vdev
= VIRTIO_DEVICE(dev
);
561 VirtQueue
*vq
= dev
->free_page_vq
;
562 bool continue_to_get_hints
;
565 qemu_mutex_lock(&dev
->free_page_lock
);
566 virtio_queue_set_notification(vq
, 0);
567 continue_to_get_hints
= get_free_page_hints(dev
);
568 qemu_mutex_unlock(&dev
->free_page_lock
);
569 virtio_notify(vdev
, vq
);
571 * Start to poll the vq once the hinting started. Otherwise, continue
572 * only when there are entries on the vq, which need to be given back.
574 } while (continue_to_get_hints
||
575 dev
->free_page_hint_status
== FREE_PAGE_HINT_S_START
);
576 virtio_queue_set_notification(vq
, 1);
579 static bool virtio_balloon_free_page_support(void *opaque
)
581 VirtIOBalloon
*s
= opaque
;
582 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
584 return virtio_vdev_has_feature(vdev
, VIRTIO_BALLOON_F_FREE_PAGE_HINT
);
587 static void virtio_balloon_free_page_start(VirtIOBalloon
*s
)
589 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
591 /* For the stop and copy phase, we don't need to start the optimization */
592 if (!vdev
->vm_running
) {
596 qemu_mutex_lock(&s
->free_page_lock
);
598 if (s
->free_page_hint_cmd_id
== UINT_MAX
) {
599 s
->free_page_hint_cmd_id
=
600 VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN
;
602 s
->free_page_hint_cmd_id
++;
605 s
->free_page_hint_status
= FREE_PAGE_HINT_S_REQUESTED
;
606 qemu_mutex_unlock(&s
->free_page_lock
);
608 virtio_notify_config(vdev
);
611 static void virtio_balloon_free_page_stop(VirtIOBalloon
*s
)
613 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
615 if (s
->free_page_hint_status
!= FREE_PAGE_HINT_S_STOP
) {
617 * The lock also guarantees us that the
618 * virtio_ballloon_get_free_page_hints exits after the
619 * free_page_hint_status is set to S_STOP.
621 qemu_mutex_lock(&s
->free_page_lock
);
623 * The guest isn't done hinting, so send a notification
624 * to the guest to actively stop the hinting.
626 s
->free_page_hint_status
= FREE_PAGE_HINT_S_STOP
;
627 qemu_mutex_unlock(&s
->free_page_lock
);
628 virtio_notify_config(vdev
);
632 static void virtio_balloon_free_page_done(VirtIOBalloon
*s
)
634 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
636 if (s
->free_page_hint_status
!= FREE_PAGE_HINT_S_DONE
) {
637 /* See virtio_balloon_free_page_stop() */
638 qemu_mutex_lock(&s
->free_page_lock
);
639 s
->free_page_hint_status
= FREE_PAGE_HINT_S_DONE
;
640 qemu_mutex_unlock(&s
->free_page_lock
);
641 virtio_notify_config(vdev
);
646 virtio_balloon_free_page_hint_notify(NotifierWithReturn
*n
, void *data
)
648 VirtIOBalloon
*dev
= container_of(n
, VirtIOBalloon
,
649 free_page_hint_notify
);
650 VirtIODevice
*vdev
= VIRTIO_DEVICE(dev
);
651 PrecopyNotifyData
*pnd
= data
;
653 if (!virtio_balloon_free_page_support(dev
)) {
655 * This is an optimization provided to migration, so just return 0 to
656 * have the normal migration process not affected when this feature is
662 switch (pnd
->reason
) {
663 case PRECOPY_NOTIFY_SETUP
:
664 precopy_enable_free_page_optimization();
666 case PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC
:
667 virtio_balloon_free_page_stop(dev
);
669 case PRECOPY_NOTIFY_AFTER_BITMAP_SYNC
:
670 if (vdev
->vm_running
) {
671 virtio_balloon_free_page_start(dev
);
675 * Set S_DONE before migrating the vmstate, so the guest will reuse
676 * all hinted pages once running on the destination. Fall through.
678 case PRECOPY_NOTIFY_CLEANUP
:
680 * Especially, if something goes wrong during precopy or if migration
681 * is canceled, we have to properly communicate S_DONE to the VM.
683 virtio_balloon_free_page_done(dev
);
685 case PRECOPY_NOTIFY_COMPLETE
:
688 virtio_error(vdev
, "%s: %d reason unknown", __func__
, pnd
->reason
);
694 static size_t virtio_balloon_config_size(VirtIOBalloon
*s
)
696 uint64_t features
= s
->host_features
;
698 if (s
->qemu_4_0_config_size
) {
699 return sizeof(struct virtio_balloon_config
);
701 if (virtio_has_feature(features
, VIRTIO_BALLOON_F_PAGE_POISON
)) {
702 return sizeof(struct virtio_balloon_config
);
704 if (virtio_has_feature(features
, VIRTIO_BALLOON_F_FREE_PAGE_HINT
)) {
705 return offsetof(struct virtio_balloon_config
, poison_val
);
707 return offsetof(struct virtio_balloon_config
, free_page_hint_cmd_id
);
710 static void virtio_balloon_get_config(VirtIODevice
*vdev
, uint8_t *config_data
)
712 VirtIOBalloon
*dev
= VIRTIO_BALLOON(vdev
);
713 struct virtio_balloon_config config
= {};
715 config
.num_pages
= cpu_to_le32(dev
->num_pages
);
716 config
.actual
= cpu_to_le32(dev
->actual
);
717 config
.poison_val
= cpu_to_le32(dev
->poison_val
);
719 if (dev
->free_page_hint_status
== FREE_PAGE_HINT_S_REQUESTED
) {
720 config
.free_page_hint_cmd_id
=
721 cpu_to_le32(dev
->free_page_hint_cmd_id
);
722 } else if (dev
->free_page_hint_status
== FREE_PAGE_HINT_S_STOP
) {
723 config
.free_page_hint_cmd_id
=
724 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_STOP
);
725 } else if (dev
->free_page_hint_status
== FREE_PAGE_HINT_S_DONE
) {
726 config
.free_page_hint_cmd_id
=
727 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_DONE
);
730 trace_virtio_balloon_get_config(config
.num_pages
, config
.actual
);
731 memcpy(config_data
, &config
, virtio_balloon_config_size(dev
));
734 static int build_dimm_list(Object
*obj
, void *opaque
)
736 GSList
**list
= opaque
;
738 if (object_dynamic_cast(obj
, TYPE_PC_DIMM
)) {
739 DeviceState
*dev
= DEVICE(obj
);
740 if (dev
->realized
) { /* only realized DIMMs matter */
741 *list
= g_slist_prepend(*list
, dev
);
745 object_child_foreach(obj
, build_dimm_list
, opaque
);
749 static ram_addr_t
get_current_ram_size(void)
751 GSList
*list
= NULL
, *item
;
752 ram_addr_t size
= current_machine
->ram_size
;
754 build_dimm_list(qdev_get_machine(), &list
);
755 for (item
= list
; item
; item
= g_slist_next(item
)) {
756 Object
*obj
= OBJECT(item
->data
);
757 if (!strcmp(object_get_typename(obj
), TYPE_PC_DIMM
)) {
758 size
+= object_property_get_int(obj
, PC_DIMM_SIZE_PROP
,
767 static bool virtio_balloon_page_poison_support(void *opaque
)
769 VirtIOBalloon
*s
= opaque
;
770 VirtIODevice
*vdev
= VIRTIO_DEVICE(s
);
772 return virtio_vdev_has_feature(vdev
, VIRTIO_BALLOON_F_PAGE_POISON
);
775 static void virtio_balloon_set_config(VirtIODevice
*vdev
,
776 const uint8_t *config_data
)
778 VirtIOBalloon
*dev
= VIRTIO_BALLOON(vdev
);
779 struct virtio_balloon_config config
;
780 uint32_t oldactual
= dev
->actual
;
781 ram_addr_t vm_ram_size
= get_current_ram_size();
783 memcpy(&config
, config_data
, virtio_balloon_config_size(dev
));
784 dev
->actual
= le32_to_cpu(config
.actual
);
785 if (dev
->actual
!= oldactual
) {
786 qapi_event_send_balloon_change(vm_ram_size
-
787 ((ram_addr_t
) dev
->actual
<< VIRTIO_BALLOON_PFN_SHIFT
));
790 if (virtio_balloon_page_poison_support(dev
)) {
791 dev
->poison_val
= le32_to_cpu(config
.poison_val
);
793 trace_virtio_balloon_set_config(dev
->actual
, oldactual
);
796 static uint64_t virtio_balloon_get_features(VirtIODevice
*vdev
, uint64_t f
,
799 VirtIOBalloon
*dev
= VIRTIO_BALLOON(vdev
);
800 f
|= dev
->host_features
;
801 virtio_add_feature(&f
, VIRTIO_BALLOON_F_STATS_VQ
);
806 static void virtio_balloon_stat(void *opaque
, BalloonInfo
*info
)
808 VirtIOBalloon
*dev
= opaque
;
809 info
->actual
= get_current_ram_size() - ((uint64_t) dev
->actual
<<
810 VIRTIO_BALLOON_PFN_SHIFT
);
813 static void virtio_balloon_to_target(void *opaque
, ram_addr_t target
)
815 VirtIOBalloon
*dev
= VIRTIO_BALLOON(opaque
);
816 VirtIODevice
*vdev
= VIRTIO_DEVICE(dev
);
817 ram_addr_t vm_ram_size
= get_current_ram_size();
819 if (target
> vm_ram_size
) {
820 target
= vm_ram_size
;
823 dev
->num_pages
= (vm_ram_size
- target
) >> VIRTIO_BALLOON_PFN_SHIFT
;
824 virtio_notify_config(vdev
);
826 trace_virtio_balloon_to_target(target
, dev
->num_pages
);
829 static int virtio_balloon_post_load_device(void *opaque
, int version_id
)
831 VirtIOBalloon
*s
= VIRTIO_BALLOON(opaque
);
833 if (balloon_stats_enabled(s
)) {
834 balloon_stats_change_timer(s
, s
->stats_poll_interval
);
839 static const VMStateDescription vmstate_virtio_balloon_free_page_hint
= {
840 .name
= "virtio-balloon-device/free-page-report",
842 .minimum_version_id
= 1,
843 .needed
= virtio_balloon_free_page_support
,
844 .fields
= (VMStateField
[]) {
845 VMSTATE_UINT32(free_page_hint_cmd_id
, VirtIOBalloon
),
846 VMSTATE_UINT32(free_page_hint_status
, VirtIOBalloon
),
847 VMSTATE_END_OF_LIST()
851 static const VMStateDescription vmstate_virtio_balloon_page_poison
= {
852 .name
= "vitio-balloon-device/page-poison",
854 .minimum_version_id
= 1,
855 .needed
= virtio_balloon_page_poison_support
,
856 .fields
= (VMStateField
[]) {
857 VMSTATE_UINT32(poison_val
, VirtIOBalloon
),
858 VMSTATE_END_OF_LIST()
862 static const VMStateDescription vmstate_virtio_balloon_device
= {
863 .name
= "virtio-balloon-device",
865 .minimum_version_id
= 1,
866 .post_load
= virtio_balloon_post_load_device
,
867 .fields
= (VMStateField
[]) {
868 VMSTATE_UINT32(num_pages
, VirtIOBalloon
),
869 VMSTATE_UINT32(actual
, VirtIOBalloon
),
870 VMSTATE_END_OF_LIST()
872 .subsections
= (const VMStateDescription
* []) {
873 &vmstate_virtio_balloon_free_page_hint
,
874 &vmstate_virtio_balloon_page_poison
,
879 static void virtio_balloon_device_realize(DeviceState
*dev
, Error
**errp
)
881 VirtIODevice
*vdev
= VIRTIO_DEVICE(dev
);
882 VirtIOBalloon
*s
= VIRTIO_BALLOON(dev
);
885 virtio_init(vdev
, "virtio-balloon", VIRTIO_ID_BALLOON
,
886 virtio_balloon_config_size(s
));
888 ret
= qemu_add_balloon_handler(virtio_balloon_to_target
,
889 virtio_balloon_stat
, s
);
892 error_setg(errp
, "Only one balloon device is supported");
893 virtio_cleanup(vdev
);
897 if (virtio_has_feature(s
->host_features
, VIRTIO_BALLOON_F_FREE_PAGE_HINT
) &&
899 error_setg(errp
, "'free-page-hint' requires 'iothread' to be set");
900 virtio_cleanup(vdev
);
904 s
->ivq
= virtio_add_queue(vdev
, 128, virtio_balloon_handle_output
);
905 s
->dvq
= virtio_add_queue(vdev
, 128, virtio_balloon_handle_output
);
906 s
->svq
= virtio_add_queue(vdev
, 128, virtio_balloon_receive_stats
);
908 if (virtio_has_feature(s
->host_features
,
909 VIRTIO_BALLOON_F_FREE_PAGE_HINT
)) {
910 s
->free_page_vq
= virtio_add_queue(vdev
, VIRTQUEUE_MAX_SIZE
,
911 virtio_balloon_handle_free_page_vq
);
912 precopy_add_notifier(&s
->free_page_hint_notify
);
914 object_ref(OBJECT(s
->iothread
));
915 s
->free_page_bh
= aio_bh_new(iothread_get_aio_context(s
->iothread
),
916 virtio_ballloon_get_free_page_hints
, s
);
919 if (virtio_has_feature(s
->host_features
, VIRTIO_BALLOON_F_REPORTING
)) {
920 s
->reporting_vq
= virtio_add_queue(vdev
, 32,
921 virtio_balloon_handle_report
);
927 static void virtio_balloon_device_unrealize(DeviceState
*dev
)
929 VirtIODevice
*vdev
= VIRTIO_DEVICE(dev
);
930 VirtIOBalloon
*s
= VIRTIO_BALLOON(dev
);
932 if (s
->free_page_bh
) {
933 qemu_bh_delete(s
->free_page_bh
);
934 object_unref(OBJECT(s
->iothread
));
935 virtio_balloon_free_page_stop(s
);
936 precopy_remove_notifier(&s
->free_page_hint_notify
);
938 balloon_stats_destroy_timer(s
);
939 qemu_remove_balloon_handler(s
);
941 virtio_delete_queue(s
->ivq
);
942 virtio_delete_queue(s
->dvq
);
943 virtio_delete_queue(s
->svq
);
944 if (s
->free_page_vq
) {
945 virtio_delete_queue(s
->free_page_vq
);
947 if (s
->reporting_vq
) {
948 virtio_delete_queue(s
->reporting_vq
);
950 virtio_cleanup(vdev
);
953 static void virtio_balloon_device_reset(VirtIODevice
*vdev
)
955 VirtIOBalloon
*s
= VIRTIO_BALLOON(vdev
);
957 if (virtio_balloon_free_page_support(s
)) {
958 virtio_balloon_free_page_stop(s
);
961 if (s
->stats_vq_elem
!= NULL
) {
962 virtqueue_unpop(s
->svq
, s
->stats_vq_elem
, 0);
963 g_free(s
->stats_vq_elem
);
964 s
->stats_vq_elem
= NULL
;
970 static void virtio_balloon_set_status(VirtIODevice
*vdev
, uint8_t status
)
972 VirtIOBalloon
*s
= VIRTIO_BALLOON(vdev
);
974 if (!s
->stats_vq_elem
&& vdev
->vm_running
&&
975 (status
& VIRTIO_CONFIG_S_DRIVER_OK
) && virtqueue_rewind(s
->svq
, 1)) {
976 /* poll stats queue for the element we have discarded when the VM
978 virtio_balloon_receive_stats(vdev
, s
->svq
);
981 if (virtio_balloon_free_page_support(s
)) {
983 * The VM is woken up and the iothread was blocked, so signal it to
986 if (vdev
->vm_running
&& s
->block_iothread
) {
987 qemu_mutex_lock(&s
->free_page_lock
);
988 s
->block_iothread
= false;
989 qemu_cond_signal(&s
->free_page_cond
);
990 qemu_mutex_unlock(&s
->free_page_lock
);
993 /* The VM is stopped, block the iothread. */
994 if (!vdev
->vm_running
) {
995 qemu_mutex_lock(&s
->free_page_lock
);
996 s
->block_iothread
= true;
997 qemu_mutex_unlock(&s
->free_page_lock
);
1002 static void virtio_balloon_instance_init(Object
*obj
)
1004 VirtIOBalloon
*s
= VIRTIO_BALLOON(obj
);
1006 qemu_mutex_init(&s
->free_page_lock
);
1007 qemu_cond_init(&s
->free_page_cond
);
1008 s
->free_page_hint_cmd_id
= VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN
;
1009 s
->free_page_hint_notify
.notify
= virtio_balloon_free_page_hint_notify
;
1011 object_property_add(obj
, "guest-stats", "guest statistics",
1012 balloon_stats_get_all
, NULL
, NULL
, s
);
1014 object_property_add(obj
, "guest-stats-polling-interval", "int",
1015 balloon_stats_get_poll_interval
,
1016 balloon_stats_set_poll_interval
,
1020 static const VMStateDescription vmstate_virtio_balloon
= {
1021 .name
= "virtio-balloon",
1022 .minimum_version_id
= 1,
1024 .fields
= (VMStateField
[]) {
1025 VMSTATE_VIRTIO_DEVICE
,
1026 VMSTATE_END_OF_LIST()
1030 static Property virtio_balloon_properties
[] = {
1031 DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon
, host_features
,
1032 VIRTIO_BALLOON_F_DEFLATE_ON_OOM
, false),
1033 DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon
, host_features
,
1034 VIRTIO_BALLOON_F_FREE_PAGE_HINT
, false),
1035 DEFINE_PROP_BIT("page-poison", VirtIOBalloon
, host_features
,
1036 VIRTIO_BALLOON_F_PAGE_POISON
, true),
1037 DEFINE_PROP_BIT("free-page-reporting", VirtIOBalloon
, host_features
,
1038 VIRTIO_BALLOON_F_REPORTING
, false),
1039 /* QEMU 4.0 accidentally changed the config size even when free-page-hint
1040 * is disabled, resulting in QEMU 3.1 migration incompatibility. This
1041 * property retains this quirk for QEMU 4.1 machine types.
1043 DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon
,
1044 qemu_4_0_config_size
, false),
1045 DEFINE_PROP_LINK("iothread", VirtIOBalloon
, iothread
, TYPE_IOTHREAD
,
1047 DEFINE_PROP_END_OF_LIST(),
1050 static void virtio_balloon_class_init(ObjectClass
*klass
, void *data
)
1052 DeviceClass
*dc
= DEVICE_CLASS(klass
);
1053 VirtioDeviceClass
*vdc
= VIRTIO_DEVICE_CLASS(klass
);
1055 device_class_set_props(dc
, virtio_balloon_properties
);
1056 dc
->vmsd
= &vmstate_virtio_balloon
;
1057 set_bit(DEVICE_CATEGORY_MISC
, dc
->categories
);
1058 vdc
->realize
= virtio_balloon_device_realize
;
1059 vdc
->unrealize
= virtio_balloon_device_unrealize
;
1060 vdc
->reset
= virtio_balloon_device_reset
;
1061 vdc
->get_config
= virtio_balloon_get_config
;
1062 vdc
->set_config
= virtio_balloon_set_config
;
1063 vdc
->get_features
= virtio_balloon_get_features
;
1064 vdc
->set_status
= virtio_balloon_set_status
;
1065 vdc
->vmsd
= &vmstate_virtio_balloon_device
;
1068 static const TypeInfo virtio_balloon_info
= {
1069 .name
= TYPE_VIRTIO_BALLOON
,
1070 .parent
= TYPE_VIRTIO_DEVICE
,
1071 .instance_size
= sizeof(VirtIOBalloon
),
1072 .instance_init
= virtio_balloon_instance_init
,
1073 .class_init
= virtio_balloon_class_init
,
1076 static void virtio_register_types(void)
1078 type_register_static(&virtio_balloon_info
);
1081 type_init(virtio_register_types
)