goldfish_rtc: change MemoryRegionOps endianness to DEVICE_NATIVE_ENDIAN
[qemu/ar7.git] / hw / virtio / virtio-balloon.c
blobb22b5beda3ca0866b660480a6f55ae0967c665de
1 /*
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>
8 * Authors:
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"
17 #include "qemu/iov.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 "sysemu/balloon.h"
24 #include "hw/virtio/virtio-balloon.h"
25 #include "exec/address-spaces.h"
26 #include "qapi/error.h"
27 #include "qapi/qapi-events-machine.h"
28 #include "qapi/visitor.h"
29 #include "trace.h"
30 #include "qemu/error-report.h"
31 #include "migration/misc.h"
33 #include "hw/virtio/virtio-bus.h"
34 #include "hw/virtio/virtio-access.h"
36 #define BALLOON_PAGE_SIZE (1 << VIRTIO_BALLOON_PFN_SHIFT)
38 typedef struct PartiallyBalloonedPage {
39 ram_addr_t base_gpa;
40 unsigned long *bitmap;
41 } PartiallyBalloonedPage;
43 static void virtio_balloon_pbp_free(PartiallyBalloonedPage *pbp)
45 if (!pbp->bitmap) {
46 return;
48 g_free(pbp->bitmap);
49 pbp->bitmap = NULL;
52 static void virtio_balloon_pbp_alloc(PartiallyBalloonedPage *pbp,
53 ram_addr_t base_gpa,
54 long subpages)
56 pbp->base_gpa = base_gpa;
57 pbp->bitmap = bitmap_new(subpages);
60 static bool virtio_balloon_pbp_matches(PartiallyBalloonedPage *pbp,
61 ram_addr_t base_gpa)
63 return pbp->base_gpa == base_gpa;
66 static bool virtio_balloon_inhibited(void)
68 /* Postcopy cannot deal with concurrent discards, so it's special. */
69 return ram_block_discard_is_disabled() || migration_in_incoming_postcopy();
72 static void balloon_inflate_page(VirtIOBalloon *balloon,
73 MemoryRegion *mr, hwaddr mr_offset,
74 PartiallyBalloonedPage *pbp)
76 void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
77 ram_addr_t rb_offset, rb_aligned_offset, base_gpa;
78 RAMBlock *rb;
79 size_t rb_page_size;
80 int subpages;
82 /* XXX is there a better way to get to the RAMBlock than via a
83 * host address? */
84 rb = qemu_ram_block_from_host(addr, false, &rb_offset);
85 rb_page_size = qemu_ram_pagesize(rb);
87 if (rb_page_size == BALLOON_PAGE_SIZE) {
88 /* Easy case */
90 ram_block_discard_range(rb, rb_offset, rb_page_size);
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 */
94 return;
97 /* Hard case
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
103 warn_report_once(
104 "Balloon used with backing page size > 4kiB, this may not be reliable");
106 rb_aligned_offset = QEMU_ALIGN_DOWN(rb_offset, rb_page_size);
107 subpages = rb_page_size / BALLOON_PAGE_SIZE;
108 base_gpa = memory_region_get_ram_addr(mr) + mr_offset -
109 (rb_offset - rb_aligned_offset);
111 if (pbp->bitmap && !virtio_balloon_pbp_matches(pbp, base_gpa)) {
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 */
115 virtio_balloon_pbp_free(pbp);
118 if (!pbp->bitmap) {
119 virtio_balloon_pbp_alloc(pbp, base_gpa, subpages);
122 set_bit((rb_offset - rb_aligned_offset) / BALLOON_PAGE_SIZE,
123 pbp->bitmap);
125 if (bitmap_full(pbp->bitmap, subpages)) {
126 /* We've accumulated a full host page, we can actually discard
127 * it now */
129 ram_block_discard_range(rb, rb_aligned_offset, rb_page_size);
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 */
133 virtio_balloon_pbp_free(pbp);
137 static void balloon_deflate_page(VirtIOBalloon *balloon,
138 MemoryRegion *mr, hwaddr mr_offset)
140 void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
141 ram_addr_t rb_offset;
142 RAMBlock *rb;
143 size_t rb_page_size;
144 void *host_addr;
145 int ret;
147 /* XXX is there a better way to get to the RAMBlock than via a
148 * host address? */
149 rb = qemu_ram_block_from_host(addr, false, &rb_offset);
150 rb_page_size = qemu_ram_pagesize(rb);
152 host_addr = (void *)((uintptr_t)addr & ~(rb_page_size - 1));
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 */
164 static 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",
171 [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
172 [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
173 [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
174 [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
175 [VIRTIO_BALLOON_S_NR] = NULL
179 * reset_stats - Mark all items in the stats array as unset
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
183 * stale values stick around in case the guest reports a subset of the supported
184 * statistics.
186 static inline void reset_stats(VirtIOBalloon *dev)
188 int i;
189 for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
192 static bool balloon_stats_supported(const VirtIOBalloon *s)
194 VirtIODevice *vdev = VIRTIO_DEVICE(s);
195 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
198 static bool balloon_stats_enabled(const VirtIOBalloon *s)
200 return s->stats_poll_interval > 0;
203 static void balloon_stats_destroy_timer(VirtIOBalloon *s)
205 if (balloon_stats_enabled(s)) {
206 timer_del(s->stats_timer);
207 timer_free(s->stats_timer);
208 s->stats_timer = NULL;
209 s->stats_poll_interval = 0;
213 static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
215 timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
218 static void balloon_stats_poll_cb(void *opaque)
220 VirtIOBalloon *s = opaque;
221 VirtIODevice *vdev = VIRTIO_DEVICE(s);
223 if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
224 /* re-schedule */
225 balloon_stats_change_timer(s, s->stats_poll_interval);
226 return;
229 virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
230 virtio_notify(vdev, s->svq);
231 g_free(s->stats_vq_elem);
232 s->stats_vq_elem = NULL;
235 static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
236 void *opaque, Error **errp)
238 Error *err = NULL;
239 VirtIOBalloon *s = opaque;
240 int i;
242 if (!visit_start_struct(v, name, NULL, 0, &err)) {
243 goto out;
245 if (!visit_type_int(v, "last-update", &s->stats_last_update, &err)) {
246 goto out_end;
249 if (!visit_start_struct(v, "stats", NULL, 0, &err)) {
250 goto out_end;
252 for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
253 if (!visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err)) {
254 goto out_nested;
257 visit_check_struct(v, &err);
258 out_nested:
259 visit_end_struct(v, NULL);
261 if (!err) {
262 visit_check_struct(v, &err);
264 out_end:
265 visit_end_struct(v, NULL);
266 out:
267 error_propagate(errp, err);
270 static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
271 const char *name, void *opaque,
272 Error **errp)
274 VirtIOBalloon *s = opaque;
275 visit_type_int(v, name, &s->stats_poll_interval, errp);
278 static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
279 const char *name, void *opaque,
280 Error **errp)
282 VirtIOBalloon *s = opaque;
283 int64_t value;
285 if (!visit_type_int(v, name, &value, errp)) {
286 return;
289 if (value < 0) {
290 error_setg(errp, "timer value must be greater than zero");
291 return;
294 if (value > UINT32_MAX) {
295 error_setg(errp, "timer value is too big");
296 return;
299 if (value == s->stats_poll_interval) {
300 return;
303 if (value == 0) {
304 /* timer=0 disables the timer */
305 balloon_stats_destroy_timer(s);
306 return;
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;
316 /* create a new timer */
317 g_assert(s->stats_timer == NULL);
318 s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
319 s->stats_poll_interval = value;
320 balloon_stats_change_timer(s, 0);
323 static void virtio_balloon_handle_report(VirtIODevice *vdev, VirtQueue *vq)
325 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
326 VirtQueueElement *elem;
328 while ((elem = virtqueue_pop(vq, sizeof(VirtQueueElement)))) {
329 unsigned int i;
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.
338 if (virtio_balloon_inhibited() || dev->poison_val) {
339 goto skip_element;
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;
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.
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;
366 * For now we will simply ignore unaligned memory regions, or
367 * regions that overrun the end of the RAMBlock.
369 if (!QEMU_IS_ALIGNED(ram_offset | size, qemu_ram_pagesize(rb)) ||
370 (ram_offset + size) > qemu_ram_get_used_length(rb)) {
371 continue;
374 ram_block_discard_range(rb, ram_offset, size);
377 skip_element:
378 virtqueue_push(vq, elem, 0);
379 virtio_notify(vdev, vq);
380 g_free(elem);
384 static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
386 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
387 VirtQueueElement *elem;
388 MemoryRegionSection section;
390 for (;;) {
391 PartiallyBalloonedPage pbp = {};
392 size_t offset = 0;
393 uint32_t pfn;
395 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
396 if (!elem) {
397 break;
400 while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
401 unsigned int p = virtio_ldl_p(vdev, &pfn);
402 hwaddr pa;
404 pa = (hwaddr) p << VIRTIO_BALLOON_PFN_SHIFT;
405 offset += 4;
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;
413 if (!memory_region_is_ram(section.mr) ||
414 memory_region_is_rom(section.mr) ||
415 memory_region_is_romd(section.mr)) {
416 trace_virtio_balloon_bad_addr(pa);
417 memory_region_unref(section.mr);
418 continue;
421 trace_virtio_balloon_handle_output(memory_region_name(section.mr),
422 pa);
423 if (!virtio_balloon_inhibited()) {
424 if (vq == s->ivq) {
425 balloon_inflate_page(s, section.mr,
426 section.offset_within_region, &pbp);
427 } else if (vq == s->dvq) {
428 balloon_deflate_page(s, section.mr, section.offset_within_region);
429 } else {
430 g_assert_not_reached();
433 memory_region_unref(section.mr);
436 virtqueue_push(vq, elem, offset);
437 virtio_notify(vdev, vq);
438 g_free(elem);
439 virtio_balloon_pbp_free(&pbp);
443 static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
445 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
446 VirtQueueElement *elem;
447 VirtIOBalloonStat stat;
448 size_t offset = 0;
449 qemu_timeval tv;
451 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
452 if (!elem) {
453 goto out;
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);
463 s->stats_vq_elem = elem;
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).
469 reset_stats(s);
471 while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
472 == sizeof(stat)) {
473 uint16_t tag = virtio_tswap16(vdev, stat.tag);
474 uint64_t val = virtio_tswap64(vdev, stat.val);
476 offset += sizeof(stat);
477 if (tag < VIRTIO_BALLOON_S_NR)
478 s->stats[tag] = val;
480 s->stats_vq_offset = offset;
482 if (qemu_gettimeofday(&tv) < 0) {
483 warn_report("%s: failed to get time of day", __func__);
484 goto out;
487 s->stats_last_update = tv.tv_sec;
489 out:
490 if (balloon_stats_enabled(s)) {
491 balloon_stats_change_timer(s, s->stats_poll_interval);
495 static void virtio_balloon_handle_free_page_vq(VirtIODevice *vdev,
496 VirtQueue *vq)
498 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
499 qemu_bh_schedule(s->free_page_bh);
502 static bool get_free_page_hints(VirtIOBalloon *dev)
504 VirtQueueElement *elem;
505 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
506 VirtQueue *vq = dev->free_page_vq;
507 bool ret = true;
509 while (dev->block_iothread) {
510 qemu_cond_wait(&dev->free_page_cond, &dev->free_page_lock);
513 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
514 if (!elem) {
515 return false;
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));
523 virtio_tswap32s(vdev, &id);
524 if (unlikely(size != sizeof(id))) {
525 virtio_error(vdev, "received an incorrect cmd id");
526 ret = false;
527 goto out;
529 if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED &&
530 id == dev->free_page_hint_cmd_id) {
531 dev->free_page_hint_status = FREE_PAGE_HINT_S_START;
532 } else {
534 * Stop the optimization only when it has started. This
535 * avoids a stale stop sign for the previous command.
537 if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
538 dev->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
543 if (elem->in_num) {
544 if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
545 qemu_guest_free_page_hint(elem->in_sg[0].iov_base,
546 elem->in_sg[0].iov_len);
550 out:
551 virtqueue_push(vq, elem, 1);
552 g_free(elem);
553 return ret;
556 static void virtio_ballloon_get_free_page_hints(void *opaque)
558 VirtIOBalloon *dev = opaque;
559 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
560 VirtQueue *vq = dev->free_page_vq;
561 bool continue_to_get_hints;
563 do {
564 qemu_mutex_lock(&dev->free_page_lock);
565 virtio_queue_set_notification(vq, 0);
566 continue_to_get_hints = get_free_page_hints(dev);
567 qemu_mutex_unlock(&dev->free_page_lock);
568 virtio_notify(vdev, vq);
570 * Start to poll the vq once the hinting started. Otherwise, continue
571 * only when there are entries on the vq, which need to be given back.
573 } while (continue_to_get_hints ||
574 dev->free_page_hint_status == FREE_PAGE_HINT_S_START);
575 virtio_queue_set_notification(vq, 1);
578 static bool virtio_balloon_free_page_support(void *opaque)
580 VirtIOBalloon *s = opaque;
581 VirtIODevice *vdev = VIRTIO_DEVICE(s);
583 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT);
586 static void virtio_balloon_free_page_start(VirtIOBalloon *s)
588 VirtIODevice *vdev = VIRTIO_DEVICE(s);
590 /* For the stop and copy phase, we don't need to start the optimization */
591 if (!vdev->vm_running) {
592 return;
595 qemu_mutex_lock(&s->free_page_lock);
597 if (s->free_page_hint_cmd_id == UINT_MAX) {
598 s->free_page_hint_cmd_id =
599 VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
600 } else {
601 s->free_page_hint_cmd_id++;
604 s->free_page_hint_status = FREE_PAGE_HINT_S_REQUESTED;
605 qemu_mutex_unlock(&s->free_page_lock);
607 virtio_notify_config(vdev);
610 static void virtio_balloon_free_page_stop(VirtIOBalloon *s)
612 VirtIODevice *vdev = VIRTIO_DEVICE(s);
614 if (s->free_page_hint_status != FREE_PAGE_HINT_S_STOP) {
616 * The lock also guarantees us that the
617 * virtio_ballloon_get_free_page_hints exits after the
618 * free_page_hint_status is set to S_STOP.
620 qemu_mutex_lock(&s->free_page_lock);
622 * The guest isn't done hinting, so send a notification
623 * to the guest to actively stop the hinting.
625 s->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
626 qemu_mutex_unlock(&s->free_page_lock);
627 virtio_notify_config(vdev);
631 static void virtio_balloon_free_page_done(VirtIOBalloon *s)
633 VirtIODevice *vdev = VIRTIO_DEVICE(s);
635 if (s->free_page_hint_status != FREE_PAGE_HINT_S_DONE) {
636 /* See virtio_balloon_free_page_stop() */
637 qemu_mutex_lock(&s->free_page_lock);
638 s->free_page_hint_status = FREE_PAGE_HINT_S_DONE;
639 qemu_mutex_unlock(&s->free_page_lock);
640 virtio_notify_config(vdev);
644 static int
645 virtio_balloon_free_page_hint_notify(NotifierWithReturn *n, void *data)
647 VirtIOBalloon *dev = container_of(n, VirtIOBalloon,
648 free_page_hint_notify);
649 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
650 PrecopyNotifyData *pnd = data;
652 if (!virtio_balloon_free_page_support(dev)) {
654 * This is an optimization provided to migration, so just return 0 to
655 * have the normal migration process not affected when this feature is
656 * not supported.
658 return 0;
661 switch (pnd->reason) {
662 case PRECOPY_NOTIFY_SETUP:
663 precopy_enable_free_page_optimization();
664 break;
665 case PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC:
666 virtio_balloon_free_page_stop(dev);
667 break;
668 case PRECOPY_NOTIFY_AFTER_BITMAP_SYNC:
669 if (vdev->vm_running) {
670 virtio_balloon_free_page_start(dev);
671 break;
674 * Set S_DONE before migrating the vmstate, so the guest will reuse
675 * all hinted pages once running on the destination. Fall through.
677 case PRECOPY_NOTIFY_CLEANUP:
679 * Especially, if something goes wrong during precopy or if migration
680 * is canceled, we have to properly communicate S_DONE to the VM.
682 virtio_balloon_free_page_done(dev);
683 break;
684 case PRECOPY_NOTIFY_COMPLETE:
685 break;
686 default:
687 virtio_error(vdev, "%s: %d reason unknown", __func__, pnd->reason);
690 return 0;
693 static size_t virtio_balloon_config_size(VirtIOBalloon *s)
695 uint64_t features = s->host_features;
697 if (s->qemu_4_0_config_size) {
698 return sizeof(struct virtio_balloon_config);
700 if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON)) {
701 return sizeof(struct virtio_balloon_config);
703 if (virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
704 return offsetof(struct virtio_balloon_config, poison_val);
706 return offsetof(struct virtio_balloon_config, free_page_hint_cmd_id);
709 static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
711 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
712 struct virtio_balloon_config config = {};
714 config.num_pages = cpu_to_le32(dev->num_pages);
715 config.actual = cpu_to_le32(dev->actual);
716 config.poison_val = cpu_to_le32(dev->poison_val);
718 if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED) {
719 config.free_page_hint_cmd_id =
720 cpu_to_le32(dev->free_page_hint_cmd_id);
721 } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_STOP) {
722 config.free_page_hint_cmd_id =
723 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_STOP);
724 } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_DONE) {
725 config.free_page_hint_cmd_id =
726 cpu_to_le32(VIRTIO_BALLOON_CMD_ID_DONE);
729 trace_virtio_balloon_get_config(config.num_pages, config.actual);
730 memcpy(config_data, &config, virtio_balloon_config_size(dev));
733 static int build_dimm_list(Object *obj, void *opaque)
735 GSList **list = opaque;
737 if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
738 DeviceState *dev = DEVICE(obj);
739 if (dev->realized) { /* only realized DIMMs matter */
740 *list = g_slist_prepend(*list, dev);
744 object_child_foreach(obj, build_dimm_list, opaque);
745 return 0;
748 static ram_addr_t get_current_ram_size(void)
750 GSList *list = NULL, *item;
751 ram_addr_t size = ram_size;
753 build_dimm_list(qdev_get_machine(), &list);
754 for (item = list; item; item = g_slist_next(item)) {
755 Object *obj = OBJECT(item->data);
756 if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
757 size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
758 &error_abort);
761 g_slist_free(list);
763 return size;
766 static bool virtio_balloon_page_poison_support(void *opaque)
768 VirtIOBalloon *s = opaque;
769 VirtIODevice *vdev = VIRTIO_DEVICE(s);
771 return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON);
774 static void virtio_balloon_set_config(VirtIODevice *vdev,
775 const uint8_t *config_data)
777 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
778 struct virtio_balloon_config config;
779 uint32_t oldactual = dev->actual;
780 ram_addr_t vm_ram_size = get_current_ram_size();
782 memcpy(&config, config_data, virtio_balloon_config_size(dev));
783 dev->actual = le32_to_cpu(config.actual);
784 if (dev->actual != oldactual) {
785 qapi_event_send_balloon_change(vm_ram_size -
786 ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
788 dev->poison_val = 0;
789 if (virtio_balloon_page_poison_support(dev)) {
790 dev->poison_val = le32_to_cpu(config.poison_val);
792 trace_virtio_balloon_set_config(dev->actual, oldactual);
795 static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
796 Error **errp)
798 VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
799 f |= dev->host_features;
800 virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
802 return f;
805 static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
807 VirtIOBalloon *dev = opaque;
808 info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
809 VIRTIO_BALLOON_PFN_SHIFT);
812 static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
814 VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
815 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
816 ram_addr_t vm_ram_size = get_current_ram_size();
818 if (target > vm_ram_size) {
819 target = vm_ram_size;
821 if (target) {
822 dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
823 virtio_notify_config(vdev);
825 trace_virtio_balloon_to_target(target, dev->num_pages);
828 static int virtio_balloon_post_load_device(void *opaque, int version_id)
830 VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
832 if (balloon_stats_enabled(s)) {
833 balloon_stats_change_timer(s, s->stats_poll_interval);
835 return 0;
838 static const VMStateDescription vmstate_virtio_balloon_free_page_hint = {
839 .name = "virtio-balloon-device/free-page-report",
840 .version_id = 1,
841 .minimum_version_id = 1,
842 .needed = virtio_balloon_free_page_support,
843 .fields = (VMStateField[]) {
844 VMSTATE_UINT32(free_page_hint_cmd_id, VirtIOBalloon),
845 VMSTATE_UINT32(free_page_hint_status, VirtIOBalloon),
846 VMSTATE_END_OF_LIST()
850 static const VMStateDescription vmstate_virtio_balloon_page_poison = {
851 .name = "vitio-balloon-device/page-poison",
852 .version_id = 1,
853 .minimum_version_id = 1,
854 .needed = virtio_balloon_page_poison_support,
855 .fields = (VMStateField[]) {
856 VMSTATE_UINT32(poison_val, VirtIOBalloon),
857 VMSTATE_END_OF_LIST()
861 static const VMStateDescription vmstate_virtio_balloon_device = {
862 .name = "virtio-balloon-device",
863 .version_id = 1,
864 .minimum_version_id = 1,
865 .post_load = virtio_balloon_post_load_device,
866 .fields = (VMStateField[]) {
867 VMSTATE_UINT32(num_pages, VirtIOBalloon),
868 VMSTATE_UINT32(actual, VirtIOBalloon),
869 VMSTATE_END_OF_LIST()
871 .subsections = (const VMStateDescription * []) {
872 &vmstate_virtio_balloon_free_page_hint,
873 &vmstate_virtio_balloon_page_poison,
874 NULL
878 static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
880 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
881 VirtIOBalloon *s = VIRTIO_BALLOON(dev);
882 int ret;
884 virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
885 virtio_balloon_config_size(s));
887 ret = qemu_add_balloon_handler(virtio_balloon_to_target,
888 virtio_balloon_stat, s);
890 if (ret < 0) {
891 error_setg(errp, "Only one balloon device is supported");
892 virtio_cleanup(vdev);
893 return;
896 if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_FREE_PAGE_HINT) &&
897 !s->iothread) {
898 error_setg(errp, "'free-page-hint' requires 'iothread' to be set");
899 virtio_cleanup(vdev);
900 return;
903 s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
904 s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
905 s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
907 if (virtio_has_feature(s->host_features,
908 VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
909 s->free_page_vq = virtio_add_queue(vdev, VIRTQUEUE_MAX_SIZE,
910 virtio_balloon_handle_free_page_vq);
911 precopy_add_notifier(&s->free_page_hint_notify);
913 object_ref(OBJECT(s->iothread));
914 s->free_page_bh = aio_bh_new(iothread_get_aio_context(s->iothread),
915 virtio_ballloon_get_free_page_hints, s);
918 if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_REPORTING)) {
919 s->reporting_vq = virtio_add_queue(vdev, 32,
920 virtio_balloon_handle_report);
923 reset_stats(s);
926 static void virtio_balloon_device_unrealize(DeviceState *dev)
928 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
929 VirtIOBalloon *s = VIRTIO_BALLOON(dev);
931 if (s->free_page_bh) {
932 qemu_bh_delete(s->free_page_bh);
933 object_unref(OBJECT(s->iothread));
934 virtio_balloon_free_page_stop(s);
935 precopy_remove_notifier(&s->free_page_hint_notify);
937 balloon_stats_destroy_timer(s);
938 qemu_remove_balloon_handler(s);
940 virtio_delete_queue(s->ivq);
941 virtio_delete_queue(s->dvq);
942 virtio_delete_queue(s->svq);
943 if (s->free_page_vq) {
944 virtio_delete_queue(s->free_page_vq);
946 if (s->reporting_vq) {
947 virtio_delete_queue(s->reporting_vq);
949 virtio_cleanup(vdev);
952 static void virtio_balloon_device_reset(VirtIODevice *vdev)
954 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
956 if (virtio_balloon_free_page_support(s)) {
957 virtio_balloon_free_page_stop(s);
960 if (s->stats_vq_elem != NULL) {
961 virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
962 g_free(s->stats_vq_elem);
963 s->stats_vq_elem = NULL;
966 s->poison_val = 0;
969 static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
971 VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
973 if (!s->stats_vq_elem && vdev->vm_running &&
974 (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
975 /* poll stats queue for the element we have discarded when the VM
976 * was stopped */
977 virtio_balloon_receive_stats(vdev, s->svq);
980 if (virtio_balloon_free_page_support(s)) {
982 * The VM is woken up and the iothread was blocked, so signal it to
983 * continue.
985 if (vdev->vm_running && s->block_iothread) {
986 qemu_mutex_lock(&s->free_page_lock);
987 s->block_iothread = false;
988 qemu_cond_signal(&s->free_page_cond);
989 qemu_mutex_unlock(&s->free_page_lock);
992 /* The VM is stopped, block the iothread. */
993 if (!vdev->vm_running) {
994 qemu_mutex_lock(&s->free_page_lock);
995 s->block_iothread = true;
996 qemu_mutex_unlock(&s->free_page_lock);
1001 static void virtio_balloon_instance_init(Object *obj)
1003 VirtIOBalloon *s = VIRTIO_BALLOON(obj);
1005 qemu_mutex_init(&s->free_page_lock);
1006 qemu_cond_init(&s->free_page_cond);
1007 s->free_page_hint_cmd_id = VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
1008 s->free_page_hint_notify.notify = virtio_balloon_free_page_hint_notify;
1010 object_property_add(obj, "guest-stats", "guest statistics",
1011 balloon_stats_get_all, NULL, NULL, s);
1013 object_property_add(obj, "guest-stats-polling-interval", "int",
1014 balloon_stats_get_poll_interval,
1015 balloon_stats_set_poll_interval,
1016 NULL, s);
1019 static const VMStateDescription vmstate_virtio_balloon = {
1020 .name = "virtio-balloon",
1021 .minimum_version_id = 1,
1022 .version_id = 1,
1023 .fields = (VMStateField[]) {
1024 VMSTATE_VIRTIO_DEVICE,
1025 VMSTATE_END_OF_LIST()
1029 static Property virtio_balloon_properties[] = {
1030 DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
1031 VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
1032 DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon, host_features,
1033 VIRTIO_BALLOON_F_FREE_PAGE_HINT, false),
1034 DEFINE_PROP_BIT("page-poison", VirtIOBalloon, host_features,
1035 VIRTIO_BALLOON_F_PAGE_POISON, true),
1036 DEFINE_PROP_BIT("free-page-reporting", VirtIOBalloon, host_features,
1037 VIRTIO_BALLOON_F_REPORTING, false),
1038 /* QEMU 4.0 accidentally changed the config size even when free-page-hint
1039 * is disabled, resulting in QEMU 3.1 migration incompatibility. This
1040 * property retains this quirk for QEMU 4.1 machine types.
1042 DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon,
1043 qemu_4_0_config_size, false),
1044 DEFINE_PROP_LINK("iothread", VirtIOBalloon, iothread, TYPE_IOTHREAD,
1045 IOThread *),
1046 DEFINE_PROP_END_OF_LIST(),
1049 static void virtio_balloon_class_init(ObjectClass *klass, void *data)
1051 DeviceClass *dc = DEVICE_CLASS(klass);
1052 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1054 device_class_set_props(dc, virtio_balloon_properties);
1055 dc->vmsd = &vmstate_virtio_balloon;
1056 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1057 vdc->realize = virtio_balloon_device_realize;
1058 vdc->unrealize = virtio_balloon_device_unrealize;
1059 vdc->reset = virtio_balloon_device_reset;
1060 vdc->get_config = virtio_balloon_get_config;
1061 vdc->set_config = virtio_balloon_set_config;
1062 vdc->get_features = virtio_balloon_get_features;
1063 vdc->set_status = virtio_balloon_set_status;
1064 vdc->vmsd = &vmstate_virtio_balloon_device;
1067 static const TypeInfo virtio_balloon_info = {
1068 .name = TYPE_VIRTIO_BALLOON,
1069 .parent = TYPE_VIRTIO_DEVICE,
1070 .instance_size = sizeof(VirtIOBalloon),
1071 .instance_init = virtio_balloon_instance_init,
1072 .class_init = virtio_balloon_class_init,
1075 static void virtio_register_types(void)
1077 type_register_static(&virtio_balloon_info);
1080 type_init(virtio_register_types)