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