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