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