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